Showing posts with label String. Show all posts

How to convert String to Date in Java?

In our day-to-day programming we deal with different types of date format. And converting String date to Java date is one of the regular task we all do. Sometimes its hard for us to find the exact date pattern for our date. So I thought of putting all possible date format and its pattern in one article.

Following example covers all major date format pattern. However If I missed any important date pattern then do comment in article and I'll include it. Here in example, there is Date in String format with its exact pattern to convert it into java.util.Date.

Note: There are N number of possible date formats and patterns. Here in example I gave you standard formats, you can make your own format from this example like (25-12-2015 12 - dd-MM-yyyy HH), etc...

Source code (StringToDateExample.java)
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Example: String to Date in Java
 * @author javaQuery
 * @date 9th December, 2015
 * @Github: https://github.com/javaquery/Examples
 */
public class StringToDateExample {

    public static void main(String[] args) throws ParseException {
        /**
         * parseDate(StringDate, PatternToParse) 
         */
        parseDate("20151225", "yyyyMMdd");
        parseDate("2015.12.25", "yyyy.MM.dd");
        parseDate("2015-12-25", "yyyy-MM-dd");
        parseDate("2015/12/25", "yyyy/MM/dd");
        
        parseDate("25122015", "ddMMyyyy");
        parseDate("25.12.2015", "dd.MM.yyyy");
        parseDate("25-12-2015", "dd-MM-yyyy");
        parseDate("25/12/2015", "dd/MM/yyyy");

        parseDate("25/12/2015 15:10:05", "dd/MM/yyyy HH:mm:ss");        
        parseDate("2015-12-25 15:10:05", "yyyy-MM-dd HH:mm:ss");
        parseDate("2015-12-25 15:10", "yyyy-MM-dd HH:mm");
        parseDate("2015-12-25T15:20:25Z", "yyyy-MM-dd'T'HH:mm:ss'Z'");
        parseDate("2015-12-25 15:10Z", "yyyy-MM-dd HH:mm'Z'");
        parseDate("2013-12-25T15:25:30-05:00", "yyyy-MM-dd'T'HH:mm:ssXXX");
        parseDate("2015-06-26T05:27:05.000Z", "yyyy-MM-dd'T'HH:mm:ss.'000Z'");
    }

    /**
     * Method to parse StringDate to {@link Date}.
     * @param strDate
     * @param pattern
     * @return {@link Date}
     */
    public static Date parseDate(String strDate, String pattern) {
        /* Return object of Date */
        Date date = null;
        /* Get DateFormatter for given pattern */
        DateFormat dateFormat = new SimpleDateFormat(pattern);
        try {
            /* Parse String to java.util.Date */
            date = dateFormat.parse(strDate);
        } catch (ParseException ex) {
            ex.printStackTrace();
            date = null;
        }
        /* Print the StringDate, Pattern and converted java Date */
        System.out.println("Date: " + strDate + ", Pattern: " + pattern + " -> java.util.Date[" + date + "]");
        return date;
    }
}

Output
Date: 20151225, Pattern: yyyyMMdd -> java.util.Date[Fri Dec 25 00:00:00 IST 2015]
Date: 2015.12.25, Pattern: yyyy.MM.dd -> java.util.Date[Fri Dec 25 00:00:00 IST 2015]
Date: 2015-12-25, Pattern: yyyy-MM-dd -> java.util.Date[Fri Dec 25 00:00:00 IST 2015]
Date: 2015/12/25, Pattern: yyyy/MM/dd -> java.util.Date[Fri Dec 25 00:00:00 IST 2015]
Date: 25122015, Pattern: ddMMyyyy -> java.util.Date[Fri Dec 25 00:00:00 IST 2015]
Date: 25.12.2015, Pattern: dd.MM.yyyy -> java.util.Date[Fri Dec 25 00:00:00 IST 2015]
Date: 25-12-2015, Pattern: dd-MM-yyyy -> java.util.Date[Fri Dec 25 00:00:00 IST 2015]
Date: 25/12/2015, Pattern: dd/MM/yyyy -> java.util.Date[Fri Dec 25 00:00:00 IST 2015]
Date: 25/12/2015 15:10:05, Pattern: dd/MM/yyyy HH:mm:ss -> java.util.Date[Fri Dec 25 15:10:05 IST 2015]
Date: 2015-12-25 15:10:05, Pattern: yyyy-MM-dd HH:mm:ss -> java.util.Date[Fri Dec 25 15:10:05 IST 2015]
Date: 2015-12-25 15:10, Pattern: yyyy-MM-dd HH:mm -> java.util.Date[Fri Dec 25 15:10:00 IST 2015]
Date: 2015-12-25T15:20:25Z, Pattern: yyyy-MM-dd'T'HH:mm:ss'Z' -> java.util.Date[Fri Dec 25 15:20:25 IST 2015]
Date: 2015-12-25 15:10Z, Pattern: yyyy-MM-dd HH:mm'Z' -> java.util.Date[Fri Dec 25 15:10:00 IST 2015]
Date: 2013-12-25T15:25:30-05:00, Pattern: yyyy-MM-dd'T'HH:mm:ssXXX -> java.util.Date[Thu Dec 26 01:55:30 IST 2013]
Date: 2015-06-26T05:27:05.000Z, Pattern: yyyy-MM-dd'T'HH:mm:ss.'000Z' -> java.util.Date[Fri Jun 26 05:27:05 IST 2015]

