1 PDF

Download as pdf or txt
Download as pdf or txt
You are on page 1of 70

1 |M.

sc sem I OOPs USING JAVA

UNIT I An overview of Java


(1) object-oriented,Programming
What is Object-Oriented Programming?
Object-oriented programming has a sweeping impact because it appeals at multiple levels and promises
faster and cheaper development and maintenance. It follows a bottom-up approach to develop
applications.

In this section, we will discuss in-depth what is object-oriented programming?

Object-Oriented Programming
The word object-oriented is the combination of two words i.e. object and oriented. The dictionary
meaning of the object is an article or entity that exists in the real world. The meaning of oriented is
interested in a particular kind of thing or entity. In layman's terms, it is a programming pattern that rounds
around an object or entity are called object-oriented programming.

The object-oriented programming is basically a computer programming design philosophy or


methodology that organizes/ models software design around data, or objects rather than functions and
logic.

An object is referred to as a data field that has unique attributes and behavior. Everything in OOP is grouped
as self-sustainable objects.

It is the most popular programming model among developers. It is well suited for programs that are large,
complex, and actively updated or maintained. It simplifies software development and maintenance by
providing major concepts such as abstraction, inheritance, polymorphism, and encapsulation. These
core concepts support OOP.

A real-world example of OOP is the automobile. It more completely illustrates the power of object-oriented
design.

Points to Remember

o Everything is an object
o Developer manipulates objects that uses message passing.
o Every object is an instance of a class.
o The class contains the attribute and behavior associated with an object.
2 |M.sc sem I OOPs USING JAVA

Pillars of OOPs
The major concepts that we have discussed above are known as pillars of OOPs. There are four pillars on
which OOP rests.

o Abstraction
o Encapsulation
o Inheritance
o Polymorphism

Let's discuss each in detail.

Abstraction
The concept allows us to hide the implementation from the user but shows only essential information to
the user. Using the concept developer can easily make changes and added over time.

There are the following advantages of abstraction:

o It reduces complexity.
o It avoids delicacy.
o Eases the burden of maintenance
o Increase security and confidentially.

Encapsulation
Encapsulation is a mechanism that allows us to bind data and functions of a class into an entity. It protects
data and functions from outside interference and misuse. Therefore, it also provides security. A class is the
best example of encapsulation.
3 |M.sc sem I OOPs USING JAVA

Inheritance
The concept allows us to inherit or acquire the properties of an existing class (parent class) into a newly
created class (child class). It is known as inheritance. It provides code reusability.

Polymorphism
The word polymorphism is derived from the two words i.e. ploy and morphs. Poly means many and
morphs means forms. It allows us to create methods with the same name but different method signatures.
It allows the developer to create clean, sensible, readable, and resilient code.

The above figure best describes the concepts of polymorphism. A person plays an employee role in the
office, father and husband role in the home.
4 |M.sc sem I OOPs USING JAVA

OOPs Concepts
The OOPs concepts include the following:

1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation

Object
An object is a real-world entity that has attributes, behavior, and properties. It is referred to as an instance
of the class. It contains member functions, variables that we have defined in the class. It occupies space in
the memory. Different objects have different states or attributes, and behaviors.

Class
A class is a blueprint or template of an object. It is a user-defined data type. Inside a class, we define
variables, constants, member functions, and other functionality. it binds data and functions together in a
single unit. It does not consume memory at run time. Note that classes are not considered as a data
structure. It is a logical entity. It is the best example of data binding. Note that a class can exist without an
object but vice-versa is not possible.

The following figure best illustrates the class and object in OOP.

Apart from these core concepts, there are some other object-oriented concepts used in OOP.

Coupling
5 |M.sc sem I OOPs USING JAVA

In programming, separation of concerns is known as coupling. It means that an object cannot directly
change or modify the state or behavior of other objects. It defines how closely two objects are connected
together. There are two types of coupling, loose coupling, and tight coupling.

Objects that are independent of one another and do not directly modify the state of other objects is called
loosely coupled. Loose coupling makes the code more flexible, changeable, and easier to work with.

Objects that depend on other objects and can modify the states of other objects are called tightly coupled.
It creates conditions where modifying the code of one object also requires changing the code of other
objects. The reuse of code is difficult in tight coupling because we cannot separate the code.

Since using loose coupling is always a good habit.

Cohesion
In OOP, cohesion refers to the degree to which the elements inside a module belong together. It measures
the strength of the relationship between the module and data. In short, cohesion represents the clarity of
the responsibilities of a module. It is often contrasted with coupling.

It focuses on a how single module or class is intended. Higher the cohesiveness of the module or class,
better is the object-oriented design.

There are two types of cohesion, i.e. High and Low.

o High cohesion is associated with several required qualities of software including robustness, reliability,
and understandability.
o Low cohesion is associated with unwanted qualities such as being difficult to maintain, test, reuse, or
even understand.

High cohesion often associates with loose coupling and vice versa.
6 |M.sc sem I OOPs USING JAVA

Composition
Composition is one of the vital concepts in OOP. It describes a class that references one or more objects
of other classes in instance variables. It allows us to model a has-a association between objects. We can
find such relationships in the real world. For example, a car has an engine. the following figure depicts the
same

The main benefits of composition are:

o Reuse existing code


o Design clean APIs
o Change the implementation of a class used in a composition without adapting any external clients.

Association
The association defines the relationship between the objects. Note that an object can be associated with
one or more than one object. The relationship can be unidirectional or bidirectional. There are the following
types of association.

o One to One
o One to Many
o Many to One, and
o Many to Many

Aggregation
It is an advanced form of association in which each object has its own Lifecycle but there exists ownership
as well. In other words, a relationship where a child can exist independently of the parent. It is also termed
as has-a relationship in Java. Like, inheritance represents the is-a relationship. It is another way to reuse
objects.
7 |M.sc sem I OOPs USING JAVA

Why should we use OOP?


Object-oriented programming is an evolutionary development in software engineering. Using OOP in
software development is a good habit because it accomplishes the three major software engineering goals,
as we have shown in the following figure.

Where it is used?
OOP is often the best use when we are dealing with manufacturing and designing applications. It provides
modularity in programming. It allows us to break down the software into chunks of small problems that
we then can solve one object at a time.

It should be used where the reusability of code and maintenance is a major concern. Because it makes
development easy and we can easily append code without affecting other code blocks. It should be used
where complex programming is a challenge.

Benefits of OOP
o Modular, scalable, extensible, reusable, and maintainable.
o It models the complex problem in a simple structure.
o Object can be used across the program.
o Code can be reused.
o We can easily modify, append code without affecting the other code blocs.
o Provides security through encapsulation and data hiding features.
o Beneficial to collaborative development in which a large project is divided into groups.
o Debugging is easy.

Limitations of OOP
o Requires intensive testing processes.
o Solving problems takes more time as compared to Procedure Oriented Programming.
8 |M.sc sem I OOPs USING JAVA

o The size of the programs created using this approach may become larger than the programs written using
the procedure-oriented programming approach.
o Software developed using this approach requires a substantial amount of pre-work and planning.
o OOP code is difficult to understand if you do not have the corresponding class documentation.
o In certain scenarios, these programs can consume a large amount of memory.
o Not suitable for small problems.
o Takes more time to solve problems.

List of Object-Oriented Programming Languages


There are various object-oriented programming languages are present. But we have enlisted some popular
and widely used OOP languages.

According to the TIOBE index, the top twenty OOP languages are Java, C++, C#, Python, R, PHP, Visual
Basic.NET, JavaScript, Ruby, Perl, Object Pascal, Objective-C, Dart, Swift, Scala, Kotlin, Common
Lisp, MATLAB, and Smalltalk.

Applications of OOPs
o Computer graphics applications
o Object-oriented database
o User-interface design such as windows
o Real-time systems
o Simulation and modeling
o Client-Server System
o Artificial Intelligence System
o CAD/CAM Software
o Office automation system

(2) Classes, and objects


object and class
There are many differences between object and class. A list of differences between object and class are
given below:

No. Object Class


9 |M.sc sem I OOPs USING JAVA

1) Object is an instance of a class. Class is a blueprint or


template from which objects are
created.

2) Object is a real world entity such as pen, laptop, mobile, bed, Class is a group of similar objects.
keyboard, mouse, chair etc.

3) Object is a physical entity. Class is a logical entity.

4) Object is created through new keyword mainly e.g. Class is declared using class
Student s1=new Student(); keyword e.g.
class Student{}

5) Object is created many times as per requirement. Class is declared once.

6) Object allocates memory when it is created. Class doesn't allocated memory


when it is created.

7) There are many ways to create object in java such as new keyword, There is only one way to define
newInstance() method, clone() method, factory method and class in java using class keyword.
deserialization.

Let's see some real life example of class and object in java to understand the difference well:

Class: Human Object: Man, Woman

Class: Fruit Object: Apple, Banana, Mango, Guava wtc.

Class: Mobile phone Object: iPhone, Samsung, Moto

Class: Food Object: Pizza, Burger, Samosa

(3) VARIABLES
Variables
A variable is a container which holds the value while the Java program is executed. A variable is assigned
with a data type.

Variable is a name of memory location. There are three types of variables in java: local, instance and static.

There are two types of data types in Java: primitive and non-primitive.
10 |M.sc sem I OOPs USING JAVA

Variable
A variable is the name of a reserved area allocated in memory. In other words, it is a name of the memory
location. It is a combination of "vary + able" which means its value can be changed.

1. int data=50;//Here data is variable

Types of Variables
There are three types of variables in Java:

o local variable
o instance variable
o static variable

1) Local Variable

A variable declared inside the body of the method is called local variable. You can use this variable only
within that method and the other methods in the class aren't even aware that the variable exists.

A local variable cannot be defined with "static" keyword.


11 |M.sc sem I OOPs USING JAVA

2) Instance Variable

A variable declared inside the class but outside the body of the method, is called an instance variable. It is
not declared as static.

