Create string object in Java

How to create string object?

  1. Using String literal.
  2. Using new keyword.
  3. Using character array.

1. Using String literal:

Syntax

String website = "w3schools.com";

Example

public class Main {
 
    public static void main(String[] args) {
        String website = "w3schools.com";
        System.out.println(website);
    }
}

Output

w3schools.com

2. Using new keyword:

Syntax

String website= new String("w3schools.com");

Example

public class Main {
 
    public static void main(String[] args) {
        String website = new String("w3schools.com");
        System.out.println(website);
    }
}

Output

w3schools.com

3. Using character array:

Syntax

char ch[]={ 'w','3','s','p','o','i','n','t','.','c','o','m'};
String website=new String(ch);

Example

public class Main {
 
    public static void main(String[] args) {
        char ch[]={ 'w','3','s','p','o','i','n','t','.','c','o','m'};
        String website=new String(ch);
        System.out.println(website);
    }
}

Output

w3schools.com

Java interview questions on String Handling