I recently left Python behind to pick up Java.
In Python, a variable defined in a function could not be called outside of the function.
But you could at least let the function return a value, which could be a variable defined in the function.

When a variable is defined in Java it cannot be called outside of the method it was defined in. But doesn't that make the e.g. if method close to worthless? Shouldn't you be able to use variable you got in the if statement later in the code?

My question is; Is there anything like Python's return in Java?

Recommended Answers

All 5 Replies

Can you post an example of where you are having a problem with the scope of a variable?

A return statement can return any single value to the method's caller.

Here's a simple example of what I'm talking about;

class jva {
     public static void main(String args[]) {

        int a=15;
        int b=10;

        if (a > b) {
            int c = a;
        }
        else {
            int c = b;
        }

        System.out.println(c);}
        }

Where is the method that returns a value?
What is the posted code supposed to show?

Do you know what the scope of a variable is? Its definition and usage is restricted to the pair of {}s it is defined inside of.

The variable c is out of scope and not defined on line 14. There are two variables named c defined on lines 8 & 11.

The following should compile:

class jva {
     public static void main(String args[]) {

        int a=15;
        int b=10;
        int c = 0;  // define c so in scope for the println

        if (a > b) {
            c = a;
        }
        else {
            c = b;
        }

        System.out.println(c);}
        }

public void main... declares its return type as "void" - ie it returns nothing.
Do you mean something like this?

public int timesTwo(int i) { // method returns an int
   int j = i*2;
   return j;
}

I think JamesCherrill hit the nail on the head with the "problem" you were encountering. I just wanted to post on the idea a little more explicitly.

Yes, java can return a value from a method. Using void in a method definition says that it won't return a value. Changing that to a different data type will allow you to return a variable of the type you say you will return.

Example:

// int in the method header defines that this method will return an int
public int sum (int firstNum, int secondNum) {
    int theSum = 0; // define the variable that I will use as a sum and return

    theSum = firstNum + secondNum; // update the value I'm going to return

    return theSum; // return the value now that it contains the sum of the passed numbers
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.