Monday 22 April 2013

Convert InputStream to byte array in Java

Leave a Comment

Here is complete code example of reading InputStream as byte array in Java. This Java program has two methods, one uses Apache commons IOUtils library to convert InputStream as byte array, while other uses core Java class methods. If you look at Apache commons code, it's just a one liner and it's tested for various kind of input e.g. text file, binary file, images, and both large and small files.

 By writing your own method for common utilities, which is good in sense of ownership; It's difficult to get same kind of testing exposure. That's the reason I prefer to use open source libraries, like Apache commons and Google Guava, along with JDK. They effectively complement standard Java library, and with Maven, it’s pretty easy to manage dependency.

In this example, we are reading a small text file using FileInputStream in Java.

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream; 
import java.io.FileNotFoundException; 
import java.io.IOException; 
import java.io.InputStream; 
import org.apache.commons.io.IOUtils; 
public class InputStreamToByteArray { 
   public static void main(String args[]) throws FileNotFoundException, IOException 
   { //Converting InputStream to byte array using apche commons IO library 
     int length = toByteArrayUsingCommons(new FileInputStream("C:/temp/abc.txt")).length; 
  System.out.println("Length of byte array created from InputStream in Java using IOUtils : " + length); 
  
  //Converting InputStream to Byte arrray using Java code 
  length = toByteArrayUsingJava(new FileInputStream("C:/temp/abc.txt")).length; 
  System.out.println("Length of Byte array created from FileInputStream in Java : " + length); 
   } 
   /* * Converts InputStream to ByteArray in Java using Apache commons IOUtils class */ 
   
   public static byte[] toByteArrayUsingCommons(InputStream is) throws IOException{ 
     return IOUtils.toByteArray(is); 
  } 
  
  /* * Read bytes from inputStream and writes to OutputStream, later converts * OutputStream to byte array in Java. */ 
  public static byte[] toByteArrayUsingJava(InputStream is) throws IOException{
      ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
    int reads = is.read(); 
    while(reads != -1)
    { 
      baos.write(reads); 
   reads = is.read(); 
    }
    return baos.toByteArray(); 
    } 
}

 Output: 
 Length of byte array created from InputStream in Java using IOUtils : 27
 Length of Byte array created from FileInputStream in Java : 27 


Read More...

Friday 19 April 2013

Keyboard Shortcuts (Microsoft Windows)

Leave a Comment

1. CTRL+C (Copy)
2. CTRL+X (Cut)
... 3. CTRL+V (Paste)
4. CTRL+Z (Undo)
5. DELETE (Delete)
6. SHIFT+DELETE (Delete the selected item permanently without placing the item in the Recycle Bin)
7. CTRL while dragging an item (Copy the selected item)
8. CTRL+SHIFT while dragging an item (Create a shortcut to the selected item)
9. F2 key (Rename the selected item)
10. CTRL+RIGHT ARROW (Move the insertion point to the beginning of the next word)
11. CTRL+LEFT ARROW (Move the insertion point to the beginning of the previous word)
12. CTRL+DOWN ARROW (Move the insertion point to the beginning of the next paragraph)
13. CTRL+UP ARROW (Move the insertion point to the beginning of the previous paragraph)
14. CTRL+SHIFT with any of the arrow keys (Highlight a block of text)
SHIFT with any of the arrow keys (Select more than one item in a window or on the desktop, or select text in a document)
15. CTRL+A (Select all)
16. F3 key (Search for a file or a folder)
17. ALT+ENTER (View the properties for the selected item)
18. ALT+F4 (Close the active item, or quit the active program)
19. ALT+ENTER (Display the properties of the selected object)
20. ALT+SPACEBAR (Open the shortcut menu for the active window)
21. CTRL+F4 (Close the active document in programs that enable you to have multiple documents opensimultaneously)
22. ALT+TAB (Switch between the open items)
23. ALT+ESC (Cycle through items in the order that they had been opened)
24. F6 key (Cycle through the screen elements in a window or on the desktop)
25. F4 key (Display the Address bar list in My Computer or Windows Explorer)
26. SHIFT+F10 (Display the shortcut menu for the selected item)
27. ALT+SPACEBAR (Display the System menu for the active window)
28. CTRL+ESC (Display the Start menu)
29. ALT+Underlined letter in a menu name (Display the corresponding menu) Underlined letter in a command name on an open menu (Perform the corresponding command)
30. F10 key (Activate the menu bar in the active program)
31. RIGHT ARROW (Open the next menu to the right, or open a submenu)
32. LEFT ARROW (Open the next menu to the left, or close a submenu)
33. F5 key (Update the active window)
34. BACKSPACE (View the folder onelevel up in My Computer or Windows Explorer)
35. ESC (Cancel the current task)
36. SHIFT when you insert a CD-ROMinto the CD-ROM drive (Prevent the CD-ROM from automatically playing)
Dialog Box - Keyboard Shortcuts
1. CTRL+TAB (Move forward through the tabs)
2. CTRL+SHIFT+TAB (Move backward through the tabs)
3. TAB (Move forward through the options)
4. SHIFT+TAB (Move backward through the options)
5. ALT+Underlined letter (Perform the corresponding command or select the corresponding option)
6. ENTER (Perform the command for the active option or button)
7. SPACEBAR (Select or clear the check box if the active option is a check box)
8. Arrow keys (Select a button if the active option is a group of option buttons)
9. F1 key (Display Help)
10. F4 key (Display the items in the active list)
11. BACKSPACE (Open a folder one level up if a folder is selected in the Save As or Open dialog box)

