Sunday 25 September 2011

Important Question of java...............


Q: What is the instance variables?
Instance variables are the methoda which act on the instance variables of the class. To call the instance methods.
Objectname.method().
Q: What are the static  methods?
Static methods are the methods which do not act upon th instance variables of a class. Static methods are declared as Static.
To call static methods we need not create object.

This is example
class Sample {
                static double sum(double num1,double num2)
                {
                                double s=num1+num2;
                                return s;
                               
                               
                }
}
                class method
                {
                                public static void main(String[] args) {
                                                double x=Sample.sum(10, 20.5);
                                                System.out.println(x);
                                }
                }
The reason why static methods can not act on instance variables is that the jvm first executes the static methods and then only it creates the objects.since the objects are not aviavble at the timeof calling the static methods.
This is program give a error.
Class  Test
{
Int x;
Test(int x)
{
this.x=x;
}
Static void access()
{
System.out.println(“x=”+x);
}
}
Class Demo
{
public static void main(String[] args)
{
Test obj =new Test(55);
Test.access();
}
}


Q: what is differnce b/w instance variables and class variables ?
Instance variables whose separate copy is aviable to each objact.
A class variables is a variable whose single copy in memory is shared by all the objects.
Instace variables are created in the objects in heap memory. Class variables are store on method area.

Imp property of static method…
Static call first even from main method..
class static1
{
     
      static
      {
            System.out.println("static block");
      }
     
      public static void main(String[] args) {
            System.out.println("static method");
      }
}

No comments:

Post a Comment