Translate

Friday, 20 June 2014

Interface in java

Interface 

Interface is the pure abstract class. It is syntactically similar to classes but we can not create the instance of class. Basically it is used to achieve pure abstraction.


  • all variables inside the interface are implicitly public,static and final variable.
  • all methods inside the interface are implicitly public  and abstract,even if you don't use public or abstract keyword.
  • interface can extend on or more other interface.
  • interface cannot implement a class.
  • a class implements an interface.
             Interface in Java
Multiple inheritance in java using interface


interface Printable{  

                      void print();  
                   }  
  
interface Showable{  
                     void show();  
                  }  
  
class A7 implements Printable,Showable{  
  
                 public void print()
{
   System.out.println("Hello")
}  
                 public void show()
{
   System.out.println("Welcome");
}  
  
public static void main(String args[]){  
A7 obj = new A7();  
obj.print();  
obj.show();  
 }  
}  

output: Hello
            Welcome

Why the multiple inheritance is not supported in java through class

Multiple inheritance is not supported through class in java cause of ambiguity.
But it supports in case of  interface because  there is no ambiguity in this case.
Here implementation is provided by the subclass.

interface Printable{
    void print();
}

interface Showable{
    void print();
}

class testinterface1 implements Printable,Showable{

public void print(){System.out.println("Hello");}

public static void main(String args[]){
testinterface1 obj = new testinterface1();
obj.print();
 }
}
output: Hello

Thursday, 19 June 2014

Abstract Class in Java

Abstract class in Java

If a class contains any abstract method,that class is known as abstract class. Abstract class is never instantiated.It is used to provide abstraction. Although abstract class does not provide 100% abstraction because it also contains concrete methods.

Abstraction in Java

Abstraction is a process of hiding the implementation details and showing only functionality to the user.
Another way, it shows only important things to the user and hides the internal details for example sending sms, you just type the text and send the message. You don't know the internal processing about the message delivery.
Abstraction lets you focus on what the object does instead of how it does it.

Abstract Method:The method inside the abstract class which have no body but its implementation must be provided in its subclass is known as abstract method. Abstract method never be final or static.

There are two ways to achieve abstraction
  1. Abstract class -0 to 100%
  2. Interface - 100%
Example of Abstract Class


abstract class Bike{  
         Bike()
     {
 System.out.println("bike is created");
     }  
        abstract void run();  
        void changeGear()
                       {
                           System.out.println("gear changed");
               }  
 }  
  
 class Honda extends Bike{  
                   void run()
 {
    System.out.println("running safely..");
 }  
 }  
 class TestAbstraction2{  
     public static void main(String args[]){  
          Bike obj = new Honda();  
          obj.run();  
          obj.changeGear();  
 }  
}  
output:
       bike is created
        running safely..
        gear changed

Wednesday, 18 June 2014

Static Block

Static Block

public class Static

 int obj;
static
{
System.out.println("Static-Block");
}
public static void print(int obj)
{
static int i =10;
System.out.println(i);
}
public static void main(String args[])
{
System.out.println("Main-Block");
Static.print(20);

}
}

output: Static-Block
            Main-Block
            10

Uses of static block

  • Is used to initialize the static data member.
  • It is executed before main method at the time of classloading.




Tuesday, 17 June 2014

super keyword

super Keyword

The super is a reference variable that is used to refer immediate parent class object.

Usage of super Keyword


  • super is used to refer immediate parent class instance variable.
  • super() is used to invoke immediate parent class constructor.
  • super is used to invoke immediate parent class method.

  • Problem without super keyword:-

    class Student{  
      int marks=50;  
    }  
      
    class CseStudent extends Student{  
      int marks=100;  
          
      void display(){  
       System.out.println(marks);//will print marks of cse students   
      }  
      public static void main(String args[]){  
       CseStudent cse = new CseStudent();  
       cse.display();  
         
    }  
    }  
    output: 100

    super keyword is used to refer the parent class instance variable

    class Vehicle{  
      int speed=40;  
    }  
      
    class Bike extends Vehicle{  
      int speed=100;  
          
      void display(){  
       System.out.println(super.speed);//will print speed of Vehicle now  
      }  
      public static void main(String args[]){  
       Bike b=new Bike();  
       b.display();  
         
    }  
    }  
    output: 40

    super keyword is used to invoke parent class constructor

    super() must be the first line of constructor and if programmer don't call the constructor,compiler wil automaticlly(imlicitly) call the constructor.

    Example

    class Vehicle{
              Vehicle()
     {
        System.out.println("Vehicle is created");
     }
    }
     
    class Bike5 extends Vehicle{
              Bike(){
              super();//will invoke parent class constructor
              System.out.println("Bike is created");
    }
      public static void main(String args[]){
       Bike b=new Bike();
          }
    }  

    output: Vehicle is created
                Bike is created

    super keyword is used to invoke the parent class method

    Example:

    class Person{  
                void message()
    {
       System.out.println("welcome");
    }  
    }  
      
    class Student extends Person{  
                void message()
    {
      System.out.println("welcome to java");
    }  
      
                void display()
    {  
                   message();//will invoke current class message() method  
                   super.message();//will invoke parent class message() method  
    }  
      
            public static void main(String args[]){  
            Student s=new Student();  
            s.display();  
        }  

    }  

    output: welcome to java
                welcome

    In the above example Student and Person both classes have message() method if we call message() method from Student class, it will call the message() method of Student class not of Person class because priority is given to local.
    In case there is no method in subclass as parent, there is no need to use super.

    Monday, 16 June 2014

    Method Overriding in java

    Method Overriding in Java

    If subclass (child class) has the same method as declared in the parent class, it is known as method overriding.
    In other words, If subclass provides the specific implementation of the method that has been provided by one of its parent class, it is known as Method Overriding.

    Advantage of Java Method Overriding

    • Method Overriding is used to provide specific implementation of a method that is already provided by its super class.
    • Method Overriding is used for Runtime Polymorphism

    Rules for Method Overriding

    1. method must have same name as in the parent class
    2. method must have same parameter as in the parent class.

    Understanding the problem without method overriding

    class Vehicle{  
             void run()
                {
                     System.out.println("Vehicle is running");
                 }  
     }  
      class Bike extends Vehicle{  
        
      public static void main(String args[]){  
      Bike obj = new Bike();  
      obj.run();  
      }  
    }  
    output:-vehicle is running

    Problem is that I have to provide a specific implementation of run() method in subclass that is why we use method overriding.

    Example of method overriding

    In this example, we have defined the run method in the subclass as defined in the parent class but it has some specific implementation. The name and parameter of the method is same and there is IS-A relationship between the classes, so there is method overriding.

       class Vehicle{  
                 void run()
                 {
                        System.out.println("Vehicle is running");
                 }  
       }  
       class Bike2 extends Vehicle{  
                void run()
               { 
                        System.out.println("Bike is running safely");
                }  
      
             public static void main(String args[]){  
             Bike2 obj = new Bike2();  
             obj.run();  
    }  
    output:Bike is running safely

    Real example of Java Method Overriding

    Consider a scenario, Bank is a class that provides functionality to get rate of interest. But, rate of interest varies according to banks. For example, SBI, ICICI and AXIS banks could provide 8%, 7% and 9% rate of interest.

    Java method overriding example of bank


    class Bank{  
    int getRateOfInterest(){return 0;}  
    }  
      
    class SBI extends Bank{  
    int getRateOfInterest(){return 8;}  
    }  
      
    class ICICI extends Bank{  
    int getRateOfInterest(){return 7;}  
    }  
    class AXIS extends Bank{  
    int getRateOfInterest(){return 9;}  
    }  
      
    class Test2{  
    public static void main(String args[]){  
    SBI s=new SBI();  
    ICICI i=new ICICI();  
    AXIS a=new AXIS();  
    System.out.println("SBI Rate of Interest: "+s.getRateOfInterest());  
    System.out.println("ICICI Rate of Interest: "+i.getRateOfInterest());  
    System.out.println("AXIS Rate of Interest: "+a.getRateOfInterest());  
    }  
    }  

    Output:
    SBI Rate of Interest: 8
    ICICI Rate of Interest: 7
    AXIS Rate of Interest: 9
    
    

    Can we override static method?

    No, static method cannot be overridden.
    because static method is bound with class whereas instance method is bound with object. Static belongs to class area and instance belongs to heap area.

    Can we override java main method?

    No, because main is a static method.

    Sunday, 15 June 2014

    Sandbox Model

    A security measure in the java development environment. The sandbox is a set of rules that are used when creating an applet that prevents certain functions when the applet is sent as part of a Web page. When a browser requests a Web page with applets, the applets are sent automatically and can be executed as soon as the page arrives in the browser.If the applet is allowed unlimited access to memory & operating system resources, it can do harm in the hands of someone with malicious intent. The sandbox creates an environment in which there are strict limitations on what system resources the applet can request or access. Sandboxes are used when executable code comes from unknown or untrusted sources and allow the user to run untrusted code safely.
    The Java sandbox relies on a three-tiered defense. If any one of these three elements fails, the security model is completely compromised and vulnerable to attack:
    • byte code verifier  This is one way that Java automatically checks untrusted outside code before it is allowed to run. When a Java source program is compiled, it compiles down to platform-independent Java byte code, which is verified before it can run. This helps to establish a base set of security guarantees.
    • applet class loader -- All Java objects belong to classes, and the applet class loader determines when and how an applet can add classes to a running Java environment. The applet class loader ensures that important elements of the Java run-time environment are not replaced by code that an applet tries to install.
    • security manager -- The security manager is consulted by code in the Java library whenever a dangerous operation is about to be carried out. The security manager has the option to veto the operation by generating a security exception.

    Saturday, 14 June 2014

    Methods, Method overloading

    Methods in java

    A Java method is a collection of statements that are grouped together to perform an operation. When you call the System.out.println method, for example, the system actually executes several statements in order to display a message on the console.
    Now you will learn how to create your own methods with or without return values, invoke a method with or without parameters, overload methods using the same names, and apply method abstraction in the program design.
    Declaration of methods
    access_modifier return_type  name_of_method(parameter List)
    {
        //method body
    }

    Method Overloading 

    Method Overloading:-If a class have multiple methods by same name but different parameters, it is known as Method Overloading.

    Method overloading can be done by two ways:-
    1. By changing number of arguments
           class Calculation{  
           void sum(int a,int b){System.out.println(a+b);}  
           void sum(int a,int b,int c){System.out.println(a+b+c);}  
      
           public static void main(String args[]){  
           Calculation obj=new Calculation();  
           obj.sum(10,10,10);  
           obj.sum(20,20);  
      
      }  
    }  
      output: 30
                  40
    1. By changing data type
             class Calculation2{  
             void sum(int a,int b){System.out.println(a+b);}  
             void sum(double a,double b){System.out.println(a+b);}  
      
             public static void main(String args[]){  
             Calculation2 obj=new Calculation2();  
             obj.sum(10.5,10.5);  
             obj.sum(20,20);  
      
      }  
    }  
    output:21
              40
    Note: Method overloading is not possible by changing return type because they may cause ambiguity.

    Can we overload main method() ?
    Ans:- Yes, main method can be overloaded. You can any number of main() methods in a class by method overloading.

    Example:-
                         class Overloading1{  
                               public static void main(int a){  
                                       System.out.println(a);  
                               }  
        
                              public static void main(String args[]){  
                                      System.out.println("main() method invoked");  
                                      main(10);  
                               }  
                       }  
    output: main() method invoked
                10


    Friday, 13 June 2014

    In Built Function of Array



    System.arraycopy(a,i,b,j,n);

    a-The array which is to be copied
    i- The array index from which copying is started
    b-The array in which to be copied
    j-The array index to which pasting is started
    n-The number of elements to be copied

    arrayname.length - calculates the length of array
    import java.util.*;

    class ArrayFunctionDemo
    {
    public static void main(String args[])
    {   
       //array declaration is done by using  <data type> array_name 
    //array initialization is done at run time using new keyword  
    int marks[] = new int[4];
    Scanner mark = new Scanner(System.in);//Scanner is inbuilt class
    System.out.println("ENTER THE MARKS: ");
    for(int i=0;i<marks.length;i++)
    {
    marks[i]=mark.nextInt();//here nextInt is inbuilt method to enter the integer value from user
    }
    System.out.println("THE MARKS IS:");
    //enhanced for loop
    for(int x:marks)//or we can write it as: for(int x=0;x<marks.length;x++)
    {
    System.out.println(x);//here we can also write that System.out.println(marks[]);
    }
    int arr[]={1,2,3,4,5};//direct initializatio of array
    //arraycopy() is the method to copy the one array contents with another using System.arraycopy( , , , , );
    System.arraycopy(marks,1,arr,0,2);
    for(int m:arr)
    {
    System.out.println(m);
    }
    }
    }

    Thursday, 12 June 2014

    Reference Array

    First we will have to create the any class, Here Student Class


    class Student

     {
          private int y;
          private String x;
     Student(String s,int r)
     {
    x=s;
    y=r;
     }
         public void SetRollNo(int x)
           {
                y = x;
      }
    public void SetName(String v)
           {
               x = v;
           }
    public String  GetName(){
                          return x;
                        }
         public int GetRollNo(){
                         return y;
                         }
     
         }

    In the following case array is directly initialized

    class RefArrayDemo
    {
    public static void main(String args[])
    {
    //reference array std[] is created which contains the address of attributes of Student class.....
    //by using new keyword object is created............
    Student std[]={new Student("VIKESH",1240),
      new Student("VED PRAKASH",1243),
      new Student("ABBHISHEK",1260)
     };//here in this case reference array is directly initialized
       for(int i=0;i<std.length;i++)
    {
    String s = std[i].GetName();//by using that reference array we can access the GetName() method
    int r =std[i].GetRollNo();//by using that reference array we can access the GetRollNo() method
    System.out.println(s +"\t"+r);
    }
    }
    }


    In the following case array is initialized by user

    import java.util.*;
    class RefArrayDemo1
    {
    public static void main(String args[])
    {
    Student std[]= new Student[5];
    Scanner scan = new Scanner(System.in);
    //enter the different value of x and y
    for(int i=0;i<std.length;i++)
    {
       System.out.println("ENTER THE VALUE OF X:");
    String s =scan.next();
    System.out.println("ENTER THE VALUE OF Y:");
    int n = scan.nextInt();
    std[i] = new Student(s,n);  //the reference array std[] holds the different addresses of objects 
    }
    for(int i=0;i<std.length;i++)
    {
    String s = std[i].GetName();  //calling of method defined in the given class
    int n = std[i].GetRollNo();
    System.out.println("X: "+s+"\t"+"Y:"+n);
    }
    }
    }

    Wednesday, 11 June 2014


    Java Array

    Normally, array is a collection of similar type of elements that have contiguous memory location.
    Java array is an object the contains elements of similar data type. It is a data structure where we store similar elements. We can store only fixed set of elements in a java array.
    Array in java is index based, first element of the array is stored at 0 index.
    java array

    Advantage of Java Array

    • Code Optimization: It makes the code optimized, we can retrieve or sort the data easily.
    • Random access: We can get any data located at any index position.

    Disadvantage of Java Array

    • Size Limit: We can store only fixed size of elements in the array. It doesn't grow its size at runtime. To solve this problem, collection framework is used in java.

    Types of Array in java

    There are two types of array.
    • Single Dimensional Array
    • Multidimensional Array

    Syntax to Declare an Array in java

    dataType[] arr; (or)  
    dataType []arr; (or)  
    dataType arr[]; 

    Instantiation of an Array in java

    arrayRefVar=new datatype[size]; 

    Example of single dimensional java array

        
    class Testarray{  
    public static void main(String args[]){  
      
    int a[]=new int[5];//declaration and instantiation  
    a[0]=10;//initialization  
    a[1]=20;  
    a[2]=70;  
    a[3]=40;  
    a[4]=50;  
      
    //printing array  
    for(int i=0;i<a.length;i++)//length is the property of array  
    System.out.println(a[i]);  
      
    }}   

    Syntax to Declare Multidimensional Array in java

    dataType[][] arrayRefVar; (or)  
    dataType [][]arrayRefVar; (or)  
    dataType arrayRefVar[][]; (or)  
    dataType []arrayRefVar[];   

    Example to instantiate Multidimensional Array in java

    int[][] arr=new int[3][3];//3 row and 3 column  

    Example of Multidimensional java array

    class Testarray3{  
    public static void main(String args[]){  
      
    //declaring and initializing 2D array  
    int arr[][]={{1,2,3},{2,4,5},{4,4,5}};  
      
    //printing 2D array  
    for(int i=0;i<3;i++){  
     for(int j=0;j<3;j++){  
       System.out.print(arr[i][j]+" ");  
     }  
     System.out.println();  
    }  
      
    }}  


    Tuesday, 10 June 2014

    Types of Variable and Type Casting

    There are three types of variables in java
    • local variable
    • instance variable
    • static variable
    types of variable

    Local Variable

    A variable that is declared inside the method is called local variable.

    Instance Variable

    A variable that is declared inside the class but outside the method is called instance variable .

    Static variable

    A variable that is declared as static is called static variable. It cannot be local.
    Type Casting

     Assigning a value of one type  to a variable  of another type is known as Type Casting.

    Type Casting is classified into two category :

    • Widening or implicit casting
         widening-type-conversion
    • Narrowing or explicit casting
        narrowing-type-conversion
     Examples of implicit type casting

       Class ImplicitTypeCasting{
                         public static void main(String args[])
                          {
                                 int i=100;
                                 long l =i; //implicit type conversion
                                 float f=l; //implicit type conversion
                                System.out.println("Int value: "+i);
                                System.out.println("Long value: "+l);
                                System.out.println("Float value: "+f);
                          } 
    }

    output:
                Int value: 100
                Long value: 100
                float value: 100.0
     
    Example of explicit type casting   

    Class ExplicitTypeCasting{
                         public static void main(String args[])
                          {
                                 double d=100.04;
                                 long l =(long)d; //explicit type conversion
                                 int i =(int)l; //explicit type conversion
                                System.out.println("Double value: "+d);
                                System.out.println("Long value: "+l);
                                System.out.println("Int value: "+i);
                          } 
    }   

    output:
                Double value: 100.04
                Long value: 100
                Int value: 100                                

    Monday, 9 June 2014

    Data Types

    Java language has rich implementation of data types.Data type specify the size 
    and value that can be stored in an identifier.

    In java data types are specified into two category :-
    1. Primitive Data Type
    2. Non-Primitive Data Type
    A primitive Data types can be of eight types:-
    1. char
    2. boolean
    3. byte
    4. short
    5. int
    6. long
    7. float
    8. double
    Note : -Once a primitive datatype has been declared, its type can never change,although its value can change in most of cases
    datatype in java


    Data TypeDefault ValueDefault size
    booleanfalse1 bit
    char'\u0000'2 byte
    byte01 byte
    short02 byte
    int04 byte
    long0L8 byte
    float0.0f4 byte
    double0.0d8 byte


    Non-primitive datatype - It is also known as reference data type. Reference
     data type is used to refer an object. A reference variable is declared to be specific and that type can never be changed.

    Sunday, 8 June 2014

    Package Programming Example

    //Addition
    package calculator;

    public class Addition
    {
    int x;
    int y;
    int sum;
    public Addition(int x,int y)
    {
    this.x = x;
    this.y = y;
    }
    public void add()
    {
    sum = x+y;
    System.out.println("Sum = "+sum);
    }
    }

    //Substraction

    package calculator;

    public class Subtraction
    {
    int x;
    int y;
    int diff;
    public Subtraction(int x,int y)
    {
    this.x = x;
    this.y = y;
    }
    public void subtract()
    {
    diff = x-y;
    System.out.println("Difference = "+diff);
    }
    }


    //Multiplication

    package calculator;

    public class Multiplication
    {
    int x;
    int y;
    int mul;
    public Multiplication(int x,int y)
    {
    this.x = x;
    this.y = y;
    }
    public void multi()
    {
    mul = x*y;
    System.out.println("Multiplication = "+mul);
    }
    }

    // Division
    package calculator;

    public class Division
    {
    int x;
    int y;
    int div;
    public Division(int x,int y)
    {
    this.x = x;
    this.y = y;
    }
    public void divide()
    {
    div = x/y;
    System.out.println("Division = "+div);
    }
    }