Menu
Topics Index
...
`

Static method and variables


If you need explanation Read this topic

If you need Answer Take test on this topic

Static method and variables
What will be the output of the following program?
public class GuessCondition
{
    static int a = 40;
    public static void main(String args[])
    {
        System.out.print(a + " ");
        add();
        System.out.print(a);
    }
    private static void add()
    {
        a = a + 40;
    }
}

A. 40 40
B. 0 0
C. 0 40
D. 40 80
E. Compilation Error or Runtime Error
Topic: Static Keyword In Java

If you need explanation Read this topic

If you need Answer Take test on this topic

User comments below. All of them might not be correct.

Ans is D..
Static variable: static variables are common to all Objects...if class has n number of instances than static variables are common to all...where we as instance variables will create n number..and we can access this variables with class and with instance also

Static Method:
in some situations we may need to access the methods without creating the instances..in this situations static methods will helpful...we can invoke the static methods with help of class name without creating the instance also...and we can not use the non-static(Instance) variables in the static methods

Execution: here we have a as static variable and we are calling add() there we are adding 40 to a than it will become 80..we are printing before and after adding so 40 80

Posted by Uday Kumar    2015-01-01 04:20:23


ANS IS D

In above program static variables and methods are used.
--static variables have following properties:
1.They are initialized to zero.
2.They are called with class name.
3.All Objects of the class share the static variables.
4.Only static methods can access static variables.

In above program integer variable 'a' is declared as static and assigned to 40 and it is printed in main method which is also static.

Then add() method is called in which a is incremented by 40 i.e.
-------->    a=a+40=80.

Again it is printed in main so 80 will get printed.

Posted by Mânïshå Mùlchåndânï    2015-01-01 08:46:43


This dose is now closed and the winners are Uday Kumar,  for 'First Correct Comment', Uday Kumar, Mânïshå Mùlchåndânï,  for 'Best Comment' and Uday Kumar for the 'Popular Comment'. The 'lucky liker' is Shubham Bansal. Please login into Merit Campus using facebook, to claim your recharge. Go to http://java.meritcampus.com/earnings to raise the recharge.

Posted by Merit Campus    2015-01-03 03:54:37


© meritcampus 2019

All Rights Reserved.

Open In App