0% found this document useful (0 votes)
113 views68 pages

Java Notes Quiz 1

Uploaded by

Ariyan Dey
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)
113 views68 pages

Java Notes Quiz 1

Uploaded by

Ariyan Dey
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/ 68

PROGRAMMING

CONCEPTS USING
JAVA

Week 1-4
Programming languages

A language is a medium for communication


Programming languages communicate computational instructions
Originally, directly connected to architecture
Memory locations store values, registers allow arithmetic
Load a value from memory location M into register R
Add the contents of register R1 and R2 and store the result back in R1
Write the value in R1 to memory location M 0

Tedious and error-prone

Madhavan Mukund Introduction Programming Concepts using Java 2/9

Abstraction
Abstractions used in computational thinking
Assigning values to named variables
Conditional execution
Iteration
Functions / procedures, recursion
Aggregate data structures — arrays, lists, dictionaries

Express such ideas in the programming language


Translate “high level” programming language to “low level” machine language
Compilers, interpreters

Trade off expressiveness for efficiency


Less control over how code is mapped to the architecture
But fewer errors due to mismatch between intent and implementation
Madhavan Mukund Introduction Programming Concepts using Java 3/9
Styles of programming
Imperative vs declarative
Imperative
How to compute
Step by step instructions on what is to be done

Declarative
What the computation should produce
Often exploit inductive structure, express in terms of smaller computations
Typically avoid using intermediate variables
Combination of small transformations — functional programming

Madhavan Mukund Introduction Programming Concepts using Java 4/9

Imperative vs Declarative Programming, by example


Add values in a list
Imperative (in Python) Declarative (in Python)
def sumlist(l): def sumlist(l):
mysum = 0 if l == []:
for x in l: return(0)
mysum = mysum + x else:
return(mysum) return(l[0] + sumlist(l[1:]))

Intermediate values mysum, x Describe the desired output by


induction
Explicit iteration to examine each Base case: Empty list has sum 0
element of the list
Inductive step: Add first element to
the sum of the rest of the list

No intermediate variables
Madhavan Mukund Introduction Programming Concepts using Java 5/9
Imperative vs Declarative Programming, by example, . . .
Sum of squares of even numbers upto n
Imperative (in Python) Declarative (in Python)
def sumsquareeven(n): def even(x):
mysum = 0 return(x%2 == 0)
for x in range(n+1):
if x%2 == 0: def square(x):
mysum = mysum + x*x return(x*x)
return(mysum) def sumsquareeven(n):
return(
Can code functionally in an imperative
sum(map(square,
language!
filter(even,
Helps identify natural units of range(n+1)))))
(reusable) code

Madhavan Mukund Introduction Programming Concepts using Java 6/9

Names, types, values

Internally, everything is stored a sequence of bits


No difference between data and instructions, let alone numbers, characters, booleans
For a compiler or interpreter, our code is its data

We impose a notion of type to create some discipline


Intepret bit strings as “high level” concepts
Nature and range of allowed values
Operations that are permitted on these values

Strict type-checking helps catch bugs early


Incorrect expression evaluation — like dimension mismatch in science
Incorrect assignment — expression value does not match variable type

Madhavan Mukund Introduction Programming Concepts using Java 7/9


Abstract datatypes, object-oriented programming
Collections are important
Arrays, lists, dictionaries

Abstract data types


Structured collection with fixed interface
Stack is a sequence, but only allows push and pop
Separate implementation from interface
Priority queue allows insert and delete-max
Can implement a priority queue using sorted or unsorted lists, or using a heap

Object-oriented programming
Focus on data types
Functions are invoked through the object rather than passing data to the functions
In Python, mylist.sort() vs sorted(mylist)
Madhavan Mukund Introduction Programming Concepts using Java 8/9

What this course is about

Explore concepts in programming languages


Object-oriented programming
Exception handling, concurrency, event-driven programming, . . .

Use Java as the illustrative language


Imperative, object-oriented
Incorporates almost all features of interest

Discuss design decisions where relevant


Every language makes some compromises

Understand and appreciate why there is a zoo of programming languages out there
. . . and why new ones are still being created

Madhavan Mukund Introduction Programming Concepts using Java 9/9


The role of types
Interpreting data stored in binary in a consistent manner
View sequence of bits as integers, floats, characters, . . .
Nature and range of allowed values
Operations that are permitted on these values

Naming concepts and structuring our computation


Especially at a higher level
Point vs (Float,Float)
Banking application: accounts of different types, customers . . .

Catching bugs early


Incorrect expression evaluation — like dimension mismatch in science
Incorrect assignment — expression value does not match variable type

Madhavan Mukund Types Programming Concepts using Java 2/7

Dynamic vs static typing


Every variable we use has a type
How is the type of a variable determined?
Python determines the type based on the current value
Dynamic typing — names derive type from current value
x = 10 — x is of type int
x = 7.5 — now x is of type float
An uninitialized name as no type

Static typing — associate a type in advance with a name


Need to declare names and their types in advance value
int x, float a, . . .
Cannot assign an incompatible value — x = 7.5 is no longer legal

Madhavan Mukund Types Programming Concepts using Java 3/7


Dynamic vs static typing
“Isn’t it convenient that we don’t have to declare variables in advance in Python?”
Yes, but . . .
Difficult to catch errors, such as typos
def factors(n):
factorlist = []
for i in range(1,n+1):
if n%i == 0:
factorlst = factorlist + [i] # Typo!
return(factorlist)

Empty user defined objects


Linked list is a sequence of objects of type Node
Convenient to represent empty linked list by None
Without declaring type of l, Python cannot associate a type after l = None
Madhavan Mukund Types Programming Concepts using Java 4/7

Types for organizing concepts

Even simple type “synonyms” can help clarify code


2D point is a pair (float,float), 3D point is triple (float,float,float)
Create new type names point2d and point3d
These are synonyms for (float,float) and (float,float,float)
Makes intent more transparent when writing, reading and maintaining code

More elaborate types — abstract datatypes and object-oriented programming


Consider a banking application
Data and operations related to accounts, customers, deposits, withdrawals, transfers
Denote accounts and customers as separate types
Deposits, withdrawals, transfers can be applied to accounts, not customers
Updating personal details applies to customers, not accounts

Madhavan Mukund Types Programming Concepts using Java 5/7


Static analysis

Identify errors as early as possible — saves cost, effort


In general, compilers cannot check that a program will work correctly
Halting problem — Alan Turing

With variable delarations, compilers can detect type errors at compile-time — static
analysis
Dynamic typing would catch these errors only when the code runs
Executing code also slows down due to simultaneous monitoring for type correctness

Compilers can also perform optimizations based on static analysis


Reorder statements to optimize reads and writes
Store previously computed expressions to re-use later

Madhavan Mukund Types Programming Concepts using Java 6/7

Keeping track of variables


Variables store intermediate Scope of a variable
values during computation When the variable is available for use
Typically these are local to a In the following code, the x in f() is not in
function scope within call to g()
Can also refer to global def f(l): def g(m):
variables outside the function ... ...
Dynamically created data, like for x in l: for x in range(m):
nodes in a list y = y + g(x) ...
...

Lifetime of a variable
How long the storage remains allocated
Above, lifetime of x in f() is till f() exits
“Hole in scope” — variable is alive but not in
scope
Madhavan Mukund Memory Management Programming Concepts using Java 2/7
Memory stack
Each function needs storage for local variables Memory
Storage for factorial(3)
Create activation record when function is called n 3
Activation records are stacked factorial(n-1)
Popped when function exits
Storage for factorial(2)
Control link points to start of previous record
n 2
Return value link tells where to store result
factorial(n-1)
Scope of a variable Control link
Variable in activation record at top of stack Return value link

Access global variables by following control


links
Call factorial(3)
Lifetime of a variable
factorial(3) calls factorial(2)
Storage allocated is still on the stack
Madhavan Mukund Memory Management Programming Concepts using Java 3/7

Passing arguments to functions


When a function is called, arguments are substituted for formal parameters
def f(a,l): x = 7 a = x
... myl = [8,9,10] l = myl
... f(x,myl) ... code for f() ...

Parameters are part of the activation record of the function


Values are populated on function call
Like having implicit assignment statements at the start of the function

Two ways to initialize the parameters


