Tuesday, March 11, 2014

Static methods in Java

When to make a method static in Java

Making a method static in Java is an important decision . Though, static keyword is one of the fundamental concepts, many times programmers gets confused to make a particular method static or not. In Java programming, main motivation for making a method static is convenience. You can call a static method without creating any object, just by using it's class name. So if you need a method, which you want to call directly by class name, make that method static. Utility classes e.g. java.lang.Math or StringUtils, are good examples of classes, which uses static methods. Before making a method static, you should look into limitation of static methods as well, as you can not override static method in Java. By keeping these properties in mind, we can make few rules, which will help to decidewhen to make a method static in Java and when to use them. In this Java article, we will learn more about benefits and limitation of making a method static, and also see couple of examples of static methods from JDK to learn when and how to use static method in Java.


What does static method do in Java

When you see a static method in Java code, What do you assume? What reasoning and assumptions a reader make, when he sees a static method? This is important to learn to  ensure we are using static method correctly.

1) Static method doesn't modify state of object. Since state of object is maintained as instance variables, anJava doesn't allow non static variables on static context. Modern days IDE like Netbeans also shows static method in italics to differentiate it from other methods.

2) Static method mostly operates on arguments, almost all static method accepts arguments, perform some calculation and return value.

Rules to make a method static in Java
There is no hard and fast, well written rules, to decide when to make a method static or not, But there are few observations based upon experience, which not only help to make a method static but also teaches when to use static method in Java. You should consider making a method static in Java :

1) If a method doesn't modify state of object, or not using any instance variables.
2) You want to call method without creating instance of that class.
3) A method is good candidate of being static, if it only work on arguments provided to it e.g. public int factorial(int number){}, this method only operate on number provided as argument.

4) Utility methods are also good candidate of being static e.g. StringUtils.isEmpty(String text), this a utility method to check if a String is empty or not.

5) If function of method will remain static across class hierarchy e.g. equals() method is not a good candidate of making static because every Class can redefine equality.

When to use static method in Java

How to use static method in JavaNow, we know the benefits and limitation of making a method static in Java, we can see couple of scenarios where we can use static methods. Factory design pattern provides a good use of static method. You can use static method to create instance of a class. Even Effective Java advises about using static factory method, couple of example of these in Java library is creating thread pool from Executors class. Executors provides lots of static methods to create different types of thread pool e.g. public static ExecutorService newCachedThreadPool(), public static ExecutorService newFixedThreadPool(int nThreads) etc. Another interesting use of static methods from JDK is collection classes e.g. Collections and Arrays which provides lot of static utility methods to operate on different kinds of collection. Static method can also be combined with variable arguments to create a collection of explicitly elements e.g. EnumSet.of(E first, E... rest). Apart from these, if you loot at Apache commons lang library, you will find a pattern of utils class e.g. StringUtilsArrayUtils, which provides utility methods to operate on String and arrays. One more interesting use of static method I have seen is valueOf() method inside different value classes e.g. java.lang.String, though this is also an example of factory method, but it's also a nice way to convert one type to another. For example valueOf() can also be used to convert String to Integer in Java. In short, it make sense to use static methods :

1) Along with creational design pattern e.g. Factory and Singleton.
2) As utility method, which operate on arguments.
3) A conversion tool e.g. valueOf().

That's all about when to make a method static in Java. We have seen benefits and limitation of making a method static, and few examples of static methods from JDK. JDK examples will also help you to decide when to use static method in Java
Non-static variable cannot be referenced from a static context.

Example: Wrong code shown below:

public class StaticMethodsExample {
    int a;
    
    StaticMethodsExample(int val) {
        a = val;
    }
     
    public static int doubleValue()
    {
        int result = a*a; // Error,non-static variable can't be referenced from a static context
        return result;
    }
    

}

Read more: http://javarevisited.blogspot.com/2013/07/when-to-make-method-static-in-java.html#ixzz2vd7udsUc

Monday, March 10, 2014

Java Points to remember

Structure of Java Class:

Quick list of the components of a class: (around 7 components)

■ The package statement
■ The import statement
■ Comments
■ Class declarations and definitions
■ Variables
■ Methods
■ Constructors

