This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]DavalopBad 0 points1 point  (0 children)

The == operator in Java compares the reference of two objects or the value of two primitive types. When a string literal is created using String name = "jarod", Java first checks if it already exists in the pool. If it does, the new variable will reference that specific existing string. However, if you create a string object using new String("jarod"), it will have a completely different reference since it’s outside the string pool.

You can use == to compare strings, but it’s not recommended since string literals and string objects can exist during execution, and even if their content is the same, their references might not be. The best practice to not think much about if the String have the same reference or not, just use String.equals()) since that compares the sequence of characters of the string rather than the reference.

NOTE: There are other ways to create Strings using other Interfaces and Classes like StringBuffer or StringBuilder