Friday 13 January 2012

How to write build.xml and run build in Apache ANT

This is the second article on Apache ANT tutorials for beginners series As I have always said that I like short , clear and concise tutorial which tells about few concept but in a clear and concise manner and put weight on fundamentals . I try to adopt same theory while writing my blog post while writing my experience coupled with concept which is important for a software developer point of view.


Here I am answering some of the basic questions related to installing ant , running ant , creating buidl.xml file , debugging build.xml in case of any issue .

These questions have been asked by my students , while teaching them JAVA and related technology  in my early career.

How do I run ant?
To run you need to download ant and install on your machine , then create environment variable ANT_HOME and include ANT_HOME/bin into your PATH like below.

In Windows path=%path%;%ANT_HOME%/bin
In Linux    PATH =${PATH}:${ANT_Home}/bin

Now you can open command prompt and type ant.

If you get this output, means ant binaries is not in your path

C:\Documents and Settings>ant
'ant' is not recognized as an internal or external command,operable program or batch file.

Otherwise you will get output which will complain about build file if it doesn’t exits.
   
    C:\Documents and Settings>ant
    Buildfile: build.xml does not exist!
    Build failed

How do I write build.xml file?
here is a sample build.xml you just need to know important element e.g. project ,target ,property and task and the order in which different target gets executed to start with basic build procedure.

<?xml version="1.0"?>
<project name="test" default="all" basedir=".">
  <property name="src"   value="src"/>
  <property name="build" value="build"/>
  <property name="lib"   value="lib"/>

<target name="all" depends="clean, compile" description="Builds the whole project">
    <echo>Doing all</echo>
  </target>

<target name="Clean" description="Removes previous build">
    <delete verbose="true">
      <fileset dir="${build}"/>
    </delete>
  </target>

<target name="compile" depends="clean" description="compile whole project">
    <echo>compile ${ant.project.name} </echo>
    <copy file="${src}/splashscreen.jpeg" tofile="${build}/splashscreen.jpeg"/>
    <javac srcdir="${src}" destdir="${build}" includes="Test.java"/>
  </target>
</project>

lets see what we are doing here :

<project name="test" default="all" basedir=".">

This line defines our project; every build file must have this line. Project name is “test” defined by attribute “name”; default target is “all”, while running “ant” command from commmand prompt if we don’t specify any target than ant executed this default target.
basedir tells which is top level directory for creating build in this case its current directory (from where you run ant command) , denoted by dot “.” .

<property name="src"   value="src"/>

Here we are declaring and specifying property ,you can say variable every property has atleast two attribute “name” and “value” , though you can define your all properties in a separate properties file and load from there as well .<property> denotes ant’s property task, which do have some other attribute e.g. location to specify location of any properties file. I recommend that you always use property in your build.xml instead of using hardcoded values in target for directory name etc , this will give you flexibility to change the value anytime without changing at many places (in case you have hardcoded it).

<target name="all" depends="clean, compile" description="Builds the whole project">
Here we are defining a target, since we have already called target “all” as default in project tag, so if we don’t specify this target our build will fail saying “target not found”.

”name” attribute specified name of target. “depends” says that before executing this target executed first “clean” and then “compile”

<echo>Doing all</echo>
This will print message in console as “doing all”


<target name="Clean" description="Removes previous build">
This is target “Clean” which will delete old build before building new one , you can have as many target as you want based on your need.

<delete verbose="true">
      <fileset dir="${build}"/>
</delete>

delete task or tag is used to delete directory, file etc, verbose=true makes it to print message while deleting in cosole, <fileset> is an important tag and I recommend you to read in detail somewhere in ant manual or may be I will explain in detail sometime because it include “patternset” which supports pattern matching of directory/files via its includes and excludes attribute which is extremely useful to filter unwanted files (generally meta data files form CVS, SVN etc).

Here we are deleting build directory by using value of property “build”, ${build} denotes value of any property.

<target name="compile" depends="clean" description="compile whole project">
    <echo>compile ${ant.project.name} </echo>
    <copy file="${src}/splashscreen.jpeg" tofile="${build}/splashscreen.jpeg"/>
    <javac srcdir="${src}" destdir="${build}" includes="Test.java"/>
  </target>
</project>

This is our compile target ,which compiles our code and also copies resources e.g. images, we can also create jar file using ant, which we are not doing here just for simplicity.

Imporant thing here is property ${ant.project.name} this is builtin propety provided by ant and its’s value is name of project defined by attribute “name” of proejct tag.

<copy> tag is used to copy files and <javac> tag is used to compile java code .

How do I debug build.xml?
if you see problem on your build or you are getting exception related to findiing files/directory or anything then you would like to know what’s going behind there are two option , run ant on verbose option , it will print lots of detail (I don’t prefer this) because of so much unwanted information but can be usefule in certain situation.

Second and my preffered way is good old “echo” way . use echo task to print values of properties, variables or printing simple message to check the work flow.

here are some example of using echo

<echo>Doing all</echo>
<echo message="Now creating directory source "/>
<echo level="warning" message ="Active configuration (config.active property) is not set - using default." />


How do I enforce ant to use file other than build.xml?
Normally when you run ant from any directory from command prompt it will look for file called build.xml in current directory; if it doesn’t find the file it will give error. If you have file named “custom_build.xml” you can instruct ant to use this file for building your application by using option “-f” e.g. ant –f custom_build.xml

Hope this would be useful let me know if you have any questions, doubt etc will be happy to answer.

How to traverse or loop HashMap in Java Example

There are multiple way to iterate, traverse or loop through Map, HashMap or TreeMap in Java and we all familiar of either all of those or some of those. But to my surprise one of my friends was asked in his interview (he has more than 6 years of experience in java programming) to write code for getting values from hashmap or TreeMap in Java with at least 4 ways. Just like me he also surprised on this question but written it. I don't know why exactly some one ask this kind of java interview question to a relatively senior java programmer. Though my closest guess is to verify that whether he is still hands on with coding in java. Anyway that gives me idea to write this Java tutorial and here is multiple ways to traverse, iterate or loop on a Map in Java, so remember this because you may also ask this question J.

How to traverse or loop Map, HashMap or TreeMap in Java

In next section of this Java tutorial we will see four different ways of looping or iterating over Map in Java and will display each key and value from HashMap. We will use following hashmap for our example:

HashMap<String, String> loans = new HashMap<String, String>();
loans.put<"home loan", "citibank");
loans.put<"personal loan", "Wells Fargo");


Iterating or looping map using Java5 foreach loop
Here we will use new foreach loop introduced in JDK5 for iterating over any map in java and using KeySet of map for getting keys. this will iterate through all values of Map and display key and value together.

HashMap<String, String> loans = new HashMap<String, String>();
loans.put("home loan", "citibank");
loans.put("personal loan", "Wells Fargo");

for (String key : loans.keySet()) {
   System.out.println("------------------------------------------------");
   System.out.println("Iterating or looping map using java5 foreach loop");
   System.out.println("key: " + key + " value: " + loans.get(key));
}

Output:
------------------------------------------------
Iterating or looping map using java5 foreach looop
key: home loan value: citibank
------------------------------------------------
Iterating or looping map using java5 foreach looop
key: personal loan value: Wells Fargo



Iterating Map in Java using KeySet Iterator
In this Example of looping hashmap in Java we have used Java Iterator instead of for loop, rest are similar to earlier example of looping:

Set<String> keySet = loans.keySet();
Iterator<String> keySetIterator = keySet.iterator();
while (keySetIterator.hasNext()) {
   System.out.println("------------------------------------------------");
   System.out.println("Iterating Map in Java using KeySet Iterator");
   String key = keySetIterator.next();
   System.out.println("key: " + key + " value: " + loans.get(key));
}

Output:
------------------------------------------------
Iterating Map in Java using KeySet Iterator
key: home loan value: citibank
------------------------------------------------
Iterating Map in Java using KeySet Iterator
key: personal loan value: Wells Fargo


Looping HashMap in Java using EntrySet and Java5 for loop
In this Example of traversing Map in Java, we have used EntrySet instead of KeySet. EntrySet is a collection of all Map Entries and contains both Key and Value.

Set<Map.Entry<String, String>> entrySet = loans.entrySet();
for (Entry entry : entrySet) {
   System.out.println("------------------------------------------------");
   System.out.println("looping HashMap in Java using EntrySet and java5 for loop");
   System.out.println("key: " + entry.getKey() + " value: " + entry.getValue());
}

Output:
------------------------------------------------
looping HashMap in Java using EntrySet and java5 for loop
key: home loan value: citibank
------------------------------------------------
looping HashMap in Java using EntrySet and java5 for loop
key: personal loan value: Wells Fargo


Iterating HashMap in Java using EntrySet and Java iterator
This is the fourth and last example of looping Map and here we have used Combination of Iterator and EntrySet to display all keys and values of a Java Map.

Set<Map.Entry<String, String>> entrySet1 = loans.entrySet();
Iterator<Entry<String, String>> entrySetIterator = entrySet1.iterator();
while (entrySetIterator.hasNext()) {
   System.out.println("------------------------------------------------");
   System.out.println("Iterating HashMap in Java using EntrySet and Java iterator");
   Entry entry = entrySetIterator.next();
   System.out.println("key: " + entry.getKey() + " value: " + entry.getValue());
}

Output:
------------------------------------------------
Iterating HashMap in Java using EntrySet and Java iterator
key: home loan value: citibank
------------------------------------------------
Iterating HashMap in Java using EntrySet and Java iterator
key: personal loan value: Wells Fargo


That’s all on multiple ways of looping Map in Java. We have seen exactly 4 examples to iterator on Java Map in combination of KeySet and EntrySet by using for loop and Iterator. Let me know if you are familiar with any other ways of iterating and getting each key value from Map in Java.

How to Convert Map to List in Java Example

Map and List are two common data-structures available in Java and in this article we will see how can we convert Map values or Map keys into List in Java. Primary difference between Map (HashMap, ConcurrentHashMap or TreeMap) and List is that Map holds two object key and value while List just holds one object which itself is a value. Key in hashmap is just an addon to find values, so you can just pick the values from Map and create a List out of it. Map in Java allows duplicate value which is fine with List which also allows duplicates but Map doesn't allow duplicate key.


How to Convert Map into List in Java with Example

Map to List Example in Java
Here are few examples of converting Map to List in Java. We will see first how to convert hashMap keys into ArrayList and than hashMap values into ArrayList in Java.

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;

/**
 *Converting HashMap into ArrayList in Java
 */
public class MaptoListJava {

    public static void main(String... args) {
        HashMap<String, String> personalLoanOffers = new HashMap<String, String>();
        // preparing hashmap with keys and values
        personalLoanOffers.put("personal loan by DBS", "Interest rate low");
        personalLoanOffers.put("personal loan by Standard Charted", "Interest rate low");
        personalLoanOffers.put("HSBC personal loan by DBS", "14%");
        personalLoanOffers.put("Bankd of America Personal loan", "11%");
     
        System.out.println("Size of personalLoanOffers Map: " + personalLoanOffers.size());
     
        //Converting HashMap keys into ArrayList
        List<String> keyList = new ArrayList<String>(personalLoanOffers.keySet());
        System.out.println("Size of Key list from Map: " + keyList.size());
     
        //Converting HashMap Values into ArrayList
        List<String> valueList = new ArrayList<String>(personalLoanOffers.values());
        System.out.println("Size of Value list from Map: " + valueList.size());


     
        List<Entry> entryList = new ArrayList<Entry>(personalLoanOffers.entrySet());
        System.out.println("Size of Entry list from Map: " + entryList.size());

    }
}

Output:
Size of personalLoanOffers Map: 4
Size of Key list from Map: 4
Size of Value list from Map: 4
Size of Entry list from Map: 4

That's all on Map to List Conversion in Java , as you seen in above example you can create separate list for both keySet and values Collection in Java. let me know if you know any other way except brute force way of going through each element of Map and copying into List.

How to read and write Images in java using ImageIO Utility

Writing an Image file in Java is very common scenario and in this article we will see a new way to write images into file in Java. javax.imageio.ImageIO is a utility class which provides lots of utility method related to images processing in Java. Most common of them is reading form image file and writing images to file in java. You can write any of .jpg, .png, .bmp or .gif images to file in Java. Just like writing, reading is also seamless with ImageIO and you can read BufferedImage directly from URL. Reading Images are little different than reading text or binary file in Java as they they are associated with different format. Though you can still use getClass().getResourceAsStream() approach for loading images.


Image Read Write Example using ImageIO

Code Example Image Read and Write in Java
Here is complete Code Example of reading and writing Images to file in Java, we will first read the image and than write the same image in different format e.g. JPG, PNG and BMP into disk.

In this code Exmaple of javax.imageio.ImageIO class we will see:

How to read Buffered Image in Java from File or URL
How to write JPG images to file in Java
How to write PNG images to file in Java
How to write BMP images to file in Java
How to write GIF images to file in Java



import javax.imageio.ImageIO;
import java.io.File;
import java.io.IOException;
import java.awt.image.BufferedImage;



public class ImageIOExample {   

    public static void main( String[] args ){
       BufferedImage image = null;
        try {

              //you can either use URL or File for reading image using ImageIO
            File imagefile = new File("C://Documents and Settings/Javin/My Documents/My Pictures/loan.PNG");
            image = ImageIO.read(imagefile);

            //ImageIO Image write Example in Java
            ImageIO.write(image, "jpg",new File("C:\\home_loan.jpg"));
            ImageIO.write(image, "bmp",new File("C:\\credit_card_loan.bmp"));
            ImageIO.write(image, "gif",new File("C:\\personal_loan.gif"));
            ImageIO.write(image, "png",new File("C:\\auto_loan.png"));

        } catch (IOException e) {
              e.printStackTrace();
        }
        System.out.println("Success");
    }
}

Apart from seemless support of reading and writing images in Java, ImageIO class also contains lot of other utility methods for locating ImageReaders and ImageWriters and performing encoding and decoding.

That's all on this Reading and Writing Image File in Java using javax.imageio.ImageIO. Let me know if you face any issue while trying these examples of ImageIO.

Difference between DOM and SAX Parsers in Java

Difference between SAX and DOM Parser is very popular Java interview and often asked when interviewed on Java and XML. Both DOM and SAX parser are extensively used to read and parse XML file in java and have there own set of advantage and disadvantage which we will cover in this article. Though there is another way of reading xml file using xpath in Java which is more selective approach like SQL statements people tend to stick with XML parsers. DOM Parser vs SAX parsers are also often viewed in terms of speed, memory consumption and there ability to process large xml files.


Difference between DOM and SAX XML Parser in Java

DOM XML Parser in Java

DOM Stands for Document Object Model and it represent an XML Document into tree format which each element representing tree branches. DOM Parser creates an In Memory tree representation of XML file and then parses it, so it requires more memory and its advisable to have increased heap size for DOM parser in order to avoid Java.lang.OutOfMemoryError:java heap space . Parsing XML file using DOM parser is quite fast if XML file is small but if you try to read a large XML file using DOM parser there is more chances that it will take a long time or even may not be able to load it completely simply because it requires lot of memory to create XML Dom Tree. Java provides support DOM Parsing and you can parse XML files in Java using DOM parser. DOM classes are in w3c.dom package while DOM Parser for Java is in JAXP (Java API for XML Parsing) package.

SAX XML Parser in Java
SAX Stands for Simple API for XML Parsing. This is an event based XML Parsing and it parse XML file step by step so much suitable for large XML Files. SAX XML Parser fires event when it encountered opening tag, element or attribute and the parsing works accordingly. It’s recommended to use SAX XML parser for parsing large xml files in Java because it doesn't require to load whole XML file in Java and it can read a big XML file in small parts. Java provides support for SAX parser and you can parse any xml file in Java using SAX Parser, I have covered example of reading xml file using SAX Parser here. One disadvantage of using SAX Parser in java is that reading XML file in Java using SAX Parser requires more code in comparison of DOM Parser.


Difference between DOM and SAX XML Parser
Here are few high level differences between DOM parser and SAX Parser in Java:

1) DOM parser loads whole xml document in memory while SAX only loads small part of XML file in memory.

2) DOM parser is faster than SAX because it access whole XML document in memory.

3) SAX parser in Java is better suitable for large XML file than DOM Parser because it doesn't require much memory.

4) DOM parser works on Document Object Model while SAX is an event based xml parser.


That’s all on difference between SAX and DOM parsers in Java, now it’s up to you on which XML parser you going to choose. I recommend use DOM parser over SAX parser if XML file is small enough and go with SAX parser if you don’t know size of xml files to be processed or they are large.

Step By Step guide to Read XML file in Java Using SAX Parser Example

Read XML file in Java Using SAX Parser Example

Reading XML file in java using SAX Parser is little different than reading xml file in Java with DOM parser which we had discussed in last article of this series. This tutorial is can be useful for those who are new to the java world and got the requirement for read an xml file in java in their project or assignment, key feature of java is it provides built in class and object to handle everything which makes our task very easy. Basically this process of handling XML file is known as parsing means break down the whole string into small pieces using the special tokens.
Parsing can be done using two ways:


Using DOM Parser
Using SAX Parser

In DOM parser we have seen that we have to follow simple three steps:
Ø      Parse the XML file
Ø      Create the java object
Ø      Manipulate the object means we can read that object or add them to list or whatever function we want we can do
But in SAX Parser its little bit different.

SAX Parser: it’s an event based parsing it contains default handler for handling the events whenever SAX parser pareses the xml document and it finds the Start tag “<” and end tag”>” it calls corresponding handler method.

Though there are other ways also to get data from xml file e.g. using XPATH in Java which is a language like SQL and give selective data from xml file.

Sample Example of reading XML File – SAX Parser
Suppose we have this sample XML file bank.xml which contains account details of all accounts in a hypothetical bank:

<?xml version="1.0" encoding="UTF-8"?>
<Bank>
      <Account type="saving">
            <Id>1001</Id>
            <Name>Jack Robinson</Name>
            <Amt>10000</Amt>
      </Account>
      <Account type="current">
            <Id>1002</Id>
            <Name>Sony Corporation</Name>
            <Amt>1000000</Amt>
      </Account>
</Bank>



1.      Create the SAX parser and parse the XML file:  In this step we will take one factory instance from SAXParserFactory to parse the xml  file this factory instance in turns  give us instance of parser using the parse() method will parse the Xml file.
2.      Event Handling: when Sax Parser starts the parsing whenever it founds the start or end tag it will invoke the corresponding event handling method which is public void startElement (…) and public void end Element (...).

3.       Register the events: The class extends the Default Handler class to listen for callback events and we register this handler to sax Parser to notify us for call back event

Let see java code for all these steps

To represent data from our sample xml file we need one java domain object called Account:

package parser;

public class Account {

       private String name;
       private int id;
       private int amt;
       private String type;

       public Account() {
       }

       public Account(String name, int id, int amt, String type) {
              this.name = name;
              this.amt = amt;
              this.id = id;
              this.type = type;
       }

       public int getAmt() {
              return amt;
       }

       public void setAmt(int amt) {
              this.amt = amt;
       }

       public int getId() {
              return id;
       }

       public void setId(int id) {
              this.id = id;
       }

       public String getName() {
              return name;
       }

       public void setName(String name) {
              this.name = name;
       }

       public String getType() {
              return type;
       }

       public void setType(String type) {
              this.type = type;
       }

       public String toString() {
              StringBuffer sb = new StringBuffer();
              sb.append("Account Details - ");
              sb.append("Name:" + getName());
              sb.append(", ");
              sb.append("Type:" + getType());
              sb.append(", ");
              sb.append("Id:" + getId());
              sb.append(", ");
              sb.append("Age:" + getAmt());
              sb.append(".");

              return sb.toString();
       }
}


Sample Code for implementing SAX parser in Java

package parser;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class ReadXMLFileUsingSaxparser extends DefaultHandler {

       private Account acct;
       private String temp;
       private ArrayList<Account> accList = new ArrayList<Account>();

       /** The main method sets things up for parsing */
       public static void main(String[] args) throws IOException, SAXException,
                     ParserConfigurationException {
            
              //Create a "parser factory" for creating SAX parsers
              SAXParserFactory spfac = SAXParserFactory.newInstance();

              //Now use the parser factory to create a SAXParser object
              SAXParser sp = spfac.newSAXParser();

              //Create an instance of this class; it defines all the handler methods
              ReadXMLFileUsingSaxparser handler = new ReadXMLFileUsingSaxparser();

              //Finally, tell the parser to parse the input and notify the handler
              sp.parse("bank.xml", handler);
            
              handler.readList();

       }


       /*
        * When the parser encounters plain text (not XML elements),
        * it calls(this method, which accumulates them in a string buffer
        */
       public void characters(char[] buffer, int start, int length) {
              temp = new String(buffer, start, length);
       }
     

       /*
        * Every time the parser encounters the beginning of a new element,
        * it calls this method, which resets the string buffer
        */
       public void startElement(String uri, String localName,
                     String qName, Attributes attributes) throws SAXException {
              temp = "";
              if (qName.equalsIgnoreCase("Account")) {
                     acct = new Account();
                     acct.setType(attributes.getValue("type"));

              }
       }

       /*
        * When the parser encounters the end of an element, it calls this method
        */
       public void endElement(String uri, String localName, String qName)
                     throws SAXException {

              if (qName.equalsIgnoreCase("Account")) {
                     // add it to the list
                     accList.add(acct);

              } else if (qName.equalsIgnoreCase("Name")) {
                     acct.setName(temp);
              } else if (qName.equalsIgnoreCase("Id")) {
                     acct.setId(Integer.parseInt(temp));
              } else if (qName.equalsIgnoreCase("Amt")) {
                     acct.setAmt(Integer.parseInt(temp));
              }

       }

       private void readList() {
              System.out.println("No of  the accounts in bank '" + accList.size()  + "'.");
              Iterator<Account> it = accList.iterator();
              while (it.hasNext()) {
                     System.out.println(it.next().toString());
              }
       }
     
}

Output:
No of  the accounts in bank '2'.
Account Details - Name:Jack Robinson, Type:saving, Id:1001, Age:10000.
Account Details - Name:Sony Corporation, Type:current, Id:1002, Age:1000000.



Advantage of SAX parser in Java:
It is faster than DOM parser because it will not load the XML document into the memory .its an event based.

Difference between Wait, Sleep and Yield in Java

Difference between wait and sleep or difference between Sleep and yield in Java are popular core Java interview questions and asked on multi-threading interviews. Out of three Sleep () and Yield () methods are defined in thread class while wait() is defined in Object class, which is another interview question. In this Java tutorial we will learn what is sleep in Java, important points of sleep in java and difference between Wait and sleep in Java.


Difference between Wait, Sleep and Yield in Java

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

Difference between yield and sleep in java
Major difference between yield and sleep in Java is that yield() method pauses the currently executing thread temporarily for giving a chance to the remaining waiting threads of the same priority to execute. If there is no waiting thread or all the waiting threads have a lower priority then the same thread will continue its execution. The yielded thread when it will get the chance for execution is decided by the thread scheduler whose behavior is vendor dependent. Yield method doesn’t guarantee  that current thread will pause or stop but it guarantee that CPU will be relinquish by current Thread as a result of call to Thread.yield() method in java.

Sleep method in Java has two variants one which takes millisecond as sleeping time while other which takes both mill and nano second for sleeping duration.

sleep(long millis)
or
sleep(long millis,int nanos)

Cause the currently executing thread to sleep for the specified number of milliseconds plus the specified number of nanoseconds.

Example of Thread Sleep method in Java
Here is sample code example of Sleep Thread in Java. In this example we have put Main thread in Sleep for 1 second.

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

}

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



10 points about Thread sleep() method in Java
I have listed down some important and worth to remember points about Sleep() method of Thread Class in Java:

1) Thread.sleep() method is used to pause the execution, relinquish the CPU and return it to thread scheduler.

2) Thread.sleep() method is a static method and always puts current thread on sleep.

3) Java has two variants of sleep method in Thread class one with one argument which takes milliseconds as duration for sleep and other method with two arguments one is millisecond and other is nanosecond.

4) Unlike wait() method in Java, sleep() method of Thread class doesn't relinquish the lock it has acquired.

5) sleep() method throws Interrupted Exception if another thread interrupt a sleeping thread in java.

6) With sleep() in Java its not guaranteed that when sleeping thread woke up it will definitely get CPU, instead it will go to Runnable state and fight for CPU with other thread.

7) There is a misconception about sleep method in Java that calling t.sleep() will put Thread "t" into sleeping state, that's not true because Thread.sleep method is a static method it always put current thread into Sleeping state and not thread "t".

That’s all on Sleep method in Java. We have seen difference between sleep and wait along with sleep and yield in Java. In Summary just keep in mind that both sleep() and yield() operate on current thread.

Tomcat – java.lang.OutOfMemoryError: PermGen space Cause and Solution

Tomcat web server often suffers from java.lang.OutOfMemoryError: PermGen space whenever you deploy-undeploy your web application couple of time. No matter you are using tomcat6, tomcat7 or using bundled tomcat in Netbeans or Eclipse you will face this error now and then while developing web application on tomcat server. I thought about this article after writing 2 Solution of OutOfMemoryError in Java. I have touched this issue there but then I thought to write separate tutorial for tomcat outofmemoryerror because I am getting this error too frequently.

In this article we will see what causes java.lang.OutOfMemoryError: PermGen Space in tomcat and how to fix java.lang.OutOfMemoryError: PermGen Space in tomcat server.

Tomcat – java.lang.OutOfMemoryError: PermGen space Cause and Solution

Cause of OutOfMemoryError in PermGen space in Tomcat:
PermGen Space of heap is used to store classes and Meta data about classes in Java. When a class is loaded by a classloader it got stored in PermGen space, it gets unloaded only when the classloader which loaded this class got garbage collected. If any object retains reference of classloader than its not garbage collected and Perm Gen Space is not freed up. This causes memory leak in PermGen Space and eventually cause java.lang.OutOfMemoryError: PermGen space. Another important point is that when you deploy your web application a new Clasloader gets created and it loads the classes used by web application. So if Classloader doesn't get garbage collected when your web application stops you will have memoery leak in tomcat.

Solution of Tomcat: OutOfMemroyError:
1) Find the offending classes which are retaining reference of Classloader and prventing it from being garbage collected. Tomcat provides memory leak detection functionality after tomcat 6 onwards which can help you to find when particular library, framework or class is causing memory leak in tomcat. Here are some of the common causes of java.lang.OutOfMemoryError: PermGen space in tomcat server:

1) JDBC Drivers:
JDBC drivers are most common cause of java.lang.OutOfMemoryError: PermGen space in tomcat if web app doesn't unregister during stop. One hack to get around this problem is that JDBC driver to be loaded by common class loader than application classloader and you can do this by transferring driver's jar into tomcat lib instead of bundling it on web application's war file.

2) Logging framework:
Similar solution can be applied to prevent logging libraries like Log4j causing java.lang.OutOfMemoryError: PermGen space in tomcat.

3) Application Threads which have not stopped.
Check your code carefully if you are leaving your thread unattended and running in while loop that can retain classloader's reference and cause java.lang.OutOfMemoryError: PermGen space in tomcat web server. Another common culprint is ThreadLocal, avoid using it untily you need it absolutely, if do you make sure to set them null or free any object ThreadLocal's are holding.

Another Simple Solution is to increase PermGen heap size in catalina.bat or catalina.sh of tomcat server; this can give you some breathing space but eventually this will also return in java.lang.OutOfMemoryError: PermGen space after some time.

Steps to increase PermGen Heap Space in Tomcat:

1) Go to Tomcat installation directory i.e C:\Program Files\Apache Software Foundation\Apache Tomcat 7.0.14\bin in Windows and something similar in linux.

2) Add JAVA_OPTS in your catalina.bat or Catalina.sh

In Windows:

set JAVA_OPTS="-Xms1024m -Xmx10246m -XX:NewSize=256m -XX:MaxNewSize=356m -XX:PermSize=256m -XX:MaxPermSize=356m"

In linux:

export JAVA_OPTS="-Xms1024m -Xmx10246m -XX:NewSize=256m -XX:MaxNewSize=356m -XX:PermSize=256m -XX:MaxPermSize=356m"

You can change the actual heap size and PermGen Space as per your requirement.

3) Restart Tomcat.

As I said earlier increasing PermGen space can prevent java.lang.OutOfMemoryError: PermGen in tomcat only for some time and it will eventually occur based on how many times you redeploy your web application, its best to find the offending class which is causing memory leak in tomcat and fix it.

How to check File Permission in Java with Example - Java IO Tutorial

Java provides several methods to check file and directory permissions. In last couple of articles we have seen how to create File in java and how to read text file in Java and in this article we will learn how to check whether file is read only , whether file has write permission or not etc. In Java  we know we have file object to deal with Files  if we have created any file in our application using the file object , we have the privilege to check the access permission of that file using simple method of File class in Java. Let see what the methods are and how to use that method

How to check File Permission in Java with Example

How to find if File is ReadOnly in Java
boolean canRead() : this method is used to check that our application can have access to read the file or not. Here is an example of checking a file is read only in Java. If canRead() return true means file is read only in Java other wise file is protected and we can’t read it from Java or other Unix command.


Code Example of Checking Read Permission in Java
import java.io.File;

/**
 * @author Javin
 *
 */
public class CanReadTest {
       public static void main(String[] args) throws SecurityException {
        // Create a File object
        File myTestFile = new File("C:/Documents and Settings/dost/My Documents/canReadTest.txt");
        //Tests whether the application can Read  the file
        if (myTestFile.canRead()) {
            System.out.println(myTestFile.getAbsolutePath() + "Can Read: ");
        } else {
            System.out.println(myTestFile.getAbsolutePath() + " Cannot Read: ");
        }


    }

}


How to check if File or Directory has Write Permission in Java
boolean canWrite() : this method is used to check that our application can have access to write on  the file or not. Below example is for checking whether a File has write permission in java or not. If canWrite() returns true means file is writable in Java otherwise write permission is not for current user in operating system or from Java.


Code Example of checking Write permission on File in Java
import java.io.File;
public class CanWriteTest {
       public static void main(String[] args) throws SecurityException {
        // Create a File object
        File myTestFile = new File("C:/Documents and Settings/dost/My Documents/canWriteTest.txt");
        //Tests whether the application can Read  the file
        if (myTestFile.canWrite()) {
            System.out.println(myTestFile.getAbsolutePath() + "Can Write: ");
        } else {
            System.out.println(myTestFile.getAbsolutePath() + " Cannot Write: ");
        }


    }

}



How to see if File or Directory has execute permission in Java
boolean canExecute(): This method of File Class is used to check that our application can have access to execute  the file or not. This example shows how to find execute permission of File in Java. If canExecute() return true means current user has execute permission on file in java.


Code Example of Checking Execute permission in Java
import java.io.File;

public class CanExecuteTest {
       public static void main(String[] args) throws SecurityException  {
        // Create a File object
        File myTestFile = new File("C:/Documents and Settings/dost/My Documents/canExecuteTest.txt");
        //Tests whether the application can execute the file
        if (myTestFile.canExecute()) {
            System.out.println(myTestFile.getAbsolutePath() + "Can Execute: ");
        } else {
            System.out.println(myTestFile.getAbsolutePath() + " Cannot Execute: ");
        }
    }
}


Note: All this method can throw SecurityException if security manager exist and it denies to access of that file for that operation which we are performing on that

That’s all on checking File Permission in Java. We have see how to check read permission, write permission and execute permission from Java Code with Sample Example.

Memory Mapped File in Java - Read Write Code Example

Memory Mapped Files in Java is rather new java concept for many programmers and developers, though it’s been there from JDK 1.4 along with java.nio package. Java IO has been considerably fast after introduction of NIO and memory mapped file offers fastest IO operation possible in Java and quite  useful in high frequency trading space, where electronic trading system needs to be super fast and one way latency to exchange has to be on sub-micro second level. IO has always been concern for performance sensitive applications and memory mapped file allows you to directly read from memory and write into memory. There are some other advantage also which we will see in next section.

key advantage of  Memory Mapped File is that operating system takes care of reading and writing and even if your program crashed just after writing into memory. OS will take care of writing content to File.
Another key advantage is shared memory, memory mapped files can be accessed by more than one process and can be act as shared memory with extremely low latency. See Peter's comment also on comment section.

Earlier we have seen how to read xml file in Java and how to read text file in java and in this Java IO tutorial we gonna look on  what is memory mapped file, how to read and write from memory mapped file and important points related to Memory Mapped Files.


What are Memory Mapped File and IO in Java

Memory mapped files are special files in Java which allows Java program to access contents  directly from memory, this is achieved by mapping whole file or portion of file into memory and operating system takes care of loading page requested and writing into file while application only deals with memory which results in very fast IO operations. Memory used to load Memory mapped file is outside of Java heap Space. Java programming language supports memory mapped file with java.nio package and has MappedByteBuffer to read and write from memory.


Advantage and Disadvantage of Memory Mapped file
Possibly main advantage of Memory Mapped IO is performance which is important to build high frequency electronic trading system. Memory Mapped Files are way faster than standard file access via normal IO. Another big advantage of memory mapped IO is that it allows you to load potentially larger file which is not otherwise accessible. Experiments shows that memory mapped IO performs better with large files. Though it has disadvantage in terms of increasing number of page faults. since operating system only loads a portion of file into memory if a page requested is not present in memory than it would result in page fault.

Memory Mapped IO support in Operating System
Most of major operating system like Windows platform, UNIX, Solaris and other UNIX like operating system supports memory mapped IO and with 64 bit architecture you can map almost any file into memory and access it directly using Java programming language.

Read and write Example of Memory Mapped file in Java
Below example will show you how to read and write from memory mapped file in Java. We have used RandomAccesFile to open a File and than mapped it to memory using FileChannel's map() method, map method takes three parameter mode, start and length of region to be mapped. It returns MapppedByteBuffer which is a ByteBuffer for dealing with memory mapped file.

import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;

  public class CanExecuteTest {

    private static int count = 1010241024; //10 MB

    public static void main(String[] args) throws Exception {
        RandomAccessFile memoryMappedFile = new RandomAccessFile("largeFile.txt", "rw");
      
        //Mapping a file into memory
        MappedByteBuffer out = memoryMappedFile.getChannel().map(FileChannel.MapMode.READ_WRITE, 0, count);
     
        //Writing into Memory Mapped File
        for (int i = 0; i < count; i++) {
            out.put((byte) 'A');
        }
        System.out.println("Writing to Memory Mapped File is completed");
     
        //reading from memory file in Java
        for (int i = 0; i < 10 ; i++) {
            System.out.print((char) out.get(i));
        }
        System.out.println("Reading from Memory Mapped File is completed");
    }
}


Important points of Memory Mapped IO in Java
To summarize the post here is quick summary of memory mapped files and IO in Java:

1) Java supports Memory mapped IO with java.nio package.
2) Memory mapped files is used in performance sensitive application e.g. high frequency electronic trading platforms.
3) By using memory mapped IO you can load portion of large files in memory.
4) Memory mapped file can result in page fault if requested page is not in memory.
5) Ability to map a region of file in memory depends on addressable size of memory. In a 32 bit machine you can not access beyond 4GB or 2^32.
6) Memory mapped IO is much faster than Stream IO in Java.
7) Memory used to load File is outside of Java heap and reside on Shared memory which allow two different process to access File.
8) Reading and writing on memory mapped file is done by operating system, so even if your Java Program crash after putting content into memory it will make to File until OS is fine.

That’s all on memory mapped file and memory mapped IO in Java. Its pretty useful concept and I encourage you to learn more about it. If you are working on high frequency trading space than memory mapped file is quite common there.

How to Use Code Point Methods of Java String get Unicode Characters Example Tutorial

CodePoint method in String is used to get Unicode code point value at index or before index.  In String class we have lot of utility methods for dealing with String like Split , replace and SubString method but here I am discussing a relatively lesser known method codePointAt(), codePointCount() and codePointBefore() ,but before going deep about this method lets first understand what is of code point ,what exactly CodePoint method does and how to use CodePointAt, CodePointBefore methods using java code example.

What is CodePoing in Java?
Code points are the numbers that are used in coded character set where coded character set represent collection of characters and each character will assign a unique number. This coded character set define range of valid code points. Valid code points for Unicode are U+0000 to U+10FFFF.

What CodePoint method of Java String does?

Syntax of the method:
Public   int codePointAt (int index): this method returns the Unicode value of the character specified by the index. This method throw IndexOutOfBoundException if index passed as argument is negative or less than the length of the string.

So now we clear from the syntax that what we need to pass as argument of the method and what it will return.. Now why we need the Unicode value of a particular character so the answer would be Unicode is the character encoding standard designed to clean up the mess of dozens of mutually incompatible ASCII extensions and special encoding and to allow the computer interchange of text in any of the world's writing systems.
Unicode has wide spread acceptance as we know computers just deal with numbers. They store letters and other characters by assigning a number for each one. Before Unicode was invented, there were hundreds of different encoding systems for assigning these numbers. No single encoding could contain enough characters.

So in short Code Point method helps us to get the Unicode value of particular character which in turns helps in internationalization and localization, Unicode is an international character set standard which supports all of the major scripts of the world, as well as common technical symbols.

How to Change or Set File Permissions in Java – Code Example Tutorial

In Last article we saw that how to check  whether any application can access the file and perform any read write or execute operation on that file by using the in built method provided by File Object. Now we deal with some more methods of file class which will used to provide some privileges to user so that they can perform read, write and execute operation on the particular file.

How to set Execute Permission on File in Java
 boolean setExecutable(boolean exe, boolean owneronly) : This method is used to set the execute permission for the owner  of the file and also we can provide every user execute permission using this method , if operation is successful then this method returns true.

This method is overloaded in this class if we want to provide execute permission only the owner we can also use method  boolean setExecutable(boolean exe) . here is a code example of setting or changing execute permission on File in Java. you can also change execute permission on directory similarly. In Unix if a directory doesn't have execute permission means you can not go inside that directory.

import java.io.File;
public class SetExecuteTest{

       public static void main(String[] args)throws SecurityException {

        File file = new File("C:/setExecuteTest.txt");

        if (file.exists()) {
            boolean bval = file.setExecutable(true);
            System.out.println("set the owner's execute permission: "+ bval);
        } else {
            System.out.println("File cannot exists: ");
        }

       if (file.exists()) {
            boolean bval = file.setExecutable(true,false);
            System.out.println("set the everybody execute permission: "+ bval);
        } else {
            System.out.println("File cannot exists: ");
        }
    }
}


How to set Write Permission on File in Java
boolean setWriteable(boolean write,boolean owneronly) : This method is used to set the write permission for the owner of the file and also we can provide every user write permission using this method ,if operation is successful then this method returns true. This method is overloaded and if we want to provide write permission only to the owner of file we can use instead boolean setWritable(boolean write).
here is a code example of setting write permission to a file in Java. same code can also be used to change write permission from a Java File.

import java.io.File;


public class SetWritableTest{

       public static void main(String[] args)throws SecurityException {

        File file = new File("C:/setWriteableTest.txt");
       
        //set write permission on file only for owner
        if (file.exists()) {
            boolean bval = file.setWritable(true);
             System.out.println("set the owner's write permission: "+ bval);
        } else {
             System.out.println("File cannot exists: ");
        }

        //Set write permission on File for all.
        if (file.exists()) {
            boolean bval = file.setWritable(true,false);
            System.out.println("set the every user write permission: "+ bval);
        } else {
            System.out.println("File cannot exists: ");
        }


    }
}


How to set Read Permission on File in Java
boolean setReadable(boolean read,boolean owneronly) : This method is used to set the read permission for the owner  of the file and also we can provide every user read permission using this method ,if operation is successful then this method returns true. This method is overloaded and  if we want to provide read permission  only to the owner we can use instead boolean setReadable(boolean read).

here is a complete code example to set write permission on File in Java. this code can also be used change write permission of a file in Java.

import java.io.File;
public class SetReadableTest{

       public static void main(String[] args)throws SecurityException {

        File file = new File("C:/setReadableTest.txt");
        if (file.exists()) {

            boolean bval = file.setReadable(true);
            System.out.println("set the Owner Read permission: "+ bval);
        } else {
            System.out.println("File cannot exists: ");
        }

       if (file.exists()) {
            boolean bval = file.setReadable(true,false);
            System.out.println("set the every user Read permission: "+ bval);
        } else {
            System.out.println("File cannot exists: ");
        }
    }
}


How to make a directory read only in Java
boolean setReadOnly() : This method is used to make the file or directory read only if we call this method on any file then no write operation can not be performed on that file.

import java.io.*;

public class SetReadOnlyTest{
      public static void main(String[] args)throws SecurityException {
          
        File file = new File("C:/setReadOnlyTest.txt");
        if (file.exists()) {
            boolean bval = file.setReadOnly();
            System.out.println("Read opearation is permitted: "+bval);
        } else {
            System.out.println("File cannot exists: ");
        }

    }
}

How to convert ArrayList to Set in Java with Example

Converting ArrayList to Set in Java means creating a Set implementation like HashSet from an ArrayList full of objects.Before Converting your ArrayList into hashSet do remember that List keep insertion order
and guarantees same but Set doesn't have such obligation. Also List allows duplicates but Set doesn't allow any duplicates, which means if you have duplicates in your ArrayList they will be lost when you convert ArrayList to HashSet and that's the reason why sometime size of ArrayList doesn't match with size of HashSet after conversion. Converting ArrayList to Set is entirely different than Converting Map to List but has one thing common , A constructor which takes a collection object. HashSet also has a constructor which takes another collection object e.g. ArrayList and creates Set out of those element. we have also seen a bit of this on 10 Examples of ArrayList in Java and we will see here in detail.


How to Convert List to Set in Java

ArrayList to Set Conversion Example
Converting ArrayList or any other List implementation into HashSet or any other Set Implementation is not very difficult to write. In this Java tutorial  we will see complete code example of converting ArrayList to HashSet in Java

package test;

import java.util.ArrayList;
import java.util.HashSet;

public class ArrayListToSetConverter {

    public static void main(String args[]){
     
        //Creating ArrayList for converting into HashSet
        ArrayList companies = new ArrayList();
        companies.add("Sony");
        companies.add("Samsung");
        companies.add("Microsoft");
        companies.add("Intel");
        companies.add("Sony");
     
        System.out.println("Size of ArrayList before Converstion: " + companies.size());
        System.out.println(companies);
     
        //Converting ArrayList into HashSet in Java
        HashSet companySet = new HashSet(companies);
     
        System.out.println("Size of HashSet after Converstion: " + companies.size());
        System.out.println(companySet);
 
    }
}

Output:
Size of ArrayList before Converstion: 5
[Sony, Samsung, Microsoft, Intel, Sony]
Size of HashSet after Converstion: 5
[Sony, Microsoft, Intel, Samsung]


You might have noticed that Size of Converted ArrayList cum HashSet is not same and one less than original  ArrayList because duplicate entry "Sony" is just one time in Set. This is another great way of removing  duplicates from ArrayList. just copy entries of ArrayList into Set and than copy it back into ArrayList you  don't have duplicates anymore.

That’s all on quick tip to Convert an ArrayList into HashSet in Java. You may check difference between ArrayList and Vector to know more about ArrayList and other Collection class.

How to create and initialize Anonymous array in Java Example

Anonymous arrays in Java is an Array without any name, just like Anonymous inner classes and policy of using Anonymous array is just create, initialize and use it, Since it doesn't have any name you can not reuse it. Anonymous array was a good way to implement variable argument methods before Java introduced varargs in Java5. You had the liberty to create array of any length and pass that to method which operate on anonymous array. Classical example of such variable argument method is aggregate function like sum(), avg(), min(), max() etc. In this java anonymous array tutorial we will how to create anonymous array, how to initialize them and example of anonymous array as variable argument method.


Anonymous array in Java Example Tutorial

How to create Anonymous array in Java
Anonymous array follows same syntax like normal array in Java e.g. new [] { }; , only difference is that after creating Anonymous array we don't store it on any reference variable. here is
few examples of creating anonymous array in java:

anonymous int array : new int[] { 1, 2, 3, 4};
anonymous String array : new String[] {"one", "two", "three"};
anonymous char array :  new char[] {'a', 'b', 'c');

as you have noticed just like anonymous class, creation and initialization of anonymous array is done on same time. you initialize them in same line where you create using new(). as they don't have name there is no way you can initialize() them later.

Anonymous Array Example in Java
Best use of anonymous array is to implement variable argument method which can be invoked with different number on arguments. these methods except an array type and when code invokes this method it creates an anonymous array of different length and pass to method for processing. here is complete code example of anonymous array method:

public class AnnonymousArrayExample {

    public static void main(String[] args) {
      
        //calling method with anonymous array argument
        System.out.println("first total of numbers: " + sum(new int[]{ 1, 2,3,4}));
        System.out.println("second total of numbers: " + sum(new int[]{ 1, 2,3,4,5,6,}));
     
    }
   
    //method which takes an array as argument
    public static int sum(int[] numbers){
        int total = 0;
        for(int i: numbers){
            total = total + i;
        }
        return total;
    }
}

same method sum() can also be implemented using varargs in Java like public static int sum(int... numbers) but you cannot have sum(int[] numbers) and sum(int... numbers) method in one class Java will throw compilation error because it internally used anonymous array to pass variable argument list.

How to Sort Arraylist in Java Example Tutorial

In Order to Sort Java ArrayList on natural order of elements, object stored in ArrayList must implement Comparable interface in Java and should override compareTo() method as per there natural order. In our example of natural order sorting in ArrayList we have implemented compareTo of smartphone and sorted them based on brands. So an Apple smartphone comes before Nokia smartphone. Once your object is ok just store them in Java arraylist and pass that list to Collections.sort() method, this willsort the list in natural order of objects. see bottom of this java tutorial for complete code example of Sorting Java ArrayList in Natural Order.


Sorting Java ArrayList with custom Order
To Sort a Java arraylist on Custom order we need to supply an external Comparator alongwith Arraylist
to Collections.sort(List, Comparator) method. Compare() method will define how sorting of objects
will take place in ArrayList.In our example of custom order sorting of Java Arraylist we have created
a PriceComparator which sorts objects based on there price. So you can get cheapest or expensive
smartphone stored in ArrayList. See below for full code example of ArrayList Sorting in custom order
in Java:


Code Example of Sorting ArrayList in Java
Here is complete code example of sorting an arraylist in java on both natural and custom order by using Custom comparator.

package test;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

public class ArrayListSortingExample {

   private static class SmartPhone implements Comparable {
        private String brand;
        private String model;
        private int price;

        public SmartPhone(String brand, String model, int price){
            this.brand = brand;
            this.model = model;
            this.price = price;
        }
    
        @Override
        public int compareTo(SmartPhone sp) {
            return this.brand.compareTo(sp.brand);
        }

        @Override
        public String toString() {
            return "SmartPhone{" + "brand=" + brand + ", model=" + model + ", price=" + price + '}';
        }
    
    }
 
    private static class PriceComparator implementsComparator{

        @Override
        public int compare(SmartPhone sp1, SmartPhone sp2) {
            return (sp1.price < sp2.price ) ? -1: (sp1.price > sp2.price) ? 1:0 ;
        }
    
    }

    public static void main(String... args) {
    
        //creating objects for arraylist sorting example
        SmartPhone apple = new SmartPhone("Apple", "IPhone4S",1000);
        SmartPhone nokia = new SmartPhone("Nokia", "Lumia 800",600);
        SmartPhone samsung = new SmartPhone("Samsung", "Galaxy Ace",800);
        SmartPhone lg = new SmartPhone("LG", "Optimus",500);
    
        //creating Arraylist for sorting example
        ArrayList smartPhones = new ArrayList();
    
        //storing objects into ArrayList for sorting
        smartPhones.add(apple);
        smartPhones.add(nokia);
        smartPhones.add(samsung);
        smartPhones.add(lg);
    
        //Sorting Arraylist in Java on natural order of object
        Collections.sort(smartPhones);
    
        //print sorted arraylist on natural order
        System.out.println(smartPhones);
    
        //Sorting Arraylist in Java on custom order defined by Comparator
        Collections.sort(smartPhones,new PriceComparator());
    
        //print sorted arraylist on custom order
        System.out.println(smartPhones);
  
    }
}

Output:
[SmartPhone{brand=Apple, model=IPhone4S, price=1000}, SmartPhone{brand=LG, model=Optimus, price=500}, SmartPhone{brand=Nokia, model=Lumia 800, price=600}, SmartPhone{brand=Samsung, model=Galaxy Ace, price=800}]

[SmartPhone{brand=LG, model=Optimus, price=500}, SmartPhone{brand=Nokia, model=Lumia 800, price=600}, SmartPhone{brand=Samsung, model=Galaxy Ace, price=800}, SmartPhone{brand=Apple, model=IPhone4S, price=1000}]


That’s all on Sorting ArrayList in Java based on natural order of Object and any custom order by using Custom Comparator. Let me know if you face any issue while running Sorting ArrayList Example code in Java and I wold be glad to help you.

10 Example of this keyword in Java

this keyword in Java is a special keyword which can be used to represent current object or instance of any class in Java. “this” keyword can also call constructor of same class in Java and used to call overloaded constructor. In this Java tutorial we will see how to use this keyword in Java  and
different examples of this in Java. this sometime also associate with super keyword which is used to denote instance of super class in Java and can be used to call overloaded constructor in Java.

1) this keyword represent current instance of class.

2) You can synchronize on this in synchronized block in Java

synchronized(this){
//this synchronized block will be locked on current instance
}

3) this keyword can be used to call overloaded constructor in java. if used than it must be first statement in constructor this() will call no argument constructor and this(parameter) will call one argument constructor with appropriate parameter. here is an example of using this() for constructor chaining:

Example of this keyword to call constructor in Java

class Loan{
    private double interest;
    private String type;
 
    public Loan(){
       this(“personal loan”);
    }
 
    public Loan(String type){
        this.type = type;
        this.interest = 0.0;
    } 
}

4) If member variable and local variable name conflict than this can be used to refer member variable.
here is an example of this with member variable:

  public Loan(String type, double interest){
        this.type = type;
        this.interest = interest;
  }

Here local variable interest and member variable interest conflict which is easily resolve by referring member variable as this.interest
5) this is a final variable in Java and you can not assign value to this. this will result in compilation
error:

this = new Loan(); //cannot assign value to final variable : this

6) you can call methods of class by using this keyword as shown in below example.
  
   public String getName(){
        return this.toString();
    }

7) this can be used to return object. this is a valid return value. here is an example of using as return value.

public Loan getLoan(){
 return this;
}

8) this can be used to refer static members in Java as well but its discouraged and as per best practices
this should be used on non static reference.

9) "this" keyword can not be used in static context i.e. inside static methods or static initializer block.
if use this inside static context you will get compilation error as shown in below example:

  public static void main(String args){
       this.toString{}; //compilation error: non static variable this can not be used in static context
  }

10) this can also be passed as method parameters since it represent current object of class.


That’s all on this keyword in Java. You should know about this and super keyword and get yourself familiar with different usage of this keyword in java.

How to get current Date Timestamps in Java on GMT or Local Timezone Example

Getting current data and timestamps in java is requirement for most of java enterprise application. Formatting date in java or parsing date in Java is such a common functionality that you will need it now and than. Though most of programmer look Google for finding current date and timestamps code in Java, its worth to having an idea how you can do that by using java.util.Date class. some time you might need formatted data string say "yyyy-MM--dd:HH:mm:ss". That is also possible by using dateformat in Java. I have touched base on string to date conversion and now in this article we will see that in detail in terms of current date, time-stamp and timezone values. if you are working in global core java application which runs on different timezones you must need to include timezone in your date and timestamp to avoid any confusion.

Share

Twitter Delicious Facebook Digg Stumbleupon Favorites More