Java Revision Slides (1)
Java Revision Slides (1)
Week 1
Week 2
Week 3
Week 7
Week 8
Week 9
Week 10
Week 11
Week 12
W01:L01: Introduction
Revision Slides
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
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
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 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
Revision Slides
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
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 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
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
Revision Slides
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
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
Revision Slides
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
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 10
Week 11
Week 12
Classes and objects
Revision Slides
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
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
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
Revision Slides
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 ...
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 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){ ... }
Revision Slides
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
Using one idea (hierarchy of classes) to implement both concepts blurs the distinction
between the two
W03:L06: Java modifiers
Revision Slides
Week 11
A final class cannot be inherited
Week 12 Can also have private classes
Abstract classes
Revision Slides
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 11
Week 12
Interfaces
Revision Slides
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
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
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
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
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
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
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
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
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
Week 7
Week 8
Week 9
Week 10
Week 11
Week 12
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
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
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 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
Revision Slides
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 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 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
Week 4
public E remove(){...};
Week 5
public int size(){...};
Week 6 ...
Week 7 }
Week 8
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
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
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 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
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 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
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 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
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
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());
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 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 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
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 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
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
Revision Slides
To read binary data, use DataInputStream class – many read methods
To write binary data, use DataOutputStream class
Week 1
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 8
Week 9
Week 10
Week 11
Week 12
W10:L02: Race conditions and mutual exclusion
Revision Slides
Week 6
section
Week 7
Week 8
Week 9
Week 10
Week 11
Week 12
W10:L03:Mutual Exclusion
Revision Slides
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 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 11
Week 12
W10:L04:Semaphores
Revision Slides
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
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
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 12
Steps to create GUI
Revision Slides
Week 1
Week 2
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
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);