Uday
Uday

Reputation: 5

Value of variable not updating in Java NetBeans

I have two java files in same package. I want to take the updated value of one variable from one file to another. I wrote the following code. In class1.java :-

import javax.swing.JOptionPane;
public class class1 {
    public static String bar = "Yes";
    static int age = 26;
    public static void main(String[] args){
        switch(age) {
            case 25: bar = "world";
                break;
            case 26: bar = "good";
                break;
            case 27: bar = "very";
                break;
            case 30: bar = "hello";
                break;
            default: JOptionPane.showMessageDialog(null,"Please");
                break;
        }
    }
}

In class2.java :-

public class class2 {
    public static void main(String[] args){
        class1 second = new class1();
        System.out.println(second.bar);
    }
}

The problem is that the final value is printed Yes which should not be printed. The output should be good. Please help me.

Upvotes: 0

Views: 269

Answers (2)

bigbounty
bigbounty

Reputation: 17368

class class1 {

    public String getBar(String age){
        String bar = "Yes";
        switch(Integer.valueOf(age)) {
            case 25: bar = "world";
                break;
            case 26: bar = "good";
                break;
            case 27: bar = "very";
                break;
            case 30: bar = "hello";
                break;
        }
        return bar;
    }
}

public class class2 {
    public static void main(String[] args){
    String age = JOptionPane.showInputDialog("Age Please");
    class1 class1Obj = new class1();
    System.out.println(class1Obj.getBar(age));
    }
}

enter image description here

Upvotes: 1

FailingCoder
FailingCoder

Reputation: 767

You create a class1 object, but you never run the main method. This means that the section of code never runs, and thus bar remains as "Yes".

In class2 insert second.main(args); before you print second.bar and you will get a good value.

Upvotes: 0

Related Questions