0

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.

4
  • See: stackoverflow.com/questions/7026507/… and stackoverflow.com/questions/21155438/… Commented Jul 12, 2020 at 4:43
  • Why can't you do this in constructor? Commented Jul 12, 2020 at 4:45
  • @bigbounty I don't know how to do that. Can you tell me how to do with constructor? Commented Jul 12, 2020 at 7:44
  • @UdayAgrawal I have answered in a better manner. Please check Commented Jul 12, 2020 at 7:53

2 Answers 2

1
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

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for your answer. This is much better way to get the value of var variable.
Though your answer is more tricky and better than previous, your answer do not give what exactly the solution is. So, I won't accept it as the answer. Thank you brother and sorry for this.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.