Sunday, June 30, 2013

Java Static Import Example

Static Import Example

Static import java is the great feature, which is available in Java 1.5.

Before static import came into picture, the developer needs to access the members through

class name.

For Example : ClassName.methodName();

                     ClassName.dataMember;

But with static imports you just import the members in the import section of the class, i.e

import static members at the top of the class, after package statement and before declaring

class.

If the class is too big and you are importing too many members using static import concept

it is unnecessary confusion for the developer. so you should use the static imports wherever

you require which are suitable to implement in the application. Don't import unnecessary static imports

which you are not using in that application.

Static import syntax :

import static package.className.member;

If suppose two variables/methods are same in two classes, you are importing them in the same

class, you will get compilation error.

The import <pkg.className.member> collides with another import statement.

Sample code for static import Example :


 package javademos.staticimport.example;  
 public class CommonHelper {  
      public final static int MAX_HEIGHT = 11;  
      public final static int MAX_AGE = 100;  
      public static int countTokens(String str) {  
           String[] strArray = null;  
           strArray = str != null ? str.split(",") : null;  
           return strArray != null ? strArray.length : 0;  
      }  
 }  



 package javademos.staticimport.example;  
 //import static members at the top of the class.  
 //import static data members  
 import static javademos.staticimport.example.CommonHelper.MAX_AGE;  
 import static javademos.staticimport.example.CommonHelper.MAX_HEIGHT;  
 //import static methods  
 import static javademos.staticimport.example.CommonHelper.countTokens;  
 /**  
  * java static import example  
  * Static import is very much useful while developing the applicatins.  
  * You just import the members you require at the top of the class and  
  * use in your application directly.  
  *   
  */  
 public class MainClass {  
      public static void main(String[] args) {  
           System.out.println("Person Max Age : " +MAX_AGE);  
           System.out.println("Person Max Height : " +MAX_HEIGHT);  
           System.out.println("No of tokens : "+countTokens("a,b,c"));  
      }  
 }  

Output of the Code :

Person Max Age100
Person Max Height11
3



Sunday, May 12, 2013

Access specifiers in java

Access specifiers in java :

Access specifiers in java classified into four types for the members. Access specifiers place a very important 

role in real time java applications. While developing the application we are defined the members which are 

visible outside of the class and which should not visible out side of the package. Suppose in some scenarios 

we strictly  hide some of the members which are only visible in side the class and the members which should 

not visible any of the other classes. 

  • Private
  • Default
  • Protected
  • Public
In a same class we can access all the other members of a class directly irrespective of the  access specifiers.

Private access specifier :

The visibility of the private access specifier is only with in the class. we can not access the private access 

specifiers outside of the class.

Example :

public class Test{
  private int value = 10;
}

Public access specifier :

If we declares the members of a class as public, it can be accessible any where. I mean it can be accessible

inside the class, outside the class, outside of the other packages.


Example :

public class Test{
  public int value = 10;
}

Protected access specifier :

If we declares the members of a class as protected, it can be accessible with in the same package 

and sub classes of outside the package. 

Example :

public class Test{
  protected int value = 10;
}

Default access specifier :

If we declares the members of a class as Default, it can be accessible with in the same package 

and sub classes of the same package 

We can not any access specifier for default.

Example :

public class Test{
   int value = 10;
}


Java File Output Stream Example

Java File Output Stream Example

We can write the file content by using File Output Stream .

File Output Stream  writes the stream of raw bytes to the file.

File output Stream writes the data by using the write() method.

File output Stream Example:


 import java.io.File;  
 import java.io.FileOutputStream;  
 import java.io.IOException;  
      //write the file content using File OutputStream.  
      public class FileOutputStreamExample {  
            public static void main(String[] args) {  
                 FileOutputStream fos = null;//<i>File Output Stream</i>   
                File fileName = null;  
                 try {  
                      fileName = new File("C:\\core.txt");  
                      fileName.createNewFile();  
                      fos = new FileOutputStream(fileName);  
                      fos.write("Hello Write this content".getBytes());  
                      fos.flush();                       
                } catch (IOException e) {  
                     e.printStackTrace();  
                } finally {  
                     try {  
                          if (fos != null){  
                               fos.close();  
                               fos = null;  
                          }  
                     } catch (IOException ex) {  
                          ex.printStackTrace();  
                     }  
                }  
           }  
      }  



Java File Input Stream Example