It is called an instance variable because its value is instance-specific and is not shared among instances.

3) Static variable

A variable that is declared as static is called a static variable. It cannot be local. You can create a single copy
of the static variable and share it among all the instances of the class. Memory allocation for static variables
happens only once when the class is loaded in the memory.

Example to understand the types of variables in java

1. public class A
2. {
3. static int m=100;//static variable
4. void method()
5. {
6. int n=90;//local variable
7. }
8. public static void main(String args[])
9. {
10. int data=50;//instance variable
11. }
12. }//end of class

Java Variable Example: Add Two Numbers


1. public class Simple{
2. public static void main(String[] args){
3. int a=10;
4. int b=10;
5. int c=a+b;
6. System.out.println(c);
7. }
8. }

Output:

20

Java Variable Example: Widening


12 |M.sc sem I OOPs USING JAVA

1. public class Simple{


2. public static void main(String[] args){
3. int a=10;
4. float f=a;
5. System.out.println(a);
6. System.out.println(f);
7. }}

Output:

10
10.0

Java Variable Example: Narrowing (Typecasting)


1. public class Simple{
2. public static void main(String[] args){
3. float f=10.5f;
4. //int a=f;//Compile time error
5. int a=(int)f;
6. System.out.println(f);
7. System.out.println(a);
8. }}

Output:

10.5
10

Java Variable Example: Overflow


1. class Simple{
2. public static void main(String[] args){
3. //Overflow
4. int a=130;
5. byte b=(byte)a;
6. System.out.println(a);
7. System.out.println(b);
8. }}

Output:

130
-126
13 |M.sc sem I OOPs USING JAVA

Java Variable Example: Adding Lower Type


1. class Simple{
2. public static void main(String[] args){
3. byte a=10;
4. byte b=10;
5. //byte c=a+b;//Compile Time Error: because a+b=20 will be int
6. byte c=(byte)(a+b);
7. System.out.println(c);
8. }}

Output:

20

(4) constants
What is constant?
Constant is a value that cannot be changed after assigning it. Java does not directly support the constants.
There is an alternative way to define the constants in Java by using the non-access modifiers static and
final.

How to declare constant in Java?


In Java, to declare any variable as constant, we use static and final modifiers. It is also known as non-
access modifiers. According to the Java naming convention the identifier name must be in capital letters.

Static and Final Modifiers

o The purpose to use the static modifier is to manage the memory.


o It also allows the variable to be available without loading any instance of the class in which it is defined.
o The final modifier represents that the value of the variable cannot be changed. It also makes the primitive
data type immutable or unchangeable.

The syntax to declare a constant is as follows:

1. static final datatype identifier_name=value;

For example, price is a variable that we want to make constant.


14 |M.sc sem I OOPs USING JAVA

1. static final double PRICE=432.78;

Where static and final are the non-access modifiers. The double is the data type and PRICE is the identifier
name in which the value 432.78 is assigned.

In the above statement, the static modifier causes the variable to be available without an instance of its
defining class being loaded and the final modifier makes the variable fixed.

Here a question arises that why we use both static and final modifiers to declare a constant?

If we declare a variable as static, all the objects of the class (in which constant is defined) will be able to
access the variable and can be changed its value. To overcome this problem, we use the final modifier with
a static modifier.

When the variable defined as final, the multiple instances of the same constant value will be created for
every different object which is not desirable.

When we use static and final modifiers together, the variable remains static and can be initialized once.
Therefore, to declare a variable as constant, we use both static and final modifiers. It shares a common
memory location for all objects of its containing class.

Why we use constants?


The use of constants in programming makes the program easy and understandable which can be easily
understood by others. It also affects the performance because a constant variable is cached by both JVM
and the application.

Points to Remember:

o Write the identifier name in capital letters that we want to declare as constant. For example, MAX=12.
o If we use the private access-specifier before the constant name, the value of the constant cannot be changed
in that particular class.
o If we use the public access-specifier before the constant name, the value of the constant can be changed in
the program.

Let's see some examples in which we have used constants.

Example 1: Declaring Constant as Private


ConstantExample1.java

1. import java.util.Scanner;
2. public class ConstantExample1
3. {
4. //declaring constant
5. private static final double PRICE=234.90;
15 |M.sc sem I OOPs USING JAVA

6. public static void main(String[] args)


7. {
8. int unit;
9. double total_bill;
10. System.out.print("Enter the number of units you have used: ");
11. Scanner sc=new Scanner(System.in);
12. unit=sc.nextInt();
13. total_bill=PRICE*unit;
14. System.out.println("The total amount you have to deposit is: "+total_bill);
15. }
16. }

Output:

Example 2:
ConstantExample2.java

1. public class ConstantExample2


2. {
3. private static final double PRICE=2999;
4. public static void main(String[] args)
5. {
6. System.out.println("Old Price of Iron: "+PRICE);
7. ConstantExample obj = new ConstantExample();
8. obj.showPrice();
9. }
10. }
11. class ConstantExample
12. {
13. private static final double PRICE=3599;
14. void showPrice()
15. {
16. System.out.print("New Price of Iron: "+PRICE);
17. }
18. }

Example 3: Declaring Constant as Public


16 |M.sc sem I OOPs USING JAVA

In the following example, we have declared constant PI as public. Inside the main() method, we have
assigned 3.15 in the constant PI. After that, we have invoked the printValue() method. When we execute
the program, it shows an error cannot assign a value to the final variable PI.

ConstantExample3.java

1. public class ConstantExample3


2. {
3. //declaring PI as constant
4. public static final double PI= 3.14;
5. public static void main(String[] args)
6. {
7. printValue();
8. //trying to assign 3.15 in the constant PI
9. PI = 3.15;
10. printValue();
11. }
12. void printValue()
13. {
14. System.out.print("The value of PI cannot be changed to " + PI);
15. }
16. }

Output:

Using Enumeration (Enum) as Constant


o It is the same as the final variables.
o It is a list of constants.
o Java provides the enum keyword to define the enumeration.
o It defines a class type by making enumeration in the class that may contain instance variables, methods, and
constructors.

Example of Enumeration

1. public class EnumExample


2. {
3. //defining the enum
4. public enum Color {Red, Green, Blue, Purple, Black, White, Pink, Gray}
5. public static void main(String[] args)
6. {
17 |M.sc sem I OOPs USING JAVA

7. //traversing the enum


8. for (Color c : Color.values())
9. System.out.println(c);
10. }
11. }

(5) Data Types


Data Types in Java
Data types specify the different sizes and values that can be stored in the variable. There are two types of
data types in Java:

1. Primitive data types: The primitive data types include boolean, char, byte, short, int, long, float and double.
2. Non-primitive data types: The non-primitive data types include Classes, Interfaces, and Arrays.

Java Primitive Data Types


In Java language, primitive data types are the building blocks of data manipulation. These are the most
basic data types available in Java language.

Java is a statically-typed programming language. It means, all variables must be declared before its use. That
is why we need to declare variable's type and name.

There are 8 types of primitive data types:

o boolean data type


o byte data type
o char data type
o short data type
o int data type
o long data type
o float data type
o double data type
18 |M.sc sem I OOPs USING JAVA

Data Type Default Value Default size

boolean false 1 bit

char '\u0000' 2 byte

byte 0 1 byte

short 0 2 byte

int 0 4 byte

long 0L 8 byte

float 0.0f 4 byte

double 0.0d 8 byte

Boolean Data Type


The Boolean data type is used to store only two possible values: true and false. This data type is used for
simple flags that track true/false conditions.

The Boolean data type specifies one bit of information, but its "size" can't be defined precisely.

Example:

1. Boolean one = false


19 |M.sc sem I OOPs USING JAVA

Byte Data Type


The byte data type is an example of primitive data type. It isan 8-bit signed two's complement integer. Its
value-range lies between -128 to 127 (inclusive). Its minimum value is -128 and maximum value is 127. Its
default value is 0.

The byte data type is used to save memory in large arrays where the memory savings is most required. It
saves space because a byte is 4 times smaller than an integer. It can also be used in place of "int" data type.

Example:

1. byte a = 10, byte b = -20

Short Data Type


The short data type is a 16-bit signed two's complement integer. Its value-range lies between -32,768 to
32,767 (inclusive). Its minimum value is -32,768 and maximum value is 32,767. Its default value is 0.

The short data type can also be used to save memory just like byte data type. A short data type is 2 times
smaller than an integer.

Example:

1. short s = 10000, short r = -5000

Int Data Type


The int data type is a 32-bit signed two's complement integer. Its value-range lies between - 2,147,483,648
(-2^31) to 2,147,483,647 (2^31 -1) (inclusive). Its minimum value is - 2,147,483,648and maximum value is
2,147,483,647. Its default value is 0.

The int data type is generally used as a default data type for integral values unless if there is no problem
about memory.

Example:

1. int a = 100000, int b = -200000

Long Data Type


The long data type is a 64-bit two's complement integer. Its value-range lies between -
9,223,372,036,854,775,808(-2^63) to 9,223,372,036,854,775,807(2^63 -1)(inclusive). Its minimum value is -
9,223,372,036,854,775,808and maximum value is 9,223,372,036,854,775,807. Its default value is 0. The long
data type is used when you need a range of values more than those provided by int.

Example:

1. long a = 100000L, long b = -200000L


20 |M.sc sem I OOPs USING JAVA

Float Data Type


The float data type is a single-precision 32-bit IEEE 754 floating point.Its value range is unlimited. It is
recommended to use a float (instead of double) if you need to save memory in large arrays of floating
point numbers. The float data type should never be used for precise values, such as currency. Its default
value is 0.0F.

Example:

1. float f1 = 234.5f

Double Data Type


The double data type is a double-precision 64-bit IEEE 754 floating point. Its value range is unlimited. The
double data type is generally used for decimal values just like float. The double data type also should never
be used for precise values, such as currency. Its default value is 0.0d.

