How to create string object?
- Using String literal.
- Using new keyword.
- 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
- Why string objects are immutable in java?
- How many ways we can create the string object?
- Why java uses the concept of string literal?
- What is the basic difference between string, stringbuffer and stringbuilder object in java?
- How to create immutable class in java?
- What is the purpose of toString() method in java?
- Is string a keyword in java?
- Is string a primitive type or derived type?
- What is string constant pool in java?
- What are mutable and immutable objects in java?
- What is string intern in java?
- Can we call string class methods using string literals?