Friday, 24 May 2013

jstl if/else set forEach if

Leave a Comment
<c:choose>
    <c:when test="${role eq 2}">
       <c:forEach items="${authorityList}" var="value">
         <c:if test="${value == 2}">
            <c:set var="found" value="true"/>
         </c:if>
       </c:forEach>
       <c:if test="${found == 'true'}">
     
       </c:if>
     
    </c:when>
    <c:otherwise>
       
    </c:otherwise>
</c:choose>
Read More...

Friday, 3 May 2013

Find Second Largest Number In Array Without Sorting

Leave a Comment
import java.util.Scanner;

class SecondLargest {
        public static void main(String[] args) {
        	
            int secondlargest = Integer.MIN_VALUE;
            int largest = Integer.MIN_VALUE;
            
            Scanner input = new Scanner(System.in);
            System.out.println("Enter array values: ");
            int arr[] = new int[5];
            for (int i = 0; i < arr.length; i++) 
            {
                arr[i] = input.nextInt();
                
                if (largest < arr[i]) 
                {
                    secondlargest = largest;
                    largest = arr[i];
                }
                
                if (secondlargest < arr[i] && largest != arr[i])
                    secondlargest = arr[i];
            }
            System.out.println("Second Largest number is: " + secondlargest);
        }
    }

Read More...

Thursday, 2 May 2013

ParseInt vs valueOf in Java

Leave a Comment


Both valueOf and parseInt methods are used to convert String to Integer in Java, but there are subtle difference between them. If you look at code of valueOf() method, you will find that internally it calls parseInt() method to convert Integer to String, but it also maintains a pool of Integers from -128 to 127 and if requested integer is in pool, it returns object from pool. Which means two integer objects returned using valueOf() method can be same by equality operator. This caching of Immutable object, does help in reducing garbage and help garbage collector. Another difference between parseInt() and valueOf() method is there return type. valueOf() of java.lang.Integer returns an Integer object, while parseInt() method returns an int primitive. Though, after introducing Autoboxing in Java 1.5, this doesn't count as a difference, but it's worth knowing.




If you look code of parseInt() and valueOf() method from java.lang.Integer class, you will find that actual job of converting String to integer is done by parseInt() method, valueOf() just provide caching of frequently used Integer objects, Here is code snippet from valueOf() method which makes things clear:

public static Integer valueOf(String s) throws NumberFormatException {
        return Integer.valueOf(parseInt(s, 10));
}

This method first calls parseInt() method, in order to convert String to primitive int, and then creates Integer object from that value. You can see it internally maintains an Integer cache. If primitive int is within range of cache, it returns Integer object from pool, otherwise it create a new object.

public static Integer valueOf(int i) {
        if(i >= -128 && i <= IntegerCache.high)
            return IntegerCache.cache[i + 128];
        else
            return new Integer(i);
}

There is always confusion, whether to use parseInt() or valueOf() for converting String to primitive int and java.lang.Integer, I would suggest use parseInt() if you need primitive int and use valueOf() if you need java.lang.Integer objects. Since immutable objects are safe to be pooled and reusing them only reduces load on garbage collector, it's better to use valueOf() if you need Integer object.

Read More...

Recursive Sum In Java

Leave a Comment
public class RecursiveSum {

 public static int sumOfDigits(int number)
 { 
  System.out.println("Called");
  if(number/10 == 0) return number; 
  
  return number%10 + sumOfDigits(number/10); 
 }
 
 public static int sumOfDigitsIterative(int number)
 { 
  int result = 0; 
  while(number != 0)
  {
   result = result + number%10; 
   number = number/10;
     } 
  return result; 
 } 


 public static void main(String[] args) {
  System.out.println(sumOfDigits(3000));
  System.out.println(sumOfDigitsIterative(123));
 }
}

Output:
Called
Called
Called
Called
3
6


Read More...

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...