Example:

1. double d1 = 12.3

Char Data Type


The char data type is a single 16-bit Unicode character. Its value-range lies between '\u0000' (or 0) to '\uffff'
(or 65,535 inclusive).The char data type is used to store characters.

Example:

1. char letterA = 'A'

Why char uses 2 byte in java and what is \u0000 ?


It is because java uses Unicode system not ASCII code system. The \u0000 is the lowest range of Unicode
system. To get detail explanation about Unicode visit next page

(6) Primitive Data Type


Primitive is the most fundamental data type usable in the Programming language. There are eight
primitive data types: Boolean, byte, character, short, int, long, float, and double. In a Programming
language, these data types serve as the foundation for data manipulation.

All basic data types are built-in into the majority of programming languages. Furthermore, many languages
provide a set of composite data types. Primitive data types may or may not have a one-to-one
correspondence with objects in the computer's memory, depending on the language and its
implementation. However, operations on basic primitive data types are typically thought to be the fastest
language constructs.
21 |M.sc sem I OOPs USING JAVA

For example, integer addition can be performed as a single machine instruction, and some processors
provide specific instructions for processing character sequences with a single instruction. The C standard
specifically states that "a 'plain' int object has the natural size suggested by the execution environment's
architecture". On a 32-bit architecture, this means that int will most likely be 32 bits long. Value types are
always basic primitive types.

Most programming languages do not allow programmes to change the behaviour or capabilities of
primitive (built-in or basic) data types. Smalltalk is an exception, allowing all data types to be extended
within a programme, expanding the operations that can be performed on them or even redefining the
built-in operations.

Such data types serve a single purpose: they contain pure, simple values of a type. Because these data
types are defined by default in the Programming languages type system, they come with a set of predefined
operations. Such primitive types cannot have new operations defined. There are three more types of
primitives in the Java type system:

1. Short, int, long, float, and double are the numerical primitives. These primitive data types can only store
numbers. Simple arithmetic (addition, subtraction, etc.) or comparison operations are associated with such
data types (greater than, equal to, etc.)
2. Textual primitives include bytes and characters. Characters are stored in these primitive data types (that can
be Unicode alphabets or even numbers). Textual manipulation operations are associated with data types
(comparing two words, joining characters to make words, etc.). However, byte and char can perform
arithmetic operations as well.
3. Primitives with boolean and null values: boolean and null.

The actual number of primitive data types available is determined by the programming language that is
used. Strings, for instance, are a composite but built-in data type in C#, even as they are integrated to a
primitive data type that is both basic and built-in in advanced accents of BASIC and JavaScript.

Considering the Java Programming language, the primitive data structures include integers, floats,
characters, and pointers. In general, there are 8 data types. They are as follows:

o Boolean data type


o byte data type
o char data type
o short data type
o int data type
o long data type
o float data type
o double data type
22 |M.sc sem I OOPs USING JAVA

Boolean Data Type


A Boolean data type comprises a single bit of information that can only store true or false values. True or
false conditions are tracked using this data type, and Boolean data types are also used to store the result
of various conditions. Let's write a small program and see how it works.

1. class booleanDataType{
2. public static void main(String args[]){
3. // Setting the values for boolean data type
4. boolean Java = true;
5. boolean Python = false;
6. System.out.println(Java); // Output will be true
7. System.out.println(Python); // Output will be false
8. }
9. }

Byte Data Type


The byte data type is an illustration of a primitive data type. It is a signed two's complement integer of 8
bits, and it stores whole numbers ranging from -128 to 127. A byte data type is useful for saving large
amounts of memory. Let's write a small program and see how it works.

1. class ByteExample {
2. public static void main(String[] args) {
3. byte n, a;
4. n = 127;
5. a=177;
6. System.out.println(n); // prints 127
7. System.out.println(a); // throws an error because it cannot store more than 127 bits
8. }
9. }

Char Data Type


A single character is stored in this data type, and the character must be enclosed in single quotes, such as
'E' or 'e'. You can also use ASCII values to display specific characters. Let's look at a simple example to see
how it works.

1. public class PrimitiveDataType{


2. public static void main(String[] args) {
3. //storing a single character
4. char alpha = 'J';
5. //storing the ASCII of the respective character or alphabets
6. char a = 65;
23 |M.sc sem I OOPs USING JAVA

7. char b = 66,
8. char c = 67;
9. System.out.println(alpha); // prints J
10. System.out.println(a); // Displays 65
11. System.out.println(b); // Displays 66
12. System.out.println(c); // Displays 67
13.
14. }//end of main function
15. }//end of PrimitiveDataType class

Short Data Type


A short data type is larger than a byte but smaller than an integer, and it saves values ranging from -32,768
to 32767. This data type's default size is 2 bytes. Let's look at an example to understand the short data type
better.

1. public class PrimitiveDataType{


2. public static void main(String[] args) {
3. short n= 3435,
4. System.out.println(n); // prints the value present in n i.e. 3435
5.
6. }//end of main function
7. }//end of PrimitiveDataType class

Int Data Type


This data type is capable of storing whole numbers ranging from -2147483648 to 2147483647. When
creating variables with numeric values, int is generally the preferred data type.

1. public class PrimitiveDataType{


2. public static void main(String[] args) {
3. int num = 5464564;
4. System.out.println(num); // prints 5464564
5. }//end of main function
6. }//end of PrimitiveDataType class

Long Data Type


This data type is a two's complement 64-bit integer. A long data type's default size is 64 bits, and its value
ranges from -263 to 263-1.

1. public class PrimitiveDataType{


2. public static void main(String[] args) {
3. // a variable named num of long is created to store the long value
4. long num = 15000000000L;
24 |M.sc sem I OOPs USING JAVA

5. // The output of the below System.out.println will print 15000000000 that is the value stored in num
6. System.out.println(num);
7. // a variable named num1 of long is created to store the long value
8. long num1 = 897155L;
9. // The output of the below System.out.println will print 897155 that is the value stored in num1
10. System.out.println(num);
11. }//end of main function
12. }//end of PrimitiveDataType class

Float Data Type


It would be best to use a floating-point type when you need a number with a decimal, such as 8.88 or
3.14515.

This data type supports fractional numbers ranging from 3.4e038 to 3.4e+038. It is important to note that
the value should end with an "f." Let's look at a specific example to understand this data type better.

1. public class PrimitiveDataType{


2. public static void main(String[] args) {
3. // a variable named num of float type is created to store the float value
4. float num =67;
5. // The output of the below System.out.println will print 897155 that is the value stored in num
6. System.out.println(num); // prints the floating number value
7. }//end of main function
8. }//end of PrimitiveDataType class

Double Data Type


The double data type can store fractional numbers from 1.7e-308 to 1.7e+308. Note that you should end
the value with a "d":

1. public class PrimitiveDataType{


2. public static void main(String[] args) {
3. // a variable named num of double type is created to store the double value
4. double num = 79.678d;
5. // The output of the below System.out.println will print 79.678 that is the value stored in num
6. System.out.println(num); // prints the double number value
7. }//end of main function
8. }//end of PrimitiveDataType class

(7) Primitive vs non-primitive data


structure
25 |M.sc sem I OOPs USING JAVA

Primitive vs non-primitive data structure


Data structure means organizing the data in the memory. The data can be organized in two ways either
linear or non-linear way.

There are two types of data structure available for the programming purpose:

o Primitive data structure


o Non-primitive data structure

Primitive data structure is a fundamental type of data structure that stores the data of only one type
whereas the non-primitive data structure is a type of data structure which is a user-defined that stores the
data of different types in a single entity.

In the above image, we can observe the classification of the data structure. The data structure is classified
into two types, i.e., primitive and non-primitive data structure. In the case of primitive data structure, it
contains fundamental data types such as integer, float, character, pointer, and these fundamental data
types can hold a single type of value. For example, integer variable can hold integer type of value, float
variable can hold floating type of value, character variable can hold character type of value whereas the
pointer variable can hold pointer type of value.

In the case of non-primitive data structure, it is categorized into two parts such as linear data structure and
non-linear data structure. Linear data structure is a sequential type of data structure, and here sequential
means that all the elements in the memory are stored in a sequential manner; for example, element stored
after the second element would be the third element, the element stored after the third element would be
the fourth element and so on. We have different linear data structures holding the sequential values such
as Array, Linked list, Stack, Queue.

Non-linear data structure is a kind of random type of data structure. The non-linear data structures are
Tree and Graph.
26 |M.sc sem I OOPs USING JAVA

Let's understand the differences between the primitive and non-primitive data structure.

Primitive data structure Non-primitive data structure

Primitive data structure is a kind of data structure Non-primitive data structure is a type of data structure that
that stores the data of only one type. can store the data of more than one type.

Examples of primitive data structure are integer, Examples of non-primitive data structure are Array, Linked
character, float. list, stack.

Primitive data structure will contain some value, i.e., Non-primitive data structure can consist of a NULL value.
it cannot be NULL.

The size depends on the type of the data structure. In case of non-primitive data structure, size is not fixed.

It starts with a lowercase character. It starts with an uppercase character.

Primitive data structure can be used to call the Non-primitive data structure cannot be used to call the
methods. methods.

Primitive data structure


Primitive data structure is a data structure that can hold a single value in a specific location whereas the
non-linear data structure can hold multiple values either in a contiguous location or random locations

The examples of primitive data structure are float, character, integer and pointer. The value to the primitive
data structure is provided by the programmer. The following are the four primitive data structures:

o Integer: The integer data type contains the numeric values. It contains the whole numbers that can be either
negative or positive. When the range of integer data type is not large enough then in that case, we can use
long.
o Float: The float is a data type that can hold decimal values. When the precision of decimal value increases
then the Double data type is used.
o Boolean: It is a data type that can hold either a True or a False value. It is mainly used for checking the
condition.
o Character: It is a data type that can hold a single character value both uppercase and lowercase such as 'A'
or 'a'.

