0% found this document useful (0 votes)
4 views

UNIT I OOPS with Java

The document provides comprehensive lecture notes on Object Oriented Programming with Java, covering its history, features, and execution process. It explains Java's platform independence, the role of the Java Virtual Machine (JVM), and the evolution of Java versions. Additionally, it compares Java with C and C++, highlighting its object-oriented principles and contributions to web programming.
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)
4 views

UNIT I OOPS with Java

The document provides comprehensive lecture notes on Object Oriented Programming with Java, covering its history, features, and execution process. It explains Java's platform independence, the role of the Java Virtual Machine (JVM), and the evolution of Java versions. Additionally, it compares Java with C and C++, highlighting its object-oriented principles and contributions to web programming.
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/ 116

DEPARTMENT OF COMPUTER SCIENCE

AND ENGINEERING

LECTURE

NOTES ON

Object Oriented Programming with


JAVA

II B.TECH IV SEMESTER
(BCS-403)
1

Object Oriented Programming with JAVA

UNIT I

The History and Evolution of Java

What is Java

1. Java technology is both a programming language and a platform.


2. Java is a high level, robust, secured and object-oriented programming language.

Java programming language:

The Java programming language is a high-level and object-oriented language thatcan be


characterized by all of the following buzzwords / features:

i) Simple vii) Portable


ii) Object oriented viii) Interpreted
iii) Distributed ix) High Performance
iv) Multithreaded x) Robust
v) Dynamic xi) Secure
vi) Architecture Neutral

Java Platform:

Any hardware or software environment in which a program runs is known as a platform. Since
Java has its own runtime environment (JRE-Java Runtime Environment) and API, itis called
platform.

The Java platform has two components – API and Java Virtual Machine

The Java Virtual Machine :

It is an abstract machine and it is the base for the


Java platform and is ported onto various hardware-
based platforms.

The Java Application Programming Interface (API) :

The API is a large collection of ready-made software


components that provide many useful capabilities. It
is grouped into libraries of related classes and
interfaces; these libraries are known as packages.
2

The Creation of Java

Java was originally developed to develop a language for digital devices such as set-topboxes
and consumer electronic devices such as microwave ovens and remote controls.

Java was developed by James Gosling, Patrick Naughton, Mike Sheridan at Sun
Microsystems Inc. in 1991. It took 18 months to develop the first working version.

The initial name was Oak but it was renamed to Java in 1995.

Primary Motivation(s) for Java creation:

1. The primary motivation was the need for a platform-independent (architecture-


neutral/portable) language that could be used to create software to be embedded in
various consumer electronic devices, such as microwave ovens and remote controls.

2. The second important factor is the World Wide Web / Internet.

a) Java is used to develop web based programs / Internet programming.


b) The Internet consists of a diverse, distributed universe populated with varioustypes
of computers, operating systems, and CPUs.

Platform Independence or Architecture Neutral or Portable:

(Write Once, Run Anywhere)

a) Java is a Platform Independent language. Java sometimes called as “Write Once,Run


Anywhere (WORA)” language.
b) Java achieves platform independence through bytecode and JVM.

Java Program Execution:

1. In the Java programming language, all source code is first written in plain text files
ending with the .java extension.
3

2. Those source files are then compiled into .class files by the javac compiler.
3. A .class file does not contain code that is native to your processor; it instead contains
bytecodes — the machine language of the Java Virtual Machine (JavaVM).
4. The java launcher tool then runs your application with an instance of the Java Virtual
Machine.
5. Through the JVM, the same application is capable of running on multiple platforms.

Bytecode:

Bytecode is a highly optimized set of


instructions designed to be executed
by the Java run-time system, which is
called the Java Virtual Machine (JVM).

Java is platform independent but


JVM is platform dependent:

JVM is platform independent because


JVM is designed to each platform
separately.

Java’s magic: bytecode

1) Translating a Java program into bytecode makes it much easier to run a program ina wide
variety of environments because only the JVM needs to be implemented for each
platform.
2) Although the details of the JVM will differ from platform to platform, all understand
the same Java bytecode.
3) A Java program is executed by the JVM also helps to make it secure. Because theJVM
is in control, it can contain the program and prevent it from generating side effects
outside of the system.
4

Java’s Lineage (Ancestry or pedigree)

Java is related to C++, which is a direct descendant of C.

➢ Much of the character of Java is inherited from these two languages.

➢ From C, Java derives its syntax.

➢ Many of Java’s object oriented features were influenced by C++.

Java vs C vs C++

Aspects C C++ Java


Developed Year 1972 1979 1991
Developed By Dennis Ritchie Bjarne Stroustrup James Gosling
Paradigms Procedural Object Oriented Object Oriented
Platform Dependent Dependent Independent
Dependency
Header files Supported Supported Use Packages
(import)
Pointers Supported Supported No Pointers
Storage Allocation Uses malloc, calloc Uses new , delete uses garbage
collector

Multi-threading Not Supported Not Supported Supported


Exception Handling No Exception Supported Supported
handling
Destructors No Constructor or Supported Not Supported
Destructor
Inheritance No Inheritance Supported Supported except
Multiple Inheritance
Overloading No Overloading Supported Operator
Overloading not
Supported

C compile time vs Java Compile Time


5
6

How Java changed the Internet / Java’s contribution to the Internet


Servlets : Java on the Server Side

The Internet helped Java to the forefront of programming and Java, in turn, had a profound
effect on the Internet.

Java helped in the following features:

a) Simplified web programming


b) Applet development
c) Addressed the issues with the Internet : portability and security

a) Simplified Web programming

i. Java is used in client / server programming. Servlet is used in this


programming.
ii. A servlet is a small program that executes on the server.
iii. Servlets are used to create dynamically generated content that is then
served to the client.
7

iv. Because servlets (like all Java programs) are compiled into bytecode and
executed by the JVM, they are highly portable.
v. Example: Online Store

b) Applets

i. An applet is a special kind of Java program that is designed to be transmittedover


the Internet and automatically executed by a Java-compatible web browser.
ii. The creation of the applet changed Internet programming because it expanded
the universe of objects that can move about freely in cyberspace.
iii. The applet is a dynamic, self-executing program.

c) Portability and Security issues

i. Portability is a major aspect of the Internet because there are many different
types of computers and operating systems connected to it.
a. The Bytecode and JVM made Java code to be portable.
ii. Security
a. Java achieved the security by confining internet based programs
(applet) to the Java execution environment (JRE) and not allowing it
access to other parts of the computer.
b. Java programs will be executed within JVM so, security is preserved
from virus attacks.

JAVA Features
The prime reason behind creation of Java was to bring portability and security feature into a
computer language. Beside these two major features, there were many other features thatplayed an
important role in Java language creation. Those features are:

1. Simple:

a) Java is easy to learn and its syntax is quite simple, clean and easy to understand.
b) It is simple because, Syntax is based on C and C++.
c) Java removed pointers and operator overloading concepts.

2. Object oriented:

a) In Java, everything is an object which has some data and behavior.


b) The object model in Java is simple and easy to extend, while primitive types, such as
integers, are kept as high-performance non-objects.
c) Java supports all the OOP features:
8

i. Class
ii. Object
iii. Encapsulation
iv. Inheritance
v. Polymorphism
vi. Abstraction
3. Distributed: Java is designed for the distributed environment of the Internet because it
handles TCP/IP protocols. Java has features that enables a program to invoke methods across
a network.

4. Multithreaded: With java’s multi-threaded feature it is possible to write programs that


can do many tasks simultaneously. This design feature allows developers to construct
smoothly running interactive applications. Benefit of multithreading is that it utilizes same
memory and other resources to execute multiple threads at the same time.

5. Dynamic: Java programs carry with them substantial amounts of run-time type information
that is used to verify and resolve accesses to objects at run time. This makes itpossible to
dynamically link code in a safe and expedient manner. This is crucial to the robustness of the
Java environment, in which small fragments of bytecode may be dynamically updated on a
running system.

6. Architecture Neutral (Platform Independent):

i. C and C++ are platform dependency languages, But Java is platform independent
language.
ii. Java designers goal was “Write once; run anywhere, any time, forever”(WORA).
Java programs written in one operating system can able to run on any operating system.
iii. Java compiler generates an architecture-neutral bytecode which makes the compiledcode
to be executable on many processors with the presence of Java run time system (JVM).

7. Portable: Java is a portable language means, we can carry the same Java bytecode toany
platform.
9

8. Interpreted: Java’s bytecode is interpreted by Java Virtual Machine (JVM). Java’s


bytecode was carefully designed so that it will be easily translated into Native code.

9. High Performance: Java is faster than traditional interpretation since byte code was
carefully designed so that it would be easy to translate directly into native machine code forvery
high performance by using a just-in-time compiler (JIT).

10. Robust: The ability to create robust programs was given a high priority in the designof
Java.
Some of the reasons for Java is called as a robust language:
i. Strongly Typed Language
a. Java checks the code at compile time.
ii. Automatic Memory Management (Garbage collection)
a. In C/C++, the programmer will manually allocate and free all dynamic
memory. This sometimes leads to problems, because programmer will
forget to free the memory.
b. In Java, memory de-allocation is done automatically through Garbage
Collection.
iii. Error Handling
a. Java provides object-oriented exception handling to handle the errors injava
program.
b. Using exception handling, all run time errors should be managed by the
program.
11. Secure: Java is secured because:

i. No explicit pointers.
ii. Java Programs run inside virtual machine environment.
10

Evolution of Java

Java continued to evolve at an explosive pace.


It has dynamic history. Since the beginning, Java has been at the center of a culture of
innovation.
Java Version Release History

Version Description / Features / Enhancements


Java 1.0 / JDK1.0 Initial Version Release
Java1.1/ JDK 1.1 Added AWT,JDBC,RMI,Javabeans etc
Java 2 / J2SE 1.2 Swings,Collection framework, JIT compiler in JVM
(Java 2 Standard
Edition)
J2SE 1.3 Smaller set of changes added to the existing functionality
J2SE 1.4 ASSERT keyword,Chained exceptions, Regular Expressions,Image
I/O API for reading and writing images
J2SE 5 Generics, Annotations,Autoboxing and auto-unboxing, Enumerations,
Enhanced for loop, Variable-length arguments(varargs),static import,
Formatted I/O,Concurrency utilities.
Java SE 6 (Java Synchroization and compiler performance optimizations, Garbage
Platform Standard collection algorithms
Edition)
Java SE 7 / JDK 7 Try-with-resources,Type interface, Underscores in numeric
literals,Binary integer literals, A String can control a Switch
statement, Parallel programming, Multi Catch Exception
Java SE 8 / JDK 8 New feature – lambda expression, java.util.stream, Enhanced
Security

Java Conceptual Diagram


Below is the High-level conceptual diagram of Java language.
11

JRE (Java Runtime Environment)


The Java Runtime Environment (JRE) provides
1) the libraries,

2) the Java Virtual Machine,

3) and other components to run applets and applications written in the Java
programming language.
4) In addition, two key deployment technologies are part of the JRE:

▪ Java Plug-in : It enables applets to run in popular browsers;


▪ Java Web Start : It deploys standalone applications over a network.
5) The JRE does not contain compilers or debuggers for developing applets and
applications.

JRE = The Libraries + JVM + Java Plug-in + Java Web Start + Other components

JDK (Java Development Kit)


1) The JDK is a superset of the JRE,
2) and contains everything that is in the JRE, plus tools such as the compilers and
debuggers necessary for developing applets and applications.
JDK = JRE + compilers + debuggers + etc.
12

JVM (Java Virtual Machine)


1) JVM is an Interpreter for bytecode.

2) The Java virtual machine is an abstract computing machine that has an instructionset
and manipulates memory at run time.
3) The Java Virtual Machine is responsible for the hardware- and operating system-
independence of the Java SE platform, the small size of compiled code (bytecodes),and
platform security.
4) JVM includes dynamic compilers – Just In Time Compilers (JIT) that adaptively
compile Java bytecodes into optimized machine instructions.

Internal Architecture of the JVM


13

1. class loader subsystem: a mechanism for loading types (classes and interfaces)

2. Execution engine: a mechanism responsible for executing the instructions


contained in the methods of loaded classes.

3. Run Time Data areas: The Virtual machine organizes the memory it needs to
execute a program into several runtime data areas.
i. Method area: All the class data has been placed on to the method area.
ii. Heap: All objects the program instantiates is placed onto the heap.
iii. Java Stacks: A Java stack stores the state of Java (not native) method
invocations for the thread.
iv. PC registers: The value of the pc register indicates the next instruction to
execute.
v. Native Method stacks: Native methods are the methods written in a language
other than the Java programming language. These are the stackscreated for
other languages functions or operating system functions.

JIT (Just-In-Time Compiler)


1) Java is an interpreted language, so it is considered as a slow language when
compared with compiled languages.
2) But Hot-spot technology of Java was introduced to boost performance of the Java
language.
3) HotSpot provides a Just-In-Time (JIT) compiler for bytecode.
4) When a JIT compiler is part of the JVM, selected portions of bytecode are compiledinto
executable code in real time, on a piece-by-piece, demand basis.
5) Not all sequences of bytecode are compiled—only those that will benefit from
compilation.
6) The remaining code is simply interpreted.
7) The just-in-time approach still yields a significant performance boost.

