Lecture 1 Next Lecture

Lecture 1, Mon 04/01

Introduction

Course Syllabus

Be sure to read the course syllabus for information on the logistics of this course.

https://ucsb-cs56.github.io/s19/info/syllabus/

Why use Java?

Hello World Program

// Lecture.java
public class HelloWorld {
    public static void main(String[] args) { // or String args[]
        System.out.println(“Hello World!”);
    }
}

Executing the program via the command line

$ javac Lecture.java
$ java Lecture
Hello World!
$

Note that the javac Lecture.java command will generate a Lecture.class file.

Compiling Java Code

Main Stepts of Executing a Java Program

  1. .java source code (the java code we write)
  2. javac converts .java source code into bytecode
  3. Execute bytecode on any device with the JVM installed

Some Java Basics

Comments

* Can comment blocks of code with `/* … */`
* Can comment single lines of code with `//`

Identifiers

Java Primitive Types

Note that primitive types in Java are stored on the stack.

Declaring Variables

Assignment Statements

Example:

float sum = 0.0;
int a = 1, b = 2, c = 3;
int x = 10;
double y = x;
y += 0.1; // y = y + 0.1
System.out.println(y);
x = y; // ERROR (if loss of precision occurs, Java won't compile)
x = (int) y; // type casting y into an int
System.out.println(x);

Objects

Example:

Object x = new Object();
Object y  = x; // y and x refer to the same Object
y = new Object(); // y refers to a new object
x = y; 	// x and y refer to the same object.

// Nothing points to the original object. Java’s 
// garbage collection automatically removes it from
// memory.
// Note: `==` compares object references, not values.

Overflow

Example:

int i = Integer.MAX_VALUE;
System.out.println(i); // 2147483647
System.out.println(i + 1); // -2147483648
System.out.println(Integer.MIN_VALUE); // -2147483648
// No compilation / runtime error. Programmer must check these cases

Increment / Decrement

Example:

int x = 1;
System.out.println(x++); // prints 1
System.out.println(x); // prints 2

x = 1;
System.out.println(++x); // prints 2
System.out.println(x); // prints 2

Shortcut Expressions

Similar to C++. Some Examples:

v1 += v2; // v1 = v1 + v2
v1 -= v2; // v1 = v1 – v2
v1 *= v2; // v1 = v1 * v2
v1 /= v2; // v1 = v1 / v2

Arithmetic Conversions

System.out.println(5 / 3); // 1
System.out.println(5.0 / 2); // 2.5

Typecasting

Example:

int x = 5;
int y = 2;
double answer = (double) x / y; // 2.5 even though two ints used