Thursday, February 7, 2019

Some Useful Java Programs for Technical Interview Part 2

Q6 : Why string is immutable or final in java ?

Answer
Answer : 
String objects are cached in string pool and shared between multiple thread, So it will lead to risk of value changed by one thread will affect value of other thread.

Example :

// find "abc" in string pool or create new object.

String str = "abc";

//It is available in string pool, This will point the same value in String pool.

String str1 = "abc";

// find  "abcxyz" in string pool or create new object.

str = str + "xyz";

// Now str is pointing only "abcxyz" in string pool and str1 is pointing "abc".


Q7 : Difference between name.equals("Syntaxios") and "Syntaxios".equals(name) ?

Answer
Answer : 
name.equals("Syntaxios") = compare unknown value(that means 'name') with known value (that means 'Syntaxios') and "Syntaxios".equals(name) = compare known value (that is "Syntaxios") with the unknown value (that is 'name') and it is null safe, This is used to avoid java.lang.NullPointerException.

Q8 : How to convert string to char [] array and char [] array to string ?

Answer
Answer : 
String str = "Syntaxios";

char []CharArray = str.toCharArray();

String strfromCharArray = String.valueOf(CharArray);

String.toCharArray(); // string to char[]

String.valueOf(char[]Data); // char[] to string


Q9 : Can we write try without catch ?

Answer
Answer : 
Yes, we can write try without catch, But we must write finally.
try{
        }
finally{
             }

Q10 : What is finally Block ?

Answer
Answer : 
Finally Block used to close resources used in try. Finally Block will be executed even If exception occurs try block. Finally Block will be executed even you write return variable from try block. Finally block will not be executed when System.exit(exitcode) executed in try block.

Example : 

try{
      int a = 1/0; // finally will be execute
      return a;
      System.exit(0); // finally will not execute
}    
    finally{
                System.out.println("Finally Block");
}

, ,

No comments:

Post a Comment