Search Logic Blocks

Monday, July 27, 2020

Java: String Class

String is a class and contains simple text with all the possible characters having unicode code points. I have already discussed about the char data type and unicode code points set. We are using String class and its methods again & again in our examples. So, I thought we should go little bit deep into the String class details and explore the String class methods.

As we know String is a class and to use the class methods, we need to create an object of String. We have already discussed that when an object is created, it refers to the memory location where the object's fields are stored. So, String object also refers to the text only.
String s = "Logic Blocks";
As in the above example, String class can be used as primitive data types and assign value directly to the String object. But still, String class object refers to the memory location where the data is stored, not as data value. String class is an immutable class, the text can not be changed in the memory location. Whenever you assign new value to the String class object, it refers to new memory location, doesn't replace the old memory location with new text.

There are so many String class constructors and methods, are documented here. Few of them, we have already used in earlier examples: How to get input characters and strings from consoleHow to reverse any string backwards using recursive methodCount the words and Converts alphabets - lowercase to uppercase and uppercase to lowercase.
public class StringClassDemo {
public static void main(String args[]) {
char ch[] = {'S', 't', 'r', 'i', 'n', 'g', ' ', 'D', 'e', 'm', 'o'};
int in[] = {83, 116, 114, 105, 110, 103, 32, 68, 101, 109, 111};

String s = "Logic Blocks";
// String Class Constructors
String s1 = new String(ch);
String s2 = new String("String Demo");
String s3 = new String(ch, 0, ch.length);
String s4 = new String(in,0,in.length);
String s5 = new String("String Demo");

System.out.println("s1: " + s1 + ", s2: " + s2 + ", s3: " + s3 + ", s4: " + s4 + ", s5: " + s5 + "\n");

// String Class Methods
// length()
System.out.println("String s1 has length of " + s1.length() + " characters!!\n");

// isEmpty()
System.out.println("String s2 is empty :" + s2.isEmpty() + "\n");

// charAt()
System.out.println("String s3 has character at index 8 is " + s3.charAt(8) + "\n");

// codePointAt(), codePointBefore() and codePointCount()
System.out.println("String s4 has Unicode Code Point at index 8 is " + s4.codePointAt(8) + "\n");
System.out.println("String s5 has Unicode Code Point at index before 8 is " + s5.codePointBefore( 8) + "\n");
System.out.println("String s1 has code point count " + s1.codePointCount(0, 5) + "\n");

// equals() and equalsIgnoreCase()
System.out.println("String s2 is equal to s3 " + s2.equals(s3) + "\n");

s5 = "String demo";
System.out.println("String s4 is equal to s5 " + s4.equals(s5) + "\n");
System.out.println("String s4 is equal (Ignore Case) to s5 " + s4.equalsIgnoreCase(s5) + "\n");

// compareTo() and compareToIgnoreCase()
System.out.println("String s1 is compared to s5 " + s1.compareTo(s5) + "\n");
System.out.println("String s1 is compared (Ignore Case) to s5 " + s1.compareToIgnoreCase(s5) + "\n");

// startsWith() and endsWith()
System.out.println("String s2 starts with 'Str' " + s2.startsWith("Str") + "\n");
System.out.println("String s2 starts with 'ring' at index 1 " + s2.startsWith("ring", 1) + "\n");
System.out.println("String s2 starts with 'ring' at index 2 " + s2.startsWith("ring", 2) + "\n");
System.out.println("String s5 ends with 'mo' " + s5.endsWith("mo") + "\n");

// indexOf() and lastIndexOf()
String s6 = "Logic Blocks";
System.out.println("Index of character 'o' in String s6 is " + s6.indexOf('o') + "\n");
System.out.println("Last index of character 'o' in String s6 is " + s6.lastIndexOf('o') + "\n");

// substring()
System.out.println("Substring starting at index 2 in String s6 is " + s6.substring(2) + "\n");
System.out.println("Substring starting at between index 2 and 5 in String s6 is " + s6.substring(2, 5) + "\n");

// concat()
System.out.println("'Soft' is concatenated to String s6 " + "Soft ".concat(s6) + "\n");

// replace()
System.out.println("String s6 character 'B' is replaced by 'b' " + s6.replace('B','b') + "\n");

// split
String sp[] = s6.split(" ");
System.out.print("String s6 is split with space: ");
for(int i = 0; i < sp.length; i++) {
System.out.print("(" + (i+1) + ")" + sp[i] + " ");
}
System.out.println();

// toLowerCase() and toUpperCase()
System.out.println("String s6 is converted into lowercase " + s6.toLowerCase() + "\n");
System.out.println("String s6 is converted into uppercase " + s6.toUpperCase() + "\n");

// trim
String s7 = " Logic Blocks ";
System.out.println("String s7 before trim : " + s7 + "...\n");
System.out.println("All leading and trailing spaces are trimmed in String s7 : " + s7.trim() + "...\n");

// toCharArray() and valueOf()
char ca[] = s6.toCharArray();
System.out.print("String s6 is converted into char array: ");
for(int i = 0; i < ca.length; i++) {
System.out.print(ca[i] + " ");
}
System.out.println();
System.out.println("Character Array ca has value as " + String.valueOf(ca) + "\n");

// repeat()
System.out.println("String s6 is repeated 3 times " + s6.repeat(3) + "\n");
}
}
In above example, I have used most of the String class constructors and methods. There are more other methods which are related to advanced concepts like Class Pattern and Interface IntStream, so they are not covered here. Let's discuss them one by one.

