Saturday, 13 May 2017

java Command line Argument ~ GNIITHELP

Command line argument in Java

The command line argument is the argument passed to a program at the time when you run it. To access the command-line argument inside a java program is quite easy, they are stored as string in String array passed to the args parameter of main() method.
Example
class cmd 
{
  public static void main(String[] args)
  {
    for(int i=0;i< args.length;i++)
    {
    System.out.println(args[i]);
    }
  }
}
Execute this program as java cmd 10 20 30

Output :
10
20
30
command line argument
Read More »

java instanceof Operator ~ GNIITHELP

In Java, instanceof operator is used to check the type of an object at runtime. It is the means by which your program can obtain run-time type information about an object. instanceof operator is also important in case of casting object at runtime. instanceof operator return boolean value, if an object reference is of specified type then it return true otherwise false.

Example of instanceOf

public class Test
{
    public static void main(String[] args)
    {
      Test t= new Test();
      System.out.println(t instanceof Test);
      }
}
Output :
true

Downcasting

downcasting in java

Example of downcasting with instanceof operator

class Parent{ }

public class Child extends Parent
{
    public void check()
    {
        System.out.println("Sucessfull Casting");
    }

    public static void show(Parent p)
    {
       if(p instanceof Child)
       {
           Child b1=(Child)p;
           b1.check();
       }
    }
    
    public static void main(String[] args)
    {
      
      Parent p=new Child();
      
      Child.show(p);
      
      }
}
Output :
Sucessfull Casting

More example of instanceof operator

class Parent{}

class Child1 extends Parent{}

class Child2 extends Parent{}

class Test
{
  public static void main(String[] args)
  {
      Parent p =new Parent();
      Child1 c1 = new Child1();
      Child2 c2 = new Child2();
      
      System.out.println(c1 instanceof Parent);  //true 
      System.out.println(c2 instanceof Parent);  //true 
      System.out.println(p instanceof Child1);  //false 
      System.out.println(p instanceof Child2);  //false 
      
      p = c1;
      System.out.println(p instanceof Child1);  //true 
      System.out.println(p instanceof Child2);  //false 
      
      p = c2;
      System.out.println(p instanceof Child1);  //false 
      System.out.println(p instanceof Child2);  //true 
      
   }
    
}
Output :
true
true
false
false
true
false
false
true
Read More »

java Runtime Polymorphism ~ GNIITHELP

Runtime Polymorphism or Dynamic method dispatch

Dynamic method dispatch is a mechanism by which a call to an overridden method is resolved at runtime. This is how java implements runtime polymorphism. When an overridden method is called by a reference, java determines which version of that method to execute based on the type of object it refer to. In simple words the type of object which it referred determines which version of overridden method will be called.
upcasting in java

Upcasting

When Parent class reference variable refers to Child class object, it is known as Upcasting

Example

class Game
{
 public void type()
 {  System.out.println("Indoor & outdoor"); }
}

Class Cricket extends Game
{
 public void type()
 {  System.out.println("outdoor game"); }

 public static void main(String[] args)
 {
   Game gm = new Game();
   Cricket ck = new Cricket();
   gm.type();
   ck.type();
   gm=ck;      //gm refers to Cricket object
   gm.type();  //calls Cricket's version of type
 }
}
Output :
Indoor & outdoor 
Outdoor game
Outdoor game
Notice the last output. This is because of gm = ck; Now gm.type() will call Cricket version of type method. Because here gm refers to cricket object.

Q. Difference between Static binding and Dynamic binding in java ?

Static binding in Java occurs during compile time while dynamic binding occurs during runtime. Static binding uses type(Class) information for binding while dynamic binding uses instance of class(Object) to resolve calling of method at run-time. Overloaded methods are bonded using static binding while overridden methods are bonded using dynamic binding at runtime.
Read More »

Method Overriding ~ GNIITHELP

When a method in a sub class has same name and type signature as a method in its super class, then the method is known as overridden method. Method overriding is also referred to as runtime polymorphism. The key benefit of overriding is the abitility to define method that's specific to a particular subclass type.

Example of Method Overriding

class Animal
{
 public void eat()
 {
  System.out.println("Generic Animal eating");
 }
}

