0% found this document useful (0 votes)
16 views376 pages

1 13 Merged

The document provides an introduction to Object-Oriented Programming (OOP) and its key features, including classes, objects, encapsulation, inheritance, and polymorphism. It emphasizes the advantages of OOP, such as modularization and software re-use, and compares it to conventional programming practices. Additionally, it introduces Java as a versatile programming language that supports OOP principles and is designed for internet applications.

Uploaded by

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

1 13 Merged

The document provides an introduction to Object-Oriented Programming (OOP) and its key features, including classes, objects, encapsulation, inheritance, and polymorphism. It emphasizes the advantages of OOP, such as modularization and software re-use, and compares it to conventional programming practices. Additionally, it introduces Java as a versatile programming language that supports OOP principles and is designed for internet applications.

Uploaded by

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

BITS Pilani

BITS Pilani Avinash Gautam


Department of Computer Science and Information Systems
Pilani Campus
BITS Pilani
Pilani Campus

Object Oriented Programming (CS F213)


Avinash Gautam
[email protected]
Chamber# 6120-L, NAB
Web-page: http://www.bits-pilani.ac.in/~avinash

Consultation Hour
By appointment through mail
Introduction to Object Oriented
Programming

 Object-Oriented Programming (OOP) is the term used to


describe a programming approach based on objects and classes.
 Allows us to organize software as a collection of objects that consist
of both data and behavior.
 Conventional functional programming practice only loosely connects
data and behavior.
 Object-oriented programming is the most important and powerful
way of creating software.
 The object-oriented programming approach encourages:
 Modularization: where the application can be decomposed into
modules.
 Software re-use: where an application can be composed from
existing and new modules.

BITS Pilani, Pilani Campus


Features of OOP

 An object-oriented programming language generally supports five


main features:
 Classes

 Objects

 Encapsulation

 Inheritance

 Polymorphism

BITS Pilani, Pilani Campus


An Object-Oriented Class

 If we think of a real-world object, such as a television it


will have several features and properties:
 We do not have to open the case to use it.

 We have some controls to use it (buttons on the box,

or a remote control).
 We can still understand the concept of a television,

even if it is connected to a DVD player.


 It is complete when we purchase it, with any external
requirements well documented.
 The TV will not crash!

In many ways this compares very well to the notion of a


class.

BITS Pilani, Pilani Campus


An Object-Oriented Class

 A class should:
 Provide a well-defined interface - such as the remote control of

the television.
 Represent a clear concept - such as the concept of a television.

 Be complete and well-documented - the television should have a

plug and should have a manual that documents all features.


 The code should be robust - it should not crash, like the

television.

 With a functional programming language (like C)


 The component parts of the television scattered everywhere.

 Users would be responsible for making them work correctly.

 No case surrounding the electronic components.

BITS Pilani, Pilani Campus


An Object-Oriented Class
 Humans use class based descriptions all the time.
 Classes allow us a way to represent complex structures within a
programming language. They have two components:
 States - (or data) are the values that the object has.

 Methods (or behavior) - are the ways in which the object can

interact with its data, the actions.

Unified Modelling
Language (UML)
representation of
the Television class for
object-oriented modelling
and programming.

BITS Pilani, Pilani Campus


An Object
 An object is an instance of a class.
 Class is a description/blueprint of a concept
 An object is a realization of this description/blueprint to create an
independent distinguishable entity.
 For example, in the case of the Television, the class is the set of plans
(or blueprints) for a generic television, whereas a television object is
the realization of these plans into a real-world physical television. So
there would be one set of plans (the class), but there could be
thousands of real-world televisions (objects).
 Objects have their own identity and are independent from each other.
 If the channel is changed on one television it will not change on

the other televisions.


 Objects can be concrete (a real-world object, a file on a computer) or
could be conceptual (such as a database structure) each with its own
individual identity.
8

BITS Pilani, Pilani Campus


An Object

BITS Pilani, Pilani Campus


Encapsulation

 Encapsulation is used to hide the mechanics of the object, allowing the actual
implementation of the object to be hidden. All we need to understand is the interface that
is provided for us.
 For example, Television class, where the functionality of the television is hidden from
us, but we are provided with a remote control, or set of controls for interacting with
the television, providing a high level of abstraction.

 There is no requirement to understand how the signal is decoded from the aerial and
converted into a picture to be displayed on the screen before you can use the television.
10

BITS Pilani, Pilani Campus


Encapsulation

 There is a sub-set of functionality that the user is allowed to call, termed the
interface.
 What are the interfaces of a Car?
 The full implementation of a class is the sum of the public interface plus the
private implementation.
 Encapsulation is the term used to describe the way that the interface is
separated from the implementation.
 Encapsulation as data-hiding
 Allow certain parts of an object to be visible
 Advantages for both the user and the programmer
 User
 Need only understand the interface.
 Need not understand how the implementation works or was
created.
 Programmer
 Can change the implementation, but need not notify the user. 11

BITS Pilani, Pilani Campus


Encapsulation

 We can identify a level of 'hiding' of particular methods or states


within a class using the public, private and protected keywords:
 public methods - describe the interface.

 private methods - describe the implementation.

12

BITS Pilani, Pilani Campus


Inheritance

 If we have several descriptions with some commonality between


these descriptions, we can group the descriptions and their
commonality using inheritance to provide a compact representation
of these descriptions.
 "What is a duck?“
 "a bird that swims“

 more accurately

 "a bird that swims, with

webbed feet.

13

BITS Pilani, Pilani Campus


Inheritance – Another Example

 If were to be given an unstructured group of descriptions such as


Car, Swift, i20, Van, Vehicle, Motorbike and Scooter, and asked to
organize these descriptions by their differences.
 You might say that a Swift is a Car but has a long boot, whereas an
i20 is a car with a small boot.

14

BITS Pilani, Pilani Campus


Inheritance

 One way to determine that you have organized your classes correctly is
to check them using the "IS-A" and "IS-A-PART-OF" relationship
checks.
 It is easy to confuse objects within a class and children of classes when
you first begin programming with an OOP methodology.

15

BITS Pilani, Pilani Campus


Inheritance

 So, using inheritance the programmer can:


 Inherit a behavior and add further specialized behavior

 Inherit a behavior and replace it

 Cut down on the amount of code that needs to be written and


debugged

16

BITS Pilani, Pilani Campus


Polymorphism

 When a class inherits from another class it inherits both the states and
methods of that class, so in the case of the Car class inheriting from the
Vehicle class the Car class inherits the methods of the Vehicle class
 engineStart(), gearChange(), lightsOn() etc.

 The Car class will also inherit the states of the Vehicle class
 isEngineOn, isLightsOn, numberWheels etc.

 Polymorphism means "multiple forms".


 In OOP these multiple forms refer to multiple forms of the same
method, where the exact same method name can be used in different
classes, or the same method name can be used in the same class with
slightly different parameters.
 There are two forms of polymorphism:
 Over-riding

 Over-loading

17

BITS Pilani, Pilani Campus


THANK YOU

18

BITS Pilani, Pilani Campus


Introduction to Java

BITS Pilani, Pilani Campus


Why Java?

The answer is that Java enables users to develop and deploy


applications on the Internet for servers, desktop computers, and
small hand-held devices. The future of computing is being
profoundly influenced by the Internet, and Java promises to
remain a big part of that future. Java is the Internet programming
language.

Java is a general purpose programming language.


Java is the Internet programming language.

BITS Pilani, Pilani Campus


Java, Web, and Beyond

• Java can be used to develop standalone


applications.
• Java can be used to develop applications
running from a browser.
• Java can also be used to develop applications
for hand-held devices.
• Java can be used to develop applications for
Web servers.
3

BITS Pilani, Pilani Campus


Java’s History

• James Gosling and Sun Microsystems


• Java, May 20, 1995, Sun World
• HotJava
– The first Java-enabled Web browser
• Early History Website:
https://www.ccbp.in/blog/java-tutorial/history-of-java

BITS Pilani, Pilani Campus


Characteristics of Java

• Java Is Simple
• Java Is Object-Oriented
• Java Is Distributed
• Java Is Interpreted
• Java Is Robust
• Java Is Secure
• Java Is Architecture-Neutral
• Java Is Portable
• Java's Performance
• Java Is Multithreaded
• Java Is Dynamic
5

BITS Pilani, Pilani Campus


Characteristics of Java

• Java Is Simple Java is partially modeled on C++, but greatly


simplified and improved. Some people refer to
• Java Is Object-Oriented Java as "C++--" because it is like C++ but
• Java Is Distributed with more functionality and fewer negative
aspects.
• Java Is Interpreted
• Java Is Robust
• Java Is Secure
• Java Is Architecture-Neutral
• Java Is Portable
• Java's Performance
• Java Is Multithreaded
• Java Is Dynamic
6

BITS Pilani, Pilani Campus


Characteristics of Java
• Java Is Simple Java is inherently object-oriented.
Although many object-oriented languages
• Java Is Object-Oriented began strictly as procedural languages,
• Java Is Distributed Java was designed from the start to be
• object-oriented. Object-oriented
Java Is Interpreted
programming (OOP) is a popular
• Java Is Robust programming approach that is replacing
• Java Is Secure traditional procedural programming
techniques.
• Java Is Architecture-Neutral
• Java Is Portable One of the central issues in software
development is how to reuse code. Object-
• Java's Performance oriented programming provides great
• Java Is Multithreaded flexibility, modularity, clarity, and
reusability through encapsulation,
• Java Is Dynamic inheritance, and polymorphism.
7

BITS Pilani, Pilani Campus


Characteristics of Java

• Java Is Simple Distributed computing involves several


computers working together on a network.
• Java Is Object-Oriented Java is designed to make distributed
• Java Is Distributed computing easy. Since networking
capability is inherently integrated into
• Java Is Interpreted Java, writing network programs is like
• Java Is Robust sending and receiving data to and from a
• Java Is Secure file.

• Java Is Architecture-Neutral
• Java Is Portable
• Java's Performance
• Java Is Multithreaded
• Java Is Dynamic
8

BITS Pilani, Pilani Campus


Characteristics of Java

• Java Is Simple You need an interpreter to run Java


programs. The programs are compiled into
• Java Is Object-Oriented the Java Virtual Machine code called
• Java Is Distributed bytecode. The bytecode is machine-
independent and can run on any machine
• Java Is Interpreted that has a Java interpreter, which is part of
• Java Is Robust the Java Virtual Machine (JVM).
• Java Is Secure
• Java Is Architecture-Neutral
• Java Is Portable
• Java's Performance
• Java Is Multithreaded
• Java Is Dynamic
9

BITS Pilani, Pilani Campus


Characteristics of Java

• Java Is Simple Java compilers can detect many problems


that would first show up at execution time
• Java Is Object-Oriented in other languages.
• Java Is Distributed
Java has eliminated certain types of error-
• Java Is Interpreted prone programming constructs found in
• Java Is Robust other languages.
• Java Is Secure
Java has a runtime exception-handling
• Java Is Architecture-Neutral feature to provide programming support
• Java Is Portable for robustness.

• Java's Performance
• Java Is Multithreaded
• Java Is Dynamic
10

BITS Pilani, Pilani Campus


Characteristics of Java

• Java Is Simple
• Java Is Object-Oriented
• Java Is Distributed
• Java Is Interpreted
• Java Is Robust
• Java implements several security
Java Is Secure
mechanisms to protect your system against
• Java Is Architecture-Neutral harm caused by stray programs.
• Java Is Portable
• Java's Performance
• Java Is Multithreaded
• Java Is Dynamic 11

BITS Pilani, Pilani Campus


Characteristics of Java

• Java Is Simple
• Java Is Object-Oriented
• Java Is Distributed
• Java Is Interpreted
• Java Is Robust
• Java Is Secure Write once, run anywhere
• Java Is Architecture-Neutral With a Java Virtual Machine (JVM),
• Java Is Portable you can write one program that will
run on any platform.
• Java's Performance
• Java Is Multithreaded
• Java Is Dynamic
12

BITS Pilani, Pilani Campus


Characteristics of Java

• Java Is Simple
• Java Is Object-Oriented
• Java Is Distributed
• Java Is Interpreted
• Java Is Robust
• Java Is Secure
• Java Is Architecture-Neutral
• Because Java is architecture neutral,
Java Is Portable
Java programs are portable. They can
• Java's Performance be run on any platform without being
• Java Is Multithreaded recompiled.

• Java Is Dynamic
13

BITS Pilani, Pilani Campus


Characteristics of Java

• Java Is Simple
• Java Is Object-Oriented
• Java Is Distributed
• Java Is Interpreted
• Java Is Robust
• Java Is Secure
• Java Is Architecture-Neutral
• Java Is Portable
• Java's Performance
• Java Is Multithreaded
• Java Is Dynamic
14

BITS Pilani, Pilani Campus


Characteristics of Java

• Java Is Simple
• Java Is Object-Oriented
• Java Is Distributed
• Java Is Interpreted
• Java Is Robust
• Java Is Secure
• Java Is Architecture-Neutral
• Java Is Portable Multithread programming is smoothly
• integrated in Java, whereas in other
Java's Performance
languages you have to call procedures
• Java Is Multithreaded specific to the operating system to enable
• Java Is Dynamic multithreading.
15

BITS Pilani, Pilani Campus


Characteristics of Java
• Java Is Simple
• Java Is Object-Oriented
• Java Is Distributed
• Java Is Interpreted
• Java Is Robust
• Java Is Secure
• Java Is Architecture-Neutral
• Java Is Portable Java was designed to adapt to an evolving
environment. New code can be loaded on the
• Java's Performance fly without recompilation. There is no need for
• Java Is Multithreaded developers to create, and for users to install,
major new software versions. New features can
• Java Is Dynamic be incorporated transparently as needed.
16

BITS Pilani, Pilani Campus


JDK Versions

• JDK 1.02 (1995)


• JDK 1.1 (1996)
• JDK 1.2 (1998)
• JDK 1.3 (2000)
• JDK 1.4 (2002)
• JDK 1.5 (2004) a. k. a. JDK 5 or Java 5
• JDK 1.6 (2006) a. k. a. JDK 6 or Java 6
• JDK 1.7 (2011) a. k. a. JDK 7 or Java 7
• JDK 1.8 (2014) a. k. a. JDK 8 or Java 8
17

BITS Pilani, Pilani Campus


JDK Editions

• Java Standard Edition (J2SE)


– J2SE can be used to develop client-side standalone
applications or applets.
• Java Enterprise Edition (J2EE)
– J2EE can be used to develop server-side applications
such as Java servlets, Java ServerPages, and Java
ServerFaces.
• Java Micro Edition (J2ME).
– J2ME can be used to develop applications for mobile
devices such as cell phones.
We will use J2SE to introduce Java programming. 18

BITS Pilani, Pilani Campus


Popular Java IDEs

• NetBeans
• Eclipse
• IntelliJ IDEA

19

BITS Pilani, Pilani Campus


A Simple Java Program

// This program prints Welcome to Java!


public class Welcome {
public static void main(String[] args) {
System.out.println("Welcome to Java!");
}
}

20

BITS Pilani, Pilani Campus


Creating and Editing Using NotePad

To use NotePad, type


notepad Welcome.java
from the DOS prompt.

21

BITS Pilani, Pilani Campus


Creating and Editing Using WordPad
To use WordPad, type
write Welcome.java
from the DOS prompt.

22
Creating, Compiling,
and Running Programs

23
Compiling Java Source Code

• Java was designed to run object programs on any platform.


• With Java, you write the program once, and compile the source
program into a special type of object code, known as bytecode.
• The bytecode can then run on any computer with a Java Virtual
Machine, as shown below. Java
• Virtual Machine is a software that interprets Java bytecode.

24

BITS Pilani, Pilani Campus


Trace a Program Execution

Enter main method

// This program prints Welcome to Java!


public class Welcome {
public static void main(String[] args) {
System.out.println("Welcome to Java!");
}
}

25

BITS Pilani, Pilani Campus


Trace a Program Execution

Execute statement

// This program prints Welcome to Java!


public class Welcome {
public static void main(String[] args) {
System.out.println("Welcome to Java!");
}
}

26

BITS Pilani, Pilani Campus


Trace a Program Execution

// This program prints Welcome to Java!


public class Welcome {
public static void main(String[] args) {
System.out.println("Welcome to Java!");
}
}

print a message to the


console

27

BITS Pilani, Pilani Campus


Anatomy of a Java Program

• Class name
• Main method
• Statements
• Statement terminator
• Reserved words
• Comments
• Blocks
28

BITS Pilani, Pilani Campus


Class Name

Every Java program must have at least one class.


Each class has a name. By convention, class names
start with an uppercase letter. In this example, the
class name is Welcome.
// This program prints Welcome to Java!
public class Welcome {
public static void main(String[] args) {
System.out.println("Welcome to Java!");
}
}
29

BITS Pilani, Pilani Campus


Main Method

Line 2 defines the main method. In order to run a


class, the class must contain a method named main.
The program is executed from the main method.

// This program prints Welcome to Java!


public class Welcome {
public static void main(String[] args) {
System.out.println("Welcome to Java!");
}
}
30

BITS Pilani, Pilani Campus


Statement
A statement represents an action or a sequence of
actions. The statement System.out.println("Welcome to
Java!") is a statement to display the greeting "Welcome
to Java!“.

// This program prints Welcome to Java!


public class Welcome {
public static void main(String[] args) {
System.out.println("Welcome to Java!");
}
}
31

BITS Pilani, Pilani Campus


Statement Terminator
Every statement in Java ends with a semicolon (;).

// This program prints Welcome to Java!


public class Welcome {
public static void main(String[] args) {
System.out.println("Welcome to Java!");
}
}
32

BITS Pilani, Pilani Campus


Reserved words
Reserved words or keywords are words that have a specific
meaning to the compiler and cannot be used for other
purposes in the program. For example, when the compiler
sees the word class, it understands that the word after class
is the name for the class.

// This program prints Welcome to Java!


public class Welcome {
public static void main(String[] args) {
System.out.println("Welcome to Java!");
}
}
33

BITS Pilani, Pilani Campus


Blocks

A pair of braces in a program forms a block that groups


components of a program.

public class Test {


Class block
public static void main(String[] args) {
System.out.println("Welcome to Java!"); Method block
}
}

34

BITS Pilani, Pilani Campus


Special Symbols

Character Name Description

{} Opening and closing Denotes a block to enclose statements.


braces
() Opening and closing Used with methods.
parentheses
[] Opening and closing Denotes an array.
brackets
// Double slashes Precedes a comment line.

" " Opening and closing Enclosing a string (i.e., sequence of characters).
quotation marks
; Semicolon Marks the end of a statement.

35

BITS Pilani, Pilani Campus


{ …}

// This program prints Welcome to Java!


public class Welcome {
public static void main(String[] args) {
System.out.println("Welcome to Java!");
}
}

36

BITS Pilani, Pilani Campus


( … )

// This program prints Welcome to Java!


public class Welcome {
public static void main(String[] args) {
System.out.println("Welcome to Java!");
}
}

37

BITS Pilani, Pilani Campus


;

// This program prints Welcome to Java!


public class Welcome {
public static void main(String[] args) {
System.out.println("Welcome to Java!");
}
}

38

BITS Pilani, Pilani Campus


// …

// This program prints Welcome to Java!


public class Welcome {
public static void main(String[] args) {
System.out.println("Welcome to Java!");
}
}

39

BITS Pilani, Pilani Campus


"…"

// This program prints Welcome to Java!


public class Welcome {
public static void main(String[] args) {
System.out.println("Welcome to Java!");
}
}

40

BITS Pilani, Pilani Campus


Programming Style and Documentation

• Appropriate Comments
• Naming Conventions
• Proper Indentation and Spacing Lines
• Block Styles

41

BITS Pilani, Pilani Campus


Appropriate Comments

Include a summary at the beginning of the


program to explain what the program does, its key
features, its supporting data structures, and any
unique techniques it uses.

Include your name, class section, instructor, date,


and a brief description at the beginning of the
program.

42

BITS Pilani, Pilani Campus


Naming Conventions

• Choose meaningful and descriptive names.


• Class names:
– Capitalize the first letter of each word in the
name. For example, the class name
ComputeExpression.

43

BITS Pilani, Pilani Campus


Proper Indentation and Spacing
• Indentation
– Indent two spaces.

• Spacing
– Use blank line to separate segments of the code.

44

BITS Pilani, Pilani Campus


Block Styles
Use end-of-line style for braces.

Next-line public class Test


style {
public static void main(String[] args)
{
System.out.println("Block Styles");
}
}

End-of-line
style
public class Test {
public static void main(String[] args) {
System.out.println("Block Styles");
}
}

45

BITS Pilani, Pilani Campus


Programming Errors

• Syntax Errors
– Detected by the compiler
• Runtime Errors
– Causes the program to abort
• Logic Errors
– Produces incorrect result

46

BITS Pilani, Pilani Campus


Syntax Errors

public class ShowSyntaxErrors {


public static main(String[] args) {
System.out.println("Welcome to Java);
}
}

47

BITS Pilani, Pilani Campus


Runtime Errors

public class ShowRuntimeErrors {


public static void main(String[] args) {
System.out.println(1 / 0);
}
}

48

BITS Pilani, Pilani Campus


Logic Errors

public class ShowLogicErrors {


public static void main(String[] args) {
System.out.println("Celsius 35 is Fahrenheit degree ");
System.out.println((9 / 5) * 35 + 32);
}
}

49

BITS Pilani, Pilani Campus


BITS Pilani
Pilani Campus

Object-Oriented Programming

Lecture -3 [Variables, Operators, Expressions, Statements and Blocks]


Lecture Outline

Language Basics
 Variables
 Primitive Data Types
 Operators
 Assignment, Arithmetic, and Unary Operators
 Equality, Relational, and Conditional Operators
 Bitwise and Bit Shift Operators
 Expressions, Statements, and Blocks
 Control Flow Statements
 if – then and if – then – else
 switch
 while and do – while
 for and branching statements

BITS Pilani, Pilani Campus


Variables in Java

• We know that object stores its variables in its fields (state


variables)
• What are the rules and conventions for naming a field?
• Besides int, what other data types are there?
• Do fields have to be initialized when they are declared?
• Are fields assigned a default value it they are not initialized?

In the Java programming language, the terms "field" and "variable" are both used; this is a
common source of confusion among new developers, since both often seem to refer to the
same thing.

BITS Pilani, Pilani Campus


Variables in Java

• The Java programming language defines the following kinds of variables

 Instance Variables (Non-Static Fields) - objects store their individual


states in "non-static fields", that is, 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. the currentSpeed of one bicycle is
independent from the currentSpeed of another.

 Class Variables (Static Fields) - A class variable is any field declared with
the static modifier; this tells the compiler that there is exactly one copy of this
variable in existence, regardless of how many times the class has been
instantiated. A field defining the number of gears for a particular kind of
bicycle could be marked as static since conceptually the same number of gears
will apply to all instances. The code static int numGears = 6; would create
such a static field. Additionally, the keyword final could be added to indicate
that the number of gears will never change.

BITS Pilani, Pilani Campus


Variables in Java

 Local Variables - a method will often store its temporary state in local
variables. There is no special keyword designating a variable as local;
that determination comes entirely from the location in which the
variable is declared — which is between the opening and closing braces
of a method. As such, local variables are only visible to the methods in
which they are declared; they are not accessible from the rest of the
class.

 Parameters - parameters are always classified as "variables" not


"fields".

BITS Pilani, Pilani Campus


Naming

• Variable names are case-sensitive. A variable's name can be any legal


identifier — an unlimited-length sequence of Unicode letters and digits (a-z,
A-Z, 0-9). Always begin your variable names with a letter. Subsequent
characters may be letters, digits, dollar signs, or underscore characters.

• Spell one word in all lowercase letters.


 Example: radius, area, weight etc

• For more than one word, capitalize the first letter of each subsequent word.
 Example: gearRatio, numberOfGears, monthlySalary etc

• Capitalize every letter and separate subsequent words with the underscore
character for variables that are made to store constant value, such that
those with modifiers static, final, and static final both.
 Example: static final NUM_GEARS = 6;

BITS Pilani, Pilani Campus


Primitive Data Types

BITS Pilani, Pilani Campus


Size of Primitive Types

• Because Java byte-code runs on the Java


Virtual Machine, the size (number of bytes) for
each primitive type is fixed.
• The size is not dependent on the actual
machine/device on which the code executes.
• There is no sizeof operator in Java as there
is in C – it’s not necessary.

8
BITS Pilani, Pilani Campus
Primitive Data Types (Contd.)

• 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;
• for example, String s = “this is a string”;
• String objects are immutable, which means that once
created, their values cannot be changed.
• The String class is not technically a primitive data type,
but considering the special support given to it by the
language, you'll probably tend to think of it as such.

BITS Pilani, Pilani Campus


Default values

• It's not always necessary to assign a value when a field is declared. Fields that are
declared but not initialized will be set to a reasonable default by the compiler.
Generally speaking, this default will be zero or null, depending on the data type.
Relying on such default values, however, is generally considered bad programming
style.

• Data Type Default Value (for fields)


 byte - 0
 short - 0 The compiler never assigns a default value to an
 int - 0 uninitialized local variable. If you cannot initialize
your local variable where it is declared, make sure
 long - 0L
to assign it a value before you attempt to use it.
 float - 0.0f Accessing an uninitialized local variable will result in
 double - 0.0d a compile-time error
 char - '\u0000'
 String (or any object) - null
 Boolean - false

BITS Pilani, Pilani Campus


Questions

• The term "instance variable" is another name for


 non-static field
• The term "class variable" is another name for
 static field
• A local variable stores temporary state; it is declared inside a
 method
• A variable declared within the opening and closing parenthesis of a
method is called a
 parameter
• Character strings are represented by the class
 java.lang.String

BITS Pilani, Pilani Campus


Operators

• Assignment, Arithmetic, and Unary


Operators
• Equality, Relational, and Conditional
Operators
• Bitwise and Bit Shift Operators

BITS Pilani, Pilani Campus


Operator Precedence

Operators Precedence
postfix expr++ expr–
unary ++expr --expr +expr -expr ~ !
multiplicative */%
additive +-
shift << >> >>>
relational < > <= >= instanceof
equality == !=
Operators with higher precedence are evaluated before
bitwise AND & operators with relatively lower precedence. Operators on the
bitwise exclusive OR ^ same line have equal precedence. When operators of equal
precedence appear in the same expression, a rule must govern
bitwise inclusive OR |
which is evaluated first. All binary operators except for the
logical AND && assignment operators are evaluated from left to right; assignment
logical OR || operators are evaluated right to left.

ternary ?:
assignment = += -= *= /= %= &= ^= |= <<= >>= >>>=

BITS Pilani, Pilani Campus


Arithmetic Operators & Expressions

• If an arithmetic operator is combined with int operands, then the


resulting type is int
• If an arithmetic operator is combined with one or two double
operands, then the resulting type is double
• If different types are combined in an expression, then the resulting
type is the right-most type on the following list that is found within the
expression
byteshortintlongfloatdouble
char
– Exception: If the type produced should be byte or short (according
to the rules above), then the type produced will actually be an int

14
BITS Pilani, Pilani Campus
Integer and Floating point division

• When one or both operands are a floating-point type, division results


in a floating-point type
15.0/2 evaluates to 7.5
• When both operands are integer types, division results in an integer
type
– Any fractional part is discarded
– The number is not rounded
15/2 evaluates to 7
• Be careful to make at least one of the operands a floating-point type if
the fractional portion is needed

15
BITS Pilani, Pilani Campus
Type Casting

• A type cast takes a value of one type and produces a value of another
type with an "equivalent" value
– If n and m are integers to be divided, and the fractional portion of the
result must be preserved, at least one of the two must be type cast to
a floating-point type before the division operation is performed
double ans = n / (double)m;
– Note that the desired type is placed inside parentheses immediately in
front of the variable to be cast
– Note also that the type and value of the variable to be cast does not
change

16
BITS Pilani, Pilani Campus
More on Type Casting

• When type casting from a floating-point to an integer type, the


number is truncated, not rounded
(int)2.9 evaluates to 2, not 3
• When the value of an integer type is assigned to a variable of a
floating-point type, Java performs an automatic type cast called a type
conversion
double d = 5;
• In contrast, it is illegal to place a double value into an int variable
without an explicit type cast
int i = 5.5; // Illegal
int i = (int)5.5 // Correct

17
BITS Pilani, Pilani Campus
Questions

• Consider the following code snippet.


int i = 10;
int n = i++%5;
 What are the values of i and n after the code is executed?
• Answer: i is 11, and n is 0
 What are the final values of i and n if instead of using the postfix increment
operator (i++), you use the prefix version (++i))?
• Answer: i is 11, and n is 1
• To invert the value of a boolean, which operator would you use?
 Answer: The logical complement operator "!"
• Which operator is used to compare two values, = or == ?
 Answer: The == operator is used for comparison, and = is used for assignment
• Explain the following code sample:
result = someCondition ? value1 : value2
 Answer: This code should be read as: "If someCondition is true, assign the value
of value1 to result. Otherwise, assign the value of value2 to result."

BITS Pilani, Pilani Campus


Control Flow Statements

• The if-then and if-then-else Statements


• The switch Statement
• The while and do-while Statements
• The for Statement
• Branching Statements

BITS Pilani, Pilani Campus


THANK YOU

BITS Pilani, Pilani Campus


BITS Pilani
Pilani Campus

Classes & Objects


Agenda

• Defining Classes and Access Modifiers


• Creating Objects
• Role of Constructors
• Accessing Instance Fields and Methods
• Local Variables vs. Instance Variables
• UML representation of a Class
• Method Overloading
• Constructor Overloading
• Objects as Parameters to Methods

BITS Pilani, Pilani Campus


A Class Is a Type
• A class is a special kind of programmer-defined type,
and variables can be declared of a class type (recall
structs from C)
• A value of a class type is called an object or an
instance of the class
– If A is a class, then the phrases
• “X is of type A“
• “X is an object of the class A“ mean the same thing
• “X is an instance of the class A"
• A class determines the types of data that an object
can contain, as well as the actions it can perform

BITS Pilani, Pilani Campus


The Contents of a Class Definition
• A class definition specifies the data items and
methods that all of its objects will have
• These data items and methods are sometimes called
members of the object
• Data items are called fields or instance variables
• Instance variable declarations and method
definitions can be placed in any order within the
class definition

BITS Pilani, Pilani Campus


Primitive Type Values vs. Class Type Values
• A primitive type value (int, double, char) is a single
piece of data

• A class type value or object can have multiple pieces


of data, as well as actions called methods
– All objects of a class have the same methods
– All objects of a class have the same pieces of data (i.e.,
name, type, and number)
– For a given object, each piece of data can hold a different
value

BITS Pilani, Pilani Campus


Anatomy of a Java Class

Visibility modifier
Keyword class Name of the class
(More on this later)

public class Date1

Class body: instance variables, methods

} NO semi-colon

BITS Pilani, Pilani Campus


Declaring Member Variables
• Types of variables
 Member variables in a class—these are called fields
 Variables in a method or block of code—these are called local variables
 Variables in method declarations—these are called parameters

• Field declarations are composed of three


components, in order:
 Zero or more modifiers, such as public or private
 The field's type
 The field's name
 Example:- Look at Bicycle class

• The public keyword identifies these fields as


public members, accessible by any object
that can access the class.

BITS Pilani, Pilani Campus


Anatomy of a method
Class methods are very much like functions. Methods
include a visibility modifier, return type, method
name, and optional parameters
Name of the method
Visibility modifier
(More on this later) return type
Optional parameters

public double toCelcius (double fTemp)


{

Method code: local variables and statements

}
BITS Pilani, Pilani Campus
Defining Methods
public float calculateSimpleInterest(
float pri, float rate, float time){

return((pri*rate*time)/100));
}

Method declarations have six components:


 Modifiers — such as public, private
 Return type — the data type of the value returned by the method, or void
if the method does not return a value
 Method name
 Parameter list in parenthesis — a comma-delimited list of input
parameters, preceded by their data types, enclosed by parentheses, (). If
there are no parameters, you must use empty parentheses
 An exception list — will be discussed later
 The method body, enclosed between braces — the method's code,
including the declaration of local variables, goes here

BITS Pilani, Pilani Campus


Access Modifiers
• Access modifiers lets you control what
other classes have access to the fields of
your class
 public modifier – the field is accessible from
all the classes
 private modifier – the field is accessible
only with in its own class
In the spirit of encapsulation, it is common to make fields private. We
still need access to the fields, however. This can be done indirectly by
adding public methods that obtain the field values for us

BITS Pilani, Pilani Campus


Example
public class Bicycle {

public int cadence = 0;


public int speed = 0;
public int gear = 1;

public void changeCadence(int newValue){


cadence = newValue;
}
public void changeGear(int newValue) {
gear = newValue;
}
public void speedUp(int increment) {
speed = speed + increment;
}
public void applyBrakes(int decrement) {
speed = speed - decrement;
}
} // End of Bicycle

BITS Pilani, Pilani Campus


Example
public class Bicycle {
private int cadence = 0;
private int speed = 0;
private int gear = 1;

Bicycle() {cadence = 0; ...}


public void changeCadence(int newValue) {
cadence = newValue;
}
public void changeGear(int newValue) {
gear = newValue;
}
public void speedUp(int increment) {
speed = speed + increment;
}
public void applyBrakes(int decrement) {
speed = speed - decrement;
}
} // End of Bicycle
BITS Pilani, Pilani Campus
Naming a method
• By convention, method names should be a verb in lowercase or a
multi-word name that begins with a verb in lowercase, followed by
adjectives, nouns, etc. In multi-word names, the first letter of
each of the second and following words should be capitalized
 run
 runFast
 getBackground A method has a unique name within its
 getFinalData class. However, a method might have
 compareTo
the same name as other methods due to
 setX
method overloading.
 isEmpty

BITS Pilani, Pilani Campus


Method Overloading
• The Java programming language supports overloading methods, and Java
can distinguish between methods with different method signatures. This
means that methods within a class can have the same name if they have
different parameter lists

• Overloaded methods are differentiated by the number and the type of the
arguments passed into the method

• You cannot declare more than one method with the same name and the
same number and type of arguments, because the compiler cannot tell
them apart.

• The compiler does not consider return type when differentiating methods,
so you cannot declare two methods with the same signature even if they
have a different return type.

BITS Pilani, Pilani Campus


Method Overloading – Example
public class Adder {

public int addInteger(int x, int y){


return(x+y);
}

public float addFloat(float x, float y){


return(x+y);
}

public String addString(String x, String y){


return(x+y);
}

public double addDouble(double x, double y){


return(x+y);
}
}

BITS Pilani, Pilani Campus


Method Overloading – Example
public class AdderDemo {

public static void main(String args[]){


int sum = 0, x = 5, y = 10;
Adder adder = new Adder();
sum = adder.addInteger(x,y);
}

BITS Pilani, Pilani Campus


Adder class – overloaded methods
public class Adder {

public int add(int x, int y){


return(x+y);
}

public float add(float x, float y){


return(x+y);
}

public String add(String x, String y){


return(x+y);
}

public double add(double x, double y){


return(x+y);
}
}

BITS Pilani, Pilani Campus


Method Overloading – Example
public class AdderDemo {

public static void main(String args[]){


int sum = 0, x = 5, y = 10;
Adder adder = new Adder();
sum = adder.add(x,y);
}
}

BITS Pilani, Pilani Campus


Adder class - Revisited Adder is a stateless class. There
is no point in creating a instance
of such a class. The methods can
be marked public static.
public class Adder {

public static int addInteger(int x, int y){


return(x+y);
}

public static float addFloat(float x, float y){


return(x+y);
}

public static String addString(String x, String y){


return(x+y);
}

public static double addDouble(double x, double y){


return(x+y);
}
}

BITS Pilani, Pilani Campus


Adder class –
overloaded methods It can be observed that
even static methods can
public class GenericAdder { be overloaded
public static int add(int x, int y){
return(x+y);
}

public static float add(float x, float y){


return(x+y);
}

public static String add(String x, String y){


return(x+y);
}

public static double add(double x, double y){


return(x+y);
}
}

BITS Pilani, Pilani Campus


Method Overloading – Example
public class AdderDemo {
public static void main(String args[]){
int sum = 0, x = 5, y = 10;

//Not the right way of making a call to static


method
//GenericAdder genAdder = new GenericAdder();
//sum = genAdder.add(x,y);

//a call to the static method


//should be made in static way
sum = GenericAdder.add(x,y);
}
}

BITS Pilani, Pilani Campus


Providing constructors
• A class contains constructors that are invoked to create objects from the
class blueprint. Constructor declarations look like method declarations—
except that they use the name of the class and have no return type.

public Bicycle(int startCadence, int startSpeed,


int startGear){
gear = startGear;
cadence = startCadence;
speed = startSpeed;
}
To create a new Bicycle object called myBike,
a constructor is called by the new operator:

Bicycle myBike = new Bicycle(30, 0, 8);

new Bicycle(30, 0, 8) creates space in memory


for the object and initializes its fields.
BITS Pilani, Pilani Campus
Providing constructors
• Although Bicycle only has one constructor, it could have others, including a
no-argument constructor:

public Bicycle() {
gear = 1;
cadence = 10;
speed = 0;
}

Bicycle yourBike = new Bicycle();

Invokes the no-argument constructor to create a new Bicycle object


called yourBike.

BITS Pilani, Pilani Campus


Providing constructors
• Both constructors could have been declared in Bicycle because they have
different argument lists. As with methods, the Java platform differentiates
constructors on the basis of the number of arguments in the list and their types.
You cannot write two constructors that have the same number and type of
arguments for the same class, because the platform would not be able to tell
them apart. Doing so causes a compile-time error.

• You don't have to provide any constructors for your class, but you must be
careful when doing this. The compiler automatically provides a no-argument,
default constructor for any class without constructors.

• You can use access modifiers in a constructor's declaration to control which other
classes can call the constructor.

BITS Pilani, Pilani Campus


Passing Information to a Method or a Constructor
public double computePayment(double loanAmt, double rate,
double futureValue, int numPeriods){

//your code goes here


}

Parameters refers to the list of variables in a method declaration.


Arguments are the actual values that are passed in when the
method is invoked. When you invoke a method, the arguments used
must match the declaration's parameters in type and order.

BITS Pilani, Pilani Campus


Parameter Types

• You can use any data type for a parameter of a method or a constructor.
This includes primitive data types, such as doubles, floats, and integers, as
you saw in the computePayment method, and reference data types, such as
objects and arrays.

• This method that accepts three Point objects as argument. The method
creates a new Triangle object and initializes it from three Point objects
(assume that Point is a class that represents an x, y coordinate)

public Triangle triangleFrom(Point p1, Point p2,


Point p3) {
// method body goes here

}
The Java programming language doesn't let you pass
methods into methods. But you can pass an object into
a method and then invoke the object's methods.
BITS Pilani, Pilani Campus
Parameter Names
• When you declare a parameter to a method or a constructor, you
provide a name for that parameter. This name is used within the
method body to refer to the passed-in argument.

• The name of a parameter must be unique in its scope. It cannot be


the same as the name of another parameter for the same method
or constructor, and it cannot be the name of a local variable within
the method or constructor.

• A parameter can have the same name as one of the class's fields. If
this is the case, the parameter is said to shadow the field.
Shadowing fields can make your code difficult to read and is
conventionally used only within constructors and methods that set a
particular field.

BITS Pilani, Pilani Campus


Parameter Names

public class Circle {


private int x, y, radius;
public void setOrigin(int x, int y) {
...
}
}

• The Circle class has three fields: x, y, and radius. The setOrigin
method has two parameters, each of which has the same name as
one of the fields. Each method parameter shadows the field that
shares its name. So using the simple names x or y within the body
of the method refers to the parameter, not to the field. To access
the field, you must use a qualified name.

BITS Pilani, Pilani Campus


Passing Primitive Data Type Arguments

public class PassPrimitiveByValue{

public static void main(String[] args) {

int x = 3;
passMethod(x);
S.o.p("After invoking passMethod, x = " + x);
}

// change parameter in passMethod()


public static void passMethod(int p) {
p = 10;
}
} Primitive arguments, such as an int or a double, are passed
into methods by value. This means that any changes to the
values of the parameters exist only within the scope of the
method. When the method returns, the parameters are gone
and any changes to them are lost.

BITS Pilani, Pilani Campus


Passing Reference Data Type Arguments
• Reference data type parameters, such as objects, are also passed into
methods by value. This means that when the method returns, the passed
in reference still references the same object as before. However, the
values of the object's fields can be changed in the method, if they have
the proper access level.

public void moveCircle(Circle circle, int deltaX, int deltaY) {

// code to move origin of circle to x+deltaX, y+deltaY


circle.setX(circle.getX() + deltaX);
circle.setY(circle.getY() + deltaY);

//code to assign a new reference to circle


circle = new Circle(0, 0);
}
INVOKE: moveCircle(myCircle, 23, 56) ;
BITS Pilani, Pilani Campus
Passing Reference Data Type Arguments

• Inside the method, circle initially refers to myCircle. The method


changes the x and y coordinates of the object that circle references
(i.e., myCircle) by 23 and 56, respectively. These changes will
persist when the method returns. Then circle is assigned a
reference to a new Circle object with x = y = 0. This reassignment
has no permanence, however, because the reference was passed in
by value and cannot change. Within the method, the object pointed
to by circle has changed, but, when the method returns, myCircle
still references the same Circle object as before the method was
called.

[Lecture Slides on Reference Types & Java Memory Management


have detailed discussion on this topic]

BITS Pilani, Pilani Campus


THANK YOU

BITS Pilani, Pilani Campus


BITS Pilani
Pilani Campus

Access Modifiers, Constructors, and Reference Types


Access Modifiers – public variables
public class A {
public int i, j;
public void show(){
System.out.println("i = " + i + " and j = " +
j );
}
}
public class Test {
public static void main(String[] args) {
A a = new A();
a.i = 5; /* public variables can be accessed
a.j = 10; outside of class definition */
a.show();
}
}

BITS Pilani, Pilani Campus


Access Modifiers – private variables
public class A {
private int i, j;
public void show(){
System.out.println("i = " + i + " and j = " +
j );
}
}
public class Test {
public static void main(String[] args) {
A a = new A();
Test.java:11: i has private access in A
a.i = 5;
a.i = 5;
a.j = 10;
^
a.show();
Test.java:12: j has private access in A
}
a.j = 10;
}
^
2 errors

BITS Pilani, Pilani Campus


Access Modifiers – public methods
public class A {
public int i, j;
public void show(){
System.out.println("i = " + i + " and j = " +
j );
}
}
public class Test {
public static void main(String[] args) {
A a = new A();
a.i = 5;
a.j = 10; /* public methods of a class can be
a.show(); invoked from outside of the class
} definition */
}

BITS Pilani, Pilani Campus


Access Modifiers – private methods
public class A {
private int i = 5, j = 10;
private void show(){
System.out.println("i = " + i + " and j = " +
j );
}
}
public class Test {
public static void main(String[] args) {
A a = new A();
a.show(); /* The method show() from the type A is
} not visible */
}

BITS Pilani, Pilani Campus


Access Modifiers –
public class A {
private int i, j;
private void show(){
System.out.println("i = " + i + " and j = " +
j );
}
public void display(){
i = 5;
/* public or private methods of a class
j = 10;
can refer to both public or private fields
show();
and methods of the same class*/
}
}
public class Test {
public static void main(String[] args) {
A a = new A();
a.display ();
}
}

BITS Pilani, Pilani Campus


Constructors –
public class A {
private int i;
public A(){ /* Constructor is called to instantiate
i = 5; a class and initialize the fields */
}
public void show(){
System.out.println(" Value of i = " + i)
}
}

public class Test {


public static void main(String[] args) {
A a = new A();
a.display (); /* A call to the constructor is the
} first thing that happens when you try
} to instantiate any class */

BITS Pilani, Pilani Campus


Overloading Constructors –
public class A {

private int i;

public A(){
i = 5;
}
/* Overloaded constructors are used to
public A(int x){ instantiate and initialize the fields
i = x; with the values supplied via the
} constructor */

public void show(){


System.out.println(" Value of i = " + i)
}
}

BITS Pilani, Pilani Campus


Overloading Constructors (Contd.)
public class Student { public class TestStudent {
public static void main(String[] args){
private int id; Student s1 = new Student();
private String name; Student s2 = new Student(1, "Avi",9.0);
private double cgpa; Student s3 = new Student(2, "Dol",9.0);
}
public Student(){ }
id = 0;
name = null; /* When a class is instantiated the JVM
cgpa = 0.0; first looks for the no argument constructor
} defined for this class, if it is not found
then the default constructor is called. If
public Student(int i, you have defined an overloaded constructor
for this class then the class should always
String nam, be instantiated with all the arguments
double cgp){ specified in their correct order as
id = i; specified in the constructor declaration.
name = nam; This is because, any constructor that you
cgpa = cgp; explicitly define hides the default
} constructor */
}
BITS Pilani, Pilani Campus
Pass by Value
1. Most methods are passed arguments when they are called. An
argument may be a constant or a variable.
 For example, in the expression
Math.sqrt(33), the constant 33 is passed to the sqrt()
method of the Math class. In the expression
Math.sqrt(x), the variable x is passed.

2. This is simple enough, however there is an important but


simple principle at work here. If a variable is passed, the
method receives a copy of the variable's value. The value of
the original variable cannot be changed within the method.
This seems reasonable because the method only has a copy of
the value; it does not have access to the original variable.
This process is called pass by value.

BITS Pilani, Pilani Campus


Pass by Value - Example
public class DemoPassByValue {
public static void main(String[] args) {
int i = 25;
System.out.println(i);
iMethod(i);
System.out.println(i);
}

public static void iMethod(int iTest) {


iTest = 9; // change it
System.out.println(iTest);
}
}

BITS Pilani, Pilani Campus


Pass by Reference
1. See Java Memory Management Slides before reading this section.
2. If the variable passed as an object, then the effect is
different.
3. We often say things like,
 This method returns an object
 This method is passed an object as an argument
4. This not quite true, more precisely, we should say,
 This method returns a reference to an object
 This method is passed a reference to an object as an
argument
5. In fact, objects, per se, are never passed to methods or returned
by methods. It is always "a reference to an object" that is
passed or returned.
6. The term "variable" also deserves clarification. There are two
types of variables in Java:
 Those that hold the value of a primitive data type and those
that hold a reference to an object.
 A variable that holds a reference to an object is an "object
variable" — the prefix "object" is often dropped for brevity.

BITS Pilani, Pilani Campus


Pass by Reference vs Pass by Value
1. Pass by value refers to passing a constant or a variable
holding a primitive data type to a method, and pass by
reference refers to passing an object variable to a method.
2. In both cases a copy of the variable is passed to the
method. It is a copy of the "value" for a primitive data
type variable; it is a copy of the "reference" for an object
variable. So, a method receiving an object variable as an
argument receives a copy of the reference to the original
object.
3. Here's the catch: If the method uses that reference to make
changes to the object, then the original object is changed.
This is reasonable because both the original reference and
the copy of the reference "refer to" to same thing — the
original object.
4. There is one exception: Strings. Since String objects are
immutable in Java, a method that is passed a reference to a
String object cannot change the original object.

BITS Pilani, Pilani Campus


Pass by Reference – Example (StringBuffer)

public class DemoPassByReference1 {

public static void main(String[] args) {


StringBuffer sb = new StringBuffer("Hello, world");
System.out.println(sb);
sbMethod(sb);
System.out.println(sb);
}

public static void sbMethod(StringBuffer sbTest) {


sbTest = sbTest.insert(7, "Java ");
System.out.println(sbTest);
}
}

BITS Pilani, Pilani Campus


Pass by Reference – Example (StringBuffer)

BITS Pilani, Pilani Campus


Pass by Reference – Example (String)

public class DemoPassByReference2 {

public static void main(String[] args) {


String s = "Java is fun!";
System.out.println(s);
sMethod(s);
System.out.println(s);
}

public static void sMethod(String sTest){


sTest = sTest.substring(8, 11);
System.out.println(sTest);
}
}

BITS Pilani, Pilani Campus


Pass by Reference – Example (String)

BITS Pilani, Pilani Campus


THANK YOU

BITS Pilani, Pilani Campus


BITS Pilani
Pilani Campus

Reference Types & Java Memory Management


Stack and Heap

• When your program is running, some memory is


used to store local variables. This memory is known
as the stack.
• We can use a table to represent variables stored on
the stack
Var Value
x 42
y 3.7
• The rest of memory is known as the heap and is used
for dynamically allocated “stuff” (recall using malloc()
in C)

BITS Pilani, Pilani Campus


Main Memory

The stack grows and shrinks as needed (why?)


The used part of the heap (“allocated”) also grows and shrinks.
Some of the heap is unused (“free”)

Stack Free Heap Used Heap

BITS Pilani, Pilani Campus


Object Creation

Consider this code that creates two strings


String s1, s2;
s1 = new String( “abc” );
s2 = “abc” ;

Note: Because Strings are very common, using new when creating String objects is optional.

Where are these variables and object located in


memory?
Why do we care?

BITS Pilani, Pilani Campus


Objects in Memory

The statement String s1, s2; creates two local variables on the stack.
The statements
s1 = new String( “abc” );
s2 = “abc”;

create objects on the heap. s1 and s2 contain the memory addresses of


these objects giving us the picture of memory shown below.

s1 and s2 are called reference variables. Reference variables which do not


contain the memory address of any object contain the special value null
Stack Heap

s1
s2 abc abc

BITS Pilani, Pilani Campus


Why We Care (1 of 4)

Given the previous code Stack Heap


String s1, s2;
s1 = new String( “abc” );
s2 = “abc”;
s1
and corresponding picture of memory s2 abc abc
consider the expression s1 == s2

Recall that s1 and s2 contain the addresses of their respective String objects.
Since the String objects have different addresses on the heap, s1 == s2 is
false. The == operator determines if two reference variables refer to the same
Object.

So how do we compare Strings for equality?


Strings (and other objects) implement a method named equals.
To check if two Strings are the same, use the expression
s1.equals( s2 );

BITS Pilani, Pilani Campus


Why We Care (2 of 4)

Stack Heap
On the other hand, consider this code
and corresponding picture of
memory s1
String s1 = “abc”; s2 abc
String s2 = s1; s1 and s2 are ALIASed

Now s1 and s2 refer to the same String object. This is known as ALIASING, is often
unintentional, and can be dangerous.

If your intent is for s2 to be a copy of s1, then the correct code is


String s2 = new String( s1 );

BITS Pilani, Pilani Campus


Why We Care (3 of 4)

Consider this code and the changing picture of memory

String s1 = “abc”; // line 1


s1 = “xyz”; // line 2
S1 = “Hello”; // line 3

Stack Heap Stack Heap Stack Heap


Hello

s1 abc s1 abc xyz s1 abc xyz


After line 1 After line 2 After line 3

BITS Pilani, Pilani Campus


Why We Care (4 of 4)

• Garbage collection Stack Heap

As the diagram shows, after line 3 is Hello


executed no variable refers to the
s1 abc xyz
String objects which contain “abc”
or “xyz”. After line 3

In C/C++, we’d consider this a “memory leak”. In C/C++ it’s the


programmer’s responsibility to return dynamically allocated memory
back to the free heap. (recall using malloc and free in C?)
Not so in Java!

Java has a built-in “garbage collector”. From time to time Java detects
objects has been “orphaned” because no reference variable refers to
them. The garbage collector automatically returns the memory for
those objects to the free heap.

BITS Pilani, Pilani Campus


THANK YOU

BITS Pilani, Pilani Campus


JVM Memory usage

Thread Stack Heap memory


JVM Memory usage

Thread Stack Heap memory

main
JVM Memory usage

Thread Stack Heap memory


Employee instance

name null
salary null
sales null
bonus null

String instance

“John”
Employee:new
Integer instance
this
name 5000
salary
sales

Integer instance

main 5
JVM Memory usage

Thread Stack Heap memory


Employee instance

name null
salary null
sales null
bonus null

String instance

“John”
Employee:new
Integer instance
this
name 5000
salary
sales

Integer instance

main 5
JVM Memory usage

Thread Stack Heap memory


Employee instance

name
salary null
sales null
bonus null

String instance

“John”
Employee:new
Integer instance
this
name 5000
salary
sales

Integer instance

main 5
JVM Memory usage

Thread Stack Heap memory


Employee instance

name
salary
sales null
bonus null

String instance

“John”
Employee:new
Integer instance
this
name 5000
salary
sales

Integer instance

main 5
JVM Memory usage

Thread Stack Heap memory


Employee instance

name
salary
sales
bonus null

String instance

“John”
Employee:new

this Integer instance


name
salary 5000
sales

Integer instance
main
5
JVM Memory usage

Thread Stack Heap memory


Employee instance

name
salary
sales
bonus null

String instance

“John”
Employee:new

this Integer instance


name
salary 5000
sales
return void

Integer instance
main
5
JVM Memory usage

Thread Stack Heap memory


Employee instance

name
salary
sales
bonus null

String instance

“John”

Integer instance

5000

main
john Integer instance

5
JVM Memory usage

Thread Stack Heap memory


Employee instance

name
salary
sales
bonus null

String instance

findEmployeeBonus “John”

salary 5000
noOfSales 5
Integer instance

5000

main
john Integer instance

5
JVM Memory usage

Thread Stack Heap memory


Employee instance

name
salary
sales
getBonusPercentage
bonus null
salary 5000

String instance

findEmployeeBonus “John”

salary 5000
noOfSales 5
Integer instance

5000

main
john Integer instance

5
JVM Memory usage

Thread Stack Heap memory


Employee instance

name
salary
sales
getBonusPercentage
bonus null
salary 5000
percentage 500
String instance

findEmployeeBonus “John”

salary 5000
noOfSales 5
Integer instance

5000

main
john Integer instance

5
JVM Memory usage

Thread Stack Heap memory


Employee instance

name
salary
getBonusPercentage
sales
salary 5000 bonus null
percentage 500
return 500
String instance

findEmployeeBonus “John”

salary 5000
noOfSales 5
Integer instance

5000

main
john Integer instance

5
JVM Memory usage

Thread Stack Heap memory


Employee instance

name
salary
sales
bonus null

findEmployeeBonus
String instance
salary 5000
“John”
noOfSales 5
bonusPercentage 500
bonus 2500
Integer instance

5000

main
john Integer instance

5
JVM Memory usage

Thread Stack Heap memory


Employee instance

name
salary
sales
bonus null

findEmployeeBonus
String instance
salary 5000
“John”
noOfSales 5
bonusPercentage 500
bonus 2500
return 2500 Integer instance

5000

main
john Integer instance

5
JVM Memory usage

Thread Stack Heap memory


Employee instance

name
salary
sales
bonus

String instance

“John”

Integer instance

5000

main Integer instance


john
5

Integer instance

2500
JVM Memory usage

Thread Stack Heap memory


Employee instance

name
salary
sales
bonus

String instance

“John”

Integer instance

5000

main Integer instance


john
return void 5

Integer instance

2500
JVM Memory usage

Thread Stack Heap memory


Employee instance

name
salary
sales
bonus

String instance

“John”

Integer instance

5000

Integer instance

Integer instance

2500
BITS Pilani
Pilani Campus

Object-Oriented Programming (CS F213)

Final and Abstract Classes


Restricting Inheritance

Parent

Inherited
capability

Child

2
BITS Pilani, Pilani Campus
Final Members: A way for Preventing
Overriding of Members in Subclasses
• All methods and variables can be overridden by
default in subclasses.
• This can be prevented by declaring them as final
using the keyword “final” as a modifier. For example:
– final int marks = 100;
– final void display();
• This ensures that functionality defined in this method
cannot be altered any. Similarly, the value of a final
variable cannot be altered.

3
BITS Pilani, Pilani Campus
Final Classes: A way for Preventing Classes
being extended

• We can prevent an inheritance of classes by other classes by


declaring them as final classes.
• This is achieved in Java by using the keyword final as follows:
final class Marks
{ // members
}
final class Student extends Person
{ // members
}
• Any attempt to inherit these classes will cause an error.

4
BITS Pilani, Pilani Campus
Abstract Classes

• When we define a class to be “final”, it cannot be


extended. In certain situation, we want to
properties of classes to be always extended and
used. Such classes are called Abstract Classes.

• An Abstract class is a conceptual class.


• An Abstract class cannot be instantiated – objects
cannot be created.

• Abstract classes provides a common root for a


group of classes, nicely tied together in a package:

5
BITS Pilani, Pilani Campus
Abstract Class Syntax

abstract class ClassName


{
...

abstract Type MethodName1();


Type Method2()
{
// method body
}
}
• When a class contains one or more abstract methods, it should be
declared as abstract class.
• The abstract methods of an abstract class must be defined in its subclass.
• We cannot declare abstract constructors or abstract static methods.

6
BITS Pilani, Pilani Campus
Abstract Class -Example

• Shape is a abstract class.

Shape

Circle Rectangle

7
BITS Pilani, Pilani Campus
The Shape Abstract Class

public abstract class Shape {


public abstract double area();
public void move() { // non-abstract
method
// implementation
}
}
• Is the following statement valid?
– Shape s = new Shape();
• No. It is illegal because the Shape class is an abstract class,
which cannot be instantiated to create its objects.

8
BITS Pilani, Pilani Campus
Abstract Classes

public Circle extends Shape {


protected double r;
protected static final double PI
=3.1415926535;
public Circle() { r = 1.0; )
public double area() { return PI * r * r; }

}
public Rectangle extends Shape {
protected double w, h;
public Rectangle() { w = 0.0; h=0.0; }
public double area() { return w * h; }
} 9
BITS Pilani, Pilani Campus
Abstract Classes Properties

• A class with one or more abstract methods is


automatically abstract and it cannot be instantiated.
• A class declared abstract, even with no abstract
methods can not be instantiated.
• A subclass of an abstract class can be instantiated if it
overrides all abstract methods by implementation
them.
• A subclass that does not implement all of the
superclass abstract methods is itself abstract; and it
cannot be instantiated.

10
BITS Pilani, Pilani Campus
Summary

• If you do not want (properties of) your class to be extended or


inherited by other classes, define it as a final class.
– Java supports this is through the keyword “final”.
– This is applied to classes.
• You can also apply the final to only methods if you do not
want anyone to override them.
• If you want your class (properties/methods) to be extended
by all those who want to use, then define it as an abstract
class or define one or more of its methods as abstract
methods.
– Java supports this is through the keyword “abstract”.
– This is applied to methods only.
– Subclasses should implement abstract methods; otherwise, they
cannot be instantiated.

11
BITS Pilani, Pilani Campus
BITS Pilani
Pilani Campus

Object Oriented Programming

Arrays
Introduction to Arrays
• An array is a data structure used to process a
collection of data that is all of the same type
– An array behaves like a numbered list of variables
with a uniform naming mechanism
– It has a part that does not change:
• the name of the array
– It has a part that can change:
• an integer in square brackets
– For example, given five scores:
score[0],score[1],score[2],score[3],score[4
]

BITS Pilani, Pilani Campus


Creating and Accessing Arrays
• An array that behaves like a collection of variables, all
of type double, can be created using one statement
double[] score = new double[5];
• Or using two statements:
double[] score;
score = new double[5];
– The first statement declares the variable score to be of
the array type double[] (an array of doubles)
– The second statement creates an array with five numbered
variables of type double and makes the variable score
a name for the array

BITS Pilani, Pilani Campus


Creating and Accessing Arrays
• The individual variables that together make up the
array are called indexed variables
– They can also be called subscripted variables or elements of
the array
– The number in square brackets is called an index or subscript
– The number of indexed variables in an array is called the
length or size of the array
– In Java indices must be numbered starting with 0, and
nothing else
score[0], score[1], score[2], score[3], score[4]

BITS Pilani, Pilani Campus


Creating and Accessing Arrays
• When an array is created, the length of the array is
given in square brackets after the array type

• The indexed variables are then numbered starting


with 0, and ending with the integer that is one less
than the length of the array

• The declaration
double[] score = new double[5];
results in the 5 elements
score[0], score[1], score[2], score[3], score[4]

BITS Pilani, Pilani Campus


Creating and Accessing Arrays
double[] score = new double[5];

• A variable may be used in place of the integer (i.e., in place of


the integer 5 above)
– The value of this variable can then be read from the keyboard
– This enables the size of the array to be determined when the
program is run
double[] score = new double[count];
• An array can have indexed variables of any type, including any
class type

• All of the indexed variables in a single array must be of the same


type, called the base type of the array

BITS Pilani, Pilani Campus


Declaring and Creating an Array
• An array is declared and created in almost the same way that
objects are declared and created:

BaseType[] ArrayName = new BaseType[size];

– The size may be given as an expression that evaluates


to a nonnegative integer, for example, an int variable
char[] line = new char[80];
double[] reading = new double[count];
Person[] specimen = new Person[100];

BITS Pilani, Pilani Campus


Referring to Arrays and Array Elements
• Each array element can be used just like any other single
variable by referring to it using an indexed expression:
score[0]
• The array itself (i.e., the entire collection of indexed
variables) can be referred to using the array name
(without any square brackets): score
• An array index can be computed when a program is run
– It may be represented by a variable: score[index]
– It may be represented by an expression that evaluates
to a suitable integer: score[next + 1]

BITS Pilani, Pilani Campus


Using the score Array in a Program
• The for loop is ideally suited for performing array
manipulations:
for (int index = 0; index < 5; index++)
System.out.println(score[index]
+ " differs from max by "
+ (max - score[index]) );

BITS Pilani, Pilani Campus


Three Ways to Use Square Brackets []
with an Array Name
• Square brackets can be used to create a type name:
double[] score;

• Square brackets can be used with an integer value as


part of the special syntax Java uses to create a new
array:
score = new double[5];

• Square brackets can be used to name an indexed


variable of an array:
max = score[0];

BITS Pilani, Pilani Campus


The length Instance Variable
• An array is considered to be an object
• Since other objects can have instance variables, so can arrays
• Every array has exactly one instance variable named
length
– When an array is created, the instance variable length
is automatically set equal to its size
– The value of length cannot be changed (other than by
creating an entirely new array using new)
double[] score = new double[5];
– Given score above, score.length has a value of 5

BITS Pilani, Pilani Campus


Pitfall: 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


Initializing Arrays
• An array can be initialized when it is declared
– Values for the indexed variables are enclosed in braces,
and separated by commas
– The array size is automatically set to the number of values
in the braces
int[] age = {2, 12, 1};
– Given age above, age.length has a value of 3

BITS Pilani, Pilani Campus


Initializing Arrays
• Another way of initializing an array is by using a for loop

double[] reading = new double[100];


for (int index = 0; index < reading.length; index++){
reading[index] = 42.0;
}

• If the elements of an array are not initialized explicitly, they will


automatically be initialized to the default value for their base type

BITS Pilani, Pilani Campus


An 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

(continued)

BITS Pilani, Pilani Campus


An Array of Characters Is Not a String
• The class String has a constructor that has a single
parameter of type char[]
String s = new String(a);
– The object s will have the same sequence of characters as
the entire array a ("ABC"), but is an independent copy
• Another String constructor uses a subrange of a
character array instead
String s2 = new String(a,0,2);
– Given a as before, the new string object is "AB"

(continued)

BITS Pilani, Pilani Campus


An Array of Characters Is Not a String
• An array of characters does have some things in
common with String objects
– For example, an array of characters can be output
using println
System.out.println(a);
– Given a as before, this would produce the output
ABC

BITS Pilani, Pilani Campus


Arrays and References
• Like class types, a variable of an array type
holds a reference
– Arrays are objects
– A variable of an array type holds the address of
where the array object is stored in memory
– Array types are (usually) considered to be class
types

BITS Pilani, Pilani Campus


Arrays are Objects
• An array can be viewed as a collection of indexed variables
• An array can also be viewed as a single item whose value is a collection of
values of a base type
– An array variable names the array as a single item
double[] a;
– A new expression creates an array object and stores the object in
memory
new double[10]
– An assignment statement places a reference to the memory address of
an array object in the array variable
a = new double[10];

– The previous steps can be combined into one statement


double[] a = new double[10];
(continued)

BITS Pilani, Pilani Campus


Arrays with a Class Base Type
• The base type of an array can be a class type
Date[] holidayList = new Date[20];

• The above example creates 20 indexed reference


variables of type Date. It does not create 20
objects of the class Date
– Each of these indexed variables are automatically
initialized to null
– Any attempt to reference any them at this point would
result in a "null pointer exception" error message

(continued)

BITS Pilani, Pilani Campus


Arrays with a Class Base Type
• Like any other object, each of the indexed variables requires a
separate invocation of a constructor using new (singly, or
perhaps using a for loop) to create an object to reference

holidayList[0] = new Date();


. . .
holidayList[19] = new Date();
OR
for (int i = 0; i < holidayList.length; i++)
holidayList[i] = new Date();

• Each of the indexed variables can now be referenced since


each holds the memory address of a Date object

BITS Pilani, Pilani Campus


Array Parameters
• Both array indexed variables and entire arrays
can be used as arguments to methods
– An indexed variable can be an argument to a
method in exactly the same way that any variable
of the array base type can be an argument

BITS Pilani, Pilani Campus


Array Parameters
double n = 0.0;
double[] a = {2.3, 4.5, 6.7, 8.9};
int i = 2;

Given the method declaration


public void myMethod (double x)

then all of the following are legal:


myMethod(n); //n evaluates to 0.0
myMethod(a[3]); //a[3] evaluates to 8.9
myMethod(a[i]); //i evaluates to 2,
//a[2] evaluates to 6.7

BITS Pilani, Pilani Campus


Array Parameters
• An argument to a method may be an entire array
• Array arguments behave like objects of a class
– Therefore, a method can change the values stored in the
indexed variables of an array argument
• A method with an array parameter must specify the
base type of the array only
BaseType[]
– It does not specify the length of the array

BITS Pilani, Pilani Campus


Array Parameters
The following method, doubleElements, specifies an array of
double as its single argument:

public class SampleClass{


public static void doubleElements(double[] a){
int i;
for (i = 0; i < a.length; i++)
a[i] = a[i] * 2;
. . .
}
. . .
}

(continued)
BITS Pilani, Pilani Campus
Array Parameters
• Arrays of double may be defined as follows:
double[] a = new double[10];
double[] b = new double[30];
• Given the arrays above, the method doubleElements
from class SampleClass can be invoked as follows:
SampleClass.doubleElements(a);
SampleClass.doubleElements(b);
– Note that no square brackets are used when an entire
array is given as an argument
– Note also that a method that specifies an array for a
parameter can take an array of any length as an argument

BITS Pilani, Pilani Campus


Use of = and == with Arrays
• Because an array variable contains the memory
address of the array it names (it’s a reference), the
assignment operator (=) only copies this memory
address
– It does not copy the values of each indexed variable
– Using the assignment operator b = a; will make two array
variables be different names for the same array
– The memory address in a is now the same as the memory
address in b: They reference the same array

(continued)

BITS Pilani, Pilani Campus


Use of = and == with Arrays

• A for loop is usually used to make two different arrays


have the same values in each indexed position:

for (int i = 0;(i < a.length) && (i < b.length); i++){


b[i] = a[i];
}

– Note that the above code will not make b an exact copy
of a, unless a and b have the same length
(continued)

BITS Pilani, Pilani Campus


Use of = and == with Arrays
• For the same reason, the equality operator (==) only
tests two arrays to see if they are stored in the same
location in memory
– (a == b) does not test two arrays to see if they contain
the same values

– The result of the above boolean expression will be true if


a and b share the same memory address (and, therefore,
reference the same array), and false otherwise

(continued)

BITS Pilani, Pilani Campus


Use of = and == with Arrays

• In the same way that an equals method can


be defined for a class, an equalsArray
method can be defined for a type of array
– This is how two arrays must be tested to see if they
contain the same elements

BITS Pilani, Pilani Campus


Use of = and == with Arrays
public static boolean equalsArray(int[] a,
int[] b){

if (a.length != b.length) return false;


else{
int i = 0;
while (i < a.length){
if (a[i] != b[i])
return false;
i++;
}
}
return true;
}

BITS Pilani, Pilani Campus


Arguments for the Method main
• The heading for the main method of a program has
a parameter for an array of String
– It is usually called args by convention
public static void main(String[] args)
– Note that since args is a parameter, it could be replaced
by any other non-keyword identifier
• If a Java program is run without giving an argument
to main, then a default empty array of strings is
automatically provided

BITS Pilani, Pilani Campus


Arguments for the Method main

• If a program requires that the main method


be provided an array of strings argument, each
element must be provided from the command
line when the program is run
java SomeProgram Hi ! there
– This will set args[0] to "Hi", args[1] to "!",
and args[2] to "there"
– It will also set args.length to 3

BITS Pilani, Pilani Campus


Methods That Return an Array
• In Java, a method may also return an array
– The return type is specified in the same way that an array
parameter is specified. This method returns an array of int

public static int[] incrementArray(int[] a,


int increment)
{
int[] temp = new int[a.length];
for (int i = 0; i < a.length; i++)
temp[i] = a[i] + increment;
return temp;
}

BITS Pilani, Pilani Campus


Privacy Leaks with Array Instance Variables
• If an accessor method does return the contents of an
array, special care must be taken
– Just as when an accessor returns a reference to any private
object
public double[] getArray(){
return anArray;
}
– The example above will result in a privacy leak.
– Why is this so?

BITS Pilani, Pilani Campus


Privacy Leaks with Array Instance Variables
• The previous accessor method would simply return a reference
to the array anArray itself

• Instead, an accessor method should return a reference to a deep


copy of the private array object
– Below, a is an array which is an instance variable of the class containing
the getArray method

public double[] getArray(){


double[] temp = new double[a.length];
for (int i = 0; i < a.length; i++)
temp[i] = a[i];
return temp
}

BITS Pilani, Pilani Campus


Privacy Leaks with Array Instance Variables
• If a private instance variable is an array that has a class as its
base type, then copies must be made of each class object in
the array when the array is copied. Here b is an array of class
types and an instance variable of the class containing the
getArray method
public ClassType[] getArray(){
ClassType[] temp = new ClassType[b.length];
for (int i = 0; i < b.length; i++)
temp[i] = new ClassType(b[i]);
return temp;
}

BITS Pilani, Pilani Campus


Multidimensional Arrays
• It is sometimes useful to have an array with more
than one index
• Multidimensional arrays are declared and created in
basically the same way as one-dimensional arrays
– You simply use as many square brackets as there are
indices
– Each index must be enclosed in its own brackets
double[][]table = new double[100][10];
int[][][] figure = new int[10][20][30];
Person[][] = new Person[10][100];

BITS Pilani, Pilani Campus


Multidimensional Arrays
• Multidimensional arrays may have any number of
indices, but perhaps the most common number is
two
– Two-dimensional array can be visualized as a two-
dimensional display with the first index giving the row, and
the second index giving the column
char[][] a = new char[5][12];
– Note that, like a one-dimensional array, each element of a
multidimensional array is just a variable of the base type
(in this case, char)

BITS Pilani, Pilani Campus


Multidimensional Arrays
• In Java, a two-dimensional array, such as a, is actually
an array of arrays
– The array a contains a reference to a one-dimensional
array of size 5 with a base type of char[]
– Each indexed variable (a[0], a[1], etc.) contains a
reference to a one-dimensional array of size 12, also with a
base type of char[]
• A three-dimensional array is an array of arrays of
arrays, and so forth for higher dimensions

BITS Pilani, Pilani Campus


Two-Dimensional Array as an
Array of Arrays (Part 1 of 2)

BITS Pilani, Pilani Campus


Two-Dimensional Array as an
Array of Arrays (Part 2 of 2)

BITS Pilani, Pilani Campus


Using the length Instance Variable
char[][] page = new char[30][100];
• The instance variable length does not give the total
number of indexed variables in a two-dimensional array
– Because a two-dimensional array is actually an array
of arrays, the instance variable length gives the
number of first indices (or "rows") in the array
• page.length is equal to 30
– For the same reason, the number of second indices
(or "columns") for a given "row" is given by
referencing length for that "row" variable
• page[0].length is equal to 100

BITS Pilani, Pilani Campus


Using the length Instance Variable
• The following program demonstrates how a nested for
loop can be used to process a two-dimensional array
– Note how each length instance variable is used

int row, column;


for (row = 0; row < page.length; row++)
for (column = 0; column < page[row].length;
column++)
page[row][column] = 'Z';

BITS Pilani, Pilani Campus


Multidimensional Array Parameters
and Returned Values
• Methods may have multidimensional array
parameters
– They are specified in a way similar to one-dimensional
arrays
– They use the same number of sets of square brackets as
they have dimensions
public void myMethod(int[][] a)
{ . . . }
– The parameter a is a two-dimensional array

BITS Pilani, Pilani Campus


Multidimensional Array Parameters
and Returned Values
• Methods may have a multidimensional array
type as their return type
– They use the same kind of type specification as for
a multidimensional array parameter
public double[][] aMethod()
{ . . . }
– The method aMethod returns an array of
double

BITS Pilani, Pilani Campus


A Grade Book Class
• As an example of using arrays in a program, a class
GradeBook is used to process quiz scores
• Objects of this class have three instance variables
– grade: a two-dimensional array that records the grade of
each student on each quiz
– studentAverage: an array used to record the average
quiz score for each student
– quizAverage: an array used to record the average
score for each quiz

BITS Pilani, Pilani Campus


A Grade Book Class
• The score that student 1 received on quiz number 3
is recorded in grade[0][2]
• The average quiz grade for student 2 is recorded in
studentAverage[1]
• The average score for quiz 3 is recorded in
quizAverage[2]
• Note the relationship among the three arrays

BITS Pilani, Pilani Campus


The 2-Dimensional Array grade

BITS Pilani, Pilani Campus


THANK YOU

BITS Pilani, Pilani Campus


java.util
Class Arrays
This class contains various methods for manipulating arrays (such as sorting and searching).
Method Summary
static type binarySearch(type[] a, type key)

Searches the specified array of type for the specified value using the binary
search algorithm.

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


static boolean equals(type[] a, type[] a2)

Returns true if the two specified arrays of type are equal to one another.

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


static void fill(type[] a, type val)

Assigns the specified type value to each element of the specified array of
type.

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


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.

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


static void sort(type[] a)

Sorts the specified array of type into ascending numerical order.

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


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

Object Oriented Programming

The String Class


Objectives

• Learn about literal strings


• Learn about String constructors
• Learn about commonly used methods
• Understand immutability of strings
• Learn to format numbers into strings

BITS Pilani, Pilani Campus


String class facts

• An object of the String class represents a string of


characters.
• The String class belongs to the java.lang package,
which does not require an import statement.
• Like other classes, String has constructors and
methods.
• Unlike other classes, String has two operators, + and
+= (used for concatenation).

BITS Pilani, Pilani Campus


Literal Strings

• are anonymous objects of the String class


• are defined by enclosing text in double quotes. “This
is a literal String”
• don’t have to be constructed.
• can be assigned to String variables.
• can be passed to methods and constructors as
parameters.
• have methods you can call.

BITS Pilani, Pilani Campus


Literal String examples

//assign a literal to a String variable


String name = “Robert”;

//calling a method on a literal String


char firstInitial = “Robert”.charAt(0);

//calling a method on a String variable


char firstInitial = name.charAt(0);

BITS Pilani, Pilani Campus


Immutability

• Once created, a string cannot be changed: none of its


methods changes the string.
• Such objects are called immutable.
• Immutable objects are convenient because several
references can point to the same object safely: there
is no danger of changing an object through one
reference without the others being aware of the
change.

BITS Pilani, Pilani Campus


Advantages Of Immutability

Uses less memory.


String word1 = "Java"; String word1 = “Java";
String word2 = “Java”; String word2 = new String(word1);

word1 word1 “Java"

“Java" word2 “Java"


word2
Less efficient:
OK wastes memory

BITS Pilani, Pilani Campus


Disadvantages of Immutability

Less efficient — you need to create a new string and throw


away the old one even for small changes.

String word = “java";


char ch = Character.toUpperCase(word.charAt (0));
word = ch + word.substring (1);

word “java"

“Java"

BITS Pilani, Pilani Campus


Empty Strings

• An empty String has no characters. It’s length is


0.
String word1 = ""; Empty strings
String word2 = new String();

• Not the same as an uninitialized String.


private String errorMsg; errorMsg
is null

BITS Pilani, Pilani Campus


No Argument Constructors

• No-argument constructor creates an empty


String. Rarely used.
String empty = new String();
• A more common approach is to reassign the
variable to an empty literal String. (Often done to
reinitialize a variable used to store input.)

String empty = “”;//nothing between quotes

BITS Pilani, Pilani Campus


Copy Constructors

• Copy constructor creates a copy of an existing String.


Also rarely used.
• Not the same as an assignment.

Copy Constructor: Each variable points to a different copy of the String.

String word = new String(“Java”); word “Java"


String word2 = new String(word); word2 “Java"
Assignment: Both variables point to the same String.

String word = “Java”; word


String word2 = word;
“Java"
word2

BITS Pilani, Pilani Campus


Other Constructors

Most other constructors take an array as a


parameter to create a String.

char[] letters = {‘J’, ‘a’, ‘v’, ‘a’};


String word = new String(letters);//”Java”

BITS Pilani, Pilani Campus


Methods — length, charAt

int length();  Returns the number of characters in


the string

char charAt(i);  Returns the char at position i.

Character positions in strings are numbered starting


from 0 – just like arrays.
Returns:
”Problem".length(); 7
”Window".charAt (2); ’n'

BITS Pilani, Pilani Campus


Methods — substring

Returns a new String by copying characters from an existing String.

• String subs = word.substring (i, k); television


– returns the substring of chars in
positions from i to k-1 i k
• String subs = word.substring (i); television
– returns the substring from the i-th
char to the end i
Returns:
”television".substring (2,5); “lev"
“immutable".substring (2); “mutable"
“bob".substring (9); "" (empty string)

BITS Pilani, Pilani Campus


Methods — Concatenation

String word1 = “re”, word2 = “think”; word3 = “ing”;


int num = 2;

• String result = word1 + word2;


//concatenates word1 and word2 “rethink“

• String result = word1.concat (word2);


//the same as word1 + word2 “rethink“

• result += word3;
//concatenates word3 to result “rethinking”

• result += num; //converts num to String


//and concatenates it to result “rethinking2”

BITS Pilani, Pilani Campus


Methods — Find (indexOf)

0 2 6 10 15

String name =“President George Washington";


Returns:
name.indexOf ('P'); 0
name.indexOf ('e'); 2
name.indexOf ("George"); 10
name.indexOf ('e', 3); 6 (starts searching
at position 3)
name.indexOf ("Bob"); -1
(not found)
name.lastIndexOf ('e'); 15

BITS Pilani, Pilani Campus


Methods — Equality

boolean b = word1.equals(word2);
returns true if the string word1 is equal to word2
boolean b = word1.equalsIgnoreCase(word2);
returns true if the string word1 matches word2, case-
blind

b = “Raiders”.equals(“Raiders”);//true
b = “Raiders”.equals(“raiders”);//false
b = “Raiders”.equalsIgnoreCase(“raiders”);//true

if(team.equalsIgnoreCase(“raiders”))
System.out.println(“Go You “ + team);

BITS Pilani, Pilani Campus


Methods — Comparisons

int diff = word1.compareTo(word2);


returns the “difference” word1 - word2
int diff = word1.compareToIgnoreCase(word2);
returns the “difference” word1 - word2,
case-blind
Usually programmers don’t care what the numerical “difference” of
word1 - word2 is, just whether the difference is negative (word1 comes
before word2), zero (word1 and word2 are equal) or positive (word1
comes after word2). Often used in conditional statements.

if(word1.compareTo(word2) > 0){


//word1 comes after word2…
}
BITS Pilani, Pilani Campus
Comparison Examples

//negative differences
diff = “apple”.compareTo(“berry”);//a before b
diff = “Zebra”.compareTo(“apple”);//Z before a
diff = “dig”.compareTo(“dug”);//i before u
diff = “dig”.compareTo(“digs”);//dig is shorter

//zero differences
diff = “apple”.compareTo(“apple”);//equal
diff = “dig”.compareToIgnoreCase(“DIG”);//equal

//positive differences
diff = “berry”.compareTo(“apple”);//b after a
diff = “apple”.compareTo(“Apple”);//a after A
diff = “BIT”.compareTo(“BIG”);//T after G
diff = “huge”.compareTo(“hug”);//huge is longer
BITS Pilani, Pilani Campus
Methods — trim

String word2 = word1.trim ();


returns a new string formed from word1 by
removing white space at both ends
does not affect whites space in the middle
String word1 = “ Hi Bob “;
String word2 = word1.trim();
//word2 is “Hi Bob” – no spaces on either end
//word1 is still “ Hi Bob “ – with spaces

BITS Pilani, Pilani Campus


Methods — replace

String word2 = word1.replace(oldCh, newCh);


returns a new string formed from word1 by
replacing all occurrences of oldCh with newCh

String word1 = “rare“;


String word2 = “rare“.replace(‘r’, ‘d’);
//word2 is “dade”, but word1 is still “rare“

BITS Pilani, Pilani Campus


Methods — Changing Case

String word2 = word1.toUpperCase();


String word3 = word1.toLowerCase();
returns a new string formed from word1 by
converting its characters to upper (lower) case

String word1 = “HeLLo“;


String word2 = word1.toUpperCase();//”HELLO”
String word3 = word1.toLowerCase();//”hello”
//word1 is still “HeLLo“

BITS Pilani, Pilani Campus


Replacements

• Example: to “convert” word1 to upper case, replace the


reference with a new reference.

word1 = word1.toUpperCase();
• A common bug:

word1
word1.toUpperCase();
remains
unchanged

BITS Pilani, Pilani Campus


Numbers to Strings

Three ways to convert a number into a string:


1. String s = "" + num; Integer and Double are
s = “” + 123;//”123” “wrapper” classes from
2. String s = Integer.toString (i); java.lang that represent
numbers as objects.
String s = Double.toString (d); They also provide useful
s = Integer.toString(123);//”123” static methods.
s = Double.toString(3.14); //”3.14”

3. String s = String.valueOf (num);


s = String.valueOf(123);//”123”

BITS Pilani, Pilani Campus


Review Questions:

1. The String class is part of what package?


2. What does the String class have that
other classes do not have?
3. “Text enclosed in quotes is called ?”
4. What is the returned value for
“Rumplestiltskin”.length()?
5. Define immutable objects.

BITS Pilani, Pilani Campus


Review (cont’d):

6. How does immutability of Strings make


Java more efficient?
7. How does immutability of Strings make
Java less efficient?
8. How do you declare an empty string?
9. Why are String constructors not used very
often?
10. “Bob” + “ “ + “Smith” is called ____ ?

BITS Pilani, Pilani Campus


Review (cont’d):

11. String city = "Bloomington“;


What is returned by city.charAt (2)?
12. By city.substring(2, 4)?
13. By city.lastIndexOf(‘o’)?
14. By city.indexOf(3)?
15. What does the trim method do?

BITS Pilani, Pilani Campus


Review (cont’d):

16. “sam”.equals(“Sam”) returns ?


17. What kind of value does
“sam”.compareTo(“Sam”) return?
18. What will be stored in s?
s = “mint”.replace(‘t’, ‘e’);
19. What does s.toUpperCase() do to s?
20. Name a simple way to convert a number into
a string.

BITS Pilani, Pilani Campus


THANK YOU

BITS Pilani, Pilani Campus


BITS Pilani
Pilani Campus

Object Oriented Programming (CS F213)


Interactive Input/ Output
Contents

1. Reading data from the keyboard


2. Extracting separate data items from a String
3. Converting from a String to a primitive numerical type
4. An example showing how numerical data is read from
the keyboard and used to obtain and display a result
5. Using dialog boxes to obtain input data and display
results

BITS Pilani, Pilani Campus


Keyboard Input

The System class in java provides an InputStream object: System.in


And a buffered PrintStream object System.out

The PrintStream class (System.out) provides support for outputting


primitive data type values.
However, the InputStream class only provides methods for reading byte
values.

To extract data that is at a “higher level” than the byte, we must “encase” the
InputStream, System.in, inside an InputStreamReader object that converts
byte data into 16-bit character values (returned as an int).

We next “wrap” a BufferedReader object around the InputStreamReader to


enable us to use the methods read( ) which returns a char value and readLine( ),
which return a String.

BITS Pilani, Pilani Campus


Keyboard Input

BufferedReader
InputStreamReader

byte int string

import java.io.*; //for keyboard input stream

InputStreamReader isr = new InputStreamReader(System.in);


BufferedReader br = new BufferedReader(isr);
String st = br.readLine( );
//reads chars until eol and forms string

BITS Pilani, Pilani Campus


String Tokenizer
Consider the following program fragment:

import java.io.*;
public class TotalNumbers throws java.io.IOException{
private String str;
private int num;
public static void main (String [] args) {
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
System.out.print(“Enter four integers: “);
str = br.readLine( );

str = 6 2 4 3 2 1

BITS Pilani, Pilani Campus


String Tokenizer
We need to retrieve the four separate integers from the string.

str = 6 2 4 3 2 1

A token consists of a string of characters separated by a delimiter.

Delimiters consist of {space, tab, newline, return}

A StringTokenizer parses a String and extracts the individual tokens.

StringTokenizer st = new StringTokenizer (str); //create tokenizer and pass string


String s_temp;
while (st.hasMoreTokens( ) ) {
s_temp = st.nextToken( );
//now convert this string to an integer.

BITS Pilani, Pilani Campus


Wrapper Classes

For each of the primitive types there is a Wrapper class.

Primitive type object

int num1 = 6; Integer myInt = Integer(num1);


double num2 = 3.1416; Double pi = Double(num2);

In the statement Integer myInt = Integer(num1); an Integer object named


myInt is created and assigned a value equal to the contents of num1
Wrapper classes begin with an uppercase letter to distinguish from their
primitive type counterpart (int, long, short, double, float, byte, char, boolean).
int  Integer
double  Double
float  Float
char  Character

BITS Pilani, Pilani Campus


Wrapper Classes

Unlike primitive types, objects have operations called methods that they can
be directed to perform. (These methods have visibility static  they can be
accessed by using the class name without instantiating objects of the class.
Wrapper class objects have a method for converting a string into a primitive
type, and a method for transforming a primitive type into a string.
wrapper method name return type
Integer parseInt(String st) int
Integer toString(int num) String
Double parseDouble(String st) double
Double toString(double num) String
Float parseFloat(String st) float
Long parseLong(String st) long

BITS Pilani, Pilani Campus


Converting Tokenized String to Primitive Types

Return to the code for extracting tokens from the input string

int sum = 0, num;


String s;
while (st.hasMoreTokens( )) {
s = st.nextToken( );
//convert string to int
num = Integer.parseInt(s);
sum += num;
}

BITS Pilani, Pilani Campus


Review - Reading stream of integers from keyboard

Step 1 – Prompt user to enter multiple integers on one line

System.out.print(“Enter four integers separated by spaces: “);


Step 2 – Retrieve keyboard input as a stream of 16-bit chars (retuned as int)
InputStreamReader isr = new InputStreamReader(System.in);

Step 3 – Form input stream of characters into a string (look for eol)
BufferedReader br = new BufferedReader(isr);
String str = br.readLine( ); Need to throw java.io.IOException in function in
which it is used

Step 4 – Create StringTokenizer to extract tokens from the input string


StringTokenizer st = new StringTokenizer(str);

BITS Pilani, Pilani Campus


Review – continued

Step 5 – Parse the input string to extract tokens

String s1 = st.nextToken( );
//note can use while(st.hasMoreTokens( )) to repeatedly extract each
//token in the string

Step 6 – Use wrapper class methods to convert token (string) to primitive type

int num = Integer.parseInt(s1);

BITS Pilani, Pilani Campus


Putting it all together
import java.io.*; //for keyboard input methods
import java.util.*; //for StringTokenizer
public class TotalNumbers {
public static void main (String [] args) throws java.io.IOException {
String str, s;
int sum = 0, num;
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
System.out.print(“Enter four integers separated by spaces: “);
str = br.readLine( );
StringTokenizer st = new StringTokenizer(str);
while (st.hasMoreTokens( )) {
s = st.nextToken( );
num = Integer.parseInt(s);
sum += num;
}
}
}

BITS Pilani, Pilani Campus


Interactive Input
Using a Dialog box to request input data
Step 1 – Import swing package. import javax.swing.*;
Step 2 – Create an input dialog box (returns a String)

String str = JOptionPane.showInputDialog(“the message”);


Input
Input x

the message
?

OK Cancel

Step 3 – Write input value(s) in the text field //done by user


Step 4 – Click on command button (OK, Cancel) //done by user

BITS Pilani, Pilani Campus


Output to a Dialog Box

Types of Dialog Boxes icon

WARNING_MESSAGE !

QUESTION_MESSAGE ?

INFORMATION_MESSAGE

ERROR_MESSAGE

PLAIN_MESSAGE

BITS Pilani, Pilani Campus


Output Dialog Boxes
To create a dialog box for displaying output use showMessageDialog

JOptionPane.showMessageDialog(null, “message”, “title”,icon_type);

For example, the statement:

JOptionPane.showMessageDialog(null, “Little Programmers!”, “greetings”,


JOptionPane.PLAIN_MESSAGE);

produces
greetings X

Little Programmers!

OK

BITS Pilani, Pilani Campus


Output Dialog Boxes

Note that the icon-type field in the showDialogMessage( )


method is a static constant declared in class JOptionPane, and
must be referenced by a message to this class.

JOptionPane.PLAIN_MESSAGE

The icon_type determines which of the five icons (the fifth being no
icon at all) will appear in the dialog box.

Note! Without the final statement System.exit(0); a program that


ends with a message dialog box will still be active after the dialog box
has been closed.

BITS Pilani, Pilani Campus


An Interactive Program that Uses Dialog Boxes
import javax.swing.*; //for JOptionPane
import java.util.*; //for StringTokenizer
public class DialogExample {
public static void main(String [] args) {
String sInput, str;
int num, sum = 0;
sInput = JOptionPane.showInputDialog(“enter three integers:”);
StringTokenizer st = new StringTokenizer(sInput);
while (st.hasMoreTokens( ) ) {
str = st.nextToken( );
num = Integer.parseInt(str);
sum += num;
} //output the result to a dialog box
JOptionPane.showDialogMessage(null, “DialogExample Output”,
“the sum is: ”+ sum, JOptionPane.INFORMATION_MESSAGE);
System.exit(0); //needed to close program when using dialog box
}
}

BITS Pilani, Pilani Campus


Review

To perform interactive I/O using dialog boxes

1. import javax.swing.*;
2. Use an input dialog box to prompt the user to enter data (returns a String)
String inString = JOptionPane.showInputDialog(“your message”);
3. Use a StringTokenizer (if necessary) to extract the individual tokens
from the input String
4. Convert (String) tokens into primitive types wherever necessary using
the appropriate wrapper class.
5. Use a dialog box to display the output
JOptionPane.showMessageDialog(null,”message”, “title”, icon-type):
6. When using a Message dialog box, end the program with
System.exit(0);

BITS Pilani, Pilani Campus


THANK YOU

BITS Pilani, Pilani Campus


BITS Pilani
Pilani Campus

Object Oriented Programming


Interfaces
Interfaces

• Interface is a conceptual entity similar to a Abstract


class.
• Can contain only constants (final variables) and
abstract method (no implementation) - Different
from Abstract classes.
• Use when a number of classes share a common
interface.
• Each class should implement the interface.

BITS Pilani, Pilani Campus


Interfaces: An informal way of realizing
multiple inheritance

• An interface is basically a kind of class—it contains methods


and variables, but they have to be only abstract classes and
final fields/variables.
• Therefore, it is the responsibility of the class that
implements an interface to supply the code for methods.
• A class can implement any number of interfaces, but cannot
extend more than one class at a time.
• Therefore, interfaces are considered as an informal way of
realizing multiple inheritance in Java.

BITS Pilani, Pilani Campus


Interface - Example

<<Interface>>
Speaker
speak()

Politician Priest Lecturer


speak() speak() speak()

BITS Pilani, Pilani Campus


Interfaces Definition

• Syntax (appears like abstract class):


interface InterfaceName {
// Constant/Final Variable Declaration
// Methods Declaration – only method
body
• }Example:
interface Speaker {
public void speak( );
}

BITS Pilani, Pilani Campus


Implementing Interfaces

• Interfaces are used like super-classes who


properties are inherited by classes. This is
achieved by creating a class that implements
the given interface as follows:
class ClassName implements InterfaceName, InterfaceName2,…{
// Body of Class
}

BITS Pilani, Pilani Campus


Implementing Interfaces Example
class Politician implements Speaker {
public void speak(){
System.out.println(“Talk politics”);
}
}

class Priest implements Speaker {


public void speak(){
System.out.println(“Religious Talks”);
}
}

class Lecturer implements Speaker {


public void speak(){
System.out.println(“Talks Object
Oriented Design and Programming!”);
}
}

BITS Pilani, Pilani Campus


Extending Interfaces

• Like classes, interfaces can also be extended. The


new sub-interface will inherit all the members of the
superinterface in the manner similar to classes. This
is achieved by using the keyword extends as follows:

interface InterfaceName2 extends InterfaceName1{


// Body of InterfaceName2
}

BITS Pilani, Pilani Campus


Interfaces and Software Engineering
• Interfaces, like abstract classes and methods, provide
templates of behaviour that other classes are expected to
implement.
• Separates out a design hierarchy from implementation
hierarchy. This allows software designers to enforce/pass
common/standard syntax for programmers implementing
different classes.
• Pass method descriptions, not implementation
• Java allows for inheritance from only a single superclass.
Interfaces allow for class mixing.
• Classes implement interfaces.

BITS Pilani, Pilani Campus


THANK YOU

BITS Pilani, Pilani Campus


BITS Pilani
Pilani Campus

Object Oriented Programming


Comparable & Comparator Interfaces
Comparable Interface
1. Provides an interface for comparing any two objects of same class.
2. General Form : public interface Comparable<T> {
public interface Comparable { int compareTo(<T> other );
int compareTo(Object other ); }
}

Note : other parameter should be type casted to the class type


implementing Comparable interface

3. Collections.sort() method can sort objects of any class that


implements comparable interface.

4. By implementing this interface , programmers can implement the


logic for comparing two objects of same class for less than,
greater than or equal to.

BITS Pilani, Pilani Campus


Examples for Implementation
class BOX Implements class Student Implements
Comparable{ Comparable{
……………………………………… ………………………………………
……………………………………… ………………………………………
……………………………………… ………………………………………
public int compareTo(Object other){ public int compareTo(Object other){
BOX box = (BOX) other; Student std = (Student) other;
......Logic for comparison …. ......Logic for comparison ….
} }
…………………………………. ………………………………….
} }

BITS Pilani, Pilani Campus


Examples for Implementation
class BOX Implements Comparable<BOX> class Student Implements Comparable<Student>
{ {
……………………………………… ………………………………………
……………………………………… ………………………………………
……………………………………… ………………………………………

public int compareTo(BOX other) public int compareTo(Student other)


{ {
......Logic for comparison …. ......Logic for comparison ….
} }
…………………………………. ………………………………….
} }

BITS Pilani, Pilani Campus


Examples
class BOX implements Comparable {
private double length;
private double width; Unparametrized Comparable
private double height;
BOX(double l, double b, double h) {
length=l;width=b;height=h;
}

public double getLength() { return length;}


public double getWidth() { return width;}
public double getHeight() { return height;}

public double getArea(){


return 2*(length*width + width*height+height*length);
}
public double getVolume(){
return length*width*height;
}

BITS Pilani, Pilani Campus


public int compareTo(Object other){

BOX b1 =(BOX) other;

if(this.getVolume() > b1.getVolume())


return 1;
if(this.getVolume() < b1.getVolume())
return -1;
return 0;
}

public String toString(){


return “Length:”+length+ “ Width :”+width
+ “ Height :”+height;
}
} // End of BOX class
BITS Pilani, Pilani Campus
import java.util.*; Import java.util.*;
class ComparableTest { class ComparableTest{
public static void main(String[] args){ public static void main(String[] args){
BOX[] box = new BOX[5]; ArrayList boxLst = new ArrayList();
box[0] = new BOX(10,8,6); boxLst.add( new BOX(10,8,6));
box[1] = new BOX(5,10,5); boxLst.add( new BOX(5,10,5));
box[2] = new BOX(8,8,8); boxLst.add( new BOX(8,8,8));
box[3] = new BOX(10,20,30); boxLst.add( new BOX(10,20,30));
box[4] = new BOX(1,2,3); boxLst.add( new BOX(1,2,3));
Arrays.sort(box); Collections.sort(box);
for(int i=0;i<box.length;i++) Iterator itr = boxLst.iterator();
System.out.println(box[i]); while(itr.hasNext()) {
} BOX b =(BOX) itr.next();
} // End of class System.out.println(b);
}
}//End of main
}// End of class

BITS Pilani, Pilani Campus


Problems With Comparable Interface

• Method int compareTo(Object obj) needs to


be included in the base class itself.
• We can include only single ordering logic.
• Different order requires logic to be included
and requires changes in the base class itself.
• Each type we need different order we need to
change the code itself.

BITS Pilani, Pilani Campus


import java.util.*;
class Student implements Comparable{
private String name;
private String idno;
Student[] students = new Student[10];
private int age;
……………………………
private String city;
…………………………
……………………..
Arrays.sort(students);
……………………… for(int i=0 ; i<students.length;i++)
public int compareTo(Object other) System.out.println(students[i]);
{
Student std = (Student) other;
return this.name.compareTo(other.name); Comparison
}
public String toString(){ by Name
Return “Name:”+name+”Id
No:”+idno+”Age:”+age; OUTPUT List sorted by
}
} // End of class Name

BITS Pilani, Pilani Campus


import java.util.*;
class Student implements Comparable
{
private String name; Student[] students = new Student[10];
private String idno; ……………………………
private int age; …………………………
private String city; Arrays.sort(students);
…………………….. for(int i=0 ; i<students.length;i++)
……………………… System.out.println(students[i]);
public int compareTo(Object other)
{
Student std = (Student) other;
return this.idno.compareTo(other.idno); Comparison
} by idno
public String toString(){
Return “Name:”+name+”Id OUTPUT List sorted by
No:”+idno+”Age:”+age;
} IdNo
} // End of class

BITS Pilani, Pilani Campus


Comparator Interface
• Allows two objects to compare explicitly.
• Syntax :
public interface Comparator{ Unparametrized Comparator
int compare(Object O1, Object O2);
}
public interface Comparator<T>{ Parametrized Comparator
int compare(T O1, T O2);
}

• Does not require change in the base class.


• We can define as many comparator classes for the base class.
• Each Comparator class implements Comparator interface and provides
different logic for comparisons of objects.
• But as we are passing both parameters explicitly, we have to type cast
both Object types to their base type before implementing the logic OR
Use the second form

BITS Pilani, Pilani Campus


Student Comparator

class Student{
private String name;
private String idNo;
private int age; StudentByName StudentByIdNo StudentByAge

private String city;


…………………..
………………….. StudentByNameIdNo StudentByNameAge

BITS Pilani, Pilani Campus


class StudentByName implements Comparator {
public int compare(Object o1,Object o2){
Student s1 = (Student) o1;
Student s2 = (Student) o2;
return s1.getName().compareTo(s2.getName());
}
}
class StudentByIdNo implements Comparator{
public int compare(Object o1,Object o2){
Student s1 = (Student) o1;
Student s2 = (Student) o2;
return s1.getIdNo().compareTo(s2.getIdNo());
}
}

BITS Pilani, Pilani Campus


class StudentByAge implements Comparator{
public int compare(Object o1,Object o2){
Student s1 = (Student) o1;
Student s2 = (Student) o2;
if( s1.getAge() > s2.getAge() ) return 1;
if( s1.getAge() < s2.getAge() ) return -1;
return 0;
}
}

class StudentByNameIdNo implements Comparator{


public int compare(Object o1,Object o2){
Student s1 = (Student) o1;
Student s2 = (Student) o2;
if( s1.getName().compareTo(s2.getName()) == 0)
return s1.getIdNo().compareTo(s2.getIdNo());
else
return s1.getName().compareTo(s2.getName());
}
}
BITS Pilani, Pilani Campus
class StudentByNameAge implements Comparator{
public int compare(Object o1,Object o2){
Student s1 = (Student) o1;
Student s2 = (Student) o2;
if( s1.getName().compareTo(s2.getName()) == 0)
return s1.getAge() – s2.getAge();
else
return s1.getName().compareTo(s2.getName());
}
}

BITS Pilani, Pilani Campus


Import java.util.*;
class ComparatorTest{

public static void main(String args[]){


Student[] students = new Student[5];
Student[0] = new Student(“John”,”2000A1Ps234”,23,”Pilani”);
Student[1] = new Student(“Meera”,”2001A1Ps234”,23,”Pilani”);
Student[2] = new Student(“Kamal”,”2001A1Ps344”,23,”Pilani”);
Student[3] = new Student(“Ram”,”2000A2Ps644”,23,”Pilani”);
Student[4] = new Student(“Sham”,”2000A7Ps543”,23,”Pilani”);

// Sort By Name
Comparator c1 = new StudentByName();
Arrays.sort(students,c1);

for(int i=0;i<students.length;i++)
System.out.println(students[i]);

BITS Pilani, Pilani Campus


// Sort By Idno // Sort by Name & Age
c1 = new StudentByIdNo(); c1 = new StudentByNameAge();
Arrays.sort(students,c1); Arrays.sort(students,c1);
for(int i=0;i<students.length;i++) for(int i=0;i<students.length;i++)
System.out.println(students[i]); System.out.println(students[i]);
} // End of Main
// Sort By Age } // End of test class.
c1 = new StudentByAge();
Arrays.sort(students,c1);
for(int i=0;i<students.length;i++)
System.out.println(students[i]);

// Sort by Name & Idno


c1 = new StudentByNameIdNo();
Arrays.sort(students,c1);
for(int i=0;i<students.length;i++)
System.out.println(students[i]);
BITS Pilani, Pilani Campus
THANK YOU

BITS Pilani, Pilani Campus

You might also like