Java File Input Stream Example

We can read the files content by using File Input Stream also.

File Input Stream  reads the stream of raw bytes.

File Input Stream reads the data by using the read() method.

File input Stream Example:


 import java.io.File;  
 import java.io.FileInputStream;  
 import java.io.IOException;  
 //Read the file content using File InputStream.  
 public class FileInputStreamExample {  
       public static void main(String[] args) {  
            FileInputStream fis = null;//<i>File Input Stream</i>   
           File fileName = null;  
            try {  
                 fileName = new File("C:\\core.txt");  
                 fis = new FileInputStream(fileName);  
                 int c;  
                 while ((c = fis.read()) != -1) {  
                     System.out.print((char) c);  
                }  
           } catch (IOException e) {  
                e.printStackTrace();  
           } finally {  
                try {  
                     if (fis != null){  
                          fis.close();  
                          fis = null;  
                     }  
                } catch (IOException ex) {  
                     ex.printStackTrace();  
                }  
           }  
      }  
 }  


Java Constructor Example

Java Constructor Example

In java the Objects are created by using the constructor.

Once we define a class in the java application, automatically the java compiler provides the

default constructor.

We can define parameterized constructors also depends on our requirement.

Example :

 Test test = new Test();
 class Test{
 }

In class Test we haven't defined any constructor, here the java compiler provides the constructor.

//default constructor in class Test
class Test{
  Test(){
 }
}

Constructor name must be same as class name.

//parameterized constructor

class Test{
  Test(int a,int b){
  }
}

Once we write any parameterized constructors in the class, the java compiler does not provide any
default constructor, so if we want default constructor we need explicitly define the default constructor
in the class.

To create an object for a class using parameterized constructor

Example : Test test = new Test(5,6);

Constructor is also similar to java methods, but there are the below differences
  • We must specify the return type for the method definition, where as for constructor there should not be any return type specified.
  • We can give any name for a method, but coming to constructor the constructor name and class name must be same.
 public class ConstructorExample {  
      ConstructorExample(){  
           System.out.println("default constructor");  
      }  
   ConstructorExample(int a){  
        System.out.println("one parameterized constructor "+a);  
      }  
   ConstructorExample(int a ,int b){  
        System.out.println("Two parameterized constructor "+a+ " "+b);  
      }  
      public static void main(String[] args) {  
           ConstructorExample c = new ConstructorExample();  
           ConstructorExample c1 = new ConstructorExample(1);  
           ConstructorExample c2 = new ConstructorExample(1,2);  
      }  
 }  

Output :

default constructor
one parameterized constructor 1
Two parameterized constructor 1 2

Html5 Examples

Html5 Video Example

Html5 Video Example

Html5 Video is very simple to embed video in the web page.

It is very simple, to embed the video in our browser we just use the video tag as shown in

below example.

The controls attribute which adds video controls like volume, play and pause....etc

source tag which will give the link to the video files.

for src attribute , we should give the path of the media files and for type attribute  will give

the media type.

you can change the width and height based on webpage look and feel.

Below you can find very simple Html5 Video example.


 <html>  
 <body>  
 <video width="111" height="111" controls>  
  Video tag does not support yoiur browser.  
  <source src="http://javademos.blogspot.com/java.mp4" type="video/mp4">  
  <source src="http://javademos.blogspot.com/java.mpeg" type="video/mpeg">  
 </video>  
 </body>  
 </html>  

Saturday, May 11, 2013

Java BufferedWriter

Java BufferedWriter 

BufferedWriter is the class which is under the package java.io.

BufferedWriter  Write text to a character-output stream.

We can write characters to the file  by using the  write methods .

Below i am giving the very simple example, which writes the some text content

to the file. if file is there it overwrites the content, if file is not there, it creates one file


Java BufferedWriter  Example


 import java.io.BufferedWriter;  
 import java.io.File;  
 import java.io.FileWriter;  
 import java.io.IOException;  
      //Write the content into the file  
      public class Java_BufferedWriterExample {  
            public static void main(String[] args) {  
                 BufferedWriter br = null;  
                FileWriter fr = null;  
                File file = null;  
                try {  
                      file = new File("C:\\core1.txt");  
                      file.createNewFile();  
                      fr = new FileWriter(file);  
                      br = new BufferedWriter(fr);  
                      fr.write("hello");  
                      fr.write("how are you");  
                } catch (IOException e) {  
                     e.printStackTrace();  
                } finally {  
                     try {  
                          if (fr != null){  
                               fr.close();  
                               fr = null;  
                          }  
                          if (br != null){  
                               br.close();  
                               br = null;  
                          }  
                     } catch (IOException ex) {  
                          ex.printStackTrace();  
                     }  
                }  
           }  
      }  


