I am a student who has just shifted from C++ to Java.
In Java what could be the main reason for defining separate data types for Strings and Char arrays? Wha
String is a class in Java and offers you methods and is also an Object.
A String-object is also immutable.
Internal the value is a char-array.
There is a semantic difference. Just because data is stored the same way, this doesn't mean it's the same thing. Dates
and Amounts
may also have the same internal representation (long
for a timestamp or fixed point amount of cash), but they're not the same. The char
array could as well mean a 16-bit image.
In object orientation, it's good practice to model objects based on what they are and can, and not by how they internally store their data. This allows you to encapsulate the data (and restrict or control (observer support) access with getters/setters, or even make the internal representation immutable or poolable), and provide appropriate methods for your objects.
String is immutable in Java and stored in the String pool. Once it is created it stays in the pool until garbage collected.Since, String is immutable , the logging password is as readable string.It has greater risk of producing the memory dump to find the password.
where as Char array is created in heap and you can override with some dummy values.
String
is immutable. Char
array is not. A string is implemented with a char array underneath but every time you try to modify it (like with concatenation, replace etc.) it gives you a new String
object.
So, String
behaves as a constant Char
array but comes with certain syntactic sugar that also makes them very easier to use. For example, the addition +
operator has been overloaded as a string concatenation operator as well.
The advantage to using the string object is all the methods available to it. For example:
stringExample1.equals(stringExample2);
String stringExample3 = stringExample1.replace(substring1, substring2);
In Java, String
is a basic system class that essentially wraps a char[]
. There are several reasons why, for most uses, having a full class is preferable to directly handling arrays:
String
s are immutable; once you have a reference to some String
, you know it's never going to change.String
s provide useful methods that a bare array couldn't, such as length()
, and have clearly-defined comparison semantics.+
).Essentially, it's good OO practice to use a class to collect the desired behavior and the data structures in the same place, and String
wraps up an array of characters with the useful operations that you want to perform on a string.