Saturday 29 August 2015

Finally block and Its Usage



What is finally block ?


finally block is either written after catch block or try block.finally blocks always executes when try block exits.Even if unexpected exception occurs in try block ,finally block is executed.It must be immediately followed by try or catch block.

Example:


/**  
  * @author Dixit  
  *   
  */  
 public class FinallyTest {  
      public static void main(String a[]) {  
           try {  
                System.out.println("Try block");  
           } catch (Exception e) {  
                System.out.println("catch block.");  
           } finally {  
                System.out.println("finally block.");  
           }  
      }  
 }  


Output  
 Try block  
 finally block.

Usage of finally block

finally block is mostly used to execute important code like closing db connection,closing file resources etc.

Also read Important finally interview questions

Enjoy Learning :)

Important finally interview questions


Important finally block questions which are commonly asked in interviews.

1) Find the output of below program ?

try {  
                System.out.println("Try block");  
                System.exit(0);  
           } catch (Exception ex) {  
                ex.printStackTrace();  
           }  
           finally {  
                System.out.println("finally block!!!");  
           }  

Output  
 Try block 

Reason:-the program will not execute finally block in this case because program is terminated using
System.exit(0) statement.

2) Find the output of below program ?

try {  
                System.out.println("Try block");  
                System.out.println(10 / 0);  
                System.exit(1);  
           } catch (Exception ex) {  
                ex.printStackTrace();  
           }  
           finally {  
                System.out.println("Finally block!!!");  
           }  

Output  
 Try block  
 java.lang.ArithmeticException: / by zero  
      at FinallyTest.main(FinallyTest.java:16)  
 Finally block!!!  

Reason:- An arithmetic exception occurred before executing statement System.exit(1).

3) Find the output of below program ?

public class FinallyTest {  
      public static void main(String a[]) {  
           System.out.println(tryCatchMethod());  
      }  
      private static int tryCatchMethod() {  
           try {  
                return 1;  
           } finally {  
                System.out.println("finally block");  
           }  
      }  
 }  

 Output  
 finally block  
 1  

Reason:-finally block runs before method returns 1 .

4) Find the output of below program ?

public class FinallyTest {  
      public static void main(String a[]) {  
           System.out.println(getIntegerNumber());  
      }  
      private static int getIntegerNumber() {  
           try {  
                return 1;  
           } finally {  
                return 2;  
           }  
      }  
 }  

Output  
 2  

Reason:- return value in finally block ("2") overrides return value of try block ("1").

5) Find the output of below program ?

public class FinallyTest {  
      public static void main(String a[]) {  
           System.out.println(getIntegerNumber());  
      }  
      private static int getIntegerNumber() {  
           try {  
                throw new NumberFormatException();  
           } finally {  
                return 2;  
           }  
      }  
 }  

 Output  
 2  

Reason:-Exception thrown by try block is overridden by return statement in finally block.That is why no exception is thrown.So Its bad practice to use return statements in finally block.

6)

 public class FinallyTest {  
      public static void main(String a[]) {  
           System.out.println(getIntegerNumber());  
      }  
      private static int getIntegerNumber() {  
           int i = 0;  
        try {  
          i = 1;  
          return i;  
        } finally {  
          i = 2;  
          System.out.println("finally block.");  
        }  
      }  
 }  

Output  
 finally block.  
 1  

Reason:- when return i is executed i has a value 1 after that i is assigned new value in finally block to 2 and program prints "finally block.". but here 1 is returned because return statement is not executed again.

Enjoy programming :)

Top 10 Important shortcut keys for Windows


Shortcut keys mainly improve our work efficiency by speeding up the work.

Very basic and important shortcut key that everyone must know are:-

1) ALT + Tab :- It allows you to shuffle around your open application windows.It is very useful key to easily switch to other application windows.

2) CTRL + SHIFT +Del :-It opens the window option screen for Task Manager,locking computer,witiching user etc in latest version of windows.In Windows XP,It is meant for opening task manager.
CTRL + SHIFT + Esc is used to open Windows Task manager in Wndows XP and later.

3) SHIFT + Del :-It will delete the selected files permanently without moving them to recycle bin.

4) F2 :- Instead of right clicking on file and selecting rename option,F2 function key allows you to rename file instantly.

5) WIN + D :-It will display the desktop irrespective of how many opened application .
Similarly WIN + M will minimize all the current opened application and will display desktop. 

6) WIN + L :- Lock the computer and switch users (Windows XP and above only). 

7) WIN + R :-Opens the run command dialog box.

8) CTRL + C :- It will copy the highlighted text or selected file.If you want to cut highlighted text or selected file,press CTRL + X.

9) CTRL + V or SHIFT + Insert :- Both the shortcut keys will paste the highlighted text or selected file.

10) CTRL + Z or CTRL + Y :- CTRL + Z will undo the recent changes which you have done and CTRL + Y will redo the recent undo changes.
Enjoy Learning.


10 useful windows run command every developer must know


To speed up the work in windows, run command are very useful.There are some useful run commands that every developer must know .

First to open run dialog box you can either go to Start- > run or press shortcut key win + R.
Type the following command in the dialog box and press ok button.