Package Statement:

All Java classes are part of a package. You can explicitly define a named package; otherwise, it become part of default package which doesn't have name.
  1. The package statement should be the first statement in a source code file for Java class definition.
  2. If the package statement after the class definition, the code won't compile.
  3. A package statement can't be within the class definition.
  4. A class cannot define multiple package statements. The code won't compile.
  5. Package statement must appear exactly once in a class.

Import statement

Typically to use a class or interface from another package, you must use its fully qualified name. Because this become tedious and can make your code difficult to read, you can use the import statement to use the simple name of a class or interface in your code.
  1. import statement follows the package statement but before the class definition.
  2. Reversing this order will result in your code failing to compile.

Comments

Can appear multiple times, and can use at multiple places. 2 types of comments:
a) multiline comments, b) end-of-line comments.

multiline comments: /* ..... */
end-of-line comments: // this is a comment
  1. Multiline comments can contain any special characters (including Unicode characters)

/*
Multi-line comments with
special characters &%^*{}|\|:;"'
?/>.<,!@#$%^&*()
*/


  1.  The text between // and the end of line is treated as a comment.
  2. You can as well define end of line comment within a multiline comment.
Class Declaration

Simplest declaration: keyword class followed by the class name.

Class declaration is composed of the following parts:
  1. Access Modifiers
  2. Non access modifiers
  3. Class name
  4. Name of the base class, if the class is extending another class
  5. All implemented interfaces, if the class is implementing any interfaces
  6. Class body ( fields, constructors, methods) included within pair of curly braces { }

Compulsory                                             Optional
Keyword class                                     Access modifier, such as public
Name of the class                                Nonaccess modifier, such as final
Class body, marked by the opening       Keyword extends together with the name
and closing curly braces, {}                   of the base class
                                                         Keyword implements together with the name
                                                         of the interfaces being implemented


Class Definition

A class is a design used to specify the properties and behavior of an object.
The properties of an object are implemented using variables.
The behavior is implemented using methods.
  1. A class name starts with keyword, class. The keyword is case sensitive, uses lower case letters only.
  2. The state of class is defined using attributes or instance variables.
  3. Each object has its own copy of instance variables. Instance variables are defined within a class but outside all methods in a class.
  4. The behavior is defined using methods. 
  5. A class definition also includes comments and constructors.
Variables

Each object has its own copy of the instance variables.If you change the value of an instance variable for an object, the value for the same named instance variable won’t change for another object.

A single copy of a class variable or static variable is shared by all the objects of a
class.

Methods

Methods are generally used to manipulate instance variables.

A class method or static method is used to work with the static variables.

Constructors

A class constructor is used to create and initialize the objects of a class. 
A class can define multiple constructors that accept different sets of method parameters.(Constructor overloading)

Definition of interfaces in java source code files:

An interface specifies a contract for the classes to implement.
It is a grouping of related methods and constants, but the methods in an interface cannot define any implementation.
  1. The definition of an interface starts with keyword, interface, all lowercase letters.
  2. An interface can define constants and methods.
  3. All variables in an instance are by default final static.
  4. All methods in an instance are public by default.
The classes and interfaces can be defined in any order of occurrence in a Java source code file.

Note:
  1. If you define a public class or interface in a file, its name should match the name of the Java source code file.
  2. A source code file can't define more than one public class or interface. If you try to do, your code won't compile.
  3. A java source code file can define multiple interfaces or classes in a single file.
Executable Java Classes

An executable Java class is a class which, when handed over to the JVM, starts its execution at a particular point in the class—the main method, defined in the class.

The JVM starts executing the code that is defined in the main method.

Typically, an application consists of a number of classes and interfaces that are defined in multiple Java source code files. Of all these files, a programmer designates one of the classes as an executable class.

The main method makes a Java class executable.

main() method signature:

The main method should comply with the following rules:

■ The method must be marked as a public method.
■ The method must be marked as a static method.
■ The name of the method must be main.
■ The return type of this method must be void.
■ The method must accept a method argument of a String array or a variable argument of type String.

public static void main(String[] args) {
....
}

It’s valid to define the method parameter passed to the main method as a variable argument (varargs) of type String:
               public static void main(String... args)