Non-primitive data structure


27 |M.sc sem I OOPs USING JAVA

The non-primitive data structure is a kind of data structure that can hold multiple values either in a
contiguous or random location. The non-primitive data types are defined by the programmer. The non-
primitive data structure is further classified into two categories, i.e., linear and non-linear data structure.

In case of linear data structure, the data is stored in a sequence, i.e., one data after another data. When we
access the data from the linear data structure, we just need to start from one place and will find other data
in a sequence.

The following are the types of linear data structure:

o Array: An array is a data structure that can hold the elements of same type. It cannot contain the elements
of different types like integer with character. The commonly used operation in an array is insertion, deletion,
traversing, searching.

For example:

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

The above example is an array that contains the integer type elements stored in a contiguous manner.

o String: String is defined as an array of characters. The difference between the character array and string is
that the string data structure terminates with a 'NULL' character, and it is denoted as a '\0'.

String data structure:

1. char name[100] = "Hello javaTpoint";

In the above example, the length of the string is 17 as the last character is the NULL character which denotes
the termination of the string.

Char Representation:

1. char name[100] = {'H', 'e', 'l','l','o',' ', 'j', 'a', 'v', 'a', 't','p', 'o', 'i', 'n', 't' }

In the above example, the length of the string is 16 as it does not have any NULL character as the last
character to denote the termination.

o Stack: Stack is a data structure that follows the principle LIFO (Last In First Out). All the operations on the
stack are performed from the top of the stack such as PUSH and POP operation. The push operation is the
process of inserting element into the stack while the pop operation is the process of removing element from
the stack. The stack data structure can be implemented by using either array or linked list.
o Queue: Queue is a data structure that can be implemented by using array. The difference between the stack
and queue data structure is that the elements in the queue are inserted from the rear end while the elements
in the queue are removed from the front end.
28 |M.sc sem I OOPs USING JAVA

(8) Non-primitive data types


Data types define the type of data that is stored in the variable. The type specifies the kind of data (different
sizes and values).

Java programming language has two types of data types

1. Primitive data types (predefined data types)


2. Non-primitive data types

In this section, we will understand the non-primitive data types, their uses and implementation in Java.

Non-primitive data types


Unlike primitive data types, these are not predefined. These are user-defined data types created by
programmers. These data types are used to store multiple values.

For example, consider an array that stores a group of values. Class is also a primitive type that stores
different methods and variables. Therefore, these are also called as advanced data types in Java.

Whenever a non-primitive data type is defined, it refers a memory location where the data is stored in heap
memory i.e., it refers to the memory location where an object is placed. Therefore, a non-primitive data
type variable is also called referenced data type or simply object reference variable.

An object reference variable lives on the stack memory and the object to which it points always lives on
the heap memory. The stack holds a pointer to the object on the heap.

In Java programming, all non-primitive data types are simply called objects that are created by instantiating
a class.

Key points:

1. The default value of any reference variable is null.


2. Whenever we are passing a non-primitive data type to a method, we are passing the address of that object
where the data is stored.

Types of Non-primitive data types


There are five types of non-primitive data types in Java. They are as follows:

1. Class
2. Object
3. String
4. Array
29 |M.sc sem I OOPs USING JAVA

5. Interface

1. Class and objects:


A class in Java is a user defined data type i.e. it is created by the user. It acts a template to the data which
consists of member variables and methods.

An object is the variable of the class, which can access the elements of class i.e. methods and variables.

Example:

In the following example, we are creating a class containing the variables and methods ( add() and sub() ).
Here, we are accessing the methods using the object of the Class obj.

ClassExample.java

1. public class ClassExample {


2.
3. // defining the variables of class
4. int a = 20;
5. int b = 10;
6. int c;
7.
8. // defining the methods of class
9. public void add () {
10. int c = a + b;
11. System.out.println("Addition of numbers is: " + c);
12. }
13.
14. public void sub () {
15. int c = a - b;
16. System.out.println("Subtraction of numbers is: " + c);
17. }
18.
19. // main method
20. public static void main (String[] args) {
21. // creating the object of class
22. ClassExample obj = new ClassExample();
23.
24. // calling the methods
25. obj.add();
26. obj.sub();
27. }
30 |M.sc sem I OOPs USING JAVA

28. }

Output:

2. Interface:
An interface is similar to a class however the only difference is that its methods are abstract by default i.e.
they do not have body. An interface has only the final variables and method declarations. It is also called a
fully abstract class.

Note: If the class implements an interface, it must implement all the methods of that interface. If not,
we must declare the class as abstract.

Example:

In the following example, we are creating the interface CalcInterface with two abstract methods ( multiply()
and divide() ). Here, the class InterfaceExample implements the interface and further defines the methods
of that interface. Then, the object of class is used to access those methods.

InterfaceExample.java

1. interface CalcInterface {
2. void multiply();
3. void divide();
4. }
5. public class InterfaceExample implements CalcInterface {
6.
7. // defining the variables of class
8. int a = 10;
9. int b = 20;
10. int c;
11.
12. // implementing the interface methods
13. public void multiply() {
14. int c = a * b;
15. System.out.println("Multiplication of numbers is: " + c);
16. }
17. public void divide() {
18. int c = a / b;
19. System.out.println("Division of numbers is: " + c);
20. }
21. // main method
22. public static void main (String[] args) throws IOException {
23. InterfaceExample obj = new InterfaceExample();
31 |M.sc sem I OOPs USING JAVA

24. // calling the methods


25. obj.multiply();
26. obj.divide();
27. }
28. }

3. String:
A string represents a sequence of characters for example "Javatpoint", "Hello world", etc. String is the class
of Java.

One of the ways to create a string and store a value in it is shown below:

1. String str = "You're the best";

Here, String type variable str has the value "You're the best". Click here to understand more about String
in Java.

Example:

In the following example, we are creating a string with a value. Here, we are using one of the String class
methods, substring() which prints the specified indexed part of the string.

StringExample.java

1. public class StringExample {


2. public static void main(String[] args) {
3.
4. // creating a string and initializing it
5. String str = "Hello! This is example of String type";
6.
7. // applying substring() on above string
8. String subStr = str.substring(0,14);
9.
10. // printing the string
11. System.out.println(subStr);
12. }
13. }

Output

4. Array:
32 |M.sc sem I OOPs USING JAVA

An array is a data type which can store multiple homogenous variables i.e., variables of same type in a
sequence. They are stored in an indexed manner starting with index 0. The variables can be either primitive
or non-primitive data types.

Following example shows how to declare array of primitive data type int:

1. int [ ] marks;

Following example shows how to declare array of non-primitive data type:

1. Student [ ] students;

where, Student is the class name and [ ] creates an array of object students.

Example:

In the following example, we are creating two basic array, in which one is initialized and the other is declared
(input is read from the user). Further, we are printing those array using the for loop.

ArrayExample.java

1. // importing required packages


2. import java.io. * ;
3. import java.util. * ;
4.
5. public class ArrayExample {
6. public static void main(String[] args) throws IOException {
7. int i;
8. Scanner sc = new Scanner(System. in );
9. // declaring and initializing an array
10. int arr[] = {1, 2, 3, 6, 9};
11. // defining another array arr1
12. int arr1[] = new int[5];
13. // reading values from the user
14. System.out.println("Enter the numbers (size = 5) :");
15. for (i = 0; i < 5; i++) {
16. arr1[i] = sc.nextInt();
17. }
18. System.out.println("Previous array with initialized size is: ");
19. for (i = 0; i < 5; i++) {
20. System.out.print(arr[i] + " ");
21. }
22. System.out.println("\nThe new array we have entered is:");
23. for (i = 0; i < 5; i++) {
33 |M.sc sem I OOPs USING JAVA

24. System.out.print(arr1[i] + " ");


25. }
26. }
27. }

Output:

Difference between Primitive and Non-primitive Data types in


Java
1. In Java, the primitive data types are system defined however we have to create and define the non-primitive
data types.
2. In primitive data type, variables can store only one value at a time. However in non-primitive data types,
either multiple values of the same type or different type or both can be stored.
3. All the data for primitive type variables are stored on the stack whereas, for reference types, the stack holds
a pointer to the object on the heap.
4. A primitive type starts with a lowercase letter, while non-primitive types start with an uppercase letter.
5. The size of a primitive type depends on the data type, while non-primitive types have all the same size.

(9) variable scope


Scope of Variables in Java
In programming, scope of variable defines how a specific variable is accessible within the program or
across classes. In this section, we will discuss the scope of variables in Java.

Scope of a Variable
In programming, a variable can be declared and defined inside a class, method, or block. It defines the
scope of the variable i.e. the visibility or accessibility of a variable. Variable declared inside a block or
method are not visible to outside. If we try to do so, we will get a compilation error. Note that the scope
of a variable can be nested.

o We can declare variables anywhere in the program but it has limited scope.
o A variable can be a parameter of a method or constructor.
o A variable can be defined and declared inside the body of a method and constructor.
o It can also be defined inside blocks and loops.
o Variable declared inside main() function cannot be accessed outside the main() function
34 |M.sc sem I OOPs USING JAVA

Demo.java

1. public class Demo


2. {
3. //instance variable
4. String name = "Andrew";
5. //class and static variable
6. static double height= 5.9;
7. public static void main(String args[])
8. {
9. //local variable
10. int marks = 72;
11. }
12. }

In Java, there are three types of variables based on their scope:

1. Member Variables (Class Level Scope)


2. Local Variables (Method Level Scope)

Member Variables (Class Level Scope)


These are the variables that are declared inside the class but outside any function have class-level scope.
We can access these variables anywhere inside the class. Note that the access specifier of a member variable
does not affect the scope within the class. Java allows us to access member variables outside the class with
the following rules:

Access Modifier Package Subclass Word

public Yes Yes Yes

protected Yes Yes No