Microsoft Natural Keyboard Shortcuts
1. Windows Logo (Display or hide the Start menu)
2. Windows Logo+BREAK (Display the System Properties dialog box)
3. Windows Logo+D (Display the desktop)
4. Windows Logo+M (Minimize all of the windows)
5. Windows Logo+SHIFT+M (Restorethe minimized windows)
6. Windows Logo+E (Open My Computer)
7. Windows Logo+F (Search for a file or a folder)
8. CTRL+Windows Logo+F (Search for computers)
9. Windows Logo+F1 (Display Windows Help)
10. Windows Logo+ L (Lock the keyboard)
11. Windows Logo+R (Open the Run dialog box)
12. Windows Logo+U (Open Utility Manager)
13. Accessibility Keyboard Shortcuts
14. Right SHIFT for eight seconds (Switch FilterKeys either on or off)
15. Left ALT+left SHIFT+PRINT SCREEN (Switch High Contrast either on or off)
16. Left ALT+left SHIFT+NUM LOCK (Switch the MouseKeys either on or off)
17. SHIFT five times (Switch the StickyKeys either on or off)
18. NUM LOCK for five seconds (Switch the ToggleKeys either on or off)
19. Windows Logo +U (Open Utility Manager)
20. Windows Explorer Keyboard Shortcuts
21. END (Display the bottom of the active window)
22. HOME (Display the top of the active window)
23. NUM LOCK+Asterisk sign (*) (Display all of the subfolders that are under the selected folder)
24. NUM LOCK+Plus sign (+) (Display the contents of the selected folder)
25. NUM LOCK+Minus sign (-) (Collapse the selected folder)
26. LEFT ARROW (Collapse the current selection if it is expanded, or select the parent folder)
27. RIGHT ARROW (Display the current selection if it is collapsed, or select the first subfolder)
Shortcut Keys for Character Map
After you double-click a character on the grid of characters, you can move through the grid by using the keyboard shortcuts:
1. RIGHT ARROW (Move to the rightor to the beginning of the next line)
2. LEFT ARROW (Move to the left orto the end of the previous line)
3. UP ARROW (Move up one row)
4. DOWN ARROW (Move down one row)
5. PAGE UP (Move up one screen at a time)
6. PAGE DOWN (Move down one screen at a time)
7. HOME (Move to the beginning of the line)
8. END (Move to the end of the line)
9. CTRL+HOME (Move to the first character)
10. CTRL+END (Move to the last character)
11. SPACEBAR (Switch between Enlarged and Normal mode when a character is selected)
Microsoft Management Console (MMC)
Main Window Keyboard Shortcuts
1. CTRL+O (Open a saved console)
2. CTRL+N (Open a new console)
3. CTRL+S (Save the open console)
4. CTRL+M (Add or remove a console item)
5. CTRL+W (Open a new window)
6. F5 key (Update the content of all console windows)
7. ALT+SPACEBAR (Display the MMC window menu)
8. ALT+F4 (Close the console)
9. ALT+A (Display the Action menu)
10. ALT+V (Display the View menu)
11. ALT+F (Display the File menu)
12. ALT+O (Display the Favorites menu)

MMC Console Window Keyboard Shortcuts
1. CTRL+P (Print the current page or active pane)
2. ALT+Minus sign (-) (Display the window menu for the active console window)
3. SHIFT+F10 (Display the Action shortcut menu for the selected item)
4. F1 key (Open the Help topic, if any, for the selected item)
5. F5 key (Update the content of all console windows)
6. CTRL+F10 (Maximize the active console window)
7. CTRL+F5 (Restore the active console window)
8. ALT+ENTER (Display the Properties dialog box, if any, for theselected item)
9. F2 key (Rename the selected item)
10. CTRL+F4 (Close the active console window. When a console has only one console window, this shortcut closes the console)
Remote Desktop Connection Navigation
1. CTRL+ALT+END (Open the Microsoft Windows NT Security dialog box)
2. ALT+PAGE UP (Switch between programs from left to right)
3. ALT+PAGE DOWN (Switch between programs from right to left)
4. ALT+INSERT (Cycle through the programs in most recently used order)
5. ALT+HOME (Display the Start menu)
6. CTRL+ALT+BREAK (Switch the client computer between a window and a full screen)
7. ALT+DELETE (Display the Windows menu)
8. CTRL+ALT+Minus sign (-) (Place a snapshot of the active window in the client on the Terminal server clipboard and provide the same functionality as pressing PRINT SCREEN on a local computer.)
9. CTRL+ALT+Plus sign (+) (Place asnapshot of the entire client window area on the Terminal server clipboardand provide the same functionality aspressing ALT+PRINT SCREEN on a local computer.)

Microsoft Internet Explorer Keyboard Shortcuts
1. CTRL+B (Open the Organize Favorites dialog box)
2. CTRL+E (Open the Search bar)
3. CTRL+F (Start the Find utility)
4. CTRL+H (Open the History bar)
5. CTRL+I (Open the Favorites bar)
6. CTRL+L (Open the Open dialog box)
7. CTRL+N (Start another instance of the browser with the same Web address)
8. CTRL+O (Open the Open dialog box,the same as CTRL+L)
9. CTRL+P (Open the Print dialog box)
10. CTRL+R (Update the current Web page)
11. CTRL+W (Close the current window)
Read More...

Tuesday 16 April 2013

Converting a Date object to a calendar object

Leave a Comment
Calendar cal = Calendar.getInstance();
   cal.setTime(date);
   cal.set(Calendar.HOUR_OF_DAY, 0);
   cal.set(Calendar.MINUTE, 0);    
   cal.set(Calendar.SECOND, 0);    
   cal.set(Calendar.MILLISECOND, 0);    
          
   return cal.getTime();

Read More...

Compare Two Date In Java

Leave a Comment
public static void main( String[] args ) 
    {
     try{
 
      SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
         Date date1 = sdf.parse("2009-12-31");
         Date date2 = sdf.parse("2010-01-31");
 
         System.out.println(sdf.format(date1));
         System.out.println(sdf.format(date2));
 
         if(date1.compareTo(date2)>0){
          System.out.println("Date1 is after Date2");
         }else if(date1.compareTo(date2)<0){
          System.out.println("Date1 is before Date2");
         }else if(date1.compareTo(date2)==0){
          System.out.println("Date1 is equal to Date2");
         }else{
          System.out.println("How to get here?");
         }
 
     }catch(ParseException ex){
      ex.printStackTrace();
     }
    }

Read More...

String to Date Conversion in Java

Leave a Comment
//String to Date Conversion
 stringDate = "10-04-2013";

 public Date stringToDate(String stringDate)
 {
  Date date = null;
  try {
   SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
   date = sdf.parse(stringDate);
   System.out.println(date);
   return date;
  } catch (ParseException e) {
   e.printStackTrace();
   return date;
  }
 }

Read More...

Timestamp to Date Conversion In Java

Leave a Comment
Use This Import.
import java.sql.Timestamp;
//Timestamp to Date Conversion
 public Date timeStampToDate(Timestamp timestamp)
 {
  Date date = null;
  try
  {
    date = new Date(timestamp.getTime());
    return date;
  }catch (Exception e) {
   e.printStackTrace();
   return date;
  }
 }

Read More...

Abstract Class and Interface Interview Questions Answers in Java

Leave a Comment

1) Can abstract class have constructors in Java?
Yes, abstract class can declare and define constructor in Java. Since you can not create instance of abstract class,  constructor can only be called during constructor chaining, i.e. when you create instance of concrete implementation class. Now some interviewer, ask what is the purpose of constructor, if you can not instantiate abstract class? Well, it can still be used to initialize common variables, which are declared inside abstract class, and used by various implementation. Also even if you don’t provide any constructor, compiler will add default no argument constructor in abstract class, without that your subclass will not compile, since first statement in any constructor implicitly calls super(), default super class constructor in Java.

