In this lab, you will explore and demonstrate the built-in methods in the String class. These methods help you manipulate the String data type. By the end of this lab learners will be able to describe the Strings methods and use Java Strings Methods.
Instructions
length() method
The length() method returns the length of the string, or it returns the count of the total number of characters present in the string.
The Java string trim() method removes the leading and trailing spaces. It checks the Unicode value of the space character (‘\u0020’) before and after the string. If it exists, then remove the spaces and return the omitted string.
Example:
publicclassStringTrimExample{publicstaticvoidmain(String args[]){String s1=" hello ";System.out.println(s1+"how are you"); // without trim()System.out.println(s1.trim()+"how are you"); // with trim() }}
toLowerCase() method:
The toLowerCase() method converts all the characters of the String to lowercase.
Example:
publicclassStringLowerExample{publicstaticvoidmain(String args[]){String s1="HELLO HOW Are You?";String s1lower=s1.toLowerCase();System.out.println(s1lower);}}
Output:
hello how are you.
toUpperCase() method:
The toUpperCase() method converts all of the String characters to uppercase.
Example:
publicclassStringUpperExample{publicstaticvoidmain(String args[]){String s1="hello how are you";String s1upper=s1.toUpperCase();System.out.println(s1upper);}}
Output:
HELLO HOW ARE YOU.
concat() method:
The Java String class provides the concat() method. This method combines a specific string at the end of another string, and ultimately returns a combined string.
Example:
publicclassconcatDemo {publicstaticvoidmain(String[] args) {//------By using concat method----String str1 ="Learn ";String str2 ="Java";// concatenate str1 and str2System.out.println(str1.concat(str2)); // "Learn Java"// concatenate str2 and str11System.out.println(str2.concat(str1)); // "JavaLearn "//--- By using + operator---String s3 ="hello";String s4 ="Learners";// String s5 = s3.concat(s4); orString s5 = s3 + s4;//both of the above statement will give you the same result// Three strings are concatenatedString message ="Welcome "+"to "+"Java";// String Chapter is concatenated with number 2String s ="Chapter"+2; // s becomes Chapter2// String Supplement is concatenated with character BString s1 ="Supplement"+'B'; // s1 becomes SupplementB }}
split() method:
The split() method divides the string at the specified regex and returns an array of substrings.
Example:
// importing Arrays to convert array to string// used for printing arraysimportjava.util.Arrays;publicclassMain {publicstaticvoidmain(String[] args) {String vowels ="a::b::c::d:e";// splitting the string at "::"// storing the result in an array of stringsString[] result =vowels.split("::");// converting array to string and printing itSystem.out.println("result = "+Arrays.toString(result)); }}
Output:
result = [a, b, c, d:e]
charAt() method:
The charAt() method gets the character at the specified index.
Example:
publicclassconcatdemo {publicstaticvoidmain(String[] args) {String message ="Welcome to Java";System.out.println("The first character in the message is "+message.charAt(0)); }}
compareTo() method:
The compareTo() method compares the given string with the current string.
Example:
publicclassCompareToExample{publicstaticvoidmain(String args[]){String s1="hello";String s2="hello";String s3="hemlo";String s4="flag";System.out.println(s1.compareTo(s2)); // 0 because both are equalSystem.out.println(s1.compareTo(s3)); //-1 because "l" is only one time lower than "m"System.out.println(s1.compareTo(s4)); // 2 because "h" is 2 times greater than "f"}}
substring() method:
The substring() method extracts a substring from the string and returns it.
Example:
publicclasssubstringDemo{publicstaticvoidmain(String[] args) {String str1 ="java is fun";// extract substring from index 0 to 3System.out.println(str1.substring(0,4)); }}
indexOf() method:
The indexOf() method returns the index of the first occurrence of the specified character/substring within the string.
Example:
publicclassfindString {publicstaticvoidmain(String[] args) {String str1 ="Java is fun";int result;// getting index of character 's' result =str1.indexOf('s');System.out.println(result); // 6// getting index of character 'J' result =str1.lastIndexOf('J');System.out.println(result); // 0// the last occurrence of 'a' is returned result =str1.lastIndexOf('a');System.out.println(result); // 3// character not in the string result =str1.lastIndexOf('j');System.out.println(result); // -1// getting the last occurrence of "ava" result =str1.lastIndexOf("ava");System.out.println(result); // 1// substring not in the string result =str1.lastIndexOf("java");System.out.println(result); // -1 }}
contains() method:
The contains() method checks whether the specified string (sequence of characters) is present in the string or not.
Example:
Public classcontainexmaple {publicstaticvoidmain(String[] args) {String str1 ="Learn Java";Boolean result;// check if str1 contains "Java" result =str1.contains("Java");System.out.println(result); // true// check if str1 contains "Python" result =str1.contains("Python");System.out.println(result); // false// check if str1 contains "" result =str1.contains("");System.out.println(result); // true }}
replace() method:
The replace() method replaces each matching occurrence of the old character/text in the string with the new character/text.
Example:
publicclassreplaceDemoMain {publicstaticvoidmain(String[] args) {String str1 ="abc cba";// all occurrences of 'a' is replaced with 'z'System.out.println(str1.replace('a','z'));// all occurences of 'L' is replaced with 'J'System.out.println("Lava".replace('L','J'));// character not in the stringSystem.out.println("Hello".replace('4','J'));// all occurrences of "C++" is replaced with "Java"System.out.println(str1.replace("C++","Java"));// all occurences of "aa" is replaced with "zz"System.out.println("aa bb aa zz".replace("aa","zz"));// substring not in the stringSystem.out.println("Java".replace("C++","C")); }}
Java String compares
There are three ways to compare String in Java:
By Using equals() Method
The String class's equals() method compares the original content of the string.
publicclassTeststringcomparison2 {publicstaticvoidmain(String args[]){String s1="Perscholas";String s2="Perscholas";String s3=newString("Perscholas");System.out.println(s1==s2);//true (because both refer to same instance)System.out.println(s1==s3);//false(because s3 refers to instance created in nonpool) }}
By compareTo() Method
The compareTo() method compares values lexicographically.