Tuesday, 5 February 2013

Java Basic Notes

/*
 * class- It is a Template/Blue print.
     - It represents a real time entity.
     - It defines the behaviour of the entity

     - Fields (attribute/properties/member variables) & Methods
   
      In Java- All the code exist with in the class or interface
             - You can have more than on class inside a java file
             - But you can have only one public class in a java file
             - You can define more than one main method inside the java program (In different classes)
             - The file name and the class name need not to be same until the class is declared as public
 */

class ClassDefPrg1 {
    public static void main(String arg[])
    {
        System.out.print("Hello");
    }
  
}

class Ab3
{
  
}
___________________________________________________________________________________

/*
 * Constructor has the same name of the class name
 * Constructors are used for initialization
 * Constructors don't have any return type
 * Constructors are called when ever we declare an object of that
 *      corresponding class
 *
 */


class A1
{
    //member variables
    int i;
    int j;
   
    //default constructor
    public A1() {
        i=10;
        j=20;
    }
   
    //constructor overloading
    public A1(int a,int b) {
        i=a;
        j=b;
    }
   
    public A1(int z) {
        i=z;
        j=0;
    }
   
    public void display() {
        System.out.println("Value of I="+i+" Value of J="+j);
    }
   
}


public class First {

    public static void main(String arg[])
    {
        System.out.println("Hello World");
        A1 aobj=new A1(); // creating an object. This calls the constructor without any argument
        A1 bobj=new A1(30,40);  // This calls the constructor with two arguments
        A1 cobj=new A1(50);
        aobj.display();
        bobj.display();
        cobj.display();
   
    }
   
}
___________________________________________________________________________________

/*
 * When more than one function uses the same name with different
 * parameters , we call it as Method Overloading.
 *
 * Ability to access multiple implementation of functions using
 * the same name is called as Polymorphism
 * 
 * Method overloading doesn't verify the return types
 */
public class MethodOverload {

    public void display() {
        System.out.println("Display()");
    }
   
    public int display(String a) {
        System.out.println("Display(String)");   
        return 0;
    }
   
    public void display(int a) {
        System.out.println("Display(int)");
    }
   
    public static void main(String arg[])
    {
        MethodOverload m1=new MethodOverload();
        m1.display();
        m1.display(10);
        m1.display("Hello");
    }
   
}

___________________________________________________________________________________
/*
 * MultiThreading:
 * --------------
 *
 * MultiTasking :
 * 1. Process Based Multitasking
 * 2. Thread Based Multitasking
 *
 * 1. Process Based Multitasking:
 *    Simultaneously working with more than one application at a time.
 *    The user can work without closing the application in different
 *        processors.
 *    Switching over between the processors is called Context Switching.
 *    Switching between the process with different address space consumes
 *    more resources, so we call this as heavy weighed process.
 *   
 * 2. Thread Based Multitasking:
 *       Simultaneously performing more than one task with in the same
 *    application is called Thread based multitasking.
 *    Thread is a piece of code with in a program which can execute
 *    by itself.
 *    Threads are called as light weight process since they use the
 *    same address space. Switching over with in the same address
 *    space consumes less resources.
 *  
 *   Threads can be created using two apis -
 *       implements Runnable ( interface )
 *      extends Thread ( class )
 */


/*class MyChildThread implements Runnable
{
    Thread t=null;
   
    public MyChildThread() {
        t=new Thread(this,"Child Thread");
        t.start();
    }*/


class MyChildThread extends Thread
{       
    public MyChildThread() {
        super("Child Thread");
        start();
    }
   
    public void run() {
        for (int i=0;i<10;i++)
        {
            System.out.println("Child Thread -->"+i);
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {            }
        }
    }
       
}


public class MyMainThread {
   public static void main(String arg[]) {
       MyChildThread t=new MyChildThread();
       for (int i=0;i<5;i++)
        {
            System.out.println("Main Thread -->"+i);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {            }
        }
      
   }
}
___________________________________________________________________________________


/*
 * It is a collection of abstract & concrete methods
 * Methods without definition/body is called as Abstract methods
 * The class which consist of abstract methods are called as
 *      abstract class
 * Such methods and classes are prefixed with the keyword "abstract"
 * When a class inherits an abstract class it must provide
 *    definition for all the abstract methods of that corresponding class
 * You cannot create an instance of an abstract class
 * But you can create a reference of an abstract class
 */

 abstract class A9
{
    //abstract
    public abstract void display();
   
    //concrete
    public void print() {
        System.out.println("Concrete method print()");
    }
}
class S8 extends A9
{

    @Override
    public void display() {
        // TODO Auto-generated method stub
       
    }    
}

public class UseAbstract {
    public static void main(String arg[]) {
        //A9 a=new A9();  //--> error
        A9 a;  // reference of abstract class
        a=new S8();  // instance of sub class
        a.display();
        a.print() ;    
    }
}
___________________________________________________________________________________

 /* Vector - It is a dynamic array of Objects. The methods inside the vector is synchronized */
/* ArrayList - It is also dynamic array of Objects. But the methods are not synchronized */

import java.util.ArrayList;
import java.util.Vector;

class Student
{
    String name;
    String qual;
  
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getQual() {
        return qual;
    }
    public void setQual(String qual) {
        this.qual = qual;
    }  
}


public class Usecollection {
    public static void main(String arg[]) {
        Vector <Student> v=new Vector<Student>();
        Student s1=new Student();
        s1.setName("rahul");
        s1.setQual("ma");
        v.add(s1);
        Student s2=new Student();
        s2.setName("hari");
        s2.setQual("BA");
        v.add(s2);
        for (int i=0;i<v.size();i++) {
            Student s=(Student)v.elementAt(i);
            System.out.println("Name :"+s.name);
            System.out.println("Qual :"+s.qual);
        }
      
        System.out.println("----------------");
        ArrayList<Student> ar=new ArrayList<Student>();
        ar.add(s1);
        ar.add(s2);
      
        for (int i=0;i<ar.size();i++) {
            Student s=(Student)ar.get(i);
            System.out.println("Name :"+s.name);
            System.out.println("Qual :"+s.qual);
        } 
    }
}

___________________________________________________________________________________


/*
 *    Exceptions are Objects in Java. When ever an abnormal situation
 *    is raised with in a piece of code, the JRE will search for a class
 *    that describes the situation. When found, the respective class
 *    object is created and thrown into the block of statement.
 *    Such thrown objects can be handled by the user using "try&catch"
 *    block or instruct the calling method to handle the exception
 *    using "throws" keyword.
 *    If the user wants to manually raise an exception we use the
 *    keyword "throw" and the last block of statement to be executed
 *    is provided inside the "finally" block.
 */

class MyException extends Exception
{
    public MyException() {
        System.out.println("User Defined Exception is called");
    }
   
    public String printErr() {
        return "This is an User Defined Exception method";
    }
}

public class UseException {
   public static void main(String arg[]) throws Exception {
       int i=10;
       try {
           int j=i/0;
       }catch (ArithmeticException e) {
          System.out.println("Exception is raised :"+e);
       }finally {
           System.out.println("The last block of statment to be executed");
       }
       System.out.println("After the situation");
      
       try {
           throw new MyException();
       }catch (MyException me) {
           System.out.println("User defined Exception is caught "+me.printErr());
       }
      
      /*ry {
           throw new MyException();
       } catch (MyException e) {
        // TODO Auto-generated catch block
            e.printErr();
       }*/
      
      
   }
}
___________________________________________________________________________________
/*
 * Final Variable - cannot be modified
 * Final Method = cannot be overriden
 * Final Class- cannot be inherited
 *
 */

 class A5
{
    public void display() {
       
    }
}

class A6 extends A5
{
    public void display() {
       
    }
}

public class UseFinal {
    public static void main(String arg[]) {
        A6 a1=new A6();
        final int i=10;
        //i=20;
        a1.display();
    }
}
___________________________________________________________________________________
/* Ability to reuse the member variables and functions in the sub classes
 * is achieved using Inheritance. Java uses "extends" keyword for
 * inheritance. Java doesn't support multiple inheritance.
 *
 *  Method Overriding- When the base class and the subclass methods
 *  have the same signature then the subclass method overrides the base
 *  class method. This is knows as method overriding.
 *  The return type must be same for overriding methods.
 *    
 *  In Overriding the weaker access specifier cannot override the stronger access specifier.
 */

class A3
{
    public  void display(){
        System.out.println("In A3 Main class");
    }
}

class A4 extends A3
{
    public void display() {
        System.out.println("In A4 Sub class");
       
    }   
}

public class UseInheritance {
    public static void main(String arg[]) {
        A4 a1=new A4();
        a1.display();
        /*A3 a2=new A3();
        a2.display();*/
    }
}

___________________________________________________________________________________
/*
 * It is a collection of only abstract methods & by default everything
 *   is abstract inside an interface
 * Interface is an alternative for multiple inheritance.
 * We use the keyword "implements" to use an interface. In Java we can
 *   implement more than one interface (but we can extend only one class)
 * When a class implements an interface it must provide definition for
 *   all the interface methods
 * You cannot create an instance of an interface
 * But you can create a reference of an interface
 * One interface can extend another interface.      
 */

interface Inter1{
    public void display();
}

interface Inter2 extends Inter1 {
    public void print();
}

class TestInterface implements Inter1,Inter2 {

    @Override
    public void print() {
        // TODO Auto-generated method stub
       
    }

    @Override
    public void display() {
        // TODO Auto-generated method stub
       
    }

   
   
}

public class UseInterface extends TestInterface
{
    public static void main(String arg[]) {
        //Inter1 i=new Inter1();
        Inter1 i;  // reference
        i=new TestInterface();
       
}

}
___________________________________________________________________________________
/*
 * Class Variable : A member variable is considered as class variable
 * when it is declared as static. Because the static keyword ensures
 * that, there will be only a single copy of the member variable
 * for the entire class. All the objects of the corresponding class
 * shares the same variable.
 *
 * As a result, static variable retains the last updated value
 *
 */


class A2
{
    int i;  // member variable
    static int j;  // class variable
   
    A2() {
        i=0;
        j=0;
    }
   
    A2(int a,int b) {
        i=a;
        j=b;
    }
   
    public void display() {
        System.out.println("I="+i+" J="+j);
    }   
}


public class UseStatic {
   
    public static void main(String arg[]) {
       
        A2 aobj=new A2(10,20);
        A2 bobj=new A2(30,40);
        aobj.display(); 
        bobj.display();  
    }
}
___________________________________________________________________________________
/*
 * "super" keyword is used to invoke the super class constructors
 *  The Super keyword must be the first statement within the constructor.
 * 

 */

class A7
{
    int i;
   
    A7() {
        System.out.println("Default Constructor called");
    }
   
    A7(int a) {
        i=a;
        System.out.println("A7(int) constructor called");
    }
}

class A8 extends A7
{
    int j;
   
    A8(int a,int b) {
        super(a);        // invoking super class constructor
        j=b;
        System.out.println("A8(int,int) is called");
    }
   
}


public class UseSuper {
    public static void main(String arg[])
    {
        A8 a=new A8(10,20);
    }
}
___________________________________________________________________________________
 /*  "this" keyword is used to represent the current invoking object/member variable. */

class TestAbc
{
    int i;
    int j;
   
    public TestAbc() {
        i=0;
        j=0;
    }
   
    public TestAbc(int i,int j) {
        this.i=i;
        this.j=j;       
    }
   
    void display()  {
        System.out.println("I ="+i+" J ="+j);
    }
}



public class UsingThis {

    public static void main(String arg[]) {
        TestAbc a1=new TestAbc(10,20);
        a1.display();
    }
   
}

___________________________________________________________________________________

No comments:

Post a Comment