Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
154 views
in Technique[技术] by (71.8m points)

java - What does it mean to return a value?

I'm fairly new to programming, and I'm confused about what it means exactly to return a value. At first, I thought it meant to output what value is being returned, but when I tried that in my own code, nothing happened.

class Class1 {

    public static int x = 3;

    public static int getX(){
        return x;
    }

    public static void main(String[] args){
        Class1.getX();
    }
}

This is an example of what I mean. When I run the program, nothing shows up. Considering this, I'm led to believe returning a value means something else. But what?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In simple terms, it means to return the value to caller of the method...

So, in your example, the method getX would return the value of x to the caller, allowing them access to it.

class Class1{

    static int x = 3;

    public static int getX(){
        return x;
    }

    public static void main(String args[]){
        int myX = Class1.getX(); // return the value to the caller...
        System.out.println(myX); // print the result to the console...
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...