Object Oriented Programming (OOP)


Programming Paradigms
There are two ways of writing programs:

1) Process oriented model (Procedure oriented programming)


2) Object oriented programming
14

Process oriented model OOP

Organizes a program around its code. Organizes a program around its data (that is, objects).

A program is written as a series of linear A program is written as a collection of classes and


steps. objects

Program contains procedures. Program contains classes, objects.

Ex: C uses this approach Ex: Java uses this approach.

Procedure oriented model Object oriented model

OOP principles / components

Definition: OOP is a programming methodology that helps organize complex programs


through the use of inheritance, encapsulation, and polymorphism.
Components:
1. Classes
2. Objects
3. Abstraction
15

4. Encapsulation (Data Encapsulation)


5. Inheritance
6. Polymorphism
7. Access Levels
8. Interfaces
9. Packages

Three OOP Principles

1. Encapsulation
2. Inheritance
3. Polymorphism

Class: A class defines the structure and behavior (data and code) that will be shared by aset of
objects. A class is a structure that defines the data and the methods (functions in other
languages) to work on that data.

In Java, all program data is wrapped in a class.

import java.lang.System;
class ExampleProgram
{
public static void main(String[] args)
{
System.out.println(“Hello World");
}
}

Object: An instance of a class is called as an Object.

1) There can be any number of objects of a given class in memory at any one time.
2) Software objects are conceptually similar to real-world objects.
3) Objects consist of state and behavior.
4) An object stores its state in fields (variables in some programming languages) and
exposes its behavior through methods (functions in some programming languages).
16

A software object A bicycle modeled as a software object

Abstraction:

a) An essential element of object-oriented programming is abstraction.


b) Abstraction is defined as hiding the complexities of the system.
c) A powerful way to manage abstraction is through the use of hierarchical
abstractions (classifications).
d) Humans manage complexity through abstraction.
e) For example, people do not think of a car as a set of tens of thousands of individual
parts. They think of it as a well-defined object with its own unique behavior.

Hierarchical classifications

CAR
17

Three OOP Principles

1. Encapsulation:

Encapsulation is the mechanism that binds together code and the data it manipulates,and
keeps both safe from outside interference and misuse.

i. Encapsulation is sometimes called as Information hiding.


ii. In Java, the basis of encapsulation is the class.
iii. Using Access Modifiers (private, public,protected,default), the members of theclass
can be protected from misuse by the outside classes.
iv. private members can only accessed by the members of the class.
v. public members can be accessed by any members of the class or outside membersof the
class.
vi. Programs should interact with object data only through the object’s methods.
vii. Benefits of Encapsulation are: reuse and reliability.

Example:
18

2. Inheritance:

Inheritance is the process by which one object acquires the properties of another object.

i. Inheritance defines relationships among classes in an object-oriented language.


ii. Inheritance allows classes to inherit commonly used state and behavior from other
classes.
iii. It supports the concept of hierarchical classification.
iv. Benefits are : Code reuse and Decrease of Program size
v. In the Java programming language, all classes descend from java.lang.Object, thatis,
Object is the superclass for all classes.

Example:
a) Different kinds of objects often have a certain amount in common with each other.
Mountain bikes, road bikes, and tandem bikes, for example, all share the
characteristics of bicycles (current speed, current pedal cadence, current gear).

b) Yet each also defines additional features that make them different: tandem bicycles have
two seats and two sets of handlebars; road bikes have drop handlebars; somemountain
bikes have an additional chain ring, giving them a lower gear ratio.
19

Syntax for creating subclasses:

The syntax for creating a subclass is simple. At the beginning of your class declaration, usethe
extends keyword, followed by the name of the class to inherit from:

class MountainBike extends Bicycle { Also contains the same fields and
methods as Superclass Bicycle,
// new fields and methods defining but that code will not appear.
// a mountain bike would go here

Subclass = Same attributes of super class + any attributes of subclass

➢ In the Java programming language, each class is allowed to have one direct
superclass, and each superclass has the potential for an unlimited number of
subclasses.

3. Polymorphism: Polymorphism in Greek, meaning “many forms”.

Definition:
Polymorphism in java is a concept by which we can perform a single action by
different ways.

a) In JAVA, More generally, the concept of polymorphism is often expressed by the


phrase “one interface, multiple methods.”
b) We can perform polymorphism in java by method overloading and method
overriding.

Types of Polymorphism:

There are two types of polymorphism in java:


1. Compile time polymorphism and
2. Runtime polymorphism.

Example

i. You might have a program that requires three types of stacks.


ii. One stack is used for integer values, one for floating point values, and one for
characters.
iii. The algorithm that implements each stack is the same, even though the databeing
stored differs.
iv. In a non–object-oriented language, you would be required to create three
different sets of stack routines, with each set using different names.
20

v. However, because of polymorphism, in Java you can specify a general set ofstack
routines that all share the same names.

FIRST JAVA Program - Description

/* This is a simple Java program. This is called as


Call this file "Hello.java". Multi Line Comment
*/
class Hello { This is called as
// this is main method Single Line Comment
public static void main(String args[])
{
System.out.println(“Hello”);
}

class : class keyword is used to declare classes in Java.


public : It is an access specifier. Public means this function is visible to all.
static : static is again a keyword used to make a function static. To execute a static functionyou do
not have to create an Object of the class. The main() method here is called by JVM,without
creating any object for class.
void : It is the return type, meaning this function will not return anything.
main : main() method is the most important method in a Java program. This is the method
which is executed, hence all the logic must be inside the main() method. If a java class is not
having a main() method, it causes compilation error.
System.out.println: This is used to print anything on the console like printf in C language.

Steps to Compile and Run our first Java program

Step 1: Open a text editor and write the code as above.


Step 2: Save the file as Hello.java
Step 3: Open command prompt and go to the directory where you saved your first java
program assuming it is saved in D:\
Step 4: Type javac Hello.java and press Enter to compile your code.
D:\>javac Hello.java
21

This command will call the Java Compiler asking it to compile the specified file. If there areno
errors in the code the command prompt will take you to the next line.
Step 5: Now type java Hello on command prompt to run your program.
D:\>java Hello
Step 6: You will be able to see Hello printed on your command prompt.

Code blocks (or) blocks of code

i. Java allows two or more statements to be grouped into blocks of code, also called
code blocks.
ii. Code blocks can be created by enclosing the statements between opening andclosing
curly braces.
iii. Once a block of code has been created, it becomes a logical unit that can be usedany
place that a single statement can.

Example:

/* Demonstrate a block of code.


Call this file "BlockTest.java"
*/

class BlockTest {
public static void main(String args[]) {
if(x < y) If X is less than Y then both
{ // begin a block statements inside the block
x = y; will be executed.
y = 0;
} // end of block
22

}
}

Lexical Issues (or) Atomic Elements of Java

Java programs are a collection of –


1) whitespace
2) identifiers
3) literals
4) comments
5) operators
6) separators and
7) keywords

whitespace
a) Java is a free-form language – do not need to follow any indentation rules.
b) In Java, whitespace is a space, tab, or newline.

Identifiers
a) Identifiers are used to name classes, variables, and methods.
b) An identifier may be any descriptive sequence of uppercase and lowercase letters,
numbers, or the underscore and dollar-sign characters.
c) Java is case-sensitive language.

Valid Identifiers: Invalid Identifiers

AvgTemp 2count
Count high-temp
A4 Not/ok
$test
This_is_ok

Literals

A constant value in Java is created by using a literal representation of it.

Example:

integer literal 100


floating-point literal 98.6
character literal ‘X’
String literal “This is a test”
23

Integer Literals

3 bases are used to represent integer literals –


1) Decimal (base 10)
Ex: 1, 2, 3 and 42

2) Octal (base 8) - denoted by a leading zero


Ex: 05

3) Hexadecimal (base 16) - denoted by a leading zero-x (0x or 0X)Ex:


ox7f

Floating-point Literals

1) Represented in –
a) Standard notation -> 2.0, 3.14
b) Scientific notation -> 6.022E23, 314159E-05
2) Floating point literals in Java default to double precision.
3) To specify a float literal, we must append an F or f to the constant.
4) Hexadecimal floating point literals are also supported.
Ex: 0x12.2P2

Boolean Literals

It contains only two logical values - true or false. These values do not convert into any
numerical representation.

Character Literal
1) A literal character is represented inside a pair of single quotes.
2) All of the visible characters can be directly entered inside the quotes, such as 'a', 'z',and
'@'.
3) For characters that are impossible to enter directly, there are several escape
sequences.
Ex: ‘\’’ for single-quote character
‘\n’ for the new line character
4) Characters can be represented in Octal and Hexadecimal notation
Octal
backslash followed by the three-digit number. For example, ' \141' is the letter 'a'.
Hexadecimal
a backslash-u ( \u), then exactly four hexadecimal digits. For example, ' \u0061'
24

Escape Sequence Description


\ddd Octal character (ddd)
\uxxxx Hexadecimal Unicode character (xxxx)
\' Single quote
\" Double quote
\\ Backslash
\r Carriage return
\n New line (also known as line feed)
\f Form feed
\t Tab
\b Backspace

String Literal

String literals in Java are specified by enclosing a sequence of characters between a pair ofdouble
quotes.

Example:

"Hello
World"
"two\nlines"
" \"This is in quotes\""

Comments

There are 3 types of comments defined by Java.

1) Single-line comments starts with //

Example: // Test program

2) Multi-line comments begins with /* and ends with */

Example : /* Program for Multiplication


*/

3) Documentation comment begins with a /** and ends with a */

Example : /**
First Java Program
*/

Separators

In Java, there are a few characters that are used as separators.


25

Symbol Name Purpose


() Parentheses Used in method parameters, expressions, casting
{} Braces Array initializer, block of code, classes and methods
[] Brackets Declare array types and used when dereferencing array
values
; Semicolon Terminates statements.
, Comma Variable declarations, inside a for statement
. Period Used to separate package names from subpackages and
classes. Also used to separate a variable or method from a
reference variable.
.. Colons Used to create a method or constructor reference. (Added by
.. JDK 8.)

The Java Keywords

Keywords are the reserved words which can not be used as identifiers in program.

i. There are 50 keywords currently defined in the Java language.


ii. The keywords const and goto are reserved but not used.
iii. true, false, and null are also reserved. These are the values defined by Java. Wemay
not use these words for the names of variables, classes, and so on.

abstract continue for new switch


Assert default Goto package synchronized
Boolean do If private this
Break double implements protected throw
Byte else import public throws
Case enum instanceof return transient
Catch extends Int short try
Char final interface static void
Class finally Long strictfp volatile
Const float native super while

The Java class Libraries (API)

1) Java class libraries provide much of the functionality that comes with Java.
2) Java language is a combination of the Java language itself, plus its standard
classes.
26

3) Java environment relies on several built-in class libraries that contain many built-in
methods that provide support for Input / Output, String handling, networking, graphics
and Graphical User Interface (GUI).
4) Java has very rich and large Application Programming Interface (API) content.

Example:

println() and print() methods are built-in methods and available through System.out.

System is a predefined class and out is an output stream associated with system.

Data Types, Arrays and Variables

Data Types

Java is a Strongly Typed Language -

a) Every variable has a type, every expression has a type, and every type is strictly
defined.
b) All assignments, whether explicit or via parameter passing in method calls, are
checked for type compatibility.
c) There are no automatic conversions of conflicting types as in some languages.
d) The Java compiler checks all expressions and parameters to ensure that the typesare
compatible.
27

Primitive Data Types and Ranges

1) Primitive types are also called as Simple types. The primitive types represent single
values.

2) A primitive can be one of eight types:

char, boolean, byte, short, int, long, double, or float.

2) Primitive variables can be declared as class variables (static), instance variables,


method parameters, or local variables.

byte b;

boolean myBooleanPrimitive;

int x, y, z; // declare three int primitives

3) The number types (both integer and floating point types) are all signed, meaning they canbe
negative or positive.

4) The leftmost bit (the most significant digit) is used to represent the sign, where a 1 means
negative and 0 means positive. The rest of the bits represent the value, using two's complement
notation.

Type Bits Bytes Minimum Range Maximum Range

byte 8 1 -128 (- 27) 127 (27-1)

short 16 2 -32768 (-215) 32767 (215-1)

int 32 4 -231 231-1

long 64 8 -263 263-1

float 32 4 4.9e–324 1.8e+308

double 64 8 1.4e–045 3.4e+038

char 16 2 0 65535
28

boolean: The boolean data type has only two possible values: true and false.

Characters (char)

a) In Java, the data type used to store characters is char.


b) char in Java is not the same as char in C or C++. In C/C++, char is 8 bits wide. In
Java, char is 16 bit.
c) Java uses Unicode to represent characters. Unicode defines a fully international
character set that can represent all of the characters found in all human languages.
d) At the time of Java's creation, Unicode required 16 bits. Thus, in Java char is a 16-bit
type. The range of a char is 0 to 65,536. There are no negative chars.

Example

Example for char data type

// Demonstrate char data type.

class CharDemo
{ Output:
public static void main(String args[]) {
char ch1, ch2; ch1 and ch2 : X Y
ch1 = 88; // code for X
ch2 = 'Y';
System.out.print("ch1 and ch2: ");
System.out.println(ch1 + " " + ch2);
}
}

