It is known that we cannot declare variable two times in java.Can anyone explain the following code?

问题内容:

The output of the program written is Null.
I cant find where is the error in here?
Can anyone explain the following code and why does it return Null?

class methodexample 
{ 
    int number; 
    String name; 

    void data() 
    {
        int number=5; 
        int name="Rahul";
    } 

    void display() 
    { 
        System.out.println("Number is" +number); 
        System.out.println("Name is " +name);
    } 

    public static void main(String args[]) 
    {
        methodexample m=new methodexample(); 
        m.data();
        m.display();
    }
 }

问题评论:

3  
Please read stackoverflow.com/editing-help, then add text in your question as well as just code. The text shouldn’t all be in the title. You should also be more precise – when you say “It is known that we cannot declare variable two times in java”, it’s perfectly allowable to declare a local variable with the same name as an instance variable, which is what you’ve done.
3  
your data() function assigns values to local variables, not to class variables
    
Your fields are declared in two different scopes, and the ones getting assigned are local, while the ones printed out are not assigned, and therefore are set to their default values.
    
Possible duplicate of Why does Java throw NullPointerException here? (Lrrrs answer explains the issue)
3  
It’s vastly oversimplified to say you can’t declare 2 variables with the same name. You could have 2 variables with the same name, but in 2 different methods. In your case, it’s between class variables and local (method) variables, which are in different scopes.

答案:

答案1:

“void data()” changes the global variables in its scope, but not globally. So, if you call display(), for it the variables didnt got changed – to change them in your intrest, you can let the data()-method return the string and the int: (dont use int for “rahul” tho)

int number = m.setNumber()
int name = m.setName()
int setNumber(){
return 5;
}
int setName(){
return "Rahul";
}

答案评论:

答案2:

The variables declared in void data() are local to that method and can only be referred to in that method, so the 2 variables you set at the top are still null.

class methodexample {

    int number; 
    String name;

    void data() {

        number=5;
        name="Rahul";

    }

    void display() {

        System.out.println("Number is " + number);
        System.out.println("Name is " + name);

    }


    public static void main(String args[]) {

        methodexample m=new methodexample();

        m.data();

        m.display();

    }
}

答案评论:

原文地址:

https://stackoverflow.com/questions/47755338/it-is-known-that-we-cannot-declare-variable-two-times-in-java-can-anyone-explain

Add a Comment