Using Loops, Arrays, Methods to do stuff in Java

Random numbers in Java

Let's write a simple game with the following rules:

Let's add another rule:

Another application: A simplsitic version of computer displays

How can we display images on computer displays?

How can we display images on computer displays?

Every cell in the grid is called a pixel

Pixel : Picture element

Pixel coordinates on a display

Changing coordinate origin to the center of the screen

Changing coordinate origin to the center of the screen

Let's emulate a computer display with the Java console

Our display will only have two "colors"

How do we draw a circle of radius R in our display?

x^2 + y^2 = R

How do we draw a circle of radius R in our display?

x^2 + y^2 = R


for y from 0 to H {
    for x from 0 to W {
        if (x,y) is part of the circle {
            print "*"
        }
        else {
            print " "
        }
        jump to the next line
    }
}

How do we draw a circle of radius R in our display?

x^2 + y^2 = R


Since our display is discrete we will have to be more forgiving

R - line_width ≤ x^2 + y^2 ≤ R + line_width

How do we draw a circle of radius R in our display?

R - line_width ≤ x^2 + y^2 ≤ R + line_width


for y from 0 to H {
    for x from 0 to W {
        if (x,y) is within line_width from the circle {
            print "*"
        }
        else {
            print " "
        }
        jump to the next line
    }
}

Drawing a circle centered at (a, b)

(x - a)^2 + (y - b)^2 = R

Drawing a circle centered at (a, b)

(x - a)^2 + (y - b)^2 = R

A computer's memory

Let's try swapping the values of variables

Let's try swapping the values of variables

Let's try swapping the values of variables

Let's try swapping the values of variables inside a method

Memory addresses

Passing primitive variables

When we pass primitive types as arguments to a method, we are passing copies of the arguments. So the value of the original variables cannot be changed inside a method

Passing array variables

Arrays are a reference type

Arrays are a reference type

Passing array variables (reference types )

When we pass reference types as arguments to a method, we are passing the memory address of the arguments. So the values of the original variables CAN be changed inside a method

Resources

/