// char variables behave like integers.


class CharDemo2
{ Output:
public static void main(String args[])
{ ch1 contains X
char ch1;
ch1 is now Y
ch1 = 'X';
System.out.println("ch1 contains " + ch1);

ch1++; // increment ch1


System.out.println("ch1 is now " + ch1);
}
}
29

Example for double data type

// Compute the area of a circle.


class Area { Output:
public static void main(String args[]) {
double pi, r, a; Area of circle is
r = 10.8; // radius of circle 366.436224
pi = 3.1416; // pi, approximatelya
= pi * r * r; // compute area

System.out.println ("Area of circle is ” + a);


}
}

Example for boolean data type

// Demonstrate boolean values.


class BoolTest {
public static void main(String args[]) {
boolean b;
Output:
b = false; b is false
System.out.println("b is " + b);
b = true; System.out.println("b b is true
is " + b);
This is executed.
// a boolean value can control the if statement 10 > 9 is true
if(b)
System.out.println("This is executed.");b
= false;
if(b) System.out.println("This is not executed.");

// outcome of a relational operator is a boolean value


System.out.println("10 > 9 is " + (10 > 9));
}
}

Reference Types

reference

1) A reference variable is used to refer to (or access) an object.


2) Class types, array types and interface types are called as references.
30

3) Reference variables can be declared as static variables, instance variables, method


parameters, or local variables.

Object o;
Pen p1;
String s1, s2, s3; // declare three String vars.

Example

class A
{
int i;
void m1() {
System.out.println(“Hello”);
}

class Test
{
public static void main(String args[])
{
A obj; // reference
obj = new A(); // object
}
}

Variables

Variables are the identifiers of the memory location, which used to store the data temporaryfor
later use.

Declaring a Variable:

a) In Java, all variables must be declared before they can be used.


b) The basic form of a variable declaration is shown here:

type identifier [ = value ][, identifier [= value ] …];

Here, type is the data type or class name or interface name.

c) To declare more than one variable of the specified type, use a comma-separated list.

Example:

int a, b, c; // declares three ints, a, b, and c.


int d = 3, e, f = 5; // declares three more ints, initializing d and f.
31

byte z = 22; // initializes z.


double pi = 3.14159; // declares an approximation of pi.
char x = 'x'; // the variable x has the value 'x'.

Dynamic Initialization:

Java allows variables to be initialized dynamically, using any expression valid at the timethe
variable is declared.

class DynInit {
public static void main(String args []) {
double a = 3.0, b = 4.0;

// c is dynamically initialized
double c = a + b;

System.out.println ("C value is ” + c);


}
}

The Scope(Visibility) and Lifetime of Variables

Scope:
a) A scope determines what objects are visible to other parts of your program.
b) It also determines the lifetime of those objects.

In Java, there are two major scopes:


i. Scope defined by a Class
ii. Scope defined by a Method

Scope defined by a Method (or) block scope

a) The scope defined by a method begins with its opening curly brace and ends with
closing curly brace.
b) Variables declared inside a scope are not visible (that is, accessible) to code that is
defined outside that scope.
c) Every block defines a new scope.
d) Scopes can be nested:
i. objects declared in the outer scope will be visible to the code withinthe
inner scope.
ii. Objects declared within the inner scope will not be visible outside it.
iii. We cannot declare a variable to have the same name as one in anouter
scope.
32

// Demonstrate block scope and Nested scope

class Scope {
public static void main(String args[]) {
int x; // known to all code within main

x = 10;
{ // start new scope
int y = 20; // known only to this block

// x and y both known here.


System.out.println("x and y: " + x + " " + y);
x = y * 2;
}

// y = 100; // Error! y not known here

// x is still known here.


System.out.println ("x is ” + x);
}
}

// Nested scope – Outer scope and inner scope with same variable
class ScopeErr {
public static void main(String args[]) {
int bar = 1;
{ // creates a new scope
int bar = 2; // Compile-time error – bar already defined!
}
}
}

Lifetime of a variable

a) The lifetime of a variable is confined to its scope.


b) Variables are created when their scope is entered, and destroyed when their scopeis left.
This means that a variable will not hold its value once it has gone out of scope.
c) If a variable declaration includes an initializer, then that variable will be reinitialized
each time the block in which it is declared is entered.
33

// Demonstrate lifetime of a variable.

class LifeTime {
public static void main(String args[]) {
int x;

for(x = 0; x < 3; x++) {


int y = -1; // y is initialized each time block is entered
System.out.println("y is: " + y); // this always prints -1

y = 100;
System.out.println("y is now: " + y);
}
}
}

Type Conversion and Casting

1) Assigning a value of one type to a variable of another type is known as Type


conversion.
2) In Java, Type conversions will occur in two places :
a. In Assignments
b. In Expressions

3) In Java, Type conversion is classified into two types:

a. Automatic / Widening conversion / Implicit conversion (Between


compatible types)

b. Casting / Narrowing conversion / Explicit conversion (Between


Incompatible types)
34

Type Conversion in Assignments

1. Automatic Conversions / Widening conversion / Implicit conversion

1) When one type of data is assigned to another type of variable, an automatic type
conversion will take place if the following two conditions are met:
i. The two types are compatible.
ii. The destination type is larger than the source type.
2) For widening conversions, the numeric types, including integer and floating-point
types, are compatible with each other.
3) There are no automatic conversions from the numeric types to char or boolean.
4) Java also performs an automatic type conversion when storing a literal integer
constant into variables of type byte, short, long, or char.

public class Test


{
public static void main(String[] args) Ouput:
{ Int value 100
int i = 100; Long value 100
long L = i; //no explicit type casting required float f Float value 100.0
= L; //no explicit type casting required char ch = Char value d
100; //no explicit type casting required

System.out.println("Int value "+i);


System.out.println("Long value "+L);
System.out.println("Float value "+f);
System.out.println("Char value "+ch);
}
}

2. Explicit conversion or Casting or Narrowing conversion

1) To create a conversion between two incompatible types, we must use a cast.


2) A cast is simply an explicit type conversion.
3) The general form of Casting is –

(target-type) value

Note:
❖ When a floating-point value is assigned to an integer type then truncation will occur.
35

❖ If the size of the value is too large to fit into the target integer type, then that valuewill
be reduced modulo (the remainder of an integer division by the) target type’s
range.

// Demonstrate casting
class Casting {
public static void main(String args[]) {
byte b; Output:
int I = 257;
double d = 323.142; Conversion of int to byte.

I and b: 257 1
System.out.println("\n Conversion of int to byte.");b
= (byte) I; Conversion of double to int.
System.out.println("I and b: " + I + " " + b);
d and I: 323.142 323
System.out.println("\n Conversion of double to int.");I
Conversion of double to byte.
= (int) d;
System.out.println("d and I :" + d + " " + I); d and b: 323.142 67

System.out.println("\n Conversion of double to byte.");b


= (byte) d;
System.out.println("d and b: " + d + " " + b);
}
}

Type Conversion in Expressions

Automatic Type Promotion in Expressions

Java’s Type Promotion Rules

1. All byte, short, and char values are promoted to int.


2. If one operand is a long, the whole expression is promoted to long.
3. If one operand is a float, the entire expression is promoted to float.
4. If any of the operands are double, the result is double.

Example:
byte b = 50; Output:
b = b * 2; Compilation Error (because, in expression,
byte is promoted to int so, the result also int)
36

Example
class Test {
public static void main(String args[]) {
byte b = 42;
char c = 'a'; Output:
short s = 1024;
int i = 50000; 235.2 + 515 - 126.3616
float f = 5.67f;
double d = .1234; result = 623.8384122070313

double result = (f * b) + (i / c) - (d * s);

System.out.println((f * b) + " + " + (i / c) + " - " + (d * s));

System.out.println("result = " + result);


}
}

Arrays

1. In Java, arrays are objects.


2. An array is a container object that holds a fixed number of values of a single type.
3. Arrays can hold either primitives or object references, but the array itself will
always be an object on the heap memory.
4. Arrays offer a convenient means of grouping related information.
5. In Java all arrays are dynamically allocated.
6. We can access a specific element in the array by specifying its index within square
brackets. All array indexes start at zero.

Types of Arrays

2 types of arrays exist:

a) One-Dimensional arrays
b) Multidimensional arrays
37

One-Dimensional arrays

Syntax:

type var-name [ ];
var-name = new type [size];

Declaring an Array of Primitives

int [ ] key; // Square brackets before name (recommended)


int key [ ]; // Square brackets after name (legal but less readable)

Declaring an Array of Object References

String [ ] s1; // Recommended


String s1 [ ]; // Legal but less readable

Note:

It is never legal to include the size of the array in your declaration.


Ex:
int[5] scores; // this code won’t compile.

Creating, Initializing, and Accessing an Array

1) Arrays are created or constructed by using new on the array type.


2) To create an array object, Java must know how much space to allocate on the heap,so we
must specify the size of the array at creation time.
3) The size of the array is the number of elements the array will hold.

Creating One-Dimensional Arrays :

int[ ] months;
months = new int[12];

Initializing an array:

months[0] = 1; // initialize first element


months[1] = 2; // initialize second element
months[1] = 2; // and so forth
38

Accessing an array:

Each array element is accessed by its numerical index:


System.out.println("Element 1 at index 0: " + months[0]);
System.out.println("Element 2 at index 1: " + months[1]);
System.out.println("Element 3 at index 2: " + months[2]);

Default values for Array elements

The elements in the array allocated by new will automatically be initialized to


i. Zero for numeric types
ii. false for boolean
iii. null for reference types
iv. ‘\u0000’ for char types

// Demonstrate a one-dimensional array.


class Array
{
public static void main(String args[])
{
int month_days[]; // declares an array of integers
month_days = new int[12]; // allocates memory for 12 integers
month_days[0] = 31;
month_days[1] = 28;
month_days[2] = 31;
month_days[3] = 30;
month_days[4] = 31;
month_days[5] = 30;
month_days[6] = 31;
month_days[7] = 31;
month_days[8] = 30;
month_days[9] = 31;
month_days[10] = 30;
month_days[11] = 31;
System.out.println("April has " + month_days[3] + " days.");
}
}

array initializer

❑ Arrays can be initialized when they are declared.


❑ An array initializer is a list of comma-separated expressions surrounded by curly
braces.
❑ There is no need to use new.
❑ The Java run-time system will check to be sure that all array indexes are in the
correct range.
39

❑ If we try to access elements outside the range of the array (negative numbers or
numbers greater than the length of the array), we will get a run-time error.

class Array
{
public static void main(String args[])
{
int month_days[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31,30, 31 };
System.out.println("April has " + month_days[3] + " days.");
}
}

Multidimensional arrays

1. In Java, multidimensional arrays are actually arrays of arrays.

int twoD[ ][ ] = new int[4][5]; -> an array of arrays of int.

Right index determines column

[0] [0] [0] [1] [0] [2] [0] [3] [0] [4]

[1] [0] [1] [1] [1] [2] [1] [3] [1] [4]
Left index
determines row [2] [0] [2] [1] [2] [2] [2] [3] [2] [4]

[3] [0] [3] [1] [3] [2] [3] [3] [3] [4]

2. In Java, When we allocate memory for a multidimensional array, we need only


specify the memory for the first (leftmost) dimension. We can allocate the
remaining dimensions separately.

int twoD[ ][ ] = new int[4][


]; twoD[0] = new
int[5];twoD[1] = new
int[5];twoD[2] = new
int[5];twoD[3] = new
int[5];
1

// Demonstrate a two-dimensional array.

class TwoDArray { p
public static void main(String args[]) {
int twoD[ ][ ]= new int[4][5]; Output:
int i, j, k = 0;
01234
for(i=0; i<4; i++) 56789
for(j=0; j<5; j++) 10 11 12 13 14
15 16 17 18 19
{
twoD[i][j] =
k;k++;
}

for(i=0; i<4; i++)


{for(j=0; j<5;
j++)
System.out.println(twoD[i][j] + "
");System.out.println();
}
}
}

Three dimensional arrays

It requires three dimensions.

int threeD[ ][ ][ ] = new int[3][4][5];

Strings

1) String is not a primitive type.


2) String defines an object.
3) The String type is used to declare string variables.
4) We can also declare arrays of strings.
5) A quoted string constant can be assigned to a String variable.
6) A variable of type String can be assigned to another variable of type String.
7) We can use an object of type String as an argument to println( ).

String str = "this is a test";


str is an object reference of type
System.out.println(str);

Pointers
1) C and C++ supports pointers.
2) But, Java does not support or allow pointers
2
3) Java is designed in such a way that as long as we stay within the confines of the
execution environment, we never need to use a pointer.
4) There would not be any benefit using pointers.
5) In Java, memory management is handled by Garbage Collector.

Object Oriented Programming using JAVA

Operators

Java’s operators can be divided into following groups:


1. Arithmetic operators 4. Boolean Logical operators
2. The Bitwise operators 5. The assignment operator
3. Relational operators 6. The ? (Ternary) operator

1. Arithmetic Operators: Arithmetic operators are used in mathematical expressions


in the same way that they are used in algebra.

Operator Result

+ Addition (unary plus)


 The operands of the arithmetic
