Java-Gaming.org    
Featured games (91)
games approved by the League of Dukes
Games in Showcase (576)
games submitted by our members
Games in WIP (497)
games currently in development
News: Read the Java Gaming Resources, or peek at the official Java tutorials
 
    Home     Help   Search   Login   Register   
Pages: [1]
  ignore  |  Print  
  Help with return statement?  (Read 2559 times)
0 Members and 1 Guest are viewing this topic.
the_jogler
Guest
« Posted 2007-09-01 11:35:14 »

I've been wondering this for a long time now. Maybe I have some kind of problem, but I just can't grasp the concept of the "return" statement; not just in Java, but in ANY programming language. O_o What I want to know is, if you return something like a variable, to where are you returning it, what happens to the variable, and why do you need to return it? (I don't know how much Java uses the "return" statement, but I've seen it used before. And I know some of you are C/C++ developers, so even if you offer your input on the C/C++ return statement, that would be just fine, too. Grin) Thanks!  Grin
Offline keldon85

Senior Member


Medals: 1



« Reply #1 - Posted 2007-09-01 11:53:56 »

What you need to do is take a Java programming tutorial, it will tell you what is going on and get you started with programming.

the_jogler
Guest
« Reply #2 - Posted 2007-09-01 11:56:16 »

Oh, thank you, but I've already gotten started in programming. Actually, I'm quite far into Java. I just need to know those things about return statements, they just confuse me. Sad But either way, I'll check out that tutorial. Thank you!
Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline Herko_ter_Horst

Senior Newbie




Java games rock!


« Reply #3 - Posted 2007-09-01 13:23:16 »

When you return from a method, control is passed back to wherever the method was called from (i.e. another method). The return value of the method is inserted into the expression that called the method. For example, in this code
1  
int x = 1;
there is no method call, and the value 1 is assigned to the variable x.

In this code snippet
1  
2  
3  
4  
int x = add(1, 1);
public int add(int first, int second) {
 return first + second;
}

The expression is evaluated by passing control to the add() method, executing the code inside the add() method and inserting the result returned from it back into the expression. So after the return from the method, the expression is equal to:
1  
int x = 2;
That's all.
the_jogler
Guest
« Reply #4 - Posted 2007-09-01 21:26:28 »

Do you have to return every variable once you're done with it? (In the method?)
Offline keldon85

Senior Member


Medals: 1



« Reply #5 - Posted 2007-09-01 22:06:59 »

Do you have to return every variable once you're done with it? (In the method?)
It sounds like you really need to go through the tutorials a lot more. Try Sun's JAva tutorials, and when you're finished with them you'll have a much better idea of what you are doing in programming.

the_jogler
Guest
« Reply #6 - Posted 2007-09-01 23:39:14 »

I've already gone through tutorials and bought countless Java books. I'm just having trouble grasping the concept of a return statement. Sad It's just one of those things.
Offline erikd

JGO Ninja


Medals: 15
Projects: 4
Exp: 14 years


Maximumisness


« Reply #7 - Posted 2007-09-02 00:01:35 »

Quote
Actually, I'm quite far into Java.

If you're having trouble with return statements, no offense but then the first thing you need to understand is that you're really not quite far into java, or any kind of programming language.

Just see your expression that calls a function with a return statement as a question
1  
int sum = tellMeTheSumOf(1, 2);


The function as something that answers your question, and the return statement will 'return' the answer to the question
1  
2  
3  
4  
public int tellMeTheSumOf(int value1, int value2);
  int answer = value1 + value2;
  return answer;
}


Note here that the type of the answer (int) is of the same type of the variable that stores the answer (sum).

Quote
Do you have to return every variable once you're done with it? (In the method?)
If you ask a question about something to someone, you don't need to know *how* he got the answer, you just need the answer. So there can be only one return statement because your question has only one answer, so there's no need to return anything else.

Quote
to where are you returning it, what happens to the variable, and why do you need to return it?
You return it to wherever you called the function; in the above example you return it the variable 'sum'.
The variable you're returning only exists within the function (the code block between { and }), so you need to return it because you want to get the result from the function. The return statement 'copies' the variable to the expression calling the function:
In the above example, the variable 'answer' doesn't exist outside of the function 'tellMeTheSumOf', so you need the 'return' statement to 'copy' the answer into the variable 'sum'.

the_jogler
Guest
« Reply #8 - Posted 2007-09-02 00:30:55 »