1) %temp% :- This command is very useful to delete temporary files which gets created when you work on you PC.This are unnecessary files so in order to speed up your PC or clear your PC memory,you should delete all the temporary files.Keep in habbit that every week you run this command and free your PC memory space.

2) write :-It opens a Microsoft wordpad where you can write your notes and etc.

3) psr:-Its stands for Problem Steps Recorder.You can use this to automatically capture the steps you take on a computer including a text description of where you clicked and a picture of the screen during each click.Once you are done saving the steps,you can help others to troubleshoot their PC problems.

4) cmd:- Its a very important command for developers.this command use to open command prompt.

5) notepad:-this command is used to open notepad.

6) taskmgr:- Its opens a task manager where you can monitor your running process.There is shortcut key for this command also.

7) services.msc:-It provides you with all the running service on your machine. you can enable or disable unnecessary service which will speed your system.Note you should not disable any service for which you don't have knowledge because it may interrupt your PC normal behavior.

8) calc:-It will open a calculator .

9) control:-This command will open control panel on your desktop.

10) mstsc:-Its is used to open Remote Desktop Connection dialog box.With the help of this command ,you can connect to another computer running windows that's connected to the same network or to the internet.For ex: you can access you work computer from you home computer and will be able to perform various tasks.

NOTE:-Try to bring in practice to use this commands while you are working.It will speed up your work activities.

Also read Top 10 Important shortcut keys for Windows

Thursday 27 August 2015

Convert Web browser into Notepad



In order to open temporary notepad into your web browser,you need to type 
data:text/html, <html.contenteditable> in the address bar of your web browser and you have temporary notepad.







Enjoy Learning :)

Daemon Thread


What is Daemon Threads ?

Daemon threads are those threads which perform some helper functions or provide services to non-daemon threads(user threads).When JVM starts up,it creates garbage collector thread or some housekeeping threads except main thread .this threads are called Daemon threads

Daemon threads runs in background to provide services to user threads.Daemon threads are low priority threads.When no user thread is running JVM terminates all the daemon threads .

Sample Program:-


 /**  
  * @author Dixit  
  *   
  */  
 public class TestDaemonThreads extends Thread {  
      public static void main(String[] args) {  
           TestDaemonThreads daemonThread = new TestDaemonThreads();  
           TestDaemonThreads normalThread = new TestDaemonThreads();  
           daemonThread.setDaemon(true);  
           daemonThread.start();  
           normalThread.start();  
      }  
      public void run() {  
           if (Thread.currentThread().isDaemon()) {  
                System.out.println("Daemon Thread");  
           } else {  
                System.out.println("Normal Thread");  
           }  
      }  
 }  



 Output:-  
 Daemon Thread  
 Normal Thread  

Use of Daemon Threads:-

Daemon threads performs housekeeping tasks such as removing unwanted entries from memory cache,releasing memory of unused objects etc.

Enjoy Learning.


Shutdown Hooks


It is one of the concurrency concept.JVM(Java Virtual Machine) can shutdown in an orderly or abruptly manner. An orderly shutdown is nothing but when all normal threads terminates successfully,or by calling System.exit(),or by closing it from special keys like Ctrl+C.
JVM can also be shutdown abrubtly by killing the JVM process or by some OS related issues.

What is Shutdown Hooks ?

Shutdown Hooks are unstarted threads that are registered with Runtime.addShutdownHook().
JVM does not give any guarantee on the order in which shutdown hooks are started.In orderly shutdown JVM starts all registered shutdown hooks.

When all shutdown hooks have completed their task,JVM may choose to run finalizers if runFinalizersOnExit is true.JVM does not stop any of the application thread that are still running at shutdown time.they automatically terminated when JVM halts.Also JVM allows to run application threads concurrently with shutdown hooks.In an abrupt shutdown,shutdown hooks will not run.


Example of Shutdown Hook:-

/**  
  *   
  */  
 /**  
  * @author Dixit  
  *   
  */  
 public class TestShutdownHook {  
      // shutdown hook thread can be used to perform cleaning of resources.  
      private static class ShutDownHook extends Thread {  
           public void run() {  
                System.out.println("shutdown hook thread started");  
           }  
      }  
      public static void main(String[] args) {  
           ShutDownHook jvmShutdownHook = new ShutDownHook();  
           Runtime.getRuntime().addShutdownHook(jvmShutdownHook);  
           System.out.println("Register Shutdown Hook");  
           System.out.println("calling System.exit() to close the program");  
           System.exit(0);  
           System.out.println("Program Finished");  
      }  
 }  

Output:-  
 Register Shutdown Hook  
 calling System.exit() to close the program  
 shutdown hook thread started  

Advantage of Shutdown Hooks:-

It can be used for service or application cleanup,such as deleting unwanted file, releasing resources like db related resources,file operation resources etc.

 Note:-Shutdown hooks must be thread safe and they should use synchronization when   
 accessing shared data.They should not assume the state of the application(such as all worker   
 thread have completed) at any point of time.They should complete their task as quickly as   
 possible because their existence delays the JVM termination at a time when user may be   
 expecting the JVM to shutdown quickly.