Call by value — copy the value
Updating the value inside the function has no side-effect
Call by reference — parameter points to same location as argument
Can have side-effects
Be careful: can update the contents, but cannot change the reference itself
Madhavan Mukund Memory Management Programming Concepts using Java 4/7
Heap
Function that inserts a value in a linked list
Storage for new node allocated inside function
Memory
Node should persist after function exits
Cannot be allocated within activation record
Stack
Separate storage for persistent data
Dynamically allocated vs statically declared
Usually called the heap
Not the same as the heap data structure!
Conceptually, allocate heap storage from
“opposite” end with respect to stack Heap
Heap storage outlives activation record
Access through some variable that is in scope

Madhavan Mukund Memory Management Programming Concepts using Java 5/7

Managing heap storage


On the stack, variables are deallocated when a function exits
How do we “return” unused storage on the heap?
After deleting a node in a linked list, deleted node i now dead storage, unreachable

Manual memory management


Programmer explicitly requests and returns heap storage
p = malloc(...) and free(p) in C
Error-prone — memory leaks, invalid assignments

Automatic garbage collection (Java, Python, . . . )


Run-time environment checks and cleans up dead storage — e.g., mark-and-sweep
Mark all storage that is reachable from program variables
Return all unmarked memory cells to free space
Convenience for programmer vs performance penalty
Madhavan Mukund Memory Management Programming Concepts using Java 6/7
Stepwise refinement
begin
Begin with a high level description of print first thousand prime numbers
the task end
Refine the task into subtasks
begin
Further elaborate each subtask declare table p
fill table p with first thousand primes
Subtasks can be coded by different print table p
people end
Program refinement — focus on
code, not much change in data begin
structures integer array p[1:1000]
for k from 1 through 1000
make p[k] equal to the kth prime number
for k from 1 through 1000
print p[k]
Madhavan Mukund endmodularity
Abstraction and Programming Concepts using Java 2/6

Data refinement

Banking application
Typical functions: CreateAccount(), Deposit()/Withdraw(), PrintStatement()

How do we represent each account?


Only need the current balance
Overall, an array of balances

Refine PrintStatement() to include PrintTransactions()


Now we need to record transactions for each account
Data representation also changes
Cascading impact on other functions that operate on accounts

Madhavan Mukund Abstraction and modularity Programming Concepts using Java 3/6
Modular software development
Use refinement to divide the solution into components
Build a prototype of each component to validate design
Components are described in terms of
Interfaces — what is visible to other components, typically function calls
Specification — behaviour of the component, as visible through interface
Improve each component independently, preserving interface and specification
Simplest example of a component: a function
Interfaces — function header, arguments and return type
Specification — intended input-output behaviour
Main challenge: suitable language to write specifications
Balance abstraction and detail, should not be another programming language!
Cannot algorithmically check that specification is met (halting problem!)

Madhavan Mukund Abstraction and modularity Programming Concepts using Java 4/6

Programming language support for abstraction


Control abstraction
Functions and procedures
Encapsulate a block of code, reuse in different contexts
Data abstraction
Abstract data types (ADTs)
Set of values along with operations permitted on them
Internal representation should not be accessible
Interaction restricted to public interface
For example, when a stack is implemented as a list, we should not be able to observe or
modify internal elements

Object-oriented programming
Organize ADTs in a hierarchy
Implicit reuse of implementations — subtyping, inheritance

Madhavan Mukund Abstraction and modularity Programming Concepts using Java 5/6
Objects

An object is like an abstract datatype


Hidden data with set of public operations
All interaction through operations — messages, methods, member-functions, . . .

Uniform way of encapsulating different combinations of data and functionality


An object can hold single integer — e.g., a counter
An entire filesystem or database could be a single object

Distinguishing features of object-oriented programming


Abstraction
Subtyping
Dynamic lookup
Inheritance

Madhavan Mukund Object-oriented programming Programming Concepts using Java 2/9

History of object-oriented programming

Objects first introduced in Simula — Q := make-queue(first event)


simulation language, 1960s repeat
remove next event e from Q
Event-based simulation follows a basic pattern
simulate e
Maintain a queue of events to be simulated place all events generated
Simulate the event at the head of the queue by e on Q
until Q is empty
Add all events it spawns to the queue

Challenges
Queue must be well-typed, yet hold all types
of events
Use a generic simulation operation across
different types of events
Avoid elaborate checking of cases

Madhavan Mukund Object-oriented programming Programming Concepts using Java 3/9


Abstraction

Objects are similar to abstract datatypes


Public interface
Private implementation
Changing the implementation should not affect interactions with the object

Data-centric view of programming


Focus on what data we need to maintain and manipulate

Recall that stepwise refinement could affect both code and data
Tying methods to data makes this easier to coordinate
Refining data representation naturally tied to updating methods that operate on the
data

Madhavan Mukund Object-oriented programming Programming Concepts using Java 4/9

Subtyping
Recall the Simula event queue
A well-typed queue holds values of a fixed type
In practice, the queue holds different types of objects
How can this be reconciled?

Arrange types in a hierarchy


A subtype is a specialization of a type
If A is a subtype of B, wherever an object of type B is needed, an object of type A can
be used
Every object of type A is also an object of type B
Think subset — if X ⊆ Y , every x ∈ X is also in Y

If f() is a method in B and A is a subtype of B, every object of A also supports f()


Implementation of f() can be different in A

Madhavan Mukund Object-oriented programming Programming Concepts using Java 5/9


Dynamic lookup
Whether a method can be invoked on an object is a static property — type-checking
How the method acts is a dynamic property of how the object is implemented
In the simulation queue, all events support a simulate method
The action triggered by the method depends on the type of event
In a graphics application, different types of objects to be rendered
Invoke using the same operation, each object “knows” how to render itself

Different from overloading


Operation + is addition for int and float
Internal implementation is different, but choice is determined by static type

Dynamic lookup
A variable v of type B can refer to an object of subtype A
Static type of v is B, but method implementation depends on run-time type A
Madhavan Mukund Object-oriented programming Programming Concepts using Java 6/9

Inheritance
Re-use of implementations
Example: different types of employees
Employee objects store basic personal data, date of joining
Manager objects can add functionality
Retain basic data of Employee objects
Additional fields and functions: date of promotion, seniority (in current role)

Usually one hierarchy of types to capture both subtyping and inheritance


A can inherit from B iff A is a subtype of B

Philosophically, however the two are different


Subtyping is a relationship of interfaces
Inheritance is a relationship of implementations

Madhavan Mukund Object-oriented programming Programming Concepts using Java 7/9


Subtyping vs inheritance
A deque is a double-ended queue
Supports insert-front(), delete-front(), insert-rear() and delete-rear()

We can implement a stack or a queue using a deque


Stack: use only insert-front(), delete-front(),
Queue: use only insert-rear(), delete-front(),

Stack and Queue inherit from Deque — reuse implementation


But Stack and Queue are not subtypes of Deque
If v of type Deque points an object of type Stack, cannot invoke insert-rear(),
delete-rear()
Similarly, no insert-front(), delete-rear() in Queue

Interfaces of Stack and Queue are not compatible with Deque


In fact, Deque is a subtype of both Stack and Queue
Madhavan Mukund Object-oriented programming Programming Concepts using Java 8/9

Programming with objects

Object are like abstract datatypes


Hidden data with set of public operations
All interaction through operations — messages, methods, member-functions, . . .

Class
Template for a data type
How data is stored
How public functions manipulate data

Object
Concrete instance of template
Each object maintains a separate copy of local data
Invoke methods on objects — send a message to the object

Madhavan Mukund Classes and objects Programming Concepts using Java 2 / 11


Example: 2D points
A point has coordinates (x, y ) class Point:
Each point object stores its own internal def __init__(self,a=0,b=0):
values x and y — instance variables self.x = a
self.y = b
For a point p, the local values are p.x and p.y
self is a special name referring to the current
object — self.x, self.y

When we create an object, we need to set it up


Implicitly call a constructor function with a
fixed name
In Python, constructor is called init ()
Parameters are used to set up internal values
In Python, the first parameter is always self

Madhavan Mukund Classes and objects Programming Concepts using Java 3 / 11

Adding methods to a class


Translation: shift a point by (∆x, ∆y ) class Point:
(x, y ) 7→ (x + ∆x, y + ∆y ) def __init__(self,a=0,b=0):
self.x = a
Update instance variables self.y = b
Distance from the origin
d=
p
x2 + y2 def translate(self,dx,dy):
self.x += dx
Does not update instance variables self.y += dy
state of object is unchanged
def odistance(self):
import math
d = math.sqrt(self.x*self.x +
self.y*self.y)
return(d)

Madhavan Mukund Classes and objects Programming Concepts using Java 4 / 11


Changing the internal implementation
Polar coordinates: (r , θ), not (x, y ) import math
p class Point:
r= x2 + y2
def __init__(self,a=0,b=0):
θ = tan−1 (y /x) self.r = math.sqrt(a*a + b*b)
if a == 0:
Distance from origin is just r self.theta = math.pi/2
else:
self.theta = math.atan(b/a)

def odistance(self):
return(self.r)

Madhavan Mukund Classes and objects Programming Concepts using Java 5 / 11

Changing the internal implementation


Polar coordinates: (r , θ), not (x, y ) def translate(self,dx,dy):
r=
p
x2 + y2 x = self.r*math.cos(self.theta)
y = self.r*math.sin(self.theta)
θ = tan−1 (y /x) x += dx
y += dy
Distance from origin is just r
self.r = math.sqrt(x*x + y*y)
Translation if x == 0:
self.theta = math.pi/2
Convert (r , θ) to (x, y ) else:
x = r cos θ, y = r sin θ self.theta = math.atan(y/x)
Recompute r , θ from (x + ∆x, y + ∆y )

Interface has not changed


User need not be aware whether
representation is (x, y ) or (r , θ)

Madhavan Mukund Classes and objects Programming Concepts using Java 5 / 11


Abstraction
User should not know whether Point uses class Point:
(x,y) or (r,theta) def __init__(self,a=0,b=0):
Interface remains identical self.x = a
self.y = b
Even constructor is the same

Python allows direct access to instance


variables from outside the class class Point:
p = Point(5,7) def __init__(self,a=0,b=0):
p.x = 4 # Point is now (4,7) self.r = math.sqrt(a*a + b*b)
if a == 0:
Breaks the abstraction self.theta = math.pi/2
Changing the internal implementation of else:
Point can have impact on other code self.theta = math.atan(b/a)

Rely on programmer discipline

Madhavan Mukund Classes and objects Programming Concepts using Java 6 / 11

Subtyping and inheritance


Define Square to be a subtype of class Rectangle:
Rectangle def __init__(self,w=0,h=0):
Different constructor self.width = w
self.height = h
Same instance variables
def area(self):
The following is legal return(self.width*self.height)
s = Square(5)
a = s.area() def perimeter(self):
p = s.perimeter() return(2*(self.width+self.height))
Square inherits definitions of area()
class Square(Rectangle):
and perimeter() from Rectangle
def __init__(self,s=0):
self.width = s
self.height = s

Madhavan Mukund Classes and objects Programming Concepts using Java 7 / 11


Subtyping and inheritance . . .
Can change the instance variable in class Rectangle:
Square def __init__(self,w=0,h=0):
self.side self.width = w
self.height = h
The following gives a run-time error
def area(self):
s = Square(5)
return(self.width*self.height)
a = s.area()
p = s.perimeter()
def perimeter(self):
Square inherits definitions of area() return(2*(self.width+self.height))
and perimeter() from Rectangle
But s.width and s.height have not class Square(Rectangle):
been defined! def __init__(self,s=0):
Subtype is not forced to be an extension self.side = s
of the parent type

Madhavan Mukund Classes and objects Programming Concepts using Java 8 / 11

Subtyping and inheritance . . .


Subclass and parent class are usually class Rectangle:
developed separately def __init__(self,w=0,h=0):
self.wd = w
Implementor of Rectangle changes the self.ht = h
instance variables
def area(self):
The following gives a run-time error return(self.wd*self.ht)
s = Square(5)
a = s.area() def perimeter(self):
p = s.perimeter() return(2*(self.wd+self.ht))
Square constructor sets s.width and
s.height class Square(Rectangle):
def __init__(self,s=0):
But the instance variable names have
self.width = s
changed!
self.height = s
Why should Square be affected by this?

Madhavan Mukund Classes and objects Programming Concepts using Java 9 / 11


Subtyping and inheritance . . .
Need a mechanism to hide private class Rectangle:
implementation details def __init__(self,w=0,h=0):
Declare component private or public self.wd = w
self.ht = h
Working within privacy constraints
def area(self):
Instance variables wd and ht of return(self.wd*self.ht)
Rectangle are private
How can the constructor for Square set def perimeter(self):
these private variables? return(2*(self.wd+self.ht))
Square does (and should) not know the
names of the private instance variables class Square(Rectangle):
def __init__(self,s=0):
Need to have elaborate declarations self.width = s
Type and visibility of variables self.height = s

Static type checking catches errors early


Madhavan Mukund Classes and objects Programming Concepts using Java 10 / 11

Getting started
In Python
The C Programming Language,
Brian W Kernighan, Dennis M Ritchie print("hello, world")
The only way to learn a new programming ...C
language is by writing programs in it. The #include <stdio.h>
first program is the same for all languages. main()
Print the words {
hello, world printf("hello, world\n");
}
This is a big hurdle; to leap over it you
have to create the program text . . . and Java
somewhere, compile it successfully, load it, public class helloworld{
run it, and find out where your output public static void main(String[] args)
went. With these mechanical details {
System.out.println("hello, world");
mastered, everything else is comparatively
}
easy }
Madhavan Mukund A first taste of Java Programming Concepts using Java 2/9
Why so complicated?

Let’s unpack the syntax public class helloworld{


All code in Java lives within a class public static void main(String[] args)

No free floating functions, unlike {


Python and other languages System.out.println("hello, world");
}
Modifier public specifies visibility }
How does the program start?
Fix a function name that will be
called by default
From C, the convention is to call
this function main()

Madhavan Mukund A first taste of Java Programming Concepts using Java 3/9

Why so complicated . . .

Need to specify input and output public class helloworld{


types for main()
public static void main(String[] args)
The signature of main()
{
Input parameter is an array of System.out.println("hello, world");
strings; command line arguments }
No output, so return type is void }

Visibility
Function has be available to run
from outside the class
Modifier public

Madhavan Mukund A first taste of Java Programming Concepts using Java 4/9
Why so complicated . . .

Availability public class helloworld{


Functions defined inside classes are public static void main(String[] args)
attached to objects
{
How can we create an object before System.out.println("hello, world");
starting? }
Modifier static — function that }
exists independent of dynamic
creation of objects

Madhavan Mukund A first taste of Java Programming Concepts using Java 5/9

Why so complicated . . .
The actual operation
System is a public class public class helloworld{
out is a stream object defined in public static void main(String[] args)
System {
System.out.println("hello, world");
Like a file handle
Note that out must also be
}
static }

println() is a method associated


with streams
Prints argument with a newline,
like Python print()

Punctuation {, }, ; to delimit blocks, statements


Unlike layout and indentation in Python

Madhavan Mukund A first taste of Java Programming Concepts using Java 6/9
Compiling and running Java code

A Java program is a collection of public class helloworld{


classes public static void main(String[] args)
{
Each class is defined in a separate file
System.out.println("hello, world");
with the same name, with extension }
java }
Class helloworld in
helloworld.java

Java programs are usually interpreted on Java Virtual Machine (JVM)


JVM provides a uniform execution environment across operating systems
Semantics of Java is defined in terms of JVM, OS-independent
“Write once, run anywhere”

Madhavan Mukund A first taste of Java Programming Concepts using Java 7/9

Compiling and running Java code


javac compiles into JVM bytecode
javac helloworld.java creates public class helloworld{
bytecode file helloworld.class public static void main(String[] args)
{
java helloworld interprets and System.out.println("hello, world");
runs bytecode in helloworld.class }
}
Note:
javac requires file extension .java
java should not be provided file extension .class
javac automatically follows dependencies and compiles all classes required
Sufficient to trigger compilation for class containing main()

Madhavan Mukund A first taste of Java Programming Concepts using Java 8/9
Scalar types
In an object-oriented language, all data should be
encapsulated as objects
Type Size in bytes
However, this is cumbersome int 4
Useful to manipulate numeric values like long 8
conventional languages short 2
Java has eight primitive scalar types byte 1
float 4
int, long, short, byte
double 8
float, double char 2
char boolean 1
boolean

Size of each type is fixed by JVM 2-byte char for Unicode


Does not depend on native architecture

Madhavan Mukund Basic datatypes in Java Programming Concepts using Java 2/8

Declarations, assigning values

We declare variables before we use them Characters are written with


