Skip to content

Instantly share code, notes, and snippets.

@Ricket
Created August 24, 2011 23:23
Show Gist options
  • Save Ricket/1169570 to your computer and use it in GitHub Desktop.
Save Ricket/1169570 to your computer and use it in GitHub Desktop.
Correcting the notion that Java's assignment statements are evaluated "right to left."
/**
* This program proves that expressions are evaluated left to right; assignment
* statements, therefore, are evaluated left-to-right on the right side of the
* equals sign (since that's just an expression) and then assigned to the
* thing to the left of the equals sign.
*
* So when a professor tells you that assignment statements are evaluated
* right-to-left, it doesn't mean each symbol in the statement is evaluated
* in the order from right to left, just that the stuff on the right is assigned
* to the stuff on the left.
*
* @author Richard Carter
*/
public class RightToLeftTest {
public static void main(String[] args) {
// Clearly in the following statement, if it were evaluated totally from
// right-to-left, then Java would execute numberTwo, and then numberOne,
// and assign it to 'three'. Each of those two methods prints their
// number before returning it, so you will be able to see in the output
// which one executes first.
int three = numberOne() + numberTwo();
System.out.println("answer is "+three);
}
/**
* Print "one" and then return 1
* @return 1
*/
public static int numberOne() {
System.out.println("one");
return 1;
}
/**
* Print "two" and then return 2
* @return 2
*/
public static int numberTwo() {
System.out.println("two");
return 2;
}
}
// I don't normally comment this much.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment