Wednesday, January 16, 2013

Concepts introduced in JAVA version 5

package example.basics;

import java.util.ArrayList;

public class javaClassExample {
    /*************1. VARARGS************/

/*    public static void main(String args[]){
        System.out.println("Inside main class...");
       
    }
    */
   
    public static void main(String... args){//VARARGS
        System.out.println("Inside main class...after J2SE 5");
       
    }

   
    /********************VARARGS ends here******************/
}

Saturday, January 12, 2013

ThreadStartExample


package com.multithreading;
public class ThreadStartExample extends Thread{

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

ThreadStartExample t1 = new ThreadStartExample();
t1.setName("firstThread");

t1.start();/*
if START() IS not CALLED than newly created thread(BY EXTENDING THREAD.......) also runs within main thread
*/
t1.run();



Thread t2 = new Thread(new ThreadByRunnable(),"second");

t2.start();
/*
if START() IS not CALLED than newly created thread (BY IMPLEMENTATION OF RUNNABLE)also runs within main thread i.e. in different stack
*/
t2.run();


}

public void run(){
System.out.println("Thread running is..............."+Thread.currentThread().getName());
}

}

class ThreadByRunnable implements Runnable{

public void run() {
System.out.println("Running thread when implemanted runnable is............."+Thread.currentThread().getName());
}



}

SyncronizationModesExample


package com.multithreading;



public class SyncronizationModes implements Runnable{
SharedResource1 sr = new SharedResource1();
public static void main(String args[]) {
SyncronizationModes rn = new SyncronizationModes();


Thread t1 = new Thread(rn,"FirstThread");
Thread t2 = new Thread(rn,"SecondThread");

t1.start();
t2.start();



}

public void run(){

sr.test();

sr.testAgain();

   synchronized (this) {
sr.testNew();
   }
}

}



class SharedResource1{/*
  SYNCRONIZED BLOCK
*/

public  void test() {
synchronized(this){
for(int i=0;i<10;i++){
System.out.println("Thread accessing the resource is..................."+Thread.currentThread().getName()+"value of i is::::"+i);
}
}
 }

public synchronized void testAgain() {
/*
* SYNCRONIZED METHOD
*/
for(int i=0;i<10;i++){
System.out.println("Thread accessing the New resource is..................."+Thread.currentThread().getName()+"Thread is accessing the shared resource for ::::"+i+"time");
}

 }

/*
*
* SYNCRONIZED RESOURCE
*/
public void testNew() {
for(int i=0;i<10;i++){
System.out.println("Thread accessing the New resource is..................."+Thread.currentThread().getName()+"------------------> ::::"+i+"time");
}
}



}

InterfaceCastingExample


package com.interfaces;


interface FirstInterface{
void show();
}

interface SecondInterface{
void show();

void display();
}


public class InterfaceCastExample implements FirstInterface,SecondInterface{

public void show() {
System.out.println("Show method content");
}


public void display() {
System.out.println("Inside display method.........................");
}

public static void main(String args[]) {

FirstInterface fi = new InterfaceCastExample();

fi.show();

SecondInterface si = new InterfaceCastExample();

si.show();


InterfaceCastExample ic = (InterfaceCastExample)si;

ic.display();

}

}

NestedInterfaceExample


package com.interfaces;

import com.interfaces.OuterInterface.InnerInterface;


interface OuterInterface {

void show();

interface InnerInterface{

void msg();
}
}


public class NestedInterfaceExample implements OuterInterface.InnerInterface{

public void msg(){
System.out.println("Implementation for msg method");
}

public static void main(String args[]) {

OuterInterface.InnerInterface message = new NestedInterfaceExample();//UPCASTING TO INTERFACE

message.msg();
}

}

TypeCastingExample


package com.datatypes;

public class TypeCastingExample {

public static void main(String args[]){

byte b=1;
short s  = 2;
int i= 300;
long l=4l;
char c = 'e';
boolean bn = false;

//long myLong = 123123123123123l; usage of long literal. without l prefix it's out of range
b = (byte) c;

System.out.println("Boolean value is-----"+bn);//cannnot cast boolean to either datatype AND otherway around

System.out.println("after conversion from character+++"+b);//char to byte

float f = 10.00f;
double d = 20d;

d = f;

System.out.println("value of d is --------"+d);//narrowing downcasting

System.out.println("Byte is........"+b);
System.out.println("short is........"+s);
System.out.println("Integer is......"+i);
System.out.println("Long is......"+l);


b = (byte)i;//LOSS OF DATA AS INTEGER TO BYTE CAUSES DATA LOSS//CONVERT THE INTEGER TO DECIMAL TRUNCATE HIGH ORDER BYTES THAN USING 2S COMPLIMENT GENERATES BYTE VALUE

i = s;

System.out.println("Byte value after narrowing is........."+b);

System.out.println("Integer value after widening is........."+i);







}
}

DataShadowingExample


package com.constructor;

public class DataShadowingExample {

private int age=001;

private String name="className";



DataShadowingExample(String nameInput,int ageInput){
this.age = ageInput;
this.name = nameInput;
}


public void testMethod(){

int age = 007;

System.out.println("age is......."+this.age);
System.out.println("class age is------->"+age);

}

public static void main(String args[]) {

//private String name="india";

DataShadowingExample dse = new DataShadowingExample("akkhil", 007);

   dse.testMethod();

}

}




SimpleHelloWorldExample


package com.basics;
/*
 *
 * WHY DO MAIN METHOD NEED TO HAVE RTEURN TYPE AS VOID
 */
public class HelloWorld {


HelloWorld hw = new HelloWorld();

// String[] test;

//hw.main(test);

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


/*public static void main(String... args){
System.out.println("Hello World>>>>>>>>");
}*/

/*static public  void  main(String... args){
System.out.println("Hello World::::::::::::::::");
}*/

/* static   void  main(String... args){ //error as main need to be public
System.out.println("Hello World::::::::::::::::");
}
*/

public static String main(String args[]){
System.out.println("Hello World............");
return "akkhil";
}
/*
public static void main(String args[]){
// System.out.println("Hello World............");
return;
}*/

}

JVMTerminationExample


package com.basics;
/*
 *
 * Runtime.getRuntime.exit() and System.exit() method to terminate the CURRENTLY RUNNING JVM
 * where non-zero status code is ABNORMAL TERMINATION?????????????
 */

public class JVMTerminationExample {
public static void main(String args[]) {
System.out.println("I this a daemon thread........"+Thread.currentThread().isDaemon());
// Thread.currentThread().setDaemon(true);
System.exit(1);
// Runtime.getRuntime().exit(0);
System.out.println("After system exit............"+Thread.currentThread().isAlive());
}
}

MainMethodDaemonThreadExample


package com.basics;

public class MainMethodExample {
/*
 The thread by default is NON Daemon*/
public static void main(String args[]) {
System.out.println("Is this a daemon thread........"+Thread.currentThread().isDaemon());
Thread.currentThread().setDaemon(true);
System.exit(0);
// Runtime.getRuntime().exit(0);
System.out.println("After system exit............"+Thread.currentThread().isAlive());
}
 
}

NonDaemonThreadExample


package com.basics;
/*
 *
 * Runtime.getRuntime.exit() and System.exit() method to terminate the CURRENTLY RUNNING JVM
 */

public class NonDaemonThreadExample {

public static void main(String args[]) {
System.out.println("I this a daemon thread........"+Thread.currentThread().isDaemon());
// Thread.currentThread().setDaemon(true);
System.exit(1);
// Runtime.getRuntime().exit(0);
System.out.println("After system exit............"+Thread.currentThread().isAlive());
}
}

PrintStreamExample


package com.basics;
/*
 *
 * System class static field of type PrintStream has method println of printstream.
 * same thing holds for err also which is the reference to static field of printstream
 */
public class PrintStreamExample {
public static void main(String args[]) {
System.out.println("this is printstrean class method println");
System.err.println("this is printstrean class method println for error stream");
}

}

TwoMainMethodExample


package com.basics;

public class TwoMainMethodsExample {

public static void main(String args[]) {

Temp tp = new Temp();
//tp.main("");
tp.main(null);//null can be passed in place of String....
}

}



class Temp {

public static void main(String... args) {
System.out.println("inside temp class------------");
}
}

StringConcatenationExample


package com.string;

public class StringConcatenationExample {



public static void main(String args[]) {
String name = "akkhil";

System.out.println("value of name before concatenation is................."+name);

String name1 = name+"add";

name.concat("addnewstring");//concat doesnot nakes string to get modified while assigning the same to a string variable i.e name here
//does as shoen below
name = name.concat("addnewstring");



// name = name+"addinstring";

System.out.println("value of name after concatenation is................."+name);

// System.out.println("value of name is................."+name1);
}

}

StaticFactoryMethodExample

package com.objectcreation;
 /*The examples of static factory method: * * Pattern.compile Calendar.getInstance Collections.synchronizeCollection */
 public class StaticFactoryMethodExample {
 private String name;
 public StaticFactoryMethodExample() { }
 public StaticFactoryMethodExample(String name) {
 this.name = name;
 }
 public static StaticFactoryMethodExample getInstance() {
 return new StaticFactoryMethodExample();
 }
 public static StaticFactoryMethodExample getInstanceWithParameter() {
 return new StaticFactoryMethodExample("akkhil");
 }
 public static void main(String... args) {
 StaticFactoryMethodExample.getInstance();// FIRST CONSTRUCTOR WITHOUT // PARAMETERS StaticFactoryMethodExample.getInstanceWithParameter();// FIRST // CONSTRUCTOR // WITH // PARAMETERS
 System.out .println("Parameter from parametrized constructor-------->>>>>>>>>" + StaticFactoryMethodExample.getInstanceWithParameter().name); }
}

Ways to create an object in Java


package com.objectcreation;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class ObjectCreation implements Cloneable,Serializable{

private String name="testname";

private int age=20;

private static long testValue;

private ObjectCreation(long testValue){

this.testValue = testValue;

}

public static ObjectCreation getInstance(){

return new ObjectCreation(007);
}


ObjectCreation(String name,int age){
this.name = name;
this.age = age;
}


ObjectCreation(ObjectCreation ocreation) {//CONSTUCTOR FOR COPY CONSTRUCTOR
this(ocreation.name,ocreation.age);
}



public static void main(String args[]) {
/*Method 1: using new operator */
ObjectCreation oc = new ObjectCreation("akkhil",10);
System.out.println("Object created using new operated is"+oc.toString());

/*Method 2: copy constructor*/
ObjectCreation oc1 = new ObjectCreation(oc);
System.out.println("Object created using copy constructor is--------------------->"+oc1.toString());

/*method 3:Static factory method**/

ObjectCreation.getInstance();
System.out.println("Object created using static factory method............"+ObjectCreation.getInstance().testValue);

/*Method 4:Using Reflection**/
/* try {
Class cs = Class.forName("com.objectcreation.ObjectCreation");
try {
ObjectCreation ocnew = (ObjectCreation)cs.newInstance();
System.out.println("OBJECT CREATED USING REFLECTION..............."+ocnew.hashCode());
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

*/
/**Method 5: Using clone*/
try {
ObjectCreation clonedObject = (ObjectCreation) oc.clone();
System.out.println("Object created using clone is-----------------"+clonedObject.hashCode());
} catch (CloneNotSupportedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

/**Method 6: Using Deserialization
*
****/
File f = new File("C:\\Users\\Dell\\Desktop\\SerializedFile.ser");
try {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(f));
oos.writeObject(oc);
oos.close();
} catch (FileNotFoundException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}


try {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(f));
try {
Object ob = ois.readObject();
System.out.println("Object created from deserializatuon is>>>>>>>>>>>>>>>>>>>>>>>"+ob.hashCode());
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}

/**
* Method 7: Using Constructor
*/
Class clazz = String.class;
Constructor cons = null;
try {
cons = clazz.getConstructor(new Class[]{clazz});
} catch (SecurityException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (NoSuchMethodException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
System.out.println("Object created using constructor is>>>>>>>>>>>>"+cons.newInstance(new Object[]{101}));
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

}