The document discusses various concepts related to strings in Java like how to create string objects, string immutability, string comparison methods, string concatenation, substring, common string methods, StringBuffer and StringBuilder classes for mutable strings, toString() method, and StringTokenizer class.
The document discusses various concepts related to strings in Java like how to create string objects, string immutability, string comparison methods, string concatenation, substring, common string methods, StringBuffer and StringBuilder classes for mutable strings, toString() method, and StringTokenizer class.
The document discusses various concepts related to strings in Java like how to create string objects, string immutability, string comparison methods, string concatenation, substring, common string methods, StringBuffer and StringBuilder classes for mutable strings, toString() method, and StringTokenizer class.
The document discusses various concepts related to strings in Java like how to create string objects, string immutability, string comparison methods, string concatenation, substring, common string methods, StringBuffer and StringBuilder classes for mutable strings, toString() method, and StringTokenizer class.
Download as TXT, PDF, TXT or read online from Scribd
Download as txt, pdf, or txt
You are on page 1of 6
1)String
Generally string is a sequence of characters. But in java, string is an object.
String class is used to create string object. 2)How to create String object? There are two ways to create String object: a)By string literal b)By new keyword a) String literal String literal is created by double quote.For Example: String s="Hello";
Each time you create a string literal, the JVM checks the string constant pool f irst. If the string already exists in the pool, a reference to the pooled instan ce returns. If the string does not exist in the pool, a new String object instan tiates, then is placed in the pool.For example: String s1="Welcome"; String s2="Welcome";//no new object will be created In the above example only one object will be created.First time JVM will find no string object with the name "Welcome" in string constant pool,so it will create a new object.Second time it will find the string with the name "Welcome" in str ing constant pool,so it will not create new object whether will return the refer ence to the same instance. Note: String objects are stored in a special memory area known as string constan t pool inside the Heap memory. 3)Why java uses concept of string literal? To make Java more memory efficient (because no new objects are created if it exi sts already in string constant pool). b) By new keyword String s=new String("Welcome");//creates two objects and one reference variable
In such case, JVM will create a new String object in normal(nonpool) Heap memory and the literal "Welcome" will be placed in the string constant pool.The variab le s will refer to the object in Heap(nonpool). 3)Immutable String in Java? In java, string objects are immutable. Immutable simply means unmodifiable or un changeable. Once string object is created its data or state can't be changed but a new strin g object is created. Let's try to understand the immutability concept by the example given below: class Simple{ public static void main(String args[]){ String s="Sachin"; s.concat(" Tendulkar");//concat() method appends the string at the end System.out.println(s);//will print Sachin because strings are immutable objec ts } } Output:Sachin Now it can be understood by the diagram given below. Here Sachin is not changed but a new object is created with sachintendulkar. That is why string is known as immutable. 4)Why string objects are immutable in java? Because java uses the concept of string literal.Suppose there are 5 reference va riables,all referes to one object "sachin".If one reference variable changes the value of the object, it will be affected to all the reference variables. That i s why string objects are immutable in java. 5)String comparison in Java: We can compare two given strings on the basis of content and reference. It is used in authentication (by equals() method), sorting (by compareTo() metho d), reference matching (by == operator) etc. There are three ways to compare String objects: a)By equals() method b)By = = operator c)By compareTo() method a) By equals() method equals() method compares the original content of the string.It compares values o f string for equality. b) By == operator The = = operator compares references not values. c) By compareTo() method: compareTo() method compares values and returns an int which tells if the values compare less than, equal, or greater than. Suppose s1 and s2 are two string variables.If: s1 == s2 :0 s1 > s2 :positive value s1 < s2 :negative value 6)String Concatenation in Java: Concating strings form a new string i.e. the combination of multiple strings. There are two ways to concat string objects: a)By + (string concatenation) operator b)By concat() method a) By + (string concatenation) operator String concatenation operator is used to add strings.For Example: //Example of string concatenation operator
class Simple{ public static void main(String args[]){
String s="Sachin"+" Tendulkar"; System.out.println(s);//Sachin Tendulkar } } Output:Sachin Tendulkar The compiler transforms this to: String s=(new StringBuilder()).append("Sachin").append(" Tendulkar).toString();
String concatenation is implemented through the StringBuilder(or StringBuffer) c lass and its append method.String concatenation operator produces a new string b y appending the second operand onto the end of the first operand.The string conc atenation operator can concat not only string but primitive values also.For Exam ple: class Simple{ public static void main(String args[]){
String s=50+30+"Sachin"+40+40; System.out.println(s);//80Sachin4040 } } Output:80Sachin4040 Note:If either operand is a string, the resulting operation will be string conca tenation. If both operands are numbers, the operator will perform an addition. b) By concat() method concat() method concatenates the specified string to the end of current string. Syntax:public String concat(String another){} //<b><i>Example of concat(String) method</i></b>
class Simple{ public static void main(String args[]){
String s1="Sachin "; String s2="Tendulkar";
String s3=s1.concat(s2);
System.out.println(s3);//Sachin Tendulkar } } Output:Sachin Tendulkar 7)Substring in Java: A part of string is called substring. In other words, substring is a subset of a nother string. In case of substring startIndex starts from 0 and endIndex starts from 1 or star tIndex is inclusive and endIndex is exclusive. Example for substring: class Simple{ public static void main(String args[]){
String s="Sachin Tendulkar"; System.out.println(s.substring(9));//ndulkar System.out.println(s.substring(0,3));//Sac } } **8)String Methods in java: Ans)Method 1:toUpperCase() and toLowerCase() method class Simple{ public static void main(String args[]){
String s="Sachin"; System.out.println(s.toUpperCase());//SACHIN System.out.println(s.toLowerCase());//sachin System.out.println(s);//Sachin(no change in original) } } Output:SACHIN sachin Sachin Method 2:Trim method class Simple{ public static void main(String args[]){
String s=" Sachin "; System.out.println(s);// Sachin System.out.println(s.trim());//Sachin } } Output:Sachin Sachin Method 3:startsWith() and endsWith() method class Simple{ public static void main(String args[]){
String s="Sachin"; System.out.println(s.startsWith("Sa"));//true System.out.println(s.endsWith("n"));//true } } Output:true true Method 4:charAt() method class Simple{ public static void main(String args[]){
String s="Sachin"; System.out.println(s.charAt(0));//S System.out.println(s.charAt(3));//h } } Output:S h Method 5:length() method class Simple{ public static void main(String args[]){
String s="Sachin"; System.out.println(s.length());//6 } } Output:6 Method 6:intern() method A pool of strings, initially empty, is maintained privately by the class String. When the intern method is invoked, if the pool already contains a string equal t o this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool a nd a reference to this String object is returned. class Simple{ public static void main(String args[]){
String s=new String("Sachin"); String s2=s.intern(); System.out.println(s2);//Sachin } } Output:Sachin 9)StringBuffer class: The StringBuffer class is used to created mutable (modifiable) string. The Strin gBuffer class is same as String except it is mutable i.e. it can be changed. Note: StringBuffer class is thread-safe i.e. multiple threads cannot access it s imultaneously .So it is safe and will result in an order. 10)What is mutable string? A string that can be modified or changed is known as mutable string. StringBuffe r and StringBuilder classes are used for creating mutable string. 11)StringBuilder class: The StringBuilder class is used to create mutable (modifiable) string. The Strin gBuilder class is same as StringBuffer class except that it is non-synchronized. 12)Understanding toString() method: If you want to represent any object as a string, toString() method comes into ex istence. 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. depends on your implementation. Advantage of the toString() method: By overriding the toString() method of the Object class, we can return values of the object, so we don't need to write much code. 13)StringTokenizer in Java: The java.util.StringTokenizer class allows you to break a string into tokens. It is simple way to break string. It doesn't provide the facility to differentiate numbers, quoted strings, identi fiers etc. like StreamTokenizer class. Simple example of StringTokenizer class: Let's see the simple example of StringTokenizer class that tokenizes a string "m y name is khan" on the basis of whitespace. import java.util.StringTokenizer; public class Simple{ public static void main(String args[]){ StringTokenizer st = new StringTokenizer("my name is khan"," "); while (st.hasMoreTokens()) { System.out.println(st.nextToken()); } } } Output:my name is khan Note:StringTokenizer class is deprecated now. It is recommended to use split() m ethod of String class or regex (Regular Expression).