String Class Constructors
String s = "Logic Blocks";
// String Class Constructors
String s1 = new String(ch);
String s2 = new String("String Demo");
String s3 = new String(ch, 0, ch.length);
String s4 = new String(in,0,in.length);
String str = "String Demo";
String s5 = new String(str);
String class object can be created by assigning text literal value directly to the object:
String s = "Logic Blocks";
String class object can be created using the array of characters:
char ch[] = {'S', 't', 'r', 'i', 'n', 'g', ' ', 'D', 'e', 'm', 'o'};
String s1 = new String(ch);
String  class object can be created by String text or another String object:
String s2 = new String("String Demo");
String str = "String Demo";
String s5 = new String(str);
String class object can be created by char array, starting index and ending index:
String s3 = new String(ch, 0, ch.length);
String class object can be created by unicode code points array (Characters are represented by Unicode set values: S = 83, t = 116...), starting index and ending index:
int in[] = {83, 116, 114, 105, 110, 103, 32, 68, 101, 109, 111};
String s4 =  new String(in,0,in.length);
String class Methods
length() method tells how many characters are there in the given string:
System.out.println("String s1 has length of " + s1.length() + " characters!!\n");
isEmpty() method tell if the String is empty:
System.out.println("String s2 is empty :" + s2.isEmpty() + "\n");
charAt() method returns the character at the particular index:
System.out.println("String s3 has character at index 8 is " + s3.charAt(8) + "\n");
codePointAt() method returns the unicode code point at the particular index:
System.out.println("String s4 has Unicode Code Point at index 8 is " + s4.codePointAt(8) + "\n");
codePointBefore() method returns the unicode code point before the particular index:
System.out.println("String s5 has Unicode Code Point at index before 8 is " + s5.codePointBefore( 8) + "\n");
codePointCount() method returns the count of total unicode code points in the given string:
System.out.println("String s1 has code point count " + s1.codePointCount(0, 5) + "\n");
equals() and equalsIgnoreCase() methods return true or false depending on whether the string text value is equal to another text or string:
System.out.println("String s2 is equal to s3 " + s2.equals(s3) + "\n");