operators must be of a numeric type.
– Subtraction (also unary
minus)  We cannot use them on boolean
types, but we can use them on char
* Multiplication types, since the char type in Java is,
essentially, a subset of int.
/ Division
 The unary minus operator negates its
% Modulus single operand.
++ Increment  The unary plus operator just returns
the operand value.
+= Addition assignment
 When the division operator is applied
–= Subtraction assignment to an integer type, there will be no
fractional component attached to the
*= Multiplication assignment result.
/= Division assignment

%= Modulus assignment

–– Decrement
3

// Demonstrate the basic arithmetic operators.

class BasicMath {
public static void main(String args[]) {
// arithmetic using integers
System.out.println("Integer
Arithmetic");int a = 1 + 1;
int b = a * 3; Output:
int c = b / 4;
int d = c - a; Integer Arithmetic
int e = -d; a=2
System.out.println("a = " + a); b=6
System.out.println("b = " + c=1
b);System.out.println("c = " + d = -1
c);System.out.println("d = " + e=1
d);System.out.println("e = " +
e); Floating Point Arithmetic
da = 2.0
// arithmetic using doubles db = 6.0
System.out.println("\nFloating Point dc = 1.5
Arithmetic");double da = 1 + 1; dd = -0.5
double db = da * 3; de = 0.5
double dc = db / 4;
double dd = dc - a;
double de = -dd;
System.out.println("da = " + da);
System.out.println("db = " +
db);System.out.println("dc = " +
dc);System.out.println("dd = " +
dd);System.out.println("de = " +
de);
}
}

The Modulus Operator (%) : The modulus operator, %, returns the remainder of a
division operation. It can be applied to floating-point types as well as integer types.

// Demonstrate the % operator.

class Modulus {
public static void main(String args[]) Output:
{int x = 42;
double y = 42.25; x mod 10 = 2
System.out.println("x mod 10 = " + x % y mod 10 = 2.25
10);System.out.println("y mod 10 = " + y
% 10);
}
}

Arithmetic Compound Assignment Operators (+=, – =, *=, /=, %=)


4
Any statement of the form var = var op expression; can be written as
var op= expression;

// Demonstrate several assignment operators. Output:

a=6
class OpEquals { b=8
public static void main(String args[]) c=3
{int a = 1;
int b = 2;
int c = 3;
a += 5;
Benefits of compound assignment
b *= 4;
c += a * b; operators
c %= 6; 1. They save a bit of typing.
System.out.println("a = " + a);
System.out.println("b = " + 2. In some cases they are more
b);System.out.println("c = " + efficient than are their equivalent
c); long forms.
}
}

Increment and Decrement (++ and --)

The increment operator (++)

The increment operator increases its operand by one.

x = x + 1; can be rewritten like this by use of the increment operator: x++;The

decrement operator (--)

The decrement operator decreases its operand by one.

x = x - 1; can be rewritten like this by use of the increment operator: x--;

// Demonstrate ++.
class IncDec {  These operators can appear both in prefix or
public static void main(String args[]) postfix form.
{int a = 1;
int b = 2;
int c; Prefix form: The operand is incremented or
int d; decremented before the value is obtained for use in
c = ++b; the expression.
d = a++; x = x + 1;
x = 42; equal to Y = 43, X = 43
c++; y = ++x; y = x;
System.out.println("a = " + a);
System.out.println("b = " +
b);System.out.println("c = " + Postfix form: The previous value is obtained for use
c);System.out.println("d = " + in the expression, and then the operand is modified.

x = 42; equal to Y=x;


5
d);
}
}
Output:
a=2
b=3
c=4
d=1

2. The Bitwise Operators

➢ Java defines several bitwise operators that can be applied to the integer types: long,
int, short, char, and byte.
➢ These operators act upon the individual bits of their operands.

Operator Result

~ Bitwise unary NOT

& Bitwise AND

| Bitwise OR

^ Bitwise exclusive OR

>> Shift right

>>> Shift right zero fill

<< Shift left

&= Bitwise AND assignment

|= Bitwise OR assignment

^= Bitwise exclusive OR assignment

>>= Shift right assignment

>>>= Shift right zero fill assignment


<<= Shift left assignment

The Bitwise Logical Operators

The bitwise logical operators are &, |, ^, and ~.

The Bitwise NOT

Also called the bitwise complement, the unary NOT operator, ~, inverts all of the
bits of its operand.
6
The Bitwise AND

The AND operator, &, produces a 1 bit if both operands are also 1.

A zero is produced in all other cases.

The Bitwise OR

The OR operator, |, combines bits such that if either of the bits in the operands is a 1,
then the resultant bit is a 1.

The Bitwise XOR

The XOR operator, ^, combines bits such that if exactly one operand is 1, then the result
is 1. Otherwise, the result is zero.

A B A|B A&B A^B ~A

0 0 0 0 0 1

1 0 1 0 1 0

0 1 1 0 1 1
1 1 1 1 0 0

// Demonstrate the bitwise logical operators.


class BitLogic
{
public static void main(String args[])
{int a = 3; // 0011 in binary
int b = 6; // 0110 in binary
int c = a | b;
int d = a &
b;
int e = a ^ b;
System.out.println(" a|b = " + a | b);
System.out.println(" a&b = " + a &
b);System.out.println(" a^b = " + a ^ b);
}

The Left Shift

The left shift operator, <<, shifts all of the bits in a value to the left a specified number of times.
Ithas this general form:

value << num


7
a) Here, num specifies the number of positions to left-shift the value in value.
b) For each shift left, the high-order bit is shifted out (and lost), and a zero is brought in on
the right.

// Left shifting a byte value.


class ByteShift
{ Output:
public static void main(String args[])
{byte a = 64, b; Originalvalueof a: 64
int i;
i and b: 256 0
i = a << 2;
b = (byte) (a << 2);
System.out.println("Original value of a: " +
a);System.out.println("i and b: " + i + " " +
b);
}
}

The Right Shift

1) The right shift operator, >>, shifts all of the bits in a value to the right a specified number
of times. It has this general form:

value >> num

2) Here, num specifies the number of positions to right-shift the value in value.

3) Each time you shift a value to the right, it divides that value by two—and discards
any remainder.

int a = 35;
a = a >> 2; // a contains 8
00100011 35
>> 2
00001000 8

4) When we are shifting right, the top (leftmost) bits exposed by the right shift are filled
inwith the previous contents of the top bit. This is called sign extension and serves to
preserve the sign of negative numbers.

11111000 –8
>> 1
11111100 –4

The Unsigned Right Shift (>>>)

Java’s unsigned, shift right operator, >>>, which always shifts zeros into the high-order bit.
8
int a = -1;

a = a >>> 24;

11111111 11111111 11111111 11111111 –1 in binary as an int

>>>24

00000000 00000000 00000000 11111111 255 in binary as an int

Bitwise Operator Compound Assignments

a = a >> 4; can be written as a >>= 4;

class OpBit {
public static void main(String args[])
{int a = 1; Output
int b = 2;
a= 3
int c = 3;
a |= 4; b=1
b >>= 1;
c <<= 1;
c=6
a ^= c;
System.out.println("a = " +
a);System.out.println("b = " +
b);System.out.println("c = " +
c);
}
}

3. Relational Operators

1) The relational operators determine the relationship that one operand has to the other.
Specifically, they determine equality and ordering.
2) The outcome of these operations is a boolean value.

Operator Result

== Equal to

!= Not equal to

> Greater than

< Less than

>= Greater than or equal to


<= Less than or equal to
3) The relational operators are most frequently used in the expressions that control the if
9
statement and the various loop statements.

int a = 4; Output:
int b = 1;
boolean c = a < b; false

4. Boolean Logical Operators

The Boolean logical operators shown here operate only on boolean operands.

Operator Result

& Logical AND

| Logical OR

^ Logical XOR (exclusive OR)

|| Short-circuit OR

&& Short-circuit AND


! Logical unary NOT
10

&= AND assignment

|= OR assignment

^= XOR assignment

== Equal to

!= Not equal to
?: Ternary if-then-else

Example

A B A|B A&B A^B !A

False False False False False True

True False True False True False

False True True False True True


True True True True False False

// Demonstrate the boolean logical operators.

class BoolLogic {

public static void main(String args[]) Output:


{boolean a = true;
boolean b = false; true
boolean c = a | b; false
boolean d = a & b; true
System.out.println( a); false
System.out.println(b);
System.out.println( c);
System.out.println(d);
}
}

Short-Circuit Logical Operators(&& , ||)

The secondary versions of the Boolean AND (&) and OR (|) operators are known as Short-
circuit operators.
11

If we use short-circuit operators || and &&, Java will not bother to evaluate the right hand
operand when the outcome of the expression can be determined by the left operand alone.

Short-circuit AND - && (Conditional-and)

class ShortCktAnd
{
public static void main(String args[])
{
Output:
int num = 20;
int denom = 0; After if

if (denom != 0 && num / denom > 10)


{
System.out.println("Inside If");
}
System.out.println("After if");
}
}

Short-circuit OR - || (Conditional-or)

class ShortCktOr
{
public static void main(String args[])
{ Ouput:
int num = 20;
int denom = 0; Inside if

if (denom == 0 || num / denom > 10) After if


{
System.out.println("Inside If");
}
System.out.println("After if");
}
}

5. The Assignment Operator

The assignment operator is the single equal sign, =.

It’s general form is:

var = expression;

Here, the type of var must be compatible with the type of expression.

Example:
12
int x, y, z;
x = y = z = 100;

The ternary / three-way operator (?)

The ? has this general form:

expression1 ? expression2 : expression3

➢ expression1 can be any expression that evaluates to a boolean value.

➢ If expression1 is true, then expression2 is evaluated; otherwise, expression3 is


evaluated.

➢ Both expression2 and expression3 are required to return the same (or compatible) type,
which can’t be void.

➢ It will be used to replace certain types of if-then-else statements.

Example

// Demonstrate ?.

class Ternary {
public static void main(String args[]) Ouput:
{
int num = 20; 0
int denom = 0;

int ratio = denom == 0 ? 0 : num / denom;


System.out.println(ratio);
}
}

Operator Precedence

1) In the below table, Operators with higher precedence are evaluated before operators
with relatively lower precedence. Operators on the same line have equal precedence.
2) When operators of equal precedence appear in the same expression, All binary
operators except for the assignment operators are evaluated from left to right;
assignment operators are evaluated right to left.

Highest
postfix ++ postfix --
prefix ++ prefix -- ~ ! unary + unary - (type-cast)
13

* / %
+ -

>> >>> <<


> >= < <= instanceof
== !=
&
^
|
&&
||
?:
->
= op=
Lowest

Using Parentheses

1) Parentheses raise the precedence of the operations that are inside them.
2) Parentheses can sometimes be used to help clarify the meaning of an expression.

Example

a >> b + 3 This expression first adds 3 to b and then shifts a right by that result.

If we want to first shift a right by b positions and then add 3 to that result, we will need
toparenthesize the expression like this:

(a >> b) + 3

Control Statements

Programming languages uses control statements to cause the flow of execution to advance and
branch based on changes to the state of a program.

Categories of Java’s Control statements

Java’s program control statements can be put into three categories:


14

1) selection,
2) iteration, and
3) jump.

1) Selection statements (if and switch)

Selection statements allow the program to choose different paths of execution based upon the
outcome of an expression or the state of a variable.

Java supports two selection statements: if and switch.

if

➢ The if statement is Java’s


conditional branch statement.

➢ It can be used to route program


execution through two different
paths.

General form

if (condition) statement1;
else statement2;

➢ Each statement may be a single statement or a compound statement enclosed in curly


braces (that is, a block).
➢ The condition is any expression that returns a boolean value.
➢ else clause is optional.

Working of if

➢ If the condition is true, then statement1 is executed.


➢ Otherwise, statement2 (if it exists) is executed.
Example:
Explanation:
int a, b; If a is less than b, then a is set to zero. Otherwise, b is set to zero.
if(a < b) a =
0;else b = 0;

Nested ifs
A nested if is an if statement that is the target of another if or else.

Example:

if(i == 10) {
if(j < 20) a = b;
if(k > 100) c = d;
15

else a = c;
}
else a = d;

The if-else-if Ladder

A sequence of nested ifs is the if-else-if ladder.

if(condition)
statement; Working of if-else-if ladder
else
if(condition) 1) The if statements are executed from the top down.
statement; 2) As soon as one of the conditions controlling the if
else is true, the statement associated with that if is
if(condition) executed, and the rest of the ladder is bypassed.
statement; 3) If none of the conditions is true, then the final else
. statement will be executed.
. 4) If there is no final else and all other conditions are
. false, then no action will take place.
else
statement;

// Demonstration if-else-if statements.


class IfElse {
public static void main(String args[])
{int month = 4; // April
String season; Q: This program is to
if(month == 12 || month == 1 || month == determine which season
2)season = "Winter"; a particular month is in.
else if(month == 3 || month == 4 || month == 5)
season = "Spring";
else if(month == 6 || month == 7 || month == 8) Output:
season = "Summer";
else if(month == 9 || month == 10 || month == 11) April is in the Spring.
season = "Autumn";
else
season = "Invalid Month";

System.out.println("April is in the " + season + ".");


}
}
➢ The switch statement is Java’s 16
multiway branch statement.
switch ➢ It provides an easy way to dispatch
execution to different parts of your
switch (expression) { code based on the value of an
case value1: expression.
// statement sequence ➢ It often provides a better alternative
break; than a large series of if-else-if
case value2: statements.
// statement sequence ➢ expression must be of type
break;
. byte,short,int,char,enum,or String
. ➢ Duplicate case values are not allowed.
. case constants must be unique.
case valueN :
// statement sequence
break;
default:
// default statement sequence
}