int x, y; single-quotes (only)
double y; char c,d;
char c;
boolean b1, b2; c = ’x’;
Note the semicolons after each d = ’\u03C0’; // Greek pi, unicode
statement Double quotes denote strings
The assignment statement works as Boolean constants are true, false
usual
boolean b1, b2;
int x,y;
x = 5; b1 = false;
y = 7; b2 = true;

Madhavan Mukund Basic datatypes in Java Programming Concepts using Java 3/8
Initialization, constants

Declarations can come anywhere Can we declare a value to be a


int x; constant?
x = 10; float pi = 3.1415927f;
double y;
Use this judiciously to retain pi = 22/7; // Disallow?
readability Note: Append f after number for
Initialize at time of declaration float, else interpreted as double

int x = 10; Modifier final indicates a constant


double y = 5.7; final float pi = 3.1415927f;

pi = 22/7; // Flagged as error;

Madhavan Mukund Basic datatypes in Java Programming Concepts using Java 4/8

Operators, shortcuts, type casting

Arithmetic operators are the usual ones Special operators for incrementing and
+, -, *, /, % decrementing integers
int a = 0, b = 10;
No separate integer division operator // a++; // Same as a = a+1
When both arguments are integer, / is b--; // Same as b = b-1
integer division Shortcut for updating a variable
float f = 22/7; // Value is 3.0
int a = 0, b = 10;
Note implicit conversion from int to a += 7; // Same as a = a+7
float b *= 12; // Same as b = b*12

No exponentiation operater, use


Math.pow()
Math.pow(a,n) returns an
Madhavan Mukund Basic datatypes in Java Programming Concepts using Java 5/8
Strings
String is a built in class Strings are not arrays of characters
String s,t; Cannot write
s[3] = ’p’;
String constants enclosed in double s[4] = ’!’;
quotes
Instead, invoke method substring in
String s = "Hello", t = "world";
class String
+ is overloaded for string concatenation s = s.substring(0,3) + "p!";
String s = "Hello";
If we change a String, we get a new
String t = "world";
String u = s + " " + t; object
// "Hello world" After the update, s points to a new
String
Java does automatic garbage
collection
Madhavan Mukund Basic datatypes in Java Programming Concepts using Java 6/8

Arrays
Arrays are also objects Size of the array can vary
Typical declaration Array constants: {v1, v2, v3}
int[] a;
a = new int[100]; For example

Or int a[] instead of int[] a int[] a;


int n;
Combine as int[] a = new
int[100]; n = 10;
a = new int[n];
a.length gives size of a
Note, for String, it is a method n = 20;
s.length()! a = new int[n];

Array indices run from 0 to a.length-1 a = {2, 3, 5, 7, 11};

Madhavan Mukund Basic datatypes in Java Programming Concepts using Java 7/8
Control flow
Program layout
Statements end with semi-colon
Blocks of statements delimited by braces

Conditional execution
if (condition) { ... } else { ... }

Conditional loops
while (condition) { ... }
do { ... } while (condition)

Iteration
Two kinds of for

Multiway branching – switch

Madhavan Mukund Control flow in Java Programming Concepts using Java 2/9

Conditional execution
if (c) {...} else {...}
else is optional public class MyClass {
Condition must be in parentheses
...
If body is a single statement, braces are not
needed public static int sign(int v) {
if (v < 0) {
No elif, à la Python return(-1);
Indentation is not forced } else if (v > 0) {
Just align else if return(1);
} else {
Nested if is a single statement, no separate return(0);
braces required }
}
No surprises
Aside: no def for function definition }

Madhavan Mukund Control flow in Java Programming Concepts using Java 3/9
Conditional loops
while (c) {...}
Condition must be in parentheses public class MyClass {
If body is a single statement, braces are not
...
needed
public static int sumupto(int n) {
int sum = 0;

while (n > 0){


sum += n;
n--;
}

return(sum);
}

}
Madhavan Mukund Control flow in Java Programming Concepts using Java 4/9

Conditional loops
while (c) {...}
Condition must be in parentheses public class MyClass {
If body is a single statement, braces are not
...
needed

do {...} while (c) public static int sumupto(int n) {


int sum = 0;
Condition is checked at the end of the loop int i = 0;
At least one iteration
Useful for interactive user input do {
sum += i;
do { i++;
read input; } while (i <= n);
} while (input-condition);
return(sum);
}

Madhavan Mukund Control flow in Java } Programming Concepts using Java 4/9
Iteration
for loop is inherited from C
for (init; cond; upd) {...} public class MyClass {

init is initialization ...


cond is terminating condition
public static int sumarray(int[] a) {
upd is update
int sum = 0;
Intended use is int n = a.length;
int i;
for(i = 0; i < n; i++){...}
Completely equivalent to for (i = 0; i < n; i++){
sum += a[i];
i = 0;
}
while (i < n) {
i++;
return(sum);
}
}

Madhavan Mukund }
Control flow in Java Programming Concepts using Java 5/9

Iteration
Intended use is
for(i = 0; i < n; i++){...} public class MyClass {
Completely equivalent to
...
i = 0;
while (i < n) { public static int sumarray(int[] a) {
i++; int sum = 0;
} int n = a.length;
However, not good style to write for for (int i = 0; i < n; i++){
instead of while sum += a[i];
}
Can define loop variable within loop
The scope of i is local to the loop return(sum);
An instance of more general local }
scoping allowed in Java
}
Madhavan Mukund Control flow in Java Programming Concepts using Java 6/9
Iterating over elements directly
Java later introduced a for in the style of
Python public class MyClass {
for x in l:
do something with x ...

Again for, different syntax public static int sumarray(int[] a) {


for (type x : a) int sum = 0;
do something with x; int n = a.length;
}
for (int v : a){
It appears that loop variable must be sum += v;
declared in local scope for this version of }
for
return(sum);
}

Madhavan Mukund }
Control flow in Java Programming Concepts using Java 7/9

Multiway branching
switch selects between different public static void printsign(int v) {
options switch (v) {
case -1: {
Be careful, default is to “fall System.out.println("Negative");
through” from one case to the next break;
}
Need to explicitly break out of
case 1: {
switch
System.out.println("Positive");
break available for loops as well break;
Check the Java documentation }
case 0: {
Options have to be constants System.out.println("Zero");
Cannot use conditional expressions break;
}
Aside: here return type is void }
Non-void return type requires an }
appropriate return value
Madhavan Mukund Control flow in Java Programming Concepts using Java 8/9
Classes and objects

A class is a template for an encapsulated type


An object is an instance of a class
How do we create objects?
How are objects initialized?

Madhavan Mukund Defining classes and objects in Java Programming Concepts using Java 2/8

Defining a class
Definition block using class, with class name
Modifier public to indicate visibility public class Date {
Java allows public to be omitted private int day, month, year;
Default visibility is public to package
Packages are administrative units of code ...

All classes defined in same directory form part }


of same package

Instance variables
Each concrete object of type Date will have
local copies of date, month, year
These are marked private
Can also have public instance variables, but
breaks encapsulation
Madhavan Mukund Defining classes and objects in Java Programming Concepts using Java 3/8
Creating objects
public void UseDate() {
Declare type using class name Date d;
d = new Date();
new creates a new object ...
}
How do we set the instance variables?

Can add methods to update values public class Date {


this is a reference to current object private int day, month, year;
Can omit this if reference is unambiguous
public void setDate(int d, int m,
int y){
day = d;
month = m;
year = y;
}
}

Madhavan Mukund Defining classes and objects in Java Programming Concepts using Java 4/8

Creating objects
public class Date {
Declare type using class name ...

new creates a new object public int getDay(){


return(day);
How do we set the instance variables?
}
Can add methods to update values
public int getMonth(){
this is a reference to current object return(month);
Can omit this if reference is unambiguous }

What if we want to check the values? public int getYear(){


Methods to read and report values return(year);
}
Accessor and Mutator methods
}

Madhavan Mukund Defining classes and objects in Java Programming Concepts using Java 4/8
Initializing objects
Would be good to set up an object when we public class Date {
create it private int day, month, year;

Combine new Date() and setDate() public Date(int d, int m, int y){
day = d;
Constructors — special functions called when month = m;
an object is created year = y;
Function with the same name as the class }
d = new Date(13,8,2015);
public Date(int d, int m){
Constructors with different signatures day = d;
month = m;
d = new Date(13,8); sets year to 2021 year = 2021;
Java allows function overloading — same }
name, different signatures }
Python: default (optional) arguments, no
overloading
Madhavan Mukund Defining classes and objects in Java Programming Concepts using Java 5/8

