Lecture 04 Expressions

Joseph Haugh

University of New Mexico

Free Recall

  • Get out a sheet of paper or open a text editor
  • For 2 minutes write down whatever comes to mind about the last class
    • This could be topics you learned
    • Questions you had
    • Connections you made

A Note On Playing With Lecture Code

  • In Java if you want to play with snippets of code from lecture you cannot simply copy and paste them into a java file
  • Instead you should create a lecture playground project in IntelliJ
  • Then each time you want to play around with some code create a new Java compact file and paste the lecture code inside of main
  • Then you can run main and see the results
  • Later we will have longer examples where this process doesn’t necessarily apply

Example Of Playing With Lecture Code

  • For example, take some code from the previous lecture:

    int i = 0;
    while (i < 5) {
        IO.println(i);
        i = i + 1;
  • Create a Java compact file and then paste the code inside main

  • It should look like this:

    void main() {
        int i = 0;
        while (i < 5) {
            IO.println(i);
            i = i + 1;
        }
    }

Fixing Indentation

  • Recall that most modern IDEs/Text Editors give you the ability to indent multiple lines at once by selecting the lines then:
    • <tab> to indent
    • <shift+tab> to de-indent

Expressions

  • An expression is piece of code which results in a value
  • For example,
    • Literal (i.e. “hello”, 1, 2.3, etc.)
    • Variable
    • Function call
    • Many expressions combine with operators (i.e. +, *, /, -, etc.)

Arithmetic Operators

Java has all the standard arithmetic operators:

Name Symbol
Addition +
Subtraction -
Multiplication *
Division /
Modulus %

Python vs Java: Integer Division

One difference does exist between Java and Python: integer vs floating-point division

Python

x = 7
y = 3
# Floating-point division
print(x / y)  # 2.3333333...
# Integer division
print(x // y) # 2

Java

int x = 7;
int y = 3;
// Floating-point division
IO.println((double)x / y); // 2.3333333...
// Integer division
IO.println(x / y);         // 2
  • (double)x is called casting meaning we are changing its type from int to double

Python vs Java: Types

  • In Python types are implicit and can change without your knowledge
  • In Java types are explicit and cannot change without your knowledge
  • Thus, Java needs a way for you to change the types of variables
  • This is called casting

Type Casting

  • Type casting is a necessary part of Java but it must be treated with care
  • It allows you to change the type of a variable in your program
  • As we saw previously this can allow you to do thing such as compute the result of floating-point division given 2 ints (more on this in a second)
  • It can also cause major bugs in your code!
  • Different data types store distinct:
    • Information about the data
    • Amounts of data

Type Casting Danger: Different Information

  • The easiest example of casting gone wrong is trying to convert from a double to an int
  • Try running the following code (recall):
double x = 3.14;
IO.println(x);
IO.println((int)x);

Type Casting Danger: Different Amounts

  • You can also run into trouble when the data type you are casting from has less available space then the type you are casting to
  • For example int has 32 bits to work with where as short only has 16 bits
  • Thus, if you have a really big int it won’t all fit into a short and you will get data loss
  • We will talk about this more later but try this example now anyway:
int x = 2_147_483_647; // Max Int
IO.println(x);
IO.println((short)x);

Java Rules For Integer vs Floating Point Math

  • An operator’s operands (arguments) must have same type
  • The result will have the same type as the arguments
  • Some times Java can ensure this property implicitly
    • When 1 type can represent the other without loss
  • For all operators if either operand is a double then the result with be a double
  • Thus, when performing division if you want floating-point division cast 1 or both operands to double
  • If you want integer division then both arguments must have type int

Relational Operators

Java has all the standard relational operators:

Name Symbol
Equal ==
Not Equal !=
Less Than <
Greater Than >
Less Than Equal <=
Greater Than Equal >=

Boolean Operators

Java has all the standard boolean operators:

Name Symbol
And &&
Or ||
Not !

Python vs Java: Boolean Operators

  • Python capitalizes booleans (True and False) whereas Java does not (true and false)

Python

if True and False or not True:
    print("hello")

Java

if (true && false || !true) {
    IO.println("hello");
}

Combining Operators With Assignment

  • Every operator which has two operands has an assignment shortcut
  • For example:
// Variable declarations omitted
x += y  // x = x + y
x *= y  // x = x * y
x /= y  // x = x / y
x %= y  // x = x % y
q &&= p // q = q && p

Increment and Decrement

  • Incrementing and decrementing by 1 is so common that each received a special operator ++ and -- respectively
  • For example:
int x = 0;
x++; // x = x + 1
x--; // x = x - 1

Python vs Java: Randomness

  • Recall, that all randomness in computers is actually pseudo randomness
  • Meaning it really is just a sequence of numbers which appears random but if you know which number started the sequence you know the whole sequence
  • This first number is referred to as the seed
# Set seed to 123
random.seed(123)
# Generate a number between [1,10]
x = random.randint(1, 10)
# Print it
print(x)
// Create Random object and set seed to 123
Random random = new Random(123);
// Generate a number between [1,10]
int x = random.nextInt(1, 11);
// Print it
IO.println(x);