OOPS NOTES 1 to 10
OOPS NOTES 1 to 10
What is Java?
Java is a programming language and a platform. Java is a high level, robust, object-oriented
and secure programming language.
Java was developed by Sun Microsystems (which is now the subsidiary of Oracle) in the year
1995. James Gosling is known as the father of Java. Before Java, its name was Oak. Since Oak
was already a registered company, so James Gosling and his team changed the name from Oak
to Java.
Platform: Any hardware or software environment in which a program runs, is known as a
platform. Since Java has a runtime environment (JRE) and API, it is called a platform.
Java Example
Let's have a quick look at Java programming example. A detailed description of Hello Java
example is available in next page.
Simple.java
class Simple{
public static void main(String args[]){
System.out.println("Hello Java");
}
}
Application
According to Sun, 3 billion devices run Java. There are many devices where Java is currently
used. Some of them are as follows:
1. Desktop Applications such as acrobat reader, media player, antivirus, etc.
2. Web Applications such as irctc.co.in, javatpoint.com, etc.
3. Enterprise Applications such as banking applications.
4. Mobile
5. Embedded System
6. Smart Card
7. Robotics
8. Games, etc.
1
DESIGN INTRODUCTION
2) Web Application
An application that runs on the server side and creates a dynamic page is called a web
application. Currently, Servlet , JSP, Struts, Spring, Hibernate, JSF, etc. technologies are used
for creating web applications in Java.
3) Enterprise Application
An application that is distributed in nature, such as banking applications, etc. is called an
enterprise application. It has advantages like high-level security, load balancing, and clustering.
In Java, EJB is used for creating enterprise applications.
4) Mobile Application
An application which is created for mobile devices is called a mobile application. Currently,
Android and Java ME are used for creating mobile applications.
2
DESIGN INTRODUCTION
o Loads code
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
3
DESIGN INTRODUCTION
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.
What is JVM
1. A specification where working of Java Virtual Machine is specified. But implementation
provider is independent to choose the algorithm. Its implementation has been provided
by Oracle and other companies.
2. An implementation Its implementation is known as JRE (Java Runtime Environment).
3. Runtime Instance Whenever you write java command on the command prompt to run
the java class, an instance of JVM is created.
4
DESIGN INTRODUCTION
What it does
The JVM performs following operation:
o Loads code
o Verifies code
o Executes code
o Provides runtime environment
JVM Architecture
Let's understand the internal architecture of JVM. It contains classloader, memory area,
execution engine etc.
1) Classloader
Classloader is a subsystem of JVM which is used to load class files. Whenever we run
the java program, it is loaded first by the classloader. There are three built-in classloaders
in Java.
5
DESIGN INTRODUCTION
1. Bootstrap ClassLoader: This is the first classloader which is the super class of Extension
classloader. It loads the rt.jar file which contains all class files of Java Standard Edition
like java.lang package classes, java.net package classes, java.util package classes, java.io
package classes, java.sql package classes etc.
2. Extension ClassLoader: This is the child classloader of Bootstrap and parent classloader
of System classloader. It loades the jar files located
inside $JAVA_HOME/jre/lib/ext directory.
3. System/Application ClassLoader: This is the child classloader of Extension classloader. It
loads the classfiles from classpath. By default, classpath is set to current directory. You
can change the classpath using "-cp" or "-classpath" switch. It is also known as
Application classloader.
2) Class(Method) Area
Class(Method) Area stores per-class structures such as the runtime constant pool, field
and method data, the code for methods.
3) Heap
It is the runtime data area in which objects are allocated.
4) Stack
Java Stack stores frames. It holds local variables and partial results, and plays a part in
method invocation and return.
Each thread has a private JVM stack, created at the same time as thread.
A new frame is created each time a method is invoked. A frame is destroyed when its
method invocation completes.
6
DESIGN INTRODUCTION
7) Execution Engine
It contains:
1. A virtual processor
2. Interpreter: Read bytecode stream then execute the instructions.
3. Just-In-Time(JIT) compiler: It is used to improve the performance. JIT compiles parts of
the byte code that have similar functionality at the same time, and hence reduces the
amount of time needed for compilation. Here, the term "compiler" refers to a translator
from the instruction set of a Java virtual machine (JVM) to the instruction set of a specific
CPU.
7
DESIGN INTRODUCTION
o Class
o Inheritance
o Polymorphism
o Abstraction
o Encapsulation
Apart from these concepts, there are some other terms which are used in Object-
Oriented design:
o Coupling
o Cohesion
o Association
o Aggregation
o Composition
8
DESIGN INTRODUCTION
Object
Any entity that has state and behavior is known as an object. For example, a chair, pen,
table, keyboard, bike, etc. It can be physical or logical.
An Object can be defined as an instance of a class. An object contains an address and
takes up some space in memory. Objects can communicate without knowing the details
of each other's data or code. The only necessary thing is the type of message accepted
and the type of response returned by the objects.
Example: A dog is an object because it has states like color, name, breed, etc. as well as
behaviors like wagging the tail, barking, eating, etc.
Class
Collection of objects is called class. It is a logical entity.
A class can also be defined as a blueprint from which you can create an individual object.
Class doesn't consume any space.
Inheritance
9
DESIGN INTRODUCTION
Polymorphism
The word “Polymorphism” derives from two words i.e. “Poly” which means many and
“morphs” meaning forms. Thus polymorphism means many forms. In a programming
language, we can say that an object can take many forms, and hence the object is
polymorphic.
Polymorphism in Java can be achieved in two ways i.e., method overloading and
method overriding.
● Compile-time polymorphism
● Runtime polymorphism
Abstraction
BY LOVELEEN KAUR 1
DESIGN INTRODUCTION
Encapsulation
Coupling
Coupling refers to the knowledge or information or dependency of another class. It arises
when classes are aware of each other. If a class has the details information of another
class, there is strong coupling. In Java, we use private, protected, and public modifiers to
display the visibility level of a class, method, and field. You can use interfaces for the
weaker coupling because there is no concrete implementation.
Cohesion
Cohesion refers to the level of a component which performs a single well-defined task.
A single well-defined task is done by a highly cohesive method. The weakly cohesive
method will split the task into separate parts. The java.io package is a highly cohesive
package because it has I/O related classes and interface. However, the java.util package
is a weakly cohesive package because it has unrelated classes and interfaces.
Association
Association represents the relationship between the objects. Here, one object can be
associated with one object or many objects. There can be four types of association
between the objects:
o One to One
o One to Many
o Many to One, and
o Many to Many
BY LOVELEEN KAUR 1
DESIGN INTRODUCTION
Let's understand the relationship with real-time examples. For example, One country
can have one prime minister (one to one), and a prime minister can have many ministers
(one to many). Also, many MP's can have one prime minister (many to one), and many
ministers can have many departments (many to many).
Association can be undirectional or bidirectional.
Aggregation
Aggregation is a way to achieve Association. Aggregation represents the relationship
where one object contains other objects as a part of its state. It represents the weak
relationship between objects. It is also termed as a has-a relationship in Java. Like,
inheritance represents the is-a relationship. It is another way to reuse objects.
Composition
The composition is also a way to achieve Association. The composition represents the
relationship where one object contains other objects as a part of its state. There is a
strong relationship between the containing object and the dependent object. It is the
state where containing objects do not have an independent existence. If you delete the
parent object, all the child objects will be deleted automatically.
BY LOVELEEN KAUR 1
DESIGN INTRODUCTION
BY LOVELEEN KAUR 1
JAVA DATA TYPES VARIABLES & OPERATORS
Java -DataTypes
Variables are nothing but reserved memory locations to store values. This means that
when you create a variable you reserve some space in the memory.
Based on the data type of a variable, the operating system allocates memory and
decides what can be stored in the reserved memory. Therefore, by assigning different
data types to variables, you can store integers, decimals, or characters in these
variables.
There are two data types available in Java −
byte
Byte data type is an 8-bit signed two's complement integer
Minimum value is -128 (-2^7)
BY LOVELEEN KAUR 1
JAVA DATA TYPES VARIABLES & OPERATORS
BY LOVELEEN KAUR 2
JAVA DATA TYPES VARIABLES & OPERATORS
Double data type should never be used for precise values such as
currency
Default value is 0.0d
Example: double d1 = 123.4
boolean
boolean data type represents one bit of information
There are only two possible values: true and false
This data type is used for simple flags that track true/false conditions
Default value is false
Example: boolean one = true
char
char data type is a single 16-bit Unicode character
Minimum value is '\u0000' (or 0)
Maximum value is '\uffff' (or 65,535 inclusive)
Char data type is used to store any character
Example: char letterA = 'A'
Byte 0 1 byte
Short 0 2 byte
Int 0 4 byte
Long 0L 8 byte
Note-> To get 2's complement of binary number is 1's complement of given number
plus 1 to the least significant bit (LSB). For example 2's complement of binary number
10010 is (01101) + 1 = 01110.
BY LOVELEEN KAUR 3
JAVA DATA TYPES VARIABLES & OPERATORS
Reference Datatypes
Reference variables are created using defined constructors of the
classes. They are used to access objects. These variables are declared
to be of a specific type that cannot be changed. For example, Employee,
Puppy, etc.
Class objects and various type of array variables come under reference
datatype.
Default value of any reference variable is null.
A reference variable can be used to refer any object of the declared type
or any compatible type.
Example: Animal animal = new Animal("giraffe");
Java Literals
A literal is a source code representation of a fixed value. They are represented directly
in the code without any computation.
Literals can be assigned to any primitive type variable. For example −
byte a = 68;
char a = 'A';
byte, int, long, and short can be expressed in decimal(base 10), hexadecimal(base
16) or octal(base 8) number systems as well.
Prefix 0 is used to indicate octal, and prefix 0x indicates hexadecimal when using
these number systems for literals. For example −
Example
"Hello World"
"two\nlines"
"\"This is in quotes\""
String and char types of literals can contain any Unicode characters. For example −
char a = '\u0001';
String a = "\u0001";
BY LOVELEEN KAUR 4
JAVA DATA TYPES VARIABLES & OPERATORS
Java language supports few special escape sequences for String and char literals as
well. They are −
\n Newline (0x0a)
\f Formfeed (0x0c)
\b Backspace (0x08)
\s Space (0x20)
\t Tab
\\ Backslash
https://www.geeksforgeeks.org/escape-sequences-in-java/
BY LOVELEEN KAUR 5
JAVA DATA TYPES VARIABLES & OPERATORS
Java - Variables
A variable provides us with named storage that our programs can manipulate. Each
variable in Java has a specific type, which determines the size and layout of the
variable's memory; the range of values that can be stored within that memory; and
the set of operations that can be applied to the variable.
You must declare all variables before they can be used. Following is the basic form
of a variable declaration −
data type variable [ = value][, variable [ = value] ...] ;
Here data type is one of Java's datatypes and variable is the name of the variable. To
declare more than one variable of the specified type, you can use a comma-separated
list.
Following are valid examples of variable declaration and initialization in Java −
Example
int a, b, c; // Declares three ints, a, b, and c.
int a = 10, b = 10; // Example of initialization
byte B = 22; // initializes a byte type variable B.
double pi = 3.14159; // declares and assigns a value of PI.
char a = 'a'; // the char variable a iis initialized with value 'a'
This chapter will explain various variable types available in Java Language. There are
three kinds of variables in Java −
Local variables
Instance variables
Class/Static variables
Local Variables
Local variables are declared in methods, constructors, or blocks.
Local variables are created when the method, constructor or block is
entered and the variable will be destroyed once it exits the method,
constructor, or block.
Access modifiers cannot be used for local variables.
Local variables are visible only within the declared method, constructor,
or block.
Local variables are implemented at stack level internally.
There is no default value for local variables, so local variables should be
declared and an initial value should be assigned before the first use.
BY LOVELEEN KAUR 6
JAVA DATA TYPES VARIABLES & OPERATORS
Example
Here, age is a local variable. This is defined inside pupAge() method and its scope is
limited to only this method.
Output
Puppy age is: 7
Example
Following example uses age without initializing it, so it would give an error at the
time of compilation.
Output
Test.java:4:variable number might not have been initialized
age = age + 7;
^
1 error
BY LOVELEEN KAUR 7
JAVA DATA TYPES VARIABLES & OPERATORS
Instance Variables
Instance variables are declared in a class, but outside a method,
constructor or any block.
When a space is allocated for an object in the heap, a slot for each
instance variable value is created.
Instance variables are created when an object is created with the use of
the keyword 'new' and destroyed when the object is destroyed.
Instance variables hold values that must be referenced by more than
one method, constructor or block, or essential parts of an object's state
that must be present throughout the class.
Instance variables can be declared in class level before or after use.
Access modifiers can be given for instance variables.
The instance variables are visible for all methods, constructors and
block in the class. Normally, it is recommended to make these variables
private (access level). However, visibility for subclasses can be given for
these variables with the use of access modifiers.
Instance variables have default values. For numbers, the default value
is 0, for Booleans it is false, and for object references it is null. Values
can be assigned during the declaration or within the constructor.
Instance variables can be accessed directly by calling the variable name
inside the class. However, within static methods (when instance
variables are given accessibility), they should be called using the fully
qualified name. ObjectReference.VariableName.
Example
import java.io.*;
public class Employee {
BY LOVELEEN KAUR 8
JAVA DATA TYPES VARIABLES & OPERATORS
Output
name : Ransika
salary :1000.0
Class/Static Variables
Class variables also known as static variables are declared with the
static keyword in a class, but outside a method, constructor or a block.
There would only be one copy of each class variable per class,
regardless of how many objects are created from it.
Static variables are rarely used other than being declared as constants.
Constants are variables that are declared as public/private, final, and
static. Constant variables never change from their initial value.
Static variables are stored in the static memory. It is rare to use static
variables other than declared final and used as either public or private
constants.
Static variables are created when the program starts and destroyed
when the program stops.
Visibility is similar to instance variables. However, most static variables
are declared public since they must be available for users of the class.
Default values are same as instance variables. For numbers, the default
value is 0; for Booleans, it is false; and for object references, it is null.
Values can be assigned during the declaration or within the constructor.
Additionally, values can be assigned in special static initializer blocks.
Static variables can be accessed by calling with the class
name ClassName.VariableName.
When declaring class variables as public static final, then variable
names (constants) are all in upper case. If the static variables are not
public and final, the naming syntax is the same as instance and local
variables.
BY LOVELEEN KAUR 9
JAVA DATA TYPES VARIABLES & OPERATORS
Example
import java.io.*;
public class Employee {
// DEPARTMENT is a constant
public static final String DEPARTMENT = "Development ";
Output
Development average salary:1000
Note − If the variables are accessed from an outside class, the constant should be
accessed as Employee.DEPARTMENT
If any vaíiable is not assigned with value at compile-time and assigned at íun time
is called dynamic initialization of a vaíiable. Basically, this is achieved thíough
constíuctoís, setteí methods, noímal methods and builtin api methods which íetuíns a
value oí object.
Let us see the few examples of how to initialize vaíiables at íun time.
class Rectangle {
private double length;
private double width;
BY LOVELEEN KAUR 10
JAVA DATA TYPES VARIABLES & OPERATORS
this.length = length;
this.width = width;
System.out.println("Length is:"+length);
System.out.println("Width is:"+width);
}
public static void main(String[] args) {
// passing the values at runtime.
Rectangle rectangle1 = new Rectangle(10,16);
}
in the above píogíam, length and width aíe initialized at íuntime with diffeíent values foí each
Rectangle object.
Let us do now with setteí methods. Now add the following to the Rectangle class.
class Rectangle {
double length;
double width;
public double getLength() {
BY LOVELEEN KAUR 11
JAVA DATA TYPES VARIABLES & OPERATORS
return length;
}
}
}
BY LOVELEEN KAUR 12
JAVA DATA TYPES VARIABLES & OPERATORS
Class Variables
A variable which is declared inside a class, outside all the blocks and is marked static
is known as a class variable. The general scope of a class variable is throughout the
class and the lifetime of a class variable is until the end of the program or as long as
the class is loaded in memory.
Local Variables
All other variables which are not instance and class variables are treated as local
variables including the parameters in a method. Scope of a local variable is within
the block in which it is declared and the lifetime of a local variable is until the control
leaves the block in which it is declared.
BY LOVELEEN KAUR 13
JAVA DATA TYPES VARIABLES & OPERATORS
implicit type casting. In this case both datatypes should be compatible with each
other.
Example
public class WideningExample {
public static void main(String args[]){
char ch = 'C';
int i = ch;
System.out.println(i);
}
}
Output
Integer value of the given character: 67
Narrowing − Converting a higher datatype to a lower datatype is known as
narrowing. In this case the casting/conversion is not done automatically, you need to
convert explicitly using the cast operator “( )” explicitly. Therefore, it is known as
explicit type casting. In this case both datatypes need not be compatible with each
other.
Example
import java.util.Scanner;
public class NarrowingExample {
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.println("Enter an integer value: ");
int i = sc.nextInt();
char ch = (char) i;
System.out.println("Character value of the given integer: "+ch);
}
}
BY LOVELEEN KAUR 14
JAVA DATA TYPES VARIABLES & OPERATORS
Output
Enter an integer value:
67
Character value of the given integer: C
BY LOVELEEN KAUR 15
JAVA DATA TYPES VARIABLES & OPERATORS
Java - Operators
Java provides a rich set of operators to manipulate variables. We can divide all the
Java operators into the following groups –
Unary Operators
Arithmetic Operators
Shift Operators
Relational Operators
Bitwise Operators
Logical Operators
Ternary Operator
Assignment Operators
Java Unary Operator
The Java unary operators require only one operand. Unary operators are used to
perform various operations i.e.:
Output:
10
12
12
10
Java Unary Operator Example 2: ++ and --
public class OperatorExample{
BY LOVELEEN KAUR 16
JAVA DATA TYPES VARIABLES & OPERATORS
}}
Output:
22
21
BY LOVELEEN KAUR 17
JAVA DATA TYPES VARIABLES & OPERATORS
Example
public class Test {
System.out.println("a + b = " + (a + b) );
System.out.println("a - b = " + (a - b) );
System.out.println("a * b = " + (a * b) );
System.out.println("b / a = " + (b / a) );
System.out.println("b % a = " + (b % a) );
System.out.println("c % a = " + (c % a) );
System.out.println("a++ = " + (a++) );
System.out.println("a-- = " + (a--) );
Output
a + b = 30
a - b = -10
a * b = 200
b/a=2
b%a=0
c%a=5
a++ = 10
b-- = 11
BY LOVELEEN KAUR 18
JAVA DATA TYPES VARIABLES & OPERATORS
d++ = 25
++d = 27
Java Left Shift Operator
The Java left shift operator << is used to shift all of the bits in a value to the left side
of a specified number of times.
Output:
40
80
80
240
Java Right Shift Operator
The Java right shift operator >> is used to move the value of the left operand to right
by the number of bits specified by the right operand.
Output:
2
5
2
BY LOVELEEN KAUR 19
JAVA DATA TYPES VARIABLES & OPERATORS
Output:
5
5
-5
1073741819
Checks if the value of left operand is greater than the (A > B) is not
> (greater than)
value of right operand, if yes then condition becomes true. true.
Checks if the value of left operand is less than the value (A < B) is
< (less than)
of right operand, if yes then condition becomes true. true.
BY LOVELEEN KAUR 20
JAVA DATA TYPES VARIABLES & OPERATORS
Example
public class Test {
System.out.println("a == b = " + (a == b) );
System.out.println("a != b = " + (a != b) );
System.out.println("a > b = " + (a > b) );
System.out.println("a < b = " + (a < b) );
System.out.println("b >= a = " + (b >= a) );
System.out.println("b <= a = " + (b <= a) );
}
}
This will produce the following result −
Output
a == b = false
a != b = true
a > b = false
a < b = true
b >= a = true
b <= a = false
The Bitwise Operators
Java defines several bitwise operators, which can be applied to the integer types,
long, int, short, char, and byte.
Bitwise operator works on bits and performs bit-by-bit operation. Assume if a = 60
and b = 13; now in binary format they will be as follows −
a = 0011 1100
b = 0000 1101
BY LOVELEEN KAUR 21
JAVA DATA TYPES VARIABLES & OPERATORS
& (bitwise Binary AND Operator copies a bit to the (A & B) will give 12 which is
and) result if it exists in both operands. 0000 1100
^ (bitwise Binary XOR Operator copies the bit if it is (A ^ B) will give 49 which is
XOR) set in one operand but not both. 0011 0001
>>> (zero fill Shift right zero fill operator. The left A >>>2 will give 15 which is
right shift) operands value is moved right by the 0000 1111
number of bits specified by the right
BY LOVELEEN KAUR 22
JAVA DATA TYPES VARIABLES & OPERATORS
Example
public class Test {
c = a | b; /* 61 = 0011 1101 */
System.out.println("a | b = " + c );
c = a ^ b; /* 49 = 0011 0001 */
System.out.println("a ^ b = " + c );
c = a >> 2; /* 15 = 1111 */
System.out.println("a >> 2 = " + c );
Output
a & b = 12
a | b = 61
a ^ b = 49
~a = -61
a << 2 = 240
a >> 2 = 15
a >>> 2 = 15
BY LOVELEEN KAUR 23
JAVA DATA TYPES VARIABLES & OPERATORS
Example
public class Test {
Output
a && b = false
a || b = true
!(a && b) = true
BY LOVELEEN KAUR 24
JAVA DATA TYPES VARIABLES & OPERATORS
Ternary Operator ( ? : )
Conditional operator is also known as the ternary operator. This operator consists of
three operands and is used to evaluate Boolean expressions. The goal of the operator
is to decide, which value should be assigned to the variable. The operator is written
as −
variable x = (expression) ? value if true : value if false
Following is an example −
Example
instanceof Operator
This operator is used only for object reference variables. The operator checks whether
the object is of a particular type (class type or interface type). instanceof operator is
written as −
( Object reference variable ) instanceof (class/interface type)
If the object referred by the variable on the left side of the operator passes the IS-A
check for the class/interface type on the right side, then the result will be true.
Following is an example −
Example
BY LOVELEEN KAUR 25
JAVA DATA TYPES VARIABLES & OPERATORS
BY LOVELEEN KAUR 26
JAVA DATA TYPES VARIABLES & OPERATORS
to C = C /
A
C <<= 2 is
<<= Left shift AND assignment operator. same as C
= C << 2
C >>= 2 is
>>= Right shift AND assignment operator. same as C
= C >> 2
C &= 2 is
&= Bitwise AND assignment operator. same as C
=C&2
Example
public class Test {
c = a + b;
System.out.println("c = a + b = " + c );
c += a ;
BY LOVELEEN KAUR 27
JAVA DATA TYPES VARIABLES & OPERATORS
System.out.println("c += a = " + c );
c -= a ;
System.out.println("c -= a = " + c );
c *= a ;
System.out.println("c *= a = " + c );
a = 10;
c = 15;
c /= a ;
System.out.println("c /= a = " + c );
a = 10;
c = 15;
c %= a ;
System.out.println("c %= a = " + c );
c <<= 2 ;
System.out.println("c <<= 2 = " + c );
c >>= 2 ;
System.out.println("c >>= 2 = " + c );
c >>= 2 ;
System.out.println("c >>= 2 = " + c );
c &= a ;
System.out.println("c &= a = " + c );
c ^= a ;
System.out.println("c ^= a = " + c );
c |= a ;
System.out.println("c |= a = " + c );
}
}
This will produce the following result −
Output
c = a + b = 30
c += a = 40
c -= a = 30
c *= a = 300
c /= a = 1
c %= a = 5
c <<= 2 = 20
c >>= 2 = 5
c >>= 2 = 1
BY LOVELEEN KAUR 28
JAVA DATA TYPES VARIABLES & OPERATORS
c &= a = 0
c ^= a = 10
c |= a = 10
BY LOVELEEN KAUR 29
CONTROL STATEMENTS
Decision-Making statements:
As the name suggests, decision-making statements decide which statement to execute
and when. Decision-making statements evaluate the Boolean expression and control
the program flow depending upon the result of the condition provided. There are two
types of decision-making statements in Java, i.e., If statement and switch statement.
1) If Statement:
In Java, the "if" statement is used to evaluate a condition. The control of the program
is diverted depending upon the specific condition. The condition of the If statement
gives a Boolean value, either true or false. In Java, there are four types of if-statements
given below.
BY LOVELEEN KAUR 1
CONTROL STATEMENTS
1. Simple if statement
2. if-else statement
3. if-else-if ladder
4. Nested if-statement
1) Simple if statement:
It is the most basic statement among all control flow statements in Java. It evaluates a
Boolean expression and enables the program to enter a block of code if the expression
evaluates to true.
if(condition) {
statement 1; //executes when condition is true
}
Consider the following example in which we have used the if statement in the java
code.
Student.java
Student.java
Output:
x + y is greater than 20
BY LOVELEEN KAUR 2
CONTROL STATEMENTS
2) if-else statement
The if-else statement is an extension to the if-statement, which uses another block of
code, i.e., else block. The else block is executed if the condition of the if-block is
evaluated as false.
Syntax:
if(condition) {
statement 1; //executes when condition is true
}
else{
statement 2; //executes when condition is false
}
Student.java
Output:
x + y is greater than 20
3) if-else-if ladder:
BY LOVELEEN KAUR 3
CONTROL STATEMENTS
if(condition 1) {
statement 1; //executes when condition 1 is true
}
else if(condition 2) {
statement 2; //executes when condition 2 is true
}
else {
statement 2; //executes when all the conditions are false
}
Student.java
Output:
Delhi
4. Nested if-statement
BY LOVELEEN KAUR 4
CONTROL STATEMENTS
if(condition 1) {
statement 1; //executes when condition 1 is true
if(condition 2) {
statement 2; //executes when condition 2 is true
}
else{
statement 2; //executes when condition 2 is false
}
}
Student.java
if(address.endsWith("India")) {
if(address.contains("Meerut")) {
System.out.println("Your city is Meerut");
}else if(address.contains("Noida")) {
System.out.println("Your city is Noida");
}else {
System.out.println(address.split(",")[0]);
}
}else {
System.out.println("You are not living in India");
}
}
}
Output:
Delhi
Switch Statement:
In Java, Switch statements are similar to if-else-if statements. The switch statement
contains multiple blocks of code called cases and a single case is executed based on
BY LOVELEEN KAUR 5
CONTROL STATEMENTS
the variable which is being switched. The switch statement is easier to use instead of
if-else-if statements. It also enhances the readability of the program.
o The case variables can be int, short, byte, char, or enumeration. String type is also
supported since version 7 of Java
o Cases cannot be duplicate
o Default statement is executed when any of the case doesn't match the value of
expression. It is optional.
o Break statement terminates the switch block when the condition is satisfied.
It is optional, if not used, next case is executed.
o While using switch statements, we must notice that the case expression will be of the
same type as the variable. However, it will also be a constant value.
switch (expression){
case value1:
statement1;
break;
.
.
.
case valueN:
statementN;
break;
default:
default statement;
}
Consider the following example to understand the flow of the switch statement.
Student.java
BY LOVELEEN KAUR 6
CONTROL STATEMENTS
switch (num){
case 0:
System.out.println("number is 0");
break;
case 1:
System.out.println("number is 1");
break;
default:
System.out.println(num);
}
}
}
Output:
While using switch statements, we must notice that the case expression will be of the
same type as the variable. However, it will also be a constant value. The switch permits
only int, string, and Enum type variables to be used.
Loop Statements
In programming, sometimes we need to execute the block of code repeatedly while
some condition evaluates to true. However, loop statements are used to execute the
set of instructions in a repeated order. The execution of the set of instructions depends
upon a particular condition.
In Java, we have three types of loops that execute similarly. However, there are
differences in their syntax and condition checking time.
1. for loop
2. while loop
3. do-while loop
BY LOVELEEN KAUR 7
CONTROL STATEMENTS
loop only when we exactly know the number of times, we want to execute the block
of code.
Consider the following example to understand the proper functioning of the for loop
in java.
Calculation.java
Output:
BY LOVELEEN KAUR 8
CONTROL STATEMENTS
Consider the following example to understand the functioning of the for-each loop in
Java.
Calculation.java
Output:
Java
C
C++
Python
JavaScript
Java while loop
The while loop is also used to iterate over the number of statements multiple times.
However, if we don't know the number of iterations in advance, it is recommended to
use a while loop. Unlike for loop, the initialization and increment/decrement doesn't
take place inside the loop statement in while loop.
BY LOVELEEN KAUR 9
CONTROL STATEMENTS
It is also known as the entry-controlled loop since the condition is checked at the start
of the loop. If the condition is true, then the loop body will be executed; otherwise, the
statements after the loop will be executed.
1. while(condition){
2. //looping statements
3. }
The flow chart for the while loop is given in the following image.
Calculation .java
BY LOVELEEN KAUR 10
CONTROL STATEMENTS
Output:
0
2
4
6
8
10
Java do-while loop
The do-while loop checks the condition at the end of the loop after executing the loop
statements. When the number of iteration is not known and we have to execute the
loop at least once, we can use do-while loop.
It is also known as the exit-controlled loop since the condition is not checked in
advance. The syntax of the do-while loop is given below.
do
{
//statements
} while (condition);
The flow chart of the do-while loop is given in the following image.
BY LOVELEEN KAUR 11
CONTROL STATEMENTS
Consider the following example to understand the functioning of the do-while loop in
Java.
Calculation.java
Outpt:
BY LOVELEEN KAUR 12
CONTROL STATEMENTS
8
10
Jump Statements
Jump statements are used to transfer the control of the program to the specific
statements. In other words, jump statements transfer the execution control to the
other part of the program. There are two types of jump statements in Java, i.e., break
and continue.
The break statement cannot be used independently in the Java program, i.e., it can
only be written inside the loop or switch statement.
Consider the following example in which we have used the break statement with the
for loop.
BreakExample.java
Output:
0
1
2
BY LOVELEEN KAUR 13
CONTROL STATEMENTS
3
4
5
6
Calculation.java
}
}
Output:
0
1
2
3
4
5
BY LOVELEEN KAUR 14
CONTROL STATEMENTS
if(j == 4) {
continue;
}
System.out.println(j);
}
}
}
Output:
0
1
2
3
5
1
2
3
5
2
3
5
BY LOVELEEN KAUR 15
ARRAYS
Arrays in Java
Array in java is a group of like-typed variables referred to by a common name.
Arrays in Java work differently than they do in C/C++. Following are some
important points about Java arrays.
In Java, all arrays are dynamically allocated. (discussed below).
Arrays are stored in contiguous memory [consecutive memory
locations].
Since arrays are objects in Java, we can find their length using the object
property length. This is different from C/C++, where we find length using
sizeof.
A Java array variable can also be declared like other variables with []
after the data type.
The variables in the array are ordered, and each has an index beginning
with 0.
Java array can also be used as a static field, a local variable, or a method
parameter.
The size of an array must be specified by int or short value and not long.
The direct superclass of an array type is Object.
Every array type implements the interfaces Cloneable
and java.io.Serializable.
This storage of arrays helps us randomly access the elements of an array
[Support Random Access].
The size of the array cannot be altered(once initialized). However, an
array reference can be made to point to another array.
An array can contain primitives (int, char, etc.) and object (or non-primitive)
references of a class depending on the definition of the array. In the case of
primitive data types, the actual values are stored in contiguous memory locations.
In the case of class objects, the actual objects are stored in a heap segment.
BY LOVELEEN KAUR 1
ARRAYS
One-Dimensional Arrays:
byte byteArray[];
short shortsArray[];
boolean booleanArray[];
long longArray[];
float floatArray[];
double doubleArray[];
char charArray[];
BY LOVELEEN KAUR 2
ARRAYS
// of unknown type
Although the first declaration establishes that int Array is an array variable, no
actual array exists. It merely tells the compiler that this variable (int Array) will
hold an array of the integer type. To link int Array with an actual, physical array of
integers, you must allocate one using new and assign it to int Array.
Array Literal
In a situation where the size of the array and variables of the array are already
known, array literals can be used.
int[] intArray = new int[]{ 1,2,3,4,5,6,7,8,9,10 };
// Declaring array literal
The length of this array determines the length of the created array.
There is no need to write the new int[] part in the latest versions of Java.
BY LOVELEEN KAUR 3
ARRAYS
Each element in the array is accessed via its index. The index begins with 0 and
ends at (total array size)-1. All the elements of array can be accessed using Java for
Loop.
// accessing the elements of the specified array
for (int i = 0; i < arr.length; i++)
System.out.println("Element at index " + i +
" : "+ arr[i]);
Implementation:
class Arrays {
public static void main(String[] args)
{
// declares an Array of integers.
int[] arr;
// so on...
arr[2] = 30;
arr[3] = 40;
arr[4] = 50;
BY LOVELEEN KAUR 4
ARRAYS
Output
Element at index 0 : 10
Element at index 1 : 20
Element at index 2 : 30
Element at index 3 : 40
Element at index 4 : 50
You can also access java arrays using for each loops.
For-each is another array traversing technique like for loop, while loop, do-
while loop introduced in Java5.
import java.io.*;
class Easy
// array declaration
BY LOVELEEN KAUR 5
ARRAYS
Output
10 50 60 80 90
Arrays of Objects
The student Array contains five memory spaces each of the size of student class in
which the address of five Student objects can be stored. The Student objects have
to be instantiated using the constructor of the Student class, and their references
should be assigned to the array elements in the following way.
BY LOVELEEN KAUR 6
ARRAYS
Example
// an array of objects
class Student {
public int roll_no;
public String name;
Student(int roll_no, String name)
{
this.roll_no = roll_no;
this.name = name;
}
// so on...
arr[2] = new Student(3, "shikar");
arr[3] = new Student(4, "dharmesh");
arr[4] = new Student(5, "mohit");
Output
Element at 0 : 1 aman
Element at 1 : 2 vaibhav
Element at 2 : 3 shikar
Element at 3 : 4 dharmesh
BY LOVELEEN KAUR 7
ARRAYS
Element at 4 : 5 mohit
System.out.println(
"Trying to access element outside the size of array");
System.out.println(arr[5]);
}
}
Output
Trying to access element outside the size of array
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:
Index 5 out of bounds for length 4
at GFG.main(GFG.java:13)
Output
10
20
BY LOVELEEN KAUR 8
ARRAYS
Multidimensional Arrays:
Multidimensional arrays are arrays of arrays with each element of the array
holding the reference of other arrays. These are also known as Jagged Arrays. A
multidimensional array is created by appending one set of square brackets ([]) per
dimension.
Syntax :
datatype [][] arrayrefvariable;
or
datatype arrayrefvariable[][];
Syntax:
import java.io.*;
class MDA {
public static void main (String[] args) {
// Syntax
int [][] arr= new int[3][3];
// 3 row and 3 column
}
}
Output
BY LOVELEEN KAUR 9
ARRAYS
int arr[][]
= { { 2, 7, 9 }, { 3, 6, 1 }, { 7, 4, 2 } };
// printing 2D array
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++)
System.out.print(arr[i][j] + " ");
System.out.println();
}
}
}
Output
2 7 9
3 6 1
7 4 2
Here,
d1, d2, d3 = sizes of the dimensions
data_type = data type of the elements of the array
array_name = name of the 3d array
This means that in a 3d array, the three dimensions are interpreted as:
The number of Tables/Arrays: The first dimension indicates how many
tables or arrays a 3d array will have.
The number of Rows: The second dimension signifies the total
number of rows an array will have.
The number of Columns: The third dimension indicates the total
columns in the 3d array.
BY LOVELEEN KAUR 10
ARRAYS
Initialize 3d Array
The approaches used to initialize a 3d array are the same as the ones used
for initializing Two-dimensional arrays.
You can either initialize the array by assigning values to individual array
elements or initialize the array during the declaration.
BY LOVELEEN KAUR 11
ARRAYS
BY LOVELEEN KAUR 12
ARRAYS
}
System.out.println();
}
System.out.println();
}
}
}
Output:
BY LOVELEEN KAUR 13
ARRAYS
};
System.out.println("Multidimensional Array (3-d) is as follows:");
// use for..each loop to iterate through elements of 3d array
for (int[][] array_2D: intArray) {
for (int[] array_1D: array_2D) {
for(intelem: array_1D) {
System.out.print(elem + "\t");
}
System.out.println();
}
System.out.println();
}
}
}
Output:
BY LOVELEEN KAUR 14
ARRAYS
Like variables, we can also pass arrays to methods. For example, the below
program passes the array to method sum to calculate the sum of the array’s values.
// Java program to demonstrate
// passing of array to method
Output
sum of array values : 15
As usual, a method can also return an array. For example, the below program
returns an array from method m1.
// Java program to demonstrate
// return of array from method
class RAFM {
// Driver method
public static void main(String args[])
{
int arr[] = m1();
BY LOVELEEN KAUR 15
ARRAYS
Output
1 2 3
Every array has an associated Class object, shared with all other arrays with the
same component type.
class COFA {
public static void main(String args[])
{
int intArray[] = new int[3];
byte byteArray[] = new byte[3];
short shortsArray[] = new short[3];
// array of Strings
String[] strArray = new String[3];
System.out.println(intArray.getClass());
System.out.println(
intArray.getClass().getSuperclass());
System.out.println(byteArray.getClass());
System.out.println(shortsArray.getClass());
System.out.println(strArray.getClass());
}
}
Output
class [I
class java.lang.Object
class [B
class [S
BY LOVELEEN KAUR 16
ARRAYS
class [Ljava.lang.String;
Explanation:
1. The string “[I” is the run-time type signature for the class object “array
with component type int.”
2. The only direct superclass of an array type is java.lang.Object.
3. The string “[B” is the run-time type signature for the class object “array
with component type byte.”
4. The string “[S” is the run-time type signature for the class object “array
with component type short.”
5. The string “[L” is the run-time type signature for the class object “array
with component type of a Class.” The Class name is then followed.
Array Members
Now, as you know that arrays are objects of a class, and a direct superclass of
arrays is a class Object. The members of an array type are all of the following:
The public final field length contains the number of components of the
array. Length may be positive or zero.
All the members are inherited from class Object; the only method of
Object that is not inherited is its clone method.
The public method clone() overrides the clone method in class Object
and throws no checked exceptions.
Object Type Arrays Either declared type objects or it’s child class objects.
BY LOVELEEN KAUR 17
ARRAYS
BY LOVELEEN KAUR 18
OBJECT ORIENTED PROGRAMMING
An object is any entity that has a state and behavior. For example,
a bicycle is an object. It has
States: idle, first gear, etc
Behaviors: braking, accelerating, etc.
Before we learn about objects, let's first know about classes in Java.
Java Class
A class is a blueprint for the object. Before we create an object, we first need
to define the class.
Since many houses can be made from the same description, we can create
many objects from a class.
We can create a class in Java using the class keyword. For example,
class ClassName {
// fields
// methods
}
Here, fields (variables) and methods represent the state and behavior of the
object respectively.
BY LOVELEEN KAUR 1
OBJECT ORIENTED PROGRAMMING
class Bicycle {
// state or field
private int gear = 5;
// behavior or method
public void braking() {
System.out.println("Working of Braking");
}
}
Note: We have used keywords private and public. These are known as
access modifiers.
Java Objects
BY LOVELEEN KAUR 2
OBJECT ORIENTED PROGRAMMING
We have used the new keyword along with the constructor of the class to
create an object. Constructors are similar to methods and have the same
name as the class. For example, Bicycle() is the constructor of
the Bicycle class.
Here, sportsBicycle and touringBicycle are the names of objects. We can use
them to access fields and methods of the class.
As you can see, we have created two objects of the class. We can create
multiple objects of a single class in Java.
Note: Fields and methods of a class are also called members of the class.
We can use the name of objects along with the . operator to access
members of a class. For example,
class Bicycle {
// field of class
int gear = 5;
// method of class
void braking() {
...
}
}
// create object
Bicycle sportsBicycle = new Bicycle();
sportsBicycle.braking();
Now that we understand what is class and object. Let's see a fully working
example.
class Main {
public static void main(String[] args) {
BY LOVELEEN KAUR 4
OBJECT ORIENTED PROGRAMMING
Output:
Light on? true
Light on? false
Inside the Main class, we have created two objects: led and halogen of
the Lamp class. We then used the objects to call the methods of the class.
led.turnOn() - It sets the isOn variable to true and prints the output.
halogen.turnOff() - It sets the isOn variable to false and prints the
output.
The variable isOn defined inside the class is also called an instance variable.
It is because when we create an object of the class, it is called an instance
of the class. And, each instance will have its own copy of the variable.
That is, led and halogen objects will have their own copy of the isOn variable.
Example: Create objects inside the same class
Note that in the previous example, we have created objects inside another
class and accessed the members from that class.
class Lamp {
BY LOVELEEN KAUR 5
OBJECT ORIENTED PROGRAMMING
Output
Here, we are creating the object inside the main() method of the same class.
Java Methods
A method is a block of code that performs a specific task.
Suppose you need to create a program to create a circle and color it. You
can create two methods to solve this problem:
a method to draw the circle
a method to color the circle
Dividing a complex problem into smaller chunks makes your program easy
to understand and reusable.
In Java, there are two types of methods:
User-defined Methods: We can create our own method based on our
requirements.
Standard Library Methods: These are built-in methods in Java that
are available to use.
Let's first learn about user-defined methods.
BY LOVELEEN KAUR 6
OBJECT ORIENTED PROGRAMMING
returnType methodName() {
// method body
}
Here,
If the method does not return a value, its return type is void.
int addNumbers() {
// code
}
In the above example, the name of the method is adddNumbers(). And, the
return type is int. We will learn more about return types later in this tutorial.
This is the simple syntax of declaring a method. However, the complete
syntax of declaring a method is
BY LOVELEEN KAUR 7
OBJECT ORIENTED PROGRAMMING
Here,
BY LOVELEEN KAUR 8
OBJECT ORIENTED PROGRAMMING
// create a method
public int addNumbers(int a, int b) {
int sum = a + b;
// return value
return sum;
}
Sum is: 40
Here, we have called the method by passing two arguments num1 and num2.
Since the method is returning some value, we have stored the value in
the result variable.
Note: The method is not static. Hence, we are calling the method using the
object of the class.
BY LOVELEEN KAUR 9
OBJECT ORIENTED PROGRAMMING
A Java method may or may not return a value to the function call. We use
the return statement to return any value. For example,
int addNumbers() {
...
return sum;
}
Here, we are returning the variable sum. Since the return type of the function
is int. The sum variable should be of int type. Otherwise, it will generate an
error.
Example 2: Method Return Type
class Main {
// create a method
public static int square(int num) {
// return statement
return num * num;
}
BY LOVELEEN KAUR 10
OBJECT ORIENTED PROGRAMMING
Here, we have mentioned the return type of the method as int. Hence, the
method should always return an integer value.
Note: If the method does not return any value, we use the void keyword as
the return type of the method. For example,
BY LOVELEEN KAUR 11
OBJECT ORIENTED PROGRAMMING
Here, the parameter of the method is int. Hence, if we pass any other data
type instead of int, the compiler will throw an error. It is because Java is a
strongly typed language.
Note: The argument 24 passed to the display2() method during the method
call is called the actual argument.
BY LOVELEEN KAUR 12
OBJECT ORIENTED PROGRAMMING
The standard library methods are built-in methods in Java that are readily
available for use. These standard libraries come along with the Java Class
Library (JCL) in a Java archive (*.jar) file with JVM and JRE.
For example,
Output:
BY LOVELEEN KAUR 13
INHERITANCE
Java - Inheritance
Inheritance can be defined as the process where one class acquires the properties
(methods and fields) of another. With the use of inheritance the information is made
manageable in a hierarchical order.
The class which inherits the properties of other is known as subclass (derived class,
child class) and the class whose properties are inherited is known as superclass (base
class, parent class).
extends Keyword
extends is the keyword used to inherit the properties of a class. Following is the
syntax of extends keyword.
Syntax
class Super {
.....
.....
}
class Sub extends Super {
.....
.....
}
Sample Code
Following is an example demonstrating Java inheritance. In this example, you can
observe two classes namely Calculation and My_Calculation.
Using extends keyword, the My_Calculation inherits the methods addition() and
Subtraction() of Calculation class.
Copy and paste the following program in a file with name My_Calculation.java
Example
class Calculation {
int z;
BY LOVELEEN KAUR 1
INHERITANCE
The Superclass reference variable can hold the subclass object, but using that
variable you can access only the members of the superclass, so to access the
members of both classes it is recommended to always create reference variable to
the subclass.
BY LOVELEEN KAUR 2
INHERITANCE
If you consider the above program, you can instantiate the class as given below. But
using the superclass reference variable ( cal in this case) you cannot call the
method multiplication(), which belongs to the subclass My_Calculation.
class Super_class {
int num = 20;
BY LOVELEEN KAUR 3
INHERITANCE
}
}
BY LOVELEEN KAUR 4
INHERITANCE
parameterized constructor of the superclass, you need to use the super keyword as
shown below.
super(values);
Sample Code
The program given in this section demonstrates how to use the super keyword to
invoke the parametrized constructor of the superclass. This program contains a
superclass and a subclass, where the superclass contains a parameterized
constructor which accepts a integer value, and we used the super keyword to invoke
the parameterized constructor of the superclass.
Copy and paste the following program in a file with the name Subclass.java
Example
class Superclass {
int age;
Superclass(int age) {
this.age = age;
}
BY LOVELEEN KAUR 5
INHERITANCE
IS-A Relationship
Programmer is the subclass and Employee is the superclass. The relationship between
the two classes is Programmer IS-A Employee. It means that Programmer is a type
of Employee.
class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}
HAS-A relationship
Aggregation in Java
If a class have an entity reference, it is known as Aggregation. Aggregation represents HAS-
A relationship.
Consider a situation, Employee object contains many informations such as id, name, emailId
etc. It contains one more object named address, which contains its own informations such as
city, state, country, zipcode etc. as given below.
class Employee
{
int id;
String name;
Address address;//Address is a class
...
}
In such case, Employee has an entity reference address, so relationship is Employee HAS-A
address.
BY LOVELEEN KAUR 6
INHERITANCE
example of Aggregation
In this example, Employee has an object of Address, address object contains its own
information’s such as city, state, country etc. In such case relationship is Employee
HAS-A address.
Address.java
public class Address {
String city,state,country;
}
Emp.java
public class Emp {
int id;
String name;
Address address;
BY LOVELEEN KAUR 7
INHERITANCE
void display(){
System.out.println(id+" "+name);
System.out.println(address.city+" "+address.state+" "+address.country);
}
e.display();
e2.display();
}
}
Output:111 varun
gzb UP india
112 arun
gno UP india
Types of Inheritance
There are various types of inheritance as demonstrated below.
BY LOVELEEN KAUR 8
INHERITANCE
A very important fact to remember is that Java does not support multiple inheritance.
This means that a class cannot extend more than one class. Therefore following is
illegal −
Example
Example
Variables and methods can be declared without any modifiers, as in the following
examples −
boolean processOrder() {
return true;
}
Private Access Modifier - Private
Methods, variables, and constructors that are declared private can only be accessed
within the declared class itself.
Private access modifier is the most restrictive access level. Class and interfaces
cannot be private.
BY LOVELEEN KAUR 9
INHERITANCE
Variables that are declared private can be accessed outside the class, if public getter
methods are present in the class.
Using the private modifier is the main way that an object encapsulates itself and hides
data from the outside world.
Example
The following class uses private access control −
Example
The following function uses public access control −
BY LOVELEEN KAUR 10
INHERITANCE
Example
The following parent class uses protected access control, to allow its child class
override openSpeaker() method −
class AudioPlayer {
protected boolean openSpeaker(Speaker sp) {
// implementation details
}
}
BY LOVELEEN KAUR 11
INHERITANCE
Now, if the same method is defined in both the superclass and the subclass,
then the method of the subclass class overrides the method of the
superclass. This is known as method overriding.
class Main {
public static void main(String[] args) {
Dog d1 = new Dog();
d1.displayInfo();
}
}
Output:
I am a dog.
BY LOVELEEN KAUR 12
INHERITANCE
When we call displayInfo() using the d1 object (object of the subclass), the
method inside the subclass Dog is called. The displayInfo() method of the
subclass overrides the same method of the superclass.
Both the superclass and the subclass must have the same method
name, the same return type and the same parameter list.
BY LOVELEEN KAUR 13
INHERITANCE
class Main {
public static void main(String[] args) {
Dog d1 = new Dog();
d1.displayInfo();
}
}
Output:
I am an animal.
I am a dog.
In the above example, the subclass Dog overrides the method displayInfo() of
the superclass Animal.
When we call the method displayInfo() using the d1 object of the Dog subclass,
the method inside the Dog subclass is called; the method inside the
superclass is not called.
BY LOVELEEN KAUR 14
INHERITANCE
It is important to note that constructors in Java are not inherited. Hence, there
is no such thing as constructor overriding in Java.
However, we can call the constructor of the superclass from its subclasses.
For that, we use super().
The same method declared in the superclass and its subclasses can have
different access specifiers. However, there is a restriction.
We can only use those access specifiers in subclasses that provide larger
access than the access specifier of the superclass. For example,
class Main {
public static void main(String[] args) {
Dog d1 = new Dog();
d1.displayInfo();
}
BY LOVELEEN KAUR 15
INHERITANCE
BY LOVELEEN KAUR 16
INHERITANCE
Output:
I am a dog.
In the above example, the subclass Dog overrides the method displayInfo() of
the superclass Animal.
BY LOVELEEN KAUR 17
INHERITANCE
The abstract class in Java cannot be instantiated (we cannot create objects
of abstract classes). We use the abstract keyword to declare an abstract
class. For example,
An abstract class can have both the regular methods and abstract methods.
For example,
// abstract method
abstract void method1();
// regular method
void method2() {
System.out.println("This is regular method");
}
}
BY LOVELEEN KAUR 18
INHERITANCE
// error
// class should be abstract
class Language {
// abstract method
abstract void method1();
}
BY LOVELEEN KAUR 19
INHERITANCE
Output
We have created the Main class that inherits the abstract class. Notice the
statement,
obj.display();
Here, obj is the object of the child class Main. We are calling the method of
the abstract class using the object obj.
If the abstract class includes any abstract method, then all the child classes
inherited from the abstract superclass must provide the implementation of
the abstract method. For example,
BY LOVELEEN KAUR 20
INHERITANCE
System.out.println("Bark bark");
}
}
class Main {
public static void main(String[] args) {
d1.makeSound();
d1.eat();
}
}
Output
Bark bark
I can eat.
In the above example, we have created an abstract class Animal. The class
contains an abstract method makeSound() and a non-abstract method eat().
We have inherited a subclass Dog from the superclass Animal. Here, the
subclass Dog provides the implementation for the abstract method makeSound().
Note: If the Dog class doesn't provide the implementation of the abstract
method makeSound(), Dog should also be declared as abstract. This is because
the subclass Dog inherits makeSound() from Animal.
BY LOVELEEN KAUR 21
INHERITANCE
An abstract class can have constructors like the regular class. And, we can
access the constructor of an abstract class from the subclass using
the super keyword. For example,
Here, we have used the super() inside the constructor of Dog to access the
constructor of the Animal .
BY LOVELEEN KAUR 22
INHERITANCE
class Main {
public static void main(String[] args) {
BY LOVELEEN KAUR 23
INHERITANCE
In Java, the final method cannot be overridden by the child class. For
example,
class FinalDemo {
// create a final method
public final void display() {
System.out.println("This is a final method.");
}
}
BY LOVELEEN KAUR 24
INHERITANCE
In Java, the final class cannot be inherited by another class. For example,
In the above example, we have created a final class named FinalClass. Here,
we have tried to inherit the final class by the Main class.
When we run the program, we will get a compilation error with the following
message.
BY LOVELEEN KAUR 25
INHERITANCE
Example
Let us look at an example.
class Animal {
public void move() {
System.out.println("Animals can move");
}
}
BY LOVELEEN KAUR 26
INHERITANCE
Output
Animals can move
Dogs can walk and run
In the above example, you can see that even though b is a type of Animal it runs the
move method in the Dog class. The reason for this is: In compile time, the check is
made on the reference type. However, in the runtime, JVM figures out the object type
and would run the method that belongs to that particular object.
Therefore, in the above example, the program will compile properly since Animal
class has the method move. Then, at the runtime, it runs the method specific for that
object.
BY LOVELEEN KAUR 27
Unit-7-OOP NOTES
Java String
In Java, string is basically an object that represents sequence of char values.
An array of characters works same as Java string. For example:
is same as:
String s="section";
Syntax
The signature of the string length() method is given below:
Example
public class LengthExample{
public static void main(String args[]){
String s1="Parul";
String s2="University";
System.out.println("string length is: "+s1.length());
System.out.println("string length is: "+s2.length());
}}
Syntax
The signature or syntax of string isEmpty() method is given below:
class Teststringcomparison1{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3=new String("Sachin");
String s4="Saurav";
System.out.println(s1.equals(s2));//true
System.out.println(s1.equals(s3));//true
System.out.println(s1.equals(s4));//false
}
}
Example 2
class Teststringcomparison2{
public static void main(String args[]){
String s1="Sachin";
String s2="SACHIN";
System.out.println(s1.equals(s2));//false
System.out.println(s1.equalsIgnoreCase(s2));//true
}
}
2) By Using == operator
The == operator compares references not values.
Teststringcomparison3.java
class Teststringcomparison3{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3=new String("Sachin");
System.out.println(s1==s2);//true (because both refer to same instance)
System.out.println(s1==s3);//false(because s3 refers to instance created in o
npool)
}
}
3) By Using compareTo() method
The String class compareTo() method compares values lexicographically and
returns an integer value that describes if first string is less than, equal to or
greater than second string.
Teststringcomparison4.java
class Teststringcomparison4{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3="Ratan";
System.out.println(s1.compareTo(s2));//0
System.out.println(s1.compareTo(s3));//1(because s1>s3)
System.out.println(s3.compareTo(s1));//-1(because s3 < s1 )
}
}
class TestStringConcatenation1{
public static void main(String args[]){
String s="Sachin"+" Tendulkar";
System.out.println(s);//Sachin Tendulkar
}
}
class TestStringConcatenation3{
public static void main(String args[]){
String s1="Sachin ";
String s2="Tendulkar";
String s3=s1.concat(s2);
System.out.println(s3);//Sachin Tendulkar
}
}
Package in java can be categorized in two form, built-in package and user-defined
package.
1) Java package is used to categorize the classes and interfaces so that they can be
easily maintained.
//save as Simple.java
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}
1. //save by A.java
2. package pack;
3. public class A{
4. public void msg(){System.out.println("Hello");}
5. }
1. //save by B.java
2. package mypack;
3. import pack.*;
4.
5. class B{
6. public static void main(String args[]){
7. A obj = new A();
8. obj.msg();
9. }
10.}
Interfaces in Java
An Interface in Java programming language is defined as an abstract type used
to specify the behavior of a class. An interface in Java is a blueprint of a
behavior. A Java interface contains static constants and abstract methods.
Like a class, an interface can have methods and variables, but the methods
declared in an interface are by default abstract (only method signature, no
body).
Interfaces specify what a class must do and not how. It is the blueprint of the
behaviour.
Interface do not have constructor.
Syntax:
interface {
// declare constant fields
// declare methods that abstract
// by default.
}
import java.io.*;
// A simple interface
interface In1 {
// Driver Code
public static void main(String[] args)
{
TestClass t = new TestClass();
t.display();
System.out.println(a);
}
}
S.
No. Class Interface
The core advantage of exception handling is to maintain the normal flow of the
application. An exception normally disrupts the normal flow of the application; that is
why we need to handle exceptions. Let's consider a scenario:
1. statement 1;
2. statement 2;
3. statement 3;
4. statement 4;
5. statement 5;//exception occurs
6. statement 6;
7. statement 7;
8. statement 8;
9. statement 9;
10. statement 10;
BY LOVELEEN KAUR 1
EXCEPTIONS HANDLING
1. Checked Exception
2. Unchecked Exception
3. Error
BY LOVELEEN KAUR 2
EXCEPTIONS HANDLING
The classes that directly inherit the Throwable class except RuntimeException and Error
are known as checked exceptions. For example, IOException, SQLException, etc.
Checked exceptions are checked at compile-time.
2) Unchecked Exception
The classes that inherit the RuntimeException are known as unchecked exceptions. For
example, ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException, etc. Unchecked exceptions are not checked at
compile-time, but they are checked at runtime.
3) Error
BY LOVELEEN KAUR 3
EXCEPTIONS HANDLING
Keyword Description
try The "try" keyword is used to specify a block where we should place an exception code. It
means we can't use try block alone. The try block must be followed by either catch or finally.
catch The "catch" block is used to handle the exception. It must be preceded by try block which
means we can't use catch block alone. It can be followed by finally block later.
finally The "finally" block is used to execute the necessary code of the program. It is executed
whether an exception is handled or not.
throws The "throws" keyword is used to declare exceptions. It specifies that there may occur an
exception in the method. It doesn't throw an exception. It is always used with method
signature.
JavaExceptionExample.java
Output:
1. int a=50/0;//ArithmeticException
2) A scenario where NullPointerException occurs
If we have a null value in any variable, performing any operation on the variable throws
a NullPointerException.
1. String s=null;
2. System.out.println(s.length());//NullPointerException
3) A scenario where NumberFormatException occurs
1. String s="abc";
2. int i=Integer.parseInt(s);//NumberFormatException
4) A scenario where ArrayIndexOutOfBoundsException occurs
BY LOVELEEN KAUR 5
EXCEPTIONS HANDLING
Java finally block is always executed whether an exception is handled or not. Therefore,
it contains all the necessary statements that need to be printed regardless of the
exception occurs or not.
TestFinallyBlock.java
class TestFinallyBlock {
public static void main(String args[]){
try{
//below code do not throw any exception
int data=25/5;
System.out.println(data);
}
//catch won't be executed
catch(NullPointerException e){
System.out.println(e);
}
//executed regardless of exception occurred or not
finally {
System.out.println("finally block is always executed");
}
Output:
BY LOVELEEN KAUR 6
EXCEPTIONS HANDLING
There are many differences between throw and throws keywords. A list of differences
between throw and throws are given below:
BY LOVELEEN KAUR 7
EXCEPTIONS HANDLING
Output:
BY LOVELEEN KAUR 8
EXCEPTIONS HANDLING
Output:
BY LOVELEEN KAUR 9
EXCEPTIONS HANDLING
Output:
BY LOVELEEN KAUR 10
MULTITHREADING
Multithreading in Java
Multithreading is a Java feature that allows concurrent execution of two or more
parts of a program for maximum utilization of CPU. Each part of such program is
called a thread. So, threads are light-weight processes within a process.
Threads can be created by using two mechanisms:
1. Extending the Thread class
2. Implementing the Runnable Interface
Thread creation by extending the Thread class
We create a class that extends the java.lang.Thread class. This class overrides the
run() method available in the Thread class. A thread begins its life inside run()
method. We create an object of our new class and call start() method to start the
execution of a thread. Start() invokes the run() method on the Thread object.
// Main Class
public class Multithread {
public static void main(String[] args)
{
int n = 8; // Number of threads
for (int i = 0; i < n; i++) {
MultithreadingDemo object
= new MultithreadingDemo();
object.start();
}
BY LOVELEEN KAUR 1
MULTITHREADING
}
}
Thread creation by implementing the Runnable Interface
// Main Class
class Multithread {
public static void main(String[] args)
{
int n = 8; // Number of threads
for (int i = 0; i < n; i++) {
Thread object
= new Thread(new MultithreadingDemo());
object.start();
}
}
}
1. If we extend the Thread class, our class cannot extend any other
class because Java doesn’t support multiple inheritance. But, if we
BY LOVELEEN KAUR 2
MULTITHREADING
implement the Runnable interface, our class can still extend other
base classes.
2. We can achieve basic functionality of a thread by extending Thread
class because it provides some inbuilt methods like yield(),
interrupt() etc. that are not available in Runnable interface.
3. Using runnable will give you an object that can be shared amongst
multiple threads.
2) Daemon Thread :
Daemon threads are threads which are mostly created by the JVM. These
threads always run in background. These threads are used to perform some
background tasks like garbage collection and house-keeping tasks. These
threads are less priority threads. JVM will not wait for these threads to finish
their execution. JVM will exit as soon as all user threads finish their execution.
JVM doesn’t wait for daemon threads to finish their task.
BY LOVELEEN KAUR 3
COLLECTIONS FRAMEWORK
Let us see the hierarchy of Collection framework. The java.util package contains all
the classes and interfaces for the Collection framework.
BY LOVELEEN KAUR 1
COLLECTIONS FRAMEWORK
The Java collections framework provides various interfaces. These interfaces include
several methods to perform different operations on collections.
The Collection interface is the root interface of the collections framework hierarchy.
Java does not provide direct implementations of the Collection interface but provides
implementations of its subinterfaces like List, Set, and Queue .
BY LOVELEEN KAUR 2
COLLECTIONS FRAMEWORK
The List interface is an ordered collection that allows us to add and remove elements
like an array.
Set Interface
The Set interface allows us to store elements in different sets similar to the set in
mathematics. It cannot have duplicate elements.
Queue Interface
The Queue interface is used when we want to store and access elements in First In,
First Out manner.
Methods of Collection
The Collection interface includes various methods that can be used to perform
different operations on objects. These methods are available in all its subinterfaces.
add() - inserts the specified element to the collection
size() - returns the size of the collection
remove() - removes the specified element from the collection
iterator() - returns an iterator to access elements of the collection
addAll() - adds all the elements of a specified collection to the collection
removeAll() - removes all the elements of the specified collection from the
collection
clear() - removes all the elements of the collection
BY LOVELEEN KAUR 3
COLLECTIONS FRAMEWORK
In Java, the Map interface allows elements to be stored in key/value pairs. Keys are
unique names that can be used to access a particular element in a map. And, each
key has a single value associated with it.
In Java, the Iterator interface provides methods that can be used to access elements
of collections.
The Java collections framework provides various data structures and algorithms that
can be used directly. This has two main advantages:
We do not have to write code to implement these data structures and algorithms
manually.
Our code will be much more efficient as the collections framework is highly
optimized.
Moreover, the collections framework allows us to use a specific data structure for a
particular type of data. Here are a few examples,
If we want our data to be unique, then we can use the Set interface provided
by the collections framework.
To store data in key/value pairs, we can use the Map interface.
The ArrayList class provides the functionality of resizable arrays.
BY LOVELEEN KAUR 4
COLLECTIONS FRAMEWORK
The ArrayList class allows us to create resizable arrays. The class implements
the List interface (which is a subinterface of the Collection interface).
class Main {
public static void main(String[] args){
ArrayList<String> animals = new ArrayList<>();
// Add elements
animals.add("Dog");
animals.add("Cat");
animals.add("Horse");
class Main {
public static void main(String[] args) {
ArrayList<String> animals = new ArrayList<>();
BY LOVELEEN KAUR 5
COLLECTIONS FRAMEWORK
In the above example, we have used the get() method with parameter 1. Here, the
method returns the element at index 1.
Java Vector
The Vector class is an implementation of the List interface that allows us to create
resizable-arrays similar to the ArrayList class.
In Java, both ArrayList and Vector implements the List interface and provides the
same functionalities. However, there exist some differences between them.
The Vector class synchronizes each individual operation. This means whenever we
want to perform some operation on vectors, the Vector class automatically applies a
lock to that operation.
It is because when one thread is accessing a vector, and at the same time another
thread tries to access it, an exception called ConcurrentModificationException is
generated. Hence, this continuous use of lock for each operation makes vectors less
efficient.
However, in array lists, methods are not synchronized. Instead, it uses
the Collections.synchronizedList() method that synchronizes the list as a whole.
BY LOVELEEN KAUR 6
COLLECTIONS FRAMEWORK
import java.util.Vector;
class Main {
public static void main(String[] args) {
Vector<String> mammals= new Vector<>();
// Using addAll()
Vector<String> animals = new Vector<>();
animals.add("Crocodile");
animals.addAll(mammals);
System.out.println("New Vector: " + animals);
}
}
Output
-remove(index)
removes an element from specified position
BY LOVELEEN KAUR 7
COLLECTIONS FRAMEWORK
import java.util.Vector;
class Main {
public static void main(String[] args) {
Vector<String> animals= new Vector<>();
animals.add("Dog");
animals.add("Horse");
animals.add("Cat");
// Using remove()
String element = animals.remove(1);
System.out.println("Removed Element: " + element);
System.out.println("New Vector: " + animals);
// Using clear()
animals.clear();
System.out.println("Vector after clear(): " + animals);
}
}
Output
The Map interface of the Java collections framework provides the functionality of the
map data structure.
Working of Map
In Java, elements of Map are stored in key/value pairs. Keys are unique values
associated with individual Values.
BY LOVELEEN KAUR 8
COLLECTIONS FRAMEWORK
A map cannot contain duplicate keys. And, each key is associated with a single value.
We can access and modify values using the keys associated with them.
In the above diagram, we have values: United States, Brazil, and Spain. And we have
corresponding keys: us, br, and es.
Now, we can access those values using their corresponding keys.
BY LOVELEEN KAUR 9
COLLECTIONS FRAMEWORK
In Java, we must import the java.util.Map package in order to use Map. Once we
import the package, here's how we can create a map.
In the above code, we have created a Map named numbers. We have used
the HashMap class to implement the Map interface.
Here,
class Main {
BY LOVELEEN KAUR 10
COLLECTIONS FRAMEWORK
BY LOVELEEN KAUR 11
COLLECTIONS FRAMEWORK
The Iterator interface of the Java collections framework allows us to access elements
of a collection. It has a subinterface ListIterator.
BY LOVELEEN KAUR 11
COLLECTIONS FRAMEWORK
All the Java collections include an iterator() method. This method returns an instance
of iterator used to iterate over elements of collections.
Methods of Iterator
The Iterator interface provides 4 methods that can be used to perform various
operations on elements of collections.
hasNext() - returns true if there exists an element in the collection
next() - returns the next element of the collection
remove() - removes the last element returned by the next()
forEachRemaining() - performs the specified action for each remaining
element of the collection
class Main {
public static void main(String[] args) {
// Creating an ArrayList
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(1);
numbers.add(3);
numbers.add(2);
System.out.println("ArrayList: " + numbers);
BY LOVELEEN KAUR 12
COLLECTIONS FRAMEWORK
ArrayList: [1, 3, 2]
Acessed Element: 1
Removed Element: 1
Updated ArrayList: 3, 2,
import java.util.Iterator;
import java.util.Vector;
class Main {
public static void main(String[] args) {
Vector<String> animals= new Vector<>();
animals.add("Dog");
animals.add("Horse");
animals.add("Cat");
// Using get()
BY LOVELEEN KAUR 13
COLLECTIONS FRAMEWORK
// Using iterator()
Iterator<String> iterate = animals.iterator();
System.out.print("Vector: ");
while(iterate.hasNext()) {
System.out.print(iterate.next());
System.out.print(", ");
}
}
}
Output
BY LOVELEEN KAUR 14