Constructors . . .
A later constructor can call an earlier one using public class Date {
this private int day, month, year;

If no constructor is defined, Java provides a public Date(int d, int m, int y){


default constructor with empty arguments day = d;
month = m;
new Date() would implicitly invoke this year = y;
Sets instance variables to sensible defaults }
For instance, int variables set to 0
public Date(int d, int m){
Only valid if no constructor is defined this(d,m,2021);
Otherwise need an explicit constructor without }
arguments }

Madhavan Mukund Defining classes and objects in Java Programming Concepts using Java 6/8
Copy constructors
Create a new object from an existing one public class Date {
private int day, month, year;
Copy constructor takes an object of the same
type as argument public Date(Date d){
this.day = d.day;
Copies the instance variables this.month = d.month;
Use object name to disambiguate which this.year = d.year;
instance variables we are talking about }
Note that private instance variables of }
argument are visible
public void UseDate() {
Shallow copy vs deep copy Date d1,d2;
Want new object to be disjoint from old one d1 = new Date(12,4,1954);
d2 = new.Date(d1);
If instance variable are objects, we may end up
}
aliasing rather than copying
Discuss later — cloning objects
Madhavan Mukund Defining classes and objects in Java Programming Concepts using Java 7/8

Interacting with a Java program

We have seen how to print data


System.out.println("hello, world");

How do we read data

Madhavan Mukund Basic input and output in Java Programming Concepts using Java 2/4
Reading input

Simplest to use is the Console class Console cons = System.console();


Functionality similar to Python String username =
input() cons.readLine("User name: ");
char[] passwd =
Defined within System cons.readPassword("Password: ");
Two methods, readLine and
readPassword More general Scanner class
readPassword does not echo Allows more granular reading of input
characters on the screen Read a full line, or read an integer, . . .
readLine returns a string (like
Python input()) Scanner in = new Scanner(System.in);
readPassword returns an array of String name = in.nextLine();
char — for security reasons int age = in.nextInt();
....

Madhavan Mukund Basic input and output in Java Programming Concepts using Java 3/4

Generating output

System.out.println(arg) prints arg and goes


to a new line
Implicitly converts argument to a string

System.out.print(arg) is similar, but does not


advance to a new line
System.out.printf(arg) generates formatted
output
Same conventions as printf in C
Read the documentation

Madhavan Mukund Basic input and output in Java Programming Concepts using Java 4/4
Algorithms + Data Structures = Programs

Title of Niklaus Wirth’s introduction to Pascal


Traditionally, algorithms come first
Structured programming
Design a set of procedures for specific tasks
Combine them to build complex systems

Data representation comes later


Design data structures to suit procedural manipulations

Madhavan Mukund The philosophy of OO programming Programming Concepts using Java 2/7

Object Oriented design

Reverse the focus


First identify the data we want to maintain and manipulate
Then identify algorithms to operate on the data
Claim: works better for large systems
Example: simple web browser
2000 procedures manipulating global data
. . . vs 100 classes, each with about 20 methods
Much easier to grasp the design
Debugging: an object is in an incorrect state
Search among 20 methods rather than 2000 procedures

Madhavan Mukund The philosophy of OO programming Programming Concepts using Java 3/7
Object Oriented design: Example

An order processing system typically involves


Items
Orders
Shipping addresses
Payments
Accounts

What happens to these objects?


Items are added to orders
Orders are shipped, cancelled
Payments are accepted, rejected

Nouns signify objects, verbs denote methods that operate on objects


Associate with each order, a method to add an item

Madhavan Mukund The philosophy of OO programming Programming Concepts using Java 4/7

Designing objects

Behaviour — what methods do we need to operate on objects?


State — how does the object react when methods are invoked?
State is the information in the instance variables
Encapsulation — should not change unless a method operates on it

Identity — distinguish between different objects of the same class


State may be the same — two orders may contain the same item

These features interact


State will typically affect behaviour
Cannot add an item to an order that has been shipped
Cannot ship an empty order

Madhavan Mukund The philosophy of OO programming Programming Concepts using Java 5/7
Relationship between classes

Dependence
Order needs Account to check credit status
Item does not depend on Account
Robust design minimizes dependencies, or coupling between classes

Aggregation
Order contains Item objects

Inheritance
One object is a specialized versions of another
ExpressOrder inherits from Order
Extra methods to compute shipping charges, priority handling

Madhavan Mukund The philosophy of OO programming Programming Concepts using Java 6/7

A Java class
public class Employee{
An Employee class private String name;
private double salary;
Two private instance variables
// Some Constructors ...
Some constructors to set up the
// "mutator" methods
object public boolean setName(String s){ ... }
public boolean setSalary(double x){ ... }
Accessor and mutator methods to set
instance variables // "accessor" methods
public String getName(){ ... }
A public method to compute bonus public double getSalary(){ ... }

// other methods
public double bonus(float percent){
return (percent/100.0)*salary;
}
}
Madhavan Mukund Subclasses and inheritance Programming Concepts using Java 2/6
Subclasses

Managers are special types of employees with extra features


public class Manager extends Employee{
private String secretary;
public boolean setSecretary(name s){ ... }
public String getSecretary(){ ... }
}

Manager objects inherit other fields and methods from Employee


Every Manager has a name, salary and methods to access and manipulate these.

Manager is a subclass of Employee


Think of subset

Madhavan Mukund Subclasses and inheritance Programming Concepts using Java 3/6

Subclasses
Manager objects do not public class Employee{
automatically have access to private ...
public Employee(String n, double s){
data of parent class. name = n; salary = s;
Common to extend a parent class }
written by someone else public Employee(String n){
this(n,500.00);
How can a constructor for Manager }
set instance variables that are private }
to Employee?
public class Manager extends Employee{
Some constructors for Employee ..
public Manager(String n, double s, String sn){
Use parent class’s constructor using super(n,s); /* super calls
super Employee constructor */
secretary = sn;
A constructor for Manager }
}
Madhavan Mukund Subclasses and inheritance Programming Concepts using Java 4/6
Inheritance

In general, subclass has more features Recall


than parent class int[] a = new int[100];
Subclass inherits instance variables, Why the seemingly redundant
methods from parent class reference to int in new?
Every Manager is an Employee, but not One can now presumably write
vice versa! Employee[] e = new Manager(...)[100]

Can use a subclass in place of a


superclass
Employee e = new Manager(...)

But the following will not work


Manager m = new Employee(...)

Madhavan Mukund Subclasses and inheritance Programming Concepts using Java 5/6

Subclasses and inheritance


public class Employee{
A subclass extends a parent class private String name;
private double salary;
Subclass inherits instance variables
public boolean setName(String s){ ... }
and methods from the parent class public boolean setSalary(double x){ ... }
public String getName(){ ... }
Subclasses cannot see private public double getSalary(){ ... }
components of parent class
public double bonus(float percent){
Subclass can add more instance return (percent/100.0)*salary;
variables and methods }
}
Can also override methods
public class Manager extends Employee{
private String secretary;
public boolean setSecretary(name s){ ... }
public String getSecretary(){ ... }
}
Madhavan Mukund Dynamic dispatch and polymorphism Programming Concepts using Java 2/8
Dynamic dispatch
Manager can redefine bonus() What about e.bonus(p)? Which
double bonus(float percent){ bonus() do we use?
return 1.5*super.bonus(percent); Static: Use Employee.bonus()
}
Dynamic: Use Manager.bonus()
Uses parent class bonus() via super
Dynamic dispatch (dynamic binding,
Overrides definition in parent class late method binding, . . . ) turns out to
Consider the following assignment be more useful
Default in Java, optional in languages
Employee e = new Manager(...)
like C++ (virtual function)
Can we invoke e.setSecretary()?
e is declared to be an Employee
Static typechecking — e can only
refer to methods in Employee
Madhavan Mukund Dynamic dispatch and polymorphism Programming Concepts using Java 3/8

Polymorphism

Every Employee in emparray Q := make-queue(first event)


“knows” how to calculate its bonus repeat
correctly! remove next event e from Q
simulate e
Recall the event simulation loop that place all events generated
motivated Simula to introduce by e on Q
objects until Q is empty

Madhavan Mukund Dynamic dispatch and polymorphism Programming Concepts using Java 4/8
Polymorphism

Every Employee in emparray Employee[] emparray = new Employee[2];


