# CS116 - What is Java? **Lecturer**: [Boris Glavic](http://www.cs.iit.edu/~glavic/) **Semester**: Spring 2019
## Java * Imperative and Object-oriented * Stricly typed * Automatic memory management * garbage-collected * Compiled to byte-code for the Java Virtual Machine * **JVM**
# Imperative Programming
## Imperative Programming * In imperative programming we specify what operations to execute and in which order * Alternative forms of programming include **functional** and **logic programming** * Main imperative programming constructs: * **Variables** * **Expression** * **Methods** * **Control Structures**
## Variables * **Variables**: are used to store a **value** of a certain **type**, e.g., an integer variable * Variables have to be declared (exactly once) before they are used: ```java int x; // define a variable of type int in Java ``` * Variables can be assigned values (multiple times): ```java int x; x = 1; // assign the value 1 to x x = 2; // assign the value 2 to x ```
## Expressions * **Expression**: expressions consists of variables, **literals**, **operators**, and **method** calls. * An expression evaluates to a *result* that is determined based on the values of variables used in the expression and the return value of methods. * **Literals**: A constant value of a certain type, e.g., `1` is an integer literal * **Operators**: Take one or more values as input and return a value * **Method Calls**: Calling a piece of code that take zero or more values as input **parameters** and return zero or one values ```java int x; x = 1 + 1; // assign to x the value of expression 1 + 1 ```
## Expressions * **Literals**: A constant value of a certain type ```java int x; x = 15; // assign to x the literal 15 ```
## Expressions * **Operators**: Take one or more values of a **type** (the types of the inputs are not necessarily the same) as input and return a value (possible of a different type) * For instance, the operator `+` in Java may takes to integer values as input and returns their sum ```java int x; x = 1 + 1; // assign to x the value of expression 1 + 1 ```
## Expressions * **Method Call**: **Methods** are blocks of code that take zero or more values as input **parameters** and return zero or one values. A method call `
(
)` evaluates to the result returned by the method `
` for input `
` ```java int x; x = myMysteryMethod(); // assign to x the result of the method myMysteryMethod ```
## Methods * **Methods**: are blocks of code * **Input Parameters**: are a list of `
` pairs that defined what input values of which types should be passed to the method * **Return Type**: methods return values of a certain type. In Java methods that do not return a value have the special return type `void` * **Body**: the method body is code that is executed when the method is called. Within the method body the values passed to the method are available through their parameter names
## Method Example * In Java the syntax for defining a method is `
(
)` * Inside the method body the keyword `return` is used to declare what value should be returned ```java int mult(int a, int b) { // declare method mult return a * b; } int z = mult(5,3); // expression calling method mult with two integer literals as input ```
## User-defined types * Most languages allow the user to define new **types**. > **Example:** In the C language you can create `structs` which consists of multiple named elements ```c struct ComplexNumber { float realComponent; float irrealComponent; } ```
# Object-Oriented Programming
## Object-Oriented Programming * Object-oriented programming is a special form of imperative programming supporting a special category of **types** called **classes**. * Values of a class type are **objects** * **Terminology**: An object is an **instance** of a class * Specific to classes is that they define **data** as well as **functionality** * Compare with structs that only store data
## Anatomy of a Class * A class has **fields** that have a *type* and a *name* * A class has **methods** which implement functionality * Fields and methods can either be **instance** or **static** * **Instance** fields and methods exists for each instance of a class * **Static** fields and methods exist only once for a class independent of how many instances of the class have been created
## Inheritance * In object-oriented programming a class can be **inherited** from another class * If class `A` inherits from class `B` then * `A` is called the **superclass** * `B` is called the **subclass** * The subclass inherits all fields and methods from the superclass * this allows for code reuse
## Inheritance Example ```java class Employee { String name; int salary; String getName() { return name; } } class Programmer extends Employee { String language = "Java"; String getLanguage() { return language; } } ```
## Encapsulation and Information Hiding * Object-oriented programming *"philosophy"* dictates the use of information hiding * By **information hiding** we mean that a class exposes an *interface* through its methods through which we interact with instances of the class. However, the fields and implementation details of the methods are hidden from us.
## Encapsulation and Information Hiding * **Advantages**: * We can change the implementation of the class (as long as this doesn't change the semantics of its interface) without having to change all the pieces of code that use the class * **Disadvantages**: * This can lead to boilerplate code (using IDEs or good editors this is not really a problem)
## Getter and Setter Methods * To implement information hiding in Java it is idiomatic use **Getter** and **Setter** methods to allow clients of the class to access data. The convention is that the getter for a field `myfield` is called `getMyfield` and the setter for `myfield` is called `setMyfield`
## Getter and Setter Examples ```java class Person { int salary; int getSalary() { return salary; } void setSalary(int salary) { this.salary = salary; } } ```
# Syntax and Semantics
## Syntax * The syntax of a language defines what are valid strings (sequences of symbols) in the language * If a program confirms with the syntax of a language then we call it syntactially correct
## Semantics * The semantics of the language defines its meaning * e.g., according to the semantics of Java `1 + 1` evaluates to `2`
## Scope * Languages restrict the validaty of constructs in a program to parts of the a program. * We will discuss Java scopping rules later on, but here is one example * A variable is only valid in the part of the program after its declaration ```java x = 3; // invalid since x has not been declared yet int x; ``` ```java int x; x = 3; // that is ok! ```
# Strictly Typed
## Strict Typing * Java is a strictly typed language which means that in all contexts only expression of an appropriate type can be used. For instance: * Variables are assigned a type at declaration only expressions of this type can be assigned to the variable * As a strictly typed language, Java enforces type safety at compile and runtime ```java int x; x = "Hello world!" // compile time error - "Hello world!" is a String ```
# Java Syntax and Semantics 101
## Statements and Code blocks * In Java, **statements** are always ended with `;` * Sequences of statements can be grouped together into **code blocks** which are enclosed in `{}`
## Java Types * Java distinguishes between two categories of types: * **Primitive types** * e.g., an `int` or `boolean` * **Classes** * e.g., `String`
## Variables * **Declaration**: ```java int x; // an int variable ``` * **Assignment**: ```java x = 13; // assign 13 to x ```
## Creating Object * objects are created with `new` operator like this: > `new
(
)` ```java new Object() // create an object of class "Object" ``` * `new` returns a **reference** to the newly created object that we can use to manipulate it
## Reference Variables * In Java there are no variables of object types. All variables are reference types, i.e., they store a reference to an object, but not the object itself * A reference variable is declared like this: ```java
``` * For example, to create a reference variable called `x` that stores references to objects that are instances of class `String`: ```java String x; ```
## Null * Java has a special **literal** reference value `null` that means that a reference is currently not pointing to any object * We can assign `null` to reference variables and check whether a value is `null` using equality like so ```java x == null ```
## How References Work ```java Object x = null; ```
%3
x
x
null
null
x->null
## How References Work ```java Object x = new Object(); ```
%3
x
x
O1
Object 1
x->O1
## How References Work ```java Object x = new Object(); x = new Object(); ```
%3
x
x
O2
Object 2
x->O2
O1
Object 1
## Java Notebooks * We discuss the basic syntax and semantics in much more detail in the [notebooks](/~glavic/cs116/lectures.html) for the first part of the class.
# Heap and Stack
## The heap and stack * Objects are allocted in a memory area called the **heap** * When a **method** is called, then temporary memory for the execution of this method is allocated on the **stack**
## Controlflow and the Call Stack * Execution in Java proceeds top-down ```java x = 3; // first statement to be executed x = 5; // second statement to be executed ... ```
## What happens if a method is called? * When a method is called the following happens: * A new **stack frame** for the method is created and is put on top of the **call stack** * Within the stack frame memory is allocated for the parameters and local variables of the method * Parameters are set to the values produced as input to the method call * The control is handed over to the method and the code in the method body is executed
## The Call Stack * The **Call Stack** is a data structure that keeps track of what methods are currently running and their call hierarchy * Whenever a method is called it is put on the stack * Whenever a method returns it is removed from the call stack
## When a method finishes execution * When a method finishes execution than the following happens: * The call frame for the method is deallocated * The return value (if any) is passed on to the caller of the method and execution continues at the place where the method was called
## Caveat * A typical misunderstanding is that parameters and local variables of a method exist once. However, this is **not** the case. Each invocation of a method creates new copies of these variables and parameters that are independ of the parameters and variables of other active invocations of the method
# Garbage Collection
## Objects that are no longer referenced * In the previous example `Object 1` is no longer referenced by any variable * There is no way for our program to ever again get a reference to this object! * This object still occupies memory * Java uses automatic memory management * We cannot destroy objects * How to avoid filling up our memory with useless objects over time?
## Garbage Collection * Java implements a concept called **garbage collection** to deal with this problem * The Java VM garbage collector detects unreachable objects and deletes them
## Garbage Collection * **Advantages** * We do not have to clean-up ourselves * We cannot accidentally reference an object that no longer exists * **Disadvatanges** * We may run out of memory if references to unused objects are not cleaned up * Garbage collection is costly and we have very limited control
# The Java Virtual Machine
## The Java Virtual Machine * Unlike languages like `C` of `C++`, Java is source code is not compiled into platform-specific machine code, but into **byte-code** (instructions) for a Java Virtual Machine (JVM) * To execute compiled Java code, you need an implementation of the JVM that simulates the execution of Java byte-code on top of your hardware
## Other JVM Languages * Java is not the only language that can be compiled into JVM byte-code * Some other languages that can be run on the JVM are: * **Scala** - an object-oriented and functional language (famous for its use in Spark) * **Clojure** - a Lisp dialect * **Jython** - an implementation of Python on top of the JVM * A comprehensive list of JVM languages: [Wikipedia](https://en.wikipedia.org/wiki/List_of_JVM_languages)
## Summary * Imperative Programming * Object-oriented Programming * Syntax and Semantics * Imperative Constructs * Variables, Expressions, Methods, Control Constructs * Java 101 * A bit of syntax and semantics * JVM, garbage collections