0% found this document useful (0 votes)
2 views

JAVA DAY 4

The document provides an overview of Java Strings, highlighting their immutability, creation methods, and comparison techniques. It explains the use of StringBuffer and StringBuilder for mutable strings, along with their constructors and differences. Additionally, it covers various string methods and their functionalities, including concatenation, substring extraction, and character manipulation.

Uploaded by

selene6141744
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

JAVA DAY 4

The document provides an overview of Java Strings, highlighting their immutability, creation methods, and comparison techniques. It explains the use of StringBuffer and StringBuilder for mutable strings, along with their constructors and differences. Additionally, it covers various string methods and their functionalities, including concatenation, substring extraction, and character manipulation.

Uploaded by

selene6141744
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

JAVA DAY 4

7.String

● String is basically an object that represents a sequence of char


values. An array of characters works same as Java string. String
class implements Serializable, Comparable, CharSequence.
Example:
char[] ch={'j','a','v','a','t','p','o','i','n','t'};
String s=new String(ch);
is same as:
String s="javatpoint";

CharSequence Interface
The CharSequence interface is used to represent the sequence of
characters.

● The Java String is immutable which means it cannot be


changed. Whenever we change any string, a new instance is
created.
● For mutable strings, you can use StringBuffer and StringBuilder
classes.
● String is an object that represents a sequence of characters. The
java. lang. String class is used to create a string object.

How to create a string object?


There are two ways to create String object:
● By string literal
● By new keyword
String Literal
● Java String literal is created by using double quotes.
● For Example:
String s="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.
● For example:
String s1="Welcome";
String s2="Welcome";//It doesn't create a new instance

Example Explanation
Only one object will be created. Firstly, JVM will not find any
string object with the value "Welcome" in the 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.
Uses
● To make more memory efficiently

new keyword

Example: String s=new String("Welcome”);

Note:
While using new keyword JVM will create a new string object in
normal (non-pool) heap memory, and the literal "Welcome" will be
placed in the string constant pool. The variable s will refer to the
object in a heap (non-pool).
Example
public class StringExample
{
public static void main(String args[])
{
String s1="java";// Java string literal
char ch[]={'s','t','r','i','n','g','s'};
String s2=new String(ch);//converting char array to string

String s3=new String("example");// Java string by new key


word.
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}
}

● Comparison methods

● Compare String in Java on the basis of content and reference.

● It is used in authentication (by equals() method), sorting (by


compareTo() method), reference matching (by == operator)
etc.
Three ways to compare String in Java:

1. By Using equals() Method


2. By Using == Operator
3. By compareTo() Method

equals() Method

The String class equals() method compares the original content of the
string. It compares values of string for equality. String class provides
the following two methods:

o public boolean equals(Object another) compares this string to


the specified object.
o public boolean equalsIgnoreCase(String another) compares
this string to another string, ignoring case.

Example

class Teststringcomparison1
{
public static void main(String args[])
{
String s1="Sachin";
String s2="Sachin";
String s3=new String("Sachin");
String s4="Saurav";
String s5="Java";
String s6="JAVA";

System.out.println(s1.equals(s2));//true
System.out.println(s1.equals(s3));//true
System.out.println(s1.equals(s4));//false
System.out.println(s5.equals(s6));//false
System.out.println(s5.equalsIgnoreCase(s6));//true
}
}

Using == operator

● The == operator compares references not values.

Example

class Teststringcomparison3
{
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 inst
ance)
System.out.println(s1==s3);//false(because s3 refers to instance c
reated in nonpool)
}
}

compareTo() method

The String class compareTo() method compares values


lexicographically and returns an integer value that describes if the first
string is less than, equal to or greater than the 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.

Example

class Teststringcomparison4{
public static void main(String args[]){
String s1="Java";
String s2="Java";
String s3="Programming";
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 )
}
}

● Java String class provides a lot of methods to perform


operations on strings such as compare(), concat(), equals(),
split(), length(), replace(), compareTo(), intern(), substring()
etc.

● String Methods

public class String_methods


