Monday, October 10, 2011

Conditional Operator Example in java.


package ConditionalOperatorExample;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class ConditionalOperatorExample
{
public static void main(String[] arun) throws IOException
{
String s1,s2,s3;
int i1,i2,i3,Max,Min;

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

System.out.println("Enter first number; ");
s1 = br.readLine();

System.out.println("Enter second number: ");
s2 = br.readLine();

System.out.println("Enter third number: ");
s3 = br.readLine();

i1 = Integer.valueOf(s1).intValue();
i2 = Integer.valueOf(s2).intValue();
i3 = Integer.valueOf(s3).intValue();

Max = (i1>i2)?((i1>i3)?i1:i3):((i2>i3)?i2:i3);
System.out.println("Maximum number is "+Max);

Min = (i1 System.out.println("Minimum number is "+Min);
}
}


Output =>
Enter first number;
25
Enter second number:
3
Enter third number:
64
Maximum number is 64
Minimum number is 3

Wednesday, September 28, 2011

A static method can't make reference of a non-static variable.


/*
* A static method can't make reference of a non-static variable.
* But a non-static method can make reference of a non-static as well as static variable.
*/
package SCJP;

public class StaticMethodExample
{
static int static_variable = 99;
int non_static_variable = 98;

public static void static_method()
{
System.out.println("Access static variable from static method = "+static_variable);
/*System.out.println("Access non-static variable from static method = "+non_static_variable); can't do this coz of non-static variable.*/
}
public void non_static_method()
{
System.out.println("Access static variable from non-static method = "+static_variable);
System.out.println("Access non-static variable from non-static method = "+non_static_variable);
}


public static void main(String[] arun)
{
new StaticMethodExample().static_method();
new StaticMethodExample().non_static_method();
}
}


Output =>
Access static variable from static method = 99
Access static variable from non-static method = 99
Access non-static variable from non-static method = 98

Inner Class calling example


package SCJP;

public class innerClass
{
public static void main(String[] args)
{
A a = new A();
a.displayA();

A.B b1 = a.new B();
b1.displayB();

A.B b2 = new A().new B();
b2.displayB();
}
}
class A
{
public void displayA()
{
System.out.println("Hi! I am in class A");
}
class B
{
public void displayB()
{
System.out.println("Hi! I am in class B");
}
}
}
Output =>
Hi! I am in class A
Hi! I am in class B
Hi! I am in class B
***********************************************
[NOTE: Bellow class has only difference with above one is in above one class "A" is outside the class"innerClass" where as for the bellow one class "A" is inside the class "innerClassToAccessOuterClass"]
package SCJP;

public class innerClassToAccessOuterClass
{
public static void main(String[] arun)
{
A a = new innerClassAccessOuterClass().new A();
a.diaplayA();
}
class A
{
void diaplayA()
{
System.out.println("Hi! I am in class A.");
}
}
}

Output =>
Hi! I am in class A.

String and StringBuffer R&D.


R&D with String and StringBuffer.
**************************************************************
package SCJP;

public class StringExample1
{
public static void main(String[] args)
{
boolean s1 = "Arun" == "Arun";
boolean s2 = new String("Arun") == "Arun";
boolean s3 = new String("Arun") == new String("Arun");

System.out.println("S1 is "+s1);
System.out.println("S2 is "+s2);
System.out.println("S3 is "+s3);

System.out.println("(s2&&s3||s1) is "+(s2&&s3||s1));
}
}

Output =>
S1 is true
S2 is false
S3 is false
(s2&&s3||s1) is true
*****************************************************************
package SCJP;

public class StringExample2
{
public static void main(String arun[])
{
boolean s1 = "Arun" == "Arun";
boolean s2 = new String("Arun").equals(new String("Arun"));
boolean s3 = "Arun".toString() == "Arun";

System.out.println("S1 is "+s1);
System.out.println("S2 is "+s2);
System.out.println("S3 is "+s3);

System.out.println("(s1&&s2&&s3) is "+(s1&&s2&&s3));
}
}

Output =>
S1 is true
S2 is true
S3 is true
(s1&&s2&&s3) is true
******************************************************************
package SCJP;

public class StringExample3
{
public static void main(String[] args)
{
StringBuffer sb = "";//compile time error.
}
}
*******************************************************************
package SCJP;

public class StringExample4
{
public static void main(String[] args)
{
String s = null;
System.out.println(null+s);
}
}

Output =>
nullnull
*********************************************************************

Tuesday, September 27, 2011

SCJP-Link

Exception handling (Create my own exception)


package MyException;

public class MyException extends Exception {
public MyException(String str)
{
super(str);
}
}


package MyException;

public class mainClass
{
public static void main(String args[])
{
try
{
int n = 105;
if(n<199)
throw new MyException(n+" is less than 199");
}catch (MyException e)
{
System.out.println(e.getMessage());
}
}
}


Output =>
105 is less than 199

Monday, September 26, 2011

StringBuffer and StringBuilder are mutable (Example)


//Bellow program shows that StringBuffer/StringBuilder is mutable
package StringBuffered;
public class StringObjectIsImmutable
{
public static void main(String[] arun)
{
//StringBuffered is mutable and synchronized.
StringBuffer name = new StringBuffer("Arun");
System.out.println(name);
name.append(" Kumar");
// in the above line like String object no new StringBuffered Object (name) is created. That's the reason executable time for StringBuffer/String Builder is faster than String.
System.out.println(name);
/*//StringBuffered is mutable and not synchronized
StringBuilder name = new StringBuilder("Arun");
System.out.println(name);
name.append(" Kumar");
// in the above line like String object no new StringBuffered Object (name) is created. That's the reason executable time for StringBuffer/String Builder is faster than String.
System.out.println(name);*/
}
}
Output =>
Arun
Arun Kumar

String Object is immutable (example)


//Bellow program shows that String Object is immutable
package StringBufferedPackage;

public class StringObjectIsImmutable
{
public static void main(String[] arun)
{
String name = "Arun";
System.out.println("Initially name is "+ name);
//the above print statement print "Initially name is Arun"

name.concat(" Kumar");
System.out.println("After concat middle-name name print like => "+name);
//this println print as "After concat middle-name name print like => Arun" i.e concatenation didn't done here.

name = name.concat(" Kumar");
System.out.println("After creating a new string object the name become : "+name);
//it prove that string objects are immutable.
}
}


Output=>
Initially name is Arun
After concat middle-name name print like => Arun
After creating a new string object the name become : Arun Kumar

Different between String and StringBuffer/StringBuilder

A google search result.................
Different between String and StringBuffer/StringBuilder


Well, the most important difference between String and StringBuffer/StringBuilder in java is that String object is immutable whereas StringBuffer/StringBuilder objects are mutable.
By immutable, we mean that the value stored in the String object cannot be changed. Then the next question that comes to our mind is “If String is immutable then how am I able to change the contents of the object whenever I wish to?” . Well, to be precise it’s not the same String object that reflects the changes you do. Internally a new String object is created to do the changes.
So suppose you declare a String object:
String myString = “Hello”;
Next, you want to append “Guest” to the same String. What do you do?
myString = myString + ” Guest”;
When you print the contents of myString the output will be “Hello Guest”. Although we made use of the same object(myString), internally a new object was created in the process. So, if you were to do some string operation involving an append or trim or some other method call to modify your string object, you would really be creating those many new objects of class String.
Now isn’t that a performance issue?
Yes, it definitely is.
Then how do you make your string operations efficient?
By using StringBuffer or StringBuilder.
How would that help?
Well, since StringBuffer/StringBuilder objects are mutable, we can make changes to the value stored in the object. What this effectively means is that string operations such as append would be more efficient if performed using StringBuffer/StringBuilder objects than String objects.
Finally, whats the difference between StringBuffer and StringBuilder?
StringBuffer and StringBuilder have the same methods with one difference and that’s of synchronization. StringBuffer is synchronized( which means it is thread safe and hence you can use it when you implement threads for your methods) whereas StringBuilder is not synchronized( which implies it isn’t thread safe).
So, if you aren’t going to use threading then use the StringBuilder class as it’ll be more efficient than StringBuffer due to the absence of synchronization.
Incase you do not know – Here’s how you use StringBuilder
A simple Example to demonstrate that String object is Immutable
Incase you still have any doubts regarding String or StringBuilder then do leave a comment. I’ll be more than eager to help you out.
Note: StringBuilder was introduced in Java 1.5 (so if you happen to use versions 1.4 or below you’ll have to use StringBuffer)

transient variable example


//A transient variable is a variable that may not be serialized
package Serialization;

import java.io.Serializable;

public class serializableClass implements Serializable
{

/**
*
*/
private static final long serialVersionUID = 1L;

String name;
int DOB;
int DOM;
/*If we don't want to pass the Year Of Birth of any one, then we simply make that variable as "transient"*/
transient int year;
public serializableClass(String name,int dob,int year)
{
this.name = name;
this.DOB = dob;
this.year = year;
}
public void showWish()
{
System.out.print("Good Morning!");
}
public String toString()
{
showWish();
return "Mr."+name+". Your date of birth is "+DOB+"/"+DOM+"/"+year;
}
}

package Serialization;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class mainClass {
public static void main(String args[]) {
try {
System.out
.println("Start of serialization ******************************");
serializableClass srl = new serializableClass("Arun", 14, 1984);
srl.DOM = 02;

System.out.println(srl);
FileOutputStream fos = new FileOutputStream("serial");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(srl);

oos.close();
fos.close();
System.out
.println("End of serialization *************************");

} catch (Exception e) {
System.out.println(e);
System.exit(0);
}
try {
System.out.println("\n");
System.out
.println("Start of deserialization ************************");
serializableClass srl2;
FileInputStream fis = new FileInputStream("serial");
ObjectInputStream ois = new ObjectInputStream(fis);
srl2 = (serializableClass) ois.readObject();

System.out.println(srl2);
ois.close();
System.out
.println("End of deserialization ************************");

} catch (Exception e) {
System.out.println(e);
System.exit(0);
}
}
}


Output =>
Start of serialization ******************************
Good Morning!Mr.Arun. Your date of birth is 14/2/1984
End of serialization *************************


Start of deserialization ************************
Good Morning!Mr.Arun. Your date of birth is 14/2/0
End of deserialization ************************

SERILIZATION example in java


[NOTE:In SERILIZATION cases for sequirity purpose if we want only some of the parameters of a class can be deserialized and some not then the solution is only pass that parameter through toString() method on that class.
If we consider the bellow example then we can see that we don't want the DOB's "year" parameter on the time of deserialization. So we simply not pass the year parameter by the toString() method.]

package Serialization;

import java.io.Serializable;

public class serializableClass implements Serializable
{

/**
*
*/
private static final long serialVersionUID = 1L;

String name;
int DOB;
int DOM;
int year;
public serializableClass(String name,int dob,int year)
{
this.name = name;
this.DOB = dob;
this.year = year;
}
public void showWish()
{
System.out.print("Good Morning!");
}
/*public String toString()
{
showWish();
return "Mr."+name+". Your date of birth is "+DOB+"/"+DOM+"/"+year;
}*/

/*If we don't want to pass the Year Of Birth of any one, then we simply don't pass the "year" parameter through toString() method.*/
public String toString()
{
showWish();
return "Mr."+name+". Your date of birth is "+DOB+"/"+DOM;
}
}


package Serialization;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class mainClass
{
public static void main(String args[])
{
try
{
System.out.println("Start of serialization ******************************");
serializableClass srl = new serializableClass("Arun", 14, 1984);
srl.DOM = 02;
System.out.println(srl);
FileOutputStream fos = new FileOutputStream("serial");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(srl);

oos.close();
fos.close();
System.out.println("End of serialization *************************");

}catch(Exception e)
{
System.out.println(e);
System.exit(0);
}
try
{
System.out.println("\n");
System.out.println("Start of deserialization ************************");
serializableClass srl2;
FileInputStream fis = new FileInputStream("serial");
ObjectInputStream ois = new ObjectInputStream(fis);
srl2 = (serializableClass) ois.readObject();

System.out.println(srl2);
ois.close();
System.out.println("End of deserialization ************************");

} catch (Exception e)
{
System.out.println(e);
System.exit(0);
}
}
}

Output =>
Start of serialization ******************************
Good Morning!Mr.Arun. Your date of birth is 14/2
End of serialization *************************


Start of deserialization ************************
Good Morning!Mr.Arun. Your date of birth is 14/2
End of deserialization ************************

Friday, September 16, 2011

TreeMap Example in java


//Print the key and it's value where key is an integer and it's value is an ArrayList.
//TreeMapWithIntegerKeyAndListValues.java
import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;

public class TreeMapWithIntegerKeyAndListValues
{
public static void main(String arg[])
{
List list1 = new ArrayList();
List list2 = new ArrayList();
for (int i = 1; i < 11; i++)
{
list1.add(i);
list2.add(i);
}
TreeMap> treemap = new TreeMap>();

treemap.put(1, list2);

for (int key : treemap.keySet())
{
System.out.println("Key : " + key + " Value : " + treemap.get(key));
}
}
}

Output =>
Key : 1 Value : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

HashTable implemented by List


//Print a HashTable's key and values where key is an Integer element and value is a ArrayList.
//HashTableImplementedByList.java
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.List;

public class HashTableImplementedByList
{
public static void main(String arg[])
{
List list = new ArrayList();
for (int i = 1; i < 11; i++)
{
list.add(i);
}
Hashtable> hashtable = new Hashtable>();

hashtable.put(1, list);

Enumeration e;

System.out.print("HashTable key is: ");
e = hashtable.keys();
while (e.hasMoreElements())
{
Object o = (Object) e.nextElement();
System.out.println(o);
}
System.out.print("HashTable elements are : ");
e = hashtable.elements();
while (e.hasMoreElements())
{
Object o = (Object) e.nextElement();
System.out.println(o);

}
}
}


Output =>
HashTable key is: 1
HashTable elements are : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Tuesday, September 13, 2011

max() function and min() function to find out maximum and minimum number from an ArrayList


//Print the list value and also find out the maximum and minimum number from the list.
//MaxMinOfArrayLisExample.java
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

public class MaxMinOfArrayLisExample
{
public static void main(String arg[])
{
List li = new ArrayList();
li.add(23);
li.add(25);
li.add(27);
li.add(22);
li.add(29);
li.add(29);

Iterator it;
it = li.iterator();
System.out.println("The list is as follows");
while (it.hasNext())
{
System.out.println(it.next());
}

System.out.print("Max number from the list is ");
int maximum= Collections.max(li);
System.out.println(maximum);

System.out.print("Min number from the list is ");
int minimum= Collections.min(li);
System.out.println(minimum);
}
}


Output =>
The list is as follows
23
25
27
22
29
29
Max number from the list is 29
Min number from the list is 22

Find out location of a list element using BinarySearch


//How to find out location of a list element using BinarySearch
//UseBinarySearchExample.java
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class UseBinarySearchExample
{
public static void main(String arg[])
{
List ls = new ArrayList();
ls.add("Bappa");
ls.add("Tarun");
ls.add("Arun");
ls.add("Arup");
ls.add("Barun");
ls.add("Milan");

List li = new ArrayList();
li.add(23);
li.add(25);
li.add(27);
li.add(22);
li.add(29);
li.add(29);

int i= Collections.binarySearch(li,25);
System.out.println("25 location is: "+i);

int s= Collections.binarySearch(ls,"Barun");
System.out.println("Barun's location is "+s+"th");
}
}

Output =>
25 location is: 1
Barun's location is 4th

List sorting - Collections.sort() and Collections.reverse()


//Print a list in sorted order and also in reverse order.
//PrintListInDifferentOrderExample.java
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

public class PrintListInDifferentOrderExample
{
public static void main(String arg[])
{
List ls = new ArrayList();
ls.add("Bappa");
ls.add("Tarun");
ls.add("Arun");
ls.add("Arup");
ls.add("Barun");
ls.add("Milan");

List li = new ArrayList();
li.add(23);
li.add(25);
li.add(27);
li.add(22);
li.add(29);
li.add(29);

Collections.sort(ls);
Collections.sort(li);

Iterator it;

System.out.println("Print the name in sorted order");
it = ls.iterator();
while (it.hasNext())
{
System.out.println("Name: " + it.next());
}

System.out.println("Print the number in sorted order");
it = li.iterator();
while (it.hasNext())
{
System.out.println("Number: " + it.next());
}

Collections.reverse(ls);
System.out.println("Print the name in reverse order");
it = ls.iterator();
while (it.hasNext())
{
System.out.println("Number: " + it.next());
}

Collections.reverse(li);
System.out.println("Print the number in reverse order");
it = li.iterator();
while (it.hasNext())
{
System.out.println("Number: " + it.next());
}
}
}


Output =>
Print the name in sorted order
Name: Arun
Name: Arup
Name: Bappa
Name: Barun
Name: Milan
Name: Tarun
Print the number in sorted order
Number: 22
Number: 23
Number: 25
Number: 27
Number: 29
Number: 29
Print the name in reverse order
Number: Tarun
Number: Milan
Number: Barun
Number: Bappa
Number: Arup
Number: Arun
Print the number in reverse order
Number: 29
Number: 29
Number: 27
Number: 25
Number: 23
Number: 22

Comparator Example in java


//ComparatorExample.java
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;

public class ComparatorExample
{
public static void main(String arg[])
{
System.out.println("Print decreasing order using TreeSet");

Comparator c = Collections.reverseOrder();

Set s = new TreeSet(c);
s.add(1);
s.add(21);
s.add(12);
s.add(13);
s.add(4);
s.add(15);
s.add(16);
s.add(77);
s.add(18);
s.add(29);

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

}
}


Output =>
Print decreasing order using TreeSet
77
29
21
18
16
15
13
12
4
1

TreeMap Example in java


//How to print Name and age of students in sorted order with respect to their name ?
//TreeMapExample.java
import java.util.TreeMap;

public class TreeMapExample
{
public static void main(String arg[])
{
TreeMap treeMap = new TreeMap();

treeMap.put("Bappa", 23);
treeMap.put("Tarun", 25);
treeMap.put("Arun", 27);
treeMap.put("Arup", 22);
treeMap.put("Barun", 29);
treeMap.put("Milan", 29);

for(String name : treeMap.keySet())
{
System.out.println("Name: "+name+" Age= "+treeMap.get(name));
}
}
}

Output =>
Name: Arun Age= 27
Name: Arup Age= 22
Name: Bappa Age= 23
Name: Barun Age= 29
Name: Milan Age= 29
Name: Tarun Age= 25

Friday, September 9, 2011

HashMap supports null key and null values

HashMap supports one null key and more than one null values. If we used more than one null keys then as HashMap support unique key then previous null key is override by next null key and only next null key and value is shown.


//HashMap.java (Test for null key and value)
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class HashMap
{
public static void main(String args[])
{
try
{
HashMap hashMap = new HashMap();
hashMap.put(null, 2); //Put a null key.
hashMap.put(2, null); //Put a null value.
hashMap.put(null, 1); //Put again a null key.
hashMap.put(3, 3);
hashMap.put(4, 89);

Set set = hashMap.entrySet();
Iterator it = set.iterator();
while (it.hasNext())
{
Map.Entry me = (Map.Entry) it.next();
System.out.println("HashMap key " + me.getKey() + " and it's value is " + me.getValue());
}
}
catch (Exception e)
{
// TODO: handle exception
System.out.println("HashTable don't support " + e.getMessage() + " key and value.");
}
}
}

Output =>
HashMap key 2 and it's value is null
HashMap key 4 and it's value is 89
HashMap key null and it's value is 1
HashMap key 3 and it's value is 3


HashMap Examples:
1)       Simple HashMap example :
package com.example.hashmap;

