Skip to main content

Amazing Facts About java

Exceptions:- 


 1) One catch with many Exception(I am talking about java 7 special feature) do not allow to keep same type (i.e from same hierarchy ) in one catch with piped symbols. catch (FileNotFoundException | IOException e)

 2) It is not mandatory to catch or handle unchecked exception, Following method we can call with try block easily:-

public static void doSomething() throws NullPointerException{


 }

 3) You can not override methods with broader exception , For example super class methods throws FileNotFoundException then your sub class can not override same method changing the exception to IOException.

4) You can not assign values to exception reference if it is multi-catch block , Reason is it is made final by Java giants .

  Threads:- 


1) Even you make thread to sleep , it is not guaranteed it will start working right after completing the sleep time. It will go in runnable state and whenever it will get time from scheduler will start executing. Scheduler is OS specific and it can be different for different OS.

 2) Thready priority can be set 1-10 , but no guarantee it will behave same. 1- lowest , 10 is highest priority.

 3) Context Switching is the process of storing and restoring of CPU state so that Thread execution can be resumed from the same point at a later point of time

 4) sleep and yield both methods are static method m Reason is  these methods are always called on current thread so you do not need to call other threads(waiting , sleeping ) and if you do not to call other threads (other than current thread) you do not need them to be instance methods.

eg:- Thread.sleep(time to sleep);
        Thread.yield();

 5)  wait , notify and  notifyAll are kept in Object class not in Thread , Reason is these methods should be called from synchronized piece of code (either method or a block) and whenever you want to access synchronized block you will need the lock on object  And locks are associated with Object not with Thread s these are kept in Object class.

 6) Ways to achieve thread safety in java- synchronization,volatile,immutable

 7) You can set Thread as demon before starting it.

 8) ThreadGroup class was intended to give information about the group of threads and to give handler for uncaught exception for the group . But java 5 added uncaught handler in Thread so it is absolute to use thread group and not advised.

  Strings :-


 1) new String(“shadab”) , does not create two objects . It just create one only in heap as usual but we are passing “shadab” is an string object already which will be available in string constant pool(so these called two objects).

 2) We can use intern() to assign the reference from pool if string is available pool(SCP).

Comments