Various date format conversions


import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class GeneralUtil {

//Date Time Util
public static Timestamp getTimeStamp(String date) throws ParseException {
String DATE_FORMAT = "MM-dd-yyyy";
SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
Date today = dateFormat.parse(date);
Timestamp t1 = new Timestamp(today.getTime());
return t1;
}

public static String getCurrentDateTime(String format) {
DateFormat dateFormat = new SimpleDateFormat(format);
Date date = new Date();
return dateFormat.format(date);
}

public static String getDateMMDDYYY(Timestamp timestamp) {
String dateStr = "";

dateStr = timestamp.toString().substring(0, 10);
return dateStr;
}

public static String getDateFromDBStringMMDDYYYY(String theDate) {
String strOutDt = "";
try {
Date dtTmp = new SimpleDateFormat("yyyy-MM-dd").parse(theDate);
strOutDt = new SimpleDateFormat("MM-dd-yyyy").format(dtTmp);
} catch (ParseException pe) {
}
return strOutDt;
}

// public static void main(String[] args) throws ParseException {
//
public static String getDateFromTimeStamp(Timestamp t) {
String result = "";
try {
Timestamp dateTime = (Timestamp) t;

SimpleDateFormat dateFormat = new SimpleDateFormat("MM-dd-yyyy");
result = dateFormat.format(dateTime);
return result;
} catch (Exception exception) {
}
return result;

}

public static String getDBDateFormat(String dateStr) {
String result = "";
try {
Date dtTmp = new SimpleDateFormat("MM-dd-yyyy").parse(dateStr);
result = new SimpleDateFormat("yyyy-MM-dd").format(dtTmp);
return result;
} catch (Exception exception) {
}
return result;

}

public static double roundTwoDecimals(double d) {
DecimalFormat twoDForm = new DecimalFormat("#.##");
return Double.valueOf(twoDForm.format(d));
}
//End Date Time Util

public static void main(String[] args) throws ParseException {
String str = "11-24-2010";

}
}

Date Format Example2


/*
Output:

on Tue Oct 01 00:00:00 PDT 2013 in Vancouver, B.C.
on Sun Mar 01 00:00:00 PST 1248 in Ottawa, ON
on Mon Jun 06 00:00:00 PST 1323 in Toronto, ON

*/

import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateFormatDemo2 {

public static void main(String[] a) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
String input[] = { "2013-10-01 Vancouver, B.C.",
"1248-03-01 Ottawa, ON",
"1323-06-06 Toronto, ON" };
for (int i = 0; i < input.length; i++) {
ParsePosition pp = new ParsePosition(0);
Date d = formatter.parse(input[i], pp);
if (d == null) {
System.err.println("Invalid date in " + input[i]);
continue;
}
String location = input[i].substring(pp.getIndex());
System.out.println(" on " + d + " in " + location);

}
}
}

Date Format Example


import java.util.*;
import java.text.*;
class DateFormatDemo
{
public static void main(String A[])
{
//String dob="23/12/1998";
//String dob="DEC/23/1998";
String dob="1998-23-12";
//SimpleDateFormat sdf=new SimpleDateFormat("yyyy'/'dd'/'MM");
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
// Date d=null;
try{

Date d=sdf.parse(dob);//01/31/98
System.out.println("Formated Date="+d);
System.out.println("Formated Date="+sdf.format(d));
}
catch(ParseException pe)
{
System.out.println("Parse Exception Is"+pe);
}

}
}

How to validate IP address with regular expression

IP Address Regular Expression Pattern

^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.
([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])$

Description:

^ #start of the line
( # start of group #1
[01]?\\d\\d? # Can be one or two digits. If three digits appear, it must start
either 0 or 1
# e.g ([0-9], [0-9][0-9],[0-1][0-9][0-9])
| # …or
2[0-4]\\d # start with 2, follow by 0-4 and end with any digit (2[0-4][0-9])
| # …or
25[0-5] # start with 2, follow by 5 and end with 0-5 (25[0-5])
) # end of group #2
\. # follow by a dot “.”

…. # repeat with 3 time (3x)
$ #end of the line

Whole combination means , digit from 0 to 255 and follow by a dot “.”, repeat 4 time and ending with no dot “.” Valid IP address format is “0-255.0-255.0-255.0-255″.
Java Regular Expression Example