How to convert String to Integer in Java?

Integer.parseInt(String s)
You can convert any String that represents number into signed decimal integer by passing String as an argument to method Integer.parseInt(String s). Following excerpt shows how you can convert String to Integer in Java.
public class StringToInteger {
    public static void main(String[] args) {
        String strNumber = "123";
        System.out.println("Number in String: " + strNumber);
        
        /**
         * javadoc:
         * Parses the string argument as a signed decimal integer. 
         * The characters in the string must all be decimal digits, except that the first character may be an ASCII minus sign '-' ('\u002D') to indicate a negative value. 
         * The resulting integer value is returned, exactly as if the argument and the radix 10 were given as arguments to the Integer.parseInt(java.lang.String, int) method.
         * 
         * Throws: NumberFormatException - if the string cannot be parsed as an integer. 
         */
        int intValue = Integer.parseInt(strNumber);
        System.out.println("int value: " + intValue);
        
        /* Increment value by 1 */
        intValue = intValue + 1;
        System.out.println("int value incremented: " + intValue);
    }
}

Output
Number in String: 123
int value: 123
int value increment: 124

Radix
Following table represent the numbering system in mathematics. Read more about it on wikipedia.
Base/Radix Name
10 Decimal system
12 DuoDecimal(dozenal) system
2 Binary numeral system
16 HexaDecimal system
8 Octal system
60 Sexagesimal system
64 MIME Base64
85 PostScript ASCII85
256 byte


What is the difference between String.valueOf() and toString() in Java?

Java String

Each piece of code represents the expertise of developer. You can judge the developer by his/her code. One faulty piece of code may lead to critical damage. So write your code by understanding the fundamental not because someone created and we've to use it.

String.valueOf(argument)
String.valueOf() is null safe. You can avoid java.lang.NullPointerException by using it. It returns "null" String when Object is null. Let explore the source code of String.valueOf().
/* Original Source code */
public static String valueOf(Object obj) {
   return (obj == null) ? "null" : obj.toString();
}

toString()
toString() can cause the java.lang.NullPointerException. It throws java.lang.NullPointerException when Object is null and also terminate the execution of program in case its not handled properly.


Example
public class StringExample {

   public static void main(String[] args) {
      Object obj = "Hello World!";
      System.out.println("String.valueOf(): " + String.valueOf(obj));
      System.out.println("toString(): " + obj.toString());
  
      obj = null;
      System.out.println("String.valueOf(): " + String.valueOf(obj));
      System.out.println("toString(): " + obj.toString());
   }
}

Output
String.valueOf(): Hello World!
toString(): Hello World!
String.valueOf(): null
Exception in thread "main" java.lang.NullPointerException
 at javaQuery.core.StringExample.main(StringExample.java:14)


Top 10 String interview question in Java

Top 10 String interview question in Java

What is String pool in Java?
Its the special area in Java heap to store the String literals like "javaQuery". When you create new String JVM first checks String in Pool, Its its available in Pool then it'll return the same object from Pool. If you create String using
new String("javaQuery") then it'll create the same object in Java heap not in String pool.


Why String is immutable or final in Java?
String objects are cached in String Pool and shared between multiple thread so it will lead to risk of value changed by one thread will affect value of other thread. This is one of the popular question in asked in Java interviews. This is explained with example and diagram Read more >>


What is the difference between str.equals("Vicky") and "Vicky".equals(str) in Java?
- name.equals("Vicky") Compare unknown value(name) with known value("Vicky").
- "Vicky".equals(name) Compare known value("Vicky") with unknown value(name) and its null safe. This is used to avoid java.lang.NullPointerException. Read more >>


What will be the output of following program? or Comparing two Strings in Java.
String str = "abc";
String str1 = "abc";
String str2 = new String("abc");

/**
 * '==' will compare the reference of two String.
 * str == str1 both points to same String in String Pool.
 */