private No No No
35 |M.sc sem I OOPs USING JAVA

default Yes No No

Syntax:

1. public class DemoClass


2. {
3. //variables declared inside the class have class level scope
4. int age;
5. private String name;
6. void displayName()
7. {
8. //statements
9. }
10. int dispalyAge()
11. {
12. //statements
13. }
14. char c;
15. }

Let's see an example.

VariableScopeExample1.java

1. public class VariableScopeExample1


2. {
3. public static void main(String args[])
4. {
5. int x=10;
6. {
7. //y has limited scope to this block only
8. int y=20;
9. System.out.println("Sum of x+y = " + (x+y));
10. }
11. //here y is unknown
12. y=100;
13. //x is still known
14. x=50;
15. }
16. }
36 |M.sc sem I OOPs USING JAVA

Output:

We see that y=100 is unknown. If you want to compile and run the above program remove or comment
the statement y=100. After removing the statement, the above program runs successfully and shows the
following output.

Sum of x+y = 30

There is another variable named an instance variable. These are declared inside a class but outside any
method, constructor, or block. When an instance variable is declared using the keyword static is known as
a static variable. Their scope is class level but visible to the method, constructor, or block that is defined
inside the class.

Let's see an example.

Product.java

1. public class Product


2. {
3. //variable visible to any child class
4. public String pName;
5. //variable visible to product class only
6. private double pPrice;
7. //creating a constructor and parsed product name as a parameter
8. public Product (String pname)
9. {
10. pName = pname;
11. }
12. //function sets the product price
13. public void setPrice(double pprice)
14. {
15. pPrice= pprice;
16. }
17. //method prints all product info
18. public void getInfo()
19. {
20. System.out.println("Product Name: " +pName );
21. System.out.println("Product Price: " +pPrice);
22. }
37 |M.sc sem I OOPs USING JAVA

23. public static void main(String args[])


24. {
25. Product pro = new Product("Mac Book");
26. pro.setPrice(65000);
27. pro.getInfo();
28. }
29. }

Output:

Product Name: Mac Book


Product Price: 65000.0

Let's see another example.

StaticVariableScope.java

1. public class StaticVariableScope


2. {
3. //declaring a private static variable
4. private static double pivalue;
5. //declaring a constant variable
6. public static final String piconstant = "PI";
7. public static void main(String args[])
8. {
9. pivalue = 3.14159265359;
10. System.out.println("The value of " + piconstant + " is: " + pivalue);
11. }
12. }

Output:

The value of PI is: 3.14159265359

Local Variables (Method Level Scope)


These are the variables that are declared inside a method, constructor, or block have a method-
level or block-level scope and cannot be accessed outside in which it is defined. Variables declared inside
a pair of curly braces {} have block-level scope.

Declaring a Variable Inside a Method

1. public class DemoClass1


2. {
3. void show()
38 |M.sc sem I OOPs USING JAVA

4. {
5. //variable declared inside a method has method level scope
6. int x=10;
7. System.out.println("The value of x is: "+x);
8. }
9. public static void main(String args[])
10. {
11. DemoClass1 dc = new DemoClass1();
12. dc.show();
13. }
14. }

Output:

The value of x is: 10

Let's see another example of method-level scope.

DemoClass2.java

1. public class DemoClass2


2. {
3. private int a;
4. public void setNumber(int a)
5. {
6. this.a = a;
7. System.out.println("The value of a is: "+a);
8. }
9. public static void main(String args[])
10. {
11. DemoClass2 dc = new DemoClass2();
12. dc.setNumber(3);
13. }
14. }

Output:

The value of a is: 3

In the above example, we have passed a variable as a parameter. We have used this keyword that
differentiates the class variable and local variable.

Declaring a Variable Inside a Constructor

VariableInsideConstructor.java
39 |M.sc sem I OOPs USING JAVA

1. public class VariableInsideConstructor


2. {
3. //creating a default constructor
4. VariableInsideConstructor()
5. {
6. int age=24;
7. System.out.println("Age is: "+age);
8. }
9. //main() method
10. public static void main(String args[])
11. {
12. //calling a default constructor
13. VariableInsideConstructor vc=new VariableInsideConstructor();
14. }
15. }

Output:

Age is: 24

Declaring a Variable Inside a Block

VariableInsideBlock.java

1. public class VariableInsideBlock


2. {
3. public static void main(String args[])
4. {
5. int x=4;
6. {
7. //y has limited scope to this block only
8. int y=100;
9. System.out.println("Sum of x+y = " + (x+y));
10. y=10;
11. //gives error, already defined
12. int y=200;
13. }
14. //creates a new variable
15. int y;
16. }
17. }

Output:
40 |M.sc sem I OOPs USING JAVA

We see that y=100 is unknown. If you want to compile and run the above program remove or comment
the statement y=100. After removing the statement, the above program runs successfully and shows the
following output.

Sum of x+y = 30

Let's see another example.

BlockScopeExample1.java

1. public class BlockScopeExample1


2. {
3. public static void main(String args[])
4. {
5. for (int x = 0; x < 10; x++)
6. {
7. System.out.println(x);
8. }
9. System.out.println(x);
10. }
11. }

Output:

When we run the above program, it shows an error at line 9, cannot find symbol because we have tried
to print the variable x that is declared inside the loop. To resolve this error, we need to declare the variable
x just before the for loop.

BlockScopeExample2.java

1. public class BlockScopeExample2


2. {
3. public static void main(String args[])
4. {
5. int x;
6. for (x = 0; x < 10; x++)
41 |M.sc sem I OOPs USING JAVA

7. {
8. //prints 0 to 9
9. System.out.print(x+"\t");
10. }
11. //prints 10
12. System.out.println(x);
13. }
14. }

Output:

a. wrapper
Use of Wrapper classes in Java
Java is an object-oriented programming language, so we need to deal with objects many times like in
Collections, Serialization, Synchronization, etc. Let us see the different scenarios, where we need to use the
wrapper classes.

o Change the value in Method: Java supports only call by value. So, if we pass a primitive value, it will not
change the original value. But, if we convert the primitive value in an object, it will change the original value.
o Serialization: We need to convert the objects into streams to perform the serialization. If we have a primitive
value, we can convert it in objects through the wrapper classes.
o Synchronization: Java synchronization works with objects in Multithreading.
o java.util package: The java.util package provides the utility classes to deal with objects.
o Collection Framework: Java collection framework works with objects only. All classes of the collection
framework (ArrayList, LinkedList, Vector, HashSet, LinkedHashSet, TreeSet, PriorityQueue, ArrayDeque, etc.)
deal with objects only.

The eight classes of the java.lang package are known as wrapper classes in Java. The list of eight wrapper
classes are given below:

Primitive Type Wrapper class

boolean Boolean

char Character

byte Byte
42 |M.sc sem I OOPs USING JAVA

short Short

int Integer

long Long

float Float

double Double

Autoboxing
The automatic conversion of primitive data type into its corresponding wrapper class is known as
autoboxing, for example, byte to Byte, char to Character, int to Integer, long to Long, float to Float, boolean
to Boolean, double to Double, and short to Short.

Since Java 5, we do not need to use the valueOf() method of wrapper classes to convert the primitive into
objects.

Wrapper class Example: Primitive to Wrapper

1. //Java program to convert primitive into objects


2. //Autoboxing example of int to Integer
3. public class WrapperExample1{
4. public static void main(String args[]){
5. //Converting int into Integer
6. int a=20;
7. Integer i=Integer.valueOf(a);//converting int into Integer explicitly
8. Integer j=a;//autoboxing, now compiler will write Integer.valueOf(a) internally
9.
10. System.out.println(a+" "+i+" "+j);
11. }}

Output:

20 20 20

Unboxing
The automatic conversion of wrapper type into its corresponding primitive type is known as unboxing. It is
the reverse process of autoboxing. Since Java 5, we do not need to use the intValue() method of wrapper
classes to convert the wrapper type into primitives.

Wrapper class Example: Wrapper to Primitive


43 |M.sc sem I OOPs USING JAVA

1. //Java program to convert object into primitives


2. //Unboxing example of Integer to int
3. public class WrapperExample2{
4. public static void main(String args[]){
5. //Converting Integer to int
6. Integer a=new Integer(3);
7. int i=a.intValue();//converting Integer to int explicitly
8. int j=a;//unboxing, now compiler will write a.intValue() internally
9.
10. System.out.println(a+" "+i+" "+j);
11. }}

Output:

b. conditional statements
A conditional statement is a part of mathematical reasoning which is a critical skill that
enables students to analyze a given hypothesis without any reference to a particular context
or meaning. In layman words, when a scientific inquiry or statement is examined, the
reasoning is not based on an individual's opinion. Derivations and proofs need a factual and
scientific basis.

Mathematical critical thinking and logical reasoning are important skills that are required to
solve maths reasoning questions.

In this mini-lesson, we will explore the world of conditional statements. We will walk through
the answers to the questions like what is meant by a conditional statement, what are the
parts of a conditional statement, and how to create conditional statements along with solved
examples and interactive questions.

What Is Meant By a Conditional Statement?


A statement that is of the form "If p, then q" is a conditional statement. Here 'p' refers to
'hypothesis' and 'q' refers to 'conclusion'.

For example, "If Cliff is thirsty, then she drinks water."

This is a conditional statement. It is also called an implication.

'→→' is the symbol used to represent the relation between two statements. For example,
A→→B. It is known as the logical connector. It can be read as A implies B.

Here are two more conditional statement examples

Example 1: If a number is divisible by 4, then it is divisible by 2.


44 |M.sc sem I OOPs USING JAVA

Example 2: If today is Monday, then yesterday was Sunday.

What Are the Parts of a Conditional Statement?

Hypothesis (if) and Conclusion (then) are the two main parts that form a conditional
statement.

Let us consider the above-stated example to understand the parts of a conditional statement.

Conditional Statement: If today is Monday, then yesterday was Sunday.