public static void main(String args...) ---> X (wrong).The ellipses(...) should follow the data type.

public static void main(String[] arguments)
public static void main(String[] HelloWorld)
             The names of the method arguments are arguments and HelloWorld, which is acceptable.

To define an array, the square brackets, [], can follow either the variable name or its type. The following is a correct method declaration of the main method:

public static void main(String[] args)
public static void main(String minnieMouse[])

The square brackets, [], can follow either the variable name or its type.

It’s interesting to note that the placement of the keywords public and static can be interchanged, which means that the following are both correct method declarations of the main method:
public static void main(String[] args)
static public void main(String[] args)

Java does not pass class name on command line as an argument to main method.

Java Packages

You can use packages to group together a related set of classes and interfaces. 
Packages also provide access protection and namespace management.

You can create separate packages to define classes for separate projects.


Note: In real-life projects, you will never work with an unpackaged class or interface. Almost all organizations that develop software have strict package-naming rules, which are often documented.

Packaged classes are part of a named package—a namespace—and they’re defined as being part of a package by including a package statement in a class.

All classes and interfaces are packaged.
If you don’t include an explicit package statement in a class or an interface, it’s part of a default package.

A few of important rules about packages:
■ Per Java naming conventions, package names should all be in lowercase.
■ The package and subpackage names are separated using a dot (.).
■ Package names follow the rules defined for valid identifiers in Java.
■ For packaged classes and interfaces, the package statement is the first statement in a Java source file (a .java file). The exception is that comments can appear before or after a package statement.
■ There can be a maximum of one package statement per Java source code file (.java file).
■ All the classes and interfaces defined in a Java source code file will be defined in the same package. There is no way to package classes and interfaces defined within the same Java source code file in different packages.

Directory structure and package hierarchy:

The hierarchy of the packaged classes should match the hierarchy of the directories in which these classes and interfaces are defined in the code.

There isn’t any constraint on the location of the base directory in which the directory structure is defined.



Setting CLASSPATH for packaged classes

To enable the Java Runtime Environment (JRE) to find your classes, add the base directory that contains your packaged Java code to the classpath.

For the above example: 
To enable the JRE to locate the class com.oracle.javacert.associate.ExamQuestion, add the directory C:\ProjectCode to the classpath.

Using import statement, no need to use the fully qualified name of class in different package.

Note:
The import statement doesn’t embed the contents of the imported class in your class, which means that importing more classes doesn’t increase the size of your own class. It lets you use the simple name for a class or interface defined in a separate package.

It’s important to note that you can’t use the import statement to access multiple classes or interfaces with the same names from different packages. For example, the Java API defines the class Date in two commonly used packages: java.util and java.sql. To define variables of these classes in a class, use their fully qualified names with the variable declaration:

class AnnualExam {
         java.util.Date date1;
         java.sql.Date date2;
}

Code to import classes with the same name from different packages won’t compile.
Ex:
import java.util.Date;
import java.sql.Date;
class AnnualExam { }

The above code won't compile.

You can import either a single member of all members(classes and interfaces) of a package using the import statement.

By using the wildcard character, an asterisk (*), you can import all of the public members, classes, and interfaces of a package.

Unlike in C or C++, importing a class doesn’t add to the size of a Java .class file. An import statement enables Java to refer to the imported classes without embedding their source code in the target .class file.

You can’t import classes from a subpackage by using an asterisk in the import statement.
You have to explicitly import subpackages.

If you don't explicitly package your classes or interface, they packaged in default package. This default package is automatically imported in Java classes and interfaces defined within the same directory on your system.

Note: A class from a default package can’t be used in any named packaged class, regardless of whether they are defined within the same directory or not.

Static imports:

You can import an individual static member of a class or all its static members by using the import static statement.

Ex: import static certification.ExamQuestion.*;

For final, it can be assigned different values at run-time when initialized. A final variable must either be assigned a value, or have a value assigned in its constructors.

Final(non-static) variables can differ from object to object!!! But that's only if the initialization is made within the constructor!

Example:

public class FinalFieldsExample {
    public final int a;
    
    FinalFieldsExample(int val) {
        a = val;
    }
    
