How to Parse URL in Java

What is URL? URL represents Uniform Resource Locator. It's a pointer to a "resource" on the WorldWide Web.
A resource can be something as simple as a file or a directory,or it can be a reference to a more complicated object,such as a query to a database or to a search engine.

A URL can optionally specify a "port", which is the port number to which the TCP connection is made on the remote host machine. If the port is not specified, the default port for the protocol is used instead. For example, the default port for http is 80.

Java Class java.net.URL provides number of methods such as getFile(),getHost(),getQuery() etc to deal with URL. Please refer to J2SE 6 Documentation for URL Class.

Here I will show you how You can retrieve different parts of URL using Java Program.

Deadlock Example in Java

Deadlock is situation where two or more thread are blocked and waiting for each other.

Consider example that there are two threads running. Thread1 and Thread2. Thread1 puts lock on object1 and goes to sleep.Consider that when thread 1 puts lock on object1 after it goes to sleep, it tries to put lock on object2. 

When Thread 1 goes to sleeps,Thread 2 is up and running. it puts lock on object2. and thread 2 goes to sleep. and try to put lock on object1. but since object 1 is locked by Thread 1 and only will be released when thread 1 gets lock on object2. But Thread 2 already has locked on object2 and will be only released when it get locks on object1. This is Deadlock :) ha ha.

If you are using netbeans then you can get Thread Dump using netbeans Wiki.

Java Program to demostrate Deadlock Situation :

Retrieve HTTP Header information using Java

HttpURLConnection java class is used to retrieve HTTP Header Information. HttpURLConnection class provides connect() and disconnect() method in order to connect to url or disconnect.

You can check that whether connection to URL is successfull or not by checking response Code. if response code if 200 and Response message is OK then connection is successfull.

HttpURLConnection provides two useful method called getHeaderField() and getHeaderFieldKey(). Using these methods you can get key and value of HTTP Header and can retrieve HTTP Header information.Please have a look at below java program which retrieves http header information.

Java Program to Retrieve Header Information: 

Retrieve IP information of my machine

Sometimes you require to retrieve IP information of current machine your are running using Java Program.
Using following program you can get  main Local IP Address,main local host name, alt local ip addresses,alt local host names.

Java provides class java.net.InetAddress which presents an Internet Protocol (IP) address.There are some of useful methods as below which one can deal with to retrieve host name from IP and from IP to host name.

Useful InetAddress methods :
1. getLocalHost() -return local host
2. getByName(String host)  - Determines the IP address of a host, given the host's name
3. getAllByName(String host)- Given the name of a host, returns an array of its IP addresses, based on the configured name service on the system

How to Retrieve My Documents path using Java

Using Java System Class, You can easily retrieve My Documents path in Java

Retrieve My Documents path in Java :

String temp = ((System.getenv("USERPROFILE"))+("\\My Documents\\"));
Output : C:\Users\user\My Documents\

File f1 = new JFileChooser().getFileSystemView().getDefaultDirectory();
Output : C:\Users\user\Documents

Get system32 folder in java

String win = System.getenv("windir");
String winsys32 = win +"\\System32\\";
System.out.println(winsys32);

Retrieve list of Local Interfaces on a machine using Java

package com.anuj.utils;

import java.net.*;
import java.util.*;

public class InterfaceLister {
    public static void main(String[] args) throws SocketException {        
        Enumeration enu = NetworkInterface.getNetworkInterfaces();
        while (enu.hasMoreElements()) {
            NetworkInterface net = (NetworkInterface) enu.nextElement();
            System.out.println(net);
        }
    }
}

RMI Client And RMI Server Implementation in Java

Introduction
The RMI application comprises of the two separate programs, a server and a client. A typical server program creates some remote objects, makes references to these objects accessible, and waits for clients to invoke methods on these objects. The RMI application provides the mechanism by which the server and the client communicate and pass information back and forth. The RMI distributed application uses the RMI Registry to obtain a reference to a remote object. The server calls the registry to associate a name with a remote object. The client looks up the remote object by its name in the server’s registry and then invokes a method on it.

Retrieve Previous, Current and Next Date using Java

Using Java Class "Date" you can get date using Date d = new Date();
Java Provies class named SimpleDateFormat which allows to format date to specific DateFormat.

Using Following program You can  :
  1. Retrieve Current Date in Java
  2. Retrieve Previous Date in Java
  3. Retrieve Next Date in Java
Java Program to retrieve Current Date , Previous Date and Next Day :

Parsing Character-Separated Data in Java

In order to parse data based on some character, Split method is used. There is another approch called StringTokenizer which is more powerful than Split.

String names = "Ali Anuj Munjal Jigar Kamesh Harish Kamesh";
List lstoriginal = Arrays.asList(names.split(" "));
System.out.println("Element in List"+lstoriginal);

Regular Expression Search Program

Pattern:
This is the class of the java.util.regex package which is the compiled representation. Specified string is first compiled into an instance of this class. The pattern to be used to create a matcher object which finds the character sequences for the regular expression.

Matcher:
This is also a class of java.util.regex package which is used to match character sequences.

matcher.find():

Above method finds the matched string in the given string for searching. This method returns a boolean value either true or false.

Writing Logs to a Console and File using Log4j

While doing application development it's require you to write logs into File or print logs into Console with expected Date/Time, ProgramName with line number and many more information.

  1. Download Apache Log4j.jar and add it to your classpath
  2. Create Instance of Logger
  3. Use debug,info,warn,error,fatal methods to log required information

How to List Entries in ZipFile using Java

Java Utils package provides class ZipFile which is used to deal with ZipFile.

To retrieve entries in ZipFile, entries() method is used.
Ex. ZipFile zipFile = new ZipFile("CoreJava.zip");
zipFile.entries();

Once we have all entries available, we can enumerate using Enumerations.
Enumeration enumeration = zipFile.entries();
while(enumeration.hasMoreElements()){
System.out.println(enumeration.nextElement());
}

Java Program to List content of ZIP File :

How to create Zip File using Java

Java utils package provide class called ZipOutputStream which is used to write files to Zip format.

ZipEntry class is used to represent entry in Zip File.
getName() - used to get zip entry name
getMethod() - returns compression method of entry
getTime() - returns modification time
isDirectory() - returns true of entry is Directory entry
getCompressedSize() - returns compressed size of entry
getSize() - return uncompressed size of entry

One can create new ZipEntry and add it to ZipOutputStream.
Ex,
ZipEntry zipEntry = new ZipEntry(filesToZip);
/Add new Zip Entry to OutputStream
zipOutputStream.putNextEntry(zipEntry);

Java Program to calculate actual age from birthdate

package com.anuj.utils;

import java.util.*;
import java.io.*;

public class AgeCalculation {
    public static void main(String[] args) throws IOException {
        int day = 1, month = 0, year = 1, ageYears, ageMonths, ageDays;
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        Calendar cd = Calendar.getInstance();
        try {
            System.out.print("Enter year of your date of birth : ");
            year = Integer.parseInt(in.readLine());
            if (year > cd.get(Calendar.YEAR)) {
                System.out.print("Invalid date of birth.");
                System.exit(0);
            }
            System.out.print("Enter month of your date of birth : ");
            month = Integer.parseInt(in.readLine());
            if (month < 1 || month > 12) {
                System.out.print("Please enter monthe between 1 to 12.");
                System.exit(0);
            } else {
                month--;
                if (year == cd.get(Calendar.YEAR)) {
                    if (month > cd.get(Calendar.MONTH)) {
                        System.out.print("Invalid month!");
                        System.exit(0);
                    }
                }
            }
            System.out.print("Enter day of your date of birth : ");
            day = Integer.parseInt(in.readLine());
            if (month == 0 || month == 2 || month == 4 || month == 6
                    || month == 7 || month == 9 || month == 11) {
                if (day > 31 || day < 1) {
                    System.out.print("Please enter day between 1 to 31.");
                    System.exit(0);
                }
            } else if (month == 3 || month == 5 || month == 8 || month == 10) {
                if (day > 30 || day < 1) {
                    System.out.print("Please enter day between 1 to 30.");
                    System.exit(0);
                }
            } else {
                if (new GregorianCalendar().isLeapYear(year)) {
                    if (day < 1 || day > 29) {
                        System.out.print("Please enter day between 1 to 29.");
                        System.exit(0);
                    }
                } else if (day < 1 || day > 28) {
                    System.out.print("Please enter day between 1 to 28.");
                    System.exit(0);
                }
            }
            if (year == cd.get(Calendar.YEAR)) {
                if (month == cd.get(Calendar.MONTH)) {
                    if (day > cd.get(Calendar.DAY_OF_MONTH)) {
                        System.out.print("Invalid date!");
                        System.exit(0);
                    }
                }
            }
        } catch (NumberFormatException ne) {
            System.out.print(ne.getMessage() + " is not a legal entry!");
            System.out.print("Please enter number.");
            System.exit(0);
        }
        Calendar bd = new GregorianCalendar(year, month, day);
        ageYears = cd.get(Calendar.YEAR) - bd.get(Calendar.YEAR);
        if (cd.before(new GregorianCalendar(cd.get(Calendar.YEAR), month, day))) {
            ageYears--;
            ageMonths = (12 - (bd.get(Calendar.MONTH) + 1))
                    + (bd.get(Calendar.MONTH));
            if (day > cd.get(Calendar.DAY_OF_MONTH)) {
                ageDays = day - cd.get(Calendar.DAY_OF_MONTH);
            } else if (day < cd.get(Calendar.DAY_OF_MONTH)) {
                ageDays = cd.get(Calendar.DAY_OF_MONTH) - day;
            } else {
                ageDays = 0;
            }
        } else if (cd.after(new GregorianCalendar(cd.get(Calendar.YEAR), month,
                day))) {
            ageMonths = (cd.get(Calendar.MONTH) - (bd.get(Calendar.MONTH)));
            if (day > cd.get(Calendar.DAY_OF_MONTH))
                ageDays = day - cd.get(Calendar.DAY_OF_MONTH) - day;
            else if (day < cd.get(Calendar.DAY_OF_MONTH)) {
                ageDays = cd.get(Calendar.DAY_OF_MONTH) - day;
            } else
                ageDays = 0;
        } else {
            ageYears = cd.get(Calendar.YEAR) - bd.get(Calendar.YEAR);
            ageMonths = 0;
            ageDays = 0;
        }
        System.out.print("Age of the person : " + ageYears + " year, "
                + ageMonths + " months and " + ageDays + " days.");
    }
}

Determining If a Year is a Leap Year in Java

Leap Year: Leap Year is the year contains an extra day. In the leap year, February month contains 29 days since normally February month has 28 days. The year which is completely divided by 4 that is the leap year.

This section determines whether the given year is leap year or not using the isLeapYear(year) method of the Calendar class.

Calendar.isLeapYear(year):
This method returns a boolean value true, if the year is leap year otherwise it returns the boolean value false.

Comparing Dates in Java

Java Provides class called Calendar. One can create instance of Calendar using  Calendar.getInstance():

Setting Default Date in Java :
Calendar.set(2000, Calendar.JUNE, 29) - sets the default date to the calendar passing three arguments like year, month and day.

How to check First Date is before of Second Date :
cal.before(currentcal):
it Returns a boolean value true, if the date mentioned for the cal object is previous date of the mentioned date for the currentcal object of the Calendar class, otherwise it returns the boolean value false.

How to check First Date is after of Second Date :
cal.after(currentcal):
It Returns a booean value true, if the date mentioned for the cal object is later date from the mentioned date for the currentcal object of the Calendar class, otherwise it returns the boolean value false.

Getting the current date using Java

Calendar.MONTH:
This field of the Calendar class returns the static integer which is the value of the month of the year.

Calendar.DAY:
This field returns a static integer value which is the value of the day of the month in the year.

Calendar.YEAR:
This field returns a static integer value which is the current year.

Here is the code of the program:

Scheduling Task for specific time usinng TimerTask and Timer in Java

Java  Utils package provides class called Timer which is facility for threads to schedule task for future execution. Execution can be one time or repeated.

To Schedule Specific task using Time, You need to do Following
1. Create TimerTask
2. Create Object of Timer
3. Schedule timer using timer.schedule


Java Program to create Own TimeTask

Hash Table in Java

HashTable is implementation of key value pair data Structure in Java. You can store value using key and can retrieve value using key. Key should be unique.

Java Provides Class called HashTable which has following importan methods.

1. put(Object key, Object value) - used to store value into hashtable
2.get(Object key) - used to get values from hashtable using key.

Hashtable hashTable = new Hashtable():

hashTable.put('key1', 'value1'):
This method takes two arguments in which, one is the key and another one is the value for the separate key.

Map map = new TreeMap(hashTable):

Finding an Element in a Sorted Array using Java

Arrays is Java Class which provides various methods for manipulating arrays (such as sorting and searching).

Sorting using Arrays :

Arrays.sort(srcArray)  sorts all the elements present in the array. By Default it sorts elements in ascending order where srcArray is source Array on which sorting will appy.

Binary Search using Arrays :
Arrays.binarySearch(srcArray, element) - searches the element in the specified source array in the way of binary search. Binary Search takes more less time than the index search or the sequential search.

Sorting elements of a Collection in Java

Java Collections class provided method called sort which is used to sort List.
Ex.Collections.sort(list):

Java Program to sort elements using Collections.sort:
String names = "Ali Anuj Munjal Jigar Kamesh Harish Kamesh";
List lstoriginal = Arrays.asList(names.split(" "));
System.out.println("Element in List"+lstoriginal);

Collections.sort(lstoriginal);
System.out.println("Arrays After sorting : "+lstoriginal);


How to convert List to Array using Java

List is interface and ArrayList is class which implements List Interface.
To add elements to List, add() method is used.

List provied toArray metiond which is used to convert basically Collection to Array using Java
List.toArray(new String[0]):

Java Program to convert List to Array :

List lstFruit = new ArrayList();
lstFruit.add("Apple Juice "); 
lstFruit.add("Pinaple Juice"); 
lstFruit.add("Watermalones Juice"); 

String[] arrayFruits = lstFruit.toArray(new String[0]);        
for(int i = 0; i < arrayFruits.length; ++i){
   System.out.println(arrayFruits[i]);
} 

How to Iterate Linklist using Java

LinkedList is java class which implements List interface. Hence same way can be used to iterate LinkList using Iterator.

Java Utils package provides Iterator interface to iterate over collection. LinkedList is part of Collection. You can check whether next elements is available or not using hasNext() method.

If next element is available, next() method is used to retrieve element.

Java Program to iterate LinkedList :
LinkedList list = new LinkedList();
list.add(5);
list.add(1);
list.add(2);
list.add(10);
list.add(6);

// iterate over list
Iterator iterator = list.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}

Implementing a Stack in Java

A Stack is like a bucket in which you can put elements one-by-one in sequence and retrieve elements from the bucket according to the sequence of the last entered element. Stack is a collection of data and follows the LIFO (Last in, first out) rule that mean you can insert the elements one-by-one in sequence and the last inserted element can be retrieved at once from the bucket. Elements are inserted and retrieved to/from the stack through the push() and pop() method.


Using Following Stack Java Program , You will be able to do as :

1. Add elements into stack
2. Read all elements from Stack
3. Remove elements from Stack
4. Get element at specific index in Stack
5. Check capacity of Stack
6. Check that Wether Stack contains specific element or not
7. Clear the Stack
8. Check that Stack is empty or not

Implement the Queue in Java

A queue holds a collection of data or elements and follows the FIFO ( First In First Out) rule. The FIFO that means which data added first in the list, only that element can be removed or retrieved first from the list. In other sense, You can remove or perform operation on that data which had been added first in the Collection (list). Whenever you need to remove the last added element then you must remove all these elements which are entered before the certain element.

Using following Queue Java Program, You can do :

1. Get Size of queue
2. Get first element and don't remove it from Queue
3. Get first element and remove it from Queue
4. Check that wether element is present in Queue or not
5. Clear the queue
6. Check that Queue is cleared or not
7. Add Elements into Queue
8. Iterate and list elements in Queue

How to display All Available Time Zones Information using Java

Java Utils provides class named TimeZone which has many inbuilt methods to retrieve available timeZoneId, retrieve timeZone name along with Daylight and current time.

TimeZone Important Methods :
  1. getAvailableIDs - used to get available timezone Ids
  2. getDisplayName - used to display timeZone Name
  3. getRawOffset - used to get amount of time in milliseconds to add to UTC to get standard time
Please refer to TimeZone API Documentation for more details.

Determining the Number of Days in a Month

GregorianCalendar is a concrete subclass of Calendar and provides the standard calendar system used by most of the world.

GregorianCalendar is a hybrid calendar that supports both the Julian and Gregorian calendar systems with the support of a single discontinuity

Constructor for GregorianCalendar looks like :

GregorianCalendar(year, Calendar.FEBRUARY, 1):
Year and month are specified in the constructor to create instance for finding the number of days in that month of the specified year.

GregorianCalendar the constructor takes three arguments as follows:

* First is the year.
* Second is the month Ex. February.
* And third is the initial date value.