Tuesday, December 25, 2012

33 Java String Interview Questions


1. What is immutable object in Java? Can you change values of an immutable object?
Ans. By immutable, we mean that the value stored in the object cannot be changed.

2. How to create a immutable object in Java? Does all property of immutable object needs to be final?
Ans. Follow the below steps:
1.  make class final so it can’t be inherited to make changes.
2. make every property private so nobody from outside can access them you can declare every property also as final, so kind of u r saying that every property is constant and you can not change it.
3. define parameterized constructor to set the value of various properties.
4. Only define getter methods so value can be accessed only.
5. no setter methods or any other method so no modification possible.

3. What is difference between String, StringBuffer and StringBuilder? When to use them?
Ans. The most important difference between String and StringBuffer/ StringBuilder in java is that String object is immutable whereas StringBuffer/ StringBuilder objects are mutable.

StringBuffer and StringBuilder have the same methods with one difference and that’s of synchronization. StringBuffer is synchronized (which means it is thread safe and hence you can use it when you implement threads for your methods) whereas StringBuilder is not synchronized (which implies it isn’t thread safe).

So, if you aren’t going to use threading then use the StringBuilder class as it’ll be more efficient than StringBuffer due to the absence of synchronization.

4. What are the benefits of immutable object?
Ans. At least 3 great benefits of immutable objects:
  • They simplify multithreaded programming.
  • They can be used as hashtables key.
  • They simplify state comparison.

5. What is String pool  in Java ?
Ans. String Pool is memory available along with object heap memory. It contains all String Literal created.

6. What does intern method do in String?
Ans. you can call intern() on a String object. This will put the String object in the pool if it is not already there, and return the reference to the pooled string.

7. What is special about String Class in Java?
8. Why String is popular HashMap key in Java,?
Ans. Being immutable String in Java caches its hashcode and do not calculate every time we call hashcode method of String, which makes it very fast as hashmap key to be used in hashmap in Java.  In short because String is immutable, no one can change its contents once created which guarantees hashCode of String to be same on multiple invocation.

9. Does String is thread-safe in Java?
Ans. Since String is immutable it can safely shared between many threads,
which is very important for multi-threaded programming and to avoid any synchronization issues in Java, Immutability also makes String instance thread-safe in Java, means you don't need to synchronize String operation externally

10. How to compare two String in Java?
Ans. str1.compareTo(str2).

11. How SubString works in Java?
Ans. it will create a separate string and if u will provide any reference to it, it will be available otherwise will be lost in heap and available to GC. 

12. Why char array is preferred over String for passwords?
Ans. Strings are immutable. That means once you've created the string, if another process can dump memory, there's no way (aside from reflection) you can get rid of the data before GC kicks in.
With an array, you can explicitly wipe the data after you're done with it: you can overwrite the array with anything you like, and the password won't be present anywhere in the system, even before garbage collection.
So yes, this is a security concern - but even using char[] only reduces the window of opportunity for an attacker, and it's only for this specific type of attack.

13. Give name of five very useful methods in String other than length(), equals(), toString(), concate() methods.

14. Why String class is final or immutable?
Ans. String has been widely used as parameter for many java classes e.g. for opening network connection you can pass hostname and port number as string , you can pass database URL as string for opening database connection, you can open any file in Java by passing name of file as argument to File I/O classes.

In case if String is not immutable, this would lead serious security threat, I mean some one can access to any file for which he has authorization and then can change the file name either deliberately or accidentally and gain access of those file. This is some time asked as Why Char array is better than String for Storing password in Java in interviews as well.

The absolutely most important reason that String is immutable is that it is used by the class loading mechanism, and thus has profound and fundamental security aspects.

15. Why String class is Final?
Ans. If String is not final, you can always extend it so that it is no longer immutable.

16. Is there any other class in Java beside String which is Immutable?
Ans. Yes. Wrapper classes.

17. How will you make a class emp immutable, it has some member variable, and another member variable say Salary, on which you don't have any control. In the sense the interviewer said the methods in salary class, can actually change the state of class salary?
Ans. While creating Object for Immutable class you should only provide the complete detail of mutable member, kind of saying before giving object to anybody completely make it mutable, if object contains reference of any other object than make the copy of original object and share the copy, it will ensure nothing is remaining which can be changed.