import java.util.HashMap;

public class HashMapExample {
      public static void main(String[] args) {
            try {
                  HashMap<Integer, Integer> hashMap = new HashMap<Integer, Integer>();
                  hashMap.put(1, 11);
                  hashMap.put(2, 22);
                  hashMap.put(3, 33);
                  hashMap.put(4, 44);
                  hashMap.put(5, 55);

                  for (Object name : hashMap.keySet()) {
                        System.out.println("Name: " + name + " Age= "
                                    + hashMap.get(name));
                  }
            } catch (Exception e) {
                  System.out.println("HashMap don't support " + e.getMessage()
                              + " key and value.");
            }
      }

}
OUTPUT:

Name: 1 Age= 11
Name: 2 Age= 22
Name: 3 Age= 33
Name: 4 Age= 44
Name: 5 Age= 55
2)       Has map supports only one null key. If we will used more than one null keys then the last one is override over the previous null key.
//One null key applied in HashMap example.
package com.example.hashmap;

import java.util.HashMap;

public class HashMapExample {
      public static void main(String[] args) {
            try {
                  HashMap<Integer, Integer> hashMap = new HashMap<Integer, Integer>();
                  hashMap.put(null, 11);//HasMap supports one null key.
                  hashMap.put(2, 22);
                  hashMap.put(3, 33);
                  hashMap.put(4, 44);
                  hashMap.put(5, 55);

                  for (Object name : hashMap.keySet()) {
                        System.out.println("Name: " + name + " Age= "
                                    + hashMap.get(name));
                  }
            } catch (Exception e) {
                  System.out.println("HashMap don't support " + e.getMessage()
                              + " key and value.");
            }
      }

}

OUTPUT:
Name: null Age= 11
Name: 2 Age= 22
Name: 3 Age= 33
Name: 4 Age= 44
Name: 5 Age= 55
//Multiple null keys applied in HashMap example.
package com.example.hashmap;

import java.util.HashMap;

public class HashMapExample {
      public static void main(String[] args) {
            try {
                  HashMap<Integer, Integer> hashMap = new HashMap<Integer, Integer>();
                  hashMap.put(null, 11);//First null key.
                  hashMap.put(2, 22);
                  hashMap.put(null, 33);//Second null key. First null key will be override by this (second null key.)
                  hashMap.put(4, 44);
                  hashMap.put(5, 55);

                  for (Object name : hashMap.keySet()) {
                        System.out.println("Name: " + name + " Age= "
                                    + hashMap.get(name));
                  }
            } catch (Exception e) {
                  System.out.println("HashMap don't support " + e.getMessage()
                              + " key and value.");
            }
      }

}
OUTPUT:
Name: null Age= 33
Name: 2 Age= 22
Name: 4 Age= 44
Name: 5 Age= 55


3)       HasMapp supports multiple null values.

//Multiple null values applied in HashMap example.
package com.example.hashmap;

import java.util.HashMap;

public class HashMapExample {
      public static void main(String[] args) {
            try {
                  HashMap<Integer, Integer> hashMap = new HashMap<Integer, Integer>();
                  hashMap.put(1, null);//First null value.
                  hashMap.put(2, 22);
                  hashMap.put(3, null);//Second null value.
                  hashMap.put(4, 44);
                  hashMap.put(5, 55);

                  for (Object name : hashMap.keySet()) {
                        System.out.println("Name: " + name + " Age= "
                                    + hashMap.get(name));
                  }
            } catch (Exception e) {
                  System.out.println("HashMap don't support " + e.getMessage()
                              + " key and value.");
            }
      }

}
OUTPUT:
Name: 1 Age= null
Name: 2 Age= 22
Name: 3 Age= null
Name: 4 Age= 44
Name: 5 Age= 55