Hypothesis: "If today is Monday."

Conclusion: "Then yesterday was Sunday."

On interchanging the form of statement the relationship gets changed.

To check whether the statement is true or false here, we have subsequent parts of a
conditional statement. They are:

 Converse
 Inverse
 Contrapositive
 Biconditional Statement

Let us consider hypothesis as statement A and Conclusion as statement B.

Following are the observations made:

Converse of Statement

When hypothesis and conclusion are switched or interchanged, it is termed as converse


statement.
For example,

Conditional Statement: “If today is Monday, then yesterday was Sunday.”

Hypothesis: “If today is Monday”

Converse: “If yesterday was Sunday, then today is Monday.”


45 |M.sc sem I OOPs USING JAVA

Here the conditional statement logic is, If B, then A (B → A)

Inverse of Statement

When both the hypothesis and conclusion of the conditional statement are negative, it is
termed as an inverse of the statement.
For example,

Conditional Statement:“If today is Monday, then yesterday was Sunday”.

Inverse: “If today is not Monday, then yesterday was not Sunday.”

Here the conditional statement logic is, If not A, then not B (~A → ~B)

Contrapositive Statement

When the hypothesis and conclusion are negative and simultaneously interchanged, then the
statement is contrapositive.
For example,

Contrapositive: “If yesterday was not Sunday, then today is not Monday”

Here the conditional statement logic is, if not B, then not A (~B → ~A)

Biconditional Statement

The statement is a biconditional statement when a statement satisfies both the conditions as
true, being conditional and converse at the same time.
For example,

Biconditional: “Today is Monday if and only if yesterday was Sunday.”

Here the conditional statement logic is, A if and only if B (A ↔ B)

How to Create Conditional Statements?

Here, the point to be kept in mind is that the 'If' and 'then' part must be true.

If a number is a perfect square, then it is even.

 'If' part is a number that is a perfect square.

Think of 4 which is a perfect square.

This has become true.

 The 'then' part is that the number should be even. 4 is even.

This has also become true.


46 |M.sc sem I OOPs USING JAVA

Thus, we have set up a conditional statement.

Let us hypothetically consider two statements, statement A and statement B. Observe the
truth table for the statements:

Statement A Statement B A→B

Truth Truth Truth

Truth False False

False Truth Truth

False False Truth

According to the table, only if the hypothesis (A) is true and the conclusion (B) is false then, A
→ B will be false, or else A → B will be true for all other conditions.

 A sentence needs to be either true or false, but not both, to be considered as a


mathematically accepted statement.
 Any sentence which is either imperative or interrogative or exclamatory cannot be
considered a mathematically validated statement.
 A sentence containing one or many variables is termed as an open statement. An open
statement can become a statement if the variables present in the sentence are
replaced by definite values.
Solved Examples
Let us have a look at a few solved examples on conditional statements.

Example 1

Identify the types of conditional statements.

Solution

There are four types of conditional statements:

 If condition
 If-else condition
 Nested if-else
 If-else ladder.
Example 2

Ray tells "If the perimeter of a rectangle is 14, then its area is 10."
47 |M.sc sem I OOPs USING JAVA

Which of the following could be the counterexamples? Justify your decision.

a) A rectangle with sides measuring 2 and 5

b) A rectangle with sides measuring 10 and 1

c) A rectangle with sides measuring 1 and 5

d) A rectangle with sides measuring 4 and 3

Solution

a) Rectangle with sides 2 and 5: Perimeter = 14 and area = 10

Both 'if' and 'then' are true.

b) Rectangle with sides 10 and 1: Perimeter = 22 and area = 10

'If' is false and 'then' is true.

c) Rectangle with sides 1 and 5: Perimeter = 12 and area = 5

Both 'if' and 'then' are false.

d) Rectangle with sides 4 and 3: Perimeter = 14 and area = 12

'If' is true and 'then' is false.

Example 3

Joe examined the set of numbers {16, 27, 24} to check if they are the multiples of 3. He
claimed that they are divisible by 9. Do you agree or disagree? Justify your answer.

Solution

Conditional statement: If a number is a multiple of 3, then it is divisible by 9.

Let us find whether the conditions are true or false.

a) 16 is not a multiple of 3. Thus, the condition is false.

16 is not divisible by 9. Thus, the conclusion is false.

b) 27 is a multiple of 3. Thus, the condition is true.

27 is divisible by 9. Thus, the conclusion is true.

c) 24 is a multiple of 3. Thus the condition is true.


48 |M.sc sem I OOPs USING JAVA

24 is not divisible by 9. Thus the conclusion is false.

Example 4

Write the converse, inverse, and contrapositive statement for the following conditional
statement.

If you study well, then you will pass the exam.

Solution

The given statement is - If you study well, then you will pass the exam.

It is of the form, "If p, then q"

The converse statement is, "You will pass the exam if you study well" (if q, then p).

The inverse statement is, "If you do not study well then you will not pass the exam" (if not p,
then not q).

The contrapositive statement is, "If you did not pass the exam, then you did not study well" (if
not q, then not p).

c.method overloading
If a class has multiple methods having same name but different in parameters, it is known as Method
Overloading.

If we have to perform only one operation, having same name of the methods increases the readability of
the program.

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

So, we perform method overloading to figure out the program quickly.4.2M

Advantage of method overloading

Method overloading increases the readability of the program.

Different ways to overload the method

There are two ways to overload the method in java

1. By changing number of arguments


49 |M.sc sem I OOPs USING JAVA

2. By changing the data type

In Java, Method Overloading is not possible by changing the return type of the method only.

1) Method Overloading: changing no. of arguments


In this example, we have created two methods, first add() method performs addition of two numbers and
second add method performs addition of three numbers.

In this example, we are creating static methods so that we don't need to create instance for calling methods.

1. class Adder{
2. static int add(int a,int b){return a+b;}
3. static int add(int a,int b,int c){return a+b+c;}
4. }
5. class TestOverloading1{
6. public static void main(String[] args){
7. System.out.println(Adder.add(11,11));
8. System.out.println(Adder.add(11,11,11));
9. }}
Test it Now

Output:

22
33

2) Method Overloading: changing data type of arguments


In this example, we have created two methods that differs in data type. The first add method receives two
integer arguments and second add method receives two double arguments.

1. class Adder{
2. static int add(int a, int b){return a+b;}
3. static double add(double a, double b){return a+b;}
4. }
5. class TestOverloading2{
6. public static void main(String[] args){
7. System.out.println(Adder.add(11,11));
8. System.out.println(Adder.add(12.3,12.6));
9. }}
Test it Now
50 |M.sc sem I OOPs USING JAVA

Output:

22
24.9

Q) Why Method Overloading is not possible by changing the return type of


method only?
In java, method overloading is not possible by changing the return type of the method only because of
ambiguity. Let's see how ambiguity may occur:

1. class Adder{
2. static int add(int a,int b){return a+b;}
3. static double add(int a,int b){return a+b;}
4. }
5. class TestOverloading3{
6. public static void main(String[] args){
7. System.out.println(Adder.add(11,11));//ambiguity
8. }}
Test it Now

Output:

Compile Time Error: method add(int,int) is already defined in class Adder

System.out.println(Adder.add(11,11)); //Here, how can java determine which sum() method should be
called?

Note: Compile Time Error is better than Run Time Error. So, java compiler renders compiler time error
if you declare the same method having same parameters.

Can we overload java main() method?


Yes, by method overloading. You can have any number of main methods in a class by method overloading.
But JVM calls main() method which receives string array as arguments only. Let's see the simple example:

1. class TestOverloading4{
2. public static void main(String[] args){System.out.println("main with String[]");}
3. public static void main(String args){System.out.println("main with String");}
4. public static void main(){System.out.println("main without args");}
5. }
Test it Now

Output:

main with String[]


51 |M.sc sem I OOPs USING JAVA

Method Overloading and Type Promotion


One type is promoted to another implicitly if no matching datatype is found. Let's understand the concept
by the figure given below:

As displayed in the above diagram, byte can be promoted to short, int, long, float or double. The short
datatype can be promoted to int, long, float or double. The char datatype can be promoted to int,long,float
or double and so on.

Example of Method Overloading with TypePromotion


1. class OverloadingCalculation1{
2. void sum(int a,long b){System.out.println(a+b);}
3. void sum(int a,int b,int c){System.out.println(a+b+c);}
4.
5. public static void main(String args[]){
6. OverloadingCalculation1 obj=new OverloadingCalculation1();
7. obj.sum(20,20);//now second int literal will be promoted to long
8. obj.sum(20,20,20);
9.
10. }
11. }
Test it Now
Output:40
60

Example of Method Overloading with Type Promotion if matching found


If there are matching type arguments in the method, type promotion is not performed.
52 |M.sc sem I OOPs USING JAVA

1. class OverloadingCalculation2{
2. void sum(int a,int b){System.out.println("int arg method invoked");}
3. void sum(long a,long b){System.out.println("long arg method invoked");}
4.
5. public static void main(String args[]){
6. OverloadingCalculation2 obj=new OverloadingCalculation2();
7. obj.sum(20,20);//now int arg sum() method gets invoked
8. }
9. }
Test it Now
Output:int arg method invoked

Example of Method Overloading with Type Promotion in case of ambiguity


If there are no matching type arguments in the method, and each method promotes similar number of
arguments, there will be ambiguity.

1. class OverloadingCalculation3{
2. void sum(int a,long b){System.out.println("a method invoked");}
3. void sum(long a,int b){System.out.println("b method invoked");}
4.
5. public static void main(String args[]){
6. OverloadingCalculation3 obj=new OverloadingCalculation3();
7. obj.sum(20,20);//now ambiguity
8. }
9. }

d. class methods
The Object class is the parent class of all the classes in java by default. In other words, it is the
topmost class of java.

The Object class is beneficial if you want to refer any object whose type you don't know. Notice that parent
class reference variable can refer the child class object, know as upcasting.

