Tuesday, 8 September 2015

Java Program to Find Lexicographically Smallest and Largest substring of Length K


What is Lexicographic order?

Lexicographic order is an order in which words are displayed in alphabetical order using the appearance of letters in the word.It is also know as dictionary order or alphabetical order.For ex:-"Africa" is smaller than "Bangladesh" ,"He" is smaller than "he".

Sample program:-

 import java.util.ArrayList;  
 import java.util.Collections;  
 import java.util.List;  
 import java.util.Scanner;  
 /**  
  * @author Dixit  
  *   
  */  
 public class LexicographicExample {  
      public static void main(String a[]) {  
           Scanner sc = new Scanner(System.in);  
           System.out.println("Enter the String:-");  
           String str = sc.nextLine();  
           System.out.println("Enter the length");  
           int count = sc.nextInt();  
           List<String> list = new ArrayList<String>();  
           for (int i = 0; i < str.length(); i = i + 1) {  
                if (str.length() - i >= count) {  
                     list.add(str.substring(i, count + i));  
                }  
           }  
           Collections.sort(list);  
           System.out.println("Smallest subString:-" + list.get(0));  
           System.out.println("Largest subString:-" + list.get(list.size() - 1));  
      }  
 }  


 Output  
 Enter the String:-  
 helloworld  
 Enter the length  
 2  
 Smallest subString:-el  
 Largest subString:-wo  


Enjoy programming.

Tuesday, 1 September 2015

ListenerExecutorService and its Example



What is ListenerExecutorService ?
ListenerExecutorService is almost same as ExecutorService except  in ListenerExecutorService ,callback methods can be registered and that will be called once execution of task reach some defined state.ListenerExecutorService returns ListenableFuture instances.ListenableFuture instance allows to register callback methods which will get executed once the task gets completed.

In order to create ListenerExecutorService ,you need to use decorator which accepts ExecutorService as parameter
                MoreExecutors.listeningDecorator(ExecutorService);
You can use any of the ExecutorService (newFixedThreadPool(),newSingleThreadExecutor(),etc)


Sample Example:-


 import java.util.concurrent.Callable;  
 import java.util.concurrent.Executors;  
 import com.google.common.util.concurrent.FutureCallback;  
 import com.google.common.util.concurrent.Futures;  
 import com.google.common.util.concurrent.ListenableFuture;  
 import com.google.common.util.concurrent.ListeningExecutorService;  
 import com.google.common.util.concurrent.MoreExecutors;  
 /**  
  *   
  */  
 /**  
  * @author Dixit  
  *   
  */  
 public class ListeningExecutorServiceExample {  
      @SuppressWarnings("unchecked")  
      public static void main(String a[]) {  
           ListeningExecutorService pool = MoreExecutors  
                     .listeningDecorator(Executors.newCachedThreadPool());  
           final ListenableFuture<String> future = pool.submit(new Callable() {  
                @Override  
                public String call() throws Exception {  
                     try {  
                          int a = 10 / 0;  
                     } catch (Exception e) {  
                          throw e;  
                     }  
                     return "done";  
                }  
           });  
           Futures.addCallback(future, new FutureCallback() {  
                @Override  
                public void onSuccess(Object object) {  
                     System.out.println("Success.");  
                }  
                public void onFailure(Throwable throwable) {  
                     System.out.println("Failure.");  
                }  
           });  
      }  
 }  


 Output  
 Failure.

So in this program ,the callback methods onSuccess and onFailure will be called once execution of the task is finished.In this case an arithmetic exception occurs which calls the callback method onFailure.You don't need to explicitly check the state of your ListenableFuture object ,as the registered callbacks will handle the states ,once the task is completed.

you need to download the guava jar ,here is the link http://www.java2s.com/Code/Jar/g/Downloadguavajar.htm

Enjoy programming

Sunday, 30 August 2015

Why POST method is non-idempotent and GET is idempotent ?




GET Method:-HTTP GET method is just for getting things from server.It is not supposed to change anything on server.So GET method is idempotent.It can be executed more than once without any side effects.
As you can see in below diagram,User request for a page and servlet sends back a response with a generated HTML page.You can call the same page again and again and server will return the response with no negative consequences that is called idempotent.





POST Method:-HTTP POST method is not idempotent i.e. the data submitted in the body of POST might be destined for transaction that can't be reversed.
As below diagram explains that when you submit your form ,POST method updates the data in database and servlet sends back an response.SO when you perform the submit action again,It will generate different response.





PUT,HEAD,DELETE methods are IDEMPOTENT just like GET method.

Enjoy Learning :)

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