Java BufferedReader

Java BufferedReader Example

BufferedReader is the class which is there in java.io package.

Buffered Reader reads the text from a character-input stream. We will pass the FileReader

as constructor argument to the  Buffered Reader.

BufferedReader reads the file line by line, character, group of characters.

Create one .txt file under C directory.

I am giving below very straight forward example which reads the file content line by line and print

in the console.

While iterating to the file, if the pointer reaches to the end of the file, the readLine() method

which return the null value.

BufferedReader Example



 import java.io.BufferedReader;  
 import java.io.File;  
 import java.io.FileReader;  
 import java.io.IOException;  
 //Read the file using Buffered reader.  
 public class Java_Bufferedreader {  
       public static void main(String[] args) {  
            BufferedReader br = null;  
           FileReader fr = null;  
           File file = null;  
           String line = null;  
            try {  
                 file = new File("C:\\core.txt");  
                 fr = new FileReader(file);  
                 br = new BufferedReader(fr);  
                 while ((line = br.readLine()) != null) {  
                     System.out.println(line);  
                }   
           } catch (IOException e) {  
                e.printStackTrace();  
           } finally {  
                try {  
                     if (fr != null){  
                          fr.close();  
                          fr = null;  
                     }  
                     if (br != null){  
                          br.close();  
                          br = null;  
                     }  
                } catch (IOException ex) {  
                     ex.printStackTrace();  
                }  
           }  
      }  
 }  


Java String

Java String

String class is available under the package java.lang.String.

String class is very important class, we almost use most of the places while developing the applications.

We no need to import this class in our code, automatically this class is available.

String is final class, so the string object can not be modify.

String class is immutable object, that means its contents can not be editable.

There are lot of methods are there to perform string operations like indexOf, concat,charAt...etc

We can create string objects in number of ways.

String str = "Javademos.blogspot";

It is a string constant, it will store in string constant pool.

The other way to create string object is by using new operator.

String str = new String("Javademos.blogspot");

char[] cArray = {'J','A','V','A'};

String str = new String(cArray);

There are many ways we can create string object like passing the byte[] constructor...etc.

We have  number of methods in string class to perform operations on strings.

I am giving the most useful methods which are frequently using in java real time applications.

 public class StringExample {  
      public static void main(String[] args) {  
                String str1 = new String("java");  
                String str2 = new String("j2ee");  
                //equals method Compares string to the specified object.  
                boolean flag = str1.equals(str2);  
                System.out.println("equals .. "+flag);  
                //equalsIgnoreCase method Compares String to another String, ignoring case considerations.  
                flag = str1.equalsIgnoreCase(str2);  
                System.out.println("equalsIgnoreCase .. "+flag);  
                //charAt method gives the character position.  
                int position = str1.charAt(3);  
                System.out.println("charAt .. "+position);  
                //concat the strings  
                String str = str1.concat(str2);  
                System.out.println("concat .. "+str);  
                //replace the characters  
                str = str1.replace('a','b');  
                System.out.println("replace .. "+str);  
                //return the substring  
                str = str1.substring(2);  
                System.out.println("substring .. "+str);  
                //convert all the chars to lower case  
                str = str1.toLowerCase();  
                System.out.println("toLowerCase .. "+str);  
                //convert all the chars to upper case  
                str = str1.toUpperCase();  
                System.out.println("toUpperCase .. "+str);  
                String str4 = " abc ";  
                //with leading and trailing whitespace omitted  
                str = str4.trim();  
                System.out.println("trim .. "+str);  
                //Tests if this string starts with the specified prefix  
                flag = str1.startsWith("j");  
                System.out.println("startsWith .. "+flag);  
                //Tests if this string ends with the specified prefix  
                flag = str1.endsWith("j");  
                System.out.println("endsWith .. "+flag);  
                //length of the string  
                System.out.println("endsWith .. "+str1.length());  
      }  
 }  


