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:
int x; // define a variable of type int in Java
Variables can be assigned values (multiple times):
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
int x;
x = 1 + 1; // assign to x the value of expression 1 + 1
Expressions
Literals: A constant value of a certain type
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
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 <methodname>(<parameters>) evaluates to the result returned by the method <methodname> for input <methodname>
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 <type> <name> 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 <return_type> <method_name> (<parameters>)
Inside the method body the keyword return is used to declare what value should be returned
intmult(int a, int b){ // declare method multreturn 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
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
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
x = 3; // invalid since x has not been declared yetint x;
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
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:
int x; // an int variable
Assignment:
x = 13; // assign 13 to x
Creating Object
objects are created with new operator like this:
new <class_name>(<parameters>)
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:
<class> <variable_name>
For example, to create a reference variable called x that stores references to objects that are instances of class String:
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
x == null
How References Work
Object x = null;
How References Work
Object x = new Object();
How References Work
Object x = new Object();
x = new Object();
Java Notebooks
We discuss the basic syntax and semantics in much more detail in the notebooks 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
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