2) Can abstract class implements interface in Java? does they require to implement all methods?
Yes, abstract class can implement interface by using implements keyword. Since they are abstract, they don’t need to implement all methods. It’s good practice to provide an abstract base class, along with an interface to declare Type. One example of this is java.util.List interface and corresponding java.util.AbstractList abstract class. Since AbstractList implements all common methods,  concrete implementations like LinkedList and ArrayList are free from burden of implementing all methods, had they implemented List interface directly. It’s best of both world, you can get advantage of interface for declaring type, and flexibility of abstract class to implement common behavior at one place. Effective Java has a nice chapter on how to use interface and abstract class in Java, which is worth reading.


3) Can abstract class be final in Java?
No, abstract class can not be final in Java. Making them final will stop abstract class from being extended, which is the only way to use abstract class. They are also opposite of each other, abstract keyword enforces to extend a class, for using it, on the other hand, final keyword prevents a class from being extended. In real world also, abstract signifies incompleteness, while final is used to demonstrate completeness. Bottom line is, you can not make your class abstract and final in Java, at same time, it’s a compile time error.

4) Can abstract class have static methods in Java?
Yes, abstract class can declare and define static methods, nothing prevents from doing that. But, you must follow guidelines for making a method static in Java, as it’s not welcomed in a object oriented design, because static methods can not be overridden in Java. It’s very rare, you see static methods inside abstract class, but as I said, if you have very good reason of doing it, then nothing stops you.


5) Can you create instance of abstract class?
No, you can not create instance of abstract class in Java, they are incomplete. Even though, if your abstract class don’t contain any abstract method, you can not create instance of it. By making a class abstract,  you told compiler that, it’s incomplete and should not be instantiated. Java compiler will throw error, when a code tries to instantiate abstract class.

6) Is it necessary for abstract class to have abstract method?
No, It’s not mandatory for an abstract class to have any abstract method. You can make a class abstract in Java, by just using abstract keyword in class declaration. Compiler will enforce all structural restriction, applied to abstract class, e.g. now allowing to create any instance. By the way, it’s debatable whether you should have abstract method inside abstract class or interface. In my opinion, abstract class should have abstract methods, because that’s the first thing programmer assumes, when he see that class. That would also go nicely along principle of least surprise.

7) Difference between abstract class and interface in Java?
This is the most important and one of the classic Java Interview question. I don’t know, how many times I have seen this question at all most all levels of Java interviews. One reason, which makes this question interesting is ability to produce example. It’s easy to answers questions on core OOPS concepts like Abstraction, Encapsulation, Polymorphism and Inheritance, but when it comes to subtle points like this, candidate more often fumbled. You can see this post for all syntactical difference between abstract class and interface, but it deserve a post on it’s own.

8) When do you favor abstract class over interface?
This is the follow-up of previous interview questions on abstract class and interface. If you know syntactical difference, you can answer this question quite easily, as they are the one, which drives the decision. Since it’s almost impossible to add a new method on a published interface, it’s better to use abstract class, when evolution is concern. Abstract class in Java evolves better than interface. Similarly, if you have too many methods inside interface, you are creating pain for all it’s implementation, consider providing an abstract class for default implementation. This is the pattern followed in Java collection package, you can see AbstractList provides default implementation for List interface.

9) What is abstract method in Java?
An abstract method is a method without body. You just declare method, without defining it and use abstract keyword in method declaration.  All method declared inside Java Interface are by default abstract. Here is an example of abstract method in Java

                public void abstract printVersion();

Now, In order to implement this method, you need to extend abstract class and override this method.

10) Can abstract class contains main method in Java ?
Yes, abstract class can contain main method, it just another static method and you can execute Abstract class with main method, until you don’t create any instance.

Read More...

if condition in display tag?

Leave a Comment
Use JSTL for if condition in display tag.

Include this library in your jsp page:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
 
<display:column sortable="true" title="Grand Total">
        <c:if test="${data.zone != 'GRAND TOTAL'}">      
            <html:link action="/exceptionScoreCardGrandReport.do?zone=${data.zone}">
                <b>${data.grandTotal}</b>
            </html:link>
        </c:if>
    </display:column>  
Read More...

Monday 15 April 2013

Convert JSON String to Java object using Jackson

Leave a Comment

This method takes an Jon String which represent a User object in JSON format and convert it into Java User object. In this Java example I have create User as nested static class for convenience, You may create a separate top level class if needed.

import java.io.IOException;

import org.apache.log4j.Logger;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

/*
 * Java program to convert JSON String into Java object using Jackson library.
 * Jackson is very easy to use and require just two lines of code to create a Java object
 * from JSON String format.
 *
 * @author Harit Rajput
 */
public class JsonToJavaConverter {

        private static Logger logger = Logger.getLogger(JsonToJavaConverter.class);
      
      
        public static void main(String args[]) throws JsonParseException
                                                    , JsonMappingException, IOException{

                JsonToJavaConverter converter = new JsonToJavaConverter();
              
                String json = "{\n" +
                "    \"name\": \"Harit\",\n" +
                "    \"surname\": \"Kumar\",\n" +
                "    \"phone\": 9832734651}";
              
                //converting JSON String to Java object
                converter.fromJson(json);
        }
      
      
        public Object fromJson(String json) throws JsonParseException
                                                   , JsonMappingException, IOException{
                User obj = new ObjectMapper().readValue(json, User.class);
                logger.info("Java Object created from JSON String ");
                logger.info("JSON String : " + json);
                logger.info("Java Object : " + obj);
              
                return obj;
        }
      
public static class User{
                private String name;
                private String surname;
                private long phone;
              
                public String getName() {return name;}
                public void setName(String name) {this.name = name;}

                public String getSurname() {return surname;}
                public void setSurname(String surname) {this.surname = surname;}

                public long getPhone() {return phone;}
                public void setPhone(long phone) {this.phone = phone;}

                @Override
                public String toString() {
                        return "User [name=" + name + ", surname=" + surname + ", phone="
                                        + phone + "]";
                }
              
               
        }
}



Output:
2013-01-07 01:15:05,287 0    [main] INFO  JsonToJavaConverter  - Java Object created from JSON String
2013-01-07 01:15:05,287 0    [main] INFO  JsonToJavaConverter  - JSON String : {
    "name": "Harit",
    "surname": "Kumar",
    "phone": 9787878788}
2013-01-07 01:15:05,287 0    [main] INFO  JsonToJavaConverter  - Java Object : User [name=Harit, surname=Kumar, phone=9787878788]


Read More...

Wednesday 10 April 2013

Enum to String to Enum in Java

Leave a Comment
Enum to String

public class EnumTest {

    private enum LOAN {

