1) What is String in Java?
String in Java is sequence of characters.
2) Is String a keyword in Java?
No, String is not a keyword in Java. It is final class in Java
3) In how many ways String object can be created in Java?
There are two ways we can create string object in Java. First method is using new operator and object created by this method is stored in Heap memory. Second Method is using string literal and object created by this method is stored in string concept pool(SCP).
String obj = new String("ritesh"); // using new operator
String name = "ritesh"; // using literal
4) What is string constant pool(SCP)?
String constant pool is memory space inside Heap memory and it is used to store string literal. It is immutable.
5) What is immutable object?
Once we create object we can not make any change in object and if we try to make changes , a new object is created. It is called immutable object. Let's understand it with string class object since string is immutable.
String obj = new String("ritesh");
System.out.println(obj) // output = ritesh
String newObj = obj.concat("ranjan")
System.out.println(obj) // output = ritesh
System.out.println(newObj) // output = riteshranjan
6) What is difference between String, String buffer and String Builder?
1. String is immutable class in Java whereas both String Buffer and String Builder are mutable.
2. String is stored in both Heap memory space and SCP whereas String Buffer and String Builder are stored in Heap memory space only.
3. String object is created using "new" operator and using string literals but both String Buffer and String Builder object are created using 'new' operator.
4. String and String Buffer are thread safe but String Builder is not thread safe.
5. String class override .equals() method of Object class for content comparison but String Buffer and String Builder don't override .equals() method.
7) What is difference between .equals() method and '==' operator?
Both .equals() method of Object class and "==" operator are used for address comparison whereas .equals() method of String class override .equals() method of Object class for content comparison.
8) How many object will be created in following case?
String s1 = new String("ritesh");
String s2 = new String("ritesh");
String s3 = "ritesh";
String s4 = "ritesh";
Three object will be created in this case. Two object in Heap memory and one is SCP.
8) What are different constructors of String class?
0 comments:
Post a Comment