Lecture 3.1 STRINGS School of Computer Science and Engineering
Topic of the Lecture Strings Creating a String object String class methods concat () equals() Substirng () compareTo () String class methods toLowerCase () toUpperCase () charAt () length() replace() trim() split() contains() isEmpty () String Constant Pool
Strings Definition
Strings Definition String is a sequence of characters String is an object that represents a sequence of characters. java.lang.String class is used to create a string object. String is a sequence of characters. In java, objects of String are immutable which means a constant and cannot be changed once created. Whenever a change to a String is made, an entirely new String is created.
Strings Creating string object There are two ways to create String object:
Strings Creating string object 1) String Literal Java String literal is created by using double quotes. Example: String s=“REVA"; It doesn't create a new instance String s1=“ REVA "; String s2=“ REVA "; “REVA”
Strings Creating string object 2) By new keyword String s1=new String(“REVA"); In such case, JVM will create a new string object in normal (non-pool) heap memory, and the literal “REVA" will be placed in the string constant pool. The variable s1 will refer to the object in a heap (non-pool).
Strings class StringE { public static void main(String args []) { String s1="REVA "; // creating string by Java string literal char ch []={'u','n',' i ','v','e','r','s',' i ',' t','y '}; String s2=new String( ch ); // converting char array to string String s3=new String("BANGALORE "); // creating Java string by new keyword System.out.println (s1); System.out.println (s2); System.out.println (s3); } } Example program Output: C:\lks\2020\unit 1> javac StringE.java C:\lks\2020\unit 1>java StringE REVA university BANGALORE
String Constant Pool A Java String Pool is a place in heap memory where all the strings defined in the program are stored. A separate place in a stack is there where the variable storing the string is stored. Whenever we create a new string object, JVM checks for the presence of the object in the String pool, If String is available in the pool, the same object reference is shared with the variable, else a new object is created . When we declare a string, an object of type String is created in the stack, while an instance with the value of the string is created in the heap .
import java.util .*; class Demo{ public static void main(String[] args ) { String s1 = " abc “, s2 = " abc "; String s3 = new String(" abc "); String s4 = new String(" abc "); if (s1 == s2) System.out.println ("Yes"); else System.out.println ("No"); if ( s3 == s4) System.out.println ("Yes"); else System.out.println ("No"); } } Output: Yes No
Strings In java, string concatenation forms a new string that is the combination of multiple strings. There are two ways to concat string in java: 1. By + (string concatenation) operator 2. By concat () method java string concat ()
Strings java string concat () For Example: class TestStringConcatenation1 { public static void main(String args []) { String s=" Sachin "+" Tendulkar "; System.out.println (s);// Sachin Tendulkar } } 1) String Concatenation by + (string concatenation) operator Java string concatenation operator (+) is used to add strings. Output: Sachin Tendulkar
Strings java string concat () For Example: class TestStringConcatenation3{ public static void main(String args []){ String s1=" Sachin "; String s2=" Tendulkar "; String s3=s1.concat(s2); System.out.println (s3);// Sachin Tendulkar } } 2) String Concatenation by concat () method The String concat () method concatenates the specified string to the end of current string. Syntax: public String concat (String another) Output: Sachin Tendulkar
Strings concat () example program public class ConcatExample2 { public static void main(String[] args ) { String str1 = "Hello"; String str2 = "Reva"; String str3 = "University"; // Concatenating one string String str4 = str1.concat(str2); System.out.println (str4); // Concatenating multiple strings String str5 = str1.concat(str2). concat (str3); System.out.println (str5); } } Output: HelloReva HelloRevaUniversity
Strings substring() example program public class TestSubstring { public static void main(String args []) { String s=" Sachin Tendulkar "; System.out.println ( s.substring (6));// Tendulkar . System.out.println ( s.substring (0,6));// Sachin . } } C:\pgrs>java TestSubstring Tendulkar Sachin The java string substring() method returns a part of the string.
Strings String comparison Can be done in 3 ways equals() The java string equals() method compares the two given strings based on the content of the string. If any character is not matched, it returns false. If all characters are matched, it returns true. compareTo () The String compareTo () method compares values lexicographically and returns an integer value that describes if first string is less than, equal to or greater than second string . s1 == s2 : The method returns 0. s1 > s2 : The method returns a positive value. s1 < s2 : The method returns a negative value. == Compare reference not the values. If the reference is not matched, it returns false. If all the reference is , it returns true.
Strings String equals() import java.lang.String ; public class EqualsExample { public static void main(String args []){ String s1=“ reva "; String s2=“ reva "; String s3=“REVA"; String s4="python"; System.out.println (s1.equals(s2));//true because content and case is same System.out.println (s1.equals(s3));//false because case is not same System.out.println (s1.equals(s4));//false because content is not same }} Output: true false false
Strings String compareTo () class CompareToExample { public static void main(String args []){ String s1="hello"; String s2="hello"; String s3=" meklo "; String s4=" hemlo "; String s5="flag"; System.out.println (s1.compareTo(s2));//0 because both are equal System.out.println (s1.compareTo(s3 ));//5 because "h" is 5 times lower than "m" System.out.println (s1.compareTo(s4 ));//1 because "l" is 1 times lower than "m" System.out.println (s1.compareTo(s5));//2 because "h" is 2 times greater than "f" }} C:\pgrs>java CompareExample -5 -1 2 t s r q p o n m l k j i h g f e d c b a
import java.io.*; public class Test { public static void main(String args[]) { String Str = new String("Welcome to REVA"); System.out.print ("Return Value :"); System.out.println ( Str.toLowerCase ()); } } Output Return Value :welcome to reva Strings String toLowerCase () Method Syntax: public String toLowerCase ()
import java.io.*; public class Test { public static void main(String args[]) { String Str = new String("Welcome to reva "); System.out.print ("Return Value :" ); System.out.println ( Str.toUpperCase () ); } } Output Return Value :WELCOME TO REVA Strings String toUpperCase () Method Syntax: public String toUpperCase ()
public class CharAtExample { public static void main(String args[]) { String name=“REVA UNIVERSITY”; char ch = name.charAt (5); System.out.println ( ch ); } } Output: U Strings Java String charAt () Syntax: public char charAt ( int index)
public class LengthE { public static void main(String args[]) { String s1=“corona virus"; String s2=“India"; System.out.println("string length is: "+s1.length()); System.out.println("string length is: "+s2.length()); } } Output: string length is: 12 string length is: 5 Strings Java String length() Syntax: public int length()
public class replaceE { public static void main(String args[]) { String s1=“St_y Home Stay S_fe"; String replaceString=s1.replace(‘_',‘a'); System.out.println(replaceString); } } Output: Stay Home Stay Safe Strings Java String replace() Syntax: public String replace(char oldChar, char newChar)
public class trimE { public static void main(String args []) { String s1=" REVA "; System.out.println (s1+"Bangalore"); System.out.println (s1.trim()+"Bangalore"); } } Output: C:\pgrs>java trimE REVA Bangalore REVABangalore Strings Java String trim () that eliminates leading and trailing spaces Syntax: public String trim()
public class SplitE { public static void main(String args[]) { String s1="REVA University best educational institute"; String[] words=s1.split (“ "); for(String w:words) { System.out.println(w); } } } Output: REVA University best educational Institute Strings Java String split() Syntax: public String split(String regex)
class Main { public static void main(String[] args ) { String s1="REVA_University_best_educational_institute"; String[] words=s1.split("_",1); for(String w:words ) { System.out.println (w ); } } } Output: REVA_University_best_educational_institute Strings Java String split() Syntax: public String split(String regex)
class Main { public static void main(String[] args ) { String s1="REVA_University_best_educational_institute"; String[] words=s1.split ("_",3); for(String w:words ) { System.out.println (w ); } } } Output: REVA University best_educational_institute Strings Java String split() Syntax: public String split(String regex)
class containsE { public static void main(String args[]) { String name="what do you know about me"; System.out.println( name.contains ("do you")); System.out.println( name.contains ("about")); System.out.println( name.contains ("hello")); } } Output: true true false Strings Java String contains() Syntax: public boolean contains( CharSequence sequence)
public class IsEmptyE { public static void main(String args[]) { String s1=""; String s2=“COVID-19"; System.out.println(s1.isEmpty()); System.out.println(s2.isEmpty()); } } Output: true false Strings Java String isEmpty() Syntax: public boolean isEmpty()
public class IsEmptyExample { public static void main(String args []){ String s1=""; String s2=" javatpoint "; System.out.println (s1.isEmpty()); System.out.println (s2.isEmpty()); }} Output: true false Strings Java String isEmpty() Syntax: public boolean isEmpty()
CharSequence Interface CharSequence Interface is used for representing the sequence of Characters in Java . String StringBuffer StringBuilder
1. String String is an immutable class which means a constant and cannot be changed once created and if wish to change , we need to create an new object and even the functionality it provides like toupper , tolower , etc all these return a new object , its not modify the original object. It is automatically thread safe . String str = "geeks"; or String str = new String("geeks")
2. StringBuffer String represents fixed-length, immutable character sequences StringBuffer represents growable and writable character sequences means it is immutable in nature I t is thread safe class , we can use it when we have multi threaded environment and shared object of string buffer i.e , used by mutiple thread . A llow you to modify the contents of a string without creating a new object every time. Syntax : StringBuffer demoString = new StringBuffer (“REVA");
Methods of StringBuffer The initial capacity of a StringBuffer can be specified when it is created, or it can be set later with the ensureCapacity () method. The append () method is used to add characters, strings, or other objects to the end of the buffer. The insert () method is used to insert characters, strings, or other objects at a specified position in the buffer. The delete () method is used to remove characters from the buffer. The reverse () method is used to reverse the order of the characters in the buffer.
public class StringBufferExample { public static void main(String[] args ) { StringBuffer sb = new StringBuffer ("Hello"); sb.append ("Java"); // now original string is changed System.out.println ( sb ); sb.insert (1 , "Java"); // Now original string is changed System.out.println ( sb ); sb.replace (1 , 3, “REVA");// replaces the given string from the specified beginIndex and endIndex-1 System.out.println ( sb ); sb.delete (1 , 3); System.out.println ( sb ); sb.reverse (); System.out.println ( sb ); StringBuffer sb1 = new StringBuffer (); System.out.println (“Default capacity is:"+sb1.capacity ());//default 16 sb1.append ("java is my favourite language "); System.out.println (sb1.capacity());// now it becomes (16*2)+2=34 } } Output: HelloJava HJavaelloJava HREVAvaelloJava HVAvaelloJava avaJolleavAVH Default capacity is:16 34
StringBuilder StringBuilder in Java represents a mutable sequence of characters A s it creates a mutable sequence of characters and it is not thread safe and its used only within the thread. It is mainly used for single threaded program . T he StringBuilder class differs from the StringBuffer class on the basis of synchronization . The StringBuilder class provides no guarantee of synchronization whereas the StringBuffer class does. Therefore this class is designed for use as a drop-in replacement for StringBuffer in places where the StringBuffer was being used by a single thread Syntax : StringBuilder demoString = new StringBuilder (); demoString.append (“REVA");
Creating Immutable class There are many immutable classes like String, Boolean, Byte, Short, Integer, Long, Float, Double etc. In short, all the wrapper classes and String class is immutable. We can also create immutable class by creating final class that have final data members as the example given below:
public final class Employee { final String pancardNumber ; public Employee(String pancardNumber ) { this .pancardNumber = pancardNumber ; } public String getPancardNumber () { return pancardNumber ; } } public class ImmutableDemo { public static void main(String ar []) { Employee e = new Employee("ABC123"); String s1 = e.getPancardNumber (); System.out.println (" Pancard Number: " + s1); } } Output: Pancard Number: ABC123
to String () The toString () method returns the String representation of the object. If you print any object, Java compiler internally invokes the toString () method on the object. So overriding the toString () method, returns the desired output, it can be the state of an object etc. depending on your implementation.
without using tostring () method class Student{ int rollno ; String name, city ; Student( int rollno , String name, String city){ this .rollno = rollno ; this .name=name; this .city =city ; } public static void main(String args []){ Student s1= new Student(101 ,“ABC",“Bangalore"); Student s2= new Student(102 ,“XYZ",“Mysore"); System.out.println (s1);//compiler writes here s1.toString() System.out.println (s2);//compiler writes here s2.toString() } } Output: Student@1fee6fc Student@1eed786
with using tostring () method class Student { int rollno ; String name, city ; Student( int rollno , String name, String city ) { this .rollno = rollno ; this .name=name ; this .city =city ; } public String toString () {// overriding the toString () method return rollno +" "+name+" "+city; } public static void main(String args []) { Student s1= new Student(101,“ABC",“Bangalore"); Student s2= new Student(102,“XYZ",“Mysore"); System.out.println (s1);//compiler writes here s1.toString() System.out.println (s2);//compiler writes here s2.toString() } } 101 ABC Bangalore 102 XYZ Mysore
StrigTokenizer class StringTokenizer class in Java is used to break a string into tokens. The java.util.StringTokenizer class allows you to break a String into tokens . In the StringTokenizer class, the delimiters can be provided at the time of creation or one by one to the tokens . Constructor Description StringTokenizer(String str) It creates StringTokenizer with specified string. StringTokenizer (String str , String delim ) It creates StringTokenizer with specified string and delimiter. StringTokenizer (String str , String delim , boolean returnValue ) It creates StringTokenizer with specified string, delimiter and returnValue . If return value is true, delimiter characters are considered to be tokens. If it is false, delimiter characters serve to separate tokens.
Methods of StrigTokenizer class Methods Description boolean hasMoreTokens() It checks if there is more tokens available. String nextToken() It returns the next token from the StringTokenizer object. String nextToken(String delim) It returns the next token based on the delimiter. boolean hasMoreElements() It is the same as hasMoreTokens() method. Object nextElement() It is the same as nextToken() but its return type is Object. int countTokens() It returns the total number of tokens.
import java.util.StringTokenizer ; public class StringTokenizer1 { public static void main(String args []) { StringTokenizer st = new StringTokenizer ("Demonstrating methods from StringTokenizer class"," "); while ( st.hasMoreTokens ()) { System.out.println ( st.nextToken ()); } } } Output: Demonstrating methods from StringTokenizer class