I understand, however your post could be misinterpreted to reinforce the misconception that String is among the primitive types.
I just hoped to clear that up
For any beginners, all you really need to know about Strings is this:
Code:
- Strings are objects.
- Strings are immutable which means they cannot change.
- A String to put it simply, is just an array of chars(The primitive type) wrapped in an object.
- The == operator should not be used to compare Strings.
- To compare strings use the built in .equals() method.
To give a better understanding of why, a String(internally) works a bit like this:
Code:
char[] chris = {'c', 'h', 'r', 'i', 's'};
Now, this is wrapped in an class called String.
*Note that '' denotes a char(primitive) and "" denotes a String(Object).
Code:
public class String {
char[] chris = {'c', 'h', 'r', 'i', 's'};
}
When you do "chris" == "chris", what java does is it compares the value of both OBJECTS.
Since a string is an Object, it checks if "chris" is the same object as "chris".
For example:
Code:
Object obj = new Object();
if(obj == obj) {
System.out.println("This is the same as 'chris' == 'chris'");
}
if(object == new Object()) {
System.out.println("This is not, and will return false");
}
In this case "chris" == "chris" will return true because Java under normal circumstances creates strings and caches them in the String pool.
So the first time you do "chris", Java creates a new String object and adds it to the String pool.
The second time it grabs the Object "chris" from the string pool.
Thus they are the SAME object and that statement will return true.
"chris" == "bob" WILL return false because they are two DIFFERENT Objects.
Even though this does work, it's not garunteed to work because it does not compare their values.
The .equals() method should be used instead because it compares each character in the strings and checks if they match.
(It does: 'c' == 'c' and 'h' == 'h' and 'r' == 'r', and so on to check if the strings match)
I'm not the best teacher, so I hope this was easily understood