0% found this document useful (0 votes)
6 views96 pages

Java Revision Slides (1)

The document outlines a comprehensive curriculum for a programming course using Java, covering topics such as programming concepts, memory management, object-oriented programming, and Java syntax. It includes weekly breakdowns of lessons, focusing on both theoretical concepts and practical implementations. Key areas of study include types, classes, control flow, and the philosophy of object-oriented programming.

Uploaded by

Sandeep
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views96 pages

Java Revision Slides (1)

The document outlines a comprehensive curriculum for a programming course using Java, covering topics such as programming concepts, memory management, object-oriented programming, and Java syntax. It includes weekly breakdowns of lessons, focusing on both theoretical concepts and practical implementations. Key areas of study include types, classes, control flow, and the philosophy of object-oriented programming.

Uploaded by

Sandeep
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 96

Revision Slides

Week 1

Week 2

Week 3

Week 4 Programming Concepts Using Java


Week 5
Revision Slides
Week 6

Week 7

Week 8

Week 9

Week 10

Week 11

Week 12
W01:L01: Introduction

Revision Slides

Explore concepts in programming languages


Week 1
Object-oriented programming
Week 2 Exception handling, concurrency, event-driven programming, . . .
Week 3
Use Java as the illustrative language
Week 4
Imperative, object-oriented
Week 5

Week 6 Incorporates almost all features of interest


Week 7 Discuss design decisions where relevant
Week 8
Every language makes some compromises
Week 9

Week 10
Understand and appreciate why there is a zoo of programming languages out there
Week 11 . . . and why new ones are still being created
Week 12
W01:L02: Types

Revision Slides

Types have many uses


Week 1 Making sense of arbitrary bit sequences in memory
Week 2
Organizing concepts in our code in a meaningful way
Week 3

Week 4
Helping compilers catch bugs early, optimize compiled code
Week 5
Some languages also support automatic type inference
Week 6

Week 7 Deduce the types of a variable statically, based on the context in which they are used
Week 8 x = 7 followed by y = x + 15 implies y must be int
Week 9

Week 10
If the inferred type is consistent across the program, all is well
Week 11

Week 12
W01:L03: Memory Management

Revision Slides Variables have scope and lifetime


Scope — whether the variable is available in the program
Week 1 Lifetime — whether the storage is still allocated
Week 2

Week 3 Activation records for functions are maintained as a stack


Week 4
Control link points to previous activation record
Week 5

Week 6
Return value link tells where to store result
Week 7
Two ways to initialize parameters
Week 8
Call by value
Week 9

Week 10 Call by reference


Week 11

Week 12
Heap is used to store dynamically allocated data
Outlives activation record of function that created the storage
Need to be careful about deallocating heap storage
Explicit deallocation vs automatic garbage collection
W01:L04: Abstraction and Modularity

Revision Slides

Solving a complex task requires breaking it down into manageable components


Week 1 Top down: refine the task into subtasks
Week 2
Bottom up: combine simple building blocks
Week 3

Week 4 Modular description of components


Week 5
Interface and specification
Week 6

Week 7 Build prototype implementation to validate design


Week 8 Reimplement the components independently, preserving interface and specification
Week 9

Week 10 PL support for abstraction


Week 11
Control flow: functions and procedures
Week 12
Data: Abstract data types, object-oriented programming
W01:L05: OOPS

Revision Slides

Objects are like abstract datatypes


Week 1
Uniform way of encapsulating different combinations of data and functionality
Week 2

Week 3 Distinguishing features of object-oriented programming


Week 4
Abstraction
Week 5

Week 6
Public interface, private implementation, like ADTs
Week 7 Subtyping
Week 8
Hierarchy of types, compatibility of interfaces
Week 9
Dynamic lookup
Week 10

Week 11 Choice of method implementation is determined at run-time


Week 12 Inheritance
Reuse of implementations
W01:L06: Classes

Revision Slides

A class is a template describing the instance variables and methods for an abstract
Week 1
datatype
Week 2
An object is a concrete instance of a class
Week 3

Week 4 We should separate the public interface from the private implementation
Week 5

Week 6 Hierarchy of classes to implement subtyping and inheritance


Week 7

Week 8
A language like Python has no mechanism to enforce privacy etc
Week 9 Can illegally manipulate private instance variables
Week 10
Can introduce inconsistencies between subtype and parent type
Week 11

Week 12
Use strong declarations to enforce privacy, types
Do not rely on programmer discipline
Catch bugs early through type checking
Getting started with Java

Revision Slides

Java program to print hello, world


Week 1 public class HelloWorld{
Week 2 public static void main(String[] args) {
Week 3 System.out.println("hello, world);
Week 4
}
Week 5
}
Week 6

Week 7
A Java program is a collection of classes
Week 8 All code in Java lives within a class
Week 9
Modifier public specifies visibility
Week 10

Week 11
The signature of main( )
Week 12 Input parameter is an array of strings; command line arguments
No output, so return type is void
Write once, run anywhere
Scalar types

Revision Slides

Java has eight primitive scalar types


Week 1
int, long, short, byte
Week 2
float, double
Week 3
char
Week 4
boolean
Week 5 We declare variables before we use them
Week 6
int x, y;
Week 7
x = 5;
Week 8
y = 10;
Week 9

Week 10 Characters are written with single-quotes (only)


Week 11 char c = ‘x’;
Week 12
Boolean constants are true, false
boolean b1, b2;
b1 = false;
b2 = true;
Scalar types

Revision Slides

Initialize at time of declaration


Week 1 flat pi = 3.1415927f;
Week 2
Modifier final indicates a constant
Week 3

Week 4
final float pi = 3.1415927f;
Week 5

Week 6

Week 7

Week 8

Week 9

Week 10

Week 11

Week 12
Operators

Revision Slides

Arithmetic operators are the usual ones


Week 1 +, -, *, /, %
Week 2
No separate integer division operator //
Week 3

Week 4
When both arguments are integer, / is integer division
Week 5 No exponentiation operater, use Math.pow()
Week 6
Math.pow(a,n) returns an
Week 7

Week 8 Special operators for incrementing and decrementing integers


Week 9 int a = 0, b = 10;
Week 10
a++; // Same as a = a+1
Week 11
b--; // Same as b = b-1
Week 12
Shortcut for updating a variable
int a = 0, b = 10;
a += 7; // Same as a = a+7
Strings

Revision Slides

String is a built-in class


Week 1 String constants enclosed in double quotes
Week 2
String s = "Hello", t = "world";
Week 3

Week 4
+ is overloaded for string concatenation
Week 5 String s = "Hello";
Week 6 String t = "world";
Week 7
String u = s + " " + t;
Week 8
// "Hello world"
Week 9

Week 10
Strings are not arrays of characters
Week 11 Instead use s.charAt(0), s.substring(0,3)
Week 12
Arrays

Revision Slides

Arrays are also objects


Week 1 Typical declaration
Week 2
int[] a;
Week 3
a = new int[100];
Week 4

Week 5 Or int a[] instead of int[] a


Week 6 a.length gives size of a
Week 7

Week 8
Array indices run from 0 to a.length-1
Week 9

Week 10

Week 11

Week 12
Control flow

Revision Slides

Conditional execution
Week 1 if (condition) { ... } else { ... }
Week 2
Conditional loops
Week 3

Week 4
while (condition) { ... }
Week 5 do { ... } while (condition)
Week 6
Iteration - Two kinds of for
Week 7

Week 8 Multiway branching – switch


Week 9

Week 10

Week 11

Week 12
Classes and objects

Revision Slides

A class is a template for an encapsulated type


Week 1 An object is an instance of a class
Week 2
public class Date {
Week 3
private int day, month, year;
Week 4
public Date(int d, int m, int y){
Week 5

Week 6
day = d;
Week 7
month = m;
Week 8 year = y;
Week 9 }
Week 10 public int getDay(){
Week 11 return(day);
Week 12 }
}
Instance variables - Each concrete object of type Date will have local copies of date,
month, year
Creating and initializing objects

Revision Slides

new creates a new object


Week 1 How do we set the instance variables?
Week 2 Constructors — special functions called when an object is created
Week 3
Function with the same name as the class
Week 4
d = new Date(13,8,2015);
Week 5

Week 6 Constructor overloading - same name, different signatures


Week 7 A constructor can call another one using this
Week 8
If no constructor is defined, Java provides a default constructor with empty arguments
Week 9

Week 10
new Date() would implicitly invoke this
Week 11
Sets instance variables to sensible defaults
Week 12
For instance, int variables set to 0
Only valid if no constructor is defined
Otherwise need an explicit constructor without arguments
Copy constructors

Revision Slides

Create a new object from an existing one


Week 1
public class Date {
Week 2 private int day, month, year;
Week 3 public Date(int d, int m, int y){
Week 4 day = d; month = m; year = y;
Week 5 }
Week 6
public Date(Date d){
Week 7
this.day = d.day; this.month = d.month; this.year = d.year;
Week 8
}
Week 9

Week 10
}
Week 11
public class UseDate() {
Week 12 public static void main(String[] args){
Date d1,d2;
d1 = new Date(12,4,1954); d2 = new.Date(d1);
}
}
Basic input and output in java

Revision Slides

Reading input
Week 1
Use Console class
Week 2
Use Scanner class
Week 3 Scanner in = new Scanner(System.in);
Week 4 String name = in.nextLine();
Week 5
int age = in.nextInt();
Week 6

Week 7

Week 8

Week 9

Week 10

Week 11

Week 12
W03:L01: The philosophy of OO programming

Revision Slides

Structured programming
The algorithms come first
Week 1
Design a set of procedures for specific tasks
Week 2
Combine them to build complex systems
Week 3
Data representation comes later
Week 4
Design data structures to suit procedural manipulations
Week 5

Week 6 Object Oriented design


Week 7 First identify the data we want to maintain and manipulate
Week 8 Then identify algorithms to operate on the data
Week 9
Designing objects
Week 10
Behaviour – what methods do we need to operate on objects?
Week 11
State – how does the object react when methods are invoked?
Week 12
State is the information in the instance variables
Encapsulation – should not change unless a method operates on it
W03:L01: The philosophy of OO programming (Cont.)

Revision Slides

Relationship between classes


Dependence
Week 1
Order needs Account to check credit status
Week 2
Item does not depend on Account
Week 3
Robust design minimizes dependencies, or coupling between classes
Week 4
Aggregation
Week 5
Order contains Item objects
Week 6
Inheritance
Week 7
One object is a specialized versions of another
Week 8
ExpressOrder inherits from Order
Week 9
Extra methods to compute shipping charges, priority handling
Week 10

Week 11

Week 12
W03:L02: Subclasses and inheritance

Revision Slides
public class Employee{
A subclass extends a parent class private String name;
private double salary;
Week 1
Subclass inherits instance variables and
Week 2
methods from the parent class // Some Constructors ...

Week 3 Subclass can add more instance variables // "mutator" methods


Week 4 and methods public boolean setName(String s){ ... }
public boolean setSalary(double x){ ... }
Week 5 Can also override methods
Week 6 // "accessor" methods
Week 7
Subclasses cannot see private public String getName(){ ... }
Week 8
components of parent class public double getSalary(){ ... }

Week 9 Use super to access constructor of // other methods


public double bonus(float percent){
Week 10 parent class return (percent/100.0)*salary;
Week 11 }
Week 12
Manager objects inherit other fields and }
methods from Employee public class Manager extends Employee{
private String secretary;
Every Manager has a name, salary and public boolean setSecretary(name s){ ... }
methods to access and manipulate these. public String getSecretary(){ ... }
}
W03:L03: Dynamic dispatch and polymorphism

Revision Slides
public class Employee{
private String name;
private double salary;
Week 1
Manager can redefine bonus()
double bonus(float percent){ // Some Constructors ...
Week 2

Week 3 return 1.5*super.bonus(percent); // "mutator" methods


Week 4 } public boolean setName(String s){ ... }
public boolean setSalary(double x){ ... }
Week 5
Uses parent class bonus() via super
Week 6 // "accessor" methods
Week 7
Overrides definition in parent class public String getName(){ ... }
public double getSalary(){ ... }
Week 8 Consider the following assignment
Week 9 // other methods
Employee e = new Manager(...) public double bonus(float percent){
Week 10

Week 11
Can we invoke e.setSecretary()? return (percent/100.0)*salary;
}
Week 12 e is declared to be an Employee }
Static typechecking – e can only refer public class Manager extends Employee{
private String secretary;
to methods in Employee public boolean setSecretary(name s){ ... }
public String getSecretary(){ ... }
}
W03:L03: Dynamic dispatch and polymorphism (Cont.)

Revision Slides
What about e.bonus(p)? Which bonus() public class Employee{
private String name;
do we use? private double salary;
Week 1 Static: Use Employee.bonus()
// Some Constructors ...
Week 2 Dynamic: Use Manager.bonus()
Week 3 // "mutator" methods
Week 4
Dynamic dispatch (dynamic binding, public boolean setName(String s){ ... }
Week 5
late method binding, . . . ) turns out to public boolean setSalary(double x){ ... }

Week 6
be more useful // "accessor" methods
Week 7 Polymorphism public String getName(){ ... }
public double getSalary(){ ... }
Week 8
Every Employee in emparray ”knows”
Week 9
how to calculate its bonus correctly! // other methods
Week 10
public double bonus(float percent){
Employee[] emparray = new Employee[2]; return (percent/100.0)*salary;
Week 11 Employee e = new Employee(...); }
Week 12 Manager e = new Manager(...); }
emparray[0] = e; public class Manager extends Employee{
emparray[1] = m; private String secretary;
for (i = 0; i < emparray.length; i++){ public boolean setSecretary(name s){ ... }
System.out.println(emparray[i].bonus(5.0); public String getSecretary(){ ... }
} }
W03:L03: Dynamic dispatch and polymorphism (Cont.)

Revision Slides
Signature of a function is its name and double[] darr = new double[100];
the list of argument types int[] iarr = new int[500];
...
Week 1
Overloading: multiple methods, different Arrays.sort(darr);
Week 2 // sorts contents of darr
signatures, choice is static Arrays.sort(iarr);
Week 3
// sorts contents of iarr
Week 4 Overriding: multiple methods, same class Arrays{
Week 5 signature, choice is static ...
public static void sort(double[] a){..}
Week 6 Employee.bonus() // sorts arrays of double[]
Week 7 Manager.bonus() public static void sort(int[] a){..}
Week 8 // sorts arrays of int[]
Dynamic dispatch: multiple methods, ...
Week 9
same signature, choice made at run-time }
Week 10

Week 11

Week 12
W03:L03: Dynamic dispatch and polymorphism (Cont.)

Revision Slides
public class Employee{
Type casting private String name;
private double salary;
Week 1 Consider the following assignment
// Some Constructors ...
Week 2
Employee e = new Manager(...)
Week 3 // "mutator" methods
Week 4
e.setSecretary() does not work public boolean setName(String s){ ... }
Week 5
Static type-checking disallows this public boolean setSalary(double x){ ... }

Week 6 Type casting — convert e to Manager // "accessor" methods


Week 7 public String getName(){ ... }
((Manager) e).setSecretary(s) public double getSalary(){ ... }
Week 8

Week 9 Cast fails (error at run time) if e is not a // other methods


Week 10 Manager public double bonus(float percent){
return (percent/100.0)*salary;
Week 11
Can test if e is a Manager }
Week 12 }
if (e instanceof Manager){ public class Manager extends Employee{
private String secretary;
((Manager) e).setSecretary(s); public boolean setSecretary(name s){ ... }
} public String getSecretary(){ ... }
}
W03:L04: The Java class hierarchy

Revision Slides

Java does not allow multiple inheritance


Week 1
A subclass can extend only one parent class
Week 2 The Java class hierarchy forms a tree
Week 3
The root of the hierarchy is a built-in class called Object
Week 4
Object defines default functions like equals() and toString()
Week 5
These are implicitly inherited by any class that we write
Week 6

Week 7 When we override functions, we should be careful to check the signature


Week 8
Useful methods defined in Object
Week 9

Week 10
public boolean equals(Object o) // defaults to pointer equality
Week 11
public String toString() // converts the values of the
Week 12 // instance variables to String
For Java objects x and y, x == y invokes x.equals(y)
To print o, use System.out.println(o+””);
Implicitly invokes o.toString()
W03:L05: Subtyping vs inheritance

Revision Slides

Class hierarchy provides both subtyping and inheritance


Week 1 Subtyping
Week 2 Capabilities of the subtype are a superset of the main type
Week 3 If B is a subtype of A, wherever we require an object of type A, we can use an object of
Week 4 type B
Week 5 Employee e = new Manager(...); is legal
Week 6 Compatibility of interfaces
Week 7
Inheritance
Week 8
Subtype can reuse code of the main type
Week 9
B inherits from A if some functions for B are written in terms of functions of A
Week 10
Manager.bonus() uses Employee.bonus()
Week 11
Reuse of implementations
Week 12

Using one idea (hierarchy of classes) to implement both concepts blurs the distinction
between the two
W03:L06: Java modifiers

Revision Slides

private and public are natural artefacts of encapsulation


Week 1
Usually, instance variables are private and methods are public
Week 2
However, private methods also make sense
Week 3 Modifiers static and final are orthogonal to public/private
Week 4
Use private static instance variables to maintain bookkeeping information across
Week 5
objects in a class
Week 6
Global serial number, count number of objects created, profile method invocations, . . .
Week 7

Week 8 Usually final is used with instance variables to denote constants


Week 9
A final method cannot be overridden by a subclass
Week 10

Week 11
A final class cannot be inherited
Week 12 Can also have private classes
Abstract classes

Revision Slides

Sometimes we collect together classes under a common heading


Week 1 Classes Swiggy, Zomato and UberEat are all food order
Week 2
Create a class FoodOrder so that Swiggy, Zomato and UberEat extend FoodOrder
Week 3

Week 4
We want to force every FoodOrder class to define a function
Week 5 public void order() {}
Week 6
Now we should force every class to define the public void order();
Week 7

Week 8 Provide an abstract definition in FoodOrder


Week 9 public abstract void order();
Week 10

Week 11

Week 12
Interfaces

Revision Slides

An interface is a purely abstract class


Week 1 All methods are abstract by default
Week 2
All data members are final by default
Week 3

Week 4
If any class implement an interface, it should provide concrete code for each abstract
Week 5 method
Week 6 Classes can implement multiple interfaces
Week 7

Week 8
Java interfaces extended to allow static and default methods from JDK 1.8 onwards
Week 9 If two interfaces has same default/static methods then its implemented class must
Week 10 provide a fresh implementation
Week 11
If any class wants to extend another class and an interface then it should inherit the
Week 12
class and implements interface
private classes

Revision Slides

An instance variable can be a user defined type


Week 1 public class BookMyshow{
Week 2 String user;
Week 3 int tickets;
Week 4
Payment payement;
Week 5
}
Week 6
public class Payment{
Week 7

Week 8
int cardno;
Week 9
int cvv;
Week 10
}
Week 11 Payment is a public class, also available to other classes
Week 12
Payment class has sensitive information, so there is a security concern.
private classes

Revision Slides

We cannot declare Payment class as private outside the BookMyshow class


Week 1 You can declare Payment class as private inside the BookMyshow class
Week 2
public class BookMyshow{
Week 3
String user;
Week 4
int tickets;
Week 5

Week 6
Payment payement;
Week 7
private class Payment{
Week 8 int cardno;
Week 9 int cvv;
Week 10 }
Week 11 }
Week 12
Now Payment class is a private member of the BookMyshow class
Now Payment class only available to the BookMyshow class
Interaction with State(Manipulating objects)

Revision Slides

Consider the class student below.


Week 1 Student class is encapsulated by private variables.
Week 2
public class Student{
Week 3
private String rollno;
Week 4
private String name;
Week 5

Week 6
private int age;
Week 7
//3 mutator methods
Week 8 //3 Accessor methods
Week 9 }
Week 10
Consider Student class has student1,student2.....student60 objects
Week 11

Week 12
Update date as a whole, rather than individual components
Interaction with State(Manipulating objects)

Revision Slides

public class Student{


Week 1
private String rollno;
Week 2
private String name;
Week 3 private int age;
Week 4 public void setStudent(String rollno,String name,int age){
Week 5 }
Week 6 }
Week 7

Week 8
Now public void setStudent(String rollno, String name, int age) update the Student
Week 9
object as a whole.
Week 10

Week 11

Week 12
Java Call back methods.

Revision Slides

what is call back method?


Week 1
interface Notification{
Week 2 void notification();//should be overridden in WorkingDay and Weekend
Week 3 }
Week 4 class WorkingDay implements Notification{
Week 5 }
Week 6
class Weekend implements Notification{
Week 7
}
Week 8
class Timer{//Timer will decide which call back function should be call
Week 9

Week 10
}
Week 11
public class User {
Week 12 public static void main(String[] args) {
Timer timer=new Timer();
timer.start(new Date());
}
}
Iterators

Revision Slides

what is Iterator?
Week 1 You can loop through any data structure using an Iterator.
Week 2
public interface Iterator{
Week 3
public abstract boolean has_next();
Week 4
public abstract Object get_next();
Week 5

Week 6
}
Week 7

Week 8

Week 9

Week 10

Week 11

Week 12
W5:L1: Polymorphism Revisited

Revision Slides
In object-oriented programming, polymorphism usually refers to the effect of dynamic dispatch
Depending upon the object type stored in a reference variable appropriate version of overridden and
Week 1
non-overridden methods are invoked automatically.
Week 2

Week 3 Structural Polymorphism


Week 4 public int find(Superclass[] arr, subclass o){
Week 5 int i;
Week 6 for(i =0 ;i < arr.length; i++){
Week 7 if(arr[i].equals(o)) return i;
Week 8
}
Week 9
return -1;
Week 10
}
Week 11 Can also be obtained by using interfaces, this is what we have been doing with
Week 12
Comparable<T> interface
We are actually grouping types with one common behaviour under a parent type (class/interface)
which can then polymorphically refer to appropriate subtypes depending upon actual instance type.
W5:L1: Polymorphism Revisited (Cont.)

Revision Slides
Type Consistency:
Source type can be either same as target type or a subtype of target type. In other words a super
type reference variable/array can store subtype objects but not vice versa.
Week 1

Week 2
Inference:
Inheritance/polymorphism cannot guarantee a complete type generalization of our program.
Week 3

Week 4 Using Object to generalize types in a program


Week 5 Problems:
Week 6 Type information is lost needs explicit casting on every use.
Week 7 Homogeneity cannot be guaranteed.
Week 8
Solution: Generics
Week 9

Week 10 Classes and functions can have type parameters


Week 11 1. class MyDataStructure<T> holds values of type T
Week 12 2. public T getMatch(T obj) accepts and returns values of same type T as
enclosing enclosing class
Can also use constraints by mixing inheritance rules.
public static <S extends T,T> void getMatch(S[] sarr, T obj){...}
W5:L2: Generics

Revision Slides
Example of a polymorphic List
public class LinkedList<T>{
Week 1
private int size;
Week 2

Week 3
private Node first;
Week 4
public T head(){
Week 5 T returnval;
Week 6 ...
Week 7 return(returnval);
Week 8 }
Week 9 public void insert(T newdata){...}
Week 10
private class Node {
Week 11
private T data;
Week 12
private Node next;
...
}
}
W5:L2: Generics (Cont.)

Revision Slides

Be careful not to accidentally hide a type variable


Week 1 class Myclass<S>{
Week 2 public <S,T> void myMethod(S obj){
Week 3 T obj2;
Week 4
...
Week 5
}
Week 6
}
Week 7

Week 8 Quantifier <S,T> of myMethod masks the type parameter S of class MyClass.
Week 9

Week 10

Week 11

Week 12
W5:L3: Generic Subtyping

Revision Slides Covariance of types:


If S is a subtype of T and a reference of T can store an object of S, then T[] can also refer S[].
Arrays are covariant:
Week 1 Integer[] arr1 = {10,20,30};
Week 2 Number[] arr2 = arr1;
Week 3
System.out.println(arr2[2]); // 30
Week 4 Now, try running this:
Week 5
arr2[1] = 9.8; // It’s not allowed, generates exception.
Week 6 The detailed type checking is only done only at runtime, compiler will check for supertype-subtype
Week 7
relation and if that conforms, it will allow the code.
Why the statement is executing at runtime?
Week 8

Week 9 Issue with generics:


Week 10
JVM erases the type information related to a generic type after the compilation is done, i.e. at
runtime unlike non-generic type variables/references, generic variables will not have any type
Week 11
characteristics. This process is called type erasure.
Week 12
Which means all type checking must be done by compiler, but as compiler cannot check object’s type
during compile time, so JAVA prohibits the covariance property for generic types.
List<Subtype> is not compatible with List<Supertype>
List<String> s = {"A","B"};
List<Object> o = s; Illegal use
W5:L3: Wildcard

Revision Slides We can solve this problem using wildcards <?>.


Avoid unnecessary type quantification when type variable is not needed elsewhere.
Week 1 1
Beneficial while comparing two different subtypes of a common supertype.
Week 2

Week 3 Bounded Wildcards


Week 4 LinkedList<? extends T>
Week 5 LinkedList<? super T>
Week 6

Week 7

Week 8

Week 9

Week 10

Week 11

Week 12

1 will discuss the program.


W05:L04:Reflection

Revision Slides

Week 1 Reflective programming or reflection is the ability of a process to examine, introspect, and
Week 2
modify its own structure and behaviour. (Source: Wikipedia)
Week 3

Week 4 Introspect: A program can observe, and therefore reason about its own state.
Week 5

Week 6 Intercede: A program can modify its execution state or alter its own interpretation or
Week 7 meaning.
Week 8

Week 9

Week 10

Week 11

Week 12
Reflection in Java

Revision Slides

Employee e = new Manager(...);


Week 1 ...
Week 2 if (e instanceof Manager){
Week 3
...
Week 4
}
Week 5

Week 6
What if we don’t know the type that we want to check in advance?
Week 7

Week 8 Suppose we want to write a function to check if two different objects are both
Week 9 instances of the same class?
Week 10

Week 11

Week 12
Reflection in Java . . .

Revision Slides

public static boolean classequal(Object o1, Object o2){


Week 1 ...
Week 2 // return true iff o1 and o2 point to objects of same type
Week 3
...
Week 4
}
Week 5

Week 6
We cannot use instanceof because we will have to check across all defined classes,
Week 7

Week 8
which is not a fixed set.
Week 9 We cannot use generic type variables becaue if (o1 instance of T) is not
Week 10 permitted.
Week 11

Week 12
Introspection in Java

Revision Slides

Week 1 Can extract the class of an object using getClass()


Week 2
getClass() returns an object of type Class that encodes class information
Week 3

Week 4 import java.lang.reflect.*;


Week 5 class MyReflectionClass{
Week 6
public static boolean classequal(Object o1, Object o2){
Week 7
Class c1, c2;
Week 8
c1 = o1.getClass();
Week 9

Week 10
c2 = o2.getClass();
Week 11
return (c1 == c2);
Week 12 }
}
Using the Class object

Revision Slides

Week 1
Can create new instances of a class at runtime
Week 2

Week 3
Class c = obj.getClass();
Week 4
Object o = c.newInstance();
Week 5 // Create a new object of same type as obj
Week 6
Can also get hold of the class object using the name of the class
Week 7

Week 8
String s = "Manager".
Week 9
Class c = Class.forName(s);
Week 10 Object o = c.newInstance();
Week 11 . . . , or, more compactly
Week 12
Object o = Class.forName("Manager").newInstance();
The class Class . . .

Revision Slides

Week 1
From the Class object for class C, we can extract details about constructors,
Week 2
methods and fields of C
Week 3

Week 4
Constructors, methods and fields themselves have structure
Week 5

Week 6
Constructors: arguments
Week 7 Methods : arguments and return type
Week 8
All three: modifiers static, private etc
Week 9

Week 10
Additional classes Constructor, Method, Field
Week 11

Week 12 Use getConstructors(), getMethods() and getFields() to obtain


constructors, methods and fields of C in an array.
The class Class . . .

Revision Slides

Extracting information about constructors, methods and fields


Week 1

Week 2
Class c = obj.getClass();
Week 3
Constructor[] constructors = c.getConstructors();
Week 4 Method[] methods = c.getMethods();
Week 5 Field[] fields = c.getFields();
Week 6
Constructor, Method, Field in turn have functions to get further details
Week 7

Week 8
Example: Get the list of parameters for each constructor
Week 9 Class c = obj.getClass();
Week 10 Constructor[] constructors = c.getConstructors();
Week 11
for (int i = 0; i < constructors.length; i++){
Week 12
Class params[] = constructors[i].getParameterTypes();

}
Reflection and security

Revision Slides

Week 1

Week 2 Can we extract information about private methods, fields,. . . ?


Week 3

Week 4
For private methods, fields:
Week 5 Constructor[] constructors = getDeclaredConstructors();
Week 6 Method[] methods = getDeclaredMethods();
Week 7 Field[] fields = getDeclaredFields();
Week 8

Week 9 Security issue : Access to private components may be restricted through external
Week 10 security policies
Week 11
To be used sparingly
Week 12
W5:L5: Type Erasure

Revision Slides

Java does not keep type information of generics at runtime, all type compatibilities are
checked during compile time.
Week 1
if(s instanceof ArrayList<String>) // Compilation error
Week 2

Week 3 At run time, all type variables are promoted to Object


Week 4 ArrayList<T> becomes ArrayList<Object>
Week 5
Or the upper bound,if available
Week 6
ArrayList<T extends Mammals> becomes ArrayList<Mammals>
Week 7

Week 8
Type erasure leads to illegal overloading which were legal on non generics.
Week 9
public void myMethod(ArrayList<Integer> i)...
Week 10
public void myMethod(ArrayList<Mammal> m)...
Week 11 To avoid runtime errors generic type arrays can be declared but can’t be instantiated.
Week 12 T[] arr;
arr = new T[20]; // Compiler error
W06:L01: Indirection

Revision Slides

Suppose two separate implementation


Week 1
public class CircularArrayQueue<E> {
Week 2
public void add (E element){...};
Week 3

Week 4
public E remove(){...};
Week 5
public int size(){...};
Week 6 ...
Week 7 }
Week 8

Week 9 public class LinkedListQueue<E> {


Week 10 public void add (E element){...};
Week 11
public E remove(){...};
Week 12
public int size(){...};
...
}
W06:L02: Java-Collections

Revision Slides
Collections Framework?
collection of interfaces and classes.
Week 1 organizing a group of heterogeneous objects efficiently.
Week 2 Framework has several useful classes which have tons of useful methods which makes a
Week 3 programmer task super easy.
Week 4 Some collections allow duplicate elements, while others do not.
Week 5 Some collections are ordered and others are not.
Week 6 Reduced development effort by using core collection classes rather than implementing
Week 7 our own collection classes.
Week 8

Week 9

Week 10

Week 11

Week 12
W06:L02: Java-Collections

Revision Slides
https://www.sneppets.com/java/collections-framework/collection-and-collections-
framework-in-java/
Week 1

Week 2

Week 3

Week 4

Week 5

Week 6

Week 7

Week 8

Week 9

Week 10

Week 11

Week 12
W06:L03: Java-Concrete-Collections

Revision Slides
The List interface
An ordered collection can be accessed in two ways
Week 1 Through an iterator
Week 2 By position
Week 3
public interface List<E>
Week 4

Week 5
extends Collection<E>{
Week 6
void add(int index, E element);
Week 7 void remove(int index);
Week 8 E get(int index);
Week 9 E set(int index, E element);
Week 10 }
Week 11
List interface implemented classes.
Week 12
ArrayList
LinkedList
Vector
Stack
W06:L03: Java-Concrete-Collections

Revision Slides
The Set interface
A set is a collection without duplicates.
Week 1 We cannot predict the insertion order.
Week 2
Set interface implemented classes.
Week 3

Week 4
HashSet
Week 5
TreeSet
Week 6 The Queue interface
Week 7
Ordered, remove front, insert rear.
Week 8

Week 9
Queue interface implemented classes.
Week 10 ArrayDeque
Week 11 PriorityQueue
Week 12
W06:L04: Maps

Revision Slides
The Map interface
Key-value structures come under the Map interface.
Week 1 Two type parameters
Week 2 K is the type for keys
Week 3 V is the type for values
Week 4
Map interface implemented classes.
Week 5

Week 6
HashMap
Week 7
TreeMap
Week 8
LinkeHashMap
Week 9

Week 10

Week 11

Week 12
W07:L01: Dealing with errors

Revision Slides

Our code could encounter many types of errors


Week 1
User input — enter invalid filenames or URLs
Week 2
Resource limitations — disk full
Week 3
Code errors — invalid array index, key not present in hash map, refer to a variable that
Week 4
is null, divide by zero, . .
Week 5 When we could anticipate what is going to happen we would rather signal the error
Week 6 than program crash
Week 7

Week 8
Exception handling - gracefully recover from errors that occur when running code
Week 9

Week 10

Week 11

Week 12
W07:L01: Java’s classification of errors

Revision Slides
All exceptions descend from class Throwable
Two branches, Error and Exception
Week 1
Error — relatively rare, “not the programmer’s fault”
Week 2

Week 3
Internal errors, resource limitations within Java runtime
Week 4
No realistic corrective action possible, notify caller and terminate gracefully
Week 5 Exception — two sub branches
Week 6 RunTimeException, checked exceptions
Week 7
RunTimeException — programming errors that should have been caught by code
Week 8
Array index out of bounds, invalid hash key, . . .
Week 9

Week 10 Checked exceptions


Week 11 Typically user-defined, code assumptions violated
Week 12 In a list of orders, quantities should be positive integers
W07:L02: Catching and handling exceptions

Revision Slides
try-catch
Enclose code that may generate exception in a try block
Week 1 Exception handler in catch block
Week 2 Use try-catch to safely call functions that may generate errors
Week 3
If try encounters an exception, rest of the code in the block is skipped
Week 4

Week 5 If exception matches the type in catch, handler code executes


Week 6
Otherwise, uncaught exception is passed back to the code that called this code
Week 7

Week 8
Can catch more than one type of exception
Week 9
Multiple catch blocks
Week 10 Catch (ExceptionType e) matches any subtype of ExceptionType
Week 11
Catch blocks are tried in sequence
Week 12
Match exception type against each one in turn
Order catch blocks by argument type, more specific to less specific
W07:L02: Throwing exceptions

Revision Slides
Declare exceptions thrown in header
Can throw multiple types of exceptions
Week 1

Week 2
Can throw any subtype of declared exception type
Week 3 Can throw FileNotFoundException, EOFException, both subclasses of IOException
Week 4
Method declares the exceptions it throws
Week 5

Week 6
If you call such a method, you must handle it
Week 7 ... or pass it on; your method should advertise that it throws the same exception
Week 8
Customized exceptions - Define a new class extending Exception
Week 9

Week 10
Cleaning up resources
Week 11 When exception occurs, rest of the try block is skipped
Week 12 May need to do some clean up (close files, deallocate resources, . . . )
Add a block labelled finally
W07:L03: Packages

Revision Slides
Java has an organizational unit called package
Can use import to use packages directly
Week 1

Week 2
If we omit modifiers, the default visibility is public within the package
Week 3 This applies to both methods and variables
Week 4 Can also restrict visibility with respect to inheritance hierarchy
Week 5
protected means visible within subtree, so all subclasses
Week 6
Normally, a subclass cannot expand visibility of a function
Week 7
However, protected can be made public
Week 8

Week 9

Week 10

Week 11

Week 12
W07:L04: Assertions

Revision Slides

Assertion checks are supposed to flag fatal, unrecoverable errors


Week 1 This should not be caught – Abort and print diagnostic information (stack trace)
Week 2
If assertion fails, code throws AssertionError
Week 3

Week 4
public static double myfn(double x){
Week 5 assert x >= 0;
Week 6 }
Week 7
Can provide additional information to be printed with diagnostic message
Week 8

Week 9
public static double myfn(double x){
Week 10
assert x >= 0 : x;
Week 11 }
Week 12 If you need to flag the error and take corrective action, use exceptions instead
Turned on only during development and testing
Not checked at run time after deployment
W07:L04: Assertions (Cont.)

Revision Slides
Assertions are enabled or disabled at runtime – does not require recompilation
Use the following flag to run with assertions enabled
Week 1 java -enableassertions MyCode
Week 2
Can use -ea as abbreviation for -enableassertions
Week 3
Can selectively turn on assertions for a class
Week 4

Week 5
java -ea:Myclasdes MyCo
Week 6
... or a package
Week 7 java -ea:in.ac.iitm.onlinedegree MyCode
Week 8 Similarly, disable assertions globally or selectively
Week 9
java -disableassertions MyCode
Week 10
java -da:MyClass MyCode
Week 11

Week 12
Can combine the two
java -ea in.ac.iitm.onlinedegree -da:MyClass MyCode
Separate switch to enable assertions for system classes
java -enablesystemassertions MyCode
java -esa MyCode
W07:L05: Logging

Revision Slides
Logging gives us more flexibility and control over tracking diagnostic messages than
simple print statements
Week 1
Example: call info() method of global logger:
Week 2

Week 3 Logger.getGlobal().info("Edit->Copy menu item selected");


Week 4
Can define a hierarchy of loggers
Week 5

Week 6
Seven levels of messages — SEVERE, WARNING, INFO, CONFIG, FINE, FINER, FINEST
Week 7
By default, first three levels are logged
Week 8 Can set a different level
Week 9
logger.setLevel(Level.FINE);
Week 10

Week 11 Turn on all levels, or turn off all logging


Week 12
logger.setLevel(Level.ALL);
logger.setLevel(Level.OFF);
Control logging from within code or through external configuration file
W08:L01: Cloning

Revision Slides
Making a faithful copy of an object is a tricky problem
Java provides a clone() function in Object that does shallow copy
Week 1

Week 2 However, shallow copy aliases nested objects


Week 3 Deep copy solves the problem, but inheritance can create complications
Week 4
To force programmers to consciously think about these subtleties, Java puts in some
Week 5

Week 6
checks to using clone()
Week 7 Must implement marker interface Cloneable to allow clone()
Week 8
clone() is protected by default. override as public if needed
Week 9

Week 10 clone() in Object throws CloneNotSupportedException, which must be taken into


Week 11 account when overriding
Week 12
W08:L02: Type inference

Revision Slides
Automatic type inference can avoid redundancy in
declarations
Week 1
Employee e = new Employee(...)
Week 2

Week 3
Java allows limited type inference var b = false; // boolean
Week 4 Only for local variables in functions
Week 5 Not for instance variables of a class var s = "Hello, world"; // String
Week 6
Challenge is to do this statically, at compile-time
Week 7 var d = 2.0; // double
Use generic var to declare variables
Week 8

Week 9
Must be initialized when declared
var f = 3.141f; // float
Week 10
Type is inferred from initial value
Week 11 Be careful about format for numeric constants
var e = new Manager(...); // Manager
Week 12
For classes, infer most constrained type
e is inferred to be Manager
Manager extends Employee
If e should be Employee, declare explicitly
W08:L03: Higher order functions

Revision Slides Passing a function as an argument to another function


In object-oriented programming, this is achieved using interfaces – encapsulate the
Week 1 function to be passed as an object
Week 2
Lambda expressions denote anonymous functions
Week 3

Week 4
(Parameters) -> Body
Week 5
Return value and type are implicit
Week 6 Interfaces that define a single function are called functional interfaces
Week 7 Comparator, Timerowner
Week 8
Substitute wherever a functional interface is specified
Week 9
String[] strarr = new ...;
Week 10 Arrays.sort(strarr, (String s1, String s2) -> s1.length() - s2.length());
Week 11
Limited type inference is also possible
Week 12
Java infers s1 and s2 are String
String[] strarr = new ...;
Arrays.sort(strarr, (s1, s2) -> s1.length() - s2.length());

More complicated function body can be defined as a block


W08:L03: Higher order functions

Revision Slides If the lambda expression consists of a single function call, we can pass that function by
name – method reference
Week 1
We saw an example with adding entries to a Map object – here sum is a static method
Week 2
in Integer
Map<String, Integer> scores = ...;
Week 3
scores.merge(bat,newscore,Integer::sum);
Week 4

Week 5
Here is the corresponding expression, assuming type inference
(i,j) -> Integer::sum(i,j)
Week 6

Week 7
ClassName::StaticMethod – method reference is C::f, and corresponding
Week 8
expression with as many arguments as f has
(x1,x2,..,xk) -> C::f(x1,x2,...,xk)
Week 9

Week 10
ClassName::InstanceMethod – method reference is C::f, and called with respect to
Week 11
an object that becomes implicit parameter
(o,x1,x2,...,xk) -> o.f(x1,x2,...,xk)
Week 12
object::InstanceMethod – method reference is o::f, and arguments are passed to
o.f
(x1,x2,..,xk) -> o.f(x1,x2,...,xk)
W08:L04: Streams

Revision Slides
We can view a collection as a stream of
elements
Week 1
Process the stream rather than use an
Week 2
iterator
Week 3

Week 4 Declarative way of computing over


Week 5 collections long count = words.stream()
.filter(w -> w.length() > 10)
Week 6
Create a stream, transform it, reduce it .count();
Week 7 }
to a result
Week 8

Week 9
Processing can be parallelized long count = words.parallelStream()
Week 10 filter() and count() in parallel .filter(w -> w.length() > 10)
.count();
Week 11 Apply stream() to a collection }
Week 12
Part of Collections interface
Use static method Stream.of() for
arrays
Create a stream, transform it, reduce it
W08:L04: Streams (Cont.)

Revision Slides
Static method Stream.generate() generates a stream from a function
Week 1
Stream.iterate() — a stream of dependent values
Week 2 filter() to select elements – takes a predicate as argument
Week 3
map() applies a function to each element in the stream
Week 4

Week 5 flatMap() flattens (collapses) nested list into a single stream


Week 6
Make a stream finite — limit(n)
Week 7

Week 8
Skip n elements — skip(n)
Week 9 Stop when element matches a criterion — takeWhile()
Week 10
Start after element matches a criterion — dropWhile()
Week 11

Week 12
Number of elements — count()
Largest and smallest values seen - max() and min()
First element — findFirst()
What happens if the stream is empty? Return value is optional type
W09:L01: Optional Types

Revision Slides
Optional<T> is a clean way to
encapsulate a value that may be absent
Week 1
Different ways to process values of type
Week 2
Optional<T> Optional<Double> maxrand =
Week 3
Replace the missing value by a default Stream.generate(Math::random)
Week 4
Ignore missing values .limit(100)
Week 5

Week 6 max() and min() – what happens if the .filter(n -> n < 0.001)
Week 7 stream is empty? .max(Double::compareTo);
Week 8
max() of empty stream is undefined –
Week 9
return value could be Double or null
Week 10

Week 11 Optional<T> object – wrapper Double fixrand = maxrand.orElse(-1.0);


Week 12 May contain an object of type T if value
present, or no object
Use orElse() to pass a default value
W09:L01: Optional Types (Cont.)

Revision Slides
Double fixrand = maxrand.orElseGet(
Use orElseGet() to call a function to
() -> SomeFunctionToGenerateDouble
generate replacement for a missing value
Week 1 );
Week 2

Week 3
Use orElseThrow() to generate an Double fixrand =
Week 4
exception when a missing value is maxrand.orElseThrow(
Week 5
encountered IllegalStateException::new
Week 6

Week 7
);
Week 8

Week 9
Use ifPresent() to test if a value is optionalValue.ifPresent(
Week 10
present, and process it v -> Process v);
Week 11

Week 12 maxrand.ifPresentOrElse(
Use ifPresentOrElse to Specify an
v -> results.add(v),
alternative action if the value is not
() -> System.out.println("No max")
present
);
W09:L01: Optional Types (Cont.)

Revision Slides
Creating an optional value
Optional.of(v) creates value v
Week 1 Optional.empty creates empty optional
Week 2
Use ofNullable() to transform null automatically into an empty optional
Week 3

Week 4 map applies function to value, if present; if input is empty, so is output


Week 5
Optional<Double> maxrandsqr = maxrand.map(v -> v*v);
Week 6

Week 7
Supply an alternative for a missing value using or()
Week 8 Optional<Double> fixrand = maxrand.or(() -> Optional.of(-1.0));
Week 9
flatMap allows us to cascade functions with optional types
Week 10
Use flatMap to regenerate a stream from optional values
Week 11

Week 12
W09:L02: Collecting results from streams

Revision Slides Convert collections into sequences of values — streams


Stream defines a standard iterator, use to loop through values in a stream
Week 1 Alternatively, use forEach with a suitable function
Week 2 mystream.forEach(System.out::println);
Week 3
Can convert a stream into an array using toArray()
Week 4
Object[] result = mystream.toArray();
Week 5

Week 6
String[] result = mystream.toArray(String[]::new);
Week 7 What if we want to convert the stream back into a collection? – use collect()
Week 8 Pass appropriate factory method from Collectors
Week 9 Create a list from a stream
Week 10
List<String> result = mystream.collect(Collectors.toList());
Week 11
. . . or a set
Week 12
Set<String> result = mystream.collect(Collectors.toSet());
To create a concrete collection, provide a constructor
TreeSet<String> result =
stream.collect(Collectors.toCollection(TreeSet::new));
W09:L02: Collecting results from streams (Cont.)

Revision Slides
Collectors has methods to aggregate summaries in a single object
summarizingInt works for a stream of integers
Week 1
IntSummaryStatistics summary = mystream.collect(
Week 2
Collectors.summarizingInt(String::length));
Week 3
double averageWordLength = summary.getAverage();
Week 4

