DEV Community

PRIYA K
PRIYA K

Posted on

String in Java

In Java, String is a class used to store a sequence of characters (text).
Example:

String name = "Priya";
Enter fullscreen mode Exit fullscreen mode

Here "Priya" is a string.

A string can store:
words
sentences
symbols
characters
So, String means text data in Java.

Two ways of creating String
1. Using string literal

String s1 = "Hello";
Enter fullscreen mode Exit fullscreen mode

Most common way.
Java stores it in the string pool.
Memory efficient.

Example

public class Test {
    public static void main(String[] args) {

        String a = "Java";
        String b = "Java";

        System.out.println(a == b);
    }
}
Enter fullscreen mode Exit fullscreen mode

Output:
true

Because both a and b point to the same object in the String pool.
Enter fullscreen mode Exit fullscreen mode

String Pool
Java stores string literals in a special memory area called the String Constant Pool.

2. Using new keyword

String s2 = new String("Hello");
Enter fullscreen mode Exit fullscreen mode

Creates a new object explicitly.
Stored in heap memory.

Example

public class Demo {
    public static void main(String[] args) {

        String s1 = new String("Java");
        String s2 = new String("Java");

        System.out.println(s1);
        System.out.println(s2);

        System.out.println(s1 == s2);
        System.out.println(s1.equals(s2));
    }
}
Enter fullscreen mode Exit fullscreen mode

Output
Java
Java
false
true

new keyword creates a new object
Object is created in heap memory
Even if "Java" already exists, Java creates another new object
Enter fullscreen mode Exit fullscreen mode

Same for:

String s2 = new String("Java");
Enter fullscreen mode Exit fullscreen mode

So s1 and s2 are different objects.

Why s1 == s2 is false

System.out.println(s1 == s2);
Enter fullscreen mode Exit fullscreen mode

Output:
false

== compares memory address/reference
s1 and s2 are different objects in memory
Enter fullscreen mode Exit fullscreen mode

Why s1.equals(s2) is true

System.out.println(s1.equals(s2));
Enter fullscreen mode Exit fullscreen mode

Output:
true

equals() compares actual content
Both strings contain "Java"
Enter fullscreen mode Exit fullscreen mode

Memory Representation

    String s1 = new String("Java");
    String s2 = new String("Java");
Enter fullscreen mode Exit fullscreen mode

Heap Memory
s1 ---> "Java" (Object 1)

s2 ---> "Java" (Object 2)
Two separate objects are created.

Difference
String Literal Using new
String s = "abc"; String s = new String("abc");
Stored in string pool Stored in heap
Reuses existing object Creates new object
Memory efficient Creates separate object

Why strings are immutable
Immutable means: once created, the value cannot be changed.

Example:

String s = "Hello";
s.concat(" World");
System.out.println(s);
Enter fullscreen mode Exit fullscreen mode

Output:
Hello

Because concat() creates a new string, old one stays same.

Reason why Java made String immutable
Security
String is used in passwords, file paths, URLs.
If mutable, values could be changed unexpectedly.
Memory saving
String pool can safely share objects.
Thread safety
Multiple threads can use the same string safely.
Performance
Hashcode caching and reuse are easier.

example

String s = "abc";
s = s + "d";
Enter fullscreen mode Exit fullscreen mode

"abc" remains unchanged.
New object "abcd" is created.
s now points to new object.

So String is immutable because Java protects data and improves memory efficiency.

In Java, String belongs to the java.lang package.
Compact Strings (compact1, compact2, compact3)

In newer Java versions, String internally stores characters in a memory-saving way. This is called Compact Strings. It means Java stores simple English text using less memory.

Example 1 (compact1)

String s1 = "hello";
Enter fullscreen mode Exit fullscreen mode

Contains only English letters.
Java stores it efficiently (1 byte per character internally).

Example 2 (compact2)

String s2 = "java";
Enter fullscreen mode Exit fullscreen mode

Also only English letters.
Stored in compact form.

Example 3 (compact3)

String s3 = "தமிழ்";
Enter fullscreen mode Exit fullscreen mode

Contains Tamil characters.
Java cannot use compact Latin storage here.
It uses more bytes internally.

Why Java uses compact strings?
saves memory
improves performance
automatic (programmer does not control it)

So, Compact String is an internal optimization of java.lang.String

java.lang.Object
Object is the parent class of all classes in Java.
Every class automatically inherits from Object.
So String also comes from Object.

Object → String

That means:
String is a child class of Object.

java.lang.String
This is the full package name.
package → java.lang
class → String

So:
String s = "Hello";

actually means:

java.lang.String s = "Hello";
Enter fullscreen mode Exit fullscreen mode

All Implemented Interfaces
Serializable, CharSequence, Comparable
This means String implements these interfaces.

Serializable
A string object can be converted into bytes and saved/transferred.

Example:
save object to file
send through network

CharSequence
String is a sequence of characters.

Example:
String name = "Priya";

Characters:
P r i y a
So String stores characters in order.

Comparable
String objects can be compared.

Example:
String a = "apple";
String b = "banana";
System.out.println(a.compareTo(b));

Java compares alphabetically.

java.lang.Object
        ↑
   java.lang.String
Enter fullscreen mode Exit fullscreen mode

String inherits from Object and implements:

String is a class in java.lang, child of Object, and it can:
store characters
compare strings
be saved/transferred as data

public final class String
Enter fullscreen mode Exit fullscreen mode

public → String can be used anywhere in Java.
final → String class cannot be inherited (you cannot extend it).
class String → String is a predefined class in Java.

extends Object
String is a child class of Object.
In Java, every class indirectly comes from Object.

So:
Object → String
implements Serializable, Comparable, CharSequence

This means String implements these interfaces:
Serializable
String objects can be saved to a file or sent over a network.

Comparable
Strings can be compared.

Example:

String a = "apple";
String b = "banana";
System.out.println(a.compareTo(b));
Enter fullscreen mode Exit fullscreen mode

CharSequence
String is a sequence of characters.
Example:

String s = "abc";
Enter fullscreen mode Exit fullscreen mode

contains characters:
a b c
“The String class represents character strings”
It means:
String is used to store text.

Example:

String name = "Priya";
Enter fullscreen mode Exit fullscreen mode

Here "Priya" is a string.

“All string literals … are instances of this class”
A string literal means text inside quotes:

"abc"
"hello"
"java"
These are all objects of String.
Example:

String str = "abc";
Enter fullscreen mode Exit fullscreen mode

Java automatically creates a String object.
“Strings are constant; their values cannot be changed”
This means String is immutable.
Once created, its value cannot change.
Example:

String s = "hello";
s = s + " world";
Enter fullscreen mode Exit fullscreen mode

This does not change the old object.
Java creates a new string object "hello world".

“String buffers support mutable strings”
If you want to change string content without creating many new objects, Java provides:
StringBuffer
StringBuilder
These are mutable (changeable).

Example

String str = "abc";
Enter fullscreen mode Exit fullscreen mode

Java directly creates a string object with "abc".

char data[] = {'a', 'b', 'c'};
String str = new String(data);
Enter fullscreen mode Exit fullscreen mode

character array is created:
{'a', 'b', 'c'}
That array is passed to String constructor.
It becomes "abc".

Both produce the same output:
abc

String stores text.
It is a class in java.lang.
It is immutable (cannot change after creation).
It inherits from Object.
It implements interfaces like Serializable, Comparable, and CharSequence.
"abc" and new String(data) both create string objects.

Examples of using String
Example 1

System.out.println("abc");
Enter fullscreen mode Exit fullscreen mode

Prints the string directly.

Output:
abc

Example 2

String cde = "cde";
System.out.println("abc" + cde);
Enter fullscreen mode Exit fullscreen mode

"abc" and "cde" are joined using +.

Output:
abccde

  • joins two strings. This is called string concatenation.

Example 3

String c = "abc".substring(2,3);
substring(start, end)
start index = 2
end index = 3 (excluded)
Enter fullscreen mode Exit fullscreen mode

String "abc" index:
a b c
0 1 2

So:

"abc".substring(2,3)
Enter fullscreen mode Exit fullscreen mode

takes character at index 2 → "c"

Output:
c

Example 4

String d = cde.substring(1,2);
cde = "cde"
Enter fullscreen mode Exit fullscreen mode

Index:
c d e
0 1 2
substring(1,2) → "d"

Output:
d

String methods
String class has many methods.
It can:
examine characters
compare strings
search text
extract substring
convert uppercase/lowercase

Example:

String name = "Priya";
System.out.println(name.length());
System.out.println(name.toUpperCase());
System.out.println(name.toLowerCase());
Enter fullscreen mode Exit fullscreen mode

Output:
5
PRIYA
priya

+ operator support
Java gives special support for:

String a = "Hello";
String b = "World";
System.out.println(a + b);
Enter fullscreen mode Exit fullscreen mode

Output:
HelloWorld

Internally Java converts this to:

StringBuilder sb = new StringBuilder();
sb.append(a);
sb.append(b);
Enter fullscreen mode Exit fullscreen mode

So + uses:
StringBuilder
or StringBuffer

Object to String conversion
Any object can be converted to string using:

toString()

Example:

Integer num = 10;
System.out.println(num.toString());
Enter fullscreen mode Exit fullscreen mode

Output:
10
Because every class inherits from Object.

NullPointerException
If you pass null to some String methods, Java may throw:
Example:

String s = null;
System.out.println(s.length());
Enter fullscreen mode Exit fullscreen mode

Error:
NullPointerException
Because s points to nothing.

UTF-16 format
Java stores strings internally in UTF-16.
That means it supports many world languages:
English
Tamil
Hindi
Chinese

Example:

String s = "தமிழ்";
Enter fullscreen mode Exit fullscreen mode

This works because Java uses Unicode.

Index values in String
Each character has an index.
Example:

String word = "java";
Enter fullscreen mode Exit fullscreen mode

Indexes:
j a v a
0 1 2 3
You can access characters using:

word.charAt(2)
Enter fullscreen mode Exit fullscreen mode

Output:
v

Unicode supplementary characters
Some special symbols/emojis need 2 positions.
Example:
String emoji = "😊";
Though it looks like 1 symbol, internally UTF-16 may use 2 char positions.

String in Java:
stores text
supports concatenation with +
supports substring
supports searching/comparing
uses UTF-16 Unicode
immutable
supports many methods like:
length()
charAt()
substring()
toUpperCase()
toLowerCase()

Top comments (0)