Showing posts with label Basics. Show all posts
Showing posts with label Basics. Show all posts

Saturday, 28 September 2013

Passing an array to a method

We must create an array variable to hold the data that you want to pass as an argument to a method otherwise you will get a compile time error.

Eg:


              public class PassingArrayToMethodDemo {

                       static void methodA(int a[]){
                          //some statements to accomplish the task here
               }

                       public static void main(String[] args) {

                           methodA({1,3,4,5});   // gives compile time error

                           int arr[] = {1,3,4,5};
                           methodA(arr);    //it is legal to pass an array variable
              }


               }

Friday, 27 September 2013

instanceof

The instanceof is one of the keywords that helps you in finding the object type at runtime. For example, in runtime, your method is returning an object on which you have to do something where you are not expecting the runtime error like class cast exception whih terminates your program unexpectedly. At this time this instanceof keyword helps in finding the type of your object.


Eg:

public class InstanceOfDemo {

public static void main(String args[]){

Base base = new Base();
Derived derived = new Derived();
Base baseDerived = new Derived();

System.out.println("Base instanceof Base: " + (base instanceof Base));
System.out.println("Base instanceof Derived: " + (base instanceof Derived));
System.out.println("Derived instanceof Base: " + (derived instanceof Base));
System.out.println("Derived instanceof Derived: " + (derived instanceof Derived));
System.out.println("BaseDerived instanceof Base: " + (baseDerived instanceof Base));
System.out.println("BaseDerived instanceof Derived: " + (baseDerived instanceof Derived));

}


}
class Base{
//some variable declarations and method definitions here
}
class Derived extends Base{
//some variable declarations and method definitions here
}

Result:
Base instanceof Base: true
Base instanceof Derived: false
Derived instanceof Base: true
Derived instanceof Derived: true
BaseDerived instanceof Base: true
BaseDerived instanceof Derived: true