12-03-25 ---------- String Handling ------------------ Q)What is a string in Java? =>A string is a sequence of characters represented as a single entity. =>A string is used to represent textual data in a Java application. =>A string is an object in Java. Note:- Performing operations on string objects is nothing but string handling. Q)How is a string created in a Java application? =>In two ways a string is created in Java. 1)using new keyword 2)using string literal For eg. String s=new String("hello");//string object created using new keyword String s1="hello";//string object created using a string literal Note:- If a string is created using new keyword, the string object is stored in HEAP area of RAM. If a string is created using a string literal, the string object is created in string constant pool. Q)What is a string constant pool? =>string constant pool(string pool) is a special memory region in RAM where strings that are created using string literals are stored by JVM. Q)What is an immutable string? =>non-modifiable string is known as an immutable string. =>java.lang.String class represents immutable strings. Q)How to compare two strings? =>There are two methods to compare two strings(content of the strings). 1)boolean equals() 2)boolean equalsIgnoreCase() For eg. String s1=new String("java"); String s2=new String("java"); String s3=s1.concat("Hello"); String s4=s1.concat("hello"); System.out.println(s1.equals(s2));//true System.out.println(s3.equals(s4));//false System.out.println(s3.equalsIgnoreCase(s4));//true Note:- to compare the content of two strings don't use equality operator(==) Q)Important methods of java.lang.String class. 1)length():- returns the number of characters in the string. 2)equals() 3)toUpperCase() 4)toLowerCase() 5)charAt(int index) 6)trim() :- removes leading spaces and trailing spaces 7)equalsIgnoreCase() 8)substring(int index) 8)substring(int start,int end) class Test{ public static void main(String[] args){ String s1=new String("javalanguage"); String s2=s1.toUpperCase(); if(s1.equals(s2)) //false System.out.println("strings are equal"); else System.out.println("strings are not equal"); System.out.println(s1.charAt(2));//v System.out.println(s1.substring(4));//language System.out.println(s1.substring(4,11));//4th index to 10th indext chars printed String s5=" hello " ; System.out.println("hi"+s5+"nice");//hi hello nice String s6=s5.trim();//hello System.out.println("hi"+s6+"nice");//hihellonice } }