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

Java Strings

In Java, a String is an object that represents a sequence of characters and is immutable, meaning it cannot be changed once created. The String class provides various methods for string manipulation, while mutable strings can be created using StringBuffer and StringBuilder classes. Additionally, the CharSequence interface allows for the representation of character sequences, and there are important differences between String, StringBuffer, and StringBuilder regarding mutability and performance.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

Java Strings

In Java, a String is an object that represents a sequence of characters and is immutable, meaning it cannot be changed once created. The String class provides various methods for string manipulation, while mutable strings can be created using StringBuffer and StringBuilder classes. Additionally, the CharSequence interface allows for the representation of character sequences, and there are important differences between String, StringBuffer, and StringBuilder regarding mutability and performance.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

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:

1. char[] ch={'j','a','v','a','t','p','o','i','n','t'};
2. 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.lang.String class


implements Serializable, Comparable and CharSequence interfaces.

CharSequence Interface
The CharSequence interface is used to represent the sequence of characters.
String, StringBuffer and StringBuilder classes implement it. It means, we can create
strings in Java by using these three classes.
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.

We will discuss immutable string later. Let's first understand what String in Java is
and how to create the String object.

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
1. 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);
}}

Java String class methods


The java.lang.String class provides many useful methods to perform operations on
sequence of char values.

No. Method Description

1 char charAt(int index) It returns char value for the


particular index

2 int length() It returns string length

3 static String format(String format, It returns a formatted string.


Object... args)

4 static String format(Locale l, String It returns formatted string with


format, Object... args) given locale.

5 String substring(int beginIndex) It returns substring for given


begin index.
6 String substring(int beginIndex, int It returns substring for given
endIndex) begin index and end index.

7 boolean contains(CharSequence s) It returns true or false after


matching the sequence of char
value.

8 static String join(CharSequence It returns a joined string.


delimiter, CharSequence... elements)

9 static String join(CharSequence It returns a joined string.


delimiter, Iterable<? extends
CharSequence> elements)

10 boolean equals(Object another) It checks the equality of string


with the given object.

11 boolean isEmpty() It checks if string is empty.

12 String concat(String str) It concatenates the specified


string.

13 String replace(char old, char new) It replaces all occurrences of the


specified char value.

14 String replace(CharSequence old, It replaces all occurrences of the


CharSequence new) specified CharSequence.

15 static String equalsIgnoreCase(String It compares another string. It


another) doesn't check case.

16 String[] split(String regex) It returns a split string matching


regex.

17 String[] split(String regex, int limit) It returns a split string matching


regex and limit.
18 String intern() It returns an interned string.

19 int indexOf(int ch) It returns the specified char


value index.

20 int indexOf(int ch, int fromIndex) It returns the specified char


value index starting with given
index.

21 int indexOf(String substring) It returns the specified substring


index.

22 int indexOf(String substring, int It returns the specified substring


fromIndex) index starting with given index.

23 String toLowerCase() It returns a string in lowercase.

24 String toLowerCase(Locale l) It returns a string in lowercase


using specified locale.

25 String toUpperCase() It returns a string in uppercase.

26 String toUpperCase(Locale l) It returns a string in uppercase


using specified locale.

27 String trim() It removes beginning and


ending spaces of this string.

28 static String valueOf(int value) It converts given type into


string. It is an overloaded
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.

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

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

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:

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

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.

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 )

String Concatenation by concat() method


The String concat() method concatenates the specified string to the end of current
string. Syntax:

1. public String concat(String another)

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

TestStringConcatenation3.java

1. class TestStringConcatenation3{
2. public static void main(String args[]){
3. String s1="Sachin ";
4. String s2="Tendulkar";
5. String s3=s1.concat(s2);
6. System.out.println(s3);//Sachin Tendulkar
7. }
8. }

Java String charAt()


The Java String class charAt() method returns a char value at the given index
number.

The index number starts from 0 and goes to n-1, where n is the length of the string.
It returns StringIndexOutOfBoundsException, if the given index number is greater
than or equal to this string length or a negative number.

Syntax
1. public char charAt(int index)

The method accepts index as a parameter. The starting index is 0. It returns a


character at a specific index position in a string. It
throws StringIndexOutOfBoundsException if the index is a negative value or
greater than this string length.

CharSequence interface, located inside java.lang package.

Internal implementation
public char charAt(int index) {
if ((index < 0) || (index >= value.length)) {
throw new StringIndexOutOfBoundsException(index);
}
return value[index];
}

Java String charAt() Method Examples


Let's see Java program related to string in which we will use charAt() method that
perform some operation on the give string.

FileName: CharAtExample.java

public class CharAtExample{


public static void main(String args[]){
String name="javatpoint";
char ch=name.charAt(4);//returns the char value at the 4th index
System.out.println(ch);
}}
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 capacity) It creates an empty String buffer with the specified capacity as length.

Important methods of StringBuffer class


Modifier Method Description
and Type

public append(String s) It is used to append the specified string with this string.
synchronized The append() method is overloaded like append(char),
StringBuffer append(boolean), append(int), append(float),
append(double) etc.

public insert(int offset, It is used to insert the specified string with this string at
synchronized String s) the specified position. The insert() method is overloaded
StringBuffer like insert(int, char), insert(int, boolean), insert(int, int),
insert(int, float), insert(int, double) etc.

public replace(int It is used to replace the string from specified startIndex


synchronized startIndex, int and endIndex.
StringBuffer endIndex, String str)
public delete(int startIndex, It is used to delete the string from specified startIndex
synchronized int endIndex) and endIndex.
StringBuffer

public reverse() is used to reverse the string.


synchronized
StringBuffer

public int capacity() It is used to return the current capacity.

public void ensureCapacity(int It is used to ensure the capacity at least equal to the
minimumCapacity) given minimum.

public char charAt(int index) It is used to return the character at the specified position.

public int length() It is used to return the length of the string i.e. total
number of characters.

public String substring(int It is used to return the substring from the specified
beginIndex) beginIndex.

public String substring(int It is used to return the substring from the specified
beginIndex, int beginIndex and endIndex.
endIndex)

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

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

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

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

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 memory when StringBuffer is fast and consumes
we concatenate too many strings because every less memory when we concatenate t
time it creates new instance. strings.

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

4) String class is slower while performing StringBuffer class is faster while


concatenation operation. performing concatenation operation.

5) String class uses String constant pool. StringBuffer uses Heap memory
Difference between StringBuffer and
StringBuilder
Java provides three classes to represent a sequence of characters: String,
StringBuffer, and StringBuilder. The String class is an immutable class whereas
StringBuffer and StringBuilder classes are mutable. There are many differences
between StringBuffer and StringBuilder. The StringBuilder class is introduced since
JDK 1.5.

A list of differences between StringBuffer and StringBuilder is given below:


No. StringBuffer StringBuilder

1) StringBuffer is synchronized i.e. thread safe. StringBuilder is non-synchronized i.e. not


It means two threads can't call the methods thread safe. It means two threads can call
of StringBuffer simultaneously. the methods of StringBuilder
simultaneously.

2) StringBuffer is less efficient than StringBuilder is more efficient than


StringBuilder. StringBuffer.

3) StringBuffer was introduced in Java 1.0 StringBuilder was introduced in Java 1.5

Java StringBuilder Class


Java StringBuilder class is used to create mutable (modifiable) String. The Java
StringBuilder class is same as StringBuffer class except that it is non-synchronized. It
is available since JDK 1.5.

Important Constructors of StringBuilder class


Constructor Description
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 Builder with the specified capacity as length.

Important methods of StringBuilder class


Method Description

public StringBuilder It is used to append the specified string with this string. The append()
append(String s) method is overloaded like append(char), append(boolean),
append(int), append(float), append(double) etc.

public StringBuilder It is used to insert the specified string with this string at the specified
insert(int offset, String s) position. The insert() method is overloaded like insert(int, char),
insert(int, boolean), insert(int, int), insert(int, float), insert(int, double)
etc.

public StringBuilder It is used to replace the string from specified startIndex and endIndex.
replace(int startIndex, int
endIndex, String str)

public StringBuilder It is used to delete the string from specified startIndex and endIndex.
delete(int startIndex, int
endIndex)

public StringBuilder It is used to reverse the string.


reverse()

public int capacity() It is used to return the current capacity.

public void It is used to ensure the capacity at least equal to the given minimum.
ensureCapacity(int
minimumCapacity)
public char charAt(int index) It is used to return the character at the specified position.

public int length() It is used to return the length of the string i.e. total number of
characters.

public String substring(int It is used to return the substring from the specified beginIndex.
beginIndex)

public String substring(int It is used to return the substring from the specified beginIndex and
beginIndex, int endIndex) endIndex.

Java StringBuilder Examples


Let's see the examples of different methods of StringBuilder class.

1) StringBuilder append() method


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

StringBuilderExample.java

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

Output:

Hello Java

2) StringBuilder insert() method


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

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

Output:

HJavaello

3) StringBuilder replace() method


The StringBuilder replace() method replaces the given string from the specified
beginIndex and endIndex.

StringBuilderExample3.java

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

Output:

HJavalo

4) StringBuilder delete() method


The delete() method of StringBuilder class deletes the string from the specified
beginIndex to endIndex.

StringBuilderExample4.java

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

Output:

Hlo

5) StringBuilder reverse() method


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

StringBuilderExample5.java

class StringBuilderExample5{
public static void main(String args[]){
StringBuilder sb=new StringBuilder("Hello");
sb.reverse();
System.out.println(sb);//prints olleH
}
}

StringTokenizer in Java
1. StringTokenizer
2. Methods of StringTokenizer
3. Example of StringTokenizer

The java.util.StringTokenizer class allows you to break a String into tokens. It is


simple way to break a String. It is a legacy class of Java.

It doesn't provide the facility to differentiate numbers, quoted strings, identifiers etc.
like StreamTokenizer class. We will discuss about the StreamTokenizer class in I/O
chapter.

In the StringTokenizer class, the delimiters can be provided at the time of creation or
one by one to the tokens.
Constructors of the StringTokenizer Class
There are 3 constructors defined in the StringTokenizer class.

Constructor Description

StringTokenizer(String str) It creates StringTokenizer with specified string.

StringTokenizer(String str, It creates StringTokenizer with specified string and


String delim) delimiter.

StringTokenizer(String str, It creates StringTokenizer with specified string, delimiter


String delim, boolean and returnValue. If return value is true, delimiter characters
returnValue) are considered to be tokens. If it is false, delimiter
characters serve to separate tokens.

Methods of the StringTokenizer Class


The six useful methods of the StringTokenizer class are as follows:
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.

Example of StringTokenizer Class


Let's see an example of the StringTokenizer class that tokenizes a string "my name is
khan" on the basis of whitespace.
Simple.java

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

The above Java code, demonstrates the use of StringTokenizer class and its methods
hasMoreTokens() and nextToken().

Example of nextToken(String delim) method of the


StringTokenizer class
Test.java

import java.util.*;

public class Test {


public static void main(String[] args) {
StringTokenizer st = new StringTokenizer("my,name,is,khan");

// printing next token


System.out.println("Next token is : " + st.nextToken(","));
}
}

You might also like