1

So ive learned some basic python programming and was learning some Java through some books. I was trying out some pretty basic coding examples on eclispe and i had a question about the return statement

in Python a return statement in a function for example would output something to the screen for instance in python if a function was : def test(x): return x and i tested with test(4) integer 4 would output to the screen. Does return work the same way in java?

1
  • 4
    I don't think your assumption is correct. If you're running Python in interactive mode, the result of each expression you enter is printed. test(4) evaluates to 4 (since 4 is returned), and that's why 4 is printed. Return works the same in Python and Java. Commented Sep 2, 2013 at 23:11

2 Answers 2

2

In Python the return statement does not print anything to the screen. What's happening is that you're running Python in a REPL (an interactive mode), so the values returned by the functions get automatically displayed on-screen.

However, if you run Python from a command line (say, by executing a script) the values returned by functions will not be displayed on-screen ... unless you explicitly print them. Same is true for java:

System.out.println(x); // this is how you print in Java
print(x)               // this is how you print in Python

AFAIK all the programming languages that have a return keyword (or equivalent) don't print anything on-screen, return is useful only for, well, returning a value from a function or method. A separate instruction is required for displaying results.

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

Comments

0

In Java the return function passes an object or primitive back to the calling method (the code that originally called your function). The calling method may do whatever it likes (including print) the returned value.

public static int myMethod() {
    return 5;
}

public static void main (String[] args) {
    int a = myMethod();
    System.out.println(a); //prints 5
}

2 Comments

How is that "unlike Python" (or any other language). Isn't that just what return always does everywhere?
I'm replying to what the poster implied about Python. I've not done work in Python.

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.