Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
83 views

String in Java

1) In Java, a string is an object that represents a sequence of characters. It is implemented as a wrapper over a character array. 2) The Java String class provides many useful methods for string operations like compare(), concat(), equals(), split(), length(), replace(), etc. 3) Strings in Java are immutable, meaning that once created a String object cannot be changed. Any operation that would modify a String actually returns a new String.

Uploaded by

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

String in Java

1) In Java, a string is an object that represents a sequence of characters. It is implemented as a wrapper over a character array. 2) The Java String class provides many useful methods for string operations like compare(), concat(), equals(), split(), length(), replace(), etc. 3) Strings in Java are immutable, meaning that once created a String object cannot be changed. Any operation that would modify a String actually returns a new String.

Uploaded by

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

Java String

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

char[] ch={'j','a','v','a','t','p','o','i','n','t'};
String s=new String(ch);

is same as:

1. String s="javatpoint";

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.

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.

What is String in Java?

Generally, String is a sequence of characters. But in Java, 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:

1. By string literal
2. By new keyword

1) String Literal

Java String literal is created by using double quotes. For Example:

1. 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:

1. String s1="Welcome";
2. String s2="Welcome"; //It doesn't create a new instance
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.

Note: String objects are stored in a special memory area known as the "string constant pool".

Why Java uses the concept of String literal?

To make Java more memory efficient (because no new objects are created if it exists already in the
string constant pool).

2) 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 (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).

Java String Example

StringExample.java

public class StringExample {


public static void main(String args[]) {
String s1="java"; //creating string by 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"); //creating Java string by new keyword
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}
}

Output:

java
strings
example
The above code converts a char array into a String object. And displays the String objects s1, s2,
and s3 on console using println() method.

Immutable String in Java

A String is an unavoidable type of variable while writing any application program. String
references are used to store various attributes like username, password, etc. In Java, String objects
are immutable. Immutable simply means unmodifiable or unchangeable.

Once String object is created its data or state can't be changed but a new String object is created.

Let's try to understand the concept of immutability by the example given below:

Testimmutablestring.java

class Testimmutablestring{
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 objects
}
}

Output:

Sachin

Now it can be understood by the diagram given below. Here Sachin is not changed but a new
object is created with Sachin Tendulkar. That is why String is known as immutable.
As you can see in the above figure that two objects are created but s reference variable still refers
to "Sachin" not to "Sachin Tendulkar".

But if we explicitly assign it to the reference variable, it will refer to "Sachin Tendulkar" object.

For example:

Testimmutablestring1.java

class Testimmutablestring1{
public static void main(String args[]){
String s="Sachin";
s=s.concat(" Tendulkar");
System.out.println(s);
}
}

Output:

Sachin Tendulkar

In such a case, s points to the "Sachin Tendulkar". Please notice that still Sachin object is not
modified.

Why String objects are immutable in Java?

As Java uses the concept of String literal. Suppose there are 5 reference variables, all refer to one
object "Sachin". If one reference variable changes the value of the object, it will be affected by all
the reference variables. That is why String objects are immutable in Java.
Java String compare

We can compare String in Java based on content and reference.

It is used in authentication (by equals() method), sorting (by compareTo() method), reference
matching (by == operator) etc.

There are three ways to compare String in Java:

1. By Using equals() Method


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

1) By Using 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.

Teststringcomparison1.java

class Teststringcomparison1{
public static void main(String args[]){
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
}
}

Output:

true
true
false

In the above code, two strings are compared using equals() method of String class. And the result
is printed as boolean values, true or false.

Teststringcomparison2.java

class Teststringcomparison2{
public static void main(String args[]){
String s1="Sachin";
String s2="SACHIN";
System.out.println(s1.equals(s2)); //false
System.out.println(s1.equalsIgnoreCase(s2)); //true
}
}

Output:

false
true

In the above program, the methods of String class are used. The equals() method returns true if
String objects are matching and both strings are of same case. equalsIgnoreCase() returns true
regardless of cases of strings.

2) By Using == operator

The == operator compares references not values.

Teststringcomparison3.java

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 instance)
System.out.println(s1==s3); //false (because s3 refers to instance created in
nonpool)
}
}

Output:

true
false

3) String compare by compareTo() method

The above code demonstrates the use of == operator used for comparing two String objects.

3) 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.

Teststringcomparison4.java

class Teststringcomparison4{
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 )
}
}

Output:
0
1
-1

String Concatenation in Java

In Java, String concatenation forms a new String that is the combination of multiple strings. There
are two ways to concatenate strings in Java:

1. By + (String concatenation) operator


2. By concat() method

1) String Concatenation by + (String concatenation) operator

Java String concatenation operator (+) is used to add strings. For Example:

TestStringConcatenation1.java

class TestStringConcatenation1{
public static void main(String args[]){
String s="Sachin"+" Tendulkar";
System.out.println(s); //Sachin Tendulkar
}
}

Output:
Sachin Tendulkar

The Java compiler transforms above code to this:

1. String s=(new StringBuilder()).append("Sachin").append(" Tendulkar).toString();

In Java, String concatenation is implemented through the StringBuilder (or StringBuffer) class and
it's append method. String concatenation operator produces a new String by appending the second
operand onto the end of the first operand. The String concatenation operator can concatenate not
only String but primitive values also. For Example:

TestStringConcatenation2.java

class TestStringConcatenation2{
public static void main(String args[]){
String s=50+30+"Sachin"+40+40;
System.out.println(s); //80Sachin4040
}
}

Output:

80Sachin4040

Note: After a string literal, all the + will be treated as string concatenation operator.

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)

Let's see the example of String concat() method.

TestStringConcatenation3.java

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
}
}

Output:
Sachin Tendulkar

The above Java program, concatenates two String objects s1 and s2 using concat() method and
stores the result into s3 object.

Substring in Java

A part of String is called substring. In other words, substring is a subset of another String. Java
String class provides the built-in substring() method that extract a substring from the given string
by using the index values passed as an argument. In case of substring() method startIndex is
inclusive and endIndex is exclusive.

Suppose the string is "computer", then the substring will be com, compu, ter, etc.

Note: Index starts from 0.


You can get substring from the given String object by one of the two methods:

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.

In case of String:

o startIndex: inclusive
o endIndex: exclusive

Let's understand the startIndex and endIndex by the code given below.

1. String s="hello";
2. System.out.println(s.substring(0,2)); //returns he as a substring

In the above substring, 0 points the first letter and 2 points the second letter i.e., e (because end
index is exclusive).

Example of Java substring() method

TestSubstring.java

public class TestSubstring{


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
}
}
Output:

Original String: SachinTendulkar


Substring starting from index 6: Tendulkar
Substring starting from index 0 to 6: Sachin

The above Java programs, demonstrates variants of the substring() method of String class. The
startindex is inclusive and endindex is exclusive.

Java String Class Methods

The java.lang.String class provides a lot of built-in methods that are used to manipulate string in
Java. By the help of these methods, we can perform operations on String objects such as trimming,
concatenating, converting, comparing, replacing strings etc.

Java String is a powerful concept because everything is treated as a String if you submit any form
in window based, web based or mobile application.

Let's use some important methods of String class.

Java String toUpperCase() and toLowerCase() method

The Java String toUpperCase() method converts this String into uppercase letter and String
toLowerCase() method into lowercase letter.

Stringoperation1.java

public class Stringoperation1


{
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)
}
}

Output:

SACHIN
sachin
Sachin
Java String trim() method

The String class trim() method eliminates white spaces before and after the String.
Stringoperation2.java

public class Stringoperation2


{
public static void main(String ar[])
{
String s=” Sachin “;
System.out.println(s); // Sachin
System.out.println(s.trim()); //Sachin
}
}

Output:

Sachin
Sachin
Java String startsWith() and endsWith() method

The method startsWith() checks whether the String starts with the letters passed as arguments and
endsWith() method checks whether the String ends with the letters passed as arguments.

Stringoperation3.java

public class Stringoperation3


{
public static void main(String ar[])
{
String s=”Sachin”;
System.out.println(s.startsWith("Sa")); //true
System.out.println(s.endsWith(“n”)); //true
}
}

Output:

true
true
Java String charAt() Method

The String class charAt() method returns a character at specified index.

Stringoperation4.java

public class Stringoperation4


{
public static void main(String ar[])
{
String s=”Sachin”;
System.out.println(s.charAt(0)); //S
System.out.println(s.charAt(3)); //h
}
}

Output:

S
h
Java String length() Method

The String class length() method returns length of the specified String.

Stringoperation5.java

public class Stringoperation5


{
public static void main(String ar[])
{
String s=”Sachin”;
System.out.println(s.length()); //6
}
}

Output:

6
Java String valueOf() Method

The String class valueOf() method coverts given type such as int, long, float, double, boolean, char
and char array into String.

Stringoperation7.java

public class Stringoperation7


{
public static void main(String ar[])
{
int a=10;
String s=String.valueOf(a);
System.out.println(s+10);
}
}
Output:

1010
Java String replace() Method

The String class replace() method replaces all occurrence of first sequence of character with second
sequence of character.

Stringoperation8.java

public class Stringoperation8


{
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);
}
}

Output:

Kava is a programming language. Kava is a platform. Kava is an Island.

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

Note: Java StringBuffer class is thread-safe i.e. multiple threads cannot access it
simultaneously. So it is safe and will result in an order.

Important Constructors of StringBuffer Class

Constructor Description

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 It creates an empty String buffer with the specified capacity as
capacity) length.

What is a mutable String?

A String that can be modified or changed is known as mutable String. StringBuffer and
StringBuilder classes are used for creating mutable strings.

1) StringBuffer Class append() Method

The append() method concatenates the given argument with this String.

StringBufferExample.java

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); //prints Hello Java
}
}

Output:

Hello Java
2) StringBuffer insert() Method

The insert() method inserts the given String with this string at the given position.

StringBufferExample2.java

class StringBufferExample2{
public static void main(String args[]){
StringBuffer sb=new StringBuffer(“Hello “);
sb.insert(1,”Java”); //now original string is changed
System.out.println(sb); //prints HJavaello
}
}

Output:

HJavaello
3) StringBuffer replace() Method

The replace() method replaces the given String from the specified beginIndex and endIndex.
StringBufferExample3.java

class StringBufferExample3{
public static void main(String args[]){
StringBuffer sb=new StringBuffer(“Hello”);
sb.replace(1,3,”Java”);
System.out.println(sb); //prints HJavalo
}
}

Output:

HJavalo
4) StringBuffer delete() Method

The delete() method of the StringBuffer class deletes the String from the specified beginIndex to
endIndex.

StringBufferExample4.java

class StringBufferExample4{
public static void main(String args[]){
StringBuffer sb=new StringBuffer(“Hello”);
sb.delete(1,3);
System.out.println(sb); //prints Hlo
}
}

Output:

Hlo
5) StringBuffer reverse() Method

The reverse() method of the StringBuilder class reverses the current String.

StringBufferExample5.java

class StringBufferExample5{
public static void main(String args[]){
StringBuffer sb=new StringBuffer(“Hello”);
sb.reverse();
System.out.println(sb); //prints olleH
}
}

Output:
olleH
6) StringBuffer capacity() Method

The capacity() method of the StringBuffer class returns the current capacity of the buffer. The
default capacity of the buffer is 16. If the number of character increases from its current capacity,
it increases the capacity by (oldcapacity*2)+2. For example if your current capacity is 16, it will
be (16*2)+2=34.

StringBufferExample6.java

class StringBufferExample6{
public static void main(String args[]){
StringBuffer sb=new StringBuffer();
System.out.println(sb.capacity()); //default 16
sb.append(“Hello”);
System.out.println(sb.capacity()); //now 16
sb.append(“java is my favourite language”);
System.out.println(sb.capacity()); //now (16*2)+2=34 i.e (oldcapacity*2)+2
}
}

Output:

16
16
34
7) StringBuffer ensureCapacity() method

The ensureCapacity() method of the StringBuffer class ensures that the given capacity is the
minimum to the current capacity. If it is greater than the current capacity, it increases the capacity
by (oldcapacity*2)+2. For example if your current capacity is 16, it will be (16*2)+2=34.

StringBufferExample7.java

class StringBufferExample7{
public static void main(String args[]){
StringBuffer sb=new StringBuffer();
System.out.println(sb.capacity()); //default 16
sb.append(“Hello”);
System.out.println(sb.capacity()); //now 16
sb.append(“java is my favourite language”);
System.out.println(sb.capacity()); //now (16*2)+2=34 i.e (oldcapacity*2)+2
sb.ensureCapacity(10); //now no change
System.out.println(sb.capacity()); //now 34
sb.ensureCapacity(50); //now (34*2)+2
System.out.println(sb.capacity()); //now 70
}
}

Output:

16
16
34
34
70
Difference between String and StringBuffer

There are many differences between String and StringBuffer. A list of differences between String
and StringBuffer are given below:

No. String StringBuffer

1) The String class is immutable. The StringBuffer class is mutable.

2) String is slow and consumes more StringBuffer is fast and consumes less
memory when we concatenate too many memory when we concatenate t strings.
strings because every time it creates new
instance.

3) String class overrides the equals() StringBuffer class doesn't override the
method of Object class. So you can equals() method of Object class.
compare the contents of two strings by
equals() method.

4) String class is slower while performing StringBuffer class is faster while performing
concatenation operation. concatenation operation.

5) String class uses String constant pool. StringBuffer uses Heap memory
Java toString() Method

If you want to represent any object as a string, toString() method comes into existence.

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.

Advantage of Java 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.

Understanding problem without toString() method

Let's see the simple code that prints reference.

Student.java

class Student{
int rollno;
String name;
String 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,"Raj","lucknow");
Student s2=new Student(102,"Vijay","ghaziabad");

System.out.println(s1); //compiler writes here s1.toString()


System.out.println(s2); //compiler writes here s2.toString()
}
}

Output:

Student@1fee6fc
Student@1eed786

As you can see in the above example, printing s1 and s2 prints the hashcode values of the objects
but I want to print the values of these objects. Since Java compiler internally calls toString()
method, overriding this method will return the specified values. Let's understand it with the
example given below:

Example of Java toString() method

Let's see an example of toString() method.

Student.java

class Student{
int rollno;
String name;
String 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,"Raj","lucknow");
Student s2=new Student(102,"Vijay","ghaziabad");

System.out.println(s1); //compiler writes here s1.toString()


System.out.println(s2); //compiler writes here s2.toString()
}
}

Output:

101 Raj lucknow


102 Vijay ghaziabad

In the above program, Java compiler internally calls toString() method, overriding this method
will return the specified values of s1 and s2 objects of Student class.

You might also like