UNIT-5
Strings in Java
In Java, a String is an object that represents a sequence of characters. Java provides a robust
and flexible API for handling strings, allowing for various operations such
as concatenation, comparison, and manipulation. In this article, we will go through the Java
String concept in detail.
What are Strings in Java?
Strings are the type of objects that can store the character of values and in Java, every character
is stored in 16 bits i,e using UTF 16-bit encoding. A string acts the same as an array of characters
in Java.
Example:
String name = "Geeks";
String Example in Java
Below is an example of a String in Java:
Java
// Java Program to demonstrate
// String
public class StringExample {
// Main Function
public static void main(String args[])
{
String str = new String("example");
// creating Java string by new keyword
, // this statement create two object i.e
// first the object is created in heap
// memory area and second the object is
// created in String constant pool.
System.out.println(str);
}
}
Output
example
Ways of Creating a String
There are two ways to create a string in Java:
String Literal
Using new Keyword
Syntax:
<String_Type> <string_variable> = "<sequence_of_string>";
1. String literal
To make Java more memory efficient (because no new objects are created if it exists already in
the string constant pool).
Example:
String demoString = “GeeksforGeeks”;
2. Using new keyword
String s = new String(“Welcome”);
In such a 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 the heap (non-pool)
In the given example only one object will be created. Firstly JVM will not find any string object
with the value “Welcome” in the string constant pool, so 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.
Example:
String demoString = new String (“GeeksforGeeks”);
Interfaces and Classes in Strings in Java
CharBuffer: This class implements the CharSequence interface. This class is used to allow
character buffers to be used in place of CharSequences. An example of such usage is the
regular-expression package java.util.regex.
,String: It is a sequence of characters. In Java, objects of String are immutable which means a
constant and cannot be changed once created.
CharSequence Interface
CharSequence Interface is used for representing the sequence of Characters in Java.
Classes that are implemented using the CharSequence interface are mentioned below and
these provides much of functionality like substring, lastoccurence, first occurence, concatenate ,
toupper, tolower etc.
1. String
2. StringBuffer
3. StringBuilder
1. String
String is an immutable class which means a constant and cannot be changed once created and if
wish to change , we need to create an new object and even the functionality it provides like
toupper, tolower, etc all these return a new object , its not modify the original object. It is
automatically thread safe.
Syntax
String str= "geeks";
or
String str= new String("geeks")
2. StringBuffer
StringBuffer is a peer class of String, it is mutable in nature and it is thread safe class , we can
use it when we have multi threaded environment and shared object of string buffer i.e, used by
mutiple thread. As it is thread safe so there is extra overhead, so it is mainly used for
multithreaded program.
Syntax:
StringBuffer demoString = new StringBuffer("GeeksforGeeks");
3. StringBuilder
StringBuilder in Java represents an alternative to String and StringBuffer Class, as it creates a
mutable sequence of characters and it is not thread safe. It is used only within the thread , so
there is no extra overhead , so it is mainly used for single threaded program.
Syntax:
StringBuilder demoString = new StringBuilder();
demoString.append("GFG");
StringTokenizer
StringTokenizer class in Java is used to break a string into tokens.
Example:
, A StringTokenizer object internally maintains a current position within the string to be
tokenized. Some operations advance this current position past the characters processed. A
token is returned by taking a substring of the string that was used to create the StringTokenizer
object.
StringJoiner is a class in java.util package which is used to construct a sequence of
characters(strings) separated by a delimiter and optionally starting with a supplied prefix and
ending with a supplied suffix. Though this can also be done with the help of the StringBuilder
class to append a delimiter after each string, StringJoiner provides an easy way to do that
without much code to write.
Syntax:
public StringJoiner(CharSequence delimiter)
Above we saw we can create a string by String Literal.
String demoString =”Welcome”;
Here the JVM checks the String Constant Pool. If the string does not exist, then a new string
instance is created and placed in a pool. If the string exists, then it will not create a new object.
Rather, it will return the reference to the same instance. The cache that stores these string
instances is known as the String Constant pool or String Pool. In earlier versions of Java up to
JDK 6 String pool was located inside PermGen(Permanent Generation) space. But in JDK 7 it is
moved to the main heap area.
Immutable String in Java
In Java, string objects are immutable. Immutable simply means unmodifiable or unchangeable.
Once a string object is created its data or state can’t be changed but a new string object is
created.
Below is the implementation of the topic:
Java
Strings in Java
In Java, a String is an object that represents a sequence of characters. Java provides a robust
and flexible API for handling strings, allowing for various operations such
as concatenation, comparison, and manipulation. In this article, we will go through the Java
String concept in detail.
What are Strings in Java?
Strings are the type of objects that can store the character of values and in Java, every character
is stored in 16 bits i,e using UTF 16-bit encoding. A string acts the same as an array of characters
in Java.
Example:
String name = "Geeks";
String Example in Java
Below is an example of a String in Java:
Java
// Java Program to demonstrate
// String
public class StringExample {
// Main Function
public static void main(String args[])
{
String str = new String("example");
// creating Java string by new keyword
, // this statement create two object i.e
// first the object is created in heap
// memory area and second the object is
// created in String constant pool.
System.out.println(str);
}
}
Output
example
Ways of Creating a String
There are two ways to create a string in Java:
String Literal
Using new Keyword
Syntax:
<String_Type> <string_variable> = "<sequence_of_string>";
1. String literal
To make Java more memory efficient (because no new objects are created if it exists already in
the string constant pool).
Example:
String demoString = “GeeksforGeeks”;
2. Using new keyword
String s = new String(“Welcome”);
In such a 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 the heap (non-pool)
In the given example only one object will be created. Firstly JVM will not find any string object
with the value “Welcome” in the string constant pool, so 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.
Example:
String demoString = new String (“GeeksforGeeks”);
Interfaces and Classes in Strings in Java
CharBuffer: This class implements the CharSequence interface. This class is used to allow
character buffers to be used in place of CharSequences. An example of such usage is the
regular-expression package java.util.regex.
,String: It is a sequence of characters. In Java, objects of String are immutable which means a
constant and cannot be changed once created.
CharSequence Interface
CharSequence Interface is used for representing the sequence of Characters in Java.
Classes that are implemented using the CharSequence interface are mentioned below and
these provides much of functionality like substring, lastoccurence, first occurence, concatenate ,
toupper, tolower etc.
1. String
2. StringBuffer
3. StringBuilder
1. String
String is an immutable class which means a constant and cannot be changed once created and if
wish to change , we need to create an new object and even the functionality it provides like
toupper, tolower, etc all these return a new object , its not modify the original object. It is
automatically thread safe.
Syntax
String str= "geeks";
or
String str= new String("geeks")
2. StringBuffer
StringBuffer is a peer class of String, it is mutable in nature and it is thread safe class , we can
use it when we have multi threaded environment and shared object of string buffer i.e, used by
mutiple thread. As it is thread safe so there is extra overhead, so it is mainly used for
multithreaded program.
Syntax:
StringBuffer demoString = new StringBuffer("GeeksforGeeks");
3. StringBuilder
StringBuilder in Java represents an alternative to String and StringBuffer Class, as it creates a
mutable sequence of characters and it is not thread safe. It is used only within the thread , so
there is no extra overhead , so it is mainly used for single threaded program.
Syntax:
StringBuilder demoString = new StringBuilder();
demoString.append("GFG");
StringTokenizer
StringTokenizer class in Java is used to break a string into tokens.
Example:
, A StringTokenizer object internally maintains a current position within the string to be
tokenized. Some operations advance this current position past the characters processed. A
token is returned by taking a substring of the string that was used to create the StringTokenizer
object.
StringJoiner is a class in java.util package which is used to construct a sequence of
characters(strings) separated by a delimiter and optionally starting with a supplied prefix and
ending with a supplied suffix. Though this can also be done with the help of the StringBuilder
class to append a delimiter after each string, StringJoiner provides an easy way to do that
without much code to write.
Syntax:
public StringJoiner(CharSequence delimiter)
Above we saw we can create a string by String Literal.
String demoString =”Welcome”;
Here the JVM checks the String Constant Pool. If the string does not exist, then a new string
instance is created and placed in a pool. If the string exists, then it will not create a new object.
Rather, it will return the reference to the same instance. The cache that stores these string
instances is known as the String Constant pool or String Pool. In earlier versions of Java up to
JDK 6 String pool was located inside PermGen(Permanent Generation) space. But in JDK 7 it is
moved to the main heap area.
Immutable String in Java
In Java, string objects are immutable. Immutable simply means unmodifiable or unchangeable.
Once a string object is created its data or state can’t be changed but a new string object is
created.
Below is the implementation of the topic:
Java