18. Can you write a function that will replace all tokens delimited by @ with a given String?
Ans.     
      str = “Hello @name@, where are you @name@?”
Ans : String tok[]=str.split(“@”)

19. What would you use to compare two String variables – the operator == or the method equals()?
Or
How is it possible for two String objects with identical values not to be equal under the == operator?
Ans. public class EqualsTest {

            public static void main(String[] args) {

                        String s1 = "abc";
                        String s2 = s1;
                        String s5 = "abc";
                        String s3 = new String("abc");
                        String s4 = new String("abc");
                        System.out.println("== comparison : " + (s1 == s5));
                        System.out.println("== comparison : " + (s1 == s2));
                        System.out.println("Using equals method : " + s1.equals(s2));
                        System.out.println("== comparison : " + s3 == s4);
                        System.out.println("Using equals method : " + s3.equals(s4));
            }
}

20. How to convert String to Number in java program?
Ans. The valueOf() function of Integer class is is used to convert string to Number. Here is the code example:
String numString = “1000″;
int id=Integer.valueOf(numString).intValue();

21. What is difference between String and StringTokenizer?
Ans. A StringTokenizer is utility class used to break up string.
For one thing, StringTokenizer returns one substring at a time whereas the split method returns an array of substrings. Best to use String's split(...) method. The StringTokenizer class is a legacy class. StringTokenizer can split strings based on single characters, split() takes regular expressions.

22. Is it possible to extend the java.lang.String class?
Ans. No

23. Is String a Wrapper Class or not?
Ans. A wrapper class in Java is one of those eight classes that wrap a (=one) primitive value. String wraps a char[] so according to this it is not a (primitive) wrapper class.
Furthermore, String is not designed to wrap or decorate a character array. String has been designed to model a string, a character sequence and the current implementation uses an internal char[]. But Sun could also have chosen to use a byte[] a long with a character encoding hint, a collection or something native. That doesn't matter.
That's different for the primitive wrappers: they have been designed only to wrap a primitive, to adapt a java primitive to java.lang.Object.

24. How many objects are in the memory after the execution of following code segment?
Ans. String str1 = “ABC”;
String str2 = “XYZ”;
String str1 = str1 + str2;
Ans. 0

25. What will trim () method of String class do?

26. What is the possible runtime exception thrown by substring() method?
Ans. ArrayOutofBoundException.

27. In Java, you can create a String object as below :
String str = “abc”; &
String str = new String(“abc”);
Why can’t a button object be created as : Button bt = “abc”?
Why is it compulsory to create a button object as:
Button bt = new Button(“abc”);
Why this is not compulsory in String’s case?
Ans. It is because "abc" is a literal string (something slightly different than a String object, by-the-way) and bt1 is a Button object. The only object in Java that can be assigned a literal String is java.lang.String

28. How to make any class Immutable?
Ans.
 Follow the below steps:
1.  make class final so it can’t be inherited to make changes.
2. make every property private so nobody from outside can access them you can declare every property also as final, so kind of u r saying that every property is constant and you can not change it.
3. define parameterized constructor to set the value of various properties.
4. Only define getter methods so value can be accessed only.
5. no setter methods or any other method so no modification possible.

29. == Vs equals() ?
Ans. It is important to understand that the equals( ) method and the == operator perform two different operations. As just explained, the equals( ) method compares the characters inside a String object. The == operator compares two object references to see whether they refer to the same instance. The following program shows how two different String objects can contain the same characters, but references to these objects will not compare as equal:

30. What is the difference between creating String as new() and literal?
Ans. When we create string with new() Operator, it’s created in heap and not added into string pool while String created using literal are created in String pool itself which exists in PermGen area of heap.

String s = new String("Test");

does not  put the object in String pool , we need to call String.intern() method which is used to put  them into String pool explicitly. its only when you create String object as String literal e.g. String s = "Test" Java automatically put that into String pool.

31. What will happen if beginIndex is equal to length in SubString(int beginIndex)

32. Can we say String is a character array?
Ans. No.

33. Why new String() is not added into constant String pool?
Ans.

No comments: