You are on page 1of 503

Object Oriented Programming

CS F213
J. Jennifer Ranjani
email: jennifer.ranjani@pilani.bits-pilani.ac.in
Chamber: 6121 B, NAB
BITS Pilani Consultation: Appointment by e-mail
Pilani Campus
Java – an Introduction

BITS Pilani
Pilani Campus
What is Java?

• Programming language and a platform

• Platform: Any hardware or software environment in


which a program runs
• Java has its own runtime environment (JRE) and API

BITS Pilani, Pilani Campus


Java is compiled and
interpreted

Hardware and
Programmer
Operating System

Source Code Byte Code

Text Editor Compiler Interpreter


.java file .class file
javac

BITS Pilani, Pilani Campus


Where is Java used?

Acc. To Sun, 3 billion devices run Java


• Desktop applications
• Acrobat reader, media player, antivirus etc

• Web applications
• Enterprise applications
• Mobile
• Embedded System
• Smart card
• Robotics
• Games etc.

BITS Pilani, Pilani Campus


Java Platforms / Editions

• Java SE (Standard Edition)


• Programming platform

• Java EE (Enterprise Edition)


• Web and enterprise applications

• Java ME (Micro Edition)


• Mobile applications

• JavaFx
• Rich internet applications. Uses light weight user interface APIs.

BITS Pilani, Pilani Campus


History of Java

• James Gosling, Mike Sheridan, Patrick Naughton


initiated the project in June 1991 (Green Team).
• Originally designed for small embedded systems
• “Greentalk” with file extension .gt
• Oak – symbol of strength and national tree of countries
like U.S., France, Germany, Romania etc.
• Suggested names: Dynamic, Revolutionary, Silk, Jolt,
DNA etc
• Java is named after an island in Indonesia where first coffee was produced
• Java is a name not an acronym

• Released in 1995.
• JDK 1.0 was released in Jan 23, 1996.

BITS Pilani, Pilani Campus


Java Version History
• JDK Alpha and Beta (1995)
• JDK 1.0 (23rd Jan, 1996)
• JDK 1.1 (19th Feb, 1997)
• J2SE 1.2 (8th Dec, 1998)
• J2SE 1.3 (8th May, 2000)
• J2SE 1.4 (6th Feb, 2002)
• J2SE 5.0 (30th Sep, 2004)
• Java SE 6 (11th Dec, 2006)
• Java SE 7 (28th July, 2011)
• Java SE 8 (18th March, 2014)
• Java SE 9 (21st Sep, 2017)
• Java SE 10 (20th March, 2018)
BITS Pilani, Pilani Campus
JDK

• JVM – provides runtime


environment for bytecode
execution; loads, verifies,
executes code
• JRE – contains libraries
and files used by JVM
• JDK – JVM, java, javac,
jar, Javadoc etc. for
complete java application
development.

BITS Pilani, Pilani Campus


BITS Pilani
Pilani Campus

Features of Java
Java Buzzwords

BITS Pilani, Pilani Campus


Features of Java

• Simple
• Syntax based on C++
• Removed confusing and rarely used features like pointers, operator overloading
etc.,
• Automatic garbage collection

• Object Oriented
• Object, Class, Inheritance, Polymorphism, Abstraction, Encapsulation

• Platform Independent
• Compiler converts Java code to bytecode
• Bytecode is platform independent
• Write Once and Run Anywhere

BITS Pilani, Pilani Campus


Platform Independence

JAVA COMPILER
(translator)

JAVA BYTE CODE

JAVA INTERPRETER
(one for each different system)

Windows 95 Macintosh Solaris Windows NT


BITS Pilani, Pilani Campus
Features of Java

• Secured

• Robust
• Strong memory management, secure due to lack of pointers, automatic garbage
collection, exception handling and type checking

BITS Pilani, Pilani Campus


Features of Java

• Architecture-neutral and Portable

• Size of primitive types is fixed i.e., 4 bytes for both 32 and 64 bit architectures

• Porting the java system to any new platform involves writing an interpreter.

• The interpreter will figure out what the equivalent machine dependent code to run

BITS Pilani, Pilani Campus


Features of Java

• High Performance
• Bytecode is close to native code
• It is an interpreted language hence slower than C, C++

• Distributed
• Enables access to files by calling methods from any machine on the internet
• RMI, EJB

• Multi-threaded
• Thread is like a separate program executing concurrently
• Doesn’t occupy memory for each thread
• Multimedia, Web applications etc

• Dynamic
• Supports dynamic loading of classes i.e. classes are loaded on demand
• Also supports functions from native languages i.e. C and C++

BITS Pilani, Pilani Campus


BITS Pilani
Pilani Campus

Comparison with C++


Comparison Index C++ Java

Platform- Platform-dependent. Platform-independent.


independent
Mainly used for System programming. Application
programming.
Goto Yes No
Multiple inheritance C++ supports Java doesn't support
multiple inheritance. multiple inheritance
through class. It can
be achieved
by interfaces in java.
Operator Yes No
Overloading
Pointers C++ Java supports pointer
supports pointers. You internally. But you
can write pointer can't write the pointer
program in C++. program in java.
BITS Pilani, Pilani Campus
Comparison Index C++ Java

Compiler and C++ uses compiler Java uses compiler


Interpreter only. and interpreter both.
Java source code is
converted into byte
code at compilation
time. The interpreter
executes this byte
code at run time and
produces output.
Call by Value and C++ supports both Java supports call by
Call by reference call by value and call value only.
by reference.
Structure and C++ supports Java doesn't support
Union structures and unions. structures and unions.

BITS Pilani, Pilani Campus


Comparison Index C++ Java

Thread Support C++ doesn't have Java has built-


built-in support for in thread support.
threads. It relies on
third-party libraries
for thread support.
Virtual Keyword C++ supports virtual Java has no virtual
keyword so that we keyword. Non-static
can decide whether or methods are virtual
not override a by default.
function.
unsigned right shift C++ doesn't support Supports unsigned
>>> >>> operator. right shift >>>
operator that fills zero
at the top for the
negative numbers.
For positive numbers,
it works same like >>
operator.
BITS Pilani, Pilani Campus
Simple program

BITS Pilani
Pilani Campus
My first program

class first{
public static void main(String args[]){
System.out.println("Hello World");
}
}

Save the file as first.java

BITS Pilani, Pilani Campus


Set path, Compile and Execute

Note: No space before


and after the ‘=‘ sign

BITS Pilani, Pilani Campus


Setting PATH variable

• Right click My Computer  Properties  Advanced


system setting  Environment Variables  System
Variables  Path (Edit)
• Add C:\Program Files\Java\jdk-9.0.1\bin

• It is sufficient to do this once.

BITS Pilani, Pilani Campus


BITS Pilani
Pilani Campus

Creating a New Project, New Class using


Eclipse
BITS Pilani, Pilani Campus
BITS Pilani, Pilani Campus
Importing a File

BITS Pilani, Pilani Campus


Parameters used

• class keyword is used to declare a class in java.


• public keyword is an access modifier which represents
visibility, it means it is visible to all.
• static is a keyword. The core advantage of static method
is that there is no need to create object to invoke the
static method. The main method is executed by the JVM.
• void is the return type of the method, it means it doesn't
return any value.
• main represents the starting point of the program.
• String[] args is used for command line argument.
• System.out.println() is used print statement.

BITS Pilani, Pilani Campus


Valid and Invalid ‘Main’
Signatures
• VALID
• public static void main(String[] args)
• public static void main(String []args)
• public static void main(String args[])
• public static void main(String... args)
• static public void main(String[] args)
• public static final void main(String[] args)
• final public static void main(String[] args)
• final strictfp public static void main(String[] args)

• INVALID
• public void main(String[] args)
• static void main(String[] args)
• public void static main(String[] args)
• abstract public static void main(String[] args)

BITS Pilani, Pilani Campus


Additional details

BITS Pilani, Pilani Campus


Object Oriented Programming
CS F213
J. Jennifer Ranjani
email: jennifer.ranjani@pilani.bits-pilani.ac.in
Chamber: 6121 B, NAB
BITS Pilani Consultation: Appointment by e-mail
Pilani Campus
OOP Basics
BITS Pilani
Pilani Campus
Basic OOP concepts

• Class
• Object
• Abstraction
• Encapsulation
• Inheritance
• Polymorphism

BITS Pilani, Pilani Campus


Abstract Data Type (ADT)

• A structure that contains both data and the actions to be


performed on that data.

• Class is an implementation of an Abstract Data Type.

BITS Pilani, Pilani Campus


Examples
Person Objects

Abstract Person Class


Into Attributes: Name, Age, Sex
Operations: Speak(), Listen(), Walk()

Vehicle Objects

Abstract Vehicle Class


Into Attributes: Name, Model, Color
Operations: Start(), Stop(), Accelerate()

Polygon Objects

Polygon Class
Abstract Attributes: Vertices, Border,
Into Color, FillColor
Operations: Draw(), Erase(), Move()

Figure 1.12: Objects and classes


BITS Pilani, Pilani Campus
Class
• Class is a set of attributes and operations that are
performed on the attributes.
• A blueprint from which individual objects can be
created.
• A class defines all the properties common to the object
- attributes and methods.

Student Circle
Account

accountName name centre


accountBalance age radius
studentId
withdraw() area()
deposit() getName()
getId() circumference()
determineBalance()

BITS Pilani, Pilani Campus


Objects

• Instance of the class


• Entity that has state and behavior
• Each object has an address and takes up memory
• It can communicate without knowing other object’s code
or data

BITS Pilani, Pilani Campus


Classes/Objects

John and Jill are


:John
Student objects of class
Student
:Jill

:circleA circleA and circleB


Circle are
:circleB objects of class
Circle
BITS Pilani, Pilani Campus
Object
• Objects have state and classes don’t.
John is an object (instance) of class Student.
name = “John”, age = 20, studentId = 1236

Jill is an object (instance) of class Student.


name = “Jill”, age = 22, studentId = 2345

circleA is an object (instance) of class Circle.


centre = (20,10), radius = 25

circleB is an object (instance) of class Circle.


centre = (0,0), radius = 10

BITS Pilani, Pilani Campus


Class/Object Example
class Student{
int id;
String name;
}
class TestStudent{
public static void main(String args[]){
//Creating object
Student s1=new Student();
//Initializing object
s1.id=253;
s1.name="Sathish";
//Printing data
System.out.println(s1.id+" "+s1.name);
}}

BITS Pilani, Pilani Campus


Data Abstraction

• Abstraction is a process where you show only “relevant”


data and “hide” unnecessary details of an object from the
user.
• It allows the creation of user defined data types, having
the properties of built in data types and more.
– Example: A car in itself is a well-defined object, which is
composed of several other smaller objects like a gearing system,
steering mechanism, engine, which are again have their own
subsystems. But for humans car is a one single object, which
can be managed by the help of its subsystems, even if their inner
details are unknown.

BITS Pilani, Pilani Campus


Abstraction - Example

class Student{
int id; Creates a data
String name;
type Student
}
// Class Student
Student s1;

BITS Pilani, Pilani Campus


Encapsulation

• Encapsulation is:
– Binding the data with the code that manipulates it.
– It keeps the data and the code safe from external interference

• All information (attributes and methods) in an object


oriented system are stored within the object/class.

• Information can be manipulated through operations


performed on the object/class – interface to the class.
Implementation is hidden from the user.

• Object support Information Hiding – Some attributes and


methods can be hidden from the user.
BITS Pilani, Pilani Campus
Encapsulation Example
class Student{
private int rollno;
String name;
void insertRecord(int r, String n){
rollno=r;
name=n;
}
void displayInformation(){System.out.println(rollno+" "+name);}
}
class TestStudent{
public static void main(String args[]){
Student s1=new Student();
s1.insertRecord(111,"Karan");
s1.displayInformation();
}
}
BITS Pilani, Pilani Campus
Inheritance
• New data types (classes) can be defined as extensions
to previously defined types.
• Parent Class (Super Class) – Child Class (Sub Class)
• Subclass inherits properties from the parent class.

Parent
Inherited
capability

Child

BITS Pilani, Pilani Campus


Inheritance - Example
• Example
– Define Person to be a class
• A Person has attributes, such as name, age, height, gender

– Define student to be a subclass of Person


• A student has all attributes of Person, plus attributes of
his/her own ( student no, course_enrolled)
• A student inherits all attributes of Person

– Define lecturer to be a subclass of Person


• Lecturer has all attributes of Person, plus attributes of
his/her own ( staff_id, subjectID1, subjectID2)

BITS Pilani, Pilani Campus


Inheritance - Example
• Circle Class can be a subclass (inherited from ) of a
parent class - Shape

Shape

Circle Rectangle

BITS Pilani, Pilani Campus


Uses of Inheritance - Reuse
• If multiple classes have common attributes/methods,
these methods can be moved to a common class -
parent class.

• This allows reuse since the implementation is not


repeated.

BITS Pilani, Pilani Campus


Reuse-Example
Circle Rectangle
centre
centre height
radius width
area() area()
circumference() circumference()
move(newCentre) move(newCentre)

move(newCentre){ move(newCentre){
centre = newCentre; centre = newCentre;
} }

BITS Pilani, Pilani Campus


Reuse-Example
Shape

centre move(newCentre){
centre = newCentre
}
move(newCentre)

Circle Rectangle

height
radius width

area() area()
circumference() circumference()

BITS Pilani, Pilani Campus


Polymorphism
• Polymorphic which means “many forms” has Greek
roots.
– Poly – many
– Morphos - forms.

• In OO paradigm polymorphism has many forms.

• Allow a single object, method, operator associated with


different meaning depending on the type of data passed
to it.

BITS Pilani, Pilani Campus


Polymorphism – Method Overloading
• Multiple methods can be defined with the same name,
different input arguments.
Method 1 - initialize(int a)
Method 2 - initialize(int a, int b)

• Appropriate method will be called based on the input


arguments.
initialize(2) Method 1 will be called.
initialize(2,4) Method 2 will be called.

BITS Pilani, Pilani Campus


Object Oriented Programming
CS F213
J. Jennifer Ranjani
email: jennifer.ranjani@pilani.bits-pilani.ac.in
Chamber: 6121 B, NAB
BITS Pilani Consultation: Appointment by e-mail
Pilani Campus
Programming Syntax
BITS Pilani
Pilani Campus
Naming Convention (Rule)

• Used to name your identifiers such as class, package,


variable, constant, method etc.
Name Convention
class name should start with uppercase letter and be a noun e.g.
String, Color, Button, System, Thread etc.
interface name should start with uppercase letter and be an adjective e.g.
Runnable, Remote, ActionListener etc.

method name should start with lowercase letter and be a verb e.g.
actionPerformed(), main(), print(), println() etc.

variable name should start with lowercase letter e.g. firstName,


orderNumber etc.
package name should be in lowercase letter e.g. java, lang, sql, util etc.

constants name should be in uppercase letter. e.g. RED, YELLOW,


MAX_PRIORITY etc.

BITS Pilani, Pilani Campus


Variable

• Name given to a memory


location. It is the basic unit of
storage in a program.
• The value can be changed during program
execution.
• All the operations done on the variable effects
that memory location.
• Variables must be declared before they can be
used. (but not necessarily in the beginning)

• Types of variables
• Static or class variables
• Instance Variables
• Local variables

BITS Pilani, Pilani Campus


Static Variables

• A class variable is any field declared with the static


modifier

• Tells the compiler that there is exactly one copy of this


variable in existence, regardless of how many times the
class has been instantiated.

BITS Pilani, Pilani Campus


Static Variables-Example
public class StaticVarExample {
static String myClassVar="class or static variable";

public static void main(String args[]){


StaticVarExample obj1 = new StaticVarExample();
StaticVarExample obj2 = new StaticVarExample();

System.out.println(obj1.myClassVar);
System.out.println(obj2.myClassVar);
System.out.println(myClassVar);

//changing the value of static variable using obj2


obj2.myClassVar = "Changed Text";
Output:
System.out.println(obj1.myClassVar); class or static variable
System.out.println(obj2.myClassVar); } } class or static variable
Changed Text
Changed Text
BITS Pilani, Pilani Campus
Static variable across classes-
Example
class Zero{
static String classvar = "Static Variable of another class";
}
class First{
public static void main(String args[]){
System.out.println(Zero.classvar);
}
}

BITS Pilani, Pilani Campus


Where static variables can be
used?
• Counting the number of objects

• Specify the college or dept name for all the student


objects

• Specify the branch name and code for all account


holders of a particular branch.

BITS Pilani, Pilani Campus


Instance (Non-static) Variables

• Objects store their individual states in "non-static fields"

• Fields declared without the static keyword.

• Non-static fields are also known as instance variables


because their values are unique to each instance of a
class.

BITS Pilani, Pilani Campus


Instance Variables-Example
public class InstanceVarExample {
String myInstanceVar=“instance variable";

public static void main(String args[]){


InstanceVarExample obj1 = new InstanceVarExample();
InstanceVarExample obj2 = new InstanceVarExample();

//Two objects will display "class or static variable"


System.out.println(obj1.myInstanceVar);
System.out.println(obj2.myInstanceVar);

//changing the value of static variable using obj2


obj2.myInstanceVar = "Changed Text"; Output:
instance variable
//All will display "Changed Text" instance variable
instance variable
System.out.println(obj1.myInstanceVar);
Changed Text
System.out.println(obj2.myInstanceVar); } }
BITS Pilani, Pilani Campus
Local Variable

• Defined within a block or method or constructor

• These variable are created when the block in entered or


the function is called and destroyed after exiting from the
block or when the call returns from the function.

• The scope of these variables exists only within the block


in which the variable is declared. i.e. we can access
these variable only within that block.

BITS Pilani, Pilani Campus


Local Variable-Example
public class VariableExample {

// instance variable
public String myVar="instance variable";

public void myMethod(){


// local variable
String myVar = "Inside Method";
System.out.println(myVar); }

public static void main(String args[]){

// Creating object
VariableExample obj = new VariableExample();
System.out.println("Calling Method"); Output:
Calling Method
obj.myMethod(); Inside Method
Instance variable
System.out.println(obj.myVar);
}
} BITS Pilani, Pilani Campus
Primitive Data Types

Note: There is no sizeof operator in Java as there is in C. Size of each


primitive is fixed

BITS Pilani, Pilani Campus


Type Conversion

• When the value of one data type is assigned to another,


the two types might not be compatible with each other.
• If the data types are compatible, then Java will perform
the conversion automatically known as Automatic Type
Conversion
• If not then they need to be casted or converted explicitly.
For example, assigning an int value to a long variable.

BITS Pilani, Pilani Campus


Type Conversion - Example
char ch = 'c';
int num = 88;
num = ch; // Automatic type conversion
System.out.println(num);

Ans: 99

ch = num;
System.out.println(ch);
Error: incompatible types: possible lossy conversion from int
to char
Solution: ch = (char) num; //Type casting or explicit conv.
Ans: X
BITS Pilani, Pilani Campus
Type Promotion

• While evaluating
expressions, the
intermediate value may
exceed the range of
operands and hence the
expression value will be
promoted.
• Some conditions for type
promotion are:
• Java automatically promotes
each byte, short, or char operand
to int when evaluating an
expression.
• If one operand is a long, float or
double the whole expression is
promoted to long, float or double
respectively.

BITS Pilani, Pilani Campus


Type Promotion-Example

byte b = 42;
char c = 'a';
short s = 1024;
int i = 50000;
float f = 5.67f;
double d = .1234;

// The Expression
double result = (f * b) + (i / c) - (d * s);
System.out.println("result = " + result);

BITS Pilani, Pilani Campus


Additional Example

byte b = 50;
b = (b * 2);
System.out.println(b);

Error: due to type promotion

Solution: b = (byte) (b * 2); //Explicit conversion

Ans: 100

BITS Pilani, Pilani Campus


Primitive Data Types -String

• It is not technically a primitive data type

• Java programming language provides special support for


character strings via the java.lang.String class.

• Enclosing your character string within double quotes will


automatically create a new String object;
• String s = “this is a string”;

BITS Pilani, Pilani Campus


Operators, Precedence,
Associativity

BITS Pilani, Pilani Campus


Example-Associativity

int a=10,b=20,c=30,d=40,e=50;
int result = a>=10 ? b <20 ?c :d :e ;
System.out.println("Result:" + result );

• Recall: Associativity of Ternary Operator is R to L

• Answer: 40

BITS Pilani, Pilani Campus


Example-Conditional AND

int a=-9;
Boolean b=true;
Boolean result = (a>0) && (b=false) ;
System.out.println("Result:" + result +"b="+b);

Recall: Conditional AND is a short circuit operator

Answer: b= true

BITS Pilani, Pilani Campus


Object Oriented Programming
CS F213
J. Jennifer Ranjani
email: jennifer.ranjani@pilani.bits-pilani.ac.in
Chamber: 6121 B, NAB
BITS Pilani Consultation: Appointment by e-mail
Pilani Campus
Classes, Methods,
Constructor &
Overloading
BITS Pilani
Pilani Campus
Class & Object - Example

• Write a java program for the class diagram given below.

Account
acc_no
name
amount

insert(no, name, amt)


withdraw(amt)
deposit(amt)
checkBalance()
display()

BITS Pilani, Pilani Campus


class Account{
int acc_no;
String name;
float amount;
void insert(int a,String n,float amt){
acc_no=a;
name=n;
amount=amt;
}
void deposit(float amt){
amount=amount+amt;
System.out.println(amt+" deposited");
}
void withdraw(float amt){
if(amount<amt){
System.out.println("Insufficient Balance");
}else{
amount=amount-amt;
System.out.println(amt+" withdrawn");
}
BITS Pilani, Pilani Campus
}
void checkBalance(){System.out.println("Balance is: "+amount);}
void display(){System.out.println(acc_no+" "+name+" "+amount);}
}
class TestAccount{
public static void main(String[] args){
Account a1=new Account();
a1.insert(832345,"Ankit",1000);
a1.display();
a1.checkBalance();
a1.deposit(40000);
a1.checkBalance();
a1.withdraw(15000);
a1.checkBalance();
}}

BITS Pilani, Pilani Campus


Method Overloading

• Multiple methods having same name but different


parameters is known as method overloading.

• Eg. Suppose you have to perform addition of the given


numbers but there can be any number of arguments, if
you write the method such as a(int,int) for two
parameters, and b(int,int,int) for three parameters then it
may be difficult for you as well as other programmers to
understand the behavior of the method because its name
differs.

• Adv: increases the readability of the program.

BITS Pilani, Pilani Campus


Different ways to overload

• Changing the number of arguments


• int add(int a,int b)
• int add(int a,int b,int c)

• Changing the data type


• int add(int a, int b)
• double add(double a, double b)

• Changing only the return type does not mean method


overloading
• int add(int a,int b)
• double add(int a,int b)
• Compile Time Error: method add(int,int) is already defined in class Adder

BITS Pilani, Pilani Campus


Method Overloading -
Example
class Account{
int acc_no;
String name;
float amount;
void insert(int a,String n,float amt){
acc_no=a;
name=n;
amount=amt; }
void insert(int a,String n){
acc_no=a;
Minimum balance is 1000
name=n;
amount=1000; }
void display(){
System.out.println(acc_no+" "+name+" "+amount);}
}
BITS Pilani, Pilani Campus
Method Overloading -
Example
class TestAccount{
public static void main(String[] args){
Account a1 = new Account();
a1.insert(832345,"Ankit",5000);
a1.display();

Account a2 = new Account();


a2.insert(832346,“Shobit“); Output:
832345 Ankit 5000.0
a2.display();
832346 Shobit 1000.0
}}

BITS Pilani, Pilani Campus


Can Main() be overloaded?
public static void main(String[] args){System.out.println("main with String[]");}
public static void main(String args){System.out.println("main with String");}
public static void main(){System.out.println("main without args");}

Ans: Yes. JVM calls main() method which receives string


array as arguments only.

BITS Pilani, Pilani Campus


Overloading and Type
Promotion
class OverloadingCalculation{
void add(int a,long b){System.out.println(a+b);}
void add(int a,int b,int c){System.out.println(a+b+c);}

public static void main(String args[]){


OverloadingCalculation obj=new OverloadingCalculation();
obj.add(20,20);
obj.add(20,20,20);
}
} Output:
40
60

BITS Pilani, Pilani Campus


Overloading and Type Promotion
(Matching Type Arguments)
class OverloadingCalculation{
void add(int a,int b){System.out.println("int arg method invoked");}
void add(long a,long b){System.out.println("long arg method invoked");}

public static void main(String args[]){


OverloadingCalculation obj=new OverloadingCalculation();
obj.add(20,20);
}
Output:
}
int arg method invoked

BITS Pilani, Pilani Campus


Overloading and Type
Promotion (Ambiguity)
class OverloadingCalculation{
void add(int a,long b){System.out.println(“a method invoked”);}
void add(long a,int b){System.out.println(“b method invoked”);}

public static void main(String args[]){


OverloadingCalculation obj=new OverloadingCalculation();
obj.add(20,20);

}
} Output:
Compile time error

BITS Pilani, Pilani Campus


Constructors

• Similar to a method but it is called when an instance of


the object is created and memory is allocated for the
object.

• Used to initialize an object

• Constructor – constructs values at the time of object


creation. It is not necessary to write a constructor for a
class, the compiler creates a default constructor.

BITS Pilani, Pilani Campus


More about constructors

Rules for creating constructor


• Name must be same as its class name
• Must have no explicit return type.

Types of constructors
• Default (no argument) constructor
• Provide default values to the object like 0, null etc.

• Parameterized constructor
• Provide different values to distinct objects.

BITS Pilani, Pilani Campus


Default Constructor - Example
class Account{
int acc_no;
String name;
float amount;
void display(){
System.out.println(acc_no+" "+name+" "+amount);}
}

class TestAccount{
public static void main(String[] args){
Account a1=new Account(); Output:
a1.display(); 0 null 0.0
}}

BITS Pilani, Pilani Campus


Default Constructor - Example
class Account{
int acc_no;
String name;
float amount;
Account(){
System.out.println("The default values are:");
amount = 1000; Minimum balance is 1000
}
void display(){
System.out.println(acc_no+" "+name+" "+amount);}
}

class TestAccount{ Output:


public static void main(String[] args){ The default values are:
Account a1=new Account(); 0 null 1000.0
a1.display();
}} BITS Pilani, Pilani Campus
Parameterized Constructor-
Example
class Account{
int acc_no;
String name;
float amount;
/*void insert(int a,String n,float amt){
acc_no=a;
name=n;
amount=amt; */
Account(int acc,String aname, float amt){
acc_no = acc;
name = aname;
amount = amt; }
void display(){
System.out.println(acc_no+" "+name+" "+amount);}
}
BITS Pilani, Pilani Campus
Parameterized Constructor-
Example
class TestAccount{
public static void main(String[] args){
/* Account a1 = new Account();
a1.insert(832345,"Ankit",5000);
a1.display(); */
Account a1=new Account(832345,"Ankit",5000);
a1.display();
}} Output:
832345 Ankit 5000.0

Note: When parameterized constructors are implemented;


then the copy of the default constructor is not created. In
this example you cannot create the object as
Account a1 = new Account();

BITS Pilani, Pilani Campus


Constructor Overloading

• Recall: Constructor is just like a method but without


return type.

• Constructor overloading: Having more than one


constructor with different parameter lists.

• The compiler differentiates by the number of


parameters in the list and their types.

BITS Pilani, Pilani Campus


Constructor Overloading-
Example
class Account{
int acc_no;
String name;
float amount;
Account(int acc,String aname){
acc_no = acc;
name = aname;
amount = 1000; }
Account(int acc,String aname, float amt){
acc_no = acc;
name = aname;
amount = amt; }
void display(){
System.out.println(acc_no+" "+name+" "+amount);}
}
BITS Pilani, Pilani Campus
Constructor Overloading-
Example
class TestAccount{
public static void main(String[] args){
Account a1=new Account(832345,"Ankit",5000);
a1.display();
Account a2=new Account(832346,”Shobit");
a2.display();
}}
Output:
832345 Ankit 5000.0
832346 Shobit 1000.0

BITS Pilani, Pilani Campus


Difference between a
Constructor and method
Java Constructor Java Method
Constructor is used to initialize Method is used to expose
the state of an object. behavior of an object.
Constructor must not have Method must have return type.
return type.
Constructor is invoked implicitly. Method is invoked explicitly.
The java compiler provides a Method is not provided by
default constructor if you don't compiler in any case.
have any constructor.
Constructor name must be Method name may or may not
same as the class name. be same as class name.

BITS Pilani, Pilani Campus


BITS Pilani
Pilani Campus

Static Keyword
Static Method

• A static method belongs to the class rather than object of


a class.

• A static method can be invoked without the need for


creating an instance of a class.

• Static method can access static data member and can


change the value of it.

• Restrictions
• Static method cannot use non static data member or call non-static method
directly i.e. non static members can only be accessed using objects.
• this and super keywords cannot be used in static context.
BITS Pilani, Pilani Campus
Static Method - Example
class Account{
int acc_no;
String name;
float amount;
static int branch;
Account(int acc,String aname, float amt){
acc_no = acc;
name = aname;
amount = amt; }
static void change(int bch)
{
branch = bch; }
void display(){System.out.println(acc_no+" "+name+" "+amount+"
"+branch);}
}

BITS Pilani, Pilani Campus


Static Method - Example
class TestAccount{

public static void main(String[] args)


{
Account.branch = 111;
Account a1=new Account(832345,"Ankit",5000);
// Account.change(222);
a1.display();
Account.change(222);
Account a2=new Account(832346,"Shobit",1000);
a2.display();

}
}

BITS Pilani, Pilani Campus


Static block

• Is used to initialize the static data member.

• It is executed before main method at the time of class


loading.

• Example
class first{
static int i;
static{i = 100; System.out.println("static block is invoked with i="+i);}
public static void main(String args[]){
System.out.println("Hello main");
Output:
} } static block is invoked with i=100
Hello main

BITS Pilani, Pilani Campus


Questions

• Can we overload static methods?


• ‘Yes’. We can have two or more static methods with same name, but differences
in input parameters.

• Can we overload methods that differ only by static


keyword?
• No.

BITS Pilani, Pilani Campus


Object Oriented Programming
CS F213
J. Jennifer Ranjani
email: jennifer.ranjani@pilani.bits-pilani.ac.in
Chamber: 6121 B, NAB
BITS Pilani Consultation: Appointment by e-mail
Pilani Campus
Java Objects
BITS Pilani
Pilani Campus
Passing Objects to Methods

• Java is strictly pass by value

• Call by reference can be achieved when objects are


passed as arguments

• When a variable of class type is created, it implies that a reference to an object is


created.

• Eg: Account a1;

• Reference variable is used to store the address of the object.

• When the reference is passed to a method, the parameter that receives refer to
the same object.

BITS Pilani, Pilani Campus


Passing Objects - Example
class Account{
int acc;
String name;
float amount;

Account(int act,String aname){


acc = act;
name = aname;
}

boolean equalTo(Account a) {
return(acc == a.acc && name == a.name);
}

}
BITS Pilani, Pilani Campus
Passing Objects - Example
class TestAccount{
public static void main(String[] args){
Account a1=new Account(832345,"Ankit");
Account a2=new Account(832345,"Ankit");
Account a3=new Account(832346,"Shobit");

System.out.println("a1==a2: " + a2.equalTo(a1));


System.out.println("a1==a3: " + a3.equalTo(a1));

}}
Output:
a1==a2: true
a1==a3: false

BITS Pilani, Pilani Campus


Passing Objects to
Constructors-Example
class Account{
int acc;
String name;
float amount;
Account(int act,String aname){
acc = act;
name = aname; }
Account(Account a){
acc = a.acc;
name = a.name; }
boolean equalTo(Account a) {
return(acc == a.acc && name == a.name); }
void display(){
System.out.println(acc+" "+name+" "+amount);}
}
BITS Pilani, Pilani Campus
Passing Objects to
Constructors-Example
class TestAccount{
public static void main(String[] args){
Account a1=new Account(832345,"Ankit");
Account a2 = new Account(a1);
Account a3=new Account(832346,"Shobit");

System.out.println("a1==a2: " + a2.equalTo(a1));


System.out.println("a1==a3: " + a3.equalTo(a1));

a1.name="Aankit";
Output:
a1.display();
a1==a2: true
a2.display(); a1==a3: false
832345 Aankit 0.0
}} 832345 Ankit 0.0

BITS Pilani, Pilani Campus


Assigning Object Reference
Variables
• Value of a reference variable can to assigned to another
reference variable.

• Assigning reference will not create distinct copies of


objects.

• All reference variables are referring to the same object.

BITS Pilani, Pilani Campus


Assigning Object Reference
class Account{
int acc;
String name;
float amount;
Account(int act,String aname){
acc = act;
name = aname;
}

boolean equalTo(Account a) {
return(acc == a.acc && name == a.name);
}
void display(){
System.out.println(acc+" "+name+" "+amount);}
}
BITS Pilani, Pilani Campus
Assigning Object Reference
class second{
public static void main(String[] args){
Account a1=new Account(832345,"Ankit");
Account a2= a1;
Account a3=new Account(832346,"Shobit");

System.out.println("a1==a2:" + a2.equalTo(a1));
System.out.println("a1==a3:" + a3.equalTo(a1));

a1.name="Aankit";
Output:
a1.display();
a1==a2: true
a2.display(); a1==a3: false
}} 832345 Aankit 0.0
832345 Aankit 0.0

BITS Pilani, Pilani Campus


BITS Pilani
Pilani Campus

‘This’ Keyword
‘this’ Keyword

• It is a reference variable that refers to the current object

• Six usage
• this can be used to refer current class instance variable.
• this can be used to invoke current class method (implicitly)
• this() can be used to invoke current class constructor.
• this can be passed as an argument in the method call.
• this can be passed as argument in the constructor call.
• this can be used to return the current class instance from the method.

BITS Pilani, Pilani Campus


this: to refer current class
instance variable
class Account{
int acc; Name of instance variables and formal
String name; arguments are same
float amount;
Account(int acc,String name, float amount){
acc = acc;
Output:
name = name;
0 null 0.0
amount = amount; }
void display(){
System.out.println(acc+" "+name+" "+amount);}
}
class TestAccount{
public static void main(String[] args){
Account a1=new Account(832345,"Ankit",5000);
a1.display();
}} BITS Pilani, Pilani Campus
this: to refer current class
instance variable
class Account{
int acc;
String name;
float amount;
Account(int acc,String name, float amount){
this.acc = acc;
Output:
this.name = name;
832345 Ankit 5000
this.amount = amount; }
void display(){
System.out.println(acc+" "+name+" "+amount);}
}
class TestAccount{
public static void main(String[] args){
Account a1=new Account(832345,"Ankit",5000);
a1.display();
}} BITS Pilani, Pilani Campus
this: to invoke current class
method
class Account{
int acc;
String name;
float amount;
void insert(int acc,String name, float amount){
this.acc = acc;
this.name = name;
If the function is invoked as display(), the
this.amount = amount; compiler automatically adds this keyword
this.display(); }
void display(){
System.out.println(acc+" "+name+" "+amount);}
}
class TestAccount{
public static void main(String[] args){
Account a1=new Account();
a1.insert(832345,"Ankit",5000); }}
BITS Pilani, Pilani Campus
this() : to invoke current class
constructor
• The this() constructor call can be used to invoke the
current class constructor. It is used to reuse the
constructor. In other words, it is used for constructor
chaining.

• Calling default constructor from parameterized


constructor

• Calling parameterized constructor from default


constructor

BITS Pilani, Pilani Campus


Constructor Chaining -
Example
class Account{
int acc;
String name;
float amount;
Account(int acc, String name){
this.acc = acc;
this.name = name;}

Account(int acc, String name, float amount){


this.acc = acc;
this.name = name;
this.amount = amount; }

void display(){
System.out.println(acc+" "+name+" "+amount);}
} BITS Pilani, Pilani Campus
Constructor Chaining -
Example
class Account{
int acc;
String name;
float amount;
Account(int acc, String name){
this.acc = acc;
this.name = name;}

Account(int acc, String name, float amount){


this(acc, name); //reusing constructor
this.amount = amount; }

void display(){
System.out.println(acc+" "+name+" "+amount);}
}
BITS Pilani, Pilani Campus
Constructor Chaining -
Example
class TestAccount{
public static void main(String[] args){
Account a1=new Account(832345,"Ankit",5000);
a1.display();
}}

Account(int acc, String name, float amount){


this.amount = amount;
this(acc, name); //reusing constructor }

BITS Pilani, Pilani Campus


this: to pass as an argument in
the method
class Account{
int acc;
String name;
float amount;
Account(int acc,String name){
this.acc = acc;
this.name = name; }
void update(int act,String aname, float amt) {
acc = act;
name = aname;
amount = amt;
display(this); }
void display(Account a){
System.out.println(a.acc+" "+a.name+" "+a.amount);}
}
BITS Pilani, Pilani Campus
this: to pass as an argument in
the method
class second{
public static void main(String[] args){
Account a1=new Account(832345,"Ankit");
Account a2=new Account(832345,"Shobit");
a1.display(a2);
a1.update(832346, "Aankit", 5000);
a1.display(a1);

}}

Output:
832345 Shobit 0.0
832346 Aankit 5000.0
832346 Aankit 5000.0

BITS Pilani, Pilani Campus


this: to pass as argument in the
constructor call
class Branch{
Account obj;
int branch;
Branch(Account obj){
this.obj=obj;
this.branch = 111;
}
void display(){
System.out.println(this.obj.acc+" "+this.obj.name+" "+this.branch);
}
}

BITS Pilani, Pilani Campus


this: to pass as argument in the
constructor call
class Account{
int acc;
String name;
Account(int acc,String name){
this.acc=acc;
this.name =name;
Branch b=new Branch(this);
b.display();
} Output:
} 832345 Ankit 111

class TestAccount{
public static void main(String args[]){
Account a1=new Account(832345,"Ankit");
}
}
BITS Pilani, Pilani Campus
Returning Objects using this
keyword
class Account{
int acc;
String name;
float amount;
Account(int acc,String name){
this.acc = acc;
this.name = name; }
Account update(int act,String aname, float amt) {
acc = act;
name = aname;
amount = amt;
return this; }
void display(){
System.out.println(acc+" "+name+" "+amount);}
}
BITS Pilani, Pilani Campus
Returning Objects using this
keyword
class TestAccount{
public static void main(String[] args){
Account a1=new Account(832345,"Ankit");
a1.display();
a1 = a1.update(832346, "Aankit", 5000);
a1.display();
}}

BITS Pilani, Pilani Campus


BITS Pilani
Pilani Campus

Mutable and Immutable


Objects
Immutability and Instances

• Mutable Objects: Contents of an instance that can be


modified.

• Eg: Immutable: java.lang.String


Mutable: Account

• When the contents of the String instance are modified, a


new string object is created.

BITS Pilani, Pilani Campus


Example
public class StringExamples
{
public static void main(String[] args)
{
String s1 = "JAVA";

String s2 = "JAVA";

System.out.println(s1 == s2); //Output : true

s1 = s1 + "J2EE";

System.out.println(s1 == s2); //Output : false


}
}

BITS Pilani, Pilani Campus


What happens in memory?

BITS Pilani, Pilani Campus


Are Strings created using new
operator also immutable?
public class StringExamples
{
public static void main(String[] args)
{
String s1 = new String("JAVA");

System.out.println(s1); //Output : JAVA

s1.concat("J2EE");

System.out.println(s1); //Output : JAVA


}
}

BITS Pilani, Pilani Campus


Are Strings created using new
operator also immutable?
public class StringExamples
{
public static void main(String[] args)
{
String s1 = new String("JAVA");

System.out.println(s1); //Output : JAVA

String s2=s1.concat("J2EE");

System.out.println("s1: "+s1+" s2: "+s2); //Output : s1: JAVA s2: JAVAJ2EE

}
}

BITS Pilani, Pilani Campus


How to create an Immutable
class?
• Class must be declared as final
• So that child classes can’t be created

• Data members in the class must be declared as final


• So that we can’t change the value of it after object creation

• A parameterized constructor

• Getter method for all the variables in it

• No setters
• To not have option to change the value of the instance variable

BITS Pilani, Pilani Campus


Immutable Class - Example
final class Account{
final int acc;
final String name;
final float amount;

Account(int acc,String name,float amt){


this.acc = acc;
this.name = name;
this.amount = amt; }

int getAcc(){
return acc;}
String getName() {
return name; }
float getAmount() {
return amount; }}
BITS Pilani, Pilani Campus
Immutable Class - Example
class TestAccount{
public static void main(String[] args) {

Account a= new Account(111,"Ankit",5000);

System.out.println("Acc: "+a.getAcc()+" Name: "+a.name);

a.amount = 1000;
}}

Output:
Exception in thread "main" java.lang.Error:
Unresolved compilation problem:
The final field Account.amount cannot be
assigned

BITS Pilani, Pilani Campus


Object Oriented Programming
CS F213
J. Jennifer Ranjani
email: jennifer.ranjani@pilani.bits-pilani.ac.in
Chamber: 6121 B, NAB
BITS Pilani Consultation: Appointment by e-mail
Pilani Campus
Reading Input from
Console
BITS Pilani
Pilani Campus
BITS Pilani
Pilani Campus

Command Line
Arguments
Command Line Arguments
class Account{
int acc;
String name;
float amount;
Account(int act,String aname){
acc = act;
name = aname;
}

void update(int act,String aname, float amt) {


acc = act;
name = aname;
amount = amt;
}

BITS Pilani, Pilani Campus


Command Line Arguments
void display(){
System.out.println(acc+" "+name+" "+amount);}
}
class second{
public static void main(String[] args){
Account a1=new Account(Integer.parseInt(args[0]),args[1]);
a1.display();
a1.update(Integer.parseInt(args[2]),args[3],Integer.parseInt(args[4]));
a1.display();

}}

BITS Pilani, Pilani Campus


Command Line Arguments
(From Command Prompt)

BITS Pilani, Pilani Campus


Command Line Arguments
(From Eclipse)

BITS Pilani, Pilani Campus


Command Line Arguments
(From Eclipse)

BITS Pilani, Pilani Campus


Command Line Arguments
(From Eclipse)

BITS Pilani, Pilani Campus


BITS Pilani
Pilani Campus

Array of Objects
Array of Objects
class Account{
int acc;
String name;
float amount;
void insert(int acc,String name,float amt){
this.acc = acc;
this.name = name;
this.amount = amt;
}

void display(){
System.out.println(acc+" "+name+" "+amount);}
}

BITS Pilani, Pilani Campus


Array of Objects
class TestAccount{
public static void main(String[] args){
Account[] a= new Account[3];

for(int i=0;i<3;i++)
{
a[i]= new Account();
a[i].insert(Integer.parseInt(args[3*i]), args[3*i+1], Float.parseFloat(args[3*i+2]));
a[i].display();
}
Output:
}}
111 abc 1000.0
222 bcd 2000.0
333 cde 5000.0

BITS Pilani, Pilani Campus


BITS Pilani
Pilani Campus

I/O Streams
Stream

• Java performs I/O using Steams. It is a sequence of data

• In Java, stream is composed of bytes

• Three sources for receiving input and sending output


• Console I/O, File I/O and Network I/O

• Automatically created streams


• System.out: Standard output stream
• System.in: Standard input stream
• System.err: Standard error stream

BITS Pilani, Pilani Campus


Streams Supported by JAVA

• Byte Stream: handle I/O of raw binary data; data is 8-


bits
• Character Stream: Java uses a Unicode system which
is a universal international standard character encoding
that is capable of representing most of world’s written
languages. In Unicode, character holds 2 bytes.
• Buffered Stream: optimized to reduce the number of I/O
calls. It reads a stream of data from memory to a buffer.
Native input API is called only when the buffer is empty.
• Data Stream: handle binary I/O of primitive data type
• Object Stream: handle binary I/O of objets.

BITS Pilani, Pilani Campus


BufferedReader
• Reads text from character input stream

• It is advisable to wrap BufferedReader around any Reader


whose read() operations are costlier
• Eg.: BufferedReader in = new BufferedReader(new FileReader("foo.in"));

• Without buffering, each invocation of read() could cause


bytes to be read from the file, converted into characters and
then its returned

• read() – reads a character or character array of known length


from the stream; readLine() – reads a line of text followed by
‘\n’ or \r’
BITS Pilani, Pilani Campus
BufferedReader-Example
import java.io.*;

class Account{
int acc;
String name;
float amount;

void insert(int acc,String name,float amt){


this.acc = acc;
this.name = name;
this.amount = amt; }

void display(){
System.out.println(acc+" "+name+" "+amount);}
}
BITS Pilani, Pilani Campus
class TestAccount{
public static void main(String[] args) throws IOException{

Account a= new Account();


BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

System.out.println("Enter the account no");


int acc ;
acc = Integer.parseInt(br.readLine());

System.out.println("Enter the name");


Console:
String name="";
Enter the account no
name = br.readLine();
111
Enter the name
System.out.println("Enter the amount");
Ankit
Float amount;
Enter the amount
amount = Float.parseFloat(br.readLine());
5000
111 Ankit 5000.0
a.insert(acc, name, amount);
a.display(); }}
BITS Pilani, Pilani Campus
Scanner Class

• It is in java.util package for obtaining input of primitive


types like int, double etc. and strings
• Pass an object of System.in or file to create an object of
the scanner class.
• To read numerical values of certain data type XYZ, use
nextXYZ(). Eg. nextInt(), nextFloat() etc.
• To read strings, use nextLine()
• To read a character array, use next(). It is terminated by
space, new line or carriage return
• To read single character, use next().charAt(0)

BITS Pilani, Pilani Campus


class TestAccount{
public static void main(String[] args) {
Account a= new Account();
Scanner sr = new Scanner(System.in);

System.out.println("Enter the account no");


int acc ;
acc = sr.nextInt();

System.out.println("Enter the name");


String name;
Console:
name = sr.next();
Enter the account no
111
System.out.println("Enter the amount");
Enter the name
Float amount;
Ankit
amount = sr.nextFloat();
Enter the amount
5000
a.insert(acc, name, amount);
111 Ankit 5000.0
a.display();
sr.close(); }}
BITS Pilani, Pilani Campus
class TestAccount{
public static void main(String[] args) {
Account a= new Account();
Scanner sr = new Scanner(System.in);

System.out.println("Enter the account no");


int acc ;
acc = sr.nextInt();

System.out.println("Enter the name");


String name;
name = sr.next(); Console:
Enter the account no
System.out.println("Enter the amount"); 111
Float amount; Enter the name
amount = sr.nextFloat(); Ankit Tiwari
Enter the amount
a.insert(acc, name, amount); Exception in thread "main"
java.util.InputMismatchException
a.display();
sr.close(); }}
BITS Pilani, Pilani Campus
class TestAccount{
public static void main(String[] args) {
Account a= new Account();
Scanner sr = new Scanner(System.in);

System.out.println("Enter the account no");


int acc ;
acc = sr.nextInt();

System.out.println("Enter the name");


String name;
name = sr.nextLine(); Console:
Enter the account no
System.out.println("Enter the amount"); 111
Float amount; Enter the name
amount = sr.nextFloat(); Enter the amount
Ankit
a.insert(acc, name, amount); Exception in thread "main"
java.util.InputMismatchException
a.display();
sr.close(); }}
BITS Pilani, Pilani Campus
What was the problem?

• In Scanner class if we call nextLine() method after any


one of the seven nextXYZ() method then the nextLine()
doesn’t not read values from console and cursor will not
come into console it will skip that step.
• The nextXYZ() methods are nextInt(), nextFloat(), nextByte(), nextShort(),
nextDouble(), nextLong(), next().

• nextXYZ() methods ignore newline character and


nextLine() only reads till first newline character.

• Solution ?

BITS Pilani, Pilani Campus


class TestAccount{
public static void main(String[] args) {
Account a= new Account();
Scanner sr = new Scanner(System.in);

System.out.println("Enter the account no");


int acc ;
acc = sr.nextInt();

sr.nextLine();
System.out.println("Enter the name");
String name; Console:
name = sr.nextLine(); Enter the account no
111
System.out.println("Enter the amount"); Enter the name
Float amount; Ankit Tiwari
amount = sr.nextFloat(); Enter the amount
5000
a.insert(acc, name, amount); 111 Ankit Tiwari 5000.0
a.display();
sr.close(); }} BITS Pilani, Pilani Campus
Other differences

• BufferedReader should be used if we are working with


multiple threads.

• BufferedReader has significantly larger buffer memory


than Scanner.
• The Scanner has a little buffer (1KB char buffer) as opposed to the
BufferedReader (8KB byte buffer).

• BufferedReader is a bit faster as compared to scanner


because scanner does parsing of input data and
BufferedReader simply reads sequence of characters.

BITS Pilani, Pilani Campus


Object Oriented Programming
CS F213
J. Jennifer Ranjani
email: jennifer.ranjani@pilani.bits-pilani.ac.in
Chamber: 6121 B, NAB
BITS Pilani Consultation: Appointment by e-mail
Pilani Campus
Inheritance
BITS Pilani
Pilani Campus
What is Inheritance?

• An Object acquires all the properties and behavior of a


parent

• New classes can be built upon the existing classes

• Methods and fields of the parent class can be reused

• Runtime polymorphism can be achieved

BITS Pilani, Pilani Campus


Rules

• All data members of the superclass are also data


members of the subclass. Similarly, the methods of the
superclass are also the methods of the subclass.

• The private members of the superclass cannot be


accessed by the members of the subclass directly.

• The subclass can directly access the public members of


the superclass.

BITS Pilani, Pilani Campus


Types of Inheritance

BITS Pilani, Pilani Campus


Types of Inheritance

BITS Pilani, Pilani Campus


Why is Multiple Inheritance not
Supported?
class A{
void msg(){System.out.println("Hello");}
}
class B{
void msg(){System.out.println("Welcome");}
}
class C extends A,B{//suppose if it were

Public Static void main(String args[]){


C obj=new C();
obj.msg(); //Now which msg() method would be invoked?
}
}

BITS Pilani, Pilani Campus


BITS Pilani
Pilani Campus

‘Super’ Keyword
Immediate parent class instance
variable
class Animal{
String color="white";
}
class Dog extends Animal{
String color="black";
void printColor(){
System.out.println(color);//prints color of Dog class
System.out.println(super.color);//prints color of Animal class
}
}
class TestSuper1{
public static void main(String args[]){
Dog d=new Dog();
d.printColor();
}}
BITS Pilani, Pilani Campus
Invoke parent class method
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void eat(){System.out.println("eating bread...");}
void bark(){System.out.println("barking...");}
void work(){
super.eat();
bark();
}
}
class TestSuper2{
public static void main(String args[]){
Dog d=new Dog();
d.work();
}}
BITS Pilani, Pilani Campus
Invoke parent class constructor
class Animal{
Animal(){System.out.println("animal is created");}
}
class Dog extends Animal{
Dog(){
super();
System.out.println("dog is created");
}
}
class TestSuper3{
public static void main(String args[]){
Dog d=new Dog();
}}

BITS Pilani, Pilani Campus


Multi Level Inheritance

class Car{ public class Maruti800 extends Maruti{


public Car() { public Maruti800() {
System.out.println("Class Car"); } System.out.println("Maruti Model:
public void vehicleType() { 800"); }
System.out.println("Vehicle Type: public void speed() {
Car"); } } System.out.println("Max: 80Kmph");}
class Maruti extends Car{
public Maruti() { public static void main(String args[])
System.out.println("Class Maruti"); } {
public void brand() { Maruti800 obj=new Maruti800();
System.out.println("Brand: Maruti");} obj.vehicleType();
public void speed() { obj.brand();
System.out.println("Max: 90Kmph"); obj.speed();
} } }
}

BITS Pilani, Pilani Campus


Multi Level Inheritance

class Grandparent { class Child extends Parent {


public void Print() { public void Print() {
System.out.println("Grandparent's super.super.Print(); //Error
Print()"); System.out.println("Child's
} Print()");
} }
}
class Parent extends Grandparent {
public void Print() { public class Main {
System.out.println("Parent's public static void main(String[] args) {
Print()"); Child c = new Child();
} c.Print();
} }
}

BITS Pilani, Pilani Campus


Multi Level Inheritance

class Grandparent { class Child extends Parent {


public void Print() { public void Print() {
System.out.println("Grandparent's super.Print();
Print()"); System.out.println("Child's
} Print()");
} }
}
class Parent extends Grandparent {
public void Print() { public class Main {
super.Print(); public static void main(String[] args) {
System.out.println("Parent's Child c = new Child();
Print()"); c.Print();
} }
} }

BITS Pilani, Pilani Campus


Bank Inheritance Scenario

BITS Pilani, Pilani Campus


Single Inheritance - Example
class BankAccount{ float getBalance(){
private int acc; return amount;}
private String name;
private float amount; void deposit(float amount) {
this.amount = this.amount+amount; }
BankAccount(int acc,String name,float amt)
{ void withdraw(float amount) {
this.acc = acc; if (this.amount < amount)
this.name = name; System.out.println("Insufficient
this.amount = amt; } Funds. Withdrawal Failed");
else
void setAcc(int acc) { this.amount=this.amount-amount; }
this.acc = acc; } }

void setName(String name) {


this.name = name; }

BITS Pilani, Pilani Campus


Single Inheritance - Example
class SavingsAccount extends BankAccount
{
private float interest;

SavingsAccount(int acc,String name,float amt,float interest) {


super(acc,name,amt);
this.interest = interest; }

void addInterest() {
float interest = getBalance()*this.interest /100;
deposit(interest);
}
}

BITS Pilani, Pilani Campus


Single Inheritance - Example
class TestAccount{
public static void main(String[] args) {

SavingsAccount sa= new SavingsAccount(111,"Ankit",5000,9);

System.out.println("Initial: "+sa.getBalance());

sa.deposit(1000);
System.out.println("After Deposit: " + sa.getBalance());

sa.addInterest();
System.out.println("Deposit+Interest: " + sa.getBalance());

sa.withdraw(6000);
System.out.println("After Withdraw: " + sa.getBalance()); }}

BITS Pilani, Pilani Campus


Object Oriented Programming
CS F213
J. Jennifer Ranjani
email: jennifer.ranjani@pilani.bits-pilani.ac.in
Chamber: 6121 B, NAB
BITS Pilani Consultation: Appointment by e-mail
Pilani Campus
Overriding, Abstract
Class and Arrays
BITS Pilani
Pilani Campus
BITS Pilani
Pilani Campus

Method Overriding
What is Overriding?

• In a class hierarchy, when a method in a subclass has


the same name and type signature as a method in its
superclass, then the method in the subclass is said to
override the method in the superclass.
• When an overridden method is called from within a
subclass, it will always refer to the version of that method
defined by the subclass.
• The version of the method defined by the superclass will
be hidden.
• A subclass may call an overridden superclass method by
prefixing its name with the ‘super’ keyword and a dot (.).

BITS Pilani, Pilani Campus


Overriding - Example
class CheckingAccount extends BankAccount void deposit(float amount)
{ {
private static final float TRANS_FEE = 25; TransCount++;
private static final int FREE_TRANS = 2; super.deposit(amount);
private float TransCount =0; }
void withdraw(float amount)
CheckingAccount(int acc,String name,float amt) { {
super(acc,name,amt); } TransCount++;
super.withdraw(amount);
void deductFee() { }
if(TransCount > FREE_TRANS)
{ }
float fee = (TransCount-
FREE_TRANS)*TRANS_FEE;
super.withdraw(fee);
TransCount=0;} }

BITS Pilani, Pilani Campus


Overriding - Example
class TestAccount{
public static void main(String[] args) {

CheckingAccount ca= new CheckingAccount(111,"Ankit",5000);

System.out.println("Initial: "+ca.getBalance());

ca.deposit(1000);
ca.withdraw(2000);
ca.deposit(6000);
System.out.println("After three Transactions: " + ca.getBalance());

ca.deductFee();

System.out.println("After fee Deduction: " + ca.getBalance());


}}
BITS Pilani, Pilani Campus
BITS Pilani
Pilani Campus

‘Final’ Keyword
Java Final Keyword

• Makes variable a constant

• Prevents Method Overriding

• Prevents Inheritance

BITS Pilani, Pilani Campus


Blank or uninitialized final
variable
• A final variable that is not initialized at the time of
declaration is known as blank final variable.

• It can be used when variable is initialized at the time of


object creation and should not be changed after that.
• Eg. Pan card

• It can be initialized only once (preferably within a


constructor).

BITS Pilani, Pilani Campus


Final blank variable

Example 1: Example 2:
class first{ class first{
final int i;
public static void main(String i=10 // Error
args[]){ first(){
final int i; i=10;
i=10; }

System.out.println("s1: "+i); public static void main(String


i=20; // Error args[]){

} System.out.println("s1: "+new
} first().i);
}
}

BITS Pilani, Pilani Campus


Static Blank Final Variable

• A static final variable that is not initialized at the time of


declaration is known as static blank final variable. It can
be initialized only in static block.

class A{
static final int data;//static blank final variable
static{ data=50;}
public static void main(String args[]){
System.out.println(A.data);
}
}

BITS Pilani, Pilani Campus


Questions?

• Is final method inherited?


• YES. But it cannot be overridden

• Can we declare a constructor final?


• NO. Constructor is not inherited

BITS Pilani, Pilani Campus


BITS Pilani
Pilani Campus

Run Time Polymorphism


Dynamic Method Dispatch

• Method overriding is one of the ways in which Java


supports Runtime Polymorphism.
• Dynamic method dispatch is the mechanism by which a
call to an overridden method is resolved at run time,
rather than compile time.
• An overridden method is called through the reference
variable of a superclass.
• The determination of the method to be called is based on
the object being referred to by the reference variable.
• Upcasting: The reference variable of Parent class refers
to the object of Child class.

BITS Pilani, Pilani Campus


Bank - Example
class TestAccount{
public static void main(String[] args) {

Scanner sr = new Scanner(System.in);

System.out.println("Enter 1 for new customers (< 1 year) and 0 for others");


int yr = sr.nextInt();

BankAccount ba;

if (yr==1)
ba = new BankAccount(111,"Ankit",5000);
else
ba = new CheckingAccount(111,"Ankit",5000);

BITS Pilani, Pilani Campus


Bank - Example
System.out.println("Initial: "+ba.getBalance());

ba.deposit(1000);
ba.withdraw(2000);
ba.deposit(6000);
System.out.println("After three Transactions: " + ba.getBalance());

ba.deductFee(); //ERROR

System.out.println("After fee Deduction: " + ba.getBalance());


sr.close();

}}

BITS Pilani, Pilani Campus


Solution 1

• Create an empty method in the Bank Account class

void deductFee()
{
}

• Meaningless, Isn’t it?

BITS Pilani, Pilani Campus


Solution 2 – Abstract Class
abstract class BankAccount{ float getBalance(){
private int acc; return amount;}
private String name;
private float amount; void deposit(float amount) {
this.amount = this.amount+amount; }
BankAccount(int acc,String name,float amt)
{ void withdraw(float amount) {
this.acc = acc; if (this.amount < amount)
this.name = name; System.out.println("Insufficient
this.amount = amt; } Funds. Withdrawal Failed");
else
void setAcc(int acc) { this.amount=this.amount-amount; }
this.acc = acc; }
abstract void deductFee();
void setName(String name) { }
this.name = name; }

BITS Pilani, Pilani Campus


Static vs. Dynamic Binding
(Early vs. Late Binding)
• Static binding happens at compile-time while dynamic
binding happens at runtime.
• Binding of private, static and final methods always
happen at compile time since these methods cannot be
overridden.
• When the method overriding is actually happening and
the reference of parent type is assigned to the object of
child class type then such binding is resolved during
runtime.
• The binding of overloaded methods is static and the
binding of overridden methods is dynamic.

BITS Pilani, Pilani Campus


Arrays

• Syntax to declare an array


• int[] arr;
• int []arr;
• int arr[];

• Instantiation of an array
• arr = new int[size];

• Arrays can be accessed using


• Simple for loop
• For each loop
• Labelled for loop

BITS Pilani, Pilani Campus


For each loop

int arr[]={12,23,44,56,78};
//Printing array using for-each loop
for(int i:arr){
System.out.println(i);
}

BITS Pilani, Pilani Campus


Labelled For Loop

aa:
for(int i=1;i<=3;i++){
bb:
for(int j=1;j<=3;j++){
if(i==2&&j==2){
break bb;
}
System.out.println(i+" "+j);
}
}

BITS Pilani, Pilani Campus


Array Index Out of Bounds

• Array indices always start with 0, and always end


with the integer that is one less than the size of
the array
• The most common programming error made when using arrays is attempting to
use a nonexistent array index

• When an index expression evaluates to some


value other than those allowed by the array
declaration, the index is said to be out of bounds
• An out of bounds index will cause a program to terminate with a run-time error
message
• Array indices get out of bounds most commonly at the first or last iteration of a
loop that processes the array: Be sure to test for this!

BITS Pilani, Pilani Campus


Array of Characters is not a
String!!!
• An array of characters is conceptually a list of
characters, and so is conceptually like a string
• However, an array of characters is not an object
of the class String
• char[] a = {'A', 'B', 'C'};
• String s = a; //Illegal!

• An array of characters can be converted to an


object of type String, however
• char[] a = {'A', 'B', 'C'};
• String s = new String(a);
• System.out.println(s);
• s = new String(a,1,2);
• System.out.println(s);

BITS Pilani, Pilani Campus


Copying a Java Array

public static void arraycopy(Object src, int srcPos,Object dest, int destPos, int length)

• arraycopy method of the System class is used to copy an


array to another.

int a[]= {2,3,5};


int b[] = new int[a.length];

System.arraycopy(a, 1, b, 0, a.length-1);

for(int i=0;i<b.length;i++)
System.out.print(" "+b[i]);
Output:
350

BITS Pilani, Pilani Campus


Array Class
static type binarySearch(type[] a, type key)
Searches the specified array of type for the specified value using
the binary search algorithm.
static boolean equals(type[] a, type[] a2)
Returns true if the two specified arrays of type are equal to one
another.
static void fill(type[] a, type val)
Assigns the specified type value to each element of the specified array
of type.
static void fill(type[] a, int fromIndex, int toIndex, type val)
Assigns the specified type value to each element of the specified
range of the specified array of types.
static void sort(type[] a)
Sorts the specified array of type into ascending numerical order.
static void sort(type[] a, int fromIndex, int toIndex)
Sorts the specified range of the specified array of type into ascending
numerical order.

type = byte, char, double, float, int, long, short, Object


BITS Pilani, Pilani Campus
Array Class - Example
int a[]= {2,3,5,1,4,7};

for(int i=0;i<a.length;i++)
Output:
System.out.print(a[i]+" "); 235147
[1, 2, 3, 5, 4, 7]
System.out.println(); [1, 2, 3, 4, 5, 7]
Arrays.sort(a,0,4); Binary Search for 5 is 4
System.out.println(Arrays.toString(a));

Arrays.sort(a);
System.out.println(Arrays.toString(a));

System.out.println("Binary Search for 5 is "+Arrays.binarySearch(a, 5));

BITS Pilani, Pilani Campus


Array Class - Example
int a[]= {2,3,5,1,4,7};

System.out.println(Arrays.toString(Arrays.copyOf(a, a.length)));

System.out.println(Arrays.toString(Arrays.copyOfRange(a, 1,4)));

Arrays.fill(a,4,a.length,1); Output:
System.out.println(Arrays.toString(a)); [1, 2, 3, 4, 5, 7]
[2, 3, 4]
[1, 2, 3, 4, 1, 1]
Arrays.fill(a,1);
[1, 1, 1, 1, 1, 1]
System.out.println(Arrays.toString(a));

BITS Pilani, Pilani Campus


Object Oriented Programming
CS F213
J. Jennifer Ranjani
email: jennifer.ranjani@pilani.bits-pilani.ac.in
Chamber: 6121 B, NAB
BITS Pilani Consultation: Appointment by e-mail
Pilani Campus
-Arrays
-Interfaces
BITS Pilani
Pilani Campus
Answers to the Queries in
previous class
1. Constructor cannot be preceded with a final keyword.
Only access modifiers can be specified before a
constructor
2. Class A {
int I = 10; // is allowed
A(){
I = 20; // I is changed and previously assigned value
is of no use
}
3. next(), nextInt(), nextFloat() etc ignores the leading
spaces

BITS Pilani, Pilani Campus


Difference between Reference
and Object
class zero{ i
int i;
j
float j;
} 2f410acf

class first{
public static void main(String args[]){
2f410acf
zero a = new zero(); a
System.out.println(a);
a.i =10;
a.j=20;
}
}

BITS Pilani, Pilani Campus


Runtime Polymorphism in
Multilevel Hierarchy
class zero{ class second extends first{
int i=10; int i=50;
float j=20; float j=60;
void show() { void show() {
System.out.println(i+" "+j);}} System.out.println(i+" "+j);}
public static void main(String
class first extends zero { args[]){
int i=30; zero a ;
float j=40; a = new first();
void show() { a.show();
System.out.println(i+" "+j);} first s;
Output:
} s= new second(); 30 40.0
s.show(); 50 60.0
}
}
BITS Pilani, Pilani Campus
Runtime Polymorphism with
Data Members
class zero{
int i=10;
float j=20; }
class first extends zero {
int i=30;
float j=40; }
class second extends first{
int i=50;
float j=60;
public static void main(String args[]){
zero a ; Output:
10 20.0
a = new first();
30 40.0
System.out.println(a.i+" "+a.j);
first s;
s= new second();
System.out.println(s.i+" "+s.j); } }
BITS Pilani, Pilani Campus
Predict the output

int arr1[] = {1, 2, 3};


int arr2[] = {1, 2, 3};
if (arr1 == arr2)
System.out.println("Same");
else
System.out.println("Not same");

Output: Not same


Problem: == compares the array references
Solution: Arrays.equals(arr1, arr2)

BITS Pilani, Pilani Campus


Predict the output

int inarr1[] = {1, 2, 3};


int inarr2[] = {1, 2, 3};
Object[] arr1 = {inarr1};
Object[] arr2 = {inarr2};
if (Arrays.equals(arr1, arr2))
System.out.println("Same");
else
System.out.println("Not same");

Output: Not same


Solution: Arrays.deepEquals(arr1, arr2)
BITS Pilani, Pilani Campus
Predict the output

int inarr1[] = {1, 2, 3};


int inarr2[] = {1, 2, 3};
Object[] arr1 = {inarr1};
Object[] arr2 = {inarr2};
Object[] outarr1 = {arr1};
Object[] outarr2 = {arr2};
if (Arrays.deepEquals(outarr1, outarr2))
System.out.println("Same");
else
System.out.println("Not same");
Solution: Same
BITS Pilani, Pilani Campus
Final Arrays
class Test
{
public static void main(String args[])
{
final int arr[] = {1, 2, 3, 4, 5}; // Note: arr is final
for (int i = 0; i < arr.length; i++)
{
arr[i] = arr[i]*10;
System.out.println(arr[i]);
} Output:
} 10
} 20
30
40
50

BITS Pilani, Pilani Campus


Final Arrays

• Arrays are objects and object variables are always


references in Java.

• When an object variable is declared as final, it means


that the variable cannot be changed to refer to anything
else.

BITS Pilani, Pilani Campus


Jagged Arrays

2D array with variable number of columns in each row.


int arr[][] = new int[2][];
arr[0] = new int[3];
arr[1] = new int[2];
int count = 0;
for (int i=0; i<arr.length; i++)
for(int j=0; j<arr[i].length; j++)
arr[i][j] = count++;
for (int i=0; i<arr.length; i++) {
for (int j=0; j<arr[i].length; j++)
System.out.print(arr[i][j] + " ");
System.out.println(); }

BITS Pilani, Pilani Campus


Printing a 2D Array using
toString
int inarr1[] = {1, 2, 3};
int inarr2[] = {4, 5, 6};

Object arr[] = {inarr1,inarr2};


System.out.println(Arrays.deepToString(arr));

int a[][]= {{1,2,3},{4,5}};


System.out.println(Arrays.deepToString(a));

Output:
System.out.println(a[1].length); [[1, 2, 3], [4, 5, 6]]
[[1, 2, 3], [4, 5]]
2

BITS Pilani, Pilani Campus


More on Final Objects

class Test class Test


{ {
int p = 20; int p = 20;
public static void main(String public static void main(String
args[]) args[])
{ {
final Test t = new Test(); final Test t1 = new Test();
t.p = 30; Test t2 = new Test();
System.out.println(t.p); t1 = t2;
} System.out.println(t1.p);
} }
}

Output: 30 Compiler Error

BITS Pilani, Pilani Campus


BITS Pilani
Pilani Campus

Interfaces
Interface

• Interface is a blueprint of a class containing static


constants and abstract methods. It cannot have a
method body.

• It is a mechanism to achieve abstraction.

BITS Pilani, Pilani Campus


Relationship between Classes
and Interfaces

BITS Pilani, Pilani Campus


Interfaces - Example
Interface Bank {
void deductFee();
void withdraw(float amount);
void deductFee();}

class BankAccount implements Bank{


.
.
public void deductFee();{}
}

class CheckingAccount extends BankAccount implements Bank


{
.
.
.
}
BITS Pilani, Pilani Campus
Multiple Inheritance in
Interface

BITS Pilani, Pilani Campus


Why is Multiple Inheritance not
a problem in Interface?
interface Printable{ public class test {
void print(); public static void main(String[]
void show(); } args) {
interface Showable{ trial t = new trial();
void show(); t.print();
void print(); } t.show();
}
class trial implements }
Printable,Showable {
public void show() {
System.out.println("Within Show");}

public void print() {


System.out.println("Within Print");}
}
BITS Pilani, Pilani Campus
Default Methods in Interface
(defender or virtual extension)
• Before Java 8, interfaces could have only abstract
methods. Implementation is provided in a separate class

• If a new method is to be added in an interface,


implementation code has to be provided in all the
classes implementing the interface.

• To overcome this, default methods are introduced which


allow the interfaces to have methods with
implementation without affecting the classes.

BITS Pilani, Pilani Campus


Default Methods

interface Printable{ public class test {


void print(); public static void main(String[]
default void show() args) {
{ trial t = new trial();
System.out.println("Within Show"); t.print();
} t.show();
} }

class trial implements Printable { }

public void print()


{
System.out.println("Within Print");
}
}
BITS Pilani, Pilani Campus
Default Methods & Multiple
Inheritance
interface Printable{ class trial implements Printable,Showable{
void print(); public void show() {
default void show() Printable.super.show();
{ Showable.super.show(); }
System.out.println("Within
Printable Show"); public void print() {
} System.out.println("Within Print"); }}
}
interface Showable{ public class test {
default void show() public static void main(String[] args) {
{ trial t = new trial();
System.out.println("Within t.print();
Showable Show"); t.show();
} }
void print(); }
} BITS Pilani, Pilani Campus
Object Oriented Programming
CS F213
J. Jennifer Ranjani
email: jennifer.ranjani@pilani.bits-pilani.ac.in
Chamber: 6121 B, NAB
BITS Pilani Consultation: Appointment by e-mail
Pilani Campus
-Interfaces
-Nested Interfaces
BITS Pilani
Pilani Campus
BITS Pilani
Pilani Campus

Interfaces
Default Methods in Interface
(defender or virtual extension)
• Before Java 8, interfaces could have only abstract
methods. Implementation is provided in a separate class

• If a new method is to be added in an interface,


implementation code has to be provided in all the
classes implementing the interface.

• To overcome this, default methods are introduced which


allow the interfaces to have methods with
implementation without affecting the classes.

BITS Pilani, Pilani Campus


Default Methods

interface Printable{ public class test {


void print(); public static void main(String[]
default void show() args) {
{ trial t = new trial();
System.out.println("Within Show"); t.print();
} t.show();
} }

class trial implements Printable { }

public void print()


{
System.out.println("Within Print");
}
}
BITS Pilani, Pilani Campus
Static Methods in Interfaces

interface Printable{ public class test {


void print(); public static void main(String[]
static void show() args) {
{ trial t = new trial();
System.out.println("Within t.print();
Printable Show"); Printable.show();
} }
} }

class trial implements Printable {


Question:
public void print() Can we replace Printable.show()
{ with t.show()?
System.out.println("Within Print");
}
}
BITS Pilani, Pilani Campus
Static Methods in Interfaces

interface Printable{ public class test {


void print(); public static void main(String[]
static void show() args) {
{ trial t = new trial();
System.out.println("Within t.print();
Printable Show"); t.display(); //Warning
} t.show(); //Error
} }
class trial implements Printable { }
public void print() {
System.out.println("Within Print");}
static void display()
{
System.out.println("Within
Display");
}} BITS Pilani, Pilani Campus
Default Methods & Multiple
Inheritance
interface Printable{ class trial implements Printable,Showable{
void print(); public void show() {
default void show() Printable.super.show();
{ Showable.super.show(); }
System.out.println("Within
Printable Show"); public void print() {
} System.out.println("Within Print"); }}
}
interface Showable{ public class test {
default void show() public static void main(String[] args) {
{ trial t = new trial();
System.out.println("Within t.print();
Showable Show"); t.show(); Question:
} } What happens if super
void print(); } keyword is omitted?
} BITS Pilani, Pilani Campus
Nested Interfaces

• Interface can be declared within another interface or


class

• Nested interface cant be accessed directly, it is referred


by the outer interface or class

• Nested interface must be public if it is declared inside the


interface but it can have any access modifier if declared
within the class.

• Nested interfaces are declared static implicitly.

BITS Pilani, Pilani Campus


Class Implementing Outer
Interface
interface Printable{ public class test {
void print(); public static void main(String[]
interface Showable{ args) {
void show(); } trial t = new trial();
} t.print();
t.show();
class trial implements Printable { }
public void print() }
{
System.out.println("Within Print"); Question:
} What happens when
public void show() { implementation of show() is
removed from class trial?
System.out.println("Within Show");
}
}
BITS Pilani, Pilani Campus
Class Implementing Outer
Interface
interface Printable{ public class test {
void print(); public static void main(String[]
interface Showable{ args) {
void show(); } trial t = new trial();
} t.print();
}
class trial implements Printable { }
public void print()
{ Answer: Nothing
System.out.println("Within Print"); happens. Outer interface
} does not have access to
}
inner interface.

BITS Pilani, Pilani Campus


Class Implementing Inner
Interface
interface Printable{ public class test {
void print(); public static void main(String[]
interface Showable{ args) {
void show();} trial t = new trial();
} t.print1();
class trial implements t.show();
Printable.Showable { }
public void print1()
{ }
System.out.println("Within Print");
} Note: If we omit the
public void show()
implementation of show()
{
method, we get
System.out.println("Within Show");
}
compilation error
} BITS Pilani, Pilani Campus
Interface within the Class

class Printable{ public class test {


public void print() public static void main(String[]
{ args) {
System.out.println("Within Print"); trial t = new trial();
} t.show();
interface Showable{ t.print(); //print undefined for the type
void show();} trail
} }
}
class trial implements
Printable.Showable {
public void show()
{
System.out.println("Within Show");
}}
BITS Pilani, Pilani Campus
Interface within the Class

class Printable{ public class test {


public void print() public static void main(String[]
{ args) {
System.out.println("Within Print"); trial t = new trial();
} t.show();
interface Showable{ t.print();
void show();} }
} }

class trial extends Printable Output:


implements Printable.Showable Within Show
{ Within Print
public void show()
{
System.out.println("Within Show");
}} BITS Pilani, Pilani Campus
Class within the Interface

interface Showable{ public class test {


class Printable{ public static void main(String[]
public void print() args) {
{ trial t = new trial();
System.out.println("Within Print"); t.show();
}} t.print();
void show(); }
} }

class trial extends Output:


Showable.Printable { Within Show
public void show() Within Print
{
System.out.println("Within Show");
}}
BITS Pilani, Pilani Campus
Class within the Interface

interface Showable{ public class test {


class Printable{ public static void main(String[]
public void print() args) {
{ trial t = new trial();
System.out.println("Within Print"); t.show();
}} t.print();
void show1(); }
} }
class trial extends
Showable.Printable implements
Error:
Showable {
Class trial should
public void show() implement the method
{ show1()
System.out.println("Within Show");
}}
BITS Pilani, Pilani Campus
What happens if the class does not
implement all members of the Interface?
interface Printable{
void print();
void show();
}
abstract class trial implements Printable {
public void print() {
System.out.println("Within Print");
}}

public class test {


Error:
public static void main(String[] args) {
Cannot Instantiate trial
trial t = new trial();
t.print();} (Because trail is an
} abstract class)

BITS Pilani, Pilani Campus


What happens if the class does not
implement all members of the Interface?
interface Printable{
void print();
void show(); }

abstract class trial implements Printable {


public void print() {
System.out.println("Within Print");}
}

public class test extends trial {


Output:
public void show() {
Within Show
System.out.println("Within Show");} Within Print
public static void main(String[] args) {
test t = new test();
t.print();
t.show();}} BITS Pilani, Pilani Campus
Object Oriented Programming
CS F213
J. Jennifer Ranjani
email: jennifer.ranjani@pilani.bits-pilani.ac.in
Chamber: 6121 B, NAB
BITS Pilani Consultation: Appointment by e-mail
Pilani Campus
-Interfaces
-Nested Classes
BITS Pilani
Pilani Campus
Queries asked in the previous
class

• What is the output?


class Parent{
static int A=50;
static void show() {
System.out.println(A);
}}

class Child extends Parent{


int A=10; Compilation Error:
int show() { Instance method cannot
System.out.println(A); override a static method
from parent
}}

BITS Pilani, Pilani Campus


Queries asked in the previous
class
class Parent{
static int A=50;
static void show() {
System.out.println(A); Output:
}} 50
10
class Child extends Parent{
Warning:
int A=10; The static method show() from
} the type Parent should be
class test{ accessed in a static way
public static void main(String args[]) {
Child c = new Child();
c.show();
System.out.println(c.A); }
}
BITS Pilani, Pilani Campus
Queries asked in the previous
class
interface Printable{
void show();
}
Error:
interface Showable{ Return type is incompatible
int show();
}

class trial implements Printable,Showable{


public int show() {
System.out.println("Within Show");
}
}

BITS Pilani, Pilani Campus


Queries asked in the previous
class
interface Printable{ class trial implements
static void show() { Printable,Showable{
System.out.println("Within Static }
Show"); class test{
}; public static void main(String
} args[]) {
trial t = new trial();
interface Showable{ t.show();
default void show() }
{ }
System.out.println("Within default
Output:
Show");
Within default Show
};
}

BITS Pilani, Pilani Campus


Queries asked in the previous
class
interface Printable{ class trial implements
static void show() { Printable,Showable{
System.out.println("Within Static public void show() {
Show"); System.out.println("Within Show");
}; Showable.super.show();
} Printable.show();
}}
interface Showable{ class test{
default void show() public static void main(String
{ args[]) {
System.out.println("Within default trial t = new trial();
Show"); t.show();
}; }
Output:
} } Within Show
Within default Show
Within Static Show
BITS Pilani, Pilani Campus
Queries asked in the previous
class
interface Printable{
int data=20;
class Showable{
void show()
{
System.out.println("Interface Variable "+data);
}
}
}
class test extends Printable.Showable{
Output:
public static void main(String args[]) {
Interface Variable 20
test c = new test();
c.show();
}}

BITS Pilani, Pilani Campus


BITS Pilani
Pilani Campus

Nested Classes
Inner Classes

• Nested classes are used to logically group classes or


interfaces in one place, for more readability and
maintainability.
• Nested class can access all members of the outer class
including the private data members and methods.
• Two types:
• Non-static nested class (inner class)

• Member
• Anonymous
• Local
• Static nested class

BITS Pilani, Pilani Campus


Member Inner class - Example
class Outer{
int data = 30;
private int val = 20;
class Inner{
void show() {
System.out.println("Data=:"+data+"Value="+val);} }
}
class test{
public static void main(String args[]) {
Outer o = new Outer();
Outer.Inner in = o.new Inner();
in.show();
} }

BITS Pilani, Pilani Campus


Member Inner Class

• Compiler creates two class files of the inner class


• Outer.class and Outer$Inner.class

• To instantiate the inner class, the instance of the outer


class must be created

• The inner class have a reference to the outer class, thus


it can access all the data members of the outer class.

BITS Pilani, Pilani Campus


Member Inner class - Example
class Outer{
int data = 30;
private int val = 20;
private class Inner{
void show() {
System.out.println("Data=:"+data+"Value="+val);}
}
void print() {
Inner in = new Inner();
Note:
in.show();} Unlike a class, an inner class
} can be private.
class test{
public static void main(String args[]) {
o.print();}
}
BITS Pilani, Pilani Campus
Anonymous Inner Class

• Class with no name

• Used when a method or interface is to be overridden

BITS Pilani, Pilani Campus


Anonymous class - Example
abstract class Outer{
int data = 30;
abstract void show();
void print() {
System.out.println("Within Print");
}
}
class test {
public static void main(String args[]) {
Outer o = new Outer() {
void show() {
System.out.println("Data=:"+data);}
};
o.show();
o.print();
}} BITS Pilani, Pilani Campus
Anonymous Class

• The name of the class created is decided by the


compiler

• In the given example, the anonymous class extends the


‘Outer’ class and gives implementation for the show()
method.

• The object of the anonymous class can be referred by


the reference variable ‘o’

• Anonymous class cannot have additional methods


because it is accessed using the reference to the ‘Outer’
class BITS Pilani, Pilani Campus
Anonymous Inner Class using
Interface-Example
interface Outer{
int data = 30;
void show();
}
class test {
public static void main(String args[]) {
Outer o = new Outer() {
public void show() {
System.out.println("Data=:"+data);
//data =25; // Error
}
};
o.show();
}
}
BITS Pilani, Pilani Campus
Local Inner Class-Example
class Outer{
private int data = 30;
void show() {
int val =50;
class inner{
void print() {
System.out.println("Value= "+val+"Data="+data);}}
inner i =new inner(); // Creating a named type
i.print(); }
}
class test { Note:
Local inner class can be
public static void main(String args[]) {
instantiated only within the
Outer o = new Outer(); method it is defined.
o.show();
//o.print(); //Error}
} BITS Pilani, Pilani Campus
Static Inner Class-Example
class Outer{
static int data = 30;
private static int val = 20;
static class Inner{
void show() {
System.out.println("Data=:"+data+"Value="+val);
}
}
}
class test{
public static void main(String args[]) {
Outer.Inner in = new Outer.Inner();
in.show();
}
}
BITS Pilani, Pilani Campus
Static Inner Class

• A static class created inside a class.

• It can access the static data members of the outer class


including the private members.

• It cannot access the non-static members and methods.

• The object of the outer class need not be created,


because static methods or classes can be accessed
without object.
• Note: Only inner classes can be prefixed with the static
keyword.
BITS Pilani, Pilani Campus
Take Home Exercise: What happens when the Interface
Showable is private? Update the following code.

class Printable{ public class test {


public void print() public static void main(String[]
{ args) {
System.out.println("Within Print"); trial t = new trial();
} t.show();
interface Showable{ t.print();
void show();} }
} }

class trial extends Printable Output:


implements Printable.Showable Within Show
{ Within Print
public void show()
{
System.out.println("Within Show");
}} BITS Pilani, Pilani Campus
BITS Pilani
Pilani Campus

Packages
Create a package & sub
package

Project  New 
Package

BITS Pilani, Pilani Campus


Create a class within the
package

Package  New 
class

BITS Pilani, Pilani Campus


Class within the package

package class2.sub;

public class Test {

public static void main(String[] args) {


// TODO Auto-generated method stub

BITS Pilani, Pilani Campus


Importing a package

package class1; package class2.sub;


import class1.*;
public class HelloWorld
{ public class Test {
public void show() {
System.out.println("Within class public static void main(String[]
1's show"); args) {
} HelloWorld h = new HelloWorld();
} h.show();

BITS Pilani, Pilani Campus


Importing a class

package class1; package class2.sub;


import class1.HelloWorld;
public class HelloWorld
{ public class Test {
public void show() { public static void main(String[]
System.out.println("Within class args) {
1's show"); HelloWorld h = new HelloWorld();
} h.show();
} }
}

Take Home Exercise: Learn how to execute the same


code from the command prompt.

BITS Pilani, Pilani Campus


Access Modifiers

Access within within outside outside


Modifier class package package package
by
subclass
only
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y

BITS Pilani, Pilani Campus


Object Oriented Programming
CS F213
J. Jennifer Ranjani
email: jennifer.ranjani@pilani.bits-pilani.ac.in
Chamber: 6121 B, NAB
BITS Pilani Consultation: Appointment by e-mail
Pilani Campus
-Packages
-Downcasting
-Strings
BITS Pilani
Pilani Campus
Solution to Take Home Exercise
given in the Previous Class
class Printable{ public class test {
private interface Showable{ public static void main(String[]
void show();} args) {
Printable t = new Printable();
class ShowClass implements t.print();
Showable { }
public void show() {
}
System.out.println("Within Show");}
}
public void print() {
ShowClass s = new ShowClass();
s.show();
System.out.println("Within Print"); }
}

BITS Pilani, Pilani Campus


BITS Pilani
Pilani Campus

Packages
Create a package & sub
package

Project  New 
Package

BITS Pilani, Pilani Campus


Create a class within the
package

Package  New 
class

BITS Pilani, Pilani Campus


Class within the package

package class2.sub;

public class Test {

public static void main(String[] args) {


// TODO Auto-generated method stub

BITS Pilani, Pilani Campus


Importing a package

package class1; package class2.sub;


import class1.*;
public class HelloWorld
{ public class Test {
public void show() {
System.out.println("Within class public static void main(String[]
1's show"); args) {
} HelloWorld h = new HelloWorld();
} h.show();

BITS Pilani, Pilani Campus


Importing a class

package class1; package class2.sub;


import class1.HelloWorld;
public class HelloWorld
{ public class Test {
public void show() { public static void main(String[]
System.out.println("Within class args) {
1's show"); HelloWorld h = new HelloWorld();
} h.show();
} }
}

Take Home Exercise: Learn how to execute the same


code from the command prompt.

BITS Pilani, Pilani Campus


Access Modifiers

Access within within outside outside


Modifier class package package package
by
subclass
only
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y

BITS Pilani, Pilani Campus


BITS Pilani
Pilani Campus

Down casting
Downcasting

• When subclass type refers to the object of the parent


class
• SavingsAccount sa = new BankAccount(); // compilation error

• If downcasting is done, no compilation error but


ClassCastException is thrown at run time.
• SavingsAccount sa =(SavingsAccount) new BankAccount();

BITS Pilani, Pilani Campus


‘instanceof’ operator

• It compares the instance with the type and returns true


or false.
• Account a1 = new Account();
• System.out.println(a1 instanceof Account);

• If instanceof operator is applied on a variable that has


null value, it returns false.
• Account a1=null;
• System.out.println(a1 instanceof Account);

• An object of subclass type is also a type of the parent


class.

BITS Pilani, Pilani Campus


Downcasting - Example
abstract class Animal { class Dog extends Animal {
public void eat() { public void bark() {
System.out.println("Eating..."); System.out.println("Bow
} Bow!");
}
public void move() { public void eat() {
System.out.println("Dog is
System.out.println("Moving..."); eating...");
} }
}
public void sleep() {
class Cat extends Animal {
System.out.println("Sleeping...") public void meow() {
; System.out.println("Meow
} Meow!");
}
} }
BITS Pilani, Pilani Campus
Downcasting - Example

class AnimalTrainer { class test{


public void teach(Animal anim) { public static void main(String[]
anim.move(); args) {
anim.eat(); Dog dog = new Dog();
Cat cat = new Cat();
if (anim instanceof Cat) {
Cat cat = (Cat) anim; AnimalTrainer trainer = new
cat.meow(); AnimalTrainer();
} else if (anim instanceof Dog) trainer.teach(cat);
{ }
Dog dog = (Dog) anim; }
dog.bark();
}
}
}
BITS Pilani, Pilani Campus
BITS Pilani
Pilani Campus

Strings
Strings

• Java string is a sequence of characters. They are


objects of type String.
• Once a String object is created it cannot be changed.
Stings are Immutable.
• To get changeable strings use the class called
StringBuffer.
• String and StringBuffer classes are declared final, so
there cannot be subclasses of these classes.
• The default constructor creates an empty string.
String s = new String();

BITS Pilani, Pilani Campus


String creation

String str = "abc"; is equivalent to:


char data[] = {'a', 'b', 'c'};
String str = new String(data);

• If data array in the above example is modified after the


string object str is created, then str remains unchanged.

• Construct a string object by passing another string


object.
String str2 = new String(str);

BITS Pilani, Pilani Campus


String Constructors

• String(byte[] byte_arr) – default character set (ASCII)


byte[] b_arr = {74, 97, 118, 97};
String str =new String(b_arr); // JAVA

• String(byte[] byte_arr, Charset char_set)


byte[] b_arr = {0x4a, 0x61, 0x76, 0x61};
Charset cs = Charset.forName("UTF-8");
String str = new String(b_arr, cs);

• Refer (List of character set supported by Java):


https://docs.oracle.com/javase/8/docs/technotes/gui
des/intl/encoding.doc.html

BITS Pilani, Pilani Campus


String Constructors

• String(byte[] byte_arr, String char_set_name)


byte[] b_arr = {0x4a, 0x61, 0x76, 0x61};
String str = new String(b_arr, "UTF-8");

• String(byte[] byte_arr, int start_index, int length)


• String(byte[] byte_arr, int start_index, int length,
Charset char_set)
• String(byte[] byte_arr, int start_index, int length,
String char_set_name)

• String(char[] char_arr)
• String(char[] char_array, int start_index, int count)
BITS Pilani, Pilani Campus
BITS Pilani
Pilani Campus

String Methods
Length and Append

• The length() method returns the length of the string.


System.out.println(“Hello World”.length());
// prints 11

• The + operator is used to concatenate two or more


strings.
String myname = “Harry”
String str = “My name is ” + myname+ “.”;

• For string concatenation the Java compiler converts an


operand to a String whenever the other operand of the +
is a String object.

BITS Pilani, Pilani Campus


String Methods-Character
Extraction
• Characters in a string can be extracted in a number of
ways.

• public char charAt(int index)


– Returns the character at the specified index. An index
ranges from 0 to length() - 1.
char ch;
ch = "Hello World".charAt(4);

String s1 = new String("Hello World");


ch=s1.charAt(4);
Output:
o

BITS Pilani, Pilani Campus


String Methods-Character
Extraction
• public void getChars(int start, int end, char[]
destination, int destination_start)
s1 = "Hello World";
char ch[]=new char[20];
s1.getChars(0, 11, ch, 0);

• public byte[] getBytes()

• public char[] toCharArray()


s1 = "Hello World";
char ch[]=s1.toCharArray();

BITS Pilani, Pilani Campus


String Methods

To compare two string objects


• boolean equals( Object otherObj)
• boolean equalsIgnoreCase (String anotherString)
• int compareTo( String anotherString): Compares two
string lexicographically.
s1 = "World"; Output:
15
s2 = "Hello";
p=s1.compareTo(s2);
• This returns difference s1-s2. If :
out < 0 // s1 comes before s2
out = 0 // s1 and s2 are equal.
out >0 // s1 comes after s2.

BITS Pilani, Pilani Campus


String Methods

• int compareToIgnoreCase( String anotherString)


• Compares two string lexicographically, ignoring case considerations.

• String toLowerCase()
• Converts all characters to lower case

• String toUpperCase()
• Converts all characters to upper case

• String trim()
• Returns the copy of the String, by removing whitespaces at both ends. It does
not affect whitespaces in the middle.

• String replace (char oldChar, char newChar)


• Returns new string by replacing all occurrences of oldChar with newChar

BITS Pilani, Pilani Campus


String Methods

• public boolean endsWith(String suf)


• Return true if the String has the specified suffix.

• public boolean startsWith(String pre)


• Returns true if the String has the specified prefix

s1 = "Hello World";
s2 = "World";
System.out.println(s1.endsWith(s2));

BITS Pilani, Pilani Campus


String Methods

• public boolean regionMatches(int start_OString,


String another, int start_AString, int no_of_char)

• public boolean regionMatches(boolean ignore_case,


int start_OString, String another, int start_AString,
int no_of_char)

s1 = "HellO World";
s2 = "hello";
System.out.println(s1.regionMatches(1, s2, 1,
4));

BITS Pilani, Pilani Campus


String Methods

• String substring (int i) – returns the substring from the


ith index
s1 = new String("Hello World");
Output:
s2=s1.substring(4); o World
System.out.println(s2);

• String substring (int i, int j): Returns the substring from


i to j-1 index.
s1 = new String("Hello World");
s2=s1.substring(4,7); Output:
System.out.println(s2); oW

BITS Pilani, Pilani Campus


String Methods

• String concat( String str) – Concatenates the string


‘str’ to the object invoking the method.
s1 = "Hello ";
Output:
s2 = "World"; s1: :Hello s2 :Hello World
s2=s1.concat(s2);
System.out.println("s1: :"+s1+"s2 :"+s2);

• int indexOf (String s) – returns index of the first


occurrence of the specified string;
• Returns -1 if not found
s1 = "World, Hello World, Hello"; Output:
7
s2 = "Hello";
p=s1.indexOf(s2);
BITS Pilani, Pilani Campus
String Methods

• int indexOf (String s, int i) – returns index of the first


occurrence of the specified string, starting at the
specified index
s1 = "World, Hello World, Hello";
s2 = "Hello"; Output:
p=s1.indexOf(s2,8); 20

• int lastIndexOf( int ch): Returns the index within the


string of the last occurrence of the specified string.
s1 = "World, Hello World, Hello";
s2 = "Hello";
Output:
p=s1.lastIndexOf(s2); 20

BITS Pilani, Pilani Campus


String Methods

• public int codePointAt(int index)


• returns the Unicode point of an index
s1 = "Hallo World"; Output:
97
p=s1.codePointAt(1);

• public int codePointBefore(int index)

• public boolean contains(String str)


• Returns true if the invoking string object contains ‘str’

s1 = "Hello World";
s2 = “World";
System.out.println(s1.contains(s2));
BITS Pilani, Pilani Campus
Object Oriented Programming
CS F213
J. Jennifer Ranjani
email: jennifer.ranjani@pilani.bits-pilani.ac.in
Chamber: 6121 B, NAB
BITS Pilani Consultation: Appointment by e-mail
Pilani Campus
Importing a class

package class1; package class2.sub;


import class1.HelloWorld;
public class HelloWorld
{ public class Test {
public void show() { public static void main(String[]
System.out.println("Within class args) {
1's show"); HelloWorld h = new HelloWorld();
} h.show();
} }
}

Take Home Exercise: Learn how to execute the same


code from the command prompt.

BITS Pilani, Pilani Campus


Solution 1: Class files created
in respective packages

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956


Solution 2:Setting
CLASSPATH

BITS Pilani, Deemed to be University under Section 3 of UGC Act, 1956


BITS Pilani
Pilani Campus

String Buffer
StringBuffer Constructors

String Buffer represents growable and writable character


sequences. The size grow automatically to accommodate
characters and substring insert or append operations.

Constructor Description
public StringBuffer() create an empty StringBuffer
create a StringBuffer with initial room
public StringBuffer(int capacity)
for capacity number of characters
create a StringBuffer containing the
public StringBuffer(String str)
characters from str

BITS Pilani, Pilani Campus


String Buffer - Methods
Methods Description
StringBuffer append( char c ) append c to the end of the StringBuffer
convert i to characters, then append them
StringBuffer append( int i )
to the end of the StringBuffer
convert L to characters, then append them
StringBuffer append( long L )
to the end of the StringBuffer
convert f to characters, then append them
StringBuffer append( float f )
to the end of the StringBuffer
convert d to characters, then append them
StringBuffer append( double d )
to the end of the StringBuffer
append the characters in s to the end of the
StringBuffer append( String s )
StringBuffer
return the current capacity (capacity will
int capacity()
grow as needed).
char charAt( int index ) get the character at index.
StringBuffer delete( int start, int end) delete characters from start to end-1
StringBuffer deleteCharAt( int index) delete the character at index
BITS Pilani, Pilani Campus
String Buffer - Methods
Methods Description
insert character c at index (old characters move over to
StringBuffer insert( int index, char c)
make room).
StringBuffer insert( int index, String st) insert characters from st starting at position i.
convert i to characters, then insert them starting at
StringBuffer insert( int index, int i)
index.
convert L to characters, then insert them starting at
StringBuffer insert( int index, long L)
index.
convert f to characters, then insert them starting at
StringBuffer insert( int index, float f)
index.
convert d to characters, then insert them starting at
StringBuffer insert( int index, double d)
index.

int length() return the number of characters presently in the buffer.

StringBuffer reverse() Reverse the order of the characters.


void setCharAt( int index, char c) set the character at index to c.
return a String object containing the characters in the
String toString()
StringBuffer. BITS Pilani, Pilani Campus
BITS Pilani
Pilani Campus

String Tokenizer
String Tokenizer

• java.util.StringTokenizer class allows you to break a


string into tokens
Constructor Description
StringTokenizer(String str) creates StringTokenizer with
specified string.
StringTokenizer(String str, String creates StringTokenizer with
delim) specified string and delimeter.
StringTokenizer(String str, String creates StringTokenizer with
delim, boolean returnValue) specified string, delimeter and
returnValue. If return value is true,
delimiter characters are considered
to be tokens. If it is false, delimiter
characters serve to separate tokens.

BITS Pilani, Pilani Campus


Methods

Public method Description


boolean hasMoreTokens() checks if there is more tokens available.

String nextToken() returns the next token from the


StringTokenizer object.

String nextToken(String delim) returns the next token, after switching to


the new delimiter.

boolean hasMoreElements() same as hasMoreTokens() method.

Object nextElement() same as nextToken() but its return type


is Object.

int countTokens() returns the total number of tokens.

BITS Pilani, Pilani Campus


String Tokenizer - Example
import java.util.StringTokenizer;
public class test{
public static void main(String args[]){
StringTokenizer st = new StringTokenizer("my name is \t khan \n");
int i=0,j;
j = st.countTokens();
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
Output:
i++; my
} name
System.out.println("i: "+i+"and j: "+j); is
System.out.println( st.countTokens()); khan
} i: 4 and j: 4
0

}
BITS Pilani, Pilani Campus
String Tokenizer - Example
import java.util.StringTokenizer;
public class Test{
public static void main(String args[]){
StringTokenizer st = new StringTokenizer("my name/ is \t khan \n");
int i=0,j;
j = st.countTokens();
while (st.hasMoreTokens()) {
System.out.println(st.nextToken("/"));
Output:
i++; my name
} is khan
System.out.println("i: "+i+"and j: "+j);
System.out.println( st.countTokens()); i: 2and j: 4
} 0
}

BITS Pilani, Pilani Campus


Review Questions

• StringTokenizer stuff = new StringTokenizer("abc,def,ghi");


System.out.println(stuff.nextToken() );

Output:
abc,def,ghi

• StringTokenizer stuff = new StringTokenizer("abc,def,ghi", ",");


System.out.println(stuff.nextToken());

Output:
abc

BITS Pilani, Pilani Campus


Review Questions

• StringTokenizer stuff = new StringTokenizer( "abc+def+ghi", "+", true );


System.out.println( stuff.nextToken() );
System.out.println( stuff.nextToken() );
Output:
abc
+

• StringTokenizer stuff = new StringTokenizer( "abc def+ghi", "+");


System.out.println( stuff.nextToken() );
System.out.println( stuff.nextToken() );
Output:
abc def
ghi

BITS Pilani, Pilani Campus


Review Questions

• StringTokenizer st = new StringTokenizer( "abc+def:ghi", "+:", true );


while(st.hasMoreTokens()){
System.out.println(st.nextToken()); }

Output:
abc
+
def
:
ghi

BITS Pilani, Pilani Campus


BITS Pilani
Pilani Campus

Wrapper Classes
Wrapper Class

• Converts a primitive into object (Autoboxing) and object


into a primitive (unboxing)

Primitive Type Wrapper class

boolean Boolean
char Character
byte Byte
short Short
int Integer
long Long
float Float
double Double

BITS Pilani, Pilani Campus


BITS Pilani
Pilani Campus

Autoboxing and
Unboxing (Java 5)
Wrapper Class & Boxing -
Example
int a = 50;
Integer i = Integer.valueOf(60); Output:
Integer j = a; // auto boxing -1
System.out.println(j.compareTo(i));

Integer i = new Integer(50); Output:


int a = i; // unboxing 26
int b = Integer.numberOfLeadingZeros(i);
System.out.println("Unboxing"+a+"Int Value"+b);

Note: Binary value of 50 is 0b110010; int is 32 bits long

BITS Pilani, Pilani Campus


Review Questions
static void print(int i,int j){System.out.println("int");}
static void print(Integer i,Integer j) {System.out.println("Integer");}
static void print(Integer... i){System.out.println("Var Integer");}
public static void main(String args[]){
short s=30,t=50;
Integer a=30,b=50,c=70;
// Place any of the following statements }

Which version of the print method will be invoked?


a. print(s)
b. print(s,t)
c. print(a,b)
d. print(a,b,c)
BITS Pilani, Pilani Campus
Review Questions
static void print(int i,int j){System.out.println("int");}
static void print(Integer i,Integer j) {System.out.println("Integer");}
static void print(Integer... i){System.out.println("Var Integer");}
public static void main(String args[]){
short s=30,t=50;
Integer a=30,b=50,c=70;
// Place any of the following statements }

Which version of the print method will be invoked?


a. print(s) // Error
b. print(s,t) // int
c. print(a,b) //Integer
d. print(a,b,c) //Var Integer
BITS Pilani, Pilani Campus
Rules

• Widening and boxing cant be performed at the same


time

• Boxing and Widening is allowed

• Widening > Boxing > Varargs

• Widening between wrapper classes is not allowed

• During Overloading, Widening + varargs and Boxing


+ varargs can only be used in a mutually exclusive
manner.
BITS Pilani, Pilani Campus
Object Oriented Programming
CS F213
J. Jennifer Ranjani
email: jennifer.ranjani@pilani.bits-pilani.ac.in
Chamber: 6121 B, NAB
BITS Pilani Consultation: Appointment by e-mail
Pilani Campus
BITS Pilani
Pilani Campus

Queries asked during the


previous class
Difference between String Tokenizer
& split method in String class
String str = "http://www.java.com/strings";

StringTokenizer st = new StringTokenizer(str, "://");


for (int i = 0; st.hasMoreTokens(); i++) System.out.println("#" + i + ": " +
st.nextToken());

String[] split1 = str.split("://");


for (int i = 0; i < split1.length; i++) System.out.println("#" + i + ": " +
split1[i]);

String[] split2 = str.split(":|//|/");


for (int i = 0; i < split2.length; i++) System.out.println("#" + i + ": " +
split2[i]);

BITS Pilani, Pilani Campus


Output

#0: http
#1: www.java.com
#2: strings
#0: http
#1: www.java.com/strings
#0: http
#1:
#2: www.java.com
#3: strings

BITS Pilani, Pilani Campus


Difference between String Tokenizer
& split method in String class
• Split considers the delimiter as a regular expression.

• Two consecutive delimiter or delimiters in the beginning


cause the split method to return blank strings

• String Tokenizer is fast compared to split

• String Tokenizer can not group the delimiters

BITS Pilani, Pilani Campus


Capacity of the String Buffer

• If the number of character increases from its current


capacity, it increases the capacity by (oldcapacity*2)+2

StringBuffer sb = new StringBuffer("Java");


System.out.println(sb.capacity());

sb.append(" Programming"); Output:


System.out.println(sb.capacity()); 20
20
42
sb.append("is ea");
System.out.println(sb.capacity());

BITS Pilani, Pilani Campus


ensureCapacity of the
StringBuffer

StringBuffer sb = new StringBuffer("Java is my favourite language");


System.out.println(sb.capacity());

sb.ensureCapacity(10);
System.out.println(sb.capacity());
Output:
45
sb.ensureCapacity(50);
45
System.out.println(sb.capacity()); 92

BITS Pilani, Pilani Campus


BITS Pilani
Pilani Campus

Generics (J2SE 5)
Generic Class

• Allows type to be a parameter to methods

• <> is used to specify the parameter types

• To create objects use the following syntax


BaseType <Type> obj = new BaseType <Type>()

Note: In Parameter type we can not use primitives like


'int','char' or 'double'.

BITS Pilani, Pilani Campus


Generic Class - Example
class Identity<T>{
T obj;
Identity(T obj) { this.obj = obj; }
public T getObject() { return this.obj; }
}

class Test {
public static void main (String[] args) {

Identity <Long> number = new Identity<Long>(9999955555L);


System.out.println(number.getObject());

Identity <String> name = new Identity<String>("Ankit");


System.out.println(name.getObject());
}
} BITS Pilani, Pilani Campus
Multiple Type Parameters
class Identity<T,U> {
T obj1; U obj2;
Identity(T obj1,U obj2 ) { this.obj1 = obj1;this.obj2 = obj2; }
public void printObject() {
System.out.print(this.obj1+"\t");System.out.println(this.obj2); }
}

class Test {
public static void main (String[] args) {
Identity <String, Integer> I1 = new Identity<String,
Integer>("Ankit",20171007);
Identity <Integer,String> I2 = new
Identity<Integer,String>(20171007,"Ankit");
I1.printObject();
I2.printObject();
}}
BITS Pilani, Pilani Campus
Generic Functions
class Identity {
public <T> void printObject(T obj) {System.out.println(obj); }
}

class Test {
public static void main (String[] args) {
Identity I1, I2;
I1 = new Identity();
I2 = new Identity();
I1.printObject(20071007);
I2.printObject("Ankit");
}
}

BITS Pilani, Pilani Campus


Generic Functions with
generic return type
class Identity {
public <T> T printObject(T obj) {return obj; }
}

class Test {
public static void main (String[] args) {
Identity I1, I2;
I1 = new Identity();
I2 = new Identity();
System.out.println(I1.printObject(20071007));
System.out.println(I2.printObject("Ankit"));
}
}

BITS Pilani, Pilani Campus


Bound Type with Generics

• Used to restrict the types that can be used as arguments


in a parameterized type.
• Eg: Method operating on numbers should accept the instances of the Number
class or its subclasses.

• Declare a bounded type parameter


• List the type parameter’s name.
• Along by the extends keyword
• And by its upper bound.

BITS Pilani, Pilani Campus


Bound Type - Example
class Identity<T extends Number> {
T obj;
Identity(T obj) { this.obj = obj; }
public T getObject() { return this.obj; }}
class Test {
public static void main (String[] args) {
Identity <Integer> iObj = new Identity<Integer>(20071007);
System.out.println(iObj.getObject());
Identity <Double> dObj = new Identity<Double>(2007.00);
System.out.println(dObj.getObject());
Identity <String> sObj = new Identity<String>("Ankit");
System.out.println(sObj.getObject());
}}
Note: Bound Mismatch: type argument String is not
within bounds of type-variable T
BITS Pilani, Pilani Campus
BITS Pilani
Pilani Campus

Collections
What are Collections

• Group of Objects treated as a single Object.

• Java provides supports for manipulating collections in


the form of
– Collection Interfaces
– Collection Classes

• Collection interfaces provide basic functionalities


whereas collection classes provides their concrete
implementation

BITS Pilani, Pilani Campus


Collection Classes

• Collection classes are standard classes that implement


collection interfaces
• Some Collection Classes are abstract and some classes
are concrete and can be used as it is.
• Important Collection Classes:
 AbstractCollection
 AbstractList
 AbstractSequentialList
 LinkedList
 ArrayList
 AbstractSet
 HasSet
 LinkedHashSet
 TreeSet
BITS Pilani, Pilani Campus
Partial View of Collection’s
Framework

BITS Pilani, Pilani Campus


ArrayList - Example
import java.util.*;
class Test{
public static void main(String args[]){
ArrayList<Integer> al1 = new ArrayList<Integer>();
al1.add(20);
al1.add(9);

ArrayList<Integer> al2 = new ArrayList<Integer>();


al2.add(22);
al2.add(53);
Output:
al1.addAll(al2); [9, 20, 22, 53]
Collections.sort(al1); 53
System.out.println(al1);
System.out.println(al1.get(3));}
} BITS Pilani, Pilani Campus
List Iterator

• List Iterator is used to traverse forward and backward


directions
Method Description
boolean hasNext() This method return true if the list iterator
has more elements when traversing the
list in the forward direction.
Object next() This method return the next element in
the list and advances the cursor position.

boolean hasPrevious() This method return true if this list iterator


has more elements when traversing the
list in the reverse direction.
Object previous() This method return the previous element
in the list and moves the cursor position
backwards.

BITS Pilani, Pilani Campus


List Iterator - Example
ArrayList<Integer> al = new ArrayList<Integer>(); Output:
al.add(20); Forward Traversal
20
al.add(9);
9
al.add(22); 22
al.add(53); 53
Backward Traversal
ListIterator<Integer> itr=al.listIterator(); 53
22
System.out.println("Forward Traversal");
9
while(itr.hasNext()) { 20
System.out.println(itr.next());
}
System.out.println("Backward Traversal"); Question: What happens if
while(itr.hasPrevious()) { the backward traversal
happens before the
System.out.println(itr.previous());
forward?
}
BITS Pilani, Pilani Campus
Object Oriented Programming
CS F213
J. Jennifer Ranjani
email: jennifer.ranjani@pilani.bits-pilani.ac.in
Chamber: 6121 B, NAB
BITS Pilani Consultation: Appointment by e-mail
Pilani Campus
BITS Pilani
Pilani Campus

Query asked during the


previous class
Type name in Generics

The type name can be named according to programmer’s


convenience. But the common convention is

T - Type
E - Element
K - Key
N - Number
V – Value

Note: Let there be an interface T;


class Identity<T extends T> cannot be done.

BITS Pilani, Pilani Campus


BITS Pilani
Pilani Campus

Coming back to Generics


Review Question
ArrayList al = new ArrayList(); Find the output
al.add("Sachin"); a. Compilation Error
al.add("Rahul"); b. Runtime Error
al.add(10); c. [Sachin, Rahul, 10]
[Sachin, Rahul, 10]
String s[] = new String[3];
for(int i=0;i<3;i++)
Note:
s[i] = (String)al.get(i);
No compilation error because
add(Object o) method in the
System.out.println(al);
ArrayList class
System.out.println(Arrays.toString(s));
Runtime Error because integer
object is type case to String
Solution:
Generics

BITS Pilani, Pilani Campus


Array List /Generics - Review

ArrayList<String> al = new ArrayList<String>();


al.add("Sachin");
al.add("Rahul"); Note:
al.add("10");
Compilation Error if
String s[] = new String[3];
we try to include
for(int i=0;i<3;i++) al.add(10)
s[i] =al.get(i);

System.out.println(al);
System.out.println(Arrays.toString(s));

BITS Pilani, Pilani Campus


Advantages

• Type-safety : We can hold only a single type of objects


in generics. It doesn’t allow to store other objects.

• Type casting is not required: There is no need to


typecast the object.

• Compile-Time Checking: It is checked at compile time


so problem will not occur at runtime.

BITS Pilani, Pilani Campus


Wildcard in Generics
abstract class Shape{
final double pi = 3.14;
double area;
abstract void draw();
}
class Rectangle extends Shape{
Rectangle(int l,int b){
area = l*b; }
void draw(){System.out.println("Area of Rect:"+area);}
}
class Circle extends Shape{
Circle(int r){
area = pi*r*r; }
void draw(){System.out.println("Area of circle:"+area);}
}
BITS Pilani, Pilani Campus
Wildcard in Generics
class test{
//creating a method that accepts only child class of Shape
public static void drawShapes(List<? extends Shape> lists){
for(Shape s:lists){
s.draw();}
}
public static void main(String args[]){
List<Rectangle> list1=new ArrayList<Rectangle>(); Output:
Area of Rect:15.0
list1.add(new Rectangle(3,5));
Area of circle:12.56
Area of circle:78.5
List<Circle> list2=new ArrayList<Circle>();
list2.add(new Circle(2));
list2.add(new Circle(5));
drawShapes(list1);
drawShapes(list2);
}} BITS Pilani, Pilani Campus
BITS Pilani
Pilani Campus

Comparable Interface
Comparable Interface

• It is used to order the objects of user-defined class.

• It is found in java.lang package and contains only one


method named compareTo(Object)

• Elements can be sorted based on single data member eg:


account number, name or age.

• We can sort the elements of:


• String objects
• Wrapper class objects
• User-defined class objects

BITS Pilani, Pilani Campus


Comparable-Example
import java.util.*;
class Account implements Comparable<Account>{
int acc;
String name;
float amt;
Account(int acc,String name,float amt){
this.acc = acc;
this.name = name;
this.amt = amt; }
public int compareTo(Account ac){
if(amt==ac.amt)
return 0;
else if(amt>ac.amt)
return 1;
else
return -1; }
public String toString() {
return "Acc. No.: "+acc+" Name: "+name+" Amount: "+amt;}
} BITS Pilani, Pilani Campus
Comparable-Example
class Test{
public static void main(String[] args) {
List<Account> al = new ArrayList<Account>();

al.add(new Account(111,"Ankit",5000));
al.add(new Account(112,"Ashok",4000));
al.add(new Account(123,“Ryan",5000));

Collections.sort(al);

for(Account a:al)
System.out.println(a);
}
}

BITS Pilani, Pilani Campus


BITS Pilani
Pilani Campus

Comparator Interface
Comparator Interface

• Used to order user defined class

• This interface is found in java.util package and contains


2 methods
• compare(Object obj1,Object obj2)
• equals(Object element)

• It provides multiple sorting sequence


• Elements can be sorted based on any data member

BITS Pilani, Pilani Campus


Comparator - Example
import java.util.*;

class Account{
int acc;
String name;
float amt;
Account(int acc,String name,float amt){
this.acc = acc;
this.name = name;
this.amt = amt; }
public String toString() {
return "Acc. No.: "+acc+" Name: "+name+" Amount: "+amt;}
}

BITS Pilani, Pilani Campus


Comparator - Example
class AmtCmp implements Comparator<Account>{
public int compare(Account a1,Account a2){
if(a1.amt==a2.amt)
return 0;
else if(a1.amt>a2.amt)
return 1;
else
return -1; }
}

BITS Pilani, Pilani Campus


Comparator - Example
class AccCmp implements Comparator<Account>{
public int compare(Account a1,Account a2){
if(a1.acc==a2.acc)
return 0;
else if(a1.acc>a2.acc)
return 1;
else
return -1; }
}

BITS Pilani, Pilani Campus


Comparator - Example
class test {
public static void main(String[] args) {
List<Account> al = new ArrayList<Account>();

al.add(new Account(123,"Ankit",5000));
al.add(new Account(112,"Ashok",4000));
al.add(new Account(111,"Ryan",5000));

System.out.println("Comparison on Amount");
Collections.sort(al,new AmtCmp());
for(Account a:al)
System.out.println(a);

System.out.println("Comparison on Acc. No.");


Collections.sort(al,new AccCmp());
for(Account a:al)
System.out.println(a); }
} BITS Pilani, Pilani Campus
Overriding Equals method
class Account implements Comparator<Account>{
int acc;
String name;
float amt;
Account(int acc,String name,float amt){
this.acc = acc;
this.name = name;
this.amt = amt; }
public boolean equals(Account a1) {
if (a1 == null)
return false;
if(this.acc != a1.acc)
return false;
if(this.amt != a1.amt)
return false;
if(!(a1.name.equals(this.name)))
return false;
return true;} BITS Pilani, Pilani Campus
Overriding Equals method
public String toString() {
return "Acc. No.: "+acc+" Name: "+name+" Amount: "+amt;}
public int compare(Account arg0, Account arg1) {
// TODO Auto-generated method stub
return 0;}
}

class test {
public static void main(String[] args) {
List<Account> al = new ArrayList<Account>();
al.add(new Account(111,"Ryan",5000));
al.add(new Account(112,“Ryan",5000));
al.add(new Account(111,"Ryan",5000));
System.out.println(al.get(0).equals(al.get(2)));
System.out.println(al.get(0).equals(al.get(1))); }
} BITS Pilani, Pilani Campus
Multiple Bounds in Generics
public class test {
public static void main(String[] args) {
System.out.printf("Max of %d, %d and %d is %d\n\n",
3, 4, 5, maximum( 3, 4, 5 ));
System.out.printf("Max of %.1f,%.1f and %.1f is %.1f\n\n",
6.6, 8.8, 7.7, maximum( 6.6, 8.8, 7.7 ));
System.out.printf("Max of %s,%s and %s is %s\n\n",
"s", "j", "r", maximum( "s", "j", "r" ));
}
public static <T extends Comparable<T>> T maximum(T x, T y, T z) {
T max = x;
if(y.compareTo(max) > 0) { Output:
max = y; } Max of 3, 4 and 5 is 5
Max of 6.6,8.8 and 7.7 is 8.8
if(z.compareTo(max) > 0) {
Max of s,j and r is s
max = z; }
return max; }
} BITS Pilani, Pilani Campus
Multiple Bounds in Generics
public class test {
public static void main(String[] args) {
System.out.printf("Max of %d, %d and %d is %d\n\n",
3, 4, 5, maximum( 3, 4, 5 ));
System.out.printf("Max of %.1f,%.1f and %.1f is %.1f\n\n",
6.6, 8.8, 7.7, maximum( 6.6, 8.8, 7.7 ));
System.out.printf("Max of %s,%s and %s is %s\n\n",
"s", "j", "r", maximum( "s", "j", "r" ));
}
public static <T extends Number & Comparable<T>> T maximum(T x, T
y, T z) {
T max = x; Error:
if(y.compareTo(max) > 0) { The method maximum(T, T, T)
max = y; } in the type test is not
applicable for the arguments
if(z.compareTo(max) > 0) {
(String, String, String)
max = z; }
return max; } } BITS Pilani, Pilani Campus
Text File I/O
Text Files and Binary Files
 Files that are designed to be read by human beings,
and that can be read or written with an editor are
called text files
 Text files can also be called ASCII files because the data
they contain uses an ASCII encoding scheme
 An advantage of text files is that the are usually the same
on all computers, so that they can move from one computer
to another
Text Files and Binary Files
 Files that are designed to be read by programs and
that consist of a sequence of binary digits are called
binary files
 Binary files are designed to be read on the same type of
computer and with the same programming language as the
computer that created the file
 An advantage of binary files is that they are more efficient
to process than text files
 Unlike most binary files, Java binary files have the
advantage of being platform independent also

 For this course, we will deal only with text files


Streams
 A stream is an object that enables the flow of
data between a program and some I/O
device or file
 If the data flows into a program, then the stream is
called an input stream
 If the data flows out of a program, then the stream
is called an output stream
Streams
 Input streams can flow from the keyboard or from a
file
 System.in is an input stream that connects to the
keyboard
Scanner keyboard = new Scanner(System.in);
 Output streams can flow to a screen or to a file
 System.out is an output stream that connects to the
screen
System.out.println("Output stream");
System.in, System.out, and System.err

 The standard streams System.in, System.out, and


System.err are automatically available to every
Java program
 System.out is used for normal screen output

 System.err is used to output error messages to the


screen
 The System class provides three methods (setIn,
setOut, and setErr) for redirecting these standard
streams:
public static void setIn(InputStream inStream)
public static void setOut(PrintStream outStream)
public static void setErr(PrintStream outStream)
File Names
 The rules for how file names should be
formed depend on a given operating system,
not Java
 When a file name is given to a java constructor for
a stream, it is just a string, not a Java identifier
(e.g., "fileName.txt")
 Any suffix used, such as .txt has no special
meaning to a Java program
Path Names
 When a file name is used as an argument to
a constructor for opening a file, it is assumed
that the file is in the same directory or folder
as the one in which the program is run
 If it is not in the same directory, the full or
relative path name must be given
Path Names
 A path name not only gives the name of the
file, but also the directory or folder in which
the file exists
 A full path name gives a complete path
name, starting from the root directory
 A relative path name gives the path to the
file, starting with the directory in which the
program is located
Path Names
 The way path names are specified
depends on the operating system
 A typical Windows path name that could be
used as a file name argument is
“C:\\user\\data\\data.txt”
 A Java program will accept a path name written
in either Windows or Unix format regardless of
the operating system on which it is run
A File Has Two Names
Every input file and every output file used by a
program has two names:
1. The real file name used by the operating system
2. The name of the stream that is connected to the file

The actual file name is used to connect to the stream


The stream name serves as a temporary name for the
file, and is the name that is primarily used within
the program
Writing to a Text File
 The class PrintWriter is a stream class
that can be used to write to a text file
 An object of the class PrintWriter has the
methods print and println
 These are similar to the System.out methods of
the same names, but are used for text file output,
not screen output
Writing to a Text File
 All the file I/O classes that follow are in the package
java.io, so a program that uses PrintWriter will
start with a set of import statements:
import java.io.PrintWriter;
import java.io.FileOutputStream;
import java.io.FileNotFoundException;
 The class PrintWriter has no constructor that
takes a file name as its argument
 It uses another class, FileOutputStream, to
convert a file name to an object that can be used as
the argument to its (the PrintWriter) constructor
Writing to a Text File
 A stream of the class PrintWriter is created and
connected to a text file for writing as follows:
PrintWriter outputStreamName;
outputStreamName =
new PrintWriter(new FileOutputStream(FileName));

 The class FileOutputStream takes a string representing the file


name as its argument

 The class PrintWriter takes the anonymous


FileOutputStream object as its argument
Writing to a Text File
 This produces an object of the class PrintWriter
that is connected to the file FileName
 The process of connecting a stream to a file is called
opening the file
 If the file already exists, then doing this causes the old
contents to be lost
 If the file does not exist, then a new, empty file named
FileName is created
 After doing this, the methods print, printf,
and println can be used to write to the file
Writing to a Text File
 When a text file is opened in this way, a
FileNotFoundException can be thrown
 In this context it actually means that the file could not be
created
 This type of exception can also be thrown when a program
attempts to open a file for reading and there is no such file
 It is therefore necessary to enclose this code in exception
handling blocks
 The file should be opened inside a try block

 A catch block should catch and handle the possible


exception
 The variable that refers to the PrintWriter object should
be declared outside the block (and initialized to null) so that
it is not local to the block
Sample Code
public class TextFileOutputDemo
{
public static void main(String[] args)
{
PrintWriter outStream = null;
try {
outStream =
new PrintWriter(new FileOutputStream("stuff.txt"));
}
catch(FileNotFoundException e)
{
System.err.println("Error opening the file stuff.txt.");
System.exit(0);
}
outStream.println("The quick brown fox");
outStream.println("jumped over the lazy dog.");

outStream.close( );
}
}
Writing to a Text File
 When a program is finished writing to a file, it should
always close the stream connected to that file
outputStreamName.close();
 This allows the system to release any resources used to
connect the stream to the file
 If the program does not close the file before the program
ends, Java will close it automatically, but it is safest to
close it explicitly
IOException
 When performing file I/O there are many situations in which an
exception, such as FileNotFoundException, may be thrown
 Many of these exception classes are subclasses of the class
IOException
 The class IOException is the root class for a variety of
exception classes having to do with input and/or output
 These exception classes are all checked exceptions
 Therefore, they must be caught or declared in a throws clause
Catching IOException
public class TextFileOutputDemo
{
public static void main(String[] args)
{
PrintWriter outStream = null;

// OPEN the file here as in previous code


try {
outStream =
new PrintWriter(new FileOutputStream("stuff.txt"));
outStream.println("The quick brown fox");
outStream.println("jumped over the lazy dog.");
}
catch (IOException e) {
System.err.println (e.getMessage());
}

finally { // always close the file


outputStream.close( );
}
}
}
Appending to a Text File
 To create a PrintWriter object and connect it to a text
file for appending, a second argument, set to true, must
be used in the constructor for the FileOutputStream
object
outputStreamName =
new PrintWriter(new FileOutputStream(FileName,true));

 After this statement, the methods print, println and/or


printf can be used to write to the file
 The new text will be written after the old text in the file
Reading From a Text File Using Scanner

 The class Scanner can be used for reading from a text


file as well as the keyboard
 Simply replace the argument System.in (to the
Scanner constructor) with a suitable stream that is
connected to the text file
Scanner StreamObject =
new Scanner(new FileInputStream(FileName));
 Methods of the Scanner class for reading input
(nextInt, nextLine) behave the same whether reading
from a text file or the keyboard
Input from a Text File Using Scanner (Part 1 of 4)
Input from a Text File Using Scanner (Part 2 of 4)
Input from a Text File Using Scanner (Part 3 of 4)
Input from a Text File Using Scanner (Part 4 of 4)
Testing for the End of a Text File with Scanner

 A program that tries to read beyond the end of a


file using methods of the Scanner class will
cause an exception to be thrown
 However, instead of having to rely on an
exception to signal the end of a file, the
Scanner class provides methods such as
hasNextInt and hasNextLine
 These methods can also be used to check that the
next token to be input is a suitable element of the
appropriate type
Checking for the End of a Text File with
hasNextLine (Part 1 of 4)
Checking for the End of a Text File with
hasNextLine (Part 2 of 4)
Checking for the End of a Text File with
hasNextLine (Part 3 of 4)
Checking for the End of a Text File with
hasNextLine (Part 4 of 4)
Checking for the End of a Text File with
hasNextInt (Part 1 of 2)
Checking for the End of a Text File with
hasNextInt (Part 2 of 2)
hasNext

 The scanner also provide a more general


method named hasNext that returns false if
there are no more tokens of any kind in the
file.
 hasNext can be used when the file contains
different kinds of data
Object Oriented Programming
CS F213
J. Jennifer Ranjani
email: jennifer.ranjani@pilani.bits-pilani.ac.in
Chamber: 6121 P, NAB
BITS Pilani Consultation: Appointment by e-mail
Pilani Campus
BITS Pilani
Pilani Campus

Query asked during the


previous class
Wildcard in Generics
class test{
public static void main(String[] args) {
List<Integer> list1= Arrays.asList(1,2,3);
List<Number> list2=Arrays.asList(1.1,2.2,3.3);
List<Double> list3=Arrays.asList(1.1,2.2,3.3); Output:
List<String> list4=Arrays.asList("s","j","r"); list1, list3, list4 –
compilation error
printlist(list1); Type not applicable for the
arguements
printlist(list2);
printlist(list3);
printlist(list4);
}
private static void printlist(List<Number> list) {
System.out.println(list);
}
} BITS Pilani, Pilani Campus
Wildcard in Generics
class test{
public static void main(String[] args) {
List<Integer> list1= Arrays.asList(1,2,3);
List<Number> list2=Arrays.asList(1.1,2.2,3.3);
List<Double> list3=Arrays.asList(1.1,2.2,3.3); Output:
List<String> list4=Arrays.asList("s","j","r"); [1, 2, 3]
[1.1, 2.2, 3.3]
printlist(list1); [1.1, 2.2, 3.3]
[s, j, r]
printlist(list2);
printlist(list3);
printlist(list4);
}
private static void printlist(List<?> list) {
System.out.println(list);
}
} BITS Pilani, Pilani Campus
Upper Bounded Wildcard
class test{
public static void main(String[] args) {
List<Integer> list1= Arrays.asList(1,2,3);
List<Number> list2=Arrays.asList(1.1,2.2,3.3);
List<Double> list3=Arrays.asList(1.1,2.2,3.3); Output:
List<String> list4=Arrays.asList("s","j","r"); list4 – compilation error
Type not applicable for the
printlist(list1); arguements
printlist(list2);
printlist(list3);
printlist(list4);
}
private static void printlist(List<? extends Number> list) {
System.out.println(list);
}
} BITS Pilani, Pilani Campus
Lower Bounded Wildcard
class test{
public static void main(String[] args) {
List<Integer> list1= Arrays.asList(1,2,3);
List<Number> list2=Arrays.asList(1.1,2.2,3.3);
List<Double> list3=Arrays.asList(1.1,2.2,3.3); Output:
printlist(list1); list3 – compilation error
printlist(list2); Type not applicable for the
printlist(list3); arguements
}
private static void printlist(List<? super Integer> list) {
System.out.println(list);
}
}

BITS Pilani, Pilani Campus


Multiple Bounds in Generics
class Bound<T extends A & B> {
private T objRef;
public Bound(T obj){
this.objRef = obj; }

public void doRunTest(){


this.objRef.displayClass(); }
}

interface B {
public void displayClass(); }

class A implements B{
public void displayClass() {
System.out.println("Inside class A"); }
} BITS Pilani, Pilani Campus
Multiple Bounds in Generics
class C implements B {
public void displayClass() {
Note:
System.out.println("Inside class C "); } The type passed to the
} class should be of sub
type class A and should
public class test { have implemented
interface B
public static void main(String a[]) {
//Creating object of sub class A and
//passing it to Bound as a type parameter.
Bound<A> bea = new Bound<A>(new A());
bea.doRunTest();
}
}

BITS Pilani, Pilani Campus


BITS Pilani
Pilani Campus

Coming back to
Collections
ArrayList

• Growable Array implementation of List interface.


• Insertion order is preserved.
• Duplicate elements are allowed.
• Multiple null elements of insertion are allowed.
• Default initial capacity of an ArrayList is 10.
• The capacity grows with the below formula, once ArrayList
reaches its max capacity.
• newCapacity= (oldCapacity * 3)/2 + 1
• When to use?
• If elements are to be retrieved frequently. Because ArrayList implements
RandomAccess Interface

• When not to use?


• If elements are added/removed at specific positions frequently

BITS Pilani, Pilani Campus


ArrayList vs Vector

ArrayList Vector
There are no synchronized methods. All methods are synchronized.
No Thread safe: Multiple threads can Thread safe: Only one thread is
access the array list at the same allowed to operate on vector object
time. at a time.
It increases the waiting time of
Threads are not required to wait and threads (since all the methods are
hence performance is high synchronized) and hence
performance is low

BITS Pilani, Pilani Campus


LinkedList

• Linked list is implementation class of List interface.

• Underlying data structure is Double linked list.

• Insertion order is preserved.

• Duplicate elements are allowed.

• Multiple null elements of insertion are allowed.

BITS Pilani, Pilani Campus


LinkedList - Methods
Constructor/Method Description
List list = new LinkedList(); It creates an empty linked list.
public boolean add(E e); It adds the specified element at the end of
the list.
public void addFirst(E e); It adds the specified element in the beginni
ng of the list.
public void addLast(E e); It adds the specified element to the end of
the list
public E removeFirst(); It removes and returns the first element fr
om the list.
public E removeLast(); It removes and returns the last element fro
m the list.
public E getFirst(); It returns the first element from the list.
public E getLast(); It returns the last element from the list.
BITS Pilani, Pilani Campus
Stack

• Stack is child class of Vector


• Stack class in java represents LIFO (Last in First Out) stack of
objects.

Method Description
public E push(E item); Pushes the item on top of the stack
public synchronized E pop(); Removes the item at the top of the stack
and returns that item
public synchronized E peek(); Returns the item at the top of the stack
public boolean empty(); Checks whether stack is empty or not
public synchronized int search Returns the position of an object in the
(Object o); stack.

BITS Pilani, Pilani Campus


BITS Pilani
Pilani Campus

Set Interface
Set Interface

• The set interface is an unordered collection of objects in


which duplicate values cannot be stored.

• The Java Set does not provide control over the position
of insertion or deletion of elements.

• Basically, Set is implemented


by HashSet, LinkedHashSet or TreeSet (sorted
representation).

BITS Pilani, Pilani Campus


TreeSet

• TreeSet implements the SortedSet interface so duplicate values are


not allowed.
• Objects in a TreeSet are stored in a sorted and ascending order.
• TreeSet does not preserve the insertion order of elements but
elements are sorted by keys.
• TreeSet does not allow to insert Heterogeneous objects. It will
throw classCastException at Runtime if trying to add hetrogeneous
objects.
• TreeSet serves as an excellent choice for storing large amounts of
sorted information because of its faster access and retrieval time.
• TreeSet is basically implementation of a self-balancing binary
search tree. Operations like add, remove and search take O(Log n)
time. And operations like printing n elements in sorted order takes
O(n) time.
BITS Pilani, Pilani Campus
TreeSet - Example
TreeSet<Integer> set = new TreeSet<Integer>();
set.add(12);
set.add(63);
set.add(34);
Output:
set.add(45);
Set data: 12 34 45 63

Iterator<Integer> iterator = set.iterator();


System.out.print("Set data: ");
while (iterator.hasNext()) {
System.out.print(iterator.next() + " ");
}

BITS Pilani, Pilani Campus


HashSet

• Implements Set Interface.


• Underlying data structure for HashSet is hashtable.
• As it implements the Set Interface, duplicate values are not
allowed.
• Objects that you insert in HashSet are not guaranteed to be
inserted in same order. Objects are inserted based on their
hash code.
• NULL elements are allowed in HashSet.
• Execution time of add(), contains(), remove(), size() is
constant even for large sets.

BITS Pilani, Pilani Campus


HashSet - Example
HashSet<Integer> set = new HashSet<Integer>();
set.add(12);
set.add(63);
set.add(34);
Output:
set.add(45);
Set data: 34 12 45 63

Iterator<Integer> iterator = set.iterator();


System.out.print("Set data: ");
while (iterator.hasNext()) {
System.out.print(iterator.next() + " ");
}

BITS Pilani, Pilani Campus


LinkedHashSet

• LinkedHash set extends HashSet and has no member of


its own.

• It maintains a linked list of entries in the set in the order


of insertion.

• As it implements the Set Interface, duplicate values are


not allowed.

• NULL elements are allowed.

BITS Pilani, Pilani Campus


LinkedHashSet - Example
LinkedHashSet<Integer> set = new LinkedHashSet<Integer>();
set.add(12);
set.add(63);
set.add(34);
Output:
set.add(45);
Set data: 12 63 34 45

Iterator<Integer> iterator = set.iterator();


System.out.print("Set data: ");
while (iterator.hasNext()) {
System.out.print(iterator.next() + " ");
}

BITS Pilani, Pilani Campus


Priority Queue

• PriorityQueue doesn’t permit NULL pointers.


• PriorityQueue doesn’t have restriction on duplicate elements
• PriorityQueue cannot be created for Objects that are non-
comparable
• PriorityQueue are unbound queues.
• The head of this queue is the least element with respect to the
specified ordering. If multiple elements are tied for least value,
the head is one of those elements — ties are broken
arbitrarily.
• The queue retrieval operations poll, remove, peek,
and element access the element at the head of the queue.
• It inherits methods from AbstractQueue, AbstractCollection,
Collection and Object class.
BITS Pilani, Pilani Campus
Priority Queue - Methods
• The peek() method retrieves the value of the first element of the queue
without removing it from the queue. For each invocation of the method we
always get the same value and its execution
does not affect the size of the queue. If the queue is empty the peek()
method returns null.
• The element() method behaves like peek(), so it again retrieves the value of
the first element without removing it. Unlike peek ), however, if the list is
empty element() throws a NoSuchElementException.
• The poll() method retrieves the value of the first element of the queue by
removing it from the queue. . At each invocation it removes the first
element of the list and if the list is already empty it returns null but does
not throw any exception.
• The remove() method behaves as the poll() method, so it removes the first
element of the list and if the list is empty it throws a
NoSuchElementException.

BITS Pilani, Pilani Campus


Priority Queue - Example
class Account{
int acc;
String name;
float cibil;
Account(int acc,String name,float cibil){
this.acc = acc;
this.name = name;
this.cibil = cibil; }
}
class AccCmp implements Comparator<Account>{
public int compare(Account a1,Account a2){
if(a1.cibil==a2.cibil)
return 0;
else if(a1.cibil<a2.cibil)
return 1;
else
return -1; }
} BITS Pilani, Pilani Campus
Priority Queue - Example
class test {
public static void main(String[] args) {
PriorityQueue<Account> al = new Output:
PriorityQueue<Account>(5, new AccCmp()); Acc. No. processed on
their priority order
al.add(new Account(123,"Ankit",8.1f)); 123
111
al.add(new Account(112,"Ashok",4.5f)); 112
al.add(new Account(111,"Ryan",6.5f));

System.out.println("Acc. No. processed on their priority order");


while (!al.isEmpty()) {
System.out.println(al.poll().acc); }
}
}

BITS Pilani, Pilani Campus


BITS Pilani
Pilani Campus

Map Interface
Map Interface

• A map contains values on the basis of key i.e. key and


value pair.

• Each key and value pair is known as an entry.

• Map contains only unique keys.

• Map is useful if you have to search, update or delete


elements on the basis of key.

BITS Pilani, Pilani Campus


Map Hierarchy

HashMap – no specific order

LinkedHashMap – maintains
insertion order

TreeMap – maintains ascending


order

BITS Pilani, Pilani Campus


Map Interface
Method Description
Object put(Object key, Object value) It is used to insert an entry in this map.

void putAll(Map map) It is used to insert the specified map in


this map.
Object remove(Object key) It is used to delete an entry for the
specified key.
Object get(Object key) It is used to return the value for the
specified key.
boolean containsKey(Object key) It is used to search the specified key from
this map.
Set keySet() It is used to return the Set view containing
all the keys.
Set entrySet() It is used to return the Set view containing
all the keys and values.

BITS Pilani, Pilani Campus


Map.Entry Interface

• Entry is the sub interface of Map.

• It provides methods to get key and value.

Method Description
Object getKey() It is used to obtain key.
Object getValue() It is used to obtain value.

BITS Pilani, Pilani Campus


HashMap

• A HashMap contains values


based on the key.

• It contains only unique elements.

• It may have one null key and


multiple null values.

• It maintains no order.

BITS Pilani, Pilani Campus


Hash Map
class test {
public static void main(String[] args) {
HashMap<Integer,String> hm=new HashMap<Integer,String>();
hm.put(100,"Amit");
hm.put(101,"Vijay");
hm.put(102,"Rahul");
hm.put(102,"RaKul");
hm.put(null,null);
hm.put(103,null);
Output:
for(Map.Entry<Integer,String> m:hm.entrySet()){ null null
System.out.println(m.getKey()+" "+m.getValue()); 100 Amit
} 101 Vijay
} 102 RaKul
103 null
}

BITS Pilani, Pilani Campus


Self Study

• LinkedHash Map

• Tree Map

• Hashtable

BITS Pilani, Pilani Campus


Object Oriented Programming
CS F213
J. Jennifer Ranjani
email: jennifer.ranjani@pilani.bits-pilani.ac.in
Chamber: 6121 P, NAB
BITS Pilani Consultation: Appointment by e-mail
Pilani Campus
BITS Pilani
Pilani Campus

Query asked during the


previous class
Priority Queue - Example
class test {
public static void main(String[] args) {
PriorityQueue<Account> al = new Output:
PriorityQueue<Account>(5, new AccCmp()); Acc. No. processed on
their priority order
al.add(new Account(123,“Ryan",8.1f)); 123 Ryan
123 Ankit
al.add(new Account(123,"Ankit",8.1f)); 123 Ankit
al.add(new Account(122,"Ryan",8.1f)); 122 Ryan
al.add(new Account(123,"Ankit",8.1f));

System.out.println("Acc. No. processed on their priority order");


while (!al.isEmpty()) {
System.out.println(al.peek().acc +" " +al.poll().name); }
}
}
BITS Pilani, Pilani Campus
BITS Pilani
Pilani Campus

AWT
Abstract Window Toolkit

• Java AWT (Abstract Window Toolkit) is an API to develop


GUI or window-based applications in java.

• Java AWT components are platform-dependent


• Java AWT calls native platform (Operating systems) subroutine for creating
components such as textbox, checkbox, button etc.

• AWT is heavyweight i.e. its components uses the


resources of OS.

• The java.awt package provides classes for AWT APIs


such as TextField, Label, TextArea, RadioButton,
CheckBox, Choice, List etc.
BITS Pilani, Pilani Campus
AWT Hierarchy

BITS Pilani, Pilani Campus


Key Terminologies

• Container – component in AWT that can contain another


components like buttons, textfields, labels etc. The
classes such as Frame, Dialog and Panel extends the
Container class.
• Window - The window is the container that have no
borders and menu bars. You must use frame, dialog or
another window for creating a window.
• Panel - The Panel is the container that doesn't contain
title bar and menu bars. It can have other components
like button, textfield etc.
• Frame - The Frame is the container that contain title bar
and can have menu bars. It can have other components
like button, textfield etc.
BITS Pilani, Pilani Campus
AWT by Inheritance
import java.awt.*;
class MyGui extends Frame {
MyGui(){
setSize(1000,1000);
setLayout(null);
setVisible(true);
setTitle("Core Banking");
Button b=new Button("Submit");
setBackground(Color.cyan);
b.setBounds(50,100,80,30);
add(b);}
}
class test {
public static void main(String[] args) {
MyGui mi = new MyGui();
}} BITS Pilani, Pilani Campus
AWT by Association
class test {
public static void main(String[] args) {

Frame f=new Frame("Core Banking");


Button b=new Button("Submit");
b.setBounds(50,100,80,30);
f.add(b);
f.setSize(1000,1000);
f.setBackground(Color.cyan);
f.setLayout(null);
f.setVisible(true);
}
}

BITS Pilani, Pilani Campus


Event Delegation Model

• Event: It is an object that describes a state change in a


source.
• Pressing a button, entering a character via keyboard, clicking the mouse etc.
• Indirect interactions with the user interface may cause events to occur. Eg. timer
expires, s/w or h/w failure etc.

• Event Source: It is an object that generates an event.


• A source may generate more than one type of event.
• A source must register listeners in order for the listeners to receive notification
about the specific type of the event
• public void addTypeListener(TypeListener el)
• Eg. addKeyListener(), addMouseMotionListener()
• When an event occurs, the registered listeners are notified and receive a copy of
the event object. (Multicasting)
• Some source allow only one listener to register
• To unregister: public void removeTypeListener(TypeListener el)

BITS Pilani, Pilani Campus


Event Delegation Model

• Event Listener: It is an object that is notified when an


event occurs.
• It must be registered with one or more sources to receive notifications
• It must implement methods to receive and process these notifications. (Event
handlers)
• These methods are defined in a set of interfaces in java.awt.event
• The event handler must return the control to the run-time system quickly it
should not maintain the control for an extended period of time

Event Classes:
• The root of the event class hierarchy is the EventObject
class which contains two methods
• getSource() - returns the source of the event
• toString() – returns the string equivalent of the event

• AWTEvent – is the superclass of all the AWT events


handled by the event delegation model
BITS Pilani, Pilani Campus
Event Class

BITS Pilani, Pilani Campus


Sources of Events

BITS Pilani, Pilani Campus


Event Listener Interfaces

INTERFACE INTERFACE METHODS ADD METHOD EVENT CLASS


ActionListener actionPerformed (ActionEvent) addActionListener() ActionEvent

adjustmentValueChanged(Adjustment
AdjustmentListener addAdjustmentListener() AdjustmentEvent
Event)

ComponentListener componentHidden(ComponentEvent) addComponentListener() ComponentEvent


componentMoved(ComponentEvent)
componentResized(ComponentEvent)
componentShown(ComponentEvent)

ContainerListener componentAdded(ComponentEvent) addContainerListener() ContainerEvent


componentRemoved(ComponentEvent
)

BITS Pilani, Pilani Campus


Event Listener Interfaces

INTERFACE INTERFACE METHODS ADD METHOD EVENT CLASS


ItemListener itemStateChanged(ItemEvent) addItemListener() ItemEvent

KeyListener keyPressed(KeyEvent) addKeyListener() KeyEvent


keyReleased(KeyEvent)
keyTyped(KeyEvent)

MouseListener mouseClicked(MouseEvent) addMouseListener() MouseEvent


mouseEntered(MouseEvent)
mouseExited(MouseEvent)
mousePressed(MouseEvent)
mouseReleased(MouseEvent)

MouseMotionListener mouseDragged(MouseEvent) addMouseMotionListener() MouseEvent


mouseMoved(MouseEvent)

BITS Pilani, Pilani Campus


Event Listener Interfaces

INTERFACE INTERFACE METHODS ADD METHOD EVENT CLASS


TextListener textValueChanged(TextEvent) addText:Listener() TextEvent

WindowListener windowActivated(WindowEvent) addWindowListener() WindowEvent


windowClosed(WindowEvent)
windowClosing(WindowEvent)
windowDeactivated(WindowEvent)
windowDeiconified(WindowEvent)
windowIconified(WindowEvent)
windowOpened(WindowEvent)

BITS Pilani, Pilani Campus


Object Oriented Programming
CS F213
J. Jennifer Ranjani
email: jennifer.ranjani@pilani.bits-pilani.ac.in
Chamber: 6121 P, NAB
BITS Pilani Consultation: Appointment by e-mail
Pilani Campus
Event Handling

BITS Pilani, Pilani Campus


AWT Event Handling -
Example
import java.awt.*;
import java.awt.event.*;

class test extends Frame implements ActionListener{


TextField tf;
test(){
setTitle("Core Banking");
tf = new TextField();
tf.setBounds(100,50,170,30);
Button b=new Button("Submit");
b.setBounds(100,100,100,30);
add(b);
add(tf);

b.addActionListener(this);
BITS Pilani, Pilani Campus
AWT Event Handling -
Example
setSize(1000,1000);
setBackground(Color.cyan);
setLayout(null);
setVisible(true);
}
public static void main(String[] args)
{
test t= new test();
}

public void actionPerformed(ActionEvent E)


{
tf.setText("Welcome to Core Banking");
}
}
BITS Pilani, Pilani Campus
Event Handling by an External
Class-Example
import java.awt.*;
import java.awt.event.*;
class test extends Frame{
TextField tf;
Label l;
test() {
setTitle("Core Banking");
tf = new TextField();
tf.setBounds(100,100,170,30);

Button b=new Button("Submit");


b.setBounds(100,150,100,30);

l = new Label();
l.setBounds(100,50,170,30);
l.setBackground(Color.green);
BITS Pilani, Pilani Campus
Event Handling by an External
Class-Example
add(b);
add(tf);
add(l);

AHandler a = new AHandler(this);


b.addActionListener(a);
tf.addTextListener(a);

setSize(1000,1000);
setBackground(Color.cyan);
setLayout(null);
setVisible(true); }
public static void main(String[] args) {
test t= new test(); }
}
BITS Pilani, Pilani Campus
Event Handling by an External
Class-Example
class AHandler implements ActionListener,TextListener{
test obj;
AHandler(test t){
this.obj = t;
}
public void textValueChanged(TextEvent e) {
obj.l.setText("Entered text: " + obj.tf.getText());
}

public void actionPerformed(ActionEvent E) {


obj.l.setText("Welcome to Core Banking");}
}

BITS Pilani, Pilani Campus


Screen Shot

BITS Pilani, Pilani Campus


Event Handling by
Anonymous Class- Example
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent E) {
l.setText("Welcome to Core Banking");}
});

tf.addTextListener(new TextListener() {
public void textValueChanged(TextEvent E) {
l.setText("Entered text: " + tf.getText());
}
});

BITS Pilani, Pilani Campus


Key AWT GUI Concepts

• Java supports three GUI frameworks


• AWT, Swing, JavaFX

• Four Key features of AWT programs


• Frame: Top level window is created by extending the Frame class

• paint(): Override the paint method to display output in the window. This method is
called by the run time system.

• repaint(): Invoke the repaint method if the program needs output to be displayed.
Awt program cannot call the paint method directly.

• System.exit(): When the top level window is closed, it does not cause the
program to terminate. It is necessary to handle the window-close event through a
System.exit() call.

BITS Pilani, Pilani Campus


Handling Mouse Events -
Example
import java.awt.*;
import java.awt.event.*;
public class test extends Frame implements MouseListener{
String msg ="Welcome";
Color c = Color.red;

test(){
addMouseListener(this);
setSize(300,300);
setLayout(null);
setVisible(true); }

public void mouseEntered(MouseEvent e) {


msg = "Mouse Entered";
repaint(); }
BITS Pilani, Pilani Campus
Handling Mouse Events -
Example
public void mouseExited(MouseEvent e) {
msg = "Mouse Exited";
repaint(); }

public void mouseClicked(MouseEvent e) {


Graphics g=getGraphics();
g.setColor(Color.BLUE);
g.fillOval(e.getX(),e.getY(),30,30); }

public void mousePressed(MouseEvent e) { }


public void mouseReleased(MouseEvent e) { }

public void paint(Graphics g) {


g.setColor(c);
Font font = new Font("TimesNewRoman", Font.PLAIN, 24);
g.setFont(font);
g.drawString(msg, 50, 150); }

public static void main(String[] args) {


new test(); }
} BITS Pilani, Pilani Campus
Screen Shot

BITS Pilani, Pilani Campus


Handling Key Events-Example
import java.awt.*;
import java.awt.event.*;
public class test extends Frame implements KeyListener{
String msg = "";

test(){
addKeyListener(this);
setSize(400,400);
setLayout(null);
setVisible(true);
setBackground(Color.cyan); }

public void keyPressed(KeyEvent e) {


int key = e.getKeyCode();
switch(key) {
case KeyEvent.VK_F1: msg += "<F1>";break;
case KeyEvent.VK_PAGE_UP: msg += "<PgUp>";break;
case KeyEvent.VK_LEFT: msg += "<Left Arrow>";break;}
repaint(); } BITS Pilani, Pilani Campus
Handling Key Events -
Example
public void keyReleased(KeyEvent e) {
repaint(); }

public void keyTyped(KeyEvent e) {


msg +=e.getKeyChar();
repaint(); }

public void paint(Graphics g) {


g.drawString(msg, 50, 50); }

public static void main(String[] args) {


new test(); }
}

BITS Pilani, Pilani Campus


Screen shot

BITS Pilani, Pilani Campus


Review Questions

• What is a listener in context to event handling?


a. A listener is a variable that is notified when an event occurs
b. A listener is a object that is notified when an event occurs
c. A listener is a method that is notified when an event occurs
d. None of the mentioned

• Which of these events will be notified if scroll bar is


manipulated?
a. ActionEvent
b. ComponentEvent
c. AdjustmentEvent
d. WindowEvent

BITS Pilani, Pilani Campus


Review Questions

• Which of these constant value will change when the


button at the end of scroll bar was clicked to increase its
value?
a. BLOCK_DECREMENT
b. BLOCK_INCREMENT
c. UNIT_DECREMENT
d. UNIT_INCREMENT

• Create 3 labels, 3 text fields (Number 1, Number 2 and


Result) and a Button (Enter) using AWT. Get the two
numbers as input from the user and display the result
when the ‘Enter’ Button is pressed. Handle the Key and
mouse events.
BITS Pilani, Pilani Campus
CS F213 - Object Oriented
Programming
J. Jennifer Ranjani
email: jennifer.ranjani@pilani.bits-pilani.ac.in
Chamber: 6121 P, NAB
Consultation: Appointment by e-mail
BITS Pilani https://github.com/JenniferRanjani/Object-Oriented-
Pilani Campus
Programming-with-Java
Recall

• Implementing the Listener Interface


• Same Class: b.addActionListener(this);
• External Class: b.addActionListener(Object of the Class implementing the
Interface);
• Anonymous Class: tf.addTextListener(new TextListener() {
public void textValueChanged(TextEvent E) { }
});

• Handling Mouse Events


• Handling Key Events

BITS Pilani, Pilani Campus


Adapter Classes

• They provide default implementation of listener


interfaces

• If inherited, implementation of all the methods of listener


interface is not required. Hence, it saves the code

• Adapter classes are found in java.awt.event package

BITS Pilani, Pilani Campus


java.awt.event commonly
used Adpater Classes

Adapter class Listener interface


WindowAdapter WindowListener
KeyAdapter KeyListener
MouseAdapter MouseListener
MouseMotionAdapter MouseMotionListener
FocusAdapter FocusListener
ComponentAdapter ComponentListener
ContainerAdapter ContainerListener

BITS Pilani, Pilani Campus


Window Adapter Class -
Example
import java.awt.*;
import java.awt.event.*;
public class test extends WindowAdapter {
test()
{
Frame f = new Frame("Adapter Example");
f.setSize(300,300);
f.setVisible(true);
f.addWindowListener(this);
}
public void windowClosing(WindowEvent e) {
System.exit(0);
}
public static void main(String[] args) {
new test();
}
}
BITS Pilani, Pilani Campus
Text Area & Mouse Adapter -
Example
public class test extends Frame
{
Label l;
TextArea area;

test()
{
setSize(400,400);
setVisible(true);
l=new Label();
l.setBounds(20,50,200,20);
l.setBackground(Color.cyan);

BITS Pilani, Pilani Campus


Text Area & Mouse Adapter -
Example
area=new TextArea();
area.setBounds(20,80,300, 150);
area.addMouseListener(new MouseAdapter()
{
public void mouseReleased(MouseEvent e)
{
l.setText(area.getSelectedText());
}
});

add(l);add(area);
}
public static void main(String[] args)
{
new test();
}
} BITS Pilani, Pilani Campus
Screen Shot

BITS Pilani, Pilani Campus


Review Question
Remove the label from the previous example and include a
Button. When the button is pressed, all the characters in
the Text Area are converted to uppercase and is displayed
in the Text Area. When a portion of the text is selected
using the mouse, only the selected text is converted into
upper case. Decide whether adapter classes should be
extended or listener interfaces should be implemented.

BITS Pilani, Pilani Campus


CS F213 - Object Oriented
Programming
J. Jennifer Ranjani
email: jennifer.ranjani@pilani.bits-pilani.ac.in
Chamber: 6121 P, NAB
Consultation: Appointment by e-mail
BITS Pilani https://github.com/JenniferRanjani/Object-Oriented-
Pilani Campus
Programming-with-Java
Screen Shot

BITS Pilani, Pilani Campus


Handling Buttons
public class test implements ActionListener {
Frame f;
TextField tf = new TextField();
Button b[] = new Button[3];
test(){
f = new Frame("ButtonExample");
Button y = new Button("Yes");
Button n = new Button("No");
Button m = new Button("May Be");

b[0]=(Button) f.add(y);
b[1]=(Button) f.add(n);
b[2]=(Button) f.add(m);

for(int i = 0;i<3;i++)
{
b[i].setBounds(100,100+i*50,100,30);
} BITS Pilani, Pilani Campus
Handling Buttons

for(int i =0;i<3;i++)
{
b[i].addActionListener(this);
}
tf.setBackground(Color.cyan);
tf.setBounds(100,250,200,30);
f.add(tf);
f.setSize(300,300);
f.setVisible(true);
}

BITS Pilani, Pilani Campus


Handling Buttons
public void actionPerformed(ActionEvent e)
{
for (int j=0;j<3;j++)
{
if(e.getSource() == b[j])
tf.setText("Button Pressed: "+b[j].getLabel());
}
}

public static void main(String[] args)


{
new test();
}
}

BITS Pilani, Pilani Campus


BITS Pilani
Pilani Campus

Layout Manager
Need for Layout Manager

• It is tedious to lay out large number of components


manually
• The layout manager is used every time the container is
resized or sized for the first time
• Each Container object has a layout manager associated
with it
• Pass null for setLayout() method if the default layout is to
be disabled and the components are to be positioned
manually.

BITS Pilani, Pilani Campus


Flow Layout

• Direction of the layout is defined by component


orientation: LEFT_TO_RIGHT or RIGHT_TO_LEFT

• FlowLayout can be aligned as


• FlowLayout.LEFT
• FlowLayout.RIGHT
• FlowLayout.CENTER
• FlowLayout.LEADING
• FlowLayout.TRAILING

BITS Pilani, Pilani Campus


FlowLayout.LEADING
(Difference based on Component Orientation)

Left to Right Right to Left

BITS Pilani, Pilani Campus


Border Layout

• Has four narrow fixed, fixed width components at the


edges and one large area in the center
• The regions are specified as
• BorderLayout.CENTER
• BorderLayout.EAST
• BorderLayout.WEST
• BorderLayout.NORTH
• BorderLayout.SOUTH

• void add(Component comref, Object region)

BITS Pilani, Pilani Campus


Border Layout - Example

What will happen if we try to add more components in the


same region?

BITS Pilani, Pilani Campus


Review Question

• Will adding two frames work?


• If not, what is the solution?

BITS Pilani, Pilani Campus


Grid Layout

• Lays the components in a two dimensional grid

No argument constructor Two argument constructor

BITS Pilani, Pilani Campus


Review Question

• Design the mine sweeper game using 25 buttons


arranged in a 5 x 5 grid layout.

BITS Pilani, Pilani Campus

You might also like