Java String

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 9

Java String:Predefined class of java

In java string is basically an object that represents sequence of char values. An array
of characters works same as Java string. For example:

String s=”hksdjfhdskg”;

Interview question:

What is string?

A string is a immutable (unchanged).A string is predefined class in java which is final.

Where is string is stored in memory?

It is stored in Heap memory under string constant pool.

What is base class of Java?

Object

Program:

String s1="Welcome";// string immutable its final


s1.concat("to class");

System.out.println(s1);//

Example:

char[] c= {'a','b','c','d','e'};
String s=new String(c);
System.out.println(s);
Example:
String s1=”welcome”;
String s2=”welcome”;

Each time you create a string literal, the JVM checks the "string constant pool" first. If
the string already exists in the pool, a reference to the pooled instance is returned. If
the string doesn't exist in the pool, a new string instance is created and placed in the
pool.
In the above example, only one object will be created. Firstly, JVM will not find any
string object with the value "Welcome" in string constant pool that is why it will
create a new object. After that it will find the string with the value "Welcome" in the
pool, it will not create a new object but will return the reference to the same
instance.

Program:

String s1="Welcome";// string immutable its final


String s2="to class";
//String s3=s1.concat(s2);
String s3=s1+s2;
System.out.println(s3);//Welcometo class
s1=s2;
System.out.println(s1);

Equals() Method:
Program:
String s1="Sachin";
String s2="Sachin";
String s3=new String("Sachin");
String s4="Saurav";
System.out.println(s1.equals(s2));//true
System.out.println(s1.equals(s3));//true
System.out.println(s1.equals(s4));//false

equalsIgnoreCase:
Program:
String s1="Sachin";
String s2="SACHIN";

System.out.println(s1.equals(s2));//false
System.out.println(s1.equalsIgnoreCase(s2));//true

By Using == operator :It Refers address of variable stored.

public static void main(String args[]){


String s1="Sachin";
String s2="Sachin";
String s3=new String("Sachin");
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 Using compareTo() method:

The String class 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.

Suppose s1 and s2 are two String objects. If:


o s1 == s2 : The method returns 0.
o s1 > s2 : The method returns a positive value.
o s1 < s2 : The method returns a negative value.

Program:
How it works is it ASCII based?

public static void main(String args[]){


String s1="Sachin";
String s2="Sachin";
String s3="Ratan";
System.out.println(s1.compareTo(s2));//0
System.out.println(s1.compareTo(s3));//1(because s1>s3)
System.out.println(s3.compareTo(s1));//-1(because s3 < s1 )
}

Substring in Java:
A part of String is called substring.
1. public String substring(int startIndex):
This method returns new String object containing the substring of the given
string from specified startIndex (inclusive). The method throws an
IndexOutOfBoundException when the startIndex is larger than the length of
String or less than zero.
2. public String substring(int startIndex, int endIndex):
This method returns new String object containing the substring of the given
string from specified startIndex to endIndex. The method throws an
IndexOutOfBoundException when the startIndex is less than zero or startIndex
is greater than endIndex or endIndex is greater than length of String.
3. startIndex: inclusive
4. endIndex: exclusive

Program:

String s="hello";
System.out.println(s.substring(0,2)); //returns he as a substring
Program:
public static void main(String args[]){
String s="SachinTendulkar";
System.out.println("Original String: " + s);
System.out.println("Substring starting from index 6: "
+s.substring(6));//Tendulkar
System.out.println("Substring starting from index 0 to 6: "+s.substring(0,6));
//Sachin
}

Using String.split() method:

public static void main(String args[])


{
String text= new String("Hello, My name is Sachin");
/* Splits the sentence by the delimeter passed as an argument */
String[] sentences = text.split("\\.");
System.out.println(Arrays.toString(sentences));

public static void main(String []args)


{
//String[] arg= {1,2,3,4,5,6,};
String s1="Hello class, welcome to java tutorial";
//String [] s2=s1.split(",");
//string[0]="Hello class"
//String[1]=" welcome to java tutorial"
//Strings3[0]="welcome"
//Strings3[1]="to"
//Strings3[2]="java"
//Strings3[3]="tutorial"

//System.out.println(s1[0]);
//System.out.println(s1[1]);
String [] s3=s1.split(" ");
//System.out.println(s3[0]);
//System.out.println(s3[1]);
//System.out.println(s3[2]);
//System.out.println(s3[3]);
//System.out.println(s3[4]);
System.out.println(s3[5]);

Java String trim() method:

public static void main(String ar[])


{
String s=" Sachin ";
System.out.println(s);// Sachin
System.out.println(s.trim());//Sachin

public static void main(String []args)


{
//String[] arg= {1,2,3,4,5,6,};
String s1=" Hello World ";
System.out.println(s1);
System.out.println(s1.trim());

}
Java String toUpperCase() and toLowerCase() method:

public static void main(String ar[])


{
String s="Sachin";
System.out.println(s.toUpperCase());//SACHIN
System.out.println(s.toLowerCase());//sachin
System.out.println(s);//Sachin(no change in original)

Java String charAt() Method:

public static void main(String ar[])


{
String s="Sachin";
System.out.println(s.charAt(0));//S
System.out.println(s.charAt(3));//h

Java String length() Method:

public static void main(String ar[])


{
String s="Sachin";
System.out.println(s.length());//6

Java String replace() Method:

public static void main(String ar[])


{
String s1="Java is a programming language. Java is a platform. Java is an Island.";
String replaceString=s1.replace("Java","Kava");//replaces all occurrences of "Java" to
"Kava"
System.out.println(replaceString);

}
StringBuffer:

Java StringBuffer class is used to create mutable (modifiable) String objects. The
StringBuffer class in Java is the same as String class except it is mutable i.e. it can be
changed.

String v/s StringBuffer:


String StringBuffer
StringBuffer is very similar to String class with only difference
String is immutable is that, it is mutable
After creating StringBuffer object, it can be
It means that, once new string literal is created, it cannot be altered ormodified, as and when required depending on the
changed for modification or altercation requirement
For every operation on String, a new String literal is For every operation on StringBuffer like append, insert,
createdinside String Constant Pool (SCP) reverse or replace same StringBuffer object is returned
StringBuffer objects created are stored inside heap memory
All string literals are stored inside String Constant Pool (SCP) like any Java objects
StringBuffer consumes very less memory as compared to
String consumes more memory; String;
Since it creates new string literal every-time inside String Since it doesn’t create any new object and instead returns
Constant Pool, after any concatenation operation same StringBuffer object after performing operations
Performance-wise, String is very slow when there are more Performance-wise, StringBuffer is very fast when there are
number of concatenation operation more number of append operation
We will see an example to understand this scenario We will see an example to understand this scenario

When to use String and StringBuffer ?


String:
 When there are not many modification on same string and it is going to remain constant over a
period of time, then String is preferred
 In addition, when using string provides thread-safety
StringBuffer:
 In a multi-threaded application, StringBuffer need to be preferred as it ensure thread-safety
 Though it will be slower when compared with StringBuilder but ensures data-consistency by not
allowing multiple threads to operate at the same time concurrently
 Because every time lock has to be acquired before any operation on StringBuffer object and only
after releasing the lock, 2ndthread can take charge

Program:
public static void main(String ar[])
{
StringBuffer s=new StringBuffer("Hello");
s.append(" World");
System.out.println(s);

Java StringBuilder Class:

Java StringBuilder class is used to create mutable (modifiable) String.

You might also like