    public void display()
    {
        System.out.println("The value of final field a is : " + a);
    }
    
    public static void main(String[] args) {
        FinalFieldsExample t1 = new FinalFieldsExample(10);
        t1.display();
        
        FinalFieldsExample t2 = new FinalFieldsExample(20);
        t2.display();        
        
    }
    

}


Serialization in Java

When you are talking about object I/O, serialization comes into picture as well.

ObjectInputStream and ObjectOutputStream classes can be used to read/write serializable objects.

Serializable Interface

Not every object can be written to an output stream. Objects that can be so written are said to be serializable.

A serializable object is an instance of the java.io.Serializable interface, so the object's class must implement Serializable.

The Serializable interface is a marker interface. Since, it has no methods, you don't need to add additional code in your class that implements Serializable.

Implementing Serializable interface enables the Java serialization mechanism to automate the process of storing objects and arrays.

Java provides a built-in mechanism to automate the process of writing objects. This process is referred to as object serialization, which is implemented in ObjectOutputStream.

The process of reading objects is referred to as object deserialization, which is implemented in ObjectInputStream.

Many classes in Java API implement Serializable. Attempting to store an object that does not support the Serializable interface would cause a NotSerializableException.

When a serializable object is stored, the class of the object is encoded; this includes the class name and signature of the class, the value's of the object's instance variables, and the closure of any other objects referenced by the object.

The values of the object's static variables are not stored.

Note:
If an object is an instance of Serializable, but contains nonserializable instance data fields, can it be serialized??
The answer is No. To enable the object to be serialized, mark these data fields with the transient keyword to tell JVM to ignore them when writing the object to an object stream.

public class C implements java.io.Serializable {
          private int v1;
          private static double v2;
          private transient A v3 = new A();
}
class A { } // A is not serializable

When an object of the C class is serialized, only variable v1 is serialized. Variable v2 is
not serialized because it is a static variable, and variable v3 is not serialized because it is
marked transient. If v3 were not marked transient, a java.io.NotSerializableException would occur.

Code Example:
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;
public class ObjectSerializeTest implements Serializable {
    
    private int age;
    private String name;
    
    public void setAge(int ageVal) {
        age = ageVal;
    }
    
    public void setName(String nameVal) {
        name = nameVal;
    }
    
    public void Display() {
        System.out.println("Name: " + name + ", Age: " + age);
    }
    
    public static void main(String[] args) {
        ObjectSerializeTest obj1 = new ObjectSerializeTest();
        obj1.setAge(28);
        obj1.setName("Raghu");        
        
        FileOutputStream fops;
        try {
            fops = new FileOutputStream("raghu.txt");       
            ObjectOutputStream oos = new ObjectOutputStream(fops);
            oos.writeObject(obj1);
        }
        catch (FileNotFoundException ex) {
            Logger.getLogger(ObjectSerializeTest.class.getName()).log(Level.SEVERE, null, ex);
        }
        catch (IOException ex) {
            Logger.getLogger(ObjectSerializeTest.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        FileInputStream fips;
        try {
            fips = new FileInputStream("raghu.txt");
            ObjectInputStream oips = new ObjectInputStream(fips);
            ObjectSerializeTest obj2 = (ObjectSerializeTest)oips.readObject();
            obj2.Display();
        }
        catch (FileNotFoundException ex) {
            Logger.getLogger(ObjectSerializeTest.class.getName()).log(Level.SEVERE, null, ex);
        }
        catch (IOException ex) {
            Logger.getLogger(ObjectSerializeTest.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(ObjectSerializeTest.class.getName()).log(Level.SEVERE, null, ex);
        }        
    }        
}

O/P:
Name: Raghu, Age: 28


Thursday, March 6, 2014

Packaging Classes in Java

A Java application will typically consist of many classes, sometimes hundreds or even thousands of classes.

Becasue Java requires each public class to be part of separate file, you end up with atleast as many files as classes.

This can easily become unmanageable when it comes to working with your classes, finding files, or installing and distributing your application.

Sun has defined a standard packaging mechanism for placing related classes into packages.

Creating a Package:

In a large application or library, Java classes are usually organized into packages.

To put a class into a package, you simply include a package statement, such as
      package com.timothyfisher.book;
at the beginning of class file.

The package statement must be the first non-comment line of class file.

The package name of a class becomes part of its full name. Example, if we had a class named MathBook in the com.timothyfisher.book package, the fully specified class name would be com.timothyfisher.book.MathBook.

Package names also dictate the directory structure in which the class source files are stored.

Each element in the patch name represents a directory.

Example, if your source code root directory is /project/src, the source code for MathBook class would be stored in the following directory path:
project/src/com/timothyfisher/book/

When executing a Java application from the command line using the java executable, you must include the full package name when specifying the main executable class.

For the MathBook example,
java com.timothyfisher.book.MathBook

This command would be executed from the root of the package structure. In this case, the directory above the com directory. In this case, it is /project/src/

While compiling the program to craete class files in a another directory and to create the package hierarchy use the following command:

Example: you have /project/classes directory to hold the class files.

Currently you are at /project/src direcotry and running the following command:

javac -d ..\classes com\timothyfisher\book\MathBook.java

-d option tells to create the hierarchy structure from the specified direcotry.

This will create hierarchy structure as: /project/classes/com/timothyfisher/book and it will have MathBook.class file.

To execute the file, run the execution from /project/classes directory

                    java com.timothyfisher.book.MathBook

or to run from any other directory:

                    java -cp /project/classes com.timothyfisher.book.MathBook

Archiving Classes with JAR

The jar utility is included with the JDK and is used to package groups of classes into a bundle.

Using the jar tool, you can create, update, extract,list and index a JAR file.

For the above example:
To create a jar file, run the following command at /project/classes directory.

                 jar cf project.jar .

Create a jar file to only include class files :

                 jar cf project.jar *.class

The c option tells jar utility to create a new jar file.
The f option is always followed by a file-name specifying the name of the JAR fiel to use.

Applications can also be extracted out of a JAR file.

All classes contained in a JAR file can be easily included on the CLASSPATH when running or compiling a Java application or library.

To include the contents of a JAR file in the CLASSPATH, you simply include the path to the JAR file instead of a directory.

CLASSPATH=.;/projects/classes/project.jar;

Running a program from JAR file:

Running a program from JAR without having a manifest class or main class specified, use the following format:

               java -cp classes\project.jar com.raghu.book.MathBook

Using the java command-line executable, you can execute a Java applicaiton that is packaged in a JAR file. This is with manifest file.

But for this to happen, you must specify the class containing the main() method in the manifest file.

For example, for our example, please create a manifest file with these entries:

Manifest-Version: 1.0
Created-By: 1.7.0_51 (Oracle Corporation)
Main-Class: com.raghu.book.MathBook

Save the manifest file with name: MANIFEST.MF.

Now create the jar file to include the manifest file as well.

             jar cfm project.jar manifest.mf .

This will create the jar and includes the manifest file as well.

Now to run the example:

             java -jar project.jar

This will execute the main() from the specified executable class mentioned in manifest file.

Dates and Times in Java

Java has good built-in support for working with dates and times.

3 primary classes:

java.util.Date - kind of deprecated. Use java.util.Calendar class
java.sql.Date
java.util.Calendar

Many of the methods in the java.util.Date class have become deprecated.

Finding Today's Date:

        Date today = new Date();
        System.out.println("Today is : " + today.toString());
       
        Calendar cal = Calendar.getInstance();
        System.out.println("Today is : " + cal.getTime().toString());

O/p:
Today is : Thu Mar 06 11:36:50 IST 2014
Today is : Thu Mar 06 11:36:50 IST 2014

Converting between Date and Calendar objects

// Date to Calendar conversion
Date myDate = new java.util.Date();
Calendar myCal = Calendar.getInstance();
myCal.setTime(myDate);

// Calendar to Date conversion
Calendar newCal = Calendar.getInstance();
Date newDate = newCal.getTime();

In most Java applications, you'll find uses of both the Date and Calendar classes; thus knowing how to convert from one to the other is something you want to be familiar with.

Best practice is, you create utility methods to perform these conversations so that you can convert from any place in your code with a simple method call.

public static Date calToDate(Calendar cal) {
          return cal.getTime();
}

public static Calendar dateToCal(Date date) {
          Calendar myCal = Calendar.getInstance();
          myCal.setTime(date);
          return myCal;
}


Printing Date/Time in a Given Format:

Java contains formattign classes that can be used to format a date into a desired format.

Example:
        import java.text.SimpleDateFormat;

        Date todaysDate = new Date();
        SimpleDateFormat formatter =

                                      new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss");
        String formattedString = formatter.format(todaysDate);
        System.out.println(formattedString);

o/p:
Thu, 06 Mar 2014 11:57:07

 

Using this format: "EEEE, d-MMM-yyyy HH:mm:ss a", 
o/p :
Thursday, 6-Mar-2014 11:55:07 AM

Using this format: "EEEE, dd-MMMM-yyyy HH:mm:ss a",
o/p:
Thursday, 06-March-2014 11:58:13 AM

Using Pre-defined format strings:

import java.text.DateFormat;

        DateFormat df = DateFormat.getDateInstance();
        String formatString = df.format(todaysDate);
        System.out.println(formatString);
o/p:
Mar 6, 2014


        DateFormat df = DateFormat.getTimeInstance();
        String formatString = df.format(todaysDate);
        System.out.println(formatString);
o/p:
12:02:33 PM


        DateFormat df = DateFormat.getDateTimeInstance();
        String formatString = df.format(todaysDate);
        System.out.println(formatString);
o/p:
Mar 6, 2014 12:02:56 PM

More useful things:

Calendar cal = Calendar.getInstance();

cal.getTimeZone().getDisplayName() - India Standard Time
cal.getTimeZone().toString() - sun.util.calendar.ZoneInfo
                     [id= "Asia/Calcutta", offset=19800000, dstSavings=0, useDaylight=false, transitions=6, lastRule=null]
cal.getTimeZone().getID() - Asia/Calcutta

Parsing Strings into Dates

        String dateString = "Jan 12, 1952 3:30:32 pm";
        DateFormat df = DateFormat.getDateTimeInstance();
        try {
            Date date1 = df.parse(dateString);
            System.out.println("Parsed Date: " + date1.toString());
        } catch (ParseException ex) {
            Logger.getLogger(DatesAndTimes.class.getName()).log(Level.SEVERE, null, ex);
        }

o/p:
Parsed Date: Sat Jan 12 15:30:32 IST 1952

The DateFormat object is used to parse a String and obtain a java.util.Date object.
 The java.sql.Date, java.sql.Time, and java.sql.Timestamp classes contain a static method called valueOf() which can also be used to parse simple date strings of the format "yyyy-mm-dd". This is very useful for converting dates you might use in SQL strings while using JDBC, into Date objects.     String date = "2000-11-01";
    java.sql.Date javaSqlDate = java.sql.Date.valueOf(date);

Adding to or Substracting from a Date or Calendar:

If you are using Date object, the technique for adding or substracting dates is to first convert the object to a long value using the getTime() method of Date object.

The getTime() method returns the time as measured in milliseconds since the epoch. You then perofrm arithmetic on the long values and finally convert back to date objects.

        // date arithmetic using Date objects
        Date date = new Date();
        long time = date.getTime();
        time += 5*24*60*60*1000;
        Date futureDate = new Date(time);

You perform date arithmetic directly on Calendar objects using the add() method.
    
        // date arithmetic using Calendar objects
        Calendar nowCal = Calendar.getInstance();
        nowCal.add(Calendar.DATE, 5);

Difference between Two Dates

        long time1 = date1.getTime();
        long time2 = date2.getTime();
        long diff = time2 – time1;
        System.out.println("Difference in days = " + diff/(1000*60*60*24));

Usecase: Calculating expiry days for an item:

        public static void daysTillExpired(Date expDate) {
            Date currentDate = new Date();
            long expTime = expDate.getTime();
            long currTime = currentDate.getTime();
            long diff = expTime – currTime;
            return diff/(1000*60*60*24);
        }

Comparing Dates

        if (date1.equals(date2)) {
            System.out.println("dates are the same.");
        }
        else {
            if (date1.before(date2)) {
                System.out.println("date1 before date2");
            }
            else {
                System.out.println("date1 after date2");
            }
        }

The dates must be the same down to the millisecond level in order for the equals() method to return true.

The Date class also has an after() method, which is used similar to before() method to determine if the date on which it is called occurs after the date passed in as parameter.

Another useful method for comparing two dates is the compareTo() method of the Date class. It returns an integer value. 0 - indicates dates are equal.

Finding the day of week/month/year or week number:

        Calendar cal = Calendar.getInstance();
        System.out.println("Day of week: " + cal.get(Calendar.DAY_OF_WEEK));
        System.out.println("Month: " + cal.get(Calendar.MONTH));
        System.out.println("Year: " +  cal.get(Calendar.YEAR));
        System.out.println("Week number: " + cal.get(Calendar.WEEK_OF_YEAR));

Calculating elapsed time:

By calculating elapsed time, we can determine how long it takes to do something or how long a process takes to complete.

        long start = System.currentTimeMillis();
        // do some other stuff…
        long end = System.currentTimeMillis();
        long elapsedTime = end – start;

System.currentTimeMillis() method is the time since January 1, 00:00:00, 1970 in milliseconds.

JDK 1.5 adds a nanoTime() method to the System class, which gives even more precise timing, down to nano seconds.



Tuesday, March 4, 2014

Create Java String Using ” ” or Constructor?

In Java, a string can be created by using two methods:
String x = "abc";
String y = new String("abc");
What is the difference between using double quotes and using constructor?
Double Quotes vs. Constructor
This question can be answered by using two simple code examples.
String a = "abcd";
String b = "abcd";
System.out.println(a == b);  // True
System.out.println(a.equals(b)); // True
a==b is true because a and b are referring to the same string literal in the method area. The memory references are the same.
When the same string literal is created more than once, JVM store only one copy of each distinct string value. This is called “string interning“.
String c = new String("abcd");
String d = new String("abcd");
System.out.println(c == d);  // False
System.out.println(c.equals(d)); // True
c==d is false because c and d refer to two different objects in the heap. Different objects always have different memory reference.
constructor vs double quotes Java String - New Page
When to Use Which
Because the literal “abcd” is already of type String, using constructor will create an extra unnecessary object. Therefore, double quotes should be used if you just need to create a String.

substring() method in JDK6 and JDK7

1. What substring() does?
The substring(int beginIndex, int endIndex) method returns a string that starts with beginIndex and ends with endIndex-1.
String x = "abcdef";
x = x.substring(1,3);
System.out.println(x);
Output:
bc
2. What happens when substring() is called?
You may know that because x is immutable, when x is assigned with the result of x.substring(1,3), it points to a totally new string like the following:
string-immutability
However, this diagram is not exactly right or it represents what really happens in the heap. What really happens when substring() is called is different between JDK 6 and JDK 7.
3. substring() in JDK 6
String is supported by a char array. In JDK 6, the String class contains 3 fields: char value[], int offset, int count. They are used to store real character array, the first index of the array, the number of characters in the String.
When the substring() method is called, it creates a new string, but the string’s value still points to the same array in the heap. The difference between the two Strings is their count and offset values.
string-substring-jdk6
The following code is simplified and only contains the key point for explain this problem.
//JDK 6
String(int offset, int count, char value[]) {
 this.value = value;
 this.offset = offset;
 this.count = count;
}
 
public String substring(int beginIndex, int endIndex) {
 //check boundary
 return  new String(offset + beginIndex, endIndex - beginIndex, value);
}
4. A problem caused by substring() in JDK 6
If you have a VERY long string, but you only need a small part each time by using substring(). This will cause a performance problem, since you need only a small part, you keep the whole thing. For JDK 6, the solution is using the following, which will make it point to a real sub string:
x = x.substring(x, y) + ""
5. substring() in JDK 7
This is improved in JDK 7. In JDK 7, the substring() method actually create a new array in the heap.
string-substring-jdk7
//JDK 7
public String(char value[], int offset, int count) {
 //check boundary
 this.value = Arrays.copyOfRange(value, offset, offset + count);
}
 
public String substring(int beginIndex, int endIndex) {
 //check boundary
 int subLen = endIndex - beginIndex;
 return new String(value, beginIndex, subLen);
}