Wednesday, June 4, 2014

Java Examples

Example using ArrayList:

import java.util.ArrayList;
import java.util.Iterator;
/**
 *
 * @author rdayala
 */
public class WelcomeJava {
    public static void main(String args[])
    {
        System.out.println("Welcome to Java Learning!");       
        Integer x = 5;
        Object obj = 5;
        int y = x.intValue();
        int z = ((Integer)obj).intValue();
        String name = "Raghu";
       
        System.out.printf("Y : %d, Z : %d\n\n", y, z);
       
        ArrayList list = new ArrayList();
        list.add("Raghu");
        list.add(1);
        list.add(12.5);              
                     
        Class listClass = list.getClass();
        System.out.println("list type: " + listClass.getName());
        System.out.println("list size: " + list.size());
        System.out.println("list elements are:");
       
// traversing ArrayList using iterator

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

Another Example:

import java.util.Scanner;
import javax.swing.JOptionPane;
import java.nio.file.*;
public class HelloWorld {

    /**
     * @param args the command line arguments
     */
    public static void main(String []args) {
        // TODO code application logic here
        System.out.println("Hello,World - Raghu!");
        System.out.println("Welcome to Java Programming Language");
       
        String valueFromUI = JOptionPane.showInputDialog("Enter Your Name:");
        System.out.println("Your name is: " + valueFromUI + ", Lenght of Name:" + valueFromUI.length());
       
        System.out.println("Enter a value from console:");
        Scanner input = new Scanner(System.in);       
        int value = input.nextInt();
       
        System.out.println("Value read from console is : " + value);
       
        int []num = new int[5];
        Class cls = num.getClass();
       
        System.out.println("Type of the array : " + cls.getName());
       
        int[] numArray = {1, 2, 3, 4, 5};
        int[] cpArray;
        cpArray = new int[5];
        System.arraycopy(numArray, 0, cpArray, 0, numArray.length);
        cpArray[3]=7;
       
        System.out.println("Num Array is: ");
        for(int val : numArray)
            System.out.print(val + " ");
       
        System.out.println("\nCopy Array is: ");
        for(int val : cpArray)
            System.out.print(val + " ");
       
        int[] clArray;
        clArray = numArray.clone();
        clArray[3]=8;
       
        System.out.println("\nNum Array is: ");
        for(int val : numArray)
            System.out.print(val + " ");
       
        System.out.println("\nClone Array is: ");
        for(int val : clArray)
            System.out.print(val + " ");
       
        FileSystem fs = FileSystems.getDefault();
        System.out.println("\nFileSystem is : " + fs.toString());
       
        Iterable<Path> roots = FileSystems.getDefault().getRootDirectories();
        for(Path rt : roots)
            System.out.println("\nRoot is: " + rt.toString());
               
        Path path = FileSystems.getDefault().getPath("home", "user", "images.gif");
        System.out.println("\nPath is : " + path.toString());

    }
}

Exception Example:

public class ExceptionTest {
       
    public static void main(String[] args) {
        int a = 15, b = 0;
        int c;
        try {
                if( a == 15)
                    throw new Exception("Please enter valid number for a");
                c = a / b;
        } catch(ArithmeticException e) {
            System.out.println("Inside catch block");
        }
        catch(Exception e)
        {
            System.out.println("General exception caught by throw statement.");
        }
        finally {
            System.out.println("Inside finally block");           
        }
    }
   
}

Convert a string to date in Java:

import java.text.SimpleDateFormat;
import java.util.Date;
public class Main {
  public static void main(String[] args) throws Exception {
    SimpleDateFormat myDateFormat = new SimpleDateFormat("dd/MM/yyyy");
    Date dateToday = dateFormat.parse("25/06/2011");
    System.out.println(myDateFormat.format(dateToday));
  }
}

Date & Time Example:

import java.util.Date;
import java.util.Calendar;
import java.text.SimpleDateFormat;
import java.text.DateFormat;
import java.text.ParseException;
import java.util.logging.Level;
import java.util.logging.Logger;

public class DatesAndTimes {
    public static void main(String[] args)
    {
        Date today = new Date();
        System.out.println("Today is : " + today.toString());
       
        Calendar cal = Calendar.getInstance();
        System.out.println("Today is : " + cal.getTime().toString());
        System.out.println("Timezone is : " + cal.getTimeZone().getID());
       
        Date todaysDate = new Date();
        int compareTo = today.compareTo(todaysDate);
        SimpleDateFormat formatter = new SimpleDateFormat("EEEE, dd-MMMM-yyyy HH:mm:ss a ZZZZ");
        String formattedString = formatter.format(todaysDate);
        System.out.println(formattedString);
       
        DateFormat df = DateFormat.getDateTimeInstance();
        String formatString = df.format(todaysDate);
        System.out.println(formatString);
       
        DateFormat df1 = DateFormat.getTimeInstance();
        String formatString1 = df1.format(todaysDate);
        System.out.println(formatString1);
       
        String dateString = "Jan 12, 1952 3:30:32 pm";
        DateFormat df2 = DateFormat.getDateTimeInstance();
        try {
            Date date1 = df2.parse(dateString);
            System.out.println("Parsed Date: " + date1.toString());
        } catch (ParseException ex) {
            Logger.getLogger(DatesAndTimes.class.getName()).log(Level.SEVERE, null, ex);
        }
       
        // date arithmetic using Date objects
        Date date = new Date();
        long time = date.getTime();
        time += 5*24*60*60*1000;
        Date futureDate = new Date(time);
       
        // date arithmetic using Calendar objects
        Calendar nowCal = Calendar.getInstance();
        nowCal.add(Calendar.DATE, 5);
       
        Date date1 = new Date();
        Date date2 = new Date();
        long time1 = date1.getTime();
        long time2 = date2.getTime();
       
        long diff = time2 - time1;
        System.out.println("Difference in days = " + diff/(1000*60*60*24));      
       
        if (date1.equals(date2)) {
            System.out.println("dates are the same.");
        }
        else {
            if (date1.before(date2)) {
                System.out.println("date1 before date2");
            }
            else {
                System.out.println("date1 after date2");
            }
        }
       
        System.out.println("Today is : " + cal.toString());
        System.out.println("Day of week: " + cal.get(Calendar.DAY_OF_WEEK));
        System.out.println("Month: " + cal.get(Calendar.MONTH));
        System.out.println("Year: " +  cal.get(Calendar.YEAR));
        System.out.println("Week number: " + cal.get(Calendar.WEEK_OF_YEAR));
       
        //long start = System.currentTimeMillis();
        // do some other stuff…
        // long end = System.currentTimeMillis();
        // long elapsedTime = end – start;
       
    }
}

Serialization Example:

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


Singleton using Enum:

enum MySingleton
{
    RAGHU;
    public void sayHello()
    {
        System.out.println("Hello Raghu!");
    }
   
    public void sayBye()
    {
        System.out.println("Bye Raghu!");
    }
}
public class Singleton {
    public static void main(String[] args)
    {
        MySingleton ms = MySingleton.RAGHU;
        ms.sayHello();
        ms.sayBye();
        MySingleton ms1 = MySingleton.RAGHU;
       
        if(ms == ms1)
            System.out.println("Referring to same singleton class");
    }
}

Final fields having different values, initialized using Constructor:

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


No comments:

Post a Comment