Week 5
double maxWordLength = summary.getMax();
Week 6 Methods to access relevant statistics – getCount(), getMax(), getMin(),
Week 7 getSum(), getAverage(),
Week 8 Similarly, summarizingLong() and summarizingDouble() return
Week 9
LongSummaryStatistics and DoubleSummaryStatistics
Week 10
Convert a stream of Person to a map – For Person p, p.getID() is key and
Week 11

Week 12
p.getName() is value
Stream<Person> people = ...;
Map<Integer, String> nameToID = people.collect(
Collectors.toMap(Person::getId, Person::getName)
);
W09:L02: Collecting results from streams (Cont.)

Revision Slides
Collect all ids with the same name in a list
Stream<Person> people = ...;
Week 1
Map<String, List<Person>> nameTopersons = people.collect(
Week 2

Week 3
Collectors.groupingBy(Person::getName)
Week 4
);
Week 5 Instead, may want to partition the stream using a predicate – Partition names into
Week 6 those that start with A and the rest
Week 7

Week 8
Stream<Person> people = ...;
Week 9
Map<Boolean, List<Person>> aAndOtherPersons =
Week 10 people.collect(
Week 11 Collectors.partitioningBy(
Week 12 p -> p.getName().substr(0,1).equals("A")
)
);
W09:L03: Input/output streams

