DEV Community

S Sarumathi
S Sarumathi

Posted on

String In Java

  • In Java, a String is an object used to store a sequence of characters.

  • A String in Java is a predefined class used to store text data or a collection of characters.

  • Java treats every text value inside double quotes (" ") as a String.

  • Java Strings are immutable, which improves security and performance

  • Without String, handling text data in programs becomes difficult.

Why String is Used:

String is mainly used to store:

  • Names

  • Messages

  • Email IDs

  • Addresses

  • Passwords

  • Sentences

Two way of creating String:

1. Using String Literal:

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

Explanation:

  • String → datatype/class

  • name → variable name

  • "Java" → string value

This is the most commonly used method.

Java stores this inside the String Constant Pool.

2. Using new Keyword:

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

Explanation:

  • Creates a new String object in heap memory

  • Even if "Java" already exists, a new object is created

Program:

public class Main {

    public static void main(String[] args) {

        String s1 = "Hello";

        String s2 = new String("World");

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

Output:

Top comments (0)