        HOME_LOAN {
            @Override
            public String toString() {
                return "Always look for cheaper Home loan";
            }
        },
        AUTO_LOAN {
            @Override
            public String toString() {
                return "Cheaper Auto Loan is better";
            }
        },
        PEROSNAL_LOAN{
            @Override
            public String toString() {
                return "Personal loan is not cheaper any more";
            }
        }
    }

    public static void main(String[] args) {
     
        //Exmaple of String to Enum in Java
        LOAN homeLoan = LOAN.valueOf("HOME_LOAN");
        System.out.println(homeLoan);
        LOAN autoLoan = LOAN.valueOf("AUTO_LOAN");
        System.out.println(autoLoan);
        LOAN personalLoan = LOAN.valueOf("PEROSNAL_LOAN");
        System.out.println(personalLoan);
     
    }

Output:
Always look for cheaper Home loan
Cheaper Auto Loan is better
Personal loan is not cheaper any more


String to Enum

public static void main(String[] args) {
     
        //Exmaple of Enum to String in Java
        String homeLoan = LOAN.HOME_LOAN.name();
        System.out.println(homeLoan);
        String autoLoan = LOAN.AUTO_LOAN.name();
        System.out.println(autoLoan);
        String personalLoan = LOAN.PERSONAL_LOAN.name();
        System.out.println(personalLoan);
      
    
     
    }

Output:
HOME_LOAN
AUTO_LOAN
PERSONAL_LOAN

Read More...

Compare two String in Java

Leave a Comment

Here are four examples of comparing String in Java

1) String comparison using equals method
2) String comparison using equalsIgnoreCase method
2) String comparison using compareTo method
4) String comparison using compareToIgnoreCase method


public class StringComparisonExample {

    public static void main(String args[]) {

        String tv = "Bravia";
        String television = "Bravia";

        // String compare example using equals
        if (tv.equals(television)) {
            System.out.println("Both tv and television contains same letters and equal by equals method of String");
        }

        // String compare example in java using compareTo
        if (tv.compareTo(television) == 0) {
            System.out.println("Both tv and television are equal using compareTo method of String");
        }

        television = "BRAVIA";

        // Java String comparison example using equalsIgnoreCase
        if (tv.equalsIgnoreCase(television)) {
            System.out.println("tv and television are equal by equalsIgnoreCase method of String");
        }

        // String comparison example in java using CompareToIgnoreCase
        if (tv.compareToIgnoreCase(television) == 0) {
            System.out.println("tv and television are same by compareToIgnoreCase of String");
        }

        String sony = "Sony";
        String samsung = "Samsung";

        // lexicographical comparison of String in Java with ComapreTo
        if (sony.compareTo(samsung) > 0) {
            System.out.println("Sony comes after Samsung in lexicographical order");
        } else if (sony.compareTo(samsung) < 0) {
            System.out.println("Sony comes before Samsung in lexicographical order");
        }
    }

}

Output:
Both tv and television contains same letters and equal by equals method of String
Both tv and television are equal using compareTo method of String
tv and television are equal by equalsIgnoreCase method of String
tv and television are same by compareToIgnoreCase of String
Sony comes after Samsung in lexicographical order


Read More...

Compare Two Enum in Java - Equals, == ,CompareTo

Leave a Comment

you can use both == and equals() method to compare Enum, they will produce same result because equals() method of Java.lang.Enum internally uses == to compare enum in Java.

Every Enum in Java implicitly extends java.lang.Enum ,and since equals() method is declared final, there is no chance of overriding equals method in user defined enum. If you are not just checking whether two enum are equal or not, and rather interested in order of different instance of Enum, than you can use compareTo() method of enum to compare two enums. Java.lang.Enum implements Comparable interface and implements compareTo() method. Natural order of enum is defined by the order they are declared in Java code and same order is returned by ordinal() method.

 Equals from java.lang.Enum class


public final boolean equals(Object other)
{ 
    return this==other; 
}


If you compare any Enum with null, using == operator, it will result in false, but if you use equals() method to do this check, you may get NullPointerException, unless you are using calling equals in right way

private enum Shape
{
   RECTANGLE, SQUARE, CIRCLE, TRIANGLE; 
} 

private enum Status
{ 
  ON, OFF; 
} 
Shape unknown = null; 
Shape circle = Shape.CIRCLE; 
boolean result = unknown == circle; //return false 
result = unknown.equals(circle); //throws NullPointerException



Another advantage of using == to compare enum is, compile time safety. Equality or == operator checks if both enum object are from same enum type or not at compile time itself, while equals() method will also return false but at runtime. Since it's always better to detect errors at compile time, == scores over equals in case of comparing enum

Comparing Enums with compareTo method
When we say comparing enum, it's not always checking if two enums are equal or not. Sometime you need to compare them for sorting or to arrange them in a particularly order. We know that we can compare objects using Comparable and Comparator in Java and enum is no different, though it provides additional convenience. Java.lang.Enum implements Comparable interface and it's compareTo() method compares only same type of enum. Also natural order of enum is the order in which they are declared in code

public final int compareTo(E o) 
{ 
  Enum other = (Enum)o; 
  Enum self = this; 
  if (self.getClass() != other.getClass() && // optimization 
      self.getDeclaringClass() != other.getDeclaringClass()) 
   throw new ClassCastException(); 
  return self.ordinal - other.ordinal; 
}


Read More...

Convert Secons in to mm:ss formatted time

Leave a Comment
/**
  * Converting Second In to MM:SS time
  * @param seconds
  * @author harit Kumar
  * @return time MM:SS
  */
 public String secToTime(int seconds)
 {
  String time= "";
  if(seconds > 59)
  {
   int minutes = seconds/60;
   int sec = seconds%60;
   time = minutes+":"+sec;
  }
  else 
  {
   time = "00:"+seconds;
  }
  return time;
 }

Read More...

Monday 8 April 2013

How to get current stack trace in Java for a Thread

Leave a Comment
 what is stack trace in Java

Thread executes code in Java, they call methods, and when they call, they keep them in there stack memory. You can print that stack trace to find out, from where a particular method is get called in execution flow.

One of the easiest way of printing stack trace of current thread in Java is by using dumpStack()  method from java.lang.Thread class. This method prints stack trace of thread on which it get's called. You can use Thread.currentThread() method to get reference of current thread before calling this method

Another way printing stack trace is using printStackTrace() method of Throwable class

Main difference between using dumpStack() and printStackTrace() is first entry in Stack, In case of dumpStack() first entry is always java.lang.Thread.dumpStack(), while in later case it's the method from where you printed stack trace. If you don't want to print stack trace and rather wants it in Java program, you can use getStackTrace() method from Thread class. This method returns an array of StackTraceElement.

public class StackTraceExample {

 public static void main(String args[]) 
   { 
  //calling a method to print stack trace further down
  first(); 
 } 
 public static void first()
 { 
  second();
  } 
 