System.out.println(str == str1); // true

/**
 * When we create String object using new String("abc"); then object will be created in Heap.
 * str belongs to String Pool and str2 belongs to Heap and they are not equal.
 */
System.out.println(str == str2); // false

/**
 * .equals() used with String compare the value of both String and they are equal.
 */
System.out.println(str.equals(str2)); //true

String vs StringBuilder vs StringBuffer
- String: When we have String that keeps changing then we have to use StringBuilder or StringBuffer and String is immutable.
- StringBuilder: Its fast compare to String and StringBuffer. However its not thread safe. StringBuilder is mutable.
- StringBuffer: Its slow compare to StringBuilder as its thread safe. StringBuffer is mutable.


How to reverse the String in Java? or How to check String is Palindrome or not in Java?
We can use StringBuilder.reverse() or StringBuffer.reverse() to reverse the String. Read more >>


How to convert String to char[] array and char[] array to String in Java?
- String to char[]: String.toCharArray()
- char[] to String:  String.valueOf(char[] data)
Read more >>


Why String is not good choice to store the password?
String is immutable, It means once you create the String it'll be available in memory for a long time. If one has access to memory dump then he/she can read the password from memory. char[] array is good choice for storing the password because you can wipe out the character array from memory.


How to move String object from Heap to String Pool?
String.intern() is used to move String object from Heap to String Pool.


Does String is thread-safe in Java?
Yes it it. String is immutable and we can't change value of String so it can be used in multi-threaded environment.


How to convert String to char[] array and char[] array to String in Java?

String to char array in Java

One of the rare question asked in Java interview however its worth knowing the basics of String.

Source Code
public class StringCharArray {
    public static void main(String[] args) {
        String str = "javaQuery";
        
        /* Conver String to char[] array */
        char[] charArray = str.toCharArray();
        
        /* Print the char[] array */
        System.out.println("String to char[]:");
        for(char ch : charArray){
            System.out.println(ch);
        }
        
        /* Convert char[] array to String */
        String strFromCharArray = String.valueOf(charArray);
        
        System.out.println("------------------------");
        
        /* Print the String */
        System.out.println("char[] to String: "+strFromCharArray);
    }
}

Output
String to char[]:
j
a
v
a
Q
u
e
r
y
------------------------
char[] to String: javaQuery

What is the difference between replace and replaceAll in Java?


People out there have misconception about replace and replaceAll. I was having random discussion with my colleague he said replace is used to replace first occurrence of Character/String in String and replaceAll used to replace all occurrence of Character/String in String.

For those who has misconception about replace and replaceAll
replace: It will replace all occurrence of Character/String matched in String. replace can't process Regular Expression.
replaceAll: It will replace all occurrence of Character/String matched in String. replaceAll can process Regular Expression.

Source Code
public class ReplaceExample {
    public static void main(String[] args) {
        String str = "@aa @bx @ca @ax";
        System.out.println("Original String: "+str);
        System.out.println("------------------------");
        
        /* replace '@a' with 's' */
        System.out.println("replace: "+str.replace("@a", "s"));
        
        /* replace can't process REGULAR EXPRESSION */
        System.out.println("replace(with regexp): "+str.replace("@[a-z]*", "s"));
        
        /**
         * replaceAll can process REGULAR EXPRESSION
         * Replace any String followed by '@'
         */
        System.out.println("replaceAll: "+str.replaceAll("@[a-z]*", "s"));
    }
}

Output
Original String: @aa @bx @ca @ax
------------------------
replace: sa @bx @ca sx
replace(with regexp): @aa @bx @ca @ax
replaceAll: s s s s

How to check String is Palindrome or not in Java?

Palindrome
A palindrome is a word, phrase, number, or other sequence of characters which reads the same backward or forward. Like 121 <-reverse-> 121, aba <-reverse-> aba, etc...

Source Code
public class PalindromeString {

    public static void main(String[] args) {
        String str = "aba";
        PalindromeString objPalindromeString = new PalindromeString();
        System.out.println("Is \"" + str + "\" Palindrome?");
        System.out.println(objPalindromeString.isPalindromeString(str));
    }

    /**
     * @author javaQuery
     * @param str
     * @return {@link boolean}
     * 
     * Method is used to check String is Palindrome or not.
     */
    public boolean isPalindromeString(String str) {
        /* If its null then return false */
        if (str == null) {
            return false;
        }
        /* Use StringBuilder/StringBuffer to reverse the String */
        StringBuilder strBuilder = new StringBuilder(str);
        strBuilder.reverse();
        /* Compare original and reversed String */
        return str.equalsIgnoreCase(strBuilder.toString());
    }
}

