Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Java Quiz: Static Members in Java

DZone's Guide to

Java Quiz: Static Members in Java

Learn about how static members in Java behave in DZone's newest Java quiz!

· Java Zone
Free Resource

Just released, a free O’Reilly book on Reactive Microsystems: The Evolution of Microservices at Scale. Brought to you in partnership with Lightbend.

Last Week's Answer

The correct answer is the code writes "[d, a, b, e]" to the standard output.

This Week's Quiz

Purpose

  1. To demonstrate some behaviors and tricks of static members in Java

  2. Mind training to understand what happens next.

What Happens When the Following Program is Compiled and Run?

public class MyClass {

    static int x;
    StringBuffer sb = new StringBuffer();
    static StringBuffer sb2 = new StringBuffer();

    public MyClass() {
        method();
        method2();
    }
    public void method(){
        x += 3;
        sb.append(x);
    }
    public void method2(){
        x += 3;
        sb2.append(x);
    }
    public static void main(String[] args){
        MyClass mc = new MyClass();
        MyClass mc2 = new MyClass();
        MyClass mc3 = new MyClass();
        System.out.println(mc2.sb + "-" + mc2.sb2);
    }
}


Let us know your thoughts in the comments, and visit Sar's site here!

Strategies and techniques for building scalable and resilient microservices to refactor a monolithic application step-by-step, a free O'Reilly book. Brought to you in partnership with Lightbend.

Topics:
java ,static ,members

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}