OutPut : equals .. false
equalsIgnoreCase .. false
charAt .. 97
concat .. javaj2ee
replace .. jbvb
substring .. va
toLowerCase .. java
toUpperCase .. JAVA
trim .. abc
startsWith .. true
endsWith .. false
endsWith .. 4

There are lot of methods are available you can refer the java string api.

Java static import

java import static

Static import in java is the feature which is available in Java 1.5.

This is the best feature if we want to use in some real time scenarios.

Before java 1.5 if we want to use the static members in another classes/packages

we are using the Classname.MemberName, For Example ClassA.Method();

But With this static import feature, we just define the classname/members starting with

import static pkg.class;
import static pkg.class.memberNames;

In the code we can directly use the static members, if we write static import.
But at the same time we cann't use more static members. in long run the new developer
may gets confused which member is for which class.

static imports in java Example:


 package javademos;  
 public class AppConstants {  
  public static int maxTimeLimit = 1 ;//in hours  
  public static int minTimeLimit = 1 ;//in hours  
 }  


 package javademos;  
 import static javademos.AppConstants.*;  
 // Importing all static members and using directly as shown below.
 public class StaticImport {  
      public static void main(String[] args) {  
           System.out.println("maxTimeLimit "+maxTimeLimit);  
           System.out.println("minTimeLimit "+minTimeLimit);  
      }  
 }  


Linked HashSet Example

LinkedHashSet Example :

LinkedHashSet is the class which is available in java.util package.

The main advantage of LinkedHashSet is, it preserves the order of the elements. I mean while iterating the
LinkedHashSet  the elements are retrieve in the same order how we insert into it.

LinkedHashSet implements the Set interface, it allows the Null values and allows unique elements.

LinkedHashSet  has lot of methods which are very much useful.

LinkedHashSet which extends the java.util.HashSet Class and all the methods which are available in HashSet class are available in the LinkedHashSet class.



 import java.util.Iterator;  
 import java.util.LinkedHashSet;  
      //LinkeHashSetExample Example Java  
      public class LinkeHashSetExample {  
        public static void main(String[] args) {  
          //LinkeHashSetExample, it preserves order of the elements.  
             LinkedHashSet<String> linkedHashSet = new LinkedHashSet<String>();  
             linkedHashSet.add("Item1");  
             linkedHashSet.add("Item2");  
             linkedHashSet.add("Item2");  
             linkedHashSet.add("Item4");  
             linkedHashSet.add("Item3");  
             linkedHashSet.add(null);  
             linkedHashSet.add(null);  
          Iterator<String> iterator = linkedHashSet.iterator();  
          while (iterator.hasNext()) {  
            System.out.println(iterator.next());  
          }  
          linkedHashSet.remove("Item2");  
          System.out.println("After removing Item2...");  
          // after removing jsp  
          iterator = linkedHashSet.iterator();  
          while (iterator.hasNext()) {  
            System.out.println(iterator.next());  
          }  
          if (linkedHashSet.contains("Item3")) {  
            System.out.println("Item3 available");  
          }  
        }  
      }  

Output : Item1
Item2
Item4
Item3
null
After removing Item2...
Item1
Item4
Item3
null
Item3 available

Wednesday, April 10, 2013

Java HashSet Example

Java HashSet Example

HashSet is the class, which is available in java.util package.  HashSet implements the set interface.

HashSet does not preservs the order, suppose if we inert the elments in the HashSet in some order, while
 Iterating we can not guarantee to get the same order.

HashSet allows the null values.

HashSet has the methods like add,remove,size,isEmpty...etc.

Java HashSet Sample Code : 

 
import java.util.Iterator;
import java.util.HashSet;

//HashSet Example Java
public class JavaHashSetExample {

    public static void main(String[] args) {
        // The advantage of HashSet is it sorts the elements.
        HashSet<String> hashSet = new HashSet<String>();
        hashSet.add("spring");
        hashSet.add("hibernate");
        hashSet.add("struts");
        hashSet.add(null);
        hashSet.add("webservices");
        System.out.println("size : " + hashSet.size());
        Iterator<String> iterator = hashSet.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }
        hashSet.remove("struts");
        System.out.println("After removing struts");
        // after removing jsp
        iterator = hashSet.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }
        if (hashSet.contains("struts")) {
            System.out.println("struts available");
        } else {
            System.out.println("struts not available");
        }

    }

}



Output of the code :

size : 5

null
webservices
hibernate
spring
struts

After removing struts

null
webservices
hibernate
spring
struts not available


Java ListIterator Example

Java List Iterator Example:

List Iterator is the interface in java.util package.
ListIterator has lot of methods which are very much useful based on our real time scenerios.

ListIterator has methods which we can iterate in the forward / reverse direction.
and ListIterator also have the methods like prviousIndex and nextIndex methods.
and it also has set,remove and add methods.

I am giving the below very basic ListIterator Sample.

 Java List Iterator sample code :


import java.util.ArrayList;
import java.util.ListIterator;

/*
 * Java ListIterator Example
 */
public class JavaListIteratorExample {

    @SuppressWarnings({ "rawtypes", "unchecked" })
    public static void main(String[] args) {

        // Storing the elements into the arraylist.
        ArrayList aList = new ArrayList();
        aList.add("val-1");
        aList.add("val-2");
        aList.add("val-3");

        // Retrieving the elements from the ArrayList by using ListIterator
        ListIterator listIterator = aList.listIterator();

        String value = "";
        System.out.println("List Iterator in the forward direction");
        while (listIterator.hasNext()) {
            value = (String) listIterator.next();
            System.out.println(value);
        }
        System.out.println("List Iterator in the Reverse direction");
        while (listIterator.hasPrevious()) {
            value = (String) listIterator.previous();
            System.out.println(value);
        }
        System.out.println("List Iterator Previous Index : "
                + listIterator.previousIndex());
        System.out.println("List Iterator Next Index : "
                + listIterator.nextIndex());
    }

}



Output of the above code ;

List Iterator in the forward direction
val-1
val-2
val-3
List Iterator in the Reverse direction
val-3
val-2
val-1
List Iterator Previous Index : -1
List Iterator Next Index : 0



Sunday, April 7, 2013

Java TreeSet Example

Java TreeSet Example

TreeSet is the class which is available in java.util package.

The main advantage of TreeSet is, it automatically sorts the elements.

TreeSet implements the Set interface, it doesn't allow the Null values and allows unique elements.

TreeSet has lot of methods which are very much useful.

TreeSet isEmpty() method which checks whether the TreeSet is empty or not.

TreeSet methods are remove,removeall, add,addall,contails,contailsall...etc

 Java TreeSet Example Code


import java.util.Iterator;
import java.util.TreeSet;
//TreeSet Example Java
public class TreeSetExampleJava {

    public static void main(String[] args) {
        //TreeSet, it sorts the elements.
        TreeSet<String> treeSet = new TreeSet<String>();
        treeSet.add("corejava");
        treeSet.add("jsp");
        treeSet.add("jsp");
        //treeSet.add(null);
        treeSet.add("servlets");
        treeSet.add("jdbc");
        
        Iterator<String> iterator = treeSet.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }
        treeSet.remove("jsp");
        System.out.println("After removing jsp");
        // after removing jsp
        iterator = treeSet.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }
        if (treeSet.contains("jdbc")) {
            System.out.println("jdbc available");
        }

    }

}


Output :
 
corejava
jdbc
jsp
servlets
After removing jsp
corejava
jdbc
servlets
jdbc available


Java Enhanced For Loop Example

Java Enhanced For Loop Example :

Enhanced For Loop is a more easy way and convenient way to iterate the elements from the collections or Arrays.

I am giving very basic Enhanced For Loop Example below.

The below code is very straight forward how you iterate the elements over the collections/arrays by using
Enhanced For Loop.

Enhanced For Loop Example Code 

import java.util.ArrayList;
//Java Enhanced for Loop Example
public class EnhancedForLoopExample {
    public static void main(String[] args) {
        String[] array = new String[] { "v1", "v2", "v3" };
        //Normal for loop iterate elements from the Array
        for (int i = 0; i < array.length; i++) {
            System.out.println("Normal For Loop : " + array[i]);
        }
        //Enhanced for Loop iterate elements from the Array
        for (String value : array) {
            System.out.println("Enhanced For Loop : " + value);
        }
        //Using generics storing the elements into the ArrayList
        ArrayList<String> aList = new ArrayList<String>();
        aList.add("v-1");
        aList.add("v-2");
        aList.add("v-3");
        //Normal for loop iterate elements from the ArrayList
        for (int i = 0; i < aList.size(); i++) {
            System.out.println("Normal For Loop : " + aList.get(i));
        }
        //Enhanced for Loop iterate elements from the ArrayList
        for (String value : aList) {
            System.out.println("Enhanced For Loop : " + value);
        }
    }
}


Output of the Program :


Normal For Loop : v1
Normal For Loop : v2
Normal For Loop : v3


Enhanced For Loop : v1
Enhanced For Loop : v2
Enhanced For Loop : v3


Normal For Loop : v-1
Normal For Loop : v-2
Normal For Loop : v-3


Enhanced For Loop : v-1
Enhanced For Loop : v-2
Enhanced For Loop : v-3





 

Saturday, April 6, 2013

Java Iterator Example

Java Iterator Example

I am giving the very straight forward example how you Iterate the elements from the ArrayList.

Iterator is the interface which is there in the package java.util.

You can iterate the elements from the Iterator by using the methods hashNext() and next().

By using remove() method we can remove the elements from the Iterator.

Sample code for the Java Iterator Example :


import java.util.ArrayList;
import java.util.Iterator;

/*
 * JavaIterator Example
 */
public class JavaIteratorExample {
    
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public static void main(String[] args) {
        
        //Storing the elements into the arraylist.
        ArrayList aList = new ArrayList();
        aList.add("val-1");
        aList.add("val-2");
        aList.add("val-3");
        
        //Retrieving the elements from the ArrayList by using Iterator
        Iterator iterator = aList.iterator();
        String value = "";
        while(iterator.hasNext()){
            value = (String)iterator.next();
            System.out.println(value);            
        }                
    }

}


Output :

val-1
val-2
val-3




Friday, March 29, 2013

StringTokenizer Example

StringTokenizer Example:

StringTokenizer is the class in java.util package.

The use of StringTokenizer class is breaks the given string into number of tokens based on the delimiter.

Here i am giving the very simple StringTokenizer Example. you can easily understand the below code.

In the below example, i am using the delimiter as ';'

While creating the StringTokenizer object I am passing the given string and the delimiter.

By using the countTokens() method, will get the total number of tokens.

String Tokenizer Sample code

 import java.util.StringTokenizer;  
 /**  
  * Java String Tokenizer example  
  */  
 public class StringTokenizerExample {  
      public static void main(String[] args) {  
           String str = "value1;value2;value3;value4";  
           StringTokenizer stringTokenizer = new StringTokenizer(str, ";");  
           //return the total number of tokens  
           int totalTokens = stringTokenizer.countTokens();  
           System.out.println("Total Tokens " + totalTokens);  
           //Iterate and print all the tokens  
           while (stringTokenizer.hasMoreElements()) {  
                System.out.println(stringTokenizer.nextElement());  
           }  
           //You can use the below method also to print the tokens.  
           // while(stringTokenizer.hasMoreTokens()){  
           // System.out.println(stringTokenizer.nextToken());  
           // }  
      }  
 }  


Output :


Total Tokens 4
value1
value2
value3
value4


You can also use split method to split the given string into number of tokens.

String[]   tokens = str.split(";");


Wednesday, March 20, 2013

Java HashMap Example

Java HashMap Example :

HashMap is the class in java.util package, The main advantage of HashMap is to store the information in the form of Key/Value pairs. In this HashMap Object we can store the null values also. that means the HashMap accepts to store the null values as key/value pairs. Suppose you are retrieving the data from the database, if some records are returned with null values. you can store these null values also in this HashMap object.

HashMap is not synchronized.


Below is the very straight and quick start example for HashMap.

The below HashMap example stores key/value pairs and just retrieve from the HashMap again and printing the key/value data.


import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class HashMapExample {

    @SuppressWarnings("unchecked")
    public static void main(String[] args) {
        @SuppressWarnings("rawtypes")
        HashMap map = new HashMap();
        // add the elements to the hashmap
        map.put("key1", "value1");
        map.put("key2", "value2");
        map.put("key3", "value3");
        map.put("key4", null);
        @SuppressWarnings("rawtypes")
        Set set = map.entrySet();
        @SuppressWarnings("rawtypes")
        Iterator iterator = set.iterator();
        // Iterate teh elements from the hashmap
        while (iterator.hasNext()) {
            @SuppressWarnings("rawtypes")
            Map.Entry keyValue = (Map.Entry) iterator.next();
            System.out.println("key....." + keyValue.getKey() + " value...."
                    + keyValue.getValue());
        }

    }

}



Output :

key.....key4 value....null
key.....key3 value....value3
key.....key2 value....value2
key.....key1 value....value1





Sunday, March 17, 2013

Java ArrayList Example

Java ArrayList Example :

Java ArrayList Example, I am giving very straight, short and easy description, you can straight away use this in your Code.

ArrayList : You can find this ArrayList class in java.util package. There are lot of methods available to manipulate ArrayList Object.

The advantage of ArrayList is to store the different kind of objects, either string or user defined class objects.

In the below i am giving the ArrayList Example how you can store the String Objects and again get the objects from that ArrayList object.

Here i am giving the two ways two get the Elements from the ArrayList object,

1) Get the elements from the ArrayLsit  by using Iterator.
2) Get the elements from the ArrayLsit  by using For Loop.


ArrayList Example 

import java.util.ArrayList;
import java.util.Iterator;

public class ArrayListExample {
    @SuppressWarnings("unchecked")
    public static void main(String[] args) {
        @SuppressWarnings("rawtypes")
        // Create an ArrayList Object and add the elements into it.
        ArrayList aList = new ArrayList();
        // Add the String objects in the ArrayList
        aList.add("Test1");
        aList.add("Test2");
        aList.add("Test3");
        // Get the Elements from the ArrayList
        @SuppressWarnings("rawtypes")
        Iterator itr = aList.iterator();
        System.out
                .println("Using Iterator to get the Elememts from the ArrayList: ");
        while (itr.hasNext()) {
            System.out.println((String) itr.next());
        }
        // Another Way To get the elements from the ArrayList
        System.out
                .println("Using for Loop to get the Elememts from the ArrayList: ");
        for (int i = 0; i < aList.size(); i++) {
            System.out.println((String) aList.get(i));
        }
    }
}



OutPut :

Using Iterator to get the Elements from the ArrayList:
Test1
Test2
Test3
Using for Loop to get the Elements from the ArrayList:
Test1
Test2
Test3


Thursday, March 14, 2013

Core Java Samples


Hello World Example                                   LinkedHashSet Example

Java ArrayList Example                               Java static import

Java HashMap Example                               Java String

StringTokenizer Example                             Java BufferedReader

Java Iterator Example                                  JavaBufferedWriterExample

Java TreeSet Example                                 Java Constructor Example

Java Enahnced For Loop Example                Java File Input Stream Example

Java ListIterator Example                            Java File Output Stream Example

Java HashSet Example                                Access Specifiers in Java

java static import example

Hello World Example


Java Hello World Example 

It is very simple in java to write the Hello World Example. In this Example, We just print the Text as Hello World Example on the console after executing this Program.

The below Example is very straight forward example, take the below code and just compile using from the  command prompt or you can use any tools like eclipse.

Use the Javac command to compile the java program, for Example Javac HelloWorld.java. Once you compile this program, the Java compiler compiles and generates the .class file. It is in the byte code format.

Then you execute this program by using java command for example java HelloWorld

Once you invoke the above command, we get the output as 'Hello World Example'.




 public HelloWorldExample{
  public static void main(String[] args){
   System.out.println("Hello World Example");  
  }
 }

Monday, March 11, 2013

Java Interview Questions


  •   if(null==null){

System.out.println("Both are equal");
          }else{
System.out.println("Both are not equal");
          }
       
           What is the output for the above code?

          Output : Both are equal.

  • Difference between finally and finalize?
  • What is cloning? what is deep and shallow cloning? How to do deep cloning?
  • How you write the program to read the file?
  • which version of java you used?
  • What is the difference between encapsulation and polymorphism?
  • Can you tell me about oops concepts?
  • what is polymorphism? Did you used anywhere in your project?
  • Did you work on multi threading in any of the project?
  • Can you tell me the scenarios, where you exactly used syncronization?
  • What is immutability?
  • you know how to make class as immutable object?
  • What is garbage collection? Can we invoke the garbage collection explicitly?
  • What are collections you used in your project?
  • Difference between Hashset and ArrayList?
  • How Hashset eliminates duplicates?
  • If you try to add duplicate element to the set, what happens?
  • what is the difference between java.util.Date and java.sql.Date?
  • what is the difference between java null and sql null?
  • how hashmap works internally?
  • Difference between HashMap and HashTable?
  • What is the difference between Array List and Vector?

 
Disclaimer : If you find any mistakes / corrections / feedback Please let us know...This website author shall not accept liability or responsibility for any errors, mistakes or misstatements found in this website.