Output
Is "aba" Palindrome?
true

Why String is immutable in Java?

String objects are cached in String Pool and shared between multiple thread so it will lead to risk of value changed by one thread will affect value of other thread.

Example
/**
 * Find "abc" in String Pool or create new Object.
 * Say its reference is "R"
 */        
String str = "abc";
/**
 * Find "abc" in String Pool or create new Object.
 * Its already available in String Pool [Reference "R"].
 * This will point the same value in String Pool
 */
String str1 = "abc";
/**
 * Find "abcxyz" in String Pool or create new Object.
 * Now str is pointing only "abcxyz" in String Pool and "str1" is pointing to "abc".
 */
str = str + "xyz";

Graphical Representation

Why String is immutable in Java
Initial State
Why String is immutable in Java
After modification of str
Now consider what happen if String is mutable. When we change value of str by str = str + "xyz". It will also change value of str1.

This is why creator[Lee Boynton, Arthur van Hoff taken from class file] of String class marked String class as final. To make sure no one can override behaviour of String class.

Why String is immutable or final in Java?
As explained in example you can understand the reason behind the immutability of String. To understand it with real world example like...

#1 String is used in simple HelloWorld program and also used in complex program of space so it has to maintain its value.
#2 String is used to pass values between method.
#3 String is used with many other programs like File(IO operation), Network Program, etc...

This is one of the popular Interview question and asked in any interview of java for fresher of experienced. If I missed something important please do share your comments.

What is the difference between str.equals(''Vicky'') and ''Vicky''.equals(str) in Java?

javaQuery


String Comparison
Comparing one string value against another string value either matching same case or ignoring its case. Its much important that How you're comparing Strings.

Source Code
Lets consider following code...
public class CompareString {
    private String Firstname;
    public static void main(String[] args) {
        /* Create an Object of CompareString */
        CompareString objCompareString = new CompareString();
        /* Set null value for Firstname */
        objCompareString.setFirstname(null);
        /* Get value in local variable */
        String name = objCompareString.getFirstname();
        /**
         * Compare string
         * java.lang.NullPointerException will occur in this case
         */
        if (name.equals("Vicky")) {
            System.out.println("Fail");
        }

        /**
         * Compreare string
         * It will handle java.lang.NullPointerException without checking null
         */
        if ("Vicky".equals(name)) {
            System.out.println("Passed");
        }
    }

    /**
     * Getter of Firstname
     * @return 
     */
    public String getFirstname() {
        return Firstname;
    }

    /**
     * Setter of Firstname
     * @param Firstname 
     */
    public void setFirstname(String Firstname) {
        this.Firstname = Firstname;
    }
}

Case 1: name.equals("Vicky") Compare unknown value with known value.
We are comparing name(unknown) value with another string Vicky(known) value. name will be decided based on some database call, calling another method, etc... It may possible you get null value of name and possible chances of java.lang.NullPointerException or you have to check explicitly for null value of name.

Case 2: "Vicky".equals(name) Compare known value with unknown value.
We are comparing Vicky(known) value with another string name(unknown) value. Same way name will be decided based on some database call, calling another method, etc... But equals and equalsIgnoreCase method of String will handle the null value and you don't have to check explicitly for null value of name.


Why "Vicky".equals(name) Compare known value with unknown value handles null.
To understand the core logic I extracted code of equals and equalsIgnoreCase method from String class.
/* Original source code form String class */
public boolean equals(Object anObject) {
 if (this == anObject) {
     return true;
 }
 /* This condition handles null value */
 if (anObject instanceof String) {
     String anotherString = (String)anObject;
     int n = count;
     if (n == anotherString.count) {
  char v1[] = value;
  char v2[] = anotherString.value;
  int i = offset;
  int j = anotherString.offset;
  while (n-- != 0) {
      if (v1[i++] != v2[j++])
   return false;
  }
  return true;
     }
 }
 return false;
}
anObject instanceof String implemented as null instanceof String and because null is not instance of String so It'll return false.
/* Original source code form String class */
public boolean equalsIgnoreCase(String anotherString) {
 return (this == anotherString) ? true : (anotherString != null) && (anotherString.count == count) && regionMatches(true, 0, anotherString, 0, count);
}
(anotherString != null) handles null value.

Interview Question
This is one of the popular question asked in Interviews. Those who knows answer says...

Ordinary Answer: Comparing known value with unknown value handles null.
ExtraOrdinary Answer: Comparing known value with unknown value handles null because null is not instance of String in case of equals and in case of equalsIgnoreCase, it checks the null before comparison.

Conclusion:
Always compare known value with unknown value to handle the null and to avoid the java.lang.NullPointerException.