Oh, I get it now. Okay, I'm not that far into Java, but it's not like I'm just starting out. I know about loops, conditional statements, classes, objects, methods, etc. I've just always had trouble contemplating a return statement, even when I did some stuff with C/C++. Maybe it's like some kind of learning disability (or maybe just a brain fart Tongue) but it doesn't matter, it makes sense now. Thanks! Grin
Offline rdcarvallo

Senior Member


Projects: 5
Exp: 15 years


2D Java games forever!


« Reply #9 - Posted 2007-09-03 21:27:21 »

What I want to know is, if you return something like a variable, to where are you returning it, what happens to the variable, and why do you need to return it?
Do you have to return every variable once you're done with it? (In the method?)

I guess you are thinking about returning (freeing) memory of the variables when used.

This is managed by Java itself, you do not need to free the variables.

When a method needs to pass a result (a value calculated, a new object created) to the program calling it, you must use the return statement.

Examples here:
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
public class ReturnExample{
  int value;
  String stringObject;
  public ReturnExample(){
     value = calculateValue(2,5);
     stringObject = createString();
  }
  /**
   * This calculates the value 10 * a + b
   */

  int calculateValue(int a, int b){
     int result = 10 * a + b;
     return result;
  }
  /**
   * This creates a String object
   */

  String createString(){
    String myString  = "My String";
    return myString;
  }
}


Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline broumbroum

Junior Member





« Reply #10 - Posted 2007-09-04 02:01:12 »

further the Java VM clears the variable only when they're no more linked to a reference, a.k.a the variable name itself. Whatever you want to get from the value you return from some method, Java will clear it unless you keep a so called "strong reference" to it. java code be so with EVERY single instance :
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
class Main { 
static boolean getBoolValue(int argument0, int argument1, String argument3) {
        if(argument0 > 0 )
                return true;
        else if(argument1 > 0)
                return true;
        else  if(argument3.equals("OK!!"))
                return true;
        else return false;
}

/*** this static reference variable will hold forever */
static boolean returnValue;

/*** the main will check for the variable after the first unstored call and will look again after the second stored call. You will observe null PointerException */
public static void main(String[] args) {
      try{ getBoolValue(1, 2, "3");
      if(returnValue)
          System.out.println("returnValue is " + returnValue);
      } catch(Exception e) { e.printStackrace(); } finally {
           returnValue = getBoolValue(1, 2, "3");
           if(returnValue)
                System.out.println("returnValue is " + returnValue);
     }
}
}

Of course some readers here would say this is a stupid example, but this is a way to get things explained for such terrific questions.... WinkWinkWink

::::... :..... :::::: ;;;:::™ b23:production 2006 GNU/GPL @ http://b23prodtm.webhop.info
on sf.net: /projects/sf3jswing
Java (1.6u10 plz) Web Start pool
dev' VODcast[/ur
Offline cylab

JGO Knight


Medals: 34



« Reply #11 - Posted 2007-09-04 10:40:57 »

Actually I think this example is more confusing than helping here, since static variables are something you really need only in a few special cases and learning them to soon misleads beginners to code in java like in C (having one file with a main function and only static variables and methods).

Mathias - I Know What [you] Did Last Summer!
Offline erikd

JGO Ninja


Medals: 15
Projects: 4
Exp: 14 years


Maximumisness


« Reply #12 - Posted 2007-09-04 11:22:01 »

Agreed, and apart from that, the code is pure nonsense.

Offline stef569

Junior Member





« Reply #13 - Posted 2007-09-04 12:04:42 »

Ok, I have a simular question...  Grin

You want to show a text only for a couple of seconds and then it should be gone
this is done in the paint method.

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
  private boolean canDrawStartText(int delay) {
    int startText_Timer=0;
    boolean canDraw = false;
    /* Show the Start Text until the time has elapsed. */
    if (startText_Timer != -1) delay++;

    if( startText_Timer % delay != 0 && startText_Timer != -1 )
      canDraw = true;
    else
      startText_Timer = -1;

    return canDraw;
  }

Is it possible to hold the startText_Timer var in the memory as long as the program is running?
and not set as private object var.
Offline cylab

JGO Knight


Medals: 34



« Reply #14 - Posted 2007-09-04 13:45:27 »

You are asking for a static local variable, which is not present in the java language. You have to use a (private static) member variable for this.

Mathias - I Know What [you] Did Last Summer!
Offline stef569

Junior Member





« Reply #15 - Posted 2007-09-04 14:20:52 »

Thanks  Smiley
Offline erikd

JGO Ninja


Medals: 15
Projects: 4
Exp: 14 years


Maximumisness


« Reply #16 - Posted 2007-09-04 20:05:47 »