class Dog extends Animal
{
 public void eat()   //eat() method overriden by Dog class.
 {
  System.out.println("Dog eat meat");
 }
}
As you can see here Dog class gives it own implementation of eat() method. Method must have same name and same type signature.
NOTE : Static methods cannot be overridden because, a static method is bounded with class where as instance method is bounded with object.

Covariant return type

Since Java 5, it is possible to override a method by changing its return type. If subclass override any method by changing the return type of super class method, then the return type of overriden method must be subtype of return type declared in original method inside the super class. This is the only way by which method can be overriden by changing its return type.
Example :
class Animal
{
 Animal myType()
 {
  return new Animal();
 }
}

class Dog extends Animal
{
 Dog myType()     //Legal override after Java5 onward
 {
  return new Dog();
 }
}

Difference between Overloading and Overriding

Method OverloadingMethod Overriding
Parameter must be different and name must be same.Both name and parameter must be same.
Compile time polymorphism.Runtime polymorphism.
Increase readability of code.Increase reusability of code.
Access specifier can be changed.Access specifier most not be more restrictive than original method(can be less restrictive).
difference between overloading and overriding

Q. Can we Override static method ? Explain with reasons ?

No, we cannot override static method. Because static method is bound to class whereas method overriding is associated with object i.e at runtime.
Read More »

Aggregation ~ GNIITHELP

Aggregation (HAS-A)

HAS-A relationship is based on usage, rather than inheritance. In other words, class A has-a relationship with class B, if code in class A has a reference to an instance of class B.

Example

class Student
{
 String name;
 Address ad;
}
Here you can say that Student has-a Address.
Aggregation in Java
Student class has an instance variable of type Address. Student code can use Address reference to invoke methods on the Address, and get Address behavior.
Aggregation allow you to design classes that follow good Object Oriented practices. It also provide code reusability.

Example of Aggregation

class Author
{
 String authorName;
 int age;
 String place;
 Author(String name,int age,String place)
 {
  this.authorName=name;
  this.age=age;
  this.place=place;
 }
 public String getAuthorName()
 {
  return authorName;
 }
 public int getAge()
 {
  return age;
 }
 public String getPlace()
 {
  return place;
 }
}

class Book
{
 String name;
 int price;
 Author auth;
 Book(String n,int p,Author at)
 {
  this.name=n;
  this.price=p;
  this.auth=at;
 }
 public void showDetail()
 {
  System.out.println("Book is"+name);
  System.out.println("price "+price);
  System.out.println("Author is "+auth.getAuthorName());
 }
}

class Test
{
 public static void main(String args[])
 {
  Author ath=new Author("Me",22,"India");
  Book b=new Book("Java",550,ath);
  b.showDetail();
 }
}
Output :
Book is Java.
price is 550.
Author is me.

Q. What is Composition in java?

Composition is restricted form of Aggregation. For example a class Car cannot exist without Engine.
class Car
{
 private Engine engine;
 Car(Engine en)
 {
  engine = en;
 }
}

Q. When to use Inheritance and Aggregation?



When you need to use property and behaviour of a class without modifying it inside your class. In such case Aggregation is a better option. Whereas when you need to use and modify property and behaviour of a class inside your class, its best to use Inheritance.
Read More »

Inheritance ~ GNIITHELP

Inheritance (IS-A)

Inheritance is one of the key features of Object Oriented Programming. Inheritance provided mechanism that allowed a class to inherit property of another class. When a Class extends another class it inherits all non-private members including fields and methods. Inheritance in Java can be best understood in terms of Parent and Child relationship, also known as Super class(Parent) and Sub class(child) in Java language.
Inheritance defines is-a relationship between a Super class and its Sub class. extends and implementskeywords are used to describe inheritance in Java.
Inheritance in Java
Let us see how extend keyword is used to achieve Inheritance.
class Vehicle. 
{
  ......  
}
class Car extends Vehicle 
{
 .......   //extends the property of vehicle class.
}
Now based on above example. In OOPs term we can say that,
  • Vehicle is super class of Car.
  • Car is sub class of Vehicle.
  • Car IS-A Vehicle.

Purpose of Inheritance

  1. To promote code reuse.
  2. To use Polymorphism.

Simple example of Inheritance