Let's take an example, there is getObject() method that returns an object but it can be of any type like
Employee,Student etc, we can use Object class reference to refer that object. For example:

1. Object obj=getObject();//we don't know what object will be returned from this method

The Object class provides some common behaviors to all the objects such as object can be compared,
object can be cloned, object can be notified etc.
53 |M.sc sem I OOPs USING JAVA

Methods of Object class


The Object class provides many methods. They are as follows:

Method Description

public final Class getClass() returns the Class class object of this object. The Class class can
further be used to get the metadata of this class.

public int hashCode() returns the hashcode number for this object.

public boolean equals(Object obj) compares the given object to this object.

protected Object clone() throws creates and returns the exact copy (clone) of this object.
CloneNotSupportedException

public String toString() returns the string representation of this object.

public final void notify() wakes up single thread, waiting on this object's monitor.

public final void notifyAll() wakes up all the threads, waiting on this object's monitor.

public final void wait(long timeout)throws causes the current thread to wait for the specified milliseconds,
InterruptedException until another thread notifies (invokes notify() or notifyAll()
method).

public final void wait(long timeout,int causes the current thread to wait for the specified milliseconds
nanos)throws InterruptedException and nanoseconds, until another thread notifies (invokes notify()
or notifyAll() method).
54 |M.sc sem I OOPs USING JAVA

public final void wait()throws causes the current thread to wait, until another thread notifies
InterruptedException (invokes notify() or notifyAll() method).

protected void finalize()throws Throwable is invoked by the garbage collector before object is being
garbage collected.

(11) methods argument


Method arguments are the actual values that are passed to a method while executing it. In
figure 8.3, the variables phNum and msg are method parameters. If you execute this method as sendMsg
("123456", "Hello") , then the String values "123456" and "Hello" are method arguments.

Passing Primitive Data Type Arguments

Primitive arguments, such as an int or a double, are passed into methods by value. This means that any changes to the values of
the parameters exist only within the scope of the method. When the method returns, the parameters are gone and any changes to
them are lost. Here is an example:

public class PassPrimitiveByValue {

public static void main(String[] args) {

int x = 3;

// invoke passMethod() with


// x as argument
passMethod(x);

// print x to see if its


// value has changed
System.out.println("After invoking passMethod, x = " + x);

// change parameter in passMethod()


public static void passMethod(int p) {
p = 10;
}
}

When you run this program, the output is:

After invoking passMethod, x = 3


Passing Reference Data Type Arguments

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

For example, consider a method in an arbitrary class that moves Circle objects:

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


// code to move origin of circle to x+deltaX, y+deltaY
circle.setX(circle.getX() + deltaX);
circle.setY(circle.getY() + deltaY);

// code to assign a new reference to circle


55 |M.sc sem I OOPs USING JAVA
circle = new Circle(0, 0);
}

Let the method be invoked with these arguments:

moveCircle(myCircle, 23, 56)

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

e. Method Overriding in Java


If subclass (child class) has the same method as declared in the parent class, it is known as method
overriding in Java.

In other words, If a subclass provides the specific implementation of the method that has been declared
by one of its parent class, it is known as method overriding.

Usage of Java Method Overriding

o Method overriding is used to provide the specific implementation of a method which is already provided by
its superclass.
o Method overriding is used for runtime polymorphism

Rules for Java Method Overriding


1. The method must have the same name as in the parent class
2. The method must have the same parameter as in the parent class.
3. There must be an IS-A relationship (inheritance).

Understanding the problem without method overriding

Let's understand the problem that we may face in the program if we don't use method overriding.

1. //Java Program to demonstrate why we need method overriding


2. //Here, we are calling the method of parent class with child
3. //class object.
4. //Creating a parent class
5. class Vehicle{
6. void run(){System.out.println("Vehicle is running");}
7. }
8. //Creating a child class
9. class Bike extends Vehicle{
10. public static void main(String args[]){
56 |M.sc sem I OOPs USING JAVA

11. //creating an instance of child class


12. Bike obj = new Bike();
13. //calling the method with child class instance
14. obj.run();
15. }
16. }
Test it Now

Output:

Vehicle is running

Problem is that I have to provide a specific implementation of run() method in subclass that is why we use
method overriding.

Example of method overriding


In this example, we have defined the run method in the subclass as defined in the parent class but it has
some specific implementation. The name and parameter of the method are the same, and there is IS-A
relationship between the classes, so there is method overriding.

1. //Java Program to illustrate the use of Java Method Overriding


2. //Creating a parent class.
3. class Vehicle{
4. //defining a method
5. void run(){System.out.println("Vehicle is running");}
6. }
7. //Creating a child class
8. class Bike2 extends Vehicle{
9. //defining the same method as in the parent class
10. void run(){System.out.println("Bike is running safely");}
11.
12. public static void main(String args[]){
13. Bike2 obj = new Bike2();//creating object
14. obj.run();//calling method
15. }
16. }
Test it Now

Output:

Bike is running safely


57 |M.sc sem I OOPs USING JAVA

A real example of Java Method Overriding


Consider a scenario where Bank is a class that provides functionality to get the rate of interest. However,
the rate of interest varies according to banks. For example, SBI, ICICI and AXIS banks could provide 8%, 7%,
and 9% rate of interest.

Java method overriding is mostly used in Runtime Polymorphism which we will learn in next pages.
1. //Java Program to demonstrate the real scenario of Java Method Overriding
2. //where three classes are overriding the method of a parent class.
3. //Creating a parent class.
4. class Bank{
5. int getRateOfInterest(){return 0;}
6. }
7. //Creating child classes.
8. class SBI extends Bank{
9. int getRateOfInterest(){return 8;}
10. }
11.
12. class ICICI extends Bank{
13. int getRateOfInterest(){return 7;}
14. }
15. class AXIS extends Bank{
16. int getRateOfInterest(){return 9;}
17. }
18. //Test class to create objects and call the methods
19. class Test2{
20. public static void main(String args[]){
21. SBI s=new SBI();
22. ICICI i=new ICICI();
23. AXIS a=new AXIS();
24. System.out.println("SBI Rate of Interest: "+s.getRateOfInterest());
58 |M.sc sem I OOPs USING JAVA

25. System.out.println("ICICI Rate of Interest: "+i.getRateOfInterest());


26. System.out.println("AXIS Rate of Interest: "+a.getRateOfInterest());
27. }
28. }
Test it Now
Output:
SBI Rate of Interest: 8
ICICI Rate of Interest: 7
AXIS Rate of Interest: 9

Can we override static method?


No, a static method cannot be overridden. It can be proved by runtime polymorphism, so we will learn it
later.

Why can we not override static method?


It is because the static method is bound with class whereas instance method is bound with an object. Static
belongs to the class area, and an instance belongs to the heap area.

Can we override java main method?


No, because the main is a static method.

Difference between method Overloading and Method


Overriding in java
Click me for the difference between method overloading and overriding

More topics on Method Overriding (Not For Beginners)


Method Overriding with Access Modifier

Let's see the concept of method overriding with access modifier.

Exception Handling with Method Overriding

f. Cycle of a Java program


59 |M.sc sem I OOPs USING JAVA

Life Cycle of a Servlet (Servlet Life Cycle)


The web container maintains the life cycle of a servlet instance. Let's see the life cycle of the servlet:

1. Servlet class is loaded.


2. Servlet instance is created.
3. init method is invoked.
4. service method is invoked.
5. destroy method is invoked.

As displayed in the above diagram, there are three states of a servlet: new, ready and end. The servlet is in new state
if servlet instance is created. After invoking the init() method, Servlet comes in the ready state. In the ready state,
servlet performs all the tasks. When the web container invokes the destroy() method, it shifts to the end state.

1) Servlet class is loaded


The classloader is responsible to load the servlet class. The servlet class is loaded when the first request for the
servlet is received by the web container.

2) Servlet instance is created


The web container creates the instance of a servlet after loading the servlet class. The servlet instance is created
only once in the servlet life cycle.

3) init method is invoked


60 |M.sc sem I OOPs USING JAVA

The web container calls the init method only once after creating the servlet instance. The init method is used to
initialize the servlet. It is the life cycle method of the javax.servlet.Servlet interface. Syntax of the init method is
given below:

1. public void init(ServletConfig config) throws ServletException

4) service method is invoked


The web container calls the service method each time when request for the servlet is received. If servlet is not
initialized, it follows the first three steps as described above then calls the service method. If servlet is initialized, it
calls the service method. Notice that servlet is initialized only once. The syntax of the service method of the Servlet
interface is given below:

1. public void service(ServletRequest request, ServletResponse response)


2. throws ServletException, IOException

5) destroy method is invoked


The web container calls the destroy method before removing the servlet instance from the service. It gives the
servlet an opportunity to clean up any resource for example memory, thread etc. The syntax of the destroy method
of the Servlet interface is given below:

g. JDK, JRE, and JVM


Difference between JDK, JRE, and JVM
We must understand the differences between JDK, JRE, and JVM before proceeding further to Java. See the
brief overview of JVM here.

If you want to get the detailed knowledge of Java Virtual Machine, move to the next page. Firstly, let's see
the differences between the JDK, JRE, and JVM.

JVM
JVM (Java Virtual Machine) is an abstract machine. It is called a virtual machine because it doesn't physically
exist. It is a specification that provides a runtime environment in which Java bytecode can be executed. It
can also run those programs which are written in other languages and compiled to Java bytecode.

JVMs are available for many hardware and software platforms. JVM, JRE, and JDK are platform dependent
because the configuration of each OS is different from each other. However, Java is platform independent.
There are three notions of the JVM: specification, implementation, and instance.

The JVM performs the following main tasks:

o Loads code
61 |M.sc sem I OOPs USING JAVA

o Verifies code
o Executes code
o Provides runtime environment