s5 = "String demo";
System.out.println("String s4 is equal to s5 " + s4.equals(s5) + "\n");
System.out.println("String s4 is equal (Ignore Case) to s5 " + s4.equalsIgnoreCase(s5) + "\n");
compareTo() and compareToIgnoreCase() methods compare the string text value lexicographically with another text or string, return the negative / positive values:
System.out.println("String s1 is compared to s5 " + s1.compareTo(s5) + "\n");
System.out.println("String s1 is compared (Ignore Case) to s5 " + s1.compareToIgnoreCase(s5) + "\n");
startsWith() and endsWith() methods returns true or false depending on whether the string starts / ends with the given string:
System.out.println("String s2 starts with 'Str' " + s2.startsWith("Str") + "\n");
System.out.println("String s2 starts with 'ring' at index 1 " + s2.startsWith("ring", 1) + "\n");
System.out.println("String s2 starts with 'ring' at index 2 " + s2.startsWith("ring", 2) + "\n");
System.out.println("String s5 ends with 'mo' " + s5.endsWith("mo") + "\n");
indexOf() and lastIndexOf() methods return the starting index and last index of the string for the five string or character:
String s6 = "Logic Blocks";
System.out.println("Index of character 'o' in String s6 is " + s6.indexOf('o') + "\n");
System.out.println("Last index of character 'o' in String s6 is " + s6.lastIndexOf('o') + "\n");
substring() returns the part of the string between two indexes:
System.out.println("Substring starting at index 2 in String s6 is " + s6.substring(2) + "\n");
System.out.println("Substring starting at between index 2 and 5 in String s6 is " + s6.substring(2, 5) + "\n");
concat() method concatenates one string to other string:
System.out.println("'Soft' is concatenated to String s6 " + "Soft ".concat(s6) + "\n");
replace() method replaces one part of the string with another string and returns a new string:
System.out.println("String s6 character 'B' is replaced by 'b' " + s6.replace('B','b') + "\n");
split() method splits the string by given string and creates new string array:
String sp[]  = s6.split(" ");
System.out.print("String s6 is split with space: ");
for(int i = 0; i < sp.length; i++) {
System.out.print("(" + (i+1) + ")" + sp[i] + " ");
}
System.out.println();
toLowerCase() and toUpperCase() methods convert the string into lowercase and uppercase strings respectively:
System.out.println("String s6 is converted into lowercase " + s6.toLowerCase() + "\n");
System.out.println("String s6 is converted into uppercase " + s6.toUpperCase() + "\n");
trim() method truncates the trailing and leading spaces in the string: 
String s7 = " Logic Blocks       ";
System.out.println("String s7 before trim : " + s7 + "...\n");
System.out.println("All leading and trailing spaces are trimmed in String s7 : " + s7.trim() + "...\n");
toCharArray() and valueOf() methods convert string to char array and char array to the string respectively:
char ca[]  = s6.toCharArray();
System.out.print("String s6 is converted into char array: ");
for(int i = 0; i < ca.length; i++) {
System.out.print(ca[i] + " ");
}
System.out.println();
System.out.println("Character Array ca has value as " + String.valueOf(ca) + "\n");
repeat() method repeats the string given no of times:
System.out.println("String s6 is repeated 3 times " + s6.repeat(3) + "\n");
And the output for whole code is : 

s1: String Demo, s2: String Demo, s3: String Demo, s4: String Demo, s5: String Demo

String s1 has length of 11 characters!!

String s2 is empty :false

String s3 has character at index 8 is e

String s4 has Unicode Code Point at index 8 is 101

String s5 has Unicode Code Point at index before 8 is 68

String s1 has code point count 5

String s2 is equal to s3 true

String s4 is equal to s5 false

String s4 is equal (Ignore Case) to s5 true

String s1 is compared to s5 -32

String s1 is compared (Ignore Case) to s5 0

String s2 starts with 'Str' true

String s2 starts with 'ring' at index 1 false

String s2 starts with 'ring' at index 2 true

String s5 ends with 'mo' true

Index of character 'o' in String s6 is 1

Last index of character 'o' in String s6 is 8

Substring starting at index 2 in String s6 is gic Blocks

Substring starting at between index 2 and 5 in String s6 is gic

'Soft' is concatenated to String s6 Soft Logic Blocks

String s6 character 'B' is replaced by 'b' Logic blocks

String s6 is split with space: (1)Logic (2)Blocks 
String s6 is converted into lowercase logic blocks

String s6 is converted into uppercase LOGIC BLOCKS

String s7 before trim :  Logic Blocks       ...

All leading and trailing spaces are trimmed in String s7 : Logic Blocks...

String s6 is converted into char array: L o g i c   B l o c k s 
Character Array ca has value as Logic Blocks

String s6 is repeated 3 times Logic BlocksLogic BlocksLogic Blocks

Strings in switch-case statement
In earlier versions, switch-case statement could have only int or char data type values. But after JDK7, strings can also be used in switch-case statement. Here is the example:
import java.util.Scanner;

public class StringSwitchCase {
public static void main(String args[]) {
System.out.println("Enter two numbers");
int i, j, total;
Scanner sc = new Scanner(System.in);
i = sc.nextInt();
j = sc.nextInt();
System.out.println("What do you like to do? Sum / Difference");
String ans = sc.next();
switch(ans) {
case "Sum": total = i + j;
System.out.println("The answer is: " + total);
break;
case "Difference": total = i - j;
System.out.println("The answer is: " + total);
break;
default: total = 0;
System.out.println("Wrong choice");
}
}
}
In above example, the user is asked to enter the two numbers and also is asked whether the user wants sum  or difference between two numbers. Accordingly, the answer is displayed. Output is shown below:

Enter two numbers
20 34
What do you like to do? Sum / Difference
Sum
The answer is: 54

Enter two numbers
56 73
What do you like to do? Sum / Difference
Difference
The answer is: -17

Enter two numbers
45 32
What do you like to do? Sum / Difference
er
Wrong choice

All code is accessible at Github link.

No comments: