You are on page 1of 2

Strings in java

Java String Class is immutable,that means Strings in java, once created and initialized, cannot be changed on the same reference. A java.lang.String class is final which implies no class and extend it. The java.lang.String class differs from other classes, one difference being that the String objects can be used with the += and + operators for concatenation. Two useful methods for String objects are equals( ) and substring( ). The equals( ) method is used for testing whether two Strings contain the same value. The substring( ) method is used to obtain a selected portion of a String.

Java.lang.String class creation


String str1 = My name is Anuj; String str2 = My name is Anuj; String str3 = My name + is Anuj; //Compile time expression String name = Anuj; String str4 = My name is + name; String str5 = new String(My name is Anuj); -----------------------------------------------------------------

Java String compare to determine Equality


java string compare can be done in many ways . * == Operator * equals method * compareTo method ------------------------------------------------Comparing using the == Operator -------------------------------------------The == operator is used when we have to compare the String object references. If two String variables point to the same object in memory, the comparison returns true. Otherwise, the comparison returns false. Note that the == operator does not compare the content of the text present in the String objects. It only compares the references the 2 Strings are pointing to.
public class First { public static void main(String[] args) { String name1 = "Anuj"; String name2 = new String("Anuj"); String name3 = "Anuj"; if (name1 == name2) { } else { System.out.println("The strings are equal.");

System.out.println("The strings are unequal.");

if (name1 == name3) { System.out.println("The strings are equal."); } else { System.out.println("The strings are unequal."); } } } ----------------------------------------------------------------------

Comparing using the equals Method -------------------------------------------------------------------------------------------The equals method is used when we need to compare the content of the text present in the String objects. This method returns true when two String objects hold the same content
public class First { {

public static void main(String[] args) String name1 = "Anuj"; String name2 = new String("Anuj"); String name3 = "Anuj";

if (name1.equals(name2)) { System.out.println("The strings are equal."); } else { System.out.println("The strings are unequal."); } if (name1.equals(name3)) { System.out.println("The strings are equal."); } else { System.out.println("The strings are unequal."); }}} ------------------------------------------------------------------------------------------------------

You might also like