 private static void second() 
 { 
  third();
 }
 
 private static void third() 
 { 
  //If you want to print stack trace on console than use dumpStack() method 
  System.err.println("Stack trace of current thread using dumpStack() method"); 
  Thread.currentThread().dumpStack(); 
  
  //This is another way to print stack trace from current method 
  System.err.println("Printing stack trace using printStackTrace() method of Throwable "); 
  new Throwable().printStackTrace(); 
  
  //If you want stack trace as StackTraceElement in program itself than //use getStackTrace() method of Thread class 
  StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace(); 
  
  //Once you get StackTraceElement you can also print it to console 
  System.err.println("displaying Stack trace from StackTraceElement in Java"); 
  for(StackTraceElement st : stackTrace)
  {
   System.err.println(st);
  }

  }
}


Output:
Stack trace of current thread using dumpStack() method
java.lang.Exception: Stack trace
 at java.lang.Thread.dumpStack(Thread.java:1206)
 at StackTraceExample.third(StackTraceExample.java:22)
 at StackTraceExample.second(StackTraceExample.java:15)
 at StackTraceExample.first(StackTraceExample.java:10)
 at StackTraceExample.main(StackTraceExample.java:6)
Printing stack trace using printStackTrace() method of Throwable 
java.lang.Throwable
 at StackTraceExample.third(StackTraceExample.java:26)
 at StackTraceExample.second(StackTraceExample.java:15)
 at StackTraceExample.first(StackTraceExample.java:10)
 at StackTraceExample.main(StackTraceExample.java:6)
displaying Stack trace from StackTraceElement in Java
java.lang.Thread.getStackTrace(Thread.java:1436)
StackTraceExample.third(StackTraceExample.java:29)
StackTraceExample.second(StackTraceExample.java:15)
StackTraceExample.first(StackTraceExample.java:10)
StackTraceExample.main(StackTraceExample.java:6)

Read More...

Sunday 7 April 2013

Increment & Decrements Date In Java

Leave a Comment
import java.text.SimpleDateFormat; 
import java.util.Calendar; 
import java.util.Date;
/**
 *  @author Harit 
 *  */ 

public class IncrementDecrementDate 
{ 
 public static void main(String args[]) 
 { 
  //Using Calendar to increment and decrement days from date in Java 
  Date today = new Date(); 
  System.out.println("Today is " + toddMMyy(today)); 
  Calendar cal = Calendar.getInstance(); 
  
  //adding one day to current date 
  cal.add(Calendar.DAY_OF_MONTH, 1); 
  Date tommrrow = cal.getTime(); 
  System.out.println("Tomorrow will be " + toddMMyy(tommrrow));
  
  //substracting two day from date in Java 
  cal.add(Calendar.DAY_OF_MONTH, -2); 
  Date yesterday = cal.getTime(); 
  System.out.println("Yesterday was " + toddMMyy(cal.getTime())); 
  
  
 } 
 
 public static String toddMMyy(Date day)
 { 
  SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yy"); 
  String date = formatter.format(day);
  return date; 
 } 
 
 }




Read More...

Thursday 4 April 2013

JSON to Object Mapping using Jackson

Leave a Comment

JSON:

{
"recentVideosList":[{"tags":null,"followerId":null,"videoId":"hLta6iJGtH8=","videoViewCount":"0","title":"twitter2","videoURL":"https://s3.amazonaws.com/youbusk/63/1364047039_011760.mov","userFollowingThisVideo":"No","videosByThisUser":"5","videoTimer":"6","videoUploadDateTime":"2013-03-25 07:41:49.0","isAlreadyFlagged":"N","uploadedByCountryId":"96","uploadedByUserId":"xHj2V0LLsfE=","thumbnailURL":"https://s3.amazonaws.com/youbusk/63/1364047039_011760.png","aboutUploadedBy":"ddddddddretreyreyrtyrt","tips":"0","uploadedBy":"naveen140990","abuseCount":"0","videoShareCount":"0","isAlreadyLiked":"NO"}],

"challengeOfTheDayList":[{"notificationId":"1","notificationDescription":"This is the first notification of videos."}],

"videoOfTheDayList":[{"tags":null,"followerId":null,"videoId":"jFB425S0Rv0=","videoViewCount":"9","title":"shr","videoURL":"https://s3.amazonaws.com/youbusk/2/1360314335_608470.mov","userFollowingThisVideo":"No","videosByThisUser":"6","videoTimer":"16","videoUploadDateTime":"2013-02-08 14:32:00.0","isAlreadyFlagged":"Y","uploadedByCountryId":"241","uploadedByUserId":"jFB425S0Rv0=","thumbnailURL":"https://s3.amazonaws.com/youbusk/2/1360314335_608470.png","aboutUploadedBy":"","tips":"14","uploadedBy":"gaurav11","abuseCount":"3","videoShareCount":"0","isAlreadyLiked":"YES"}],

"totalDataRequested":"2",
"totalDataSent":"2",
"responseCode":"4060",
"responseDescription":"Home service sent successfully."
}

JsonToObject.java

package com;

import java.io.IOException;

import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;


public class JsonToObject{

 public CustomBean jsonConvertor(String jsonString)
 {
  JsonFactory factory = new JsonFactory();
  ObjectMapper mapper = new ObjectMapper(factory);
  try 
  {
   CustomBean customBean = mapper.readValue(jsonString, CustomBean.class);
   
   return customBean;
  } catch (JsonParseException e) {
   e.printStackTrace();
  } catch (JsonMappingException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }
   return new CustomBean();
 }
}

CustomBean

package com;

import java.util.List;

public class CustomBean {

 private List recentVideosList;
 private List videoOfTheDayList;
 private List challengeOfTheDayList;
 private String totalDataRequested;
 private String totalDataSent;
 private String responseCode;
 private String responseDescription;
 
 public List getRecentVideosList() {
  return recentVideosList;
 }
 public void setRecentVideosList(List recentVideosList) {
  this.recentVideosList = recentVideosList;
 }
 public List getVideoOfTheDayList() {
  return videoOfTheDayList;
 }
 public void setVideoOfTheDayList(List videoOfTheDayList) {
  this.videoOfTheDayList = videoOfTheDayList;
 }
 public List getChallengeOfTheDayList() {
  return challengeOfTheDayList;
 }
 public void setChallengeOfTheDayList(
   List challengeOfTheDayList) {
  this.challengeOfTheDayList = challengeOfTheDayList;
 }
 public String getTotalDataRequested() {
  return totalDataRequested;
 }
 public void setTotalDataRequested(String totalDataRequested) {
  this.totalDataRequested = totalDataRequested;
 }
 public String getTotalDataSent() {
  return totalDataSent;
 }
 public void setTotalDataSent(String totalDataSent) {
  this.totalDataSent = totalDataSent;
 }
 public String getResponseCode() {
  return responseCode;
 }
 public void setResponseCode(String responseCode) {
  this.responseCode = responseCode;
 }
 public String getResponseDescription() {
  return responseDescription;
 }
 public void setResponseDescription(String responseDescription) {
  this.responseDescription = responseDescription;
 }
 
}


