1 PDF
1 PDF
1 PDF
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.
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
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.
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.
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.
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
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
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.
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) Object is a real world entity such as pen, laptop, mobile, bed, Class is a group of similar objects.
keyboard, mouse, chair etc.
4) Object is created through new keyword mainly e.g. Class is declared using class
Student s1=new Student(); keyword e.g.
class Student{}
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:
(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.
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.
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.
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
Output:
20
Output:
10
10.0
Output:
10.5
10
Output:
130
-126
13 |M.sc sem I OOPs USING JAVA
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.
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.
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.
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
Output:
Example 2:
ConstantExample2.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
Output:
Example of Enumeration
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 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.
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0L 8 byte
The Boolean data type specifies one bit of information, but its "size" can't be defined precisely.
Example:
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:
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:
The int data type is generally used as a default data type for integral values unless if there is no problem
about memory.
Example:
Example:
Example:
1. float f1 = 234.5f
Example:
1. double d1 = 12.3
Example:
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:
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. }
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. }
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
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
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.
There are two types of data structure available for the programming purpose:
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 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.
Primitive data structure can be used to call the Non-primitive data structure cannot be used to call the
methods. methods.
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'.
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.
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:
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'.
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
In this section, we will understand the non-primitive data types, their uses and implementation in Java.
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. Class
2. Object
3. String
4. Array
29 |M.sc sem I OOPs USING JAVA
5. Interface
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
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
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:
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
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;
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
Output:
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
private No No No
35 |M.sc sem I OOPs USING JAVA
default Yes No No
Syntax:
VariableScopeExample1.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.
Product.java
Output:
StaticVariableScope.java
Output:
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:
DemoClass2.java
Output:
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.
VariableInsideConstructor.java
39 |M.sc sem I OOPs USING JAVA
Output:
Age is: 24
VariableInsideBlock.java
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
BlockScopeExample1.java
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
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:
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.
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.
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.
'→→' 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.
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.
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
Converse of Statement
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,
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,
Here, the point to be kept in mind is that the 'If' and 'then' part must be true.
Let us hypothetically consider two statements, statement A and statement B. Observe the
truth table for the statements:
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.
Example 1
Solution
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
Solution
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
Example 4
Write the converse, inverse, and contrapositive statement for the following conditional
statement.
Solution
The given statement is - If you study well, then you will pass the exam.
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.
In Java, Method Overloading is not possible by changing the return type of the method only.
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
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
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:
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.
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:
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.
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
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
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 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.
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:
int x = 3;
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:
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.
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.
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
Let's understand the problem that we may face in the program if we don't use method overriding.
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.
Output:
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
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.
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:
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.
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:
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.
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 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 After clicking on the Finish button, it starts downloading the update files.
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.
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 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.
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
Upcasting :
Example :
class Animal{}
class Dog extends Animal{}
Copy
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
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...");
}
}
obj.showTime();
obj.on();
// obj.music(); Not Allowed
}
70 |M.sc sem I OOPs USING JAVA