Revision Slides
Input: read a sequence of bytes from some source – a file, an internet connection,
memory
Week 1
Output: write a sequence of bytes to some source – a file, an internet connection,
Week 2

Week 3
memory
Week 4 Read one or more bytes — abstract methods are implemented by subclasses of
Week 5 InputStream
Week 6
Close a stream when done — release resources
Week 7

Week 8 Flush an output stream — output is buffered


Week 9 Similarly, write one or more bytes using – OutputStream
Week 10
Create an input stream attached to a file – FileInputStream
Week 11

Week 12 Create an output stream attached to a file – FileOutputStream


Overwrite or append? – Pass a boolean second argument to the constructor
Scanner class – apply to any input stream – many read methods
To write text, use PrintWriter class – apply to any output stream
W09:L03: Input/output streams (Cont.)

Revision Slides
To read binary data, use DataInputStream class – many read methods
To write binary data, use DataOutputStream class
Week 1

Week 2 Buffering an input stream – reads blocks of data – BufferedInputStream()


Week 3 Similarly, write blocks using – BufferedOutputStream()
Week 4
PushBackStream can only read() and unread()
Week 5

Week 6 Java has a whole zoo of streams for different tasks – random access files, zipped data,
Week 7 . . .
Week 8

Week 9

Week 10

Week 11

Week 12
W09:L04: Serialization

Revision Slides
DataInputStream and DataOutputStream – read and write low level units like bytes,
integers, floats, characters, . . .
Week 1 Can we export and import objects directly?
Week 2
Backup objects onto disk, with state
Week 3
Restore objects from disk
Week 4
Send objects across a network
Week 5
Serialization and deserialization
Week 6

Week 7
To write objects, Java has another output stream type, ObjectOutputStream
Week 8 Use writeObject() to write out an object
Week 9 To read back objects, use ObjectInputStream
Week 10
Retrieve objects in the same order they were written, using readObject()
Week 11

Week 12
Class has to allow serialization — implement marker interface Serializable
Some objects should not be serialized – mark such fields as transient
Can override writeObject()
defaultWriteObject() writes out the object with all non-transient fields
Then explicitly write relevant details of transient fields
W10:L01: Concurrent Programming

Revision Slides

Multiprocessing
Week 1
Single processor executes several computations “in parallel”
Week 2
Time-slicing to share access
Week 3
Private set of local variables
Week 4
Time-slicing involves saving the state of one process and loading the suspended state of
Week 5
another
Week 6 Threads
Week 7 Logically parallel actions within a single application
Week 8 Operated on same local variables
Week 9 Communicate via “shared memory”
Week 10 Context switches are easier
Week 11

Week 12
W10:L01: Creating threads

Revision Slides
Have a class extend Thread
Define a function run( ) where execution can begin in parallel
Week 1

Week 2 Invoke start( ), initiates run( ) in a separate thread


Week 3 Directly calling run( ) does not execute in separate thread!
Week 4
Cannot always extend Thread, Instead, implement Runnable( )
Week 5

Week 6 To use class, Runnable( ) explicitly create a Thread and strat( ) it


Week 7

Week 8

Week 9

Week 10

Week 11

Week 12
W10:L02: Race conditions and mutual exclusion

Revision Slides

Race condition: Concurrent update of a shared variable can lead to


Week 1
data inconsistency
Week 2 Critical sections: sections of code where shared variables are
Week 3 updated
Week 4
Mutual exclusion: at most one thread at a time can be in a critical
Week 5

Week 6
section
Week 7

Week 8

Week 9

Week 10

Week 11

Week 12
W10:L03:Mutual Exclusion

Revision Slides

At most one thread at a time can be in a critical section


Week 1
Using a two-(int)valued variable
Week 2 Leads to starvation
Week 3 Using two boolean variables
Week 4
Leads to deadlock
Week 5

Week 6
Petersen Algorithm - Combination of a two-valued variable and two boolean variables
Week 7 Avoids both starvation and deadlock
Week 8 But difficult to generalize to more than two threads
Week 9 Bakery Algorithm - The thread itself acquires a token number by incrementing the
Week 10 current token number by 1.
Week 11
If two threads get the same number, then some system parameter is used to break the
Week 12
tie.
To avoid this, the checking for max and incrementing should be made an atomic step.
W10:L03:Mutual Exclusion

Revision Slides

Week 1 Using a two-valued variable


Week 2

Week 3 Thread 1 Thread 2


Week 4 ... ...
Week 5 while (turn != 1){ while (turn != 2){
Week 6 // "Busy" wait // "Busy" wait
Week 7
} }
Week 8
// Enter critical section // Enter critical section
Week 9
... ...
Week 10

Week 11
// Leave critical section // Leave critical section
Week 12
turn = 2; turn = 1;
... ...
W10:L03:Mutual Exclusion

Revision Slides

Week 1
Using two boolean variables
Week 2
Thread 1 Thread 2
Week 3
... ...
Week 4

Week 5
request_1 = true; request_2 = true;
Week 6
while (request_2){ while (request_1)
Week 7 // "Busy" wait // "Busy" wait
Week 8 } }
Week 9 // Enter critical section // Enter critical section
Week 10 ... ...
Week 11 // Leave critical section // Leave critical section
Week 12
request_1 = false; request_2 = false;
... ...
W10:L03:Mutual Exclusion - Peterson Algorithm

Revision Slides

Week 1
Using a single two-valued variable and two boolean variables
Week 2
Thread 1 Thread 2
Week 3
... ...
Week 4

Week 5
request_1 = true; request_2 = true;
Week 6
while (request_2){ while (request_1)
Week 7 // "Busy" wait // "Busy" wait
Week 8 } }
Week 9 // Enter critical section // Enter critical section
Week 10 ... ...
Week 11 // Leave critical section // Leave critical section
Week 12
request_1 = false; request_2 = false;
... ...
W10:L04:Test-and-set

Revision Slides

Week 1

Week 2

Week 3

Week 4
Check the current value of a variable, then update it
Week 5
If more than one thread does this in parallel, updates may overlap and get lost
Week 6

Week 7
Need to combine test and set into an atomic, indivisible step
Week 8

Week 9 Cannot be guaranteed without adding this as a language primitive


Week 10

Week 11

Week 12
W10:L04:Semaphores

Revision Slides

Programming language primitive for test-and-set is given by Semaphores.


Week 1
Thread 1 Thread 2
Week 2

Week 3
... ...
Week 4
P(S); P(S);
Week 5 // Enter critical section // Enter critical section
Week 6 ... ...
Week 7 // Leave critical section // Leave critical section
Week 8 V(S); V(S);
Week 9 ... ...
Week 10

Week 11 Semaphores guarantee


Week 12
Mutual exclusion
Freedom from starvation
Freedom from deadlock
W11:L1: Threads in JAVA

Revision Slides
Threads can be created by extending Thread class or implementing Runnable interface.
We define a function run which is executed by the spawned threads of that class.
Week 1

Week 2 Invoking the start method of the thread object initiates the run method on a separate thread (not the
Week 3
main thread).
Week 4 Thread.sleep(arg) suspends the thread for arg milliseconds.
Week 5 A thread does not release its lock (if already gained) while in sleep.
Week 6 join() method makes the thread executing this instruction wait for the thread on which join is called
Week 7 to complete its execution.
Week 8 Both join and sleep methods can throw interruptedException.
Week 9
To check a thread’s interrupt status one can use t.isInterrupted(). It does not clear the flag
Week 10
While writing a multithreaded program, one can either define multiple classes with their own run
Week 11
methods working on different features of the code or different threads can be filtered by their name
Week 12
inside one run method and corresponding utility functions are called using these threads.
W11: Thread: Synchronization

Revision Slides
Shared variables between threads can show inconsistent values as a result of context switching of
threads arbitrarily (race condition). In order to attain atomicity while updating shared variables the
synchronized keyword is used.
Week 1

Week 2 JAVA allows a method or a block of code to be executed in synchronized manner. In case of
Week 3
synchronization block, we mention the object whose lock would be held by the thread executing the
synchronized block.
Week 4

Week 5
Programs in which the critical section is synchronized will maintain consistent value of the shared
Week 6
variables irrespective of the degree of concurrency (number of threads).
Week 7 Intercommunication between threads can be done by using wait() and notify()/notifyAll()
Week 8 methods.
Week 9
wait(): is used to suspend a thread. The thread loses its lock and goes to BLOCKED state.
Week 10 notify(): signals one arbitrary thread waiting on that object that the object lock is now free to
Week 11 be gained.
Week 12 notifyAll(): signals all waiting threads, but one of them will be picked by the system to be
executed.
wait, notify, notifyAll must always be used inside synchronized blocks/methods otherwise
IllegalMonitorStateException is thrown.
W11: Thread State

Revision Slides
Life Cycle of a thread in JAVA:
New:
Week 1
Created but, start() is not invoked.
Week 2
Runnable:
Week 3
start() method has been invoked and the thread is ready to be scheduled.
Week 4
Running:
Week 5
the current thread is under execution.
Week 6
Blocked:
Week 7
the thread is suspended by wait() method, it has lost its lock.
Week 8
Timed Waiting:
Week 9
the thread is sleeping, holding its lock
Week 10
Terminated:
Week 11
Either the thread has finished its job and has terminated normally or it has terminated
Week 12
because of some abnormal event like segmentation fault/unhandled exception.
W11: Re-entrant Locks and Threadsafe Collections

Revision Slides
JAVA provides semaphore like mechanism to implement concurrency in programs using reentrant
locks.
Week 1 ReentrantLock class
Week 2
A reentrant lock object has methods lock() and unlock() just like P(s) and V(s).
Week 3
Always put the unlock() under a finally block.
Week 4

Week 5 Why re entrant?


Week 6 Thread already holding lock of an object can reacquire it.
Week 7 very useful while working with recursive codes which must be executed atomically but in a
Week 8 multithreaded environment.
Week 9 Threadsafe collections guarantees consistency of individual updates/accesses done by multiple threads
Week 10 on the same collection.
Week 11
Sequence of updates is still not guaranteed in threadsafe collections.
Week 12
JAVA provides built in collections which are threadsafe
ConcurrentHashMap
BlockingQueue
A threadsafe collection will never throw ConcurrentModificationException
W12:GUI programming

Revision Slides

Week 1
How to interact with the Java program?
Week 2
Using CLI(Command Line Interface).
Week 3
Using GUI(Graphical User Interface).
Week 4

Week 5 How to create GUI?


Week 6 Using AWT(Abstract Window Toolkit).
Week 7 Using Swing.
Week 8
Both AWT and Swing are used to create GUI.
Week 9
AWT components heavyweight.
Week 10
Swing components lightweight.
Week 11

Week 12
Steps to create GUI

Revision Slides

Week 1

Week 2

Week 3 create a class by extending JFrame/Frame.


Week 4 Create GUI components.
Week 5

Week 6
Add GUI components to the panel.
Week 7 Add panel to the frame.
Week 8
call setVisible(true) to visible the GUI screen.
Week 9

Week 10

Week 11

Week 12
Event Driven Programming

Revision Slides

AWT and Swing just create GUI.


Week 1

Week 2 If we want to perform operations behind the GUI screens, we should use event driven
Week 3 programming.
Week 4 Button
Week 5
ActionListener
Week 6
ActionEvent
Week 7
public abstract void actionPerformed(ActionEvent e)
Week 8

Week 9
KeyBoard
Week 10 KeyListener
Week 11 KeyEvent
Week 12 public abstract void keyTyped(KeyEvent e);
public abstract void keyPressed(KeyEvent e);
public abstract void keyReleased(KeyEvent e);

You might also like