Intermediate quizzes – Java static methods & variables

The following Java exercise(s) are designed for intermediate level programmers. If the level is too hard, then I recommend to select an easier one or you might consider reading my article about this topic, which offers a theoretical explanation including more exercises. Read More: Java Static Methods And Variables

static-members-blue

Quiz 1: A static method and variable in Java

What appears in the standard output when this program is invoked?

public class MyClass {

	static int x = 3;
	int y;

	MyClass() {
		x ++ ;
		y ++ ;
	}
	static void methodA(int i, int i2){
		x = x + i + i2;
		System.out.print("-x" + x);
	}
	int methodB(int i){
		this.y = y + i;
		return x - y;
	}
	public static void main(String[] args){
		MyClass mc1 = new MyClass();
		MyClass.methodA(3,2);
		MyClass.methodA(1,3);
		MyClass mc2 = new MyClass();
		MyClass.methodA(4,2);

		System.out.print("-x" + mc2.methodB(3) + "-x" + mc1.y);
	}
}

Select the correct answer.



Sar Maroof is a professional software development teacher, gives master classes and publishes technical articles. He is also an expert software developer and worked for several big as well as small companies and later as a freelancer.
 Subscribe to Sar Maroof's RSS feeds!
 Mail this page to a friend!
 Bookmark this page!

Leave a Reply

Your email address will not be published. Required fields are marked *