String Handling in Java
String Handling in Java
Introduction
• Strings are defined as an array of characters. The
difference between a character array and a string is
the string is terminated with a special character
‘\0’.
• In Java, a string is an object that represents a
sequence of characters.
• The java.lang.String class is used to create string
object.
• In java, objects of String are immutable which
means a constant and cannot be changed once
created.
Creating Strings
• By string literal : Java String literal is created
by using double quotes.
For Example: String s=“Welcome”;
• By new keyword : by using a keyword “new”.
For example:
String s=new String(“Welcome”);
String Methods
// Returns the index within the string of the first occurrence of the
specified string.
String s4 = "Learn Share Learn";
System.out.println("Index of Share " + s4.indexOf("Share"));
// Returns the index within the string of the first occurrence of the
specified string, starting at the specified index.
System.out.println("Index of a = " + s4.indexOf('a',3));
// Checking equality of Strings
Boolean out = "Geeks".equals("geeks");
System.out.println("Checking Equality " + out);
out = "Geeks".equals("Geeks");
System.out.println("Checking Equality " + out);
out = "Geeks".equalsIgnoreCase("gEeks ");
System.out.println("Checking Equality " + out);
int out1 = s1.compareTo(s2);
System.out.println("If s1 = s2 " + out);
// Converting cases
String word1 = "GeeKyMe";
System.out.println ("Changing to lower Case " +
word1.toLowerCase());
// Converting cases
String word2 = "GeekyME";
System.out.println("Changing to UPPER Case " +
word1.toUpperCase());
// Trimming the word
String word4 = " Learn Share Learn ";
System.out.println("Trim the word " + word4.trim());
// Replacing characters
String str1 = "feeksforfeeks";
System.out.println("Original String " + str1);
String str2 = "feeksforfeeks".replace('f' ,'g') ;
System.out.println("Replaced f with g -> " + str2);
}
}
Output:
String length = 13
Character at 3rd position = k
Substring ksforGeeks
Substring = eks
Concatenated string = GeeksforGeeks
Index of Share 6
Index of a = 8
Checking Equality false
Checking Equality true
Checking Equality false
If s1 = s2 false
Changing to lower Case geekyme
Changing to UPPER Case GEEKYME
Trim the word Learn Share Learn
Original String feeksforfeeks
Replaced f with g -> geeksgorgeeks