class Parent
{
    public void p1()
    {
        System.out.println("Parent method");
    }
}
public class Child extends Parent {
    public void c1()
    {
        System.out.println("Child method");
    }
    public static void main(String[] args)
    {
        Child cobj = new Child();
        cobj.c1();   //method of Child class
        cobj.p1();   //method of Parent class 
    }
}
Output :
Child method
Parent method

Another example of Inheritance

class Vehicle
{
    String vehicleType;
}
public class Car extends Vehicle {
    
    String modelType;
    public void showDetail()
    {
        vehicleType = "Car";        //accessing Vehicle class member
        modelType = "sports";
        System.out.println(modelType+" "+vehicleType);
    }
    public static void main(String[] args)
    {
        Car car =new Car();
        car.showDetail();
    }
}
Output :
sports Car

Types of Inheritance

  1. Single Inheritance
  2. Multilevel Inheritance
  3. Heirarchical Inheritance
NOTE :Multiple inheritance is not supported in java
Types of Inheritance in Java

Why multiple inheritance is not supported in Java

  • To remove ambiguity.
  • To provide more maintainable and clear design.
problem with multiple inheritance

super keyword

In Java, super keyword is used to refer to immediate parent class of a class. In other words super keyword is used by a subclass whenever it need to refer to its immediate super class.
example of super keyword in java

Example of Child class refering Parent class property using super keyword

class Parent
{
    String name;
    
}
public class Child extends Parent {
    String name;
    public void details()
    {
        super.name = "Parent";     //refers to parent class member
        name = "Child";
        System.out.println(super.name+" and "+name);
    }
    public static void main(String[] args)
    {
        Child cobj = new Child();
        cobj.details();
    }
}
Output :
Parent and Child

Example of Child class refering Parent class methods using super keyword

class Parent
{
    String name;
    public void details()
    {
      name = "Parent";
        System.out.println(name);
    }  
}
public class Child extends Parent {
    String name;
    public void details()
    {
        super.details(); //calling Parent class details() method
        name = "Child";
        System.out.println(name);
    }
    public static void main(String[] args)
    {
        Child cobj = new Child();
        cobj.details();
    }
}
Output :
Parent
Child

Example of Child class calling Parent class constructor using super keyword

class Parent
{
    String name;

    public Parent(String n) 
    {
        name = n;
    }
    
}
public class Child extends Parent {
    String name;

    public Child(String n1, String n2) 
    {
        
        super(n1);       //passing argument to parent class constructor
        this.name = n2;
    }
    public void details()
    {
        System.out.println(super.name+" and "+name);
    }
     public static void main(String[] args)
    {
        Child cobj = new Child("Parent","Child");
        cobj.details();
    }
}
Output :
Parent and Child

Super class reference pointing to Sub class object.

In context to above example where Class B extends class A.
 A a=new B();
is legal syntax because of IS-A relationship is there between class A and Class B.

Q. Can you use both this() and super() in a Constructor?

NO, because both super() and this() must be first statement inside a constructor. Hence we cannot use them together.
Read More »

Java Modifiers ~ GNIITHELP

Modifiers in Java

Modifiers are keywords that are added to change meaning of a definition. In Java, modifiers are catagorized into two types,
  1. Access control modifier
  2. Non Access Modifier

1) Access control modifier

Java language has four access modifier to control access levels for classes, variable methods and constructor.
  • Default : Default has scope only inside the same package
  • Public : Public scope is visible everywhere
  • Protected : Protected has scope within the package and all sub classes
  • Private : Private has scope only within the classes
Access modifier in java

2) Non-access Modifier

Non-access modifiers do not change the accessibility of variables and methods, but they do provide them special properties. Non-access modifiers are of 5 types,
  1. Final
  2. Static
  3. Transient
  4. Synchronized
  5. Volatile

Final

Final modifier is used to declare a field as final i.e. it prevents its content from being modified. Final field must be initialized when it is declared.
Example :
class Cloth
{
 final int MAX_PRICE = 999;    //final variable
 final int MIN_PRICE = 699;
 final void display()      //final method
 {
  System.out.println("Maxprice is" + MAX_PRICE );
  System.out.println("Minprice is" + MIN_PRICE);
 }
}
A class can also be declared as final. A class declared as final cannot be inherited. String class in java.lang package is a example of final class. Method declared as final can be inherited but you cannot override(redefine) it.

Static Modifier

Static Modifiers are used to create class variable and class methods which can be accessed without instance of a class. Lets study how it works with variables and member functions.

Static with Variables

Static variables are defined as a class member that can be accessed without any object of that class. Static variable has only one single storage. All the object of the class having static variable will have the same instance of static variable. Static variables are initialized only once.
Static variable are used to represent common property of a class. It saves memory. Suppose there are 100 employee in a company. All employee have its unique name and employee id but company name will be same all 100 employee. Here company name is the common property. So if you create a class to store employee detail, company_name field will be mark as static.
Example
class Employee
{
int e_id;
String name;
static String company_name = "StudyTonight";
}

Example of static variable

class ST_Employee
{
    int eid;
    String name;
    static String company_name ="StudyTonight";
    public void show()
    {
        System.out.println(eid+" "+name+" "+company_name);
    }
    public static void main( String[] args )
    {
     ST_Employee se1 = new ST_Employee();
     se1.eid = 104;
     se1.name = "Abhijit";
     se1.show();
     ST_Employee se2 = new ST_Employee();
     se2.eid = 108;
     se2.name = "ankit";
     se2.show();
    }

}
Output :
104 Abhijit StudyTonight
108 ankit StudyTonight
static variable example

Static variable vs Instance Variable

Static variableInstance Variable
Represent common propertyRepresent unique property
Accessed using class nameAccessed using object
get memory only onceget new memory each time a new object is created
Example
public class Test 
{
   static int x = 100;
   int y = 100;
   public void increment()
   {
       x++; y++;
   }
 public static void main( String[] args )
 {
     Test t1 = new Test();
     Test t2 = new Test();
     t1.increment();
     t2.increment();
     System.out.println(t2.y);
     System.out.println(Test.x); //accessed without any instance of class.
 }
}
Output :
101
102
See the difference in value of two variable. Static variable y shows the changes made to it by increment() method on the different object. While instance variable x show only the change made to it by increment() method on that particular instance.

Static Method

A method can also be declared as static. Static methods do not need instance of its class for being accessed. main() method is the most common example of static method. main() method is declared as static because it is called before any object of the class is created.
Example :
class Test 
{
 
 public static void square(int x) 
 {
  System.out.println(x*x);
 }

 public static void main (String[] arg) 
 {
   
  square(8)   //static method square () is called without any instance of class.
 }
}
Output: 64

Static block

Static block is used to initialize static data member. Static block executes before main() method.
Example
class ST_Employee
{
   int eid;
   String name;
   static String company_name;
    
   static {
    company_name ="StudyTonight";    //static block invoked before main() method  
    }

    public void show()
    {
        System.out.println(eid+" "+name+" "+company_name);
    }
    public static void main( String[] args )
    {
     ST_Employee se1 = new ST_Employee();
     se1.eid = 104;
     se1.name = "Abhijit";
     se1.show();
     
    }

}
Output :
104 Abhijit StudyTonight

Q. Why a non-static variable cannot be referenced from a static context ?

When you try to access a non-static variable from a static context like main method, java compiler throws a message like "a non-static variable cannot be referenced from a static context". This is because non-static variables are related with instance of class(object) and they get created when instance of a class is created by using new operator. So if you try to access a non-static variable without any instance compiler will complain because those variables are not yet created and they don't have any existence until an instance is created and associated with it.
Example of accessing non-static variable from a static context
class Test
{
 int x;
 public static void main(String[] args)
 {
  x=10;
 }
}
Output :
compiler error: non-static variable count cannot be referenced from a static context
Same example using instance of class
class Test
{
 int x;
 public static void main(String[] args)
 {
  Test tt=new Test();
  tt.x=10;  //works fine with instance of class
 }
}

Q. Why main() method is static in java ?

Because static methods can be called without any instance of a class and main() is called before any instance of a class is created.

Transient modifier

When an instance variable is declared as transient, then its value doesn't persist when an object is serialized

Synchronized modifier

When a method is synchronized it can be accessed by only one thread at a time. We will discuss it in detail in Thread.

Volatile modifier

Volatile modifier tells the compiler that the volatile variable can be changed unexpectedly by other parts of your program. Volatile variables are used in case of multithreading program.
Read More »