While making up some arrays I noticed that
char[] javaArray = {'j','a','v','a'};
prints out
java
but
String[] javaStringArray = {"j","a","v","a"};
only prints the stack location. I know char and String are both very different, but how come the JVM knows to output chars for the first and only a stack location for the second?
I am using IntelliJ and the command System.out.println(javaArray);
No. String is implemented to store sequence of characters and to be represented as a single data type and single entity. Character Array on the other hand is a sequential collection of data type char where each element is a separate entity.
We should always store the secure information in char[] array rather than String. Since String is immutable if we store the password as plain text it will be available in memory until the garbage collector cleans it.
Since Strings are immutable there is no way the contents of Strings can be changed because any change will produce a new String, while if you use a char[] you can still set all the elements as blank or zero. So storing a password in a character array clearly mitigates the security risk of stealing a password.
Duplicate elements can be found using two loops. The outer loop will iterate through the array from 0 to length of the array. The outer loop will select an element. The inner loop will be used to compare the selected element with the rest of the elements of the array.
This happens because PrintStream
has a special override for char[]
, but it lacks such overrides for String[]
and other array types:
PrintStream.println(char[] x)
If you call toString()
on javaArray
when printing, the results would look similar to what you get when you print String[]
:
char[] javaArray = {'j','a','v','a'};
System.out.println(javaArray.toString()); // Prints something like [C@1540e19d
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With