Working of switch

• The value of the expression is compared with each of the values in the case
statements.
• If a match is found, the code sequence following that case statement is executed.
• If none of the constants matches the value of the expression, then the default statementis
executed.
• However, the default statement is optional.
• If no case matches and no default is present, then no further action is taken.
• The break statement is used inside the switch to terminate a statement sequence.
• When a break statement is encountered, execution branches to the first line of codethat
follows the entire switch statement.
• break is also optional. If break is omitted, the program just keeps executing the
remaining case blocks until either a break is found or the switch statement ends.

//Demonstration of switch statement


class Switch {
public static void main(String args[])
{int month = 4;
String season;

switch (month) {
case 12:
case 1:
case 2:
season = "Winter";
break;
case 3:
case 4:
case 5: Q: This program is to
season = "Spring"; determine which season
break; a particular month is in.
case 6:
17
case 7:
case 8:
season = "Summer";
break;
case 9:
18

case 10:
case 11:
season = "Autumn";
break;
default:
season = "Invalid Month";
}

System.out.println("April is in the " + season + ".");


}
}

Switch Example without break:


Output:
int x = 1;
switch(x) x is one
{ x is two
case 1: System.out.println("x is one"); x is three
case 2: System.out.println("x is two"); out of the switch
case 3: System.out.println("x is three");
}
System.out.println("out of the switch");

Nested switch Statements

We can write a switch as part of the statement sequence of an outer switch, this is called a
nested switch.

Since a switch statement defines its own block, no conflicts arise between the case constantsin
the inner switch and those in the outer switch.

switch(count) {
case 1: Here, outer switch and inner
switch(target) { // nested switch
switch contains the same case
case 1: // no conflicts with outer switch
constant 1, but it is perfectly
System.out.println("target is
one");break; valid.
}
break; case
2: // ...

Difference between if and switch

➢ The switch differs from the if in that switch can only test for equality, whereas if
canevaluate any type of Boolean expression.
➢ A switch statement is usually more efficient than a set of nested ifs.
➢ If we need to select among a large group of values, a switch statement will run much
19
faster than the equivalent logic coded using a sequence of if-elses.
20

Iteration statements (while,do-while and for)

➢ Java’s iteration statements


are for, while, and do-while

➢ Iteration statements enable


program execution to repeat
one or more statements,
which are called as loops.

➢ A loop repeatedly executes


the same set of instructions
until a termination condition
is met.

while

It repeats a statement or block while its controlling expression is true.

syntax Example
while(condition) class While {
{ public static void main(String args[]) {
// body of loop int n = 1;
} while(n < 5) {
System.out.println(n);
Working of while n++;
}
➢ The condition can be any Boolean expression. }
}
➢ The body of the loop will be executed as long
as the conditional expression is true.
Output
➢ When condition becomes false, control
passes to the next line of code immediately 1
following the loop. 2
3
➢ ➢ . curly braces are unnecessary if only a
The 4
single statement is being repeated.
null statement

Null statement

null statement is a statement which consists only of a semicolon.


21
The body of the while can be empty, that is, it can be a null statement.

Example
Output:
int n = 1;
No output will be printed but the loop stops
while(n++ < execution after 4 iterations.

5);

do-while

do {
// body of loop
Example
} while (condition);
class While {
Working of do-while public static void main(String args[]) {
int n = 1;
➢ In do-while, conditional do{
expression is at the bottom of System.out.println(n);
the loop. n++;
}while(n < 5);
➢ Each iteration of the do-while }
loop first executes the body of }
the loop and then evaluates the
conditional expression.
Output
➢ If this expression is true, the
loop will repeat. Otherwise, the 1
loop terminates. 2
3
➢ The do-while loop always 4
executes its body at least once.

for

Beginning with JDK 5, there are two


forms of the for loop.

1. Basic for loop


2. For-each (Enhanced for loop)
22

Basic for loop Flow Diagram

for(initialization; condition;
iteration)
{
// body
}

Working of for loop

1. When the loop first starts, the


initialization portion of the
loop is executed.

2. Next, condition is evaluated.


This must be a Boolean
expression.

3. If this expression is true, then Example


the body of the loop is
executed. class For {
If it is false, the loop public static void main(String args[]) {
Enhanced for loop (for-each)
terminates. for(i=1; i<5;i++) {
System.out.println(i);
4. Next, the iteration portion of }
the loop is executed. }
}
5. The loop then iterates, first
evaluating the conditional Output
expression, then executing the
body of the loop, and then 1
2
executing the iteration
3
expression with each pass.
4

1. Declaring Loop Control Variables Inside the for Loop


It is possible to declare the variable inside the initialization portion of the for.

// here, n is declared inside of the for loop


for(int n=10; n>0; n--)
System.out.println(n);

2. Using the Comma


i. Using comma, we can include more than one statement in the
initialization and iteration portions of the for loop.
ii. We can not use more than one statement in increment section.
23

int a, b; Output:

for(a=1, b=4; a<b; a++, b--) { a= 1


System.out.println("a = " + b=4
a);System.out.println("b = " + a= 2
b); b=3
}

For loop variations

1. The condition can be any Boolean expression.


2. Either the initialization or the iteration expression or both may be absent.

public static void main(String args[])


{int i; Output:
boolean done = false;

i = 0;
for( ; !done; ) {
System.out.println( i);
if(i == 4) done =
true;i++;
}
}

3. We can leave all three parts of the for empty.

for( ; ; ) {
// ... Output:
Infinite loop
}

The For-Each Version of the for Loop

i. Beginning with JDK 5, a second form of for was defined that implements a “for-
each”style loop.
ii. A for-each style loop is designed to cycle through a collection of objects, such as an
array, in strictly sequential fashion, from start to finish.

form of for-each

for(type itr-var :
collection)statement-
block

Here,

➢ type specifies the type


24

➢ itr-var specifies the name of an iteration variable that will receive the elements from a
collection, one at a time, from beginning to end.
➢ With each iteration of the loop, the next element in the collection is retrieved and stored
in itr-var.
➢ The loop repeats until all elements in the collection have been obtained.

Example 1:
Output:
int nums[] = { 1, 2, 3, 4, 5 }; Value is: 1
Value is: 2
// use for-each style for to display and sum the values Value is: 3
for(int x : nums) { Value is: 4
System.out.println("Value is: " + x); Value is: 5
}

Example 2: Iterating over multidimensional arrays

int sum = 0;
int nums[][] = { {1,2},{3,4}}; Output:

Value is: 1
// use for-each for to display and sum the values Value is: 2
for(int x[] : nums) { Value is: 3
for(int y : x) { Value is: 4
System.out.println("Value is: " + Sum: 10
y);sum += y;
}
}
System.out.println("Sum: " + sum);

Nested For Loops

Like all other programming languages, Java allows loops to be nested. That is, one loop may be
inside another.
Output:

// Loops may be nested.


class Nested {
public static void main(String args[])
{int i, j;
for(i=0; i<10; i++) {
for(j=i; j<10; j++) {
System.out.print("*"
);
}
System.out.println(); *
}
}
}
25

Jump Statements (break, continue, return)

Jump statements allow the program to execute in a nonlinear fashion.

Java supports three jump statements: break, continue, and return.

break

In Java, the break statement has three uses.

Unlabeled break

1) It terminates a statement
sequence in a switch
statement.
2) It can be used to exit a
loop.
Labeled break:
3) It can be used as a
“civilized” form of goto.

Unlabeled break : break to Exit a loop

Example

➢ By using break, we can force


immediate termination of a loop, class BrkEx
bypassing the conditional public static void main(String args[]) {
expression and any remaining code for(int i=1; i<5;i++) {
if(i == 4)
in the body of the loop. break;
System.out.println(n);
➢ When a break statement is }
encountered inside a loop, the loop }
is terminated and program control }
resumes at the next statement
following the loop.
Output
➢ The break statement can be used
with any of Java’s loops, including 1
intentionally infinite loops. 2
3
26

Labeled break : Form of Goto

➢ In Java, break statement can also be Example:


used as form of Goto.
class Break {
➢ Java does not have a goto public static void main(String args[])
{
statement. break gives you the
boolean t = true;
benefits of a goto without its
problems. first:
{
General form second:
{
break label; third:
{
✓ label is the name of a label System.out.println("Before the break.");
that identifies a block of code. if(t) break second; // break second block
System.out.println("This won't execute");
➢ A label is any valid Java identifier }
System.out.println("This won't execute");
followed by a colon. }
System.out.println("This is after second block.");
➢ To name a block, put a label at the }
start of it. }
}
➢ Labeled break causes execution to
resume at the end of the labeled Output:
Before the break.
block.
This is after second block.

continue

1) continue is used to force an early Example:


iteration of the loop.
class Continue
2) In any iteration, continue will stop public static void main(String args[]) {
processing the code that is for(int i=1; i<5;i++) {
present after the continue and if( i % 2 == 0) continue;
continues the execution from the System.out.print(i);
next iteration. }
}
3) In while and do-while loops, a }
continue statement causes
control to be transferred directly
to the conditional expression that Output
controls the loop.
1
4) In a for loop, control goes first to 3
the iteration portion of the for
statement and then to the
conditional expression.
27

return

Example
➢ The return statement is used // Demonstrate return.
to explicitly return from a
class Return {
method.
public static void main(String args[]) {
boolean t = true;
➢ It causes program control to
transfer back to the caller of
System.out.println("Before the return.");
the method.
if(t) return; // return to caller
➢ The return statement
immediately terminates the
System.out.println("This won't execute.");
method in which it is executed.
}
}

class

The General Form of a Class


class
class classname {
➢ class is a logical construct type instance-variable1;
which defines shape and type instance-variable2;
nature of an object. // ...
type instance-variableN;
➢ class is a template which
defines data and code that type methodname1(parameter-list) {
acts on that data. // body of method
}
➢ class defines a new data type. type methodname2(parameter-list) {
// body of method
➢ A class is declared by use of }
the class keyword. // ...
type methodnameN(parameter-list) {
// body of method
}
}

Instance variables or member variables


Members of a class
➢ The data, or variables, defined within a class are
called instance variables. The variables and methods
➢ Instance variables are called so, because each defined within a class are
instance of the class (that is, each object of the class) called members of the class.
contains its own copy of these variables.
28

Methods / Instance methods / member methods

The code is contained within methods.

Class Example

class Box {
double width;
double height;
double depth;
}

Declaring Objects (new operator)

➢ Objects are created with new keyword.


➢ The new operator dynamically allocates (at runtime) memory for an object and
returns a reference to it. This reference is memory address of object. This referenceis
stored in a variable.
For
m

classname object_reference = new classname ( );

Statement Effect

Box mybox;

width

mybox = new Box(); height

depth
mybox

Box object
29

Class vs Object

class object

Class is a template. Object is an instance of a class

Class is declared with class keyword. Object is created with new keyword.

Class does not create an actual object. Object will create an actual object.

Ex: class Test { } Ex: Test t = new Test();

Methods
➢ type specifies the type of data returned
This is the general form of a method: by the method.
➢ If the method does not return a value,
type name(parameter-list) { its return type must be void.
// body of method ➢ Methods that have a return type other
than void return a value to the calling
method using the following form:
} ➢ return value;

Points about methods

➢ Method can return values (primitives and objects)


➢ Method can take parameters (primitives and objects)

class Box {
double width, height, depth;
// compute and return volume
double volume() {
return width * height * depth;
}
class BoxDemo
{
public static void main(String args[])
{Box b1 = new Box();
Box b2 = new
Box();double vol;

// assign values to mybox1's instance variables


b1.width = 10;
b1.height = 20;
b1.depth = 15;
30

/* assign different values to mybox2's instance variables */


b2.width = 3;
b2.height = 6;
b2.depth = 9;

// get volume of first


boxvol = b1.volume();
System.out.println("Volume is " + vol);

// get volume of second box


vol = b2.volume();
System.out.println("Volume is " + vol);
}
}

Constructors

1. Constructors are used to initialize objects.


2. A constructor initializes an object immediately upon creation.
3. Constructor has the same name as the class name.
4. Constructor is syntactically similar to a method but it does not contain any return type,
including void.
5. Constructor is called when the object is created, before the new operator completed.

Types of Constructors

1. Default or no-argument constructor


2. Parameterized constructor

1. Default or no-argument constructor

1. The constructor which does not take any parameters is called as default or no-arg
constructor.
2. When we do not explicitly define a constructor for a class, then Java creates a
default constructor for the class.
3. The default constructor automatically initializes all instance variables to their
defaultvalues, which are zero, null, and false, for numeric types, reference types,
and boolean, respectively.

/* Here, Box uses a constructor to initialize the dimensions of a box. */


class Box {
double width;
double height;
double depth;
31

// This is the constructor for Box.


Box() {
System.out.println("Constructing
Box");width = 10;
height = 10;
depth = 10;
}

// compute and return volume


double volume() {
return width * height * depth;
}
}

2. Parameterized constructor

1. The constructor which takes parameters is called as parameterized


constructor.
2. This is useful to initialize different objects with different values.

/* Here, Box uses a parameterized constructor to initialize the dimensions of a box. */


class Box {
double width;
double height;
double depth;

// This is the constructor for Box.


Box(double w, double h, double d)
{
System.out.println("Constructing Box");
width = w;
height = h;
depth = d;
}

// compute and return volume


double volume() {
return width * height * depth;
}
}
class BoxDemo {
public static void main(String args[]) {
// declare, allocate, and initialize Box objects
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box(3, 6,

9);double vol;

// get volume of first


32
boxvol =
mybox1.volume();
System.out.println("Volume is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
}

this keyword

this always refers to the currently executing object.

There are two uses with the this keyword.

1. To resolve the name collisions between instance variables and local variables
2. To explicitly call a constructor from another constructor

1. Instance Variable Hiding


To resolve the name collisions between instance variables and local variables

a) when a local variable has the same name as an instance variable, the local
variable hides the instance variable.
b) To resolve this name conflicts, we use this.

// Use this to resolve name-space collisions.


Box(double width, double height, double depth)
{
this.width = width;
this.height = height;
this.depth = depth;
}

2. To explicitly call a constructor from another constructor

a) We can use this to call a constructor from another constructor. This is called a
Explicit constructor invocation.
b) this() should be the first statement inside a constructor.

class Box {
double width;
double height;
double depth;
Box()
{
System.out.println("Defualt constructor");
}
// This is the constructor for Box.
Box(double w,double h, double d) {
33

// calling default constructor


this();
System.out.println("Constructing Box");
width = 10;
height = 10;
depth = 10;
}
}

Garbage Collection

➢ In Java, objects are allocated memory dynamically using new operator. Butmemory
de-allocation happens automatically.

➢ In Java, Garbage collection is the technique through which the memory de-allocation
will happen automatically.

Working of Garbage Collection

a) The job of the Garbage collector is to identify the unused objects and delete them from
memory.

b) Garbage collector checks the objects which do not have any reference and deletes
them from memory.

c) Garbage collector runs periodically during the program execution. But there is no
guarantee when a Garbage collector runs.

d) The garbage collector runs periodically, checking for objects that are no longer
referenced by any running state or indirectly through other referenced objects.

e) Garbage collector calls finalize( ) method just before it runs.

gc() method

1. The gc() method is used to invoke the garbage collector to perform cleanup
processing.
2. The gc() is found in System and Runtime classes.

public static void gc(){ }

Example

public class MemoryTest{


public static void main(String args[]) {
34

Runtime r=Runtime.getRuntime();
System.out.println("Total Memory:
"+r.totalMemory());System.out.println("Free
Memory: "+r.freeMemory());

for(int i=0;i<100;i++){
new MemoryTest();
}
System.out.println("After creating 100 instance, Free Memory: "+r.freeMemory());

System.gc();
System.out.println("After gc(), Free Memory: "+r.freeMemory());
}
}

finalize( ) method / finalization

a) By using finalize() method or finalization, we can define specific actions that


willoccur when an object is just about reclaimed by the Garbage collector.

b) To add a finalizer to a class, we simply define the finalize( ) method. The Java
run time calls that method whenever it is about to recycle an object of that class.

c) Inside the finalize( ) method, you will specify those actions that must be
performed before an object is destroyed.

The finalize( ) method has this general form:


protected void finalize( )
{
// finalization code here
}

Overloading Methods

1. Overloading is the process through which we can define two or more methods within
the same class that share the same name but with different parameters (type and/or
number).
2. The Overloaded methods must differ in the type and / or number of their parameters.
3. When an overloaded method is invoked, Java uses the type and/or number of
arguments as its guide to determine which version of the overloaded method to
actually call.
35
4. In some cases, Java’s automatic type conversions can play a role in overload
resolution.

// Demonstrate method overloading.


class OverloadDemo {
void test() {
System.out.println("No parameters");
}

// Overload test for one integer parameter.


void test(int a) {
System.out.println("a: " + a);
}

// Overload test for two integer parameters.


void test(int a, int b) { Output:
System.out.println("a and b: " + a + " " + b);
} No parameters
a: 10
a and b: 10 20
// Overload test for a double parameter
double a: 123.25
double test(double a) { Result of ob.test(123.25):
System.out.println("double a: " + 15190.5625
a);return a*a;
}
}
class Overload {
public static void main(String args[]) {
OverloadDemo ob = new OverloadDemo();
double result;

// call all versions of test()


ob.test();
ob.test(10);
ob.test(10, 20);
result = ob.test(123.25);
System.out.println("Result of ob.test(123.25): " + result);
}
}
Constructor Overloading

We can define two or more constructors with the same name but with different parameters. This
process is called Constructor overloading.

class Box {
double width;
double height;
double depth;

// This is the constructor for


Box.Box() {
width = -1;
height = -1;
36
depth = -1;
}

// This is the constructor for Box.


Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}

// compute and return volume


double volume() {
return width * height * depth;
}
}

class BoxDemo {
public static void main(String args[]) {
// declare, allocate, and initialize Box objects
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new

Box();double vol;

// get volume of first


boxvol =
mybox1.volume();
System.out.println("Volume is " + vol);

// get volume of second box


vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
}

String class

Java API defines String as a class

Two important things about Strings

1. For every string, Java creates an object of type String. Even string constants are
actually String objects.
2. String objects are immutable.

Creation of Strings / Construction of Strings

String are created many ways, but the easiest are two ways :
37

1) Without new

operatorString s =

“Java”;

2) With new operator

String s = new String(“Java”);

Difference Between the above two ways (OR) Important facts about String and Memory

When a String is created using without new operator, then the string object will be
created inside the separate memory called “String Constant pool”.

When a String is created using new operator, then the string object will be created both
heap memory and inside “String Constant pool”. But the heap memory copy will be
referred by the reference variable.

When creating a string in String constant pool, JVM first checks the pool to see if thereis
a similar string exists or not. If exists, no new string will be created, existing one will be
reused. If string does not exist, then JVM will create a new one.

Immutability:
Once a string is created, its Heap memory
contents cannot be altered.

String s = “Java”;

String s1 = new String(“Java”);

String s2 = “Java”;

String s3 = new String(“Java”);


S2 S3

String Methods

Important methods in the String class

1. charAt() Returns the character located at the specified index


2. concat() Appends one String to the end of another ( "+" also works)
3. equalsIgnoreCase() Determines the equality of two Strings, ignoring case
4. length() Returns the number of characters in a String
5. replace() Replaces occurrences of a character with a new character
6. substring() Returns a part of a String
38

7. toLowerCase() Returns a String with uppercase characters converted


8. toString() Returns the value of a String
9. toUpperCase() Returns a String with lowercase characters converted
10. trim() Removes whitespace from the ends of a String

1. public char charAt(int index)

String x = “CARGO";
System.out.println( x.charAt(2) ); Output is : R

2. public String concat(String s)

String x = "taxi";
System.out.println( x.concat(" cab") ); Output is : taxi cab

+ and += operators

String x = "library";
System.out.println( x + " card"); Output is : library card

String x =
"Atlantic";x+= "
ocean";
System.out.println( x ); Output is : Atlantic ocean

3. public boolean equals(Object anObject)

Compares this string to the specified object. The result is true if and only if the argument
is not null and is a String object that represents the same sequence of characters as this object.

String x = "Exit";
System.out.println( x.equals("EXIT")); Output is: false

String x = "Exit";
System.out.println( x.equals("Exit")); Output is: true

4. public boolean equalsIgnoreCase(String s)

This is similar to equals() method and it will return true even when characters in the String
objects being compared have differing cases.

String x = "Exit";
System.out.println( x.equalsIgnoreCase("EXIT")); Output is: true
39

5. public int length()

String x = "01234567";
System.out.println( x.length() ); Output is: 8

6. public String replace(char old, char new)

String x = "oxoxoxox";
System.out.println( x.replace('x', 'X') ); Output is: oXoXoXoX

7. public String substring(int begin)

String x = "0123456789";
System.out.println( x.substring(5) ); Output is: 56789

8. public String substring(int begin, int end)

String x = "0123456789";

System.out.println( x.substring(5, 8)); Output is: 567

9. public String toLowerCase()

String x = "A New Moon";


System.out.println( x.toLowerCase() ); Output is: a new moon

10. public String toUpperCase()

String x = "A New Moon";


System.out.println( x.toUpperCase() ); Output is: A NEW MOON

11. public String trim()

String x = " hi ";


System.out.println( x.trim()); Output is: hi

12. public String toString()

All objects in Java must have a toString() method, which typically returns a String that in
some meaningful way describes the object in question.

String x = "big surprise";


System.out.println( x.toString() ); Output is: big surprise
40

Write a Java program to demonstrate String class and its methods

// Demonstrating some String methods.


class StringDemo {
public static void main(String args[]) {
String strOb1 = "First String";
String strOb2 = "Second
String";String strOb3 = strOb1;

System.out.println("Length of strOb1: " +strOb1.length());

System.out.println("Char at index 3 in strOb1: " +strOb1.charAt(3));

if(strOb1.equals(strOb2))
System.out.println("strOb1 == strOb2");
else
System.out.println("strOb1 != strOb2");

if(strOb1.equals(strOb3))
System.out.println("strOb1 ==
strOb3");
else
System.out.println("strOb1 != strOb3");
}
}
String arrays

We can have arrays of strings, just like we can have arrays of any other type of object.

// Demonstrate String arrays.


class StringDemo { Output:
public static void main(String args[]) {
String str[] = { "one", "two", "three" one
}; two
three

for(int i=0; i<str.length; i++)


System.out.println(str[i]);
}
}
Inheritance (IS-A)

Definition:

Inheritance is the process by which one object acquires the properties of another object.

➢ Using inheritance, we can create a general class that defines characteristics commonto
a set of related items.
➢ This class can then be inherited by other, more specific classes, each adding those
things that are unique to it.

Super class / Base class / Parent class Super class


The class from which a subclass is derived is called
the superclass.

Subclass / Derived class / Extended class / Child


class
Subclass
A class that is derived from another class is called a subclass.

A subclass inherits state(variables) and behavior (method) from


all of its ancestors.

Note:

In the Java programming language, each class is allowed to have one direct superclass, and
each superclass has the potential for an unlimited number of subclasses.

Creating subclasses / extends keyword


To create a subclass of another class use the extends clause in the class declaration.

class subclass-name extends superclass-name


{
// body of class
}

Benefits of Inheritance

1. To promote code reuse


2. To use polymorphism

IS-A relationship

Inheritance represents IS-A relationship. Inheritance defines is-a relationship between a Super
class and its Sub class.

Example
In OOPs term we can say that,
class Vehicle
• Vehicle is super class of Car.
{
// fields of Vehicle
} • Car is sub class of Vehicle.
class Car extends Vehicle
{ • Car IS-A Vehicle.
// new fields and methods of Car.
}

The Object class

➢ The Object class is the superclass to all the classes in Java platform and every class
that we create.
➢ The Object class, defined in the java.lang package, defines and implements behavior
common to all classes.
Methods in Object class
clone() -> Creates and returns a copy of this object.
equals(Object obj) -> Indicates whether some other object is "equal to" this one.
finalize() -> Called by the garbage collector on an object when garbage collection
determines that there are no more references to the object.
getClass() -> Returns the runtime class of this Object.
toString() -> Returns a string representation of the object.
hashCode() -> Returns a hash code value for the object.
A Simple Example of Single Inheritance

class Parent
{
int i;
void showi()
{
System.out.println("i="+i);
}
} Output:

Parent class
class Child extends Parent i=10
{ Child class
int k; i=20
void showk() k=40
{ i+k=60
System.out.println("k="+k);
}
void sum()
{
System.out.println("i+k="+(i+k));
}
}
class InheritanceDemo
{
public static void main(String a[])
Note:
{Parent p = new Parent();
System.out.println("Parent class");
➢ A subclass can inherits all
p.i = 10; the members of the super
p.showi() class except private
; members.

Child ch = new Child(); ➢ We can use the inherited


System.out.println("Child members as is, replace
class");ch.i = 20; them, hide them, or
ch.k = 40; supplement them with new
ch.showi() members.
;
ch.showk();
ch.sum();
}
}

What We Can Do in a Subclass

1) The inherited fields can be used directly, just like any other fields.
2) we can declare a field in the subclass with the same name as the one in the superclass,
- hiding
3) We can declare new fields in the subclass that are not in the superclass.
4) The inherited methods can be used directly as they are.
5) We can write a new instance method in the subclass that has the same signature as the
one in the superclass – Method overriding.
6) We can declare new methods in the subclass that are not in the superclass.
7) We can write a subclass constructor that invokes the constructor of the superclass,
either implicitly or by using the keyword super.

Types of Inheritance

1. Single Inheritance NOTE :


2. Multilevel Inheritance
3. Hierarchical Inheritance Multiple inheritance is not supported in java
4. Multiple Inheritance

Multilevel Inheritance Example