Read More...

Tuesday 2 April 2013

Why String is immutable or final in Java

Leave a Comment

1) Imagine StringPool facility without making string immutable , its not possible at all because in case of string pool one string object/literal e.g. "Test" has referenced by many reference variables , so if any one of them change the value others will be automatically gets affected i.e. lets say

String A = "Test"
String B = "Test"

Now String B called "Test".toUpperCase() which change the same object into "TEST" , so A will also be "TEST" which is not desirable.

2)String has been widely used as parameter for many Java classes e.g. for opening network connection, you can pass hostname and port number as string , you can pass database URL as string for opening database connection, you can open any file in Java by passing name of file as argument to File I/O classes.

In case, if String is not immutable, this would lead serious security threat , I mean some one can access to any file for which he has authorization, and then can change the file name either deliberately or accidentally and gain access of those file. Because of immutability, you don't need to worry about those kind of threats

3)Since String is immutable it can safely shared between many threads ,which is very important for multithreaded programming and to avoid any synchronization issues in Java, Immutability also makes String instance thread-safe in Java, means you don't need to synchronize String operation externally.

4) Another reason of Why String is immutable in Java is to allow String to cache its hashcode , being immutable String in Java caches its hashcode, and do not calculate every time we call hashcode method of String, which makes it very fast as hashmap key to be used in hashmap in Java.

Read More...

Immutable Class and Object in Java

Leave a Comment

Immutable objects are those, whose state can not be changed once created.


Immutable object  offers several benefits in multi-threaded programming and it’s a great choice to achieve thread safety in Java code.



For e.g. java.lang.String, once created can not be modified e.g. trim, uppercase, lowercase. All modification in String result in new object,


Here are few rules, which helps to make a class immutable in Java :

1. State of immutable object can not be modified after construction, any modification should result in new immutable object.
2. All fields of Immutable class should be final.
3. Object must be properly constructed i.e. object reference must not leak during construction process.
4. Object should be final in order to restrict sub-class for altering immutability of parent class.

you can still create immutable object by violating few rules, like String has its hashcode in non final field, but its always guaranteed to be same. No matter how many times you calculate it, because it’s calculated from final fields, which is guaranteed to be same. This required a deep knowledge of Java memory model, and can create subtle race conditions if not addressed properly. 

This Java class is immutable, because its state can not be changed once created. You can see that all of it’s fields are final. This is one of the most simple way of creating immutable class in Java, where all fields of class also remains immutable like String in above case.
public final class Contacts {

    private final String name;
    private final String mobile;

    public Contacts(String name, String mobile) {
        this.name = name;
        this.mobile = mobile;
    }
  
    public String getName(){
        return name;
    }
  
    public String getMobile(){
        return mobile;
    }
}

Here is another example of making a class immutable in Java, which includes mutable member variable.
public final class ImmutableReminder{
    private final Date remindingDate;
  
    public ImmutableReminder (Date remindingDate) {
        if(remindingDate.getTime() < System.currentTimeMillis()){
            throw new IllegalArgumentException("Can not set reminder” +
                        “ for past time: " + remindingDate);
        }
        this.remindingDate = new Date(remindingDate.getTime());
    }
  
    public Date getRemindingDate() {
        return (Date) remindingDate.clone();
    }
}

In above example of creating immutable class, Date is a mutable object. If getRemindingDate() returns actual Date object than despite remindingDate being final variable, internals of Date can be modified by client code. By returning clone() or copy of remindingDate, we avoid that danger and preserves immutability of class.
Read More...

System.out.println()

Leave a Comment
Here is what the different pieces of System.out.println() actually look like: 

//the System class belongs to java.lang package 
class System { 
public static final PrintStream out; 
//... 
} 

//the Prinstream class belongs to java.io package 
class PrintStream{ 
public void println(); 
//... 
} 

Read More...

How to convert Char to String in Java with Example

Leave a Comment
1: Character.toString

Character class provides a convenient toString() method which takes a character and return its String equivalent. toString() is static method in Character class and can be accessed using class name like Character.toString(). here is an example of converting char to String using Character.toString():

char ch = 'U';
String charToString = Character.toString(ch);

2: String concatenation operator

In Java + can be used to concatenate String but it can also concatenate an String and a character and can result another String. This is another shortcut you can use to convert Character into String in Java. here is an example of converting character to String in Java:


char ch = 'U';
String str = "" + ch;

3: using Anonymous Array

Anonymous array in Java can be used to wrap a single character into a char array and than passing that array into String constructor. a new String will be created from that character.


char ch = 'U';
String fromChar = new String(new char[]{ch});


4: using String.valueOf()

char ch = 'U';
String valueOfchar = String.valueOf(ch);

public class CharToStringExample {

       public static void main(String args[]) {
              char ch = 'U';

              // char to string using Character class
              String charToString = Character.toString(ch);
              System.out.println("Converting Char to String using Character class: " + charToString);

              // char to String using String concatenation
              String str = "" + ch;
              System.out.println("Converting Char to String using String concatenation: " + str);

              // char to String using anonymous array
              String fromChar = new String(new char[] { ch });
              System.out.println("Converting Char to String using anonymous array: " + fromChar);

              // char to String using String valueOf
              String valueOfchar = String.valueOf(ch);
              System.out.println("Converting Char to String using String valueOf: " + valueOfchar);

       }

}

Output:
Converting Char to String using Character class: U
Converting Char to String using String concatenation: U
Converting Char to String using anonymous array: U
Converting Char to String using String valueOf: U

Read More...

String vs StringBuffer vs StringBuilder in Java

Leave a Comment
Some fundamental properties of String Class in Java

