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

Java Quiz: Switch Statements and Static Variables

DZone's Guide to

Java Quiz: Switch Statements and Static Variables

The latest quiz for intermediate Java programmers from DZone's resident quizmaster! This week: Do switch statements affect variables the way you think they do?

· Java Zone
Free Resource

Learn how to troubleshoot and diagnose some of the most common performance issues in Java today. Brought to you in partnership with AppDynamics.

Last Week's Answer

TreeMaps work with unique keys, which are the names of the students in this example.

When you enter the same name several times, the old one will be overwritten.

For example: The name Alexa has been added three times.

//1
  studentMap.put("Alexa",new Integer(5));
//2 
  studentMap.put("Alexa",new Integer(6));
//3 
  studentMap.put("Alexa",new Integer(8));

The first one scored 5, which wouldn't be printed to the standard output, because “5” is not greater than “5”. See the statement below!

if(i > 5)
{
System.out.print(entry.getKey() + " ");
}

The second one overwrites the first one and the third one overwrites the second one, that is the reason that only the third one is printed to the standard output.

The elements of a TreeMap are sorted, which is why the correct result is: Alexa Gemma Mason

This Week's Quiz

Purpose

  1. Comparing static and non-static variables using switch statements. 

  2. Mind training to test your expectations.

What is written to the standard output as the result of executing the following code?

class MySuper{

    int x;
    static int sx;
    int y = 2;

    MySuper(){
        this(10);
    }
    MySuper(int i){
        x += (i / 2) - y;
        sx += (i / 2) - y;
    }
}

class MySub extends MySuper{

    MySub method(){
        for(int i = 10; i > 7; i -= 2){
            switch(i){
                case 5:
                    x += i;
                    sx += i;
                case 8:
                    x += i;
                    sx += i;
                    break;
                default:
                    x += i;
                    sx += i;
                case 4:
                    x += i;
                    sx += i;
            }
        }
        return new MySub();
    }
    public static void main(String[] args){
        MySub ms = new MySub();
        ms.method();
        System.out.print(ms.x + " " + sx);
    }
}


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

Understand the needs and benefits around implementing the right monitoring solution for a growing containerized market. Brought to you in partnership with AppDynamics.

Topics:
java ,static ,variables

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}