Create a String object in Java Example

1. Introduction

In Java, strings are objects that represent sequences of characters. The String class in Java is used to create and manipulate strings. This tutorial will demonstrate different methods to create a String object in Java, highlighting the most commonly used techniques.

Key Points

- Strings can be created using string literals or by using the new keyword.

- String literals are managed in the string pool for memory efficiency.

- new String() creates a new object in memory each time it is used.

2. Program Steps

1. Create a string using a string literal.

2. Create a string using the new keyword.

3. Print both strings to verify their contents.

3. Code Program

public class StringCreationExample {
    public static void main(String[] args) {
        // Create a string using a string literal
        String stringLiteral = "Hello, Java!";
        // Create a string using the new keyword
        String stringObject = new String("Hello, Java!");
        // Print both strings
        System.out.println("String created using literal: " + stringLiteral);
        System.out.println("String created using new keyword: " + stringObject);
    }
}

Output:

String created using literal: Hello, Java!
String created using new keyword: Hello, Java!

Explanation:

1. String stringLiteral = "Hello, Java!": Creates a string using a string literal. This string is stored in the string pool.

2. String stringObject = new String("Hello, Java!"): Creates a new String object using the new keyword. This does not use the string pool but creates a new string object in the heap memory.

3. System.out.println("String created using literal: " + stringLiteral): Prints the string created using a literal.

4. System.out.println("String created using new keyword: " + stringObject): Prints the string created using the new keyword.


Comments