You are asking for a static local variable, which is not present in the java language. You have to use a (private static) member variable for this.

Preferrably not a static one though, since the method is (rightfully) not static either  Smiley

Offline JAW

Junior Member





« Reply #17 - Posted 2007-09-14 09:55:32 »

Wow, I think return is really easy Smiley

Well think of the simplest applications of return. You have a method or function and you usually want it do to something for you.
If you have a LinkedList and you want to have the 3rd object in the list, you call list.get(3), and the get function will return the object. Or you want to know the position of your object, you call list.indexOf(obj) and it will return the position. It will do something like
- start at the beginning
- if the current object is the searched one, RETURN the current position
- else go to the next object until the end of the list is reached

If you call list.size() it will return the number of elements in the list, for example by counting it.

Lets move on, if you need random numbers, you can use Random rand = new Random() and then you need a random Integer between 0 and 100, you will call rand.nextInt(100) and it will return a random int between 0 and 100.

Or the Math class. It does simple calculations for you.
Math.sqrt(4) will return the square root of the given number. Math.max(a,b) will return the bigger of the two integers.


Generally, a function can return something or nothing, then its a void function. And a function can take parameters or take no parameters. It depends on what you want it to do.

1) Add something to the list will need a parameter , the object you want to add. But you dont need a return because adding will not return any result.
2) Sorting the list does not need a parameter and does not return anything, it just modifies the order of the elements.
3) Getting the size of the list will not need a parameter, but will return the count of elements.
4) Getting the position of an element will requiere the element as parameter and will return the position.

So a method usually shall do a piece of work for you. E.g. System.out.println("abc") shall make an output in the console. Sometimes you must give the function something it needs to do its work, then you need parameters. Sometimes, the function will produce some kind of result, then you need to return it. And sometimes you need none or both.

I hope this helps. Consider a function as an question or order and return is a response or result or product. If i ask you, how much money do you have with you, you will look in your pocket, count the coins and bills and reply (return) the amount of money you have.

Another example. If you have a sentence and want to get every single word, you can use a StringTokenizer. Calling hasMoreTokens() will return true or false, depending on if there are still words left to process. Calling nextToken() will return the next word in the sentence. So this function does a piece of work for you and by return it gives you a product or result of this work.

Your real question is: How do functions work and what do I need them for? Once you understand that a function does a piece of work you will instantly come to the problem, that you will often need it to give you the result in some way, and there you are. If you need the sine of an angle, you dont compute it yourself, youll call a function which does the math and it will return the value.

The next chapter will be object orientet programming (OOP). This will explain how data and functions are bundled together in reasonable way.

Still questions?

-JAW
Pages: [1]
  ignore  |  Print  
 
 
You cannot reply to this message, because it is very, very old.

 

Add your game by posting it in the WIP section,
or publish it in Showcase.

The first screenshot will be displayed as a thumbnail.

xsi3rr4x (12 views)
2014-04-15 18:08:23

BurntPizza (11 views)
2014-04-15 03:46:01

UprightPath (24 views)
2014-04-14 17:39:50

UprightPath (10 views)
2014-04-14 17:35:47

Porlus (27 views)
2014-04-14 15:48:38

tom_mai78101 (49 views)
2014-04-10 04:04:31

BurntPizza (108 views)
2014-04-08 23:06:04

tom_mai78101 (207 views)
2014-04-05 13:34:39

trollwarrior1 (176 views)
2014-04-04 12:06:45

CJLetsGame (182 views)
2014-04-01 02:16:10
List of Learning Resources
by Longarmx
2014-04-08 03:14:44

Good Examples
by matheus23
2014-04-05 13:51:37

Good Examples
by Grunnt
2014-04-03 15:48:46

Good Examples
by Grunnt
2014-04-03 15:48:37

Good Examples
by matheus23
2014-04-01 18:40:51

Good Examples
by matheus23
2014-04-01 18:40:34

Anonymous/Local/Inner class gotchas
by Roquen
2014-03-11 15:22:30

Anonymous/Local/Inner class gotchas
by Roquen
2014-03-11 15:05:20
java-gaming.org is not responsible for the content posted by its members, including references to external websites, and other references that may or may not have a relation with our primarily gaming and game production oriented community. inquiries and complaints can be sent via email to the info‑account of the company managing the website of java‑gaming.org
Powered by MySQL Powered by PHP Powered by SMF 1.1.18 | SMF © 2013, Simple Machines | Managed by Enhanced Four Valid XHTML 1.0! Valid CSS!