Simple Inheritance Example
class A
class A {
{ }
class B extends A
} {
class B extends A }
{ class C extends B
{
} }
Hierarchical Inheritance Example
class A
{
}
class B extends A
{
}
class C extends A
{
}

MultiLevel Inheritance

In a class hierarchy, constructors are executed in the order of derivation, from


superclass to subclass.

Write a Java program to demonstrate multilevel inheritance.

class A
{
A(
)
{ System.out.println("A constructor");

void printA()
{
System.out.println("A");
}
}
class B extends A
{
B(
)
{ System.out.println("B constructor");

}
void printB()
{
System.out.println("B");
}
}

class C extends B
{
C()
{
System.out.println("C constructor");

}
void printC()
{
System.out.println("C");
} Output:
}
A constructor
B constructor
class MLInheritance C constructor
{ A
public static void main(String a[]) B
{ C
C c = new C();
c.printA();
c.printB();
c.printC();
}
}

Method Overriding

Method Overriding

Declaring an instance method in subclass which is already present in parent class is known as
method overriding.

If a subclass defines an instance method with the same signature as an instance method in the
superclass, then the method in the subclass overrides the one in the superclass.

The method in the subclass is called as overriding method. The method in the superclass is
called as overridden method.

Method overriding is also referred to as runtime polymorphism.


Rules of method overriding in Java

a) Argument list: The argument list must exactly match that of the overridden method.
b) Return Type: The return type must be the same as, or a subtype (covariant return
type) of, the return type declared in the original overridden method in the superclass.
c) Instance methods can be overridden only if they are inherited by the subclass.

Method Overridng Example

class Animal
{void eat()
{
System.out.println("Animal eating");
}
}
class Lion extends Animal {
void eat() {
System.out.println("Lion eating");
}
}
public class Override
{ Output:
public static void main(String[] args)
{ Animal eating
Animal t = new
Animal();t.eat(); Lion eating

Lion l = new
Lion();l.eat();
}
}

Why multiple inheritance is not supported in Java


➢ To remove ambiguity (OR) Deadly Diamond of Death problem.

Deadly Diamond of Death problem or Diamond problem

➢ The problem is, if a class extended two other classes, and both super classes have a
show() method, then which version of show() method would the subclass inherit?. This is
an ambiguity.

➢ This issue can lead to a scenario known as the "Deadly Diamond of Death," because of
the shape of the class diagram that can be created in a multiple inheritance design.

➢ The diamond is formed when classes B and C both extend A, and both B and C inherit a
method from A. If class D extends both B and C, and both B and C have the show() the
method from A.

➢ Drawn as a class diagram, the shape of the four classes looks like a diamond.

“super” keyword

Super keyword is used for two purposes:

a) To call a superclass constructor from a subclass


b) To access members of a superclass that has been hidden by the members of a
subclass ( to overcome name hiding)

a) To call a superclass constructor from a subclass

i. A superclass constructor can be called by a subclass constructor by using the


following form of super:
super(arg-list);
Here, arg-list specifies any arguments needed by the constructor in the
superclass.
ii. super() must be the first statement to be executed inside the subclass
constructor.

Example

class A }
{
A(int p)
{

}
System.out.println("Super class constructor");

class B extends A
{
B(int
q)
{ super(10);
System.out.println("Sub class constructor");

}
}
class SuperDemo1
{ Output:
public static void main(String ar[])
{ Super class constructor
B b = new B(20); Sub class constructor
}
}

b) To overcome name hiding

This second form of super is most applicable to situations in which member names of a
subclass hide members by the same name in the superclass.

super.member

-> Here, member can be either a method or an instance variable.

Example
class A {

int i=10;

void

print()
{
System.out.println("Super class print");
}
}
class B extends A
{
int i=20; // this hides the i in
Avoid print()
{
super.print();
System.out.println("Sub class
print");
System.out.println("Super class
i="+super.i);System.out.println("Sub class
i="+i);
}
}
Output:
class SuperDemo
{ Super class print
public static void main(String ar[]) Sub class print
{ Super class i=10
B b = new Sub class i=20
B();b.print();
}
}

Polymorphism

Polymorphism is two types:

1. Compile time polymorphism (static polymorphism)

2. Run time polymorphism (dynamic polymorphism / dynamic method dispatch /


virtualmethod invocation)

Java’s principle in Polymorphism - A Superclass Variable Can Reference a


Subclass Object.

Java uses the following principle in achieving polymorphism:


A reference variable of a superclass can be assigned a reference to any subclass derived
from that superclass.
1. Compile time polymorphism (static polymorphism)

a) Java achieves compile time polymorphism using Method Overloading.


b) In this, method resolution will happen at compile-time.
c) In this, compiler looks only at the reference type (not at the object type) and
determines which Overloaded method to call.

Example

// Compile time polymorphism or Static polymorphism


class Animal {
void eat() {
System.out.println("Animal eating");
}
}
class Lion extends Animal {

void eat(int b) {
System.out.println("Overloading - Lion eating");
}
}
class RTPoly {
public static void main(String args[]) {
Animal a = new Animal(); // object of type
AnimalLion l = new Lion(); // object of type
Lion Output:

Animal r; // obtain a reference of type Animal eating


Animal eating
Animalr = a; // r refers to an Animal object
r.eat(); // calls Animal's version of eat

r = l; // r refers to a Lion
objectr.eat();
//r.eat(10); // calls Animal's version of eat(int) – compiler error
}
}

2. Run time polymorphism

(Dynamic polymorphism / Dynamic Method dispatch / Virtual Method invocation)

1) Java achieves run time polymorphism using Method Overriding.

2) In this,method resolution will happen at run time based on actual object.


3) Dynamic method dispatch is the mechanism by which a call to an overridden
method is resolved at run time, rather than compile time.
4) When a method is overridden, the child version of the method always executes at
runtime.

Example

// Dynamic Method Dispatch or Run time polymorphism


// or Virtual Method Invocation
class Animal {
void eat() {
System.out.println("Animal eating");
}
}
class Lion extends Animal {
// override eat()
void eat() {
System.out.println("Lion eating");
}
}
class RTPDemo {
public static void main(String args[]) {
Animal a = new Animal(); // object of type
AnimalLion l = new Lion(); // object of type
Lion

Animal r; // obtain a reference of type


Output:
Animalr = a; // r refers to an Animal object
r.eat(); // calls Animal's version of eat Animal eating
Lion eating

r = l; // r refers to a Lion object


r.eat(); // calls Lionss version of eat
}
}

final keyword: Three uses with final keyword:

1. To define constants
2 & 3 are used with
2. To prevent Method Overriding
3. To prevent Inheritance Inheritance

By using final, we can prevent a method from being overridden. Methods declared as final
cannot be overridden.

class A {
final void meth() {
System.out.println("This is a final method.");
}
}
class B extends A
{
void meth() { // ERROR! Can't override.
System.out.println("Illegal!");
}
}

Because meth( ) is declared as final, it cannot be overridden in B. If we attempt to do so, a


compile-time error will result.

To Prevent Inheritance

To prevent a class from being inherited, declare the class as final. Declaring a class as final
implicitly declares all of its methods as final, too.

final class A
{
//...
}

// The following class is


illegal.class B extends A
{
// ERROR! Can't subclass A
//...
}
Abstract class

An abstract class is a class that cannot be instantiated. An

abstract class contains one or more abstract methods.

Abstract method

Abstract method is a method which do not contain it’s body. In other words, abstract method is a
method without any implementation.
Abstract method syntax:

abstract type name(parameter-list);

➢ Abstract methods are sometimes referred to as subclasser responsibility, because they


have no implementation specified in the superclass. So, subclass must override them.
➢ It is not possible to declare abstract constructors or abstract static methods.
➢ Any subclass of an abstract class must either implement all of the abstract methods in
the superclass, or be declared abstract itself.

Example:

Write a Java program to demonstrate abstract methods and abstract classes.

abstract class Figure {


double dim1; double dim2;

Figure(double a, double b) {
dim1 = a; dim2 =
b;
}
// area is now an abstract method
abstract double area();
}

class Rectangle extends Figure {


Rectangle(double a, double b) {
super(a, b);
}
// override area for rectangle
double area() {
System.out.println("Inside Area for
Rectangle.");return dim1 * dim2;
}
}

class Triangle extends Figure {


Triangle(double a, double b)
{
super(a, b);
}

// override area for right


triangledouble area() {
System.out.println("Inside Area for
Triangle.");return dim1 * dim2 / 2;
}
}

class AbstractAreas {
public static void main(String args[]) {
// Figure f = new Figure(10, 10); // illegal
nowRectangle r = new Rectangle(9, 5);
Triangle t = new Triangle(10, 8);
Figure figref; // this is OK, no object is created

figref = r;
System.out.println("Area is " + figref.area());

figref = t;
System.out.println("Area is " + figref.area());
}
}

Differences Between Method Overloading and Method Overriding

Overloaded Methods Overridden Methods

Argument(s) Must change. Must not change.


Return type Can change. Can’t change except for
covariant returns.

Exceptions Can change. Can reduce or eliminate.


Must not throw new or
broader checked exceptions

Access Can change. Must not make more


restrictive (can be less
restrictive)

Invocation Reference type determines which Object type (in other words,
overloaded version (based on declared the type of the actual
argument types) is selected. Happens at instance on the heap)
compile time. determines which method is
selected. Happens at
runtime.

Packages

A package is a grouping of related classes and interfaces.


Benefits of packages:

Packages provides -

a) access protection
✓ We can allow types within the package to have unrestricted access to one
another yet still restrict access for types outside the package.
b) Name space management.
✓ The names of one package types won’t conflict with the types in other packages.
c) Two different programmers can easily determine the types defined in the package are
related.

Defining / Creating a Package


To create a package, we choose a name for the package and put a package statement with that
name at the top of every source file.

General form of a package statement:


package pkg; -> Here, pkg is the name of the package.

✓ The package statement (for example, package graphics;) must be the first line in the
source file.
✓ There can be only one package statement in each source file, and it applies to all typesin
the file.
✓ Java uses file system directories to store packages.
✓ Ex: package MyPackage;

➢ the .class files for any classes that are part of MyPackage must be stored in a
directory called MyPackage.

Multilevel Packages

We can create a hierarchy of packages. To do so, simply separate each package name
from the one above it by use of a period.

The general form of a multileveled package statement is shown here:

package pkg1[.pkg2[.pkg3]];

Ex: package java.lang.system;

This needs to be stored in java\lang\system directory in windows environment.


Package categories

Two forms:

Built-in package:
➢ All of the standard Java classes included with Java are stored in a package called java.
➢ The basic language functions are stored in a package inside of the java package called
java.lang.

User-defined package:
User defined packages are the packages defined by the programmers specific to their
application.

Ex: package edu.cbit.example;

Access Protection in Java using Packages

In addition to the access modifiers (private,public,protected and default), packages will add
another dimension to access control.

Java addresses four categories of visibility for class members:

1. Subclasses in the same package

2. Non-subclasses in the same package

3. Subclasses in different packages

4. Classes that are neither in the same package nor subclasses


private No Protected Public

Modifier

(default)

Same class Yes Yes Yes Yes

Same package subclass No Yes Yes Yes

Same package non-subclass No Yes Yes Yes

Different package subclass No No Yes Yes

Different package non-subclass No No No Yes

Example: Write a Java program to demonstrate Access Protection in java using


Packages.

package p1;

public class Protection


{int n = 1;
private int n_pri = 2;
protected int n_pro = 3;
public int n_pub = 4;

public Protection() {
System.out.println("base constructor");
System.out.println("n = " + n);
System.out.println("n_pri = " + n_pri);
System.out.println("n_pro = " + n_pro);
System.out.println("n_pub = " +
n_pub);
}
}

class Derived extends Protection {


Derived() {
System.out.println("derived
constructor");System.out.println("n = " +
n);

// class only
// System.out.println("n_pri = "4 + n_pri);

System.out.println("n_pro = " + n_pro);


System.out.println("n_pub = " +
n_pub);
}
}

class SamePackage {
SamePackage() {

Protection p = new Protection();


System.out.println("same package constructor");
System.out.println("n = " + p.n);

// class only
// System.out.println("n_pri = " + p.n_pri);

System.out.println("n_pro = " + p.n_pro);


System.out.println("n_pub = " +
p.n_pub);
}
}
package p2;

class Protection2 extends p1.Protection


{
Protection2()
{
System.out.println("derived other package constructor");

// class or package only


// System.out.println("n = " + n);

// class only
// System.out.println("n_pri = " + n_pri);

System.out.println("n_pro = " + n_pro);


System.out.println("n_pub = " +
n_pub);
}
}

class OtherPackage {
OtherPackage() {
p1.Protection p = new p1.Protection();
System.out.println("other package constructor");

// class or package only


// System.out.println("n = " + p.n);

// class only
// System.out.println("n_pri = " + p.n_pri);

// class, subclass or package only


// System.out.println("n_pro = " + p.n_pro);
System.out.println("n_pub = " + p.n_pub);
}
}

CLASSPATH

The CLASSPATH refers to the path on your file system where your .class files are saved,
and the classpath is defined by the CLASSPATH environment variable.

The CLASSPATH environment variable specifies the directories where you want the
compilerand the JVM to search for bytecode.

Finding Packages

How does the Java run-time system know where to look for packages that we create?

1. First, by default, the Java run-time system uses the current working directory as its
starting point. Thus, if our package is in a subdirectory of the current directory, it will
befound.

2. We can specify a directory path or paths by setting the CLASSPATH


environmentalvariable.

3. we can use the -classpath option with java and javac to specify the path to your
classes.

Using the - classpath flag overrides the CLASSPATH environment variable.

Importing Packages

The types that comprise a package are known as the package members.

To use a public package member from outside its package, we must do one of the
following:

1. Refer to the member by its fully qualified name

2. Import the package member

3. Import the member's entire package

1. Referring to a Package Member by Its Qualified Name

In this, package name will be included to access the member of a package outside its package.
Test.java
package cse.p1;
public class Test
{
public void print()
{
System.out.println("Hello");
}
}

PackAccess.java

package cse.p2;
class B extends cse.p1.Test
{

}
class PackAccess
{
public static void main(String a[])
{
cse.p1.Test t = new cse.p1.Test();
t.print();

B b = new
B();b.print();
}
}

2. Import statement

In a Java source file, import statements occur immediately following the package statement (if it
exists) and before any class definitions.

import pkg1[.pkg2].(classname|*);

Ex:

import java.util.Date; import java.io.*

importing package member

Test.java

package cse.p1;
public class Test
{
public void print()
{
System.out.println("Hello");
}
}

PackAccess.java (Importing package member)

package cse.p2;
import cse.p1.Test;
class B extends Test
{

}
class PackAccess
{
public static void main(String a[]) importing Entire package
{
Test t = new Test(); package cse.p2;
t.print();
import cse.p1.*;
B b = new
B();b.print();
}
}

Encapsulation (Access Control)

Encapsulation provides two features:


1. It links data with the code it manipulates.
2. Access control

Access Control (private, public, protected and default access)

➢ Java access modifiers control which classes, methods, interfaces, constructors, and variables are
visible, which is essential for security and encapsulation. Thus, tthrough encapsulation, we can
control what parts of a program can access the members of a class.
➢ By controlling access, you can prevent misuse.
➢ Java uses access modifier to determine how a member can be accessed.
➢ Java provides three access modifiers – private, public and protected.
➢ Java also provides default (package-private) access level.
➢ Proficiency with these modifiers guarantees secure data protection and effective communication
between Java components.

private
When a member of a class is specified as private, then that member can only be accessed by
other members of its class.

public
When a member of a class is specified as public, then that member be accessed by any other
code.

Protected
protected applies only when inheritance is involved.
• The protected modifier allows subclass members to access their superclass's protected fields and functions,
promoting code reuse and extension.
• It makes members accessible to subclasses and other classes in the same package, preserving encapsulation
while providing restricted visibility.
• It also enables hierarchical relationships by allowing subclasses to inherit and override superclass methods,
encouraging flexibility and modular design.

default access

In Java, the default access modifier is applied automatically to classes, methods, and data
members when no access modifier is specified. This indicates that specific parts are only
accessible from within the package in which they are defined. When no access modifier is
used, then by default the member of a class is public within itsown package, but cannot be
accessed outside of its package.

• Subclass access for protected:


It allows access when subclassing, even if the subclass resides in a different package. However,
access is limited to inherited members.
• Default access (no modifier):
Often called "package-private." It's the default if no access modifier is specified.
• Private: Strictly confined to the declaring class.

/* This program demonstrates the difference between public and private. */


class Test {
int a; // default access
public int b; // public access
private int c; // private access

// methods to access c
void setc(int i) {
// set c's value
c = i;
}
int getc() {
// get c's value
return c;
}
}
class AccessTest {
public static void main(String args[])
{Test ob = new Test();

// These are OK, a and b may be accessed directly


ob.a = 10; ob.b = 20;

// This is not OK and will cause an error


//ob.c = 100; // Error!

// You must access c through its methods


ob.setc(100); // OK
System.out.println("a, b, and c: " + ob.a + " " + ob.b + " " + ob.getc());
}
}

Using Protected specifier

// Base class
class Vehicle {
protected String brand; // protected member variable
protected void displayDetails()
{
System.out.println("Brand: " + brand);
}
}

// Derived class
class Car extends Vehicle {
private int mileage; // private member variable specific to Car
public Car(String brand, int mileage) {
this.brand = brand; // accessing protected member from superclass
this.mileage = mileage;
}
public void displayCarDetails() {
displayDetails(); // accessing protected method from superclass
System.out.println("Mileage: " + mileage);
}
}
// Main class to test inheritance and protected access
class Main {
public static void main(String[] args) {
Car myCar = new Car("Toyota", 30);
myCar.displayCarDetails();
}
}
O/p: Brand: Toyota
Mileage: 30
Java Access Modifiers with Method Overriding
1. Access Modifier Rules in Overriding
• Cannot reduce visibility: The overridden method in the subclass must have the same or
higher visibility compared to the method in the superclass.
• Can increase visibility: For example, a protected method in the superclass can be
overridden as public in the subclass.
2. Modifier Behavior with Overriding

class SuperClass {
protected void display() {
System.out.println("Superclass display method");
}
}
class SubClass extends SuperClass {
@Override
public void display() { // Increasing visibility from protected to public
System.out.println("Subclass display method");
}
}
public class Test {
public static void main(String[] args) {
SuperClass obj = new SubClass(); // Polymorphism in action
obj.display(); // Outputs: Subclass display method
}
}
Output
Subclass display method

Static

Static is used to access a member by itself, without reference to a specific instance.


When a member is declared static, it can be accessed before any objects of its class are
created, and without reference to any object.

Things can be declared as static

1. Variables
2. Methods
3. Static blocks
4. Nested classes

Things can not be declared as static

1. Local variables
2. classes
3. constructor

static variables (class variables)

➢ Instance variables declared as static are, essentially, global variables.


➢ When objects of its class are declared, no copy of a static variable is made.
➢ Instead, all instances of the class share the same static variable.

static methods

Methods declared as static have several restrictions:

➢ They can only directly call other static methods.


➢ They can only directly access static data.
➢ They cannot refer to this or super in any way.

Static blocks (OR) static initialization block

➢ Static blocks are used to initialize the static variables.


➢ Static block gets executed exactly once, when the class is first loaded.

// Demonstrate static variables, methods, and blocks.


class UseStatic {
static int a = 3;
static int b; Order:

Static variables
static void meth(int x) { Static blocks
System.out.println("x = " + Static methods (first main() then other
x);System.out.println("a = " + methods)
a);System.out.println("b = " +
b);
}

Output:
static
{ System.out.println("Static block
initialized.");b = a * 4; Inside the same class, we can access
static members directly

} Outside the class, we can access the


static members,using the format:
public static void main(String args[])
{meth(42);
}
}
Interfaces

Interfaces are like a 100-percent abstract superclass. An interface is a contract. An Interface in


Java programming language is defined as an abstract type used to specify the behavior of a class. An
interface in Java is a blueprint of a behavior. A Java interface contains static constants and abstract
methods.
The interface in Java is a mechanism to achieve abstraction. There can be only abstract methods in the Java
interface, not the method body. It is used to achieve abstraction and multiple inheritances in Java using
Interface. In other words, you can say that interfaces can have abstract methods and variables. It cannot have
a method body. Java Interface also represents the IS-A relationship.
When we decide on a type of entity by its behavior and not via attribute we should define it as an interface.

Definition: An interface is a reference type, similar to a class, that can contain only constants,
method signatures, default methods, static methods.
➢ Using interface, we can specify what a class must do, but not how it does it.
➢ Method bodies exist only for default methods and static methods.
➢ Interfaces cannot be instantiated—they can only be implemented by classes
or extended by other interfaces.
➢ Using interfaces, Java achieves the run time polymorphism - “one interface,
multiple methods” aspect of polymorphism.

Defining an Interface

access interface name {


// constants
type final-varname = value; 1. access can be only default or
public.
//abstract methods
2. Variables defines inside an
return-type method-name(parameter-list); interface are implicitly public, final
//default methods and static, they must also be
initialized.
default type method-name(parameter-list)
3. All methods and variables are
{
implicitly public.
//body
Example:
}
//static methods public interface IntStack
{
static type method-name(parameter-list) void push(int n);
int pop();
}
{
//body
}
}

Implementing Interfaces
Once an interface has been defined, one or more classes can implement that interface.
implements
class classname [extends superclass] [implements interface [,interface...]]
{
// class-body
}

Note: When we implement an interface method, it must be declared as public.


Example:
import java.io.*;

// A simple interface
interface In1 {

// public, static and final


final int a = 10;

// public and abstract


void display();
}

// A class that implements the interface.


class TestClass implements In1 {

// Implementing the capabilities of


// interface.
public void display(){
System.out.println("Hello");
}

// Driver Code
public static void main(String[] args)
{
TestClass t = new TestClass();
t.display();
System.out.println(a);
}
}

Output
Hello
10

Interfaces properties
1) Interfaces are implicitly abstract.
2) All interface methods are implicitly public and abstract.
3) All variables defined in an interface must be public, static, and final
4) Because interface methods are abstract, they cannot be marked final.
5) An interface can extend one or more other interfaces.
6) An interface can’t extend anything except another interface.
7) An interface cannot implement another interface or class.
8) An interface must be declared with the keyword interface.
9) Interface types can be used polymorphically .

Multiple Inheritance in Java Using Interface


Multiple Inheritance is an OOPs concept that can’t be implemented in Java using classes. But we can use multiple
inheritances in Java using Interface.

Assume, we have a class that implements two interfaces. If each of these interfaces providesdefault
methods, then some behavior is inherited from both. Thus, to a limited extent, defaultmethods do
support multiple inheritance of behavior.

For example, assume that two interfaces called Alpha and Beta are implemented by a class
called MyClass.

1. What happens if both Alpha and Beta provide a method called reset( ) for which both
declare a default implementation?

2. Beta extends Alpha. Then Which version of the default method is used?

3. If MyClass provides its own implementation of the method?

To handle the above situations, Java defines a set of rules that resolves such conflicts.

Rule 1: In all cases, a class implementation takes priority over an interface default
implementation.

Rule 2: In cases in which a class implements two interfaces that both have the same default
method, but the class does not override that method, then an error will result.

Rule 3: In cases in which one interface inherits another, with both defining a common default
method, the inheriting interface’s version of the method takes precedence.

If Beta extends Alpha, then Beta’s version of reset( ) will be used.

// Java program to demonstrate How Diamond Problem


// Is Handled in case of Default Methods

// Interface 1
interface API {
// Default method
default void show()
{

// Print statement
System.out.println("Default API");
}
}

// Interface 2
// Extending the above interface
interface Interface1 extends API {
// Abstract method
void display();
}

// Interface 3
// Extending the above interface
interface Interface2 extends API {
// Abstract method
void print();
}

// Main class
// Implementation class code
class TestClass implements Interface1, Interface2 {
// Overriding the abstract method from Interface1
public void display()
{
System.out.println("Display from Interface1");
}
// Overriding the abstract method from Interface2
public void print()
{
System.out.println("Print from Interface2");
}
// Main driver method
public static void main(String args[])
{
// Creating object of this class
// in main() method
TestClass d = new TestClass();

// Now calling the methods from both the interfaces


d.show(); // Default method from API
d.display(); // Overridden method from Interface1
d.print(); // Overridden method from Interface2
}
}

Output
Default API

Extending Interfaces
One interface can inherit another by use of the keyword extends. The syntax is the same as for
inheriting classes.
When a class implements an interface that inherits another interface, it must provide
implementations for all methods required by the interface inheritance chain.
// One interface can extend another.

interface A {
void
meth1();void
meth2();
}
// B now includes meth1() and meth2() -- it adds meth3().
interface B extends A {
void meth3();
}
// This class must implement all of A and
Bclass MyClass implements B {
public void meth1()
{ System.out.println("Implement meth1().");
}
public void meth2() {
System.out.println("Implement meth2().");
}

public void meth3() {


System.out.println("Implement meth3().");
}
}
class IFExtend {
public static void main(String arg[]) {
MyClass ob = new
MyClass();ob.meth1();
ob.meth2();
ob.meth3();
}
}

Default Interface Methods (extension method)

This is the new feature added in JDK8.

Reason for adding Default method

1. To expand the capabilities of an interface


2. To define optional methods

// Java program to show that interfaces can


// have methods from JDK 1.8 onwards

interface In1
{
final int a = 10;
default void display()
{
System.out.println("hello");
}
}

// A class that implements the interface.


class TestClass implements In1
{
// Driver Code
public static void main (String[] args)
{
TestClass t = new TestClass();
t.display();
}
}
Output
hello
Abstract class vs interface

Abstract class contains abstract and non- Interfaces do not contain non-abstract
abstract methods. methods but it contains only abstract
methods

Abstract methods contains instance variables Interfaces do not contain instance variables, it
and constants. contains only constants.

Abstract methods needs to be declared as All methods are implicitly public and abstract.
abstract explicitly.

Class needs to be declared abstract explicitly. Interface is abstract implicitly.

Abstract class can extends another class, not An interface can extends another interfaces
interfaces only, not classes

An abstract class can implement an interface An interface cannot implement another


interface or class.

Ex: Ex:

abstract class A{ } interface Bounceable

You might also like