Docsity

Understanding Variables, Constants, and Assignment Operators in Java, Slides of Java Programming

Partial preview of the text

Download Understanding Variables, Constants, and Assignment Operators in Java and more Slides Java Programming in PDF only on Docsity!

Complex expressions

Announcements

I fail at binary Monday lab on website by Sunday

Variables

To use variables two things must be done:

  • Declaration
  • Initialization See: Uninitialized.java (and Test.java) I am 68882420 inches tall. I am -1094369310 inches tall. C example: Variables are objects in your method (or class)

Variables

int x, y, z; x = 2; y = 3; z = 4; int x=2, y=3, z=4; Same as: Declaration Initialization Variables can be declared anywhere (preferably at start)

Assignment operator

= is the assignment operator The object to the right of the equals sign is stored into the object in the left int x, int y; y = 2; x = y+2;

Assignment operator

= is NOT a mathematic equals x=3; x=4; This does not mean 3=

Assignment operator

What does this code do? int x = 2; y = 3; y=x; x=y; What was the intention of this code?

Assignment operator

= is the assignment operator The object to the right of the equals sign is stored into the object in the left int x, int y; y = 2; x = y+2;

Increment operators

Two types of increment operators: x++; // increments after command vs ++x; // increments before command (see IncrementOperator.java)

Complex assignments

The following format is general for common operations: variable (operator)= expression variable = variable (operator) expression Examples: x+=2 x = x + 2 x*=y+2 x = x * (y + 2) (see AssignmentOperator.java)

Order of operations

Binary operators need two arguments Examples: (see BinaryOperators.java) 2+3, 5/2 and 6% Unary operators require only one argument: Examples: (see UnaryOperators.java) +x, x++, !x (! is the logical inversion operator for booleans)

Order of operations

When multiple operations have the same precedence level: Binary operations go from left to right Unary operations go right to left;