package com.mkyong.regex;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class IPAddressValidator{

private Pattern pattern;
private Matcher matcher;

private static final String IPADDRESS_PATTERN =
"^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
"([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
"([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
"([01]?\\d\\d?|2[0-4]\\d|25[0-5])$";

public IPAddressValidator(){
pattern = Pattern.compile(IPADDRESS_PATTERN);
}

/**
* Validate ip address with regular expression
* @param ip ip address for validation
* @return true valid ip address, false invalid ip address
*/
public boolean validate(final String ip){
matcher = pattern.matcher(ip);
return matcher.matches();
}
}

IP address that match:

1. “1.1.1.1″, “255.255.255.255″,”192.168.1.1″ ,
2. “10.10.1.1″, “132.254.111.10″, “26.10.2.10″,
3. “127.0.0.1″

IP address that doesn’t match:

1. “10.10.10″ – must have 4 “.”
2. “10.10″ – must have 4 “.”
3. “10″ – must have 4 “.”
4. “a.a.a.a” – only digit is allow
5. “10.0.0.a” – only digit is allow
6. “10.10.10.256″ – digit must between [0-255]
7. “222.222.2.999″ – digit must between [0-255]
8. “999.10.10.20″ – digit must between [0-255]
9. “2222.22.22.22″ – digit must between [0-255]
10. “22.2222.22.2″ – digit must between [0-255]
Unit Test – IPAddressValidator


package com.mkyong.regex;

import org.testng.Assert;
import org.testng.annotations.*;

/**
* IPAddress validator Testing
* @author mkyong
*
*/
public class IPAddressValidatorTest {

private IPAddressValidator ipAddressValidator;

@BeforeClass
public void initData(){
ipAddressValidator = new IPAddressValidator();
}

@DataProvider
public Object[][] ValidIPAddressProvider() {
return new Object[][]{
new Object[] {"1.1.1.1"},new Object[] {"255.255.255.255"},
new Object[] {"192.168.1.1"},new Object[] {"10.10.1.1"},
new Object[] {"132.254.111.10"},new Object[] {"26.10.2.10"},
new Object[] {"127.0.0.1"}
};
}

@DataProvider
public Object[][] InvalidIPAddressProvider() {
return new Object[][]{
new Object[] {"10.10.10"},new Object[] {"10.10"},
new Object[] {"10"},new Object[] {"a.a.a.a"},
new Object[] {"10.0.0.a"},new Object[] {"10.10.10.256"},
new Object[] {"222.222.2.999"},new Object[] {"999.10.10.20"},
new Object[] {"2222.22.22.22"},new Object[] {"22.2222.22.2"},
new Object[] {"10.10.10"},new Object[] {"10.10.10"},
};
}

@Test(dataProvider = "ValidIPAddressProvider")
public void ValidIPAddressTest(String ip) {
boolean valid = ipAddressValidator.validate(ip);
System.out.println("IPAddress is valid : " + ip + " , " + valid);
Assert.assertEquals(true, valid);
}

@Test(dataProvider = "InvalidIPAddressProvider",
dependsOnMethods="ValidIPAddressTest")
public void InValidIPAddressTest(String ip) {
boolean valid = ipAddressValidator.validate(ip);
System.out.println("IPAddress is valid : " + ip + " , " + valid);
Assert.assertEquals(false, valid);
}
}

Unit Test – Result

IPAddress is valid : 1.1.1.1 , true
IPAddress is valid : 255.255.255.255 , true
IPAddress is valid : 192.168.1.1 , true
IPAddress is valid : 10.10.1.1 , true
IPAddress is valid : 132.254.111.10 , true
IPAddress is valid : 26.10.2.10 , true
IPAddress is valid : 127.0.0.1 , true
IPAddress is valid : 10.10.10 , false
IPAddress is valid : 10.10 , false
IPAddress is valid : 10 , false
IPAddress is valid : a.a.a.a , false
IPAddress is valid : 10.0.0.a , false
IPAddress is valid : 10.10.10.256 , false
IPAddress is valid : 222.222.2.999 , false
IPAddress is valid : 999.10.10.20 , false
IPAddress is valid : 2222.22.22.22 , false
IPAddress is valid : 22.2222.22.2 , false
PASSED: ValidIPAddressTest([Ljava.lang.String;@1d4c61c)
PASSED: InValidIPAddressTest([Ljava.lang.String;@116471f)

===============================================
com.mkyong.regex.IPAddressValidatorTest
Tests run: 2, Failures: 0, Skips: 0
===============================================

===============================================
mkyong
Total tests run: 2, Failures: 0, Skips: 0
===============================================

Reference

http://en.wikipedia.org/wiki/IP_address

Text Files Example

This example shows how to manipulate text files in Java. A file named “text.txt” is created and ten lines contaning the string “hello” are written to it. Then the function “readFile()” displays the content of the the created file to the screen


//TextFile.java
//manipulating text files
import java.io.*;
public class TextFile {
String fileName;
TextFile(String fn)
{
fileName = fn;
}
public void createFile()
{
}
public void writeToFile()
{
try{
PrintWriter out = new PrintWriter( new FileWriter( fileName ) );
for(int i = 0; i < 10; i++)
out.println("hello");
out.close();
}
catch(IOException ioe){
ioe.printStackTrace();
}
}
public void readFile()
{
System.out.println("Content of file: " + fileName);
try{
BufferedReader in = new BufferedReader(new FileReader( fileName ));
String line = "";
while((line = in.readLine()) != null)
System.out.println(line);
}
catch(IOException ioe){
ioe.printStackTrace();
}
}
public static void main ( String[] args )
{
TextFile txtFile = new TextFile("text.txt");
txtFile.writeToFile();
txtFile.readFile();
}
}

Extracting Integers from Strings

The following snippet of source code extracts a single digit from a String and converts it to an int. The String.charAt() method takes a zero-based index of the position of the character to be extracted from the String and the Character.digit() method takes the String from which to extract the digit and the radix.

In the example below I pass 0 to the charAt() method since I want the first character extracted and I pass 10 as the radix since I’m working in base 10.

String myString = "3blindmice";
int digit = Character.digit(myString.charAt(0), 10);
System.out.println("Digit: " + digit);

Output: 3

If the position passed to charAt is not a valid position within the String then a java.lang.StringIndexOutOfBoundsException is thrown.

If the radix is not between Character.MIN_RADIX and Character.MAX_RADIX, -1 is returned.

Varargs and Behavior of Method Argument

Varargs and Behavior of Method Arguments

Varargs

Java 5 brings a convenient new construct to Java that lets a method take zero or more arguments of a given primitive or type. It’s call variable arguments or varargs. In this article we’ll deal with some questions that the introduction of varargs brings up regarding the behavior of method arguments.

A varargs method can be called with zero, one or many individual arguments or with a single array. After the method is called, the arguments are accessed internally using the familiar square brackets array syntax. It looks like this:

public class BasicVarargs {
    public static void main(String[] args) {
        myMethod(); // zero arguments are fine
        myMethod(0); // one argument is fine
        myMethod(0, 1); // multiple arguments are fine
        myMethod(new int[] {0, 1, 2}); // array of args is fine
    }
    static void myMethod(int... myArgs) {
        System.out.println(myArgs[0]);
        System.out.println(myArgs[1]);
        // etc
    }
}

The Issue

This raises a significant question if you’re taking the Sun Certified Java Programmer (SJCP) exam or just want to be knowledgeable about how method parameters are treated. A single argument (whether a primitive or an object reference) cannot be reassigned within a method. Passing a primitive into a method and assigning it a different value will leave the primitive in the calling method unchanged. Passing an object reference into a method and then reassigning the references will, likewise, leave the reference in the calling method unchanged. Objects however, including arrays, have an associated caveat. While the reference to the object cannot be reassigned, the method can use the copy of the reference to alter the content of the object. For a non-array object, this means its instance fields. For an array, this means the primitives or object references at each of its indices. That brings us to our question: If methods with varargs access those arguments as if they were an array, does that mean that they can change the value of a primitive or reassign an object reference that’s held at any given array index? That’s the issue we’re about to explore.

Review of Primitive Argument Behavior

As a quick review, what’s the output of the following?

public class PrimitiveArgBehavior {
	static int myInt = 0;
	public static void main(String[] args) {
	    System.out.println(myInt);
		intMethod(myInt);
		System.out.println(myInt);
	}
	private static void intMethod(int someInt) {
		someInt++;
	}
}

Output:


0
0

myInt remains unchanged. intMethod() works on a copy of myInt and that copy loses scope at the end of intMethod().

Review of Array Reference Argument Behavior

What’s the output of the following?

public class ArrayReferenceArgBehavior {
    static int[] myIntArray = {0};
    public static void main(String[] args) {
        System.out.println(myIntArray[0]);
        intArrayMethod(myIntArray);
        System.out.println(myIntArray[0]);
    }
    static void intArrayMethod(int[] someIntArray) {
        someIntArray = new int[] {1};
    }
}

Output:


0
0

myIntArray remains unchanged. intArrayMethod() works on a copy of the myIntArray reference and that copy loses scope at the end of intArrayMethod(). intArrayMethod() is prevented from reassigning the original reference.

Review of Array Contents Argument Behavior

What’s the output of the following?

public class ArrayContentsArgBehavior {
    static int[] myIntArray = {0};
    public static void main(String[] args) {
        System.out.println(myIntArray[0]);
        intArrayMethod(myIntArray);
        System.out.println(myIntArray[0]);
    }
    static void intArrayMethod(int[] someIntArray) {
        someIntArray[0]++;
    }
}

Output:


0
1

In this case the value did change. While the array reference itself cannot be reassigned to point to another array, the elements of the array can be changed.

Varargs Behavior With Primitives and Arrays

So now we go on to the tricky varargs method. What’s the output of the following?

public class VarArgsBehavior {
	static int myInt = 0;
	static int[] myIntArray = {0};
	public static void main(String[] args) {
		System.out.println("myInt before: " + myInt);
		intVarArgsMethod(myInt);
		System.out.println("myInt after: " + myInt);
		System.out.println("myIntArray before: " + myIntArray[0]);
		intVarArgsMethod(myIntArray);
		System.out.println("myIntArray after: " + myIntArray[0]);
	}
	static void intVarArgsMethod(int... someVarArgsInt) {
		someVarArgsInt[0]++;
	}
}

Now you see why it’s a little unclear? The first call is using an int. The second call is using an array of ints. In either case though, the intvarArgsMethod() is using array syntax to deal with the arguments. So how does it behave when called with individual primitives? Are they treated like individual primitives or like they were placed into an array before the method call?

The output:


myInt before: 0
myInt after: 0
myIntArray before: 0
myIntArray after: 1

Thankfully, the developers that implemented varargs kept the behavior consistent. Even though vararg parameters are accessed in a manner that makes them look like elements of an array, they are still treated in accordance with how they are declared. Kudos to the varargs implementation team. They could very easily have decided to just handle the argument like an array at all times and that would have resulted in some very odd behavior in special cases.

Conclusion

Bottom line, expect varargs to treat an argument in the manner in which it was declared. If a varargs method is called with an array, its arguments will be treated like an array. If called with one or more individual arguments, they will be treated like individual arguments. Varargs respects the manner in which a method is called.

]}A{[


References


Sun Guide to Varargs


SCJP Sun Certified Java Programmer Study Guide

main() Methods in Java

Introduction

The main() method is probably one of the most familar structures in the Java language. It can easily be auto-generated in Eclipse by typing “main” followed by Ctrl-Space and in NetBeans by typing “psvm” followed by a space. It’s the entry point into thousands of applications and while it’s familiar, it also has a few hidden secrets. In this article we’ll look at more than a dozen variations of the main() method. Some will compile and run as expected. Others will not compile at all. Still others will compile and run, but can’t be used as an entry point into an application.

The Methods

Look at the methods below. Which ones will not compile? Which ones will compile, but can’t be used as entry points into an application? Which ones compile and act as you would expect a main method to act?


public static void main(String[] args) {
    System.out.println("Main1!");
}

public static void main(String[] someOtherName) {
    System.out.println("Main2!");
}

public static void main(String... args) {
    System.out.println("Main3!");
}

public static void main(String[] args)
  throws Exception {
    System.out.println("Main4!");
}

static void main(String[] args) {
    System.out.println("Main5!");
}

public void main(String[] args) {
    System.out.println("Main6!");
}

public static void main(String args[]) {
    System.out.println("Main7!");
}

public static void main(String[] args[]) {
    System.out.println("Main8!");
}

public static void main(String[][] args) {
    System.out.println("Main9!");
}

public static void main(String args) {
    System.out.println("Main10!");
}

public static void main(String[] args)
  throws IOException {
    System.out.println("Main11!");
}

static public void main(String[] args) {
    System.out.println("Main12!");
}

public strictfp static void main(String[] args) {
    System.out.println("Main13!");
}

void public static main(String[] args) {
    System.out.println("Main14!");
}

public static void main(int[] args) {
    System.out.println("Main15!");
}

public static void main(String[] args) {
    System.out.println("Main16!");
}

public static void Main(String[] args) {
    System.out.println("Main17!");
}

The Answers



/**
 * Fine.
 *
 * This is the most common form of the main method.
 */
public static void main(String[] args) {
    System.out.println("Main1!");
}

/**
 * Fine.
 *
 * This is the most common form of the main method except
 * that the variable accepting command line arguments has
 * been renamed to someOtherName. The name of the variable
 * is insignificant.
 */
public static void main(String[] someOtherName) {
    System.out.println("Main2!");
}

/**
 * Fine.
 *
 * Varargs form of the main method. New with Java 5.
 */
public static void main(String... args) {
    System.out.println("Main3!");
}

/**
 * Fine.
 *
 * This is the most common form of the main method, except
 * that it throws an exception. This is completely valid.
 */
public static void main(String[] args)
  throws Exception {
    System.out.println("Main4!");
}

/**
 * Compiles, but cannot be executed from the command line.
 *
 * Method must be public.
 *
 * Since the signature doesn't match it's a completely
 * different method that just happens to be called main.
 *
 */
static void main(String[] args) {
    System.out.println("Main5!");
}

/**
 * Compiles, but cannot be executed from the command line.
 *
 * Method must be static.
 *
 * Since the signature doesn't match it's a completely
 * different method that just happens to be called main.
 *
 */
public void main(String[] args) {
    System.out.println("Main6!");
}

/**
 * Fine.
 *
 * This is the most common form of the main method
 * except that the square
 * brackets for the String array have been put beside
 * the variable. This is valid, but many think, harder
 * to read.
 */
public static void main(String args[]) {
    System.out.println("Main7!");
}

/**
 * Although the syntax is strange, this compiles, but
 * cannot be executed from the command line.
 *
 * This is the most common form of the main method, but
 * the square brackets for the args array are beside the
 * type as well as beside the args variable. They should
 * be beside one or the other, not both.
 *
 * While I would have guessed that this would not
 * compile at all, it turns out that this is equivalent
 * to main taking a two-dimensional array as a parameter.
 * String[] args[] is the same as String[][] args or String
 * args[][]. While it's certainly valid for a method to
 * accept a two-dimensional array of Strings, this does
 * not fit the required signature for a main method
 * that is to be invoked from the command line. Attempting
 * to execute this will result in the following error
 * message: Exception in thread "main"
 * java.lang.NoSuchMethodError: main
 *
 */
public static void main(String[] args[]) {
    System.out.println("Main8!");
}

/**
 * Compiles, but cannot be executed from the command line.
 *
 * The main() method needs to accept an array of Strings
 * as a parameter. The method below accepts a
 * two-dimensional array of Strings.
 *
 * Since the signature doesn't match it's a completely
 * different method that just happens to be called main.
 *
 */
public static void main(String[][] args) {
    System.out.println("Main9!");
}

/**
 * Compiles, but cannot be executed from the command
 * line.
 *
 * The main() method needs to accept an array of Strings
 * as a parameter. The method below accepts a single
 * String called args.
 *
 * Since the signature doesn't match it's a completely
 * different method that just happens to be called main.
 *
 */
public static void main(String args) {
    System.out.println("Main10!");
}

/**
 * Fine.
 *
 * Throwing a checked exception, like IOException,
 * is legal.
 *
 */
public static void main(String[] args)
  throws IOException {
    System.out.println("Main11!");
}

/**
 * Fine.
 *
 * This is the most common form of the main method except
 * that static and public keywords are reversed. Their
 * order does not matter.
 *
 */
 static public void main(String[] args) {
    System.out.println("Main12!");
}

/**
 * Fine.
 *
 * It's perfectly acceptable to have a strictfp main
 * method.
 *
 */
public strictfp static void main(String[] args) {
    System.out.println("Main13!");
}

/**
 * Does not compile.
 *
 * The return type (void in this case) must come
 * immediately before the method name.
 *
 */
 void public static main(String[] args) {
    System.out.println("Main14!");
}

/**
 * Compiles, but cannot be run from the command line.
 *
 * The main() method must accept an array of Strings,
 * not ints, as a parameter.
 *
 * Since the signature doesn't match it's a completely
 * different method that just happens to be called main.
 *
 */
public static void main(int[] args) {
    System.out.println("Main15!");
}

/**
 * Fine.
 *
 * This is the most common form of the main method
 * except that there aren't any spaces between the
 * type, the square brackets and the variable name.
 * It's still legal.
 *
 */
public static void main(String[] args) {
    System.out.println("Main16!");
}

/**
 * Compiles, but cannot be run from the command line.
 *
 * The main() method must be all lower case.
 *
 * Since the signature doesn't match it's a completely
 * different method that just happens to be called main.
 *
 */
public static void Main(String[] args) {
    System.out.println("Main17!");
}

There are a few alternate formulations of the method that might come in handy.