Java Notes Quiz 1
Java Notes Quiz 1
CONCEPTS USING
JAVA
Week 1-4
Programming languages
Abstraction
Abstractions used in computational thinking
Assigning values to named variables
Conditional execution
Iteration
Functions / procedures, recursion
Aggregate data structures — arrays, lists, dictionaries
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
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
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
Understand and appreciate why there is a zoo of programming languages out there
. . . and why new ones are still being created
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
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
Data refinement
Banking application
Typical functions: CreateAccount(), Deposit()/Withdraw(), PrintStatement()
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
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
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
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
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?
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)
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
def odistance(self):
return(self.r)
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?
Madhavan Mukund A first taste of Java Programming Concepts using Java 3/9
Why so complicated . . .
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 . . .
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 }
Madhavan Mukund A first taste of Java Programming Concepts using Java 6/9
Compiling and running Java code
Madhavan Mukund A first taste of Java Programming Concepts using Java 7/9
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
Madhavan Mukund Basic datatypes in Java Programming Concepts using Java 2/8
Madhavan Mukund Basic datatypes in Java Programming Concepts using Java 3/8
Initialization, constants
Madhavan Mukund Basic datatypes in Java Programming Concepts using Java 4/8
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
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
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
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;
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
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 {
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 ...
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
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 ...
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?
Madhavan Mukund Defining classes and objects in Java Programming Concepts using Java 4/8
Creating objects
public class Date {
Declare type using class name ...
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;
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
Madhavan Mukund Basic input and output in Java Programming Concepts using Java 2/4
Reading input
Madhavan Mukund Basic input and output in Java Programming Concepts using Java 3/4
Generating output
Madhavan Mukund Basic input and output in Java Programming Concepts using Java 4/4
Algorithms + Data Structures = Programs
Madhavan Mukund The philosophy of OO programming Programming Concepts using Java 2/7
Madhavan Mukund The philosophy of OO programming Programming Concepts using Java 3/7
Object Oriented design: Example
Madhavan Mukund The philosophy of OO programming Programming Concepts using Java 4/7
Designing objects
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
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
Madhavan Mukund Subclasses and inheritance Programming Concepts using Java 5/6
Polymorphism
Madhavan Mukund Dynamic dispatch and polymorphism Programming Concepts using Java 4/8
Polymorphism
Madhavan Mukund Dynamic dispatch and polymorphism Programming Concepts using Java 4/8
Type casting
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
Madhavan Mukund The Java class hierarchy Programming Concepts using Java 2/7
Madhavan Mukund The Java class hierarchy Programming Concepts using Java 3/7
Java class hierarchy
Madhavan Mukund The Java class hierarchy Programming Concepts using Java 4/7
Overriding functions
Madhavan Mukund The Java class hierarchy Programming Concepts using Java 6/7
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()
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
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
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 }
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 */
}
}
final components
Recall overriding
Subclass redefines a method available with the same signature in the parent class
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();
Madhavan Mukund Abstract classes and interfaces Programming Concepts using Java 3/8
Abstract classes . . .
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
}
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
Nested objects
...
}
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 }
Madhavan Mukund Controlled interaction with objects Programming Concepts using Java 2/6
Manipulating objects
Madhavan Mukund Controlled interaction with objects Programming Concepts using Java 2/6
Querying a database
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 }
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;
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 interfaces
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;
size++;
}
...
private class Node (...}
}
Iterators
Iterators
Solution: Create an Iterator object and export it!
public class Linearlist{
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;