  •  String is immutable in Java.Immutability offers lot of benefit to the String class e.g. his hashcode value can be cached which makes it a faster hashmap key and one of the reason why String is a popular key in HashMap. Because String is final it can be safely shared between multiple threads  without any extra synchronization. 
  • when we represent string in double quotes like "abcd" they are referred as String literal and String literals are created in String pools. When you compare two String literals using equality operator "==" it returns true because they are actually same instance of String. Anyway comparing object with equality operator is bad practice in Java and you should always use equals method to check equality.
  • "+" operator is overloaded for String and used to concatenated two string. Internally "+" operation is implemented using either StringBuffer or StringBuilder.
  • Strings are backed up by character Array and represented in UTF-16 format. By the way this behavior can cause memory leak in String because same character array is shared between source String and SubString which can prevent source String from being garbage collected.
  • String class overrides equals() and hashcode() method and two Strings are considered to be equal if they contain exactly same character in same order and in same case. If you want ignore case comparison of two strings consider using equalsIgnoreCase() method.
  • toString() method provides String representation of any object and its declared in Object class and its recommended for other class to implement this and provide String representation.
  • In Java you can create String from char array, byte array, another string, from StringBuffer or from StringBuilder. Java String class provides constructor for all of these.
Problem with String in Java

One of its biggest strength Immutability is also biggest problem of Java String if not used correctly. many a times we create a String and then perform a lot of operation on them e.g. converting string into uppercase, lowercase , getting substring out of it , concatenating with other string etc. Since String is an immutable class every time a new String is created and older one is discarded which creates lots of temporary garbage in heap. If String are created using String literal they remain in String pool. To resolve this problem Java provides us two Classes StringBuffer and StringBuilder. String Buffer is an older class but StringBuilder is relatively new and added in JDK 5.


Differences between String and StringBuffer

Main difference between String and StringBuffer is String is immutable while StringBuffer is mutable means you can modify a StringBuffer object once you created it without creating any new object. This mutable property makes StringBuffer an ideal choice for dealing with Strings in Java. You can convert a StringBuffer into String by its toString() method.

Difference between StringBuilder and StringBuffer
StringBuffer is very good with mutable String but it has one disadvantage all its public methods are synchronized which makes it thread-safe but same time slow. In JDK 5 they provided similar class called StringBuilder in Java which is a copy of StringBuffer but without synchronization. Try to use StringBuilder whenever possible it performs better in most of cases than StringBuffer class. You can also use "+" for concatenating two string because "+" operation is internal implemented using either StringBuffer or StringBuilder in Java. If you see StringBuilder vs StringBuffer you will find that they are exactly similar and all API methods applicable to StringBuffer are also applicable to StringBuilder in Java. On the other hand String vs StringBuffer is completely different and there API is also completely different, same is true for StringBuilder vs String.



1) String is immutable while StringBuffer and StringBuilder is mutable object.

2) StringBuffer is synchronized while StringBuilder is not which makes StringBuilder faster than StringBuffer.

3) Concatenation operator "+" is internal implemented using either StringBuffer or StringBuilder.

4) Use String if you require immutability, use Stringbuffer in java if you need mutable + thread-safety and use StringBuilder in Java if you require mutable + without thread-safety.



Read More...

How Synchronization works in Java ?

Leave a Comment

Synchronization
Synchronization in Java is an important concept since Java is a multi-threaded language where multiple threads run in parallel to complete program execution. In multi-threaded environment synchronization of java object or synchronization of java class becomes extremely important. Synchronization in Java is possible by using java keyword "synchronized" and "volatile”. Concurrent access of shared objects in Java introduces to kind of errors: thread interference and memory consistency errors and to avoid these errors you need to properly synchronize your java object to allow mutual exclusive access of critical section to two threads.

Why in Java
If your code is executing in multi-threaded environment you need synchronization for objects which are shared among multiple threads to avoid any corruption of state or any kind of unexpected behavior. Synchronization in Java will only be needed if shared object is mutable. if your shared object is read only or immutable object you don't need synchronization despite running multiple threads. Same is true with what threads are doing with object if all the threads are only reading value then you don't require synchronization in java. JVM guarantees that Java synchronized code will only be executed by one thread at a time.
  • synchronized keyword in java provides locking which ensures mutual exclusive access of shared resource and prevent data race.
  • synchronized keyword involve locking and unlocking. before entering into synchronized method or block thread needs to acquire the lock at this point it reads data from main memory than cache and when it release the lock it flushes write operation into main memory which eliminates memory inconsistency errors.
  • You can have both static synchronized method and non static synchronized method and synchronized blocks in java but we can not have synchronized variable in java.
  • Block synchronization in java is preferred over method synchronization in java because by using block synchronization you only need to lock the critical section of code instead of whole method. Since java synchronization comes with cost of performance we need to synchronize only part of code which absolutely needs to be synchronized.

    Example of synchronized method in Java


    Using synchronized keyword along with method is easy just apply synchronized keyword in front of method. What we need to take care is that static synchronized method locked on class object lock and non static synchronized method locks on current object (this). So it’s possible that both static and non static java synchronized method running in parallel.  This is the common mistake a naive developer do while writing java synchronized code.


public class Counter{
private static int count = 0;

public static synchronized int getCount(){
  return count;
}

public synchoronized setCount(int count){
   this.count = count;
}

}


In this example of java synchronization code is not properly synchronized because both getCount() and setCount() are not getting locked on same object and can run in parallel which results in getting incorrect count. Here getCount() will lock in Counter.class object while setCount() will lock on current object (this). To make this code properly synchronized in java you need to either make bothmethod static or non static or use java synchronized block instead of java synchronized method.
Example of synchronized block in Java



public class Singleton{
private static volatile Singleton _instance;

public static Singleton getInstance(){

   if(_instance == null){
            synchronized(Singleton.class){
              if(_instance == null)
              _instance = new Singleton();
            }

   }
   return _instance;

}




This is a classic example of double checked locking in Singleton. In this example of java synchronized code we have made only critical section (part of code which is creating instance of singleton) synchronized and saved some performance because if you make whole method synchronized every call of this method will be blocked while you only need to create instance on first call.

Important points of synchronized keyword in Java

  1. Synchronized keyword in Java is used to provide mutual exclusive access of a shared resource with multiple threads in Java. Synchronization in java guarantees that no two threads can execute a synchronized method which requires same lock simultaneously or concurrently.
  2. You can use java synchronized keyword only on synchronized method or synchronized block.
  3. When ever a thread enters into java synchronized method or block it acquires a lock and whenever it leaves java synchronized method or block it releases the lock. Lock is released even if thread leaves synchronized method after completion or due to any Error or Exception.
  4. Java Thread acquires an object level lock when it enters into an instance synchronized java method and acquires a class level lock when it enters into static synchronized java method.
  5. java synchronized keyword is re-entrant in nature it means if a java synchronized method calls another synchronized method which requires same lock then current thread which is holding lock can enter into that method without acquiring lock.
  6. Java Synchronization will throw NullPointerException if object used in java synchronized block is null e.g. synchronized (myInstance) will throws NullPointerException if myInstance is null.
  7. One Major disadvantage of java synchronized keyword is that it doesn't allow concurrent read which you can implement using java.util.concurrent.locks.ReentrantLock.
  8. One limitation of java synchronized keyword is that it can only be used to control access of shared object within the same JVM. If you have more than one JVM and need to synchronized access to a shared file system or database, the java synchronized keyword is not at all sufficient. You need to implement a kind of global lock for that.
  9. Java synchronized keyword incurs performance cost. Synchronized method in Java is very slow and can degrade performance. So use synchronization in java when it absolutely requires and consider using java synchronized block for synchronizing critical section only.
  10. Its possible that both static synchronized and non static synchronized method can run simultaneously or concurrently because they lock on different object.
  11. Java synchronized code could result in deadlock or starvation while accessing by multiple thread if synchronization is not implemented correctly.
  12. You cannot apply java synchronized keyword with variables and can not use java volatile keyword with method.
  13. java synchronized keyword also synchronizes memory. In fact java synchronized synchronizes the whole of thread memory with main memory.
  14. Do not synchronize on non final field on synchronized block in Java. because reference of non final field may change any time and then different thread might synchronizing on different objects i.e. no synchronization at all. example of synchronizing on non final field :
    private String lock = new String("lock");
synchronized(lock){
System.out.println("locking on :"  + lock);
}

16. Its not recommended to use String object as lock in java synchronized block because string is immutable object and literal string and interned string gets stored in String pool. so by any chance if any other part of code or any third party library used same String as there lock then they both will be locked on same object despite being completely unrelated which could result in unexpected behavior and bad performance. instead of String object its advised to use new Object() for Synchronization in Java on synchronized block.
private static final String LOCK = "lock";   //not recommended
private static final Object OBJ_LOCK = new Object(); //better

public void process() {
   synchronized(LOCK) {
      ........
   }
}
Read More...

Why wait, notify and notifyAll is defined in Object Class and not on Thread

Leave a Comment

1) Wait and notify is not just normal methods or synchronization utility, more than that they are communication mechanism between two threads in Java. And Object class is correct place to make them available for every object if this mechanism is not available via any java keyword like synchronized. Remember synchronized and wait notify are two different area and don’t confuse that they are same or related. Synchronized is to provide mutual exclusion and ensuring thread safety of Java class like race condition while wait and notify are communication mechanism between two thread.

2 ) Locks are made available on per Object basis, which is another reason wait and notify is declared in Object class rather then Thread class.

3) In Java in order to enter critical section of code, Threads needs lock and they wait for lock, they don't know which threads holds lock instead they just know the lock is hold by some thread and they should wait for lock instead of knowing which thread is inside the synchronized block and asking them to release lock. this analogy fits with wait and notify being on object class rather than thread in Java.

Read More...

Difference between Wait and Sleep in Java

Leave a Comment



  1. Main difference between wait and sleep is that wait() method release the acquired lock when thread is waiting while Thread.sleep() method keeps the lock or monitor even if thread is waiting.
  2. wait method in java should be called from synchronized method or block while there is no such requirement for sleep() method.
  3. Thread.sleep() method is a static method and applies on current thread, while wait() is an instance specific method and only got wake up if some other thread calls notify method on same object.
  4. in case of sleep, sleeping thread immediately goes to Runnable state after waking up while in case of wait, waiting thread first acquires the lock and then goes into Runnable state.
  5. wait is called on Object while sleep is called on Thread.
  6. wait is called from synchronized context only while sleep can be called without synchronized block.
  7. Thread.sleep() method is a static method and always puts current thread on sleep.
So based upon your need if you require a specified second of pause use sleep() method or if you want to implement inter-thread communication use wait method.

/*
 * Example of Thread Sleep method in Java
 */
public class SleepTest {
      
       public static void main(String... args){
              System.out.println(Thread.currentThread().getName() + " is going to sleep for 1 Second");
              try {
                     Thread.currentThread().sleep(1000);
              } catch (InterruptedException e) {
                     // TODO Auto-generated catch block
                     e.printStackTrace();
              }
              System.out.println("Main Thread is woken now");
       }

}

Output:
main is going to sleep for 1 Second
Main Thread is woken now

wait example
package defaultt;

public class Customer {
int amount=0;
int flag=0;
public synchronized int withdraw(int amount){
 System.out.println(Thread.currentThread().getName()+" is going to withdraw");
 
       if(flag==0){
        try{
  System.out.println("waiting....");
  wait();
 }catch(Exception e){}
 }
       
 this.amount-=amount;
 System.out.println("withdraw completed");
 return amount;
}

public synchronized void deposit(int amount){
 System.out.println(Thread.currentThread().getName()+" is going to  deposit");
 this.amount+=amount;
 
 notifyAll();
 System.out.println("deposit completed");
        flag=1;
 }


}


package defaultt;

public class Test{
public static void main(String[] args) {
 final Customer c=new Customer();
 
 Thread t1=new Thread(){
  public void run(){
   c.withdraw(5000);
   System.out.println("After withdraw amount is"+c.amount);
  }
 };
 
 Thread t2=new Thread(){
  public void run(){
   c.deposit(9000);
   System.out.println("After deposit amount is "+c.amount);
  }
 };
 
 
 t1.start();
 t2.start();
 
 
}
}

Output:
Thread-0 is going to withdraw
waiting....
Thread-1 is going to  deposit
deposit completed
withdraw completed
After deposit amount is 4000
After withdraw amount is4000
Read More...

Monday 1 April 2013

Is Java 100% object oriented?

Leave a Comment
No, because it has data types that are not objects (such as int and byte).


  • it does not support multiple inheritance directly.But it does so by using the concept of interfaces.
  • Many More...
Read More...

static block in Java

Leave a Comment
which holds piece of code to executed when class is loaded in Java. This is also known as static initialize block as shown in below example.


static {
        String category = "electronic trading system";
        System.out.println("example of static block in java");
    }

Beware that if your static initialize block throws Exception than you may get java.lang.NoClassDefFoundError when you try to access the class which failed to load. 
Read More...

How to access non static variable inside static method or block

Leave a Comment

You access non static variable inside static method or block by creating an instance of class
and using that instance to reference instance variable.
public class Test {

    private int count=0;
    public static void main(String args[]) throws IOException {
        StaticTest test = new StaticTest(); //accessing static variable by creating an instance of class
        test.count++;
    }  
 }

Read More...

Why non-static variable cannot be referenced from a static context?

Leave a Comment
Lets See This Example.
public class Test {

    private int count=0;
    public static void main(String args[]) throws IOException {
        count++; //compiler error: non-static variable count cannot be referenced from a static context
    }
}
Static variable in Java belongs to Class and its value remains same for all instance. static variable initialized when class is loaded into JVM on the other hand instance variable has different value for each instances and they get created when instance of an object is created either by using new() operator or using reflection like Class.newInstance().

 So if you try to access a non static variable without any instance compiler will complain because those variables are not yet created and they don't have any existence until an instance is created and they are associated with any instance
Read More...