{
public static void main(String[] args)
{
//concatenation
String s1="hello";
String s2=" its beautiful";
System.out.println(s1.concat(" world"));
System.out.println(s1+s2);
System.out.println(s1);

//substring
String s4="java is simple";
System.out.println(s4.substring(2));
System.out.println(s4.substring(0, 1));
System.out.println(s4.substring(0, 2));
System.out.println(s4.substring(0, 3));
System.out.println(s4.substring(1, 7));

//upper and lower case


String s5="hello";
String s6="Hello";
System.out.println(s5.toUpperCase());
System.out.println(s6.toLowerCase());

//trim()
String s7=" hello ";
System.out.println(s7.trim());
System.out.println(s7);

//starts and ends with


String s8=" hello ";
String s9="hello";
String s10="Hello";
System.out.println(s8.startsWith("he"));
System.out.println(s9.startsWith("he"));
System.out.println(s10.endsWith("io"));

//char at
String s11=" morning ";
String s12="Hello";
System.out.println(s11.charAt(4));
System.out.println(s12.charAt(1));

//length()
String s13=" hello ";
String s14="hello";
System.out.println(s13.length());
System.out.println(s14.length());

//value of
int a=10,b=20;
System.out.println(a+b);
String s=String.valueOf(a);
System.out.println(s+10);

//replace of
String s15="Java is a programming language.";
String rep=s15.replace("Java", "c");
System.out.println(rep);

//indexof
String s6="java is object oriented";
System.out.println(s6.indexOf('i'));
System.out.println(s6.lastIndexOf('i'));

//contains
String z="umbrella";
System.out.println(z.contains("rel"));

//intern
String s = new String("Hello World");
String s1 = new String("Hello World");
System.out.println(s1 == s); // prints false
String s2 = new String("Welcome to JavaTpoint").intern();
String s3 = new String("Welcome to JavaTpoint").intern();
System.out.println(s3 == s2); // prints true

}
}

StringBuffer Class

● 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.

Constructors of StringBuffer Class


● StringBuffer() : It creates an empty String buffer with the initial
capacity of 16.
● StringBuffer(String str): It creates a String buffer with the
specified string.
● StringBuffer(int capacity): It creates an empty String buffer
with the specified capacity as length.

Example

class StringBufferExample
{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer("Hello ");

//append
sb.append("Java");//now original string is changed
System.out.println(sb);

//insert
sb.insert(1,"Java");
System.out.println(sb);

//replace
sb.replace(1,3,"Java");
System.out.println(sb);

//delete
sb.delete(1,3);
System.out.println(sb);

//reverse
sb.reverse();
System.out.println(sb);

//capacity

StringBuffer sb1 = new StringBuffer();

//printing default capacity of string buffer

System.out.println("default capacity: " + sb1.capacity());


sb = new StringBuffer("A");

// printing the current capacity of the string buffer i.e. 16


+1

System.out.println("capacity: " + sb.capacity());

}
}

StringBuilder Class

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


The Java StringBuilder class is the same as the StringBuffer class
except that it is non-synchronized.

Constructors of StringBuilder Class


● StringBuilder (): It creates an empty String builder with the
initial capacity of 16.
● StringBuilder (String str): It creates a String builder with the
specified string.
● StringBuilder (int length): It creates an empty String buffer
with the specified capacity as length.

Example

class StringBuilderExample
{
public static void main(String args[])
{
StringBuilder sb=new StringBuilder("Hello ");
sb.append("Java");//now original string is changed
System.out.println(sb);
sb.insert(1,"Java");
System.out.println(sb);
sb.replace(1,3,"Java");
System.out.println(sb);
sb.delete(1,3);
System.out.println(sb);
sb.reverse();
System.out.println(sb);
}
}
Difference between String and StringBuffer

Difference between StringBuffer and StringBuilder

StringBuffer StringBuilder
StringBuffer is synchronised i.e. StringBuilder
thread safe. It means two threads is non-synchronized i.e. not thread
can't call the methods of safe. It means two threads can call
StringBuffer simultaneously the methods of StringBuilder
simultaneously.
StringBuffer is less efficient than StringBuilder is more efficient than
StringBuilder. StringBuffer.
StringBuffer was introduced in StringBuilder was introduced in
Java 1.0 Java 1.5

You might also like