Monday, 22 July 2019

Interview Qns - Core java

Output please

public class Test123 {

static {
System.out.println("first static block");
}
static {
System.out.println("Second static block");
}

public static void main(String[] args) {
System.out.println("Main Method");
Test123 t = new Test123();
}

Test123() {
System.out.println("COnstructor");
}

}


Output:
first static block
Second static block
Main Method
COnstructor



Yes, we can write n number of static blocks 
Main method executes after static blocks
--------------------------------


Can we write Throwable in Catch block??

public void doNotCatchThrowable() {
try {
// do something
} catch (Throwable t) {
// don't do this!
}
}

Throwable is the superclass of all exceptions and errors. You can use it in a catch clause, but you should never do it!

If you use Throwable in a catch clause, it will not only catch all exceptions; it will also catch all errors. Errors are thrown by the JVM to indicate serious problems that are not intended to be handled by an application. Typical examples for that are the OutOfMemoryError or the StackOverflowError. Both are caused by situations that are outside of the control of the application and can’t be handled.

So, better don’t catch a Throwable unless you’re absolutely sure that you’re in an exceptional situation in which you’re able or required to handle an error.

-----------------------------------
The task is to write a program to generate the largest number possible using these digits.
Input : arr[] = {8, 6, 0, 4, 6, 4, 2, 7}
Output : Largest number: 87664420


static int findMaxNum(int arr[])
{
    // sort the given array in
    // ascending order and then
    // traverse into descending
    Arrays.sort(arr);
   
    int num = arr[0];
    int n = arr.length;
   
    // generate the number
    for(int i = n - 1; i >= 0; i--)
    {
        num = num * 10 + arr[i];
    }
   
    return num;
}
--------------------------------------
Checked: are the exceptions that are checked at compile time. If some code within a method throws a checked exception, then the method must either handle the exception or it must specify the exception using throws keyword.
FileReader thows FileNotFoundException is a subclass of IOException - hence am throwing


import java.io.*;

class Main {
    public static void main(String[] args) throws IOException {
        FileReader file = new FileReader("C:\\test\\a.txt");
        BufferedReader fileInput = new BufferedReader(file);
       
        // Print first 3 lines of file "C:\test\a.txt"
        for (int counter = 0; counter < 3; counter++)
            System.out.println(fileInput.readLine());
       
        fileInput.close();
    }
}

Ex:
ClassNotFoundException,
IOException,
SQLException


Unchecked: are the exceptions that are not checked at compiled time
Ex:
NullPointerException
ArithmeticException,
ArrayStoreException,
ClassCastException
IndexOutofbounds
---------------------------------------

Inheritance - Class casting -  Parent to Child and Child to parent


public class Parent {

public void m1() {
System.out.println("parent method");
}

}

public class Child1 extends Parent {

public void m1() {
System.out.println("Child1 method");
}

public static void main(String[] args) {
Parent p = new Parent();
p.m1();

Child1 c = new Child1();
c.m1();

Parent p1 = new Child1();
p1.m1();

Child1 cer = (Child1) p;// RuntimeError : java.lang.ClassCastException:
// javaProg.Parent cannot be cast
// to
// javaProg.Child1

Child1 cerr1 = (Child1) new Parent();// Runtime error :
// java.lang.ClassCastException: javaProg.Parent cannot be
// cast to javaProg.Child1
}
}

output:
parent method
Child1 method

Child1 method

Note - Only Child to parent casting is possible, Rest all Runtime Exception
--------------------------------------------------
Remove duplicates from array

// NOTE : SORTED ARRAY
public static int removeDuplicateElements(int arr[], int n){
        if (n==0 || n==1){
            return n;
        }
        int[] temp = new int[n]; // lets use temp array
        int j = 0;
        for (int i=0; i<n-1; i++){
            if (arr[i] != arr[i+1]){
                temp[j++] = arr[i];
            }
         }
        temp[j++] = arr[n-1]; // ADD LAST ITEM TO TEMP ARRAY
 
        // Changing original array
        for (int i=0; i<j; i++){
            arr[i] = temp[i];
        }
        return j;
    }
---------------------------------------------------
how to make thread safe

Static methods are marked as synchronized just like instance methods using the synchronized keyword. Here is a Java synchronized static method example:

  public static synchronized void add(int value){
      count += value;
  }
Also here the synchronized keyword tells Java that the method is synchronized.

Synchronized static methods are synchronized on the class object of the class the synchronized static method belongs to. Since only one class object exists in the Java VM per class, only one thread can execute inside a static synchronized method in the same class.


If the static synchronized methods are located in different classes, then one thread can execute inside the static synchronized methods of each class. One thread per class regardless of which static synchronized method it calls.
--------------------------------------
public vs protected

The protected specifier allows access by all subclasses of the class in a program, whatever package they reside in, as well as to other code in the same package. The default specifier allows access by other code in the same package, but not by code that is in subclasses residing in different packages

----------------------------------------

Guess the out put of below prog


try{
System.exit(-1);
System.out.println("in try");
}
catch(Exception ex){
System.out.println("in Exception block");
}

output : Nothing - as program exits then and there



Java System exit() Method
The exit() method of System class terminates the current Java virtual machine running on system. This method takes status code as an argument.


System.exit(0) or EXIT_SUCCESS;  ---> indicates Successful termination
System.exit(1) or EXIT_FAILURE;  ---> indicates unsuccessful termination with Exception
System.exit(-1) or EXIT_ERROR;   ---> indicates Unsuccessful termination


No comments:

Post a Comment