“knows” how to calculate its bonus Employee e = new Employee(...);
correctly! Manager e = new Manager(...);
Recall the event simulation loop that emparray[0] = e;
motivated Simula to introduce emparray[1] = m;
objects
for (i = 0; i < emparray.length; i++){
Also referred to as runtime System.out.println(emparray[i].bonus(5.0);
polymorphism or inheritance }
polymorphism

Madhavan Mukund Dynamic dispatch and polymorphism Programming Concepts using Java 4/8

Functions, signatures and overloading

Signature of a function is its name and double[] darr = new double[100];


the list of argument types int[] iarr = new int[500];
...
Can have different functions with the Arrays.sort(darr);
same name and different signatures // sorts contents of darr
Arrays.sort(iarr);
For example, multiple constructors // sorts contents of iarr
Java class Arrays has a method sort
to sort arbitrary scalar arrays class Arrays{
...
Made possible by overloaded methods public static void sort(double[] a){..}
defined in class Arrays // sorts arrays of double[]
public static void sort(int[] a){..}
// sorts arrays of int[]
...
}
Madhavan Mukund Dynamic dispatch and polymorphism Programming Concepts using Java 5/8
Functions, signatures and overloading

Overloading: multiple methods, double[] darr = new double[100];


different signatures, choice is static int[] iarr = new int[500];
...
Overriding: multiple methods, same Arrays.sort(darr);
signature, choice is static // sorts contents of darr
Arrays.sort(iarr);
Employee.bonus() // sorts contents of iarr
Manager.bonus()

Dynamic dispatch: multiple methods, class Arrays{


...
same signature, choice made at
public static void sort(double[] a){..}
run-time // sorts arrays of double[]
public static void sort(int[] a){..}
// sorts arrays of int[]
...
}
Madhavan Mukund Dynamic dispatch and polymorphism Programming Concepts using Java 6/8

Type casting

Consider the following assignment Can test if e is a Manager


Employee e = new Manager(...) if (e instanceof Manager){
((Manager) e).setSecretary(s);
Can we get e.setSecretary() to }
work?
A simple example of reflection in Java
Static type-checking disallows this
“Think about oneself”
Type casting — convert e to Manager
((Manager) e).setSecretary(s) Can also use type casting for basic
types
Cast fails (error at run time) if e is not
double d = 29.98;
a Manager int nd = (int) d;

Madhavan Mukund Dynamic dispatch and polymorphism Programming Concepts using Java 7/8
Multiple inheritance

C1 C2
public int f(); public int f();

C3 extends C1,C2

Can a subclass extend multiple parent classes?


If f() is not overridden, which f() do we use in C3?
Java does not allow multiple inheritance
C++ allows this if C1 and C2 have no conflict

Madhavan Mukund The Java class hierarchy Programming Concepts using Java 2/7

Java class hierarchy

No multiple inheritance — tree-like


In fact, there is a universal superclass Object
Useful methods defined in Object
public boolean equals(Object o) // defaults to pointer equality

public String toString() // converts the values of the


// 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()

Madhavan Mukund The Java class hierarchy Programming Concepts using Java 3/7
Java class hierarchy

Can exploit the tree structure to write generic functions


Example: search for an element in an array
public int find (Object[] objarr, Object o){
int i;
for (i = 0; i < objarr.length(); i++){
if (objarr[i] == o) {return i};
}
return (-1);
}

Recall that == is pointer equality, by default


If a class overrides equals(), dynamic dispatch will use the redefined function
instead of Object.equals() for objarr[i] == o

Madhavan Mukund The Java class hierarchy Programming Concepts using Java 4/7

Overriding functions

For instance, a class Date with instance Should write, instead


variables day, month and year public boolean equals(Object d){
if (d instanceof Date){
May wish to override equals() to
Date myd = (Date) d;
compare the object state, as follows return ((this.day == myd.day) &&
public boolean equals(Date d){ (this.month == myd.month)
return ((this.day == d.day) && (this.year == myd.year));
(this.month == d.month) && }
(this.year == d.year)); return(false);
} }

Note the run-time type check and the


Unfortunately,
cast
boolean equals(Date d)
does not override
boolean equals(Object o)!
Madhavan Mukund The Java class hierarchy Programming Concepts using Java 5/7
Overriding functions

Overriding looks for “closest” match


Suppose we have public boolean equals(Employee e) but no equals() in
Manager
Consider
Manager m1 = new Manager(...);
Manager m2 = new Manager(...);
...
if (m1.equals(m2)){ ... }

public boolean equals(Manager m) is compatible with both


boolean equals(Employee e) and boolean equals(Object o)
Use boolean equals(Employee e)

Madhavan Mukund The Java class hierarchy Programming Concepts using Java 6/7

Subclasses, subtyping and inheritance

Class hierarchy provides both subtyping and inheritance


Subtyping
Capabilities of the subtype are a superset of the main type
If B is a subtype of A, wherever we require an object of type A, we can use an object of
type B
Employee e = new Manager(...); is legal

Inheritance
Subtype can reuse code of the main type
B inherits from A if some functions for B are written in terms of functions of A
Manager.bonus() uses Employee.bonus()

Madhavan Mukund Subtyping vs inheritance Programming Concepts using Java 2/4


Subtyping vs inheritance
Recall the following example
queue, with methods insert-rear, delete-front
stack, with methods insert-front, delete-front
deque, with methods insert-front, delete-front, insert-rear, delete-rear

What are the subtype and inheritance relationships between these classes?
Subtyping
deque has more functionality than queue or stack
deque is a subtype of both these types

Inheritance
Can suppress two functions in a deque and use it as a queue or stack
Both queue and stack inherit from deque

Madhavan Mukund Subtyping vs inheritance Programming Concepts using Java 3/4

Subclasses, subtyping and inheritance

Class hierarchy represents both subtyping and inheritance


Subtyping
Compatibility of interfaces.
B is a subtype of A if every function that can be invoked on an object of type A can
also be invoked on an object of type B.

Inheritance
Reuse of implementations.
B inherits from A if some functions for B are written in terms of functions of A.

Using one idea (hierarchy of classes) to implement both concepts blurs the
distinction between the two

Madhavan Mukund Subtyping vs inheritance Programming Concepts using Java 4/4


Modifiers in Java

Java uses many modifiers in declarations, to cover different features of


object-oriented programming
public vs private to support encapsulation of data
static, for entities defined inside classes that exist without creating objects of the
class
final, for values that cannot be changed
These modifiers can be applied to classes, instance variables and methods
Let’s look at some examples of situations where different combinations make sense

Madhavan Mukund Java modifiers Programming Concepts using Java 2/8

public vs private
Faithful implementation of public class Stack {
private int[] values; // array of values
encapsulation necessitates modifiers private int tos; // top of stack
public and private private int size; // values.length
Typically, instance variables are
/* Constructors to set up values array */
private
Methods to query (accessor) and public void push (int i){
update (mutator) the state are public ....
}
Can private methods make sense?
public int pop (){
Example: a Stack class ...
Data stored in a private array }

Public methods to push, pop, query if public boolean is_empty (){


empty return (tos == 0);
}
}
Madhavan Mukund Java modifiers Programming Concepts using Java 3/8
private methods
Example: a Stack class public class Stack {
...
Data stored in a private array public void push (int i){
Public methods to push, pop, query if if (tos < size){
empty values[tos] = i;
tos = tos+1;
push() needs to check if stack has }else{
space // Deal with stack overflow
}
...
}
...
}

Madhavan Mukund Java modifiers Programming Concepts using Java 4/8

private methods
Example: a Stack class public class Stack {
...
Data stored in a private array public void push (int i){
Public methods to push, pop, query if if (stack_full()){
empty extend_stack();
}
push() needs to check if stack has ... // Usual push operations
space }
...
Deal gracefully with stack overflow private boolean stack_full(){
return(tos == size);
private methods invoked from within }
push() to check if stack is full and
expand storage private void extend_stack(){
/* Allocate additional space,
reset size etc */
}
}

Madhavan Mukund Java modifiers Programming Concepts using Java 4/8


Accessor and mutator methods

Public methods to query and update public class Date {


private instance variables private int day, month year;

Date class public void getDay(int d) {...}


Private instance variables day, month, public void getMonth(int m) {...}
year public void getYear(int y) {...}

One public accessor/mutator method public void setDay(int d) {...}


per instance variable public void setMonth(int m) {...}
public void setYear(int y) {...}
Inconsistent updates are now possible }
Separately set invalid combinations of
day and month

Madhavan Mukund Java modifiers Programming Concepts using Java 5/8

Accessor and mutator methods

Public methods to query and update public class Date {


private instance variables private int day, month year;

Date class public void getDay(int d) {...}


Private instance variables day, month, public void getMonth(int m) {...}
year public void getYear(int y) {...}

One public accessor/mutator method public void setDate(int d, int m, int y) {


per instance variable ...
// Validate d-m-y combination
Inconsistent updates are now possible }
Separately set invalid combinations of
}
day and month

Instead, allow only combined update

Madhavan Mukund Java modifiers Programming Concepts using Java 5/8


static components
public class Order {
Use static for components that exist private static int lastorderid = 0;
without creating objects
private int orderid;
Library functions, main(), . . .
....
Useful constants like Math.PI,
Integer.MAX VALUE public Order(...) {
lastorderid++;
These static components are also orderid = lastorderid;
public ...
}
Do private static components make
sense? lastorderid is private static field
Internal constants for bookkeeping Common to all objects in the class
Constructor sets unique id for each
order Be careful about concurrent updates!
Madhavan Mukund Java modifiers Programming Concepts using Java 6/8

final components

final denotes that a value cannot be updated


Usually used for constants (public and static instance variables)
Math.PI, Integer.MAX VALUE

What would final mean for a method?


Cannot redefine functions at run-time, unlike Python!

Recall overriding
Subclass redefines a method available with the same signature in the parent class

A final method cannot be overridden

Madhavan Mukund Java modifiers Programming Concepts using Java 7/8


Grouping together classes
Sometimes we collect together classes under a common heading
Classes Circle, Square and Rectangle are all shapes
Create a class Shape so that Circle, Square and Rectangle extend Shape
We want to force every Shape to define a function
public double perimeter()
Could define a function in Shape that returns an absurd value
public double perimeter() { return(-1.0); }
Rely on the subclass to redefine this function
What if this doesn’t happen?
Should not depend on programmer discipline

Madhavan Mukund Abstract classes and interfaces Programming Concepts using Java 2/8

Abstract classes

A better solution
Provide an abstract definition in Shape
public abstract double perimeter();

Forces subclasses to provide a concrete implementation


Cannot create objects from a class that has abstract functions
Shape must itself be declared to be abstract
public abstract class Shape{
...
public abstract double perimeter();
...
}

Madhavan Mukund Abstract classes and interfaces Programming Concepts using Java 3/8
Abstract classes . . .

Can still declare variables whose type is an abstract class


Shape shapearr[] = new Shape[3];
int sizearr[] = new int[3];

shapearr[0] = new Circle(...);


shapearr[1] = new Square(...);
shapearr[2] = new Rectangle(...);

for (i = 0; i < 2; i++){


sizearr[i] = shapearr[i].perimeter();
// each shapearr[i] calls the appropriate method
...
}

Madhavan Mukund Abstract classes and interfaces Programming Concepts using Java 4/8

Generic functions
Use abstract classes to specify generic properties
public abstract class Comparable{
public abstract int cmp(Comparable s);
// return -1 if this < s,
// 0 if this == 0,
// +1 if this > s
}

Now we can sort any array of objects that extend Comparable


public class SortFunctions{
public static void quicksort(Comparable[] a){
...
// Usual code for quicksort, except that
// to compare a[i] and a[j] we use a[i].cmp(a[j])
}
}
Madhavan Mukund Abstract classes and interfaces Programming Concepts using Java 5/8
Generic functions . . .
public class SortFunctions{
public static void quicksort(Comparable[] a){
...
}
}

To use this definition of quicksort, we write


public class Myclass extends Comparable{
private double size; // quantity used for comparison

public int cmp(Comparable s){


if (s instanceof Myclass){
// compare this.size and ((Myclass) s).size
// Note the cast to access s.size
}
}
}
Madhavan Mukund Abstract classes and interfaces Programming Concepts using Java 6/8

Mutiple inheritance
Can we sort Circle objects using the generic functions in SortFunctions?
Circle already extends Shape
Java does not allow Circle to also extend Comparable!
An interface is an abstract class with no concrete components
public interface Comparable{
public abstract int cmp(Comparable s);
}
A class that extends an interface is said to implement it:
public class Circle extends Shape implements Comparable{
public double perimeter(){...}
public int cmp(Comparable s){...}
...
}
Can extend only one class, but can implement multiple interfaces
Madhavan Mukund Abstract classes and interfaces Programming Concepts using Java 7/8
Interfaces

An interface is a purely abstract class


All methods are abstract

A class implements an interface


Provide concrete code for each abstract function

Classes can implement multiple interfaces


Abstract functions, so no contradictory inheritance

Interfaces describe relevant aspects of a class


Abstract functions describe a specific “slice” of capabilities
Another class only needs to know about these capabilities

Madhavan Mukund Interfaces Programming Concepts using Java 2/6

Exposing limited capabilities


Generic quicksort for any datatype
that supports comparisons public class SortFunctions{
public static void quicksort(Comparable[] a){
Express this capability by making the ...
argument type Comparable[] // Usual code for quicksort, except that
// to compare a[i] and a[j] we use
Only information that quicksort // a[i].cmp(a[j])
needs about the underlying type }
All other aspects are irrelevant }

Describe the relevant functions public interface Comparable{


supported by Comparable objects public abstract int cmp(Comparable s);
through an interface // return -1 if this < s,
// 0 if this == 0,
However, we cannot express the // +1 if this > s
intended behaviour of cmp explicitly }

Madhavan Mukund Interfaces Programming Concepts using Java 3/6


Adding methods to interfaces
Java interfaces extended to allow
functions to be added public interface Comparable{
public static String cmpdoc(){
Static functions String s;
s = "Return -1 if this < s, ";
Cannot access instance variables
s = s + "0 if this == s, ";
Invoke directly or using interface s = s + "+1 if this > s.";
name: Comparable.cmpdoc() return(s);
}
Default functions
Provide a default implementation public interface Comparable{
for some functions public default int cmp(Comparable s) {
return(0);
Class can override these }
Invoke like normal method, using }
object name: a[i].cmp(a[j])

Madhavan Mukund Interfaces Programming Concepts using Java 4/6

Dealing with conflicts


Old problem of multiple inheritance public interface Person{
public default String getName() {
returns return("No name");
Conflict between static/default }
methods }

Subclass must provide a fresh public interface Designation{


public default String getName() {
implementation
return("No designation");
}
}

public class Employee


implements Person, Designation {
...

public String getName(){


...
}
Madhavan Mukund }
Interfaces Programming Concepts using Java 5/6
Dealing with conflicts
Old problem of multiple inheritance public class Person{
public String getName() {
returns return("No name");
Conflict between static/default }
methods }

Subclass must provide a fresh public interface Designation{


public default String getName() {
implementation
return("No designation");
}
Conflict could be between a class and }
an interface
public class Employee
Employee inherits from class Person
extends Person implements Designation {
and implements Designation
...
Method inherited from the class }
“wins”
Motivated by reverse compatibility
Madhavan Mukund Interfaces Programming Concepts using Java 5/6

Nested objects

An instance variable can be a user public class Employee{


defined type private String name;
Employee uses Date private double salary;
private Date joindate;
Date is a public class, also available
...
to other classes
}
When could a private class make
sense? public class Date {
private int day, month year;

...
}

Madhavan Mukund Private classes Programming Concepts using Java 2/4


Nested objects
public class Node {
LinkedList is built using Node public Object data;
public Node next;
Why should Node be public? ...
May want to enhance with prev }
field, doubly linked list
public class LinkedList{
Does not affect interface of private int size;
LinkedList private Node first;

public Object head(){


Object returnval = null;
if (first != null){
returnval = first.data;
first = first.next;
}
return(returnval);
}
}
Madhavan Mukund Private classes Programming Concepts using Java 3/4

public void insert(Object newdata){


...
}

Nested objects
public class LinkedList{
LinkedList is built using Node private int size;
private Node first;
Why should Node be public?
May want to enhance with prev public Object head(){ ... }
field, doubly linked list
public void insert(Object newdata){
Does not affect interface of ...
LinkedList }

Instead, make Node a private class private class Node {


public Object data;
Nested within LinkedList
public Node next;
Also called an inner class ...
}
Objects of private class can see }
private components of enclosing class

Madhavan Mukund Private classes Programming Concepts using Java 3/4


Manipulating objects

Encapsulation is a key principle of public class Date {


object oriented programming private int day, month year;
Internal data is private
public void getDay(int d) {...}
Access to the data is regulated public void getMonth(int m) {...}
through public methods public void getYear(int y) {...}
Accessor and mutator methods
public void setDay(int d) {...}
Can ensure data integrity by regulating public void setMonth(int m) {...}
public void setYear(int y) {...}
access }

Madhavan Mukund Controlled interaction with objects Programming Concepts using Java 2/6

Manipulating objects

Encapsulation is a key principle of public class Date {


object oriented programming private int day, month year;
Internal data is private
public void getDay(int d) {...}
Access to the data is regulated public void getMonth(int m) {...}
through public methods public void getYear(int y) {...}
Accessor and mutator methods
public void setDate(int d, int m, int y) {
Can ensure data integrity by regulating ...
// Validate d-m-y combination
access }
Update date as a whole, rather than }
individual components
Does this provide sufficient control?

Madhavan Mukund Controlled interaction with objects Programming Concepts using Java 2/6
Querying a database

Object stores train reservation public class RailwayBooking {


information private BookingDB railwaydb;
Can query availability for a given train,
public int getStatus(int trainno, Date d) {
date
// Return number of seats available
To control spamming by bots, require // on train number trainno on date d
...
user to log in before querying }
}
Need to connect the query to the
logged in status of the user
“Interaction with state”

Madhavan Mukund Controlled interaction with objects Programming Concepts using Java 3/6

Querying a database
public class RailwayBooking {
Need to connect the query to the private BookingDB railwaydb;
logged in status of the user
public QueryObject login(String u, String p){
Use objects! QueryObject qobj;
if (valid_login(u,p)) {
On log in, user receives an object that qobj = new QueryObject();
can make a query return(qobj);
Object is created from private class }
that can look up railwaydb }

How does user know the capabilities of private class QueryObject {


public int getStatus(int trainno, Date d) {
private class QueryObject?
// Return number of seats available
// on train number trainno on date d
...
}
}
}

Madhavan Mukund Controlled interaction with objects Programming Concepts using Java 4/6
Querying a database
public interface QIF{
Need to connect the query to the public abstract int
logged in status of the user getStatus(int trainno, Date d);
}
Use objects!
public class RailwayBooking {
On log in, user receives an object that private BookingDB railwaydb;
can make a query public QIF login(String u, String p){
Object is created from private class QueryObject qobj;
that can look up railwaydb if (valid_login(u,p)) {
qobj = new QueryObject();
How does user know the capabilities of return(qobj);
}
private class QueryObject?
}
private class QueryObject implements QIF {
Use an interface!
public int getStatus(int trainno, Date d){
Interface describes the capability of ...
the object returned on login }
}
}
Madhavan Mukund Controlled interaction with objects Programming Concepts using Java 4/6

Querying a database
public class RailwayBooking {
Query object allows unlimited number private BookingDB railwaydb;
of queries public QIF login(String u, String p){
QueryObject qobj;
Limit the number of queries per login? if (valid_login(u,p)) {
qobj = new QueryObject();
Maintain a counter return(qobj);
}
Add instance variables to object }
returned on login private class QueryObject implements QIF {
Query object can remember the state private int numqueries;
of the interaction private static int QLIM;

public int getStatus(int trainno, Date d){


if (numqueries < QLIM){
// respond, increment numqueries
}
}
}
}
Madhavan Mukund Controlled interaction with objects Programming Concepts using Java 5/6
Implementing a call-back facility

Myclass m creates a Timer t


Start t to run in parallel Myclass m Timer t
Myclass m continues to run
• start()
Will see later how to invoke parallel
execution in Java! timerdone() •
Timer t notifies Myclass m when the
time limit expires
Assume Myclass m has a function
timerdone()

Madhavan Mukund Callbacks Programming Concepts using Java 2/6

Implementing callbacks
Code for Myclass
Timer t should know public class Myclass{ public class Timer
implements Runnable{
whom to notify public void f(){ // Timer can be
Myclass m passes .. // invoked in parallel
its identity when it Timer t =
creates Timer t new Timer(this); private Myclass owner;
// this object
Code for Timer // created t public Timer(Myclass o){
... owner = o; // My creator
Interface Runnable }
t.start(); // Start t
indicates that Timer ...
can run in parallel } public void start(){
...
Timer specific to
public void timerdone(){...} owner.timerdone();
Myclass } // I’m done
}
Create a generic
}
Timer?
Madhavan Mukund Callbacks Programming Concepts using Java 3/6
A generic timer

Use Java class public class Myclass{ public class Timer


hierarchy implements Runnable{
public void f(){ // Timer can be
Parameter of .. // invoked in parallel
Timer constructor Timer t =
of type Object new Timer(this); private Object owner;
// this object
Compatible // created t public Timer(Object o){
with all caller ... owner = o; // My creator
types t.start(); // Start t }
...
Need to cast public void start(){
}
owner back to ...
Myclass public void timerdone(){...} ((Myclass) owner).timerdone();
} // I’m done
}
}

Madhavan Mukund Callbacks Programming Concepts using Java 4/6

Use interfaces

Define an interface for public class Myclass public class Timer


callback implements Timerowner{ implements Runnable{
public interface // Timer can be
Timerowner{ public void f(){ // invoked in parallel
.. private Timerowner owner;
public abstract Timer t =
void timerdone(); new Timer(this); public Timer(Timerowner o){
} // this object owner = o; // My creator
// created t }
Modify Myclass to ...
implement t.start(); // Start t public void start(){
Timerowner ... ...
} owner.timerdone();
Modify Timer so that // I’m done
owner is compatible public void timerdone(){...} }
} }
with Timerowner

Madhavan Mukund Callbacks Programming Concepts using Java 5/6


Linear list
public class Linearlist {
A generic linear list of objects // Array implementation
private int limit = 100;
Internal implementation may vary private Object[] data = new Object[limit];
private int size; // Current size
An array implementation
public Linearlist(){ size = 0; }

public void append(Object o){


data[size] = o;
size++;
...
}
...
}

Madhavan Mukund Iterators Programming Concepts using Java 2/8

Linear list
public class Linearlist {
A generic linear list of objects private Node head;
private int size;
Internal implementation may vary
public Linearlist(){ size = 0; }
An array implementation
public void append(Object o){
A linked list implementation Node m;

for (m = head; m.next != null; m = m.next){}


Node n = new Node(o);
m.next = n;

size++;
}
...
private class Node (...}
}

Madhavan Mukund Iterators Programming Concepts using Java 2/8


Iteration

Want a loop to run through all values int i;


in a linear list for (i = 0; i < data.length; i++){
... // do something with data[i]
If the list is an array with public }
access, we write this
For a linked list with public access, Node m;
for (m = head; m != null; m = m.next}
we could write this ... // do something with m.data
}
We don’t have public access . . .
. . . and we don’t know which
implementation is in use!

Madhavan Mukund Iterators Programming Concepts using Java 3/8

Iterators

Need the following abstraction


Start at the beginning of the list;
while (there is a next element){
get the next element;
do something with it
}

Encapsulate this functionality in an interface called Iterator


public interface Iterator{
public abstract boolean has_next();
public abstract Object get_next();
}

Madhavan Mukund Iterators Programming Concepts using Java 4/8


Iterators

How do we implement Iterator in Linearlist?


Need a “pointer” to remember position of the iterator
How do we handle nested loops?
for (i = 0; i < data.length; i++){
for (j = 0; j < data.length; j++){
... // do something with data[i] and data[j]
}
}

Madhavan Mukund Iterators Programming Concepts using Java 5/8

Iterators
Solution: Create an Iterator object and export it!
public class Linearlist{

private class Iter implements Iterator{


private Node position;
public Iter(){...} // Constructor
public boolean has_next(){...}
public Object get_next(){...}
}

// Export a fresh iterator


public Iterator get_iterator(){
Iter it = new Iter();
return(it);
}
}

Definition of Iter depends on linear list


Madhavan Mukund Iterators Programming Concepts using Java 6/8
Iterators

Now, we can traverse the list externally For nested loops, acquire multiple
as follows: iterators!
Linearlist l = new Linearlist(); Linearlist l = new Linearlist();
... ...
Object o; Object oi,oj;
Iterator i = l.get_iterator(); Iterator i,j;

while (i.has_next()){ i = l.get_iterator();


o = i.get_next(); while (i.has_next()){
... // do something with o oi = i.get_next();
} j = l.get_iterator();
... while (j.has_next()){
oj = j.get_next();
... // do something with oi, oj
}
}
...
Madhavan Mukund Iterators Programming Concepts using Java 7/8

You might also like