JRE
JRE is an acronym for Java Runtime Environment. It is also written as Java RTE. The Java Runtime
Environment is a set of software tools which are used for developing Java applications. It is used to provide
the runtime environment. It is the implementation of JVM. It physically exists. It contains a set of libraries
+ other files that JVM uses at runtime.

The implementation of JVM is also actively released by other companies besides Sun Micro Systems.

JDK
JDK is an acronym for Java Development Kit. The Java Development Kit (JDK) is a software development
environment which is used to develop Java applications and applets. It physically exists. It contains JRE +
development tools.

JDK is an implementation of any one of the below given Java Platforms released by Oracle Corporation:

o Standard Edition Java Platform


o Enterprise Edition Java Platform
o Micro Edition Java Platform
62 |M.sc sem I OOPs USING JAVA

The JDK contains a private Java Virtual Machine (JVM) and a few other resources such as an
interpreter/loader (java), a compiler (javac), an archiver (jar), a documentation generator (Javadoc), etc. to
complete the development of a Java Application.

h. Java Edition
How to Download Minecraft Java Edition
Minecraft is a sandbox video game developed by Mojang Studios. It is written in Java programming language.
It is developed by Markus Persson. In May 2009, it was released for personal computers. The Minecraft Java
edition is a cross-platform play between Windows, Linux, and macOS. It also supports user-created skin and
mods. It is an educational game because it enhances creativity, collaboration, problem-solving skill. It is a paid
game because its demand is high. Due to high demand, its price is also high. In this section, we are going to
learn how to download and install Minecraft Java Edition.

Features of Minecraft
o Available on Windows, Linux, macOS, and Android.
o It supports user-created skin and mods.
o Compatible with Realms for Java Edition.
o It frequently receives updates via game launcher.

System Requirements
Before downloading the Minecraft Java Edition, ensure the following system requirements:
63 |M.sc sem I OOPs USING JAVA

Hardware Requirements:
The minimum requirement of the hardware is:

o Processor: Intel Core i3-3210 3.2 GHz/ AMD A8-7600 APU 3.1 GHz or equivalent
o GPU (Integrated): Intel HD Graphics 4000 (Ivy Bridge) or AMD Radeon R5 series (Kaveri line) with OpenGL
4.4*
o GPU (Discrete): Nvidia GeForce 400 Series or AMD Radeon HD 7000 series with OpenGL 4.4
o RAM: 4GB
o HDD: At least 1GB for game core, maps, and other files.
o OS: Windows, Linux or macOS

Note: The system must have internet connectivity for downloading the Minecraft files. After
downloading the files, you can disconnect the internet and play offline.

Software Requirements:
If you are using Minecraft version 1.12, the minimum required Java version is 8. If we don't know which version of
Java is installed in our system, the Minecraft installer installs the latest version of Java by default.

Note: Some Minecraft users have issues because of the mismatch version of Java and their operating
system. It also creates a problem if there are multiple Java versions is installed in the system.

Downloading Minecraft Java Edition


To download the Minecraft Java edition, follow the steps given below:

o Go through the link ://www.minecraft.net/en-us/download.


o Click on the DOWNLOAD FOR WINDOWS button if you are using the Windows platform, else scroll down
the page, and click on the platform that you are using. In this section, we are going to download Minecraft
for Windows.
o After clicking, it starts downloading the MinecraftInstaller.msi file. Now double click on the downloaded
file and give permission to run on your system. Minecraft Launcher Setup wizard appears on the screen.
Click on the Next button.

o Provide the path where you want to install Minecraft and click on the Next button. In our case, we are
installing it to C:\Program Files (x86)\Minecraft Launcher\

o Click on the Install button to begin the installation.

o During the installation a dialog box appears on the screen that asks for installing the Minecraft. Click on
the Yes button to install.
64 |M.sc sem I OOPs USING JAVA

o Click on the Finish button to complete the installation.

o After clicking on the Finish button, it starts downloading the update files.

After updating the Minecraft, Minecraft Launcher appears on the screen.

At the top left corner of the Minecraft Launcher, the language selection option is available. You can select your
language. We can continue with the launcher with credentials or without credentials. But it is recommended that
create an account to log-in. If you have already an account provides the EMAIL and PASSWORD, else click on
the Signup link.

We can also continue without credentials by clicking on the link CONTINUE WITHOUT LOGIN.

When we continue with the link highlighted above, it shows a message to buy Minecraft for full access. If you
want to purchase click on the Buy now! button, else click on the PLAY button. When we click on
the PLAY button, it again asks for a login. So, we recommended you to Sing-up first if you want to play. We don't
have a MOJANG ACCOUNT, so we are going to create it. Click on the Sign-up link.

After clicking, we land on the following page.

Provide the Email address, Repeat email address, password, Date of Birth in the above fields, and click on
the CREATE ACCOUNT button. The Mojang Studio sends a four-character verification code to the provided
email. Provide the verification code (we found the code Z4K3) in the box and click on the VERIFY button.

The credential for the Mojang account is generated. Now move to the Minecraft Launcher and provide the
credentials and click on the Login button. After login, it starts downloading some files or data from the server.

To start the Minecraft, click on the Minecraft Launcher icon that is placed on the desktop.

It starts the Minecraft 1.16.1 version. Now we can play the game by clicking on the Play Demo World button.

The following image shows the game is loading.

The following image shows the actual game window. Use the keys w, a, s, d, and spacebar to control the game.

i. Polymorphism
The polymorphism is a core concept of an object-oriented paradigm that provides a way to perform
a single action in different forms. It provides an ability to call the same method on different JavaScript
objects. As JavaScript is not a type-safe language, we can pass any type of data members with the methods.

JavaScript Polymorphism Example 1


Let's see an example where a child class object invokes the parent class method.

1. <script>
65 |M.sc sem I OOPs USING JAVA

2. class A
3. {
4. display()
5. {
6. document.writeln("A is invoked");
7. }
8. }
9. class B extends A
10. {
11. }
12. var b=new B();
13. b.display();
14. </script>
Test it Now

Output:

A is invoked

Example 2
Let's see an example where a child and parent class contains the same method. Here, the object of child
class invokes both classes method.

1. <script>
2. class A
3. {
4. display()
5. {
6. document.writeln("A is invoked<br>");
7. }
8. }
9. class B extends A
10. {
11. display()
12. {
13. document.writeln("B is invoked");
14. }
15. }
16.
17. var a=[new A(), new B()]
18. a.forEach(function(msg)
19. {
66 |M.sc sem I OOPs USING JAVA

20. msg.display();
21. });
22. </script>
Test it Now

Output:

A is invoked
B is invoked

Example 3
Let's see the same example with prototype-based approach.

1. <script>
2. function A()
3. {
4. }
5. A.prototype.display=function()
6. {
7. return "A is invoked";
8. }
9. function B()
10. {
11.
12. }
13.
14. B.prototype=Object.create(A.prototype);
15.
16. var a=[new A(), new B()]
17.
18. a.forEach(function(msg)
19. {
20. document.writeln(msg.display()+"<br>");
21. });
22. <script>
Test it Now

Output:

A is invoked
B is invoked
67 |M.sc sem I OOPs USING JAVA

j. Dynamic Method Dispatch


 Dynamic method dispatch is also known as run time polymorphism.
 It is the process through which a call to an overridden method is resolved at runtime.
 This technique is used to resolve a call to an overridden method at runtime rather than
compile time.
 To properly understand Dynamic method dispatch in Java, it is important to understand
the concept of upcasting because dynamic method dispatch is based on upcasting.

Upcasting :

 It is a technique in which a superclass reference variable refers to the object of the


subclass.

Example :

class Animal{}
class Dog extends Animal{}

Copy

Animal a=new Dog();//upcasting

Copy

In the above example, we've created two classes, named Animal(superclass) &
Dog(subclass). While creating the object 'a', we've taken the reference variable of the
parent class(Animal), and the object created is of child class(Dog).
Example to demonstrate the use of Dynamic method dispatch :

 In the below code, we've created two classes: Phone & SmartPhone.
 The Phone is the parent class and the SmartPhone is the child class.
 The method on() of the parent class is overridden inside the child class.
 Inside the main() method, we've created an object obj of the Smartphone() class by
taking the reference of the Phone() class.
 When obj.on() will be executed, it will call the on() method of the SmartPhone() class
because the reference variable obj is pointing towards the object of class SmartPhone().

class Phone{
public void showTime(){
System.out.println("Time is 8 am");
}
68 |M.sc sem I OOPs USING JAVA

public void on(){


System.out.println("Turning on Phone...");
}
}

class SmartPhone extends Phone{


public void music(){
System.out.println("Playing music...");
}
public void on(){
System.out.println("Turning on SmartPhone...");
}
}
public class CWH {
public static void main(String[] args) {

Phone obj = new SmartPhone(); // Yes it is allowed


// SmartPhone obj2 = new Phone(); // Not allowed

obj.showTime();
obj.on();
// obj.music(); Not Allowed

}
}

Copy
Output :

Time is 8 am
Turning on SmartPhone...

Copy
Note: The data members can not achieve the run time polymorphism.
69 |M.sc sem I OOPs USING JAVA
Code as described/written in the video :

package com.company;
class Phone{
public void showTime(){
System.out.println("Time is 8 am");
}
public void on(){
System.out.println("Turning on Phone...");
}
}

class SmartPhone extends Phone{


public void music(){
System.out.println("Playing music...");
}
public void on(){
System.out.println("Turning on SmartPhone...");
}
}
public class cwh_49_dynamic_method_dispatch {
public static void main(String[] args) {
// Phone obj = new Phone(); // Allowed
// SmartPhone smobj = new SmartPhone(); // Allowed
// obj.name();

Phone obj = new SmartPhone(); // Yes it is allowed


// SmartPhone obj2 = new Phone(); // Not allowed

obj.showTime();
obj.on();
// obj.music(); Not Allowed

}
70 |M.sc sem I OOPs USING JAVA

You might also like