UNIT I OOPS with Java
UNIT I OOPS with Java
AND ENGINEERING
LECTURE
NOTES ON
II B.TECH IV SEMESTER
(BCS-403)
1
UNIT I
What is Java
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
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.
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:
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 vs C vs C++
The Internet helped Java to the forefront of programming and Java, in turn, had a profound
effect on the Internet.
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. 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:
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.
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.
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
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
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:
JRE = The Libraries + JVM + Java Plug-in + Java Web Start + Other components
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.
1. class loader subsystem: a mechanism for loading types (classes and interfaces)
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.
Organizes a program around its code. Organizes a program around its data (that is, objects).
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.
import java.lang.System;
class ExampleProgram
{
public static void main(String[] args)
{
System.out.println(“Hello World");
}
}
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
Abstraction:
Hierarchical classifications
CAR
17
1. Encapsulation:
Encapsulation is the mechanism that binds together code and the data it manipulates,and
keeps both safe from outside interference and misuse.
Example:
18
2. Inheritance:
Inheritance is the process by which one object acquires the properties of another object.
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
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
➢ 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.
Definition:
Polymorphism in java is a concept by which we can perform a single action by
different ways.
Types of Polymorphism:
Example
v. However, because of polymorphism, in Java you can specify a general set ofstack
routines that all share the same names.
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.
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:
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
}
}
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.
AvgTemp 2count
Count high-temp
A4 Not/ok
$test
This_is_ok
Literals
Example:
Integer Literals
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
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
Example : /**
First Java Program
*/
Separators
Keywords are the reserved words which can not be used as identifiers in program.
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
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
1) Primitive types are also called as Simple types. The primitive types represent single
values.
byte b;
boolean myBooleanPrimitive;
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.
char 16 2 0 65535
28
boolean: The boolean data type has only two possible values: true and false.
Characters (char)
Example
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);
}
}
Reference Types
reference
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:
c) To declare more than one variable of the specified type, use a comma-separated list.
Example:
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;
Scope:
a) A scope determines what objects are visible to other parts of your program.
b) It also determines the lifetime of those objects.
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
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
// 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
class LifeTime {
public static void main(String args[]) {
int x;
y = 100;
System.out.println("y is now: " + y);
}
}
}
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.
(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
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
Arrays
Types of Arrays
a) One-Dimensional arrays
b) Multidimensional arrays
37
One-Dimensional arrays
Syntax:
type var-name [ ];
var-name = new type [size];
Note:
int[ ] months;
months = new int[12];
Initializing an array:
Accessing an array:
array initializer
❑ 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
[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]
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++;
}
Strings
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.
Operators
Operator Result
%= Modulus assignment
–– Decrement
3
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.
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);
}
}
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.
}
}
// 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.
➢ 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 OR
^ Bitwise exclusive OR
|= Bitwise OR assignment
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.
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 XOR operator, ^, combines bits such that if exactly one operand is 1, then the result
is 1. Otherwise, the result is zero.
0 0 0 0 0 1
1 0 1 0 1 0
0 1 1 0 1 1
1 1 1 1 0 0
The left shift operator, <<, shifts all of the bits in a value to the left a specified number of times.
Ithas this general form:
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:
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
Java’s unsigned, shift right operator, >>>, which always shifts zeros into the high-order bit.
8
int a = -1;
a = a >>> 24;
>>>24
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
int a = 4; Output:
int b = 1;
boolean c = a < b; false
The Boolean logical operators shown here operate only on boolean operands.
Operator Result
| Logical OR
|| Short-circuit OR
|= OR assignment
^= XOR assignment
== Equal to
!= Not equal to
?: Ternary if-then-else
Example
class BoolLogic {
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.
class ShortCktAnd
{
public static void main(String args[])
{
Output:
int num = 20;
int denom = 0; After if
Short-circuit OR - || (Conditional-or)
class ShortCktOr
{
public static void main(String args[])
{ Ouput:
int num = 20;
int denom = 0; Inside if
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;
➢ Both expression2 and expression3 are required to return the same (or compatible) type,
which can’t be void.
Example
// Demonstrate ?.
class Ternary {
public static void main(String args[]) Ouput:
{
int num = 20; 0
int denom = 0;
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
* / %
+ -
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.
1) selection,
2) iteration, and
3) jump.
Selection statements allow the program to choose different paths of execution based upon the
outcome of an expression or the state of a variable.
if
General form
if (condition) statement1;
else statement2;
Working of if
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;
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;
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.
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";
}
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: // ...
➢ 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
while
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
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
for(initialization; condition;
iteration)
{
// body
}
int a, b; Output:
i = 0;
for( ; !done; ) {
System.out.println( i);
if(i == 4) done =
true;i++;
}
}
for( ; ; ) {
// ... Output:
Infinite 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,
➢ 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
}
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);
Like all other programming languages, Java allows loops to be nested. That is, one loop may be
inside another.
Output:
break
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.
Example
continue
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
Class Example
class Box {
double width;
double height;
double depth;
}
Statement Effect
Box mybox;
width
depth
mybox
Box object
29
Class vs Object
class object
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.
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;
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;
Constructors
Types of Constructors
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.
2. Parameterized constructor
9);double vol;
this keyword
1. To resolve the name collisions between instance variables and local variables
2. To explicitly call a constructor from another constructor
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.
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
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.
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.
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.
Example
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());
}
}
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.
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.
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;
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;
String class
1. For every string, Java creates an object of type String. Even string constants are
actually String objects.
2. String objects are immutable.
String are created many ways, but the easiest are two ways :
37
1) Without new
operatorString s =
“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 s2 = “Java”;
String Methods
String x = “CARGO";
System.out.println( x.charAt(2) ); Output is : R
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
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
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
String x = "01234567";
System.out.println( x.length() ); Output is: 8
String x = "oxoxoxox";
System.out.println( x.replace('x', 'X') ); Output is: oXoXoXoX
String x = "0123456789";
System.out.println( x.substring(5) ); Output is: 56789
String x = "0123456789";
All objects in Java must have a toString() method, which typically returns a String that in
some meaningful way describes the object in question.
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.
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.
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.
Benefits of Inheritance
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 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.
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
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.
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.
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();
}
}
➢ 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
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
}
}
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
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
Example
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:
r = l; // r refers to a Lion
objectr.eat();
//r.eat(10); // calls Animal's version of eat(int) – compiler error
}
}
Example
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!");
}
}
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
{
//...
}
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:
Example:
Figure(double a, double b) {
dim1 = a; dim2 =
b;
}
// area is now an abstract method
abstract double area();
}
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());
}
}
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
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.
✓ 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.
package pkg1[.pkg2[.pkg3]];
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.
In addition to the access modifiers (private,public,protected and default), packages will add
another dimension to access control.
Modifier
(default)
package p1;
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 only
// System.out.println("n_pri = "4 + n_pri);
class SamePackage {
SamePackage() {
// class only
// System.out.println("n_pri = " + p.n_pri);
// class only
// System.out.println("n_pri = " + n_pri);
class OtherPackage {
OtherPackage() {
p1.Protection p = new p1.Protection();
System.out.println("other package constructor");
// class only
// System.out.println("n_pri = " + p.n_pri);
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.
3. we can use the -classpath option with java and javac to specify the path to your
classes.
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:
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:
Test.java
package cse.p1;
public class Test
{
public void print()
{
System.out.println("Hello");
}
}
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();
}
}
➢ 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.
// 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();
// 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
1. Variables
2. Methods
3. Static blocks
4. Nested classes
1. Local variables
2. classes
3. constructor
static methods
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
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
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
}
// A simple interface
interface In1 {
// 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 .
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?
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.
// 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();
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().");
}
interface In1
{
final int a = 10;
default void display()
{
System.out.println("hello");
}
}
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.
Abstract class can extends another class, not An interface can extends another interfaces
interfaces only, not classes
Ex: Ex: