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

OOPS NOTES 1 to 10

Java is a high-level, robust, object-oriented programming language developed by Sun Microsystems in 1995, known for its platform independence and extensive use across various applications. It encompasses four main types of applications: standalone, web, enterprise, and mobile, and operates through different platforms including Java SE, EE, ME, and JavaFX. The document also covers core concepts of Java such as JVM, JRE, JDK, and fundamental object-oriented programming principles like inheritance, polymorphism, encapsulation, and abstraction.

Uploaded by

rahulpamula123
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

OOPS NOTES 1 to 10

Java is a high-level, robust, object-oriented programming language developed by Sun Microsystems in 1995, known for its platform independence and extensive use across various applications. It encompasses four main types of applications: standalone, web, enterprise, and mobile, and operates through different platforms including Java SE, EE, ME, and JavaFX. The document also covers core concepts of Java such as JVM, JRE, JDK, and fundamental object-oriented programming principles like inheritance, polymorphism, encapsulation, and abstraction.

Uploaded by

rahulpamula123
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 154

DESIGN INTRODUCTION

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.

Types of Java Applications


There are mainly 4 types of applications that can be created using Java programming:
1) Standalone Application
Standalone applications are also known as desktop applications or window-based applications.
These are traditional software that we need to install on every machine. Examples of standalone
application are Media player, antivirus, etc. AWT and Swing are used in Java for creating
standalone applications.

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.

Java Platforms / Editions


There are 4 platforms or editions of Java:
1) Java SE (Java Standard Edition)
It is a Java programming platform. It includes Java programming APIs such as java.lang,
java.io, java.net, java.util, java.sql, java.math etc. It includes core topics like OOPs, String,
Regex, Exception, Inner classes, Multithreading, I/O Stream, Networking, AWT, Swing,
Reflection, Collection, etc.
2) Java EE (Java Enterprise Edition)
It is an enterprise platform that is mainly used to develop web and enterprise applications. It is
built on top of the Java SE platform. It includes topics like Servlet, JSP, Web Services,
EJB, JPA, etc.
3) Java ME (Java Micro Edition)
It is a micro platform that is dedicated to mobile applications.
4) JavaFX
It is used to develop rich internet applications. It uses a lightweight user interface API.

Difference between JDK, JRE, and JVM


JVM
JVM (Java Virtual Machine) is an abstract machine. It is called a virtual machine because
it doesn't physically exist. It is a specification that provides a runtime environment in
which Java bytecode can be executed. It can also run those programs which are written
in other languages and compiled to Java bytecode.
JVMs are available for many hardware and software platforms. JVM, JRE, and JDK are
platform dependent because the configuration of each OS is different from each other.
However, Java is platform independent. There are three notions of the
JVM: specification, implementation, and instance.
The JVM performs the following main tasks:

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.

JVM (Java Virtual Machine) Architecture


JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides
runtime environment in which java bytecode can be executed.
JVMs are available for many hardware and software platforms (i.e. JVM is platform
dependent).

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 provides definitions for the:


o Memory area
o Class file format
o Register set
o Garbage-collected heap
o Fatal error reporting etc.

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.

//Let's see an example to print the classloader name


public class ClassLoaderExample
{
public static void main(String[] args)
{
// Let's print the classloader name of current class.
//Application/System classloader will load this class
Class c=ClassLoaderExample.class;
System.out.println(c.getClassLoader());
//If we print the classloader name of String, it will print null because it is an
//in-
built class which is found in rt.jar, so it is loaded by Bootstrap classloader
System.out.println(String.class.getClassLoader());
}
}
Output:
sun.misc.Launcher$AppClassLoader@4e0e2f2a
null
These are the internal classloaders provided by Java. If you want to create your own
classloader, you need to extend the ClassLoader class.

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

5) Program Counter Register


PC (program counter) register contains the address of the Java virtual machine
instruction currently being executed.

6) Native Method Stack


It contains all the native methods used in the application.

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.

8) Java Native Interface


Java Native Interface (JNI) is a framework which provides an interface to communicate
with another application written in another language like C, C++, Assembly etc. Java uses
JNI framework to send output to the Console or interact with OS libraries.

Java OOPs Concepts


In this page, we will learn about the basics of OOPs. Object-Oriented Programming is a
paradigm that provides many concepts, such as inheritance, data
binding, polymorphism, etc.
Simula is considered the first object-oriented programming language. The programming
paradigm where everything is represented as an object is known as a truly object-
oriented programming language.
Smalltalk is considered the first truly object-oriented programming language.
The popular object-oriented languages are Java, C#, PHP, Python, C++, etc.

The main aim of object-oriented programming is to implement real-world entities, for


example, object, classes, abstraction, inheritance, polymorphism, etc.

OOPs (Object-Oriented Programming System)


Object means a real-world entity such as a pen, chair, table, computer, watch,
etc. Object-Oriented Programming is a methodology or paradigm to design a program
using classes and objects. It simplifies software development and maintenance by
providing some concepts:
o Object

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

Inheritance is an object-oriented programming concept in which one class acquires


the properties and behavior of another class. It represents a parent-child relationship
between two classes. This parent-child relationship is also known as an IS-A
relationship.
When one object acquires all the properties and behaviors of a parent object, it is
known as inheritance. It provides code reusability. It is used to achieve runtime
polymorphism.

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.

Polymorphism in Java is mainly divided into two types.

● Compile-time polymorphism
● Runtime polymorphism

Compile-time polymorphism can be achieved by method overloading, and Runtime


polymorphism can be achieved by method overriding. In the further article, we will be
discussing all the topics related to polymorphism in Java in more detail.

Abstraction

BY LOVELEEN KAUR 1
DESIGN INTRODUCTION

Abstraction in Java refers to hiding the implementation details of a code and


exposing only the necessary information to the user. It provides the ability to
simplify complex systems by ignoring irrelevant details and reducing complexity.
So hiding internal details of implementation and showing the functionality of the
methods is known as abstraction. For example phone call, we don't know the internal
processing.
In Java, we use abstract class and interface to achieve abstraction.

Encapsulation

Encapsulation is a way to restrict the direct access to some components of an object, so


users cannot access state values for all of the variables of a particular object.
Encapsulation can be used to hide both data members and data functions or methods
associated with an instantiated class or object.
A java class is the example of encapsulation. Java bean is the fully encapsulated class
because all the data members are private here.

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.

Advantage of OOPs over Procedure-oriented


programming language
1) OOPs makes development and maintenance easier, whereas, in a procedure-oriented
programming language, it is not easy to manage if code grows as project size increases.
2) OOPs provides data hiding, whereas, in a procedure-oriented programming language,
global data can be accessed from anywhere.

Figure: Data Representation in Procedure-Oriented Programming

BY LOVELEEN KAUR 1
DESIGN INTRODUCTION

Figure: Data Representation in Object-Oriented Programming


3) OOPs provides the ability to simulate real-world event much more effectively. We
can provide the solution of real word problem if we are using the Object-Oriented
Programming language.

What is the difference between an object-oriented


programming language and object-based programming
language?
Object-based programming language follows all the features of OOPs except
Inheritance. JavaScript and VBScript are examples of object-based programming
languages.

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 −

 Primitive Data Types


 Reference/Object Data Types

Primitive Data Types


There are eight primitive datatypes supported by Java. Primitive datatypes are
predefined by the language and named by a keyword. Let us now look into the eight
primitive data types in detail.

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

 Maximum value is 127 (inclusive)(2^7 -1)


 Default value is 0
 Byte data type is used to save space in large arrays, mainly in place of
integers, since a byte is four times smaller than an integer.
 Example: byte a = 100, byte b = -50
short
 Short data type is a 16-bit signed two's complement integer
 Minimum value is -32,768 (-2^15)
 Maximum value is 32,767 (inclusive) (2^15 -1)
 Short data type can also be used to save memory as byte data type. A
short is 2 times smaller than an integer
 Default value is 0.
 Example: short s = 10000, short r = -20000
int
 Int data type is a 32-bit signed two's complement integer.
 Minimum value is - 2,147,483,648 (-2^31)
 Maximum value is 2,147,483,647(inclusive) (2^31 -1)
 Integer is generally used as the default data type for integral values
unless there is a concern about memory.
 The default value is 0
 Example: int a = 100000, int b = -200000
long
 Long data type is a 64-bit signed two's complement integer
 Minimum value is -9,223,372,036,854,775,808(-2^63)
 Maximum value is 9,223,372,036,854,775,807 (inclusive)(2^63 -1)
 This type is used when a wider range than int is needed
 Default value is 0L
 Example: long a = 100000L, long b = -200000L
float
 Float data type is a single-precision 32-bit IEEE 754 floating point
 Float is mainly used to save memory in large arrays of floating point
numbers
 Default value is 0.0f
 Float data type is never used for precise values such as currency
 Example: float f1 = 234.5f
double
 double data type is a double-precision 64-bit IEEE 754 floating point
 This data type is generally used as the default data type for decimal
values, generally the default choice

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'


Data Type Default Value Default size

Boolean False 1 bit

Char '\u0000' 2 byte

Byte 0 1 byte

Short 0 2 byte

Int 0 4 byte

Long 0L 8 byte

Float 0.0f 4 byte

Double 0.0d 8 byte

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 −

int decimal = 100;


int octal = 0144;
int hexa = 0x64;
String literals in Java are specified like they are in most other languages by enclosing
a sequence of characters between a pair of double quotes. Examples of string literals
are −

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 −

Notation Character represented

\n Newline (0x0a)

\r Carriage return (0x0d)

\f Formfeed (0x0c)

\b Backspace (0x08)

\s Space (0x20)

\t Tab

\" Double quote

\' Single quote

\\ Backslash

\ddd Octal character (ddd)

\uxxxx Hexadecimal UNICODE character (xxxx)

Note->for more detail of escape sequence please refer:

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.

public class Test {


public void pupAge() {
int age = 0;
age = age + 7;
System.out.println("Puppy age is : " + age);
}

public static void main(String args[]) {


Test test = new Test();
test.pupAge();
}
}
This will produce the following result −

Output
Puppy age is: 7
Example
Following example uses age without initializing it, so it would give an error at the
time of compilation.

public class Test {


public void pupAge() {
int age;
age = age + 7;
System.out.println("Puppy age is : " + age);
}

public static void main(String args[]) {


Test test = new Test();
test.pupAge();
}
}
This will produce the following error while compiling it −

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 {

// this instance variable is visible for any child class.


public String name;

// salary variable is visible in Employee class only.


private double salary;

// The name variable is assigned in the constructor.


public Employee (String empName) {
name = empName;
}

// The salary variable is assigned a value.


public void setSalary(double empSal) {
salary = empSal;
}

// This method prints the employee details.

BY LOVELEEN KAUR 8
JAVA DATA TYPES VARIABLES & OPERATORS

public void printEmp() {


System.out.println("name : " + name );
System.out.println("salary :" + salary);
}

public static void main(String args[]) {


Employee empOne = new Employee("Ransika");
empOne.setSalary(1000);
empOne.printEmp();
}
}
This will produce the following result −

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 {

// salary variable is a private static variable


private static double salary;

// DEPARTMENT is a constant
public static final String DEPARTMENT = "Development ";

public static void main(String args[])


{
salary = 1000;
System.out.println(DEPARTMENT + "average salary:" + salary);
}
}
This will produce the following result −

Output
Development average salary:1000
Note − If the variables are accessed from an outside class, the constant should be
accessed as Employee.DEPARTMENT

What do you mean by a dynamic initialization of variables?

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.

Java Píogíam to vaíiables dynamic initialization

Let us see the few examples of how to initialize vaíiables at íun time.

Cíeating a class with the only constíuctoí.

class Rectangle {
private double length;
private double width;

BY LOVELEEN KAUR 10
JAVA DATA TYPES VARIABLES & OPERATORS

public Rectangle(double length, double width) {

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);

//Rectangle rectangle2 = new Rectangle(5.5, 7.5);

//Rectangle rectangle3 = new Rectangle(2.9, 10);

}
in the above píogíam, length and width aíe initialized at íuntime with diffeíent values foí each
Rectangle object.

Setteí methods based dynamic initialization:

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;
}

public void setLength(double length) {


this.length = length;
}

public double getWidth() {


return width;
}

public void setWidth(double width) {


this.width = width;
}
public void printdata()
{
System.out.println("Length is:"+length);
System.out.println("Width is:"+width);
}

public static void main(String[] args) {

Rectangle rectangle4 = new Rectangle();


rectangle4.setLength(20);
rectangle4.setWidth(30);
rectangle4.printdata();

}
}

Now, values can be set at íuntime using setteí methods.

BY LOVELEEN KAUR 12
JAVA DATA TYPES VARIABLES & OPERATORS

Scope and lifetime of variables in Java?


Instance Variables
A variable which is declared inside a class and outside all the methods and blocks is
an instance variable. The general scope of an instance variable is throughout the
class except in static methods. The lifetime of an instance variable is until the object
stays in memory.

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.

What is type conversion in java?


Java provides various datatypes to store various data values. It provides 7 primitive
datatypes (stores single values) as listed below −

 boolean − Stores 1-bit value representing true or, false.


 byte − Stores twos compliment integer up to 8 bits.
 char − Stores a Unicode character value up to 16 bits.
 short − Stores an integer value upto 16 bits.
 int − Stores an integer value upto 32 bits.
 long − Stores an integer value upto 64 bits.
 float − Stores a floating point value upto 32bits.
 double − Stores a floating point value up to 64 bits.

Type Casting/type conversion


Converting one primitive datatype into another is known as type casting (type
conversion) in Java. You can cast the primitive datatypes in two ways namely,
Widening and, Narrowing.

Widening − Converting a lower datatype to a higher datatype is known as widening.


In this case the casting/conversion is done automatically therefore, it is known as

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.:

o incrementing/decrementing a value by one


o negating an expression
o inverting the value of a boolean

Java Unary Operator Example: ++ and --


public class OperatorExample{
public static void main(String args[]){
int x=10;
System.out.println(x++);//10 (11)
System.out.println(++x);//12
System.out.println(x--);//12 (11)
System.out.println(--x);//10
}}

Output:

10
12
12
10
Java Unary Operator Example 2: ++ and --
public class OperatorExample{

BY LOVELEEN KAUR 16
JAVA DATA TYPES VARIABLES & OPERATORS

public static void main(String args[]){


int a=10;
int b=10;
System.out.println(a++ + ++a);//10+12=22
System.out.println(b++ + b++);//10+11=21

}}

Output:

22
21

The Arithmetic Operators


Arithmetic operators are used in mathematical expressions in the same way that they
are used in algebra. The following table lists the arithmetic operators −
Assume integer variable A holds 10 and variable B holds 20, then −

Operator Description Example

Adds values on either side of the operator. A+B


+ (Addition) will give
30

Subtracts right-hand operand from left-hand operand. A-B


- (Subtraction) will give
-10

Multiplies values on either side of the operator. A*B


* (Multiplication) will give
200

Divides left-hand operand by right-hand operand. B/A


/ (Division) will give
2

BY LOVELEEN KAUR 17
JAVA DATA TYPES VARIABLES & OPERATORS

Divides left-hand operand by right-hand operand and B%A


% (Modulus) returns remainder. will give
0

Increases the value of operand by 1. B++


++ (Increment)
gives 21

Decreases the value of operand by 1. B--


-- (Decrement)
gives 19

Example
public class Test {

public static void main(String args[]) {


int a = 10;
int b = 20;
int c = 25;
int d = 25;

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--) );

// Check the difference in d++ and ++d


System.out.println("d++ = " + (d++) );
System.out.println("++d = " + (++d) );
}
}
This will produce the following result −

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.

Java Left Shift Operator Example


public class OperatorExample{
public static void main(String args[]){
System.out.println(10<<2);//10*2^2=10*4=40
System.out.println(10<<3);//10*2^3=10*8=80
System.out.println(20<<2);//20*2^2=20*4=80
System.out.println(15<<4);//15*2^4=15*16=240
}}

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.

Java Right Shift Operator Example


public OperatorExample{
public static void main(String args[]){
System.out.println(10>>2);//10/2^2=10/4=2
System.out.println(20>>2);//20/2^2=20/4=5
System.out.println(20>>3);//20/2^3=20/8=2
}}

Output:

2
5
2

BY LOVELEEN KAUR 19
JAVA DATA TYPES VARIABLES & OPERATORS

Java Shift Operator Example: >> vs >>>


public class OperatorExample{
public static void main(String args[]){
//For positive number, >> and >>> works same
System.out.println(20>>2);
System.out.println(20>>>2);
//For negative number, >>> changes parity bit (MSB) to 0
System.out.println(-20>>2);
System.out.println(-20>>>2);
}}

Output:

5
5
-5
1073741819

The Relational Operators


There are following relational operators supported by Java language.
Assume variable A holds 10 and variable B holds 20, then −

Operator Description Example

Checks if the values of two operands are equal or not, if (A == B) is


== (equal to)
yes then condition becomes true. not true.

Checks if the values of two operands are equal or not, if (A != B) is


!= (not equal to)
values are not equal then condition becomes true. true.

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

Checks if the value of left operand is greater than or


>= (greater than (A >= B) is
equal to the value of right operand, if yes then condition
or equal to) not true.
becomes true.

Checks if the value of left operand is less than or equal to


<= (less than or
the value of right operand, if yes then condition becomes
equal to)
true.

Example
public class Test {

public static void main(String args[]) {


int a = 10;
int b = 20;

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

a&b = 0000 1100


a|b = 0011 1101
a^b = 0011 0001
~a = 1100 0011
The following table lists the bitwise operators −
Assume integer variable A holds 60 and variable B holds 13 then −

Operator Description Example

& (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

Binary OR Operator copies a bit if it exists (A | B) will give 61 which is


| (bitwise or)
in either operand. 0011 1101

^ (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

(~A ) will give -61 which is


~ (bitwise Binary Ones Complement Operator is unary 1100 0011 in 2's
compliment) and has the effect of 'flipping' bits. complement form due to a
signed binary number.

Binary Left Shift Operator. The left


A << 2 will give 240 which is
<< (left shift) operands value is moved left by the number
1111 0000
of bits specified by the right operand.

Binary Right Shift Operator. The left


operands value is moved right by the A >> 2 will give 15 which is
>> (right shift)
number of bits specified by the right 1111
operand.

>>> (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

operand and shifted values are filled up


with zeros.

Example
public class Test {

public static void main(String args[]) {


int a = 60; /* 60 = 0011 1100 */
int b = 13; /* 13 = 0000 1101 */
int c = 0;

c = a & b; /* 12 = 0000 1100 */


System.out.println("a & b = " + c );

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; /*-61 = 1100 0011 */


System.out.println("~a = " + c );

c = a << 2; /* 240 = 1111 0000 */


System.out.println("a << 2 = " + c );

c = a >> 2; /* 15 = 1111 */
System.out.println("a >> 2 = " + c );

c = a >>> 2; /* 15 = 0000 1111 */


System.out.println("a >>> 2 = " + c );
}
}
This will produce the following result −

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

The Logical Operators


The following table lists the logical operators −
Assume Boolean variables A holds true and variable B holds false, then −

Operator Description Example

Called Logical AND operator. If both the


&& (logical and) operands are non-zero, then the condition (A && B) is false
becomes true.

Called Logical OR Operator. If any of the two


|| (logical or) operands are non-zero, then the condition (A || B) is true
becomes true.

Called Logical NOT Operator. Use to reverses


! (logical not) the logical state of its operand. If a condition is !(A && B) is true
true then Logical NOT operator will make false.

Example
public class Test {

public static void main(String args[]) {


boolean a = true;
boolean b = false;

System.out.println("a && b = " + (a&&b));


System.out.println("a || b = " + (a||b) );
System.out.println("!(a && b) = " + !(a && b));
}
}
This will produce the following result −

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

public class Test {

public static void main(String args[]) {


int a, b;
a = 10;
b = (a == 1) ? 20: 30;
System.out.println( "Value of b is : " + b );

b = (a == 10) ? 20: 30;


System.out.println( "Value of b is : " + b );
}
}
This will produce the following result −
Output
Value of b is : 30
Value of b is : 20

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

public class Test {

public static void main(String args[]) {

BY LOVELEEN KAUR 25
JAVA DATA TYPES VARIABLES & OPERATORS

String name = "James";

// following will return true since name is type of String


boolean result = name instanceof String;
System.out.println( result );
}
}
This will produce the following result −
Output
true
The Assignment Operators
Following are the assignment operators supported by Java language −

Operator Description Example

Simple assignment operator. Assigns values from right side C=A+B


operands to left side operand. will
= assign
value of A
+ B into C

Add AND assignment operator. It adds right operand to the left C += A is


operand and assign the result to left operand. equivalent
+=
to C = C +
A

Subtract AND assignment operator. It subtracts right operand from C -= A is


the left operand and assign the result to left operand. equivalent
-=
to C = C –
A

Multiply AND assignment operator. It multiplies right operand with C *= A is


the left operand and assign the result to left operand. equivalent
*=
to C = C *
A

/= Divide AND assignment operator. It divides left operand with the C /= A is


right operand and assign the result to left operand. equivalent

BY LOVELEEN KAUR 26
JAVA DATA TYPES VARIABLES & OPERATORS

to C = C /
A

Modulus AND assignment operator. It takes modulus using two C %= A is


operands and assign the result to left operand. equivalent
%=
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

bitwise exclusive OR and assignment operator. C ^= 2 is


^= same as C
=C^2

bitwise inclusive OR and assignment operator. C |= 2 is


|= same as C
=C|2

Example
public class Test {

public static void main(String args[]) {


int a = 10;
int b = 20;
int c = 0;

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

Java Control Statements | Control Flow in Java


Java compiler executes the code from top to bottom. The statements in the code are
executed according to the order in which they appear. However, Java provides
statements that can be used to control the flow of Java code. Such statements are
called control flow statements. It is one of the fundamental features of Java, which
provides a smooth flow of program.

Java provides three types of control flow statements.

1. Decision Making statements


o if statements
o switch statement
2. Loop statements
o do while loop
o while loop
o for loop
o for-each loop
3. Jump statements
o break statement
o continue statement

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

Let's understand the if-statements one by one.

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.

Syntax of if statement is given below.

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

public class Student {


public static void main(String[] args) {
int x = 10;
int y = 12;
if(x+y > 20) {
System.out.println("x + y is greater than 20");
}
}
}

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
}

Consider the following example.

Student.java

public class Student {


public static void main(String[] args) {
int x = 10;
int y = 12;
if(x+y < 10) {
System.out.println("x + y is less than 10");
} else {
System.out.println("x + y is greater than 20");
}
}
}

Output:

x + y is greater than 20
3) if-else-if ladder:

The if-else-if statement contains the if-statement followed by multiple else-if


statements. In other words, we can say that it is the chain of if-else statements that
create a decision tree where the program may enter in the block of code where the
condition is true. We can also define an else statement at the end of the chain.

BY LOVELEEN KAUR 3
CONTROL STATEMENTS

Syntax of if-else-if statement is given below.

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
}

Consider the following example.

Student.java

public class Student {


public static void main(String[] args) {
String city = "Delhi";
if(city == "Meerut") {
System.out.println("city is meerut");
}else if (city == "Noida") {
System.out.println("city is noida");
}else if(city == "Agra") {
System.out.println("city is agra");
}else {
System.out.println(city);
}
}
}

Output:

Delhi
4. Nested if-statement

In nested if-statements, the if statement can contain a if or if-else statement inside


another if or else-if statement.

Syntax of Nested if-statement is given below.

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
}
}

Consider the following example.

Student.java

public class Student {


public static void main(String[] args) {
String address = "Delhi, India";

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.

Points to be noted about switch statement:

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.

The syntax to use the switch statement is given below.

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

public class Student implements Cloneable {


public static void main(String[] args) {
int num = 2;

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

Let's understand the loop statements one by one.

Java for loop


In Java, for loop is similar to C and C++. It enables us to initialize the loop variable,
check the condition, and increment/decrement in a single line of code. We use the for

BY LOVELEEN KAUR 7
CONTROL STATEMENTS

loop only when we exactly know the number of times, we want to execute the block
of code.

for(initialization, condition, increment/decrement) {


//block of statements
}

The flow chart for the for-loop is given below.

Consider the following example to understand the proper functioning of the for loop
in java.

Calculation.java

public class Calculattion {


public static void main(String[] args) {
// TODO Auto-generated method stub
int sum = 0;
for(int j = 1; j<=10; j++) {
sum = sum + j;
}
System.out.println("The sum of first 10 natural numbers is " + sum);
}
}

Output:

The sum of first 10 natural numbers is 55

BY LOVELEEN KAUR 8
CONTROL STATEMENTS

Java for-each loop


Java provides an enhanced for loop to traverse the data structures like array or
collection. In the for-each loop, we don't need to update the loop variable. The syntax
to use the for-each loop in java is given below.

1. for(data_type var : array_name/collection_name){


2. //statements
3. }

Consider the following example to understand the functioning of the for-each loop in
Java.

Calculation.java

public class Calculation {


public static void main(String[] args) {
// TODO Auto-generated method stub
String[] names = {"Java","C","C++","Python","JavaScript"};
System.out.println("Printing the content of the array names:\n");
for(String name:names) {
System.out.println(name);
}
}
}

Output:

Printing the content of the array names:

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.

The syntax of the while loop is given below.

1. while(condition){
2. //looping statements
3. }

The flow chart for the while loop is given in the following image.

Consider the following example.

Calculation .java

public class Calculation {


public static void main(String[] args) {
// TODO Auto-generated method stub
int i = 0;

BY LOVELEEN KAUR 10
CONTROL STATEMENTS

System.out.println("Printing the list of first 10 even numbers \n");


while(i<=10) {
System.out.println(i);
i = i + 2;
}
}
}

Output:

Printing the list of first 10 even numbers

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

public class Calculation {


public static void main(String[] args) {
// TODO Auto-generated method stub
int i = 0;
System.out.println("Printing the list of first 10 even numbers \n");
do {
System.out.println(i);
i = i + 2;
}while(i<=10);
}
}

Outpt:

Printing the list of first 10 even numbers


0
2
4
6

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.

Java break statement


As the name suggests, the break statement is used to break the current flow of the
program and transfer the control to the next statement outside a loop or switch
statement. However, it breaks only the inner loop in the case of the nested loop.

The break statement cannot be used independently in the Java program, i.e., it can
only be written inside the loop or switch statement.

The break statement example with for loop

Consider the following example in which we have used the break statement with the
for loop.

BreakExample.java

public class BreakExample {

public static void main(String[] args) {


// TODO Auto-generated method stub
for(int i = 0; i<= 10; i++) {
System.out.println(i);
if(i==6) {
break;
}
}
}
}

Output:

0
1
2

BY LOVELEEN KAUR 13
CONTROL STATEMENTS

3
4
5
6

break statement example with labeled for loop

Calculation.java

public class Calculation {

public static void main(String[] args) {


// TODO Auto-generated method stub
a:
for(int i = 0; i<= 10; i++) {
b:
for(int j = 0; j<=15;j++) {
c:
for (int k = 0; k<=20; k++) {
System.out.println(k);
if(k==5) {
break a;
}
}
}

}
}

Output:

0
1
2
3
4
5

BY LOVELEEN KAUR 14
CONTROL STATEMENTS

Java continue statement


Unlike break statement, the continue statement doesn't break the loop, whereas, it
skips the specific part of the loop and jumps to the next iteration of the loop
immediately.

Consider the following example to understand the functioning of the continue


statement in Java.

public class ContinueExample {

public static void main(String[] args) {


// TODO Auto-generated method stub

for(int i = 0; i<= 2; i++) {

for (int j = i; j<=5; j++) {

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

Creating, initializing, and accessing an Array

One-Dimensional Arrays:

The general form of a one-dimensional array declaration is


type var-name[];
OR
type[] var-name;
An array declaration has two components: the type and the name. type declares
the element type of the array. The element type determines the data type of each
element that comprises the array. Like an array of integers, we can also create an
array of other primitive data types like char, float, double, etc., or user-defined data
types (objects of a class). Thus, the element type for the array determines what
type of data the array will hold.
Example:
// both are valid declarations
int intArray[];
or int[] intArray;

byte byteArray[];
short shortsArray[];
boolean booleanArray[];
long longArray[];
float floatArray[];
double doubleArray[];
char charArray[];

// an array of references to objects of


// the class MyClass (a class created by
// user)
MyClass myClassArray[];

Object[] ao, // array of Object


Collection[] ca; // array of Collection

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.

Instantiating an Array in Java

When an array is declared, only a reference of an array is created. To create or give


memory to the array, you create an array like this: The general form of new as it
applies to one-dimensional arrays appears as follows:
var-name = new type [size];
Here, type specifies the type of data being allocated, size determines the number of
elements in the array, and var-name is the name of the array variable that is linked
to the array. To use new to allocate an array, you must specify the type and
number of elements to allocate.
Example:
int intArray[]; //declaring array
intArray = new int[20]; // allocating memory to array
OR
int[] intArray = new int[20]; // combining both statements in one
Note:
The elements in the array allocated by new will automatically be initialized
to zero (for numeric types), false (for boolean), or null (for reference types). Do
refer to default array values in Java.
Obtaining an array is a two-step process. First, you must declare a variable of the
desired array type. Second, you must allocate the memory to hold the array, using
new, and assign it to the array variable. Thus, in Java, all arrays are dynamically
allocated.

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

Accessing Java Array Elements using for Loop

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:

// Java program to illustrate creating an array

// of integers, puts some values in the array,

// and prints each value to standard output.

class Arrays {
public static void main(String[] args)
{
// declares an Array of integers.
int[] arr;

// allocating memory for 5 integers.


arr = new int[5];

// initialize the first elements of the array


arr[0] = 10;

// initialize the second elements of the array


arr[1] = 20;

// so on...
arr[2] = 30;
arr[3] = 40;
arr[4] = 50;

// accessing the elements of the specified array


for (int i = 0; i < arr.length; i++)
System.out.println("Element at index " + i
+ " : " + arr[i]);
}
}

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.

 It starts with the keyword for like a normal for-loop.


 Instead of declaring and initializing a loop counter variable, you
declare a variable that is the same type as the base type of the array,
followed by a colon, which is then followed by the array name.
 In the loop body, you can use the loop variable you created rather
than using an indexed array element.
 It’s commonly used to iterate over an array or a Collections class
(eg, ArrayList)
Syntax:
for (type var : array)
{
statements using var;
}
Simple program with for each loop:
/*package whatever //do not write package name here */

import java.io.*;

class Easy

public static void main(String[] args)

// array declaration

BY LOVELEEN KAUR 5
ARRAYS

int ar[] = { 10, 50, 60, 80, 90 };

for (int element : ar)

System.out.print(element + " ");


}
}

Output
10 50 60 80 90

Arrays of Objects

An array of objects is created like an array of primitive-type data items in the


following way.
Student[] arr = new Student[5]; //student is a user-defined class
Syntax:
1) data type[] arrName;
2) datatype arrName[];
3) datatype [] arrName;

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

// Java program to illustrate creating

// 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;
}

// Elements of the array are objects of a class Student.


public static void main(String[] args)
{
// declares an Array of integers.
Student[] arr;

// allocating memory for 5 objects of type Student.


arr = new Student[5];

// initialize the first elements of the array


arr[0] = new Student(1, "aman");

// initialize the second elements of the array


arr[1] = new Student(2, "vaibhav");

// so on...
arr[2] = new Student(3, "shikar");
arr[3] = new Student(4, "dharmesh");
arr[4] = new Student(5, "mohit");

// accessing the elements of the specified array


for (int i = 0; i < arr.length; i++)
System.out.println("Element at " + i + " : "
+ arr[i].roll_no + " "
+ arr[i].name);
}
}

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

What happens if we try to access elements outside the array size?

JVM throws ArrayIndexOutOfBoundsException to indicate that the array has


been accessed with an illegal index. The index is either negative or greater than or
equal to the size of an array.
Below code shows what happens if we try to access elements outside the array
size.

// Code for showing error "ArrayIndexOutOfBoundsException"

public class AIOB {


public static void main(String[] args)
{
int[] arr = new int[4];
arr[0] = 10;
arr[1] = 20;
arr[2] = 30;
arr[3] = 40;

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)

public class AIOBA {


public static void main(String[] args)
{
int[] arr = new int[2];
arr[0] = 10;
arr[1] = 20;

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


System.out.println(arr[i]);
}
}

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

int[][] intArray = new int[10][20]; //a 2D array or matrix


int[][][] intArray = new int[10][20][10]; //a 3D array
Example
public class multiDimensional {
public static void main(String args[])
{
// declaring and initializing 2D array

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

Three-Dimensional Arrays In Java


We already discussed that an array gets more complex as their dimensions
increase. Three-dimensional arrays are complex for multi-dimensional
arrays. A three dimensional can be defined as an array of two-dimensional
arrays.

The general definition of a Three-dimensional array is given below:


data_type [] [] [] array_name = new data_type [d1][d2][d3];

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

Example of 3d array definition is:


int [] [] [] intArray = new int[2][3][4];

The above definition of 3d array can be interpreted as having 2 tables or


arrays, 3 rows and 4 columns that totals up to 2x3x4 = 24 elements.

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.

public class Main


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

//initialize 3-d array


int[][][] intArray = { { { 1, 2, 3}, { 4, 5, 6 } , { 7, 8, 9 } } };
System.out.println ("3-d array is given below :");
//print the elements of array
for (int i = 0; i < 1; i++)
for (int j = 0; j < 3; j++)
for (int z = 0; z < 3; z++)
System.out.println ("intArray [" + i
+ "][" + j + "][" + z + "] = " + intArray [i][j][z]);
}
}
Output:

BY LOVELEEN KAUR 11
ARRAYS

After initializing the 3d array during declaration, we have accessed the


individual elements of the array and printed them.

Acces And Print 3d Array


Again, printing and accessing array elements in a three-dimensional array is
similar to that in two-dimensional arrays.

public class Main


{
public static void main(String[] args) {
//initialize 3-d array
int[][][] myArray = { { { 1, 2, 3 }, { 4, 5, 6 } }, { { 1, 4, 9 },
{ 16, 25, 36 } },
{ { 1, 8, 27 }, { 64, 125, 216 } } };
System.out.println("3x2x3 array is given below:");
//print the 3-d array
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 2; j++) {
for (int k = 0; k < 3; k++) {
System.out.print(myArray[i][j][k] + "\t");

BY LOVELEEN KAUR 12
ARRAYS

}
System.out.println();
}
System.out.println();
}
}
}
Output:

The above program displays a tabular representation of a three-dimensional


array. As shown, it is a 3x2x3 array which means that it has 3 tables, 2 rows
and 3 columns and thus 18 elements.

It is already mentioned that the column size can vary in a multi-dimensional


array. The example below demonstrates a three-dimensional array with
varied column sizes.

public class Main


{
public static void main(String[] args) {
//initialize 3-d array
int[][][] intArray = {
{{10, 20, 30},{20, 40, 60}},
{ {10, 30,50,70},{50},{80, 90}}

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:

The input array used is a Three-dimensional array with a varied length of


columns. The enhanced for each loop used for each dimension displays the
contents of the array in a tabular format.

BY LOVELEEN KAUR 14
ARRAYS

Passing Arrays to Methods

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

public class PATM {


// Driver method
public static void main(String args[])
{
int arr[] = { 3, 1, 2, 5, 4 };

// passing array to method m1


sum(arr);
}

public static void sum(int[] arr)


{
// getting sum of array values
int sum = 0;

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


sum += arr[i];

System.out.println("sum of array values : " + sum);


}
}

Output
sum of array values : 15

Returning Arrays from Methods

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

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


System.out.print(arr[i] + " ");
}

public static int[] m1()


{
// returning array
return new int[] { 1, 2, 3 };
}
}

Output
1 2 3

Class Objects for Arrays

Every array has an associated Class object, shared with all other arrays with the
same component type.

// Java program to demonstrate


// Class Objects for Arrays

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.

Arrays Types and Their Allowed Element Types

Array Types Allowed Element Types

Any type which can be implicitly promoted to declared


Primitive Type Arrays
type.

Object Type Arrays Either declared type objects or it’s child class objects.

Abstract Class Type


Its child-class objects are allowed.
Arrays

Interface Type Arrays Its implementation class objects are allowed.

BY LOVELEEN KAUR 17
ARRAYS

BY LOVELEEN KAUR 18
OBJECT ORIENTED PROGRAMMING

Java Class and Objects


Java is an object-oriented programming language. The core concept of the
object-oriented approach is to break complex problems into smaller objects.

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.

We can think of the class as a sketch (prototype) of a house. It contains all


the details about the floors, doors, windows, etc. Based on these descriptions
we build the house. House is the object.

Since many houses can be made from the same description, we can create
many objects from a class.

Create a class in Java

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

 fields are used to store data

 methods are used to perform some operations

For our bicycle object, we can create the class as

class Bicycle {

// state or field
private int gear = 5;

// behavior or method
public void braking() {
System.out.println("Working of Braking");
}
}

In the above example, we have created a class named Bicycle. It contains a


field named gear and a method named braking().

Here, Bicycle is a prototype. Now, we can create any number of bicycles


using the prototype. And, all the bicycles will share the fields and methods of
the prototype.

Note: We have used keywords private and public. These are known as
access modifiers.

Java Objects

An object is called an instance of a class. For example, suppose Bicycle is a


class then MountainBicycle, SportsBicycle, TouringBicycle, etc can be considered
as objects of the class.
Creating an Object in Java

Here is how we can create an object of a class.

BY LOVELEEN KAUR 2
OBJECT ORIENTED PROGRAMMING

className object = new className();

// for Bicycle class


Bicycle sportsBicycle = new Bicycle();

Bicycle touringBicycle = new Bicycle();

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.

Access Members of a 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();

// access field and method


sportsBicycle.gear;
BY LOVELEEN KAUR 3
OBJECT ORIENTED PROGRAMMING

sportsBicycle.braking();

In the above example, we have created a class named Bicycle. It includes a


field named gear and a method named braking() . Notice the statement,

Bicycle sportsBicycle = new Bicycle();

Here, we have created an object of Bicycle named sportsBicycle. We then use


the object to access the field and method of the class.
 sportsBicycle.gear - access the field gear

 sportsBicycle.braking() - access the method braking()

Now that we understand what is class and object. Let's see a fully working
example.

Example: Java Class and Objects


class Lamp {

// stores the value for light


// true if light is on
// false if light is off
boolean isOn;

// method to turn on the light


void turnOn() {
isOn = true;
System.out.println("Light on? " + isOn);

// method to turnoff the light


void turnOff() {
isOn = false;
System.out.println("Light on? " + isOn);
}
}

class Main {
public static void main(String[] args) {

// create objects led and halogen


Lamp led = new Lamp();

BY LOVELEEN KAUR 4
OBJECT ORIENTED PROGRAMMING

Lamp halogen = new Lamp();

// turn on the light by


// calling method turnOn()
led.turnOn();

// turn off the light by


// calling method turnOff()
halogen.turnOff();
}
}

Output:
Light on? true
Light on? false

In the above program, we have created a class named Lamp. It contains a


variable: isOn and two methods: turnOn() and turnOff().

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.

However, we can also create objects inside the same class.

class Lamp {

// stores the value for light


// true if light is on

BY LOVELEEN KAUR 5
OBJECT ORIENTED PROGRAMMING

// false if light is off


boolean isOn;

// method to turn on the light


void turnOn() {
isOn = true;
System.out.println("Light on? " + isOn);

public static void main(String[] args) {

// create an object of Lamp


Lamp led = new Lamp();

// access method using object


led.turnOn();
}
}

Output

Light on? true

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

Declaring a Java Method

The syntax to declare a method is:

returnType methodName() {
// method body
}

Here,

 returnType - It specifies what type of value a method returns For


example if a method has an int return type then it returns an integer
value.

If the method does not return a value, its return type is void.

 methodName - It is an identifier that is used to refer to the particular


method in a program.
 method body - It includes the programming statements that are used
to perform some tasks. The method body is enclosed inside the curly
braces { }.
For example,

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

modifier static returnType nameOfMethod (parameter1, parameter2, ...) {


// method body
}

BY LOVELEEN KAUR 7
OBJECT ORIENTED PROGRAMMING

Here,

 modifier - It defines access types whether the method is public,


private, and so on.
 static - If we use the static keyword, it can be accessed without
creating objects.

For example, the sqrt() method of standard Math class is static.


Hence, we can directly call Math.sqrt() without creating an instance
of Math class.
 parameter1/parameter2 - These are values passed to a method. We
can pass any number of arguments to a method.
Calling a Method in Java

In the above example, we have declared a method named addNumbers(). Now,


to use the method, we need to call it.
Here's is how we can call the addNumbers() method.
// calls the method
addNumbers();

Working of Java Method Call

BY LOVELEEN KAUR 8
OBJECT ORIENTED PROGRAMMING

Example 1: Java Methods


class Main {

// create a method
public int addNumbers(int a, int b) {
int sum = a + b;
// return value
return sum;
}

public static void main(String[] args) {

int num1 = 25;


int num2 = 15;

// create an object of Main


Main obj = new Main();
// calling method
int result = obj.addNumbers(num1, num2);
System.out.println("Sum is: " + result);
}
}
Output

Sum is: 40

In the above example, we have created a method named addNumbers(). The


method takes two parameters a and b . Notice the line,

int result = obj.addNumbers(num1, num2);

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

Java Method Return Type

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;
}

public static void main(String[] args) {


int result;

// call the method


// store returned value to result
result = square(10);

System.out.println("Squared value of 10 is: " + result);


}
}
Output:

Squared value of 10 is: 100

In the above program, we have created a method named square(). The


method takes a number as its parameter and returns the square of the
number.

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.

Representation of the Java


method returning a value

Note: If the method does not return any value, we use the void keyword as
the return type of the method. For example,

public void square(int a) {


int square = a * a;
System.out.println("Square is: " + square);
}

Method Parameters in Java

A method parameter is a value accepted by the method. As mentioned


earlier, a method can also have any number of parameters. For example,

// method with two parameters


int addNumbers(int a, int b) {
// code
}

// method with no parameter


int addNumbers(){
// code
}

If a method is created with parameters, we need to pass the corresponding


values while calling the method. For example,

BY LOVELEEN KAUR 11
OBJECT ORIENTED PROGRAMMING

// calling the method with two parameters


addNumbers(25, 15);

// calling the method with no parameters


addNumbers()

Example 3: Method Parameters


class Main {

// method with no parameter


public void display1() {
System.out.println("Method without parameter");
}

// method with single parameter


public void display2(int a) {
System.out.println("Method with a single parameter: " + a);
}

public static void main(String[] args) {

// create an object of Main


Main obj = new Main();

// calling method with no parameter


obj.display1();

// calling method with the single parameter


obj.display2(24);
}
}
Output

Method without parameter


Method with a single parameter: 24

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 parameter num accepted by the method definition is known as a formal


argument. We need to specify the type of formal arguments. And, the type
of actual arguments and formal arguments should always match.
Standard Library Methods

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,

 print() is a method of java.io.PrintSteam. The print("...") method prints


the string inside quotation marks.
 sqrt() is a method of Math class. It returns the square root of a number.
Here's a working example:

Example 4: Java Standard Library Method


public class Main {
public static void main(String[] args) {

// using the sqrt() method


System.out.print("Square root of 4 is: " + Math.sqrt(4));
}
}

Output:

Square root of 4 is: 2.0

Please refer below link for the following topics


https://www.programiz.com/java-programming/class-objects
1. constructors
2. access control
3. usage of static with data and methods
4. usage of final with data
5. overloading methods and constructors
6. recursion, nested classes

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;

public void addition(int x, int y) {


z = x + y;
System.out.println("The sum of the given numbers:"+z);
}

public void Subtraction(int x, int y) {


z = x - y;
System.out.println("The difference between the given numbers:"+z);
}
}

BY LOVELEEN KAUR 1
INHERITANCE

public class My_Calculation extends Calculation {


public void multiplication(int x, int y) {
z = x * y;
System.out.println("The product of the given numbers:"+z);
}

public static void main(String args[]) {


int a = 20, b = 10;
My_Calculation demo = new My_Calculation();
demo.addition(a, b);
demo.Subtraction(a, b);
demo.multiplication(a, b);
}
}
Compile and execute the above code as shown below.
javac My_Calculation.java
java My_Calculation
After executing the program, it will produce the following result −
Output
The sum of the given numbers:30
The difference between the given numbers:10
The product of the given numbers:200
In the given program, when an object to My_Calculation class is created, a copy of
the contents of the superclass is made within it. That is why, using the object of the
subclass you can access the members of a superclass.

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.

Calculation demo = new My_Calculation();


demo.addition(a, b);
demo.Subtraction(a, b);
Note − A subclass inherits all the members (fields, methods, and nested classes)
from its superclass. Constructors are not members, so they are not inherited by
subclasses, but the constructor of the superclass can be invoked from the subclass.

The super keyword


The super keyword is similar to this keyword. Following are the scenarios where the
super keyword is used.
 It is used to differentiate the members of superclass from the members
of subclass, if they have same names.
 It is used to invoke the superclass constructor from subclass.
Differentiating the Members
If a class is inheriting the properties of another class. And if the members of the
superclass have the names same as the sub class, to differentiate these variables we
use super keyword as shown below.
super.variable
super.method();
Sample Code
This section provides you a program that demonstrates the usage of
the super keyword.
In the given program, you have two classes namely Sub_class and Super_class, both
have a method named display() with different implementations, and a variable named
num with different values. We are invoking display() method of both classes and
printing the value of the variable num of both classes. Here you can observe that we
have used super keyword to differentiate the members of superclass from subclass.
Copy and paste the program in a file with name Sub_class.java.
Example

class Super_class {
int num = 20;

// display method of superclass


public void display() {
System.out.println("This is the display method of superclass");

BY LOVELEEN KAUR 3
INHERITANCE

}
}

public class Sub_class extends Super_class {


int num = 10;

// display method of sub class


public void display() {
System.out.println("This is the display method of subclass");
}

public void my_method() {


// Instantiating subclass
Sub_class sub = new Sub_class();

// Invoking the display() method of sub class


sub.display();

// Invoking the display() method of superclass


super.display();

// printing the value of variable num of subclass


System.out.println("value of the variable named num in sub class:"+ sub.num);

// printing the value of variable num of superclass


System.out.println("value of the variable named num in super class:"+ super.num);
}

public static void main(String args[]) {


Sub_class obj = new Sub_class();
obj.my_method();
}
}
Compile and execute the above code using the following syntax.
javac Super_Demo
java Super
On executing the program, you will get the following result −
Output
This is the display method of subclass
This is the display method of superclass
value of the variable named num in sub class:10
value of the variable named num in super class:20
Invoking Superclass Constructor
If a class is inheriting the properties of another class, the subclass automatically
acquires the default constructor of the superclass. But if you want to call a

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;
}

public void getAge() {


System.out.println("The value of the variable named age in super class is: " +age);
}
}

public class Subclass extends Superclass {


Subclass(int age) {
super(age);
}

public static void main(String args[]) {


Subclass s = new Subclass(24);
s.getAge();
}
}
Compile and execute the above code using the following syntax.
javac Subclass
java Subclass
On executing the program, you will get the following result −
Output
The value of the variable named age in super class is: 24

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

Why use Aggregation?


o For Code Reusability.

When use Aggregation?


o Code reuse is also best achieved by aggregation when there is no is-a relationship.
o Inheritance should be used only if the relationship is-a is maintained throughout the
lifetime of the objects involved; otherwise, aggregation is the best choice.

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;

public Address(String city, String state, String country) {


this.city = city;
this.state = state;
this.country = country;
}

}
Emp.java
public class Emp {
int id;
String name;
Address address;

public Emp(int id, String name,Address address) {


this.id = id;
this.name = name;
this.address=address;
}

BY LOVELEEN KAUR 7
INHERITANCE

void display(){
System.out.println(id+" "+name);
System.out.println(address.city+" "+address.state+" "+address.country);
}

public static void main(String[] args) {


Address address1=new Address("gzb","UP","india");
Address address2=new Address("gno","UP","india");

Emp e=new Emp(111,"varun",address1);


Emp e2=new Emp(112,"arun",address2);

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

public class extends Animal, Mammal{}


However, a class can implement one or more interfaces, which has helped Java get
rid of the impossibility of multiple inheritance.

Java - Access Modifiers


Java provides a number of access modifiers to set access levels for classes, variables,
methods, and constructors. The four access levels are −

 Visible to the package, the default. No modifiers are needed.


 Visible to the class only (private).
 Visible to the world (public).
 Visible to the package and all subclasses (protected).
Default Access Modifier - No Keyword
Default access modifier means we do not explicitly declare an access modifier for a
class, field, method, etc.
A variable or method declared without any access control modifier is available to any
other class in the same package. The fields in an interface are implicitly public static
final and the methods in an interface are by default public.

Example
Variables and methods can be declared without any modifiers, as in the following
examples −

String version = "1.5.1";

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 −

public class Logger {


private String format;

public String getFormat() {


return this.format;
}

public void setFormat(String format) {


this.format = format;
}
}
Here, the format variable of the Logger class is private, so there's no way for other
classes to retrieve or set its value directly.
So, to make this variable available to the outside world, we defined two public
methods: getFormat(), which returns the value of format, and setFormat(String),
which sets its value.

Public Access Modifier - Public


A class, method, constructor, interface, etc. declared public can be accessed from any
other class. Therefore, fields, methods, blocks declared inside a public class can be
accessed from any class belonging to the Java Universe.
However, if the public class we are trying to access is in a different package, then the
public class still needs to be imported. Because of class inheritance, all public
methods and variables of a class are inherited by its subclasses.

Example
The following function uses public access control −

public static void main(String[] arguments) {


// ...
}
The main() method of an application has to be public. Otherwise, it could not be called
by a Java interpreter (such as java) to run the class.

BY LOVELEEN KAUR 10
INHERITANCE

Protected Access Modifier - Protected


Variables, methods, and constructors, which are declared protected in a superclass
can be accessed only by the subclasses in other package or any class within the
package of the protected members' class.
The protected access modifier cannot be applied to class and interfaces. Methods,
fields can be declared protected, however methods and fields in a interface cannot
be declared protected.
Protected access gives the subclass a chance to use the helper method or variable,
while preventing a nonrelated class from trying to use it.

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
}
}

class StreamingAudioPlayer extends AudioPlayer {


boolean openSpeaker(Speaker sp) {
// implementation details
}
}
Here, if we define openSpeaker() method as private, then it would not be accessible
from any other class other than AudioPlayer. If we define it as public, then it would
become accessible to all the outside world. But our intention is to expose this method
to its subclass only, that’s why we have used protected modifier.

Access Control and Inheritance


The following rules for inherited methods are enforced −
 Methods declared public in a superclass also must be public in all
subclasses.
 Methods declared protected in a superclass must either be protected or
public in subclasses; they cannot be private.
 Methods declared private are not inherited at all, so there is no rule for
them.

BY LOVELEEN KAUR 11
INHERITANCE

Java Method Overriding


we learned about inheritance. Inheritance is an OOP property that allows us
to derive a new class (subclass) from an existing class (superclass). The
subclass inherits the attributes and methods of the superclass.

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.

Example 1: Method Overriding


class Animal {
public void displayInfo() {
System.out.println("I am an animal.");
}
}

class Dog extends Animal {


@Override
public void displayInfo() {
System.out.println("I am a dog.");
}
}

class Main {
public static void main(String[] args) {
Dog d1 = new Dog();
d1.displayInfo();
}
}

Output:

I am a dog.

In the above program, the displayInfo() method is present in both


the Animal superclass and the Dog subclass.

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.

Notice the use of the @Override annotation in our example. In Java,


annotations are the metadata that we used to provide information to the
compiler. Here, the @Override annotation specifies the compiler that the
method after this annotation overrides the method of the superclass.
It is not mandatory to use @Override. However, when we use this, the method
should follow all the rules of overriding. Otherwise, the compiler will generate
an error.
Java Overriding Rules

 Both the superclass and the subclass must have the same method
name, the same return type and the same parameter list.

 We cannot override the method declared as final and static.

 We should always override abstract methods of the superclass (will be


discussed in later tutorials).

BY LOVELEEN KAUR 13
INHERITANCE

super Keyword in Java Overriding

A common question that arises while performing overriding in Java is:

Can we access the method of the superclass after overriding?


Well, the answer is Yes. To access the method of the superclass from the
subclass, we use the super keyword.
Example 2: Use of super Keyword
class Animal {
public void displayInfo() {
System.out.println("I am an animal.");
}
}

class Dog extends Animal {


public void displayInfo() {
super.displayInfo();
System.out.println("I am a dog.");
}
}

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

Inside displayInfo() of the Dog subclass, we have used super.displayInfo() to


call displayInfo() of the superclass.

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().

Access Specifiers in Method Overriding

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,

Suppose, a method myClass() in the superclass is declared protected. Then,


the same method myClass() in the subclass can be either public or protected,

but not private.

Example 3: Access Specifier in Overriding


class Animal {
protected void displayInfo() {
System.out.println("I am an animal.");
}
}

class Dog extends Animal {


public void displayInfo() {
System.out.println("I am a dog.");
}
}

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.

Whenever we call displayInfo() using the d1 (object of the subclass), the


method inside the subclass is called.
Notice that, the displayInfo() is declared protected in the Animal superclass.
The same method has the public access specifier in the Dog subclass. This is
possible because the public provides larger access than the protected.

BY LOVELEEN KAUR 17
INHERITANCE

Java Abstract Class and Abstract Methods

Java Abstract Class

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,

// create an abstract class


abstract class Language {
// fields and methods
}
...

// try to create an object Language


// throws an error
Language obj = new Language();

An abstract class can have both the regular methods and abstract methods.
For example,

abstract class Language {

// abstract method
abstract void method1();

// regular method
void method2() {
System.out.println("This is regular method");
}
}

BY LOVELEEN KAUR 18
INHERITANCE

Java Abstract Method

A method that doesn't have its body is known as an abstract method. We


use the same abstract keyword to create abstract methods. For example,

abstract void display();

Here, display() is an abstract method. The body of display() is replaced by ;.


If a class contains an abstract method, then the class should be declared
abstract. Otherwise, it will generate an error. For example,

// error
// class should be abstract
class Language {

// abstract method
abstract void method1();
}

Example: Java Abstract Class and Method

Though abstract classes cannot be instantiated, we can create subclasses


from it. We can then access members of the abstract class using the object
of the subclass. For example,

abstract class Language {

// method of abstract class


public void display() {
System.out.println("This is Java Programming");
}
}

class Main extends Language {

public static void main(String[] args) {

BY LOVELEEN KAUR 19
INHERITANCE

// create an object of Main


Main obj = new Main();

// access method of abstract class


// using object of Main class
obj.display();
}
}

Output

This is Java programming

In the above example, we have created an abstract class named Language.

The class contains a regular method display().

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.

Implementing Abstract Methods

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,

abstract class Animal {


abstract void makeSound();

public void eat() {


System.out.println("I can eat.");
}
}

class Dog extends Animal {

// provide implementation of abstract method


public void makeSound() {

BY LOVELEEN KAUR 20
INHERITANCE

System.out.println("Bark bark");
}
}

class Main {
public static void main(String[] args) {

// create an object of Dog class


Dog d1 = new Dog();

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().

We then used the object d1 of the Dog class to call


methods makeSound() and eat() .

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

Accesses Constructor of Abstract Classes

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,

abstract class Animal {


Animal() {
….
}
}

class Dog extends Animal {


Dog() {
super();
...
}
}

Here, we have used the super() inside the constructor of Dog to access the
constructor of the Animal .

BY LOVELEEN KAUR 22
INHERITANCE

Java final keyword


In Java, the final keyword is used to denote constants. It can be used with
variables, methods, and classes.
Once any entity (variable, method or class) is declared final, it can be
assigned only once. That is,
 the final variable cannot be reinitialized with another value

 the final method cannot be overridden

 the final class cannot be extended

1. Java final Variable

In Java, we cannot change the value of a final variable. For example,

class Main {
public static void main(String[] args) {

// create a final variable


final int AGE = 32;

// try to change the final variable


AGE = 45;
System.out.println("Age: " + AGE);
}
}
In the above program, we have created a final variable named age. And we
have tried to change the value of the final variable.
When we run the program, we will get a compilation error with the following
message.

cannot assign a value to final variable AGE


AGE = 45;
^

BY LOVELEEN KAUR 23
INHERITANCE

Note: It is recommended to use uppercase to declare final variables in Java.

2. Java final Method

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.");
}
}

class Main extends FinalDemo {


// try to override final method
public final void display() {
System.out.println("The final method is overridden.");
}

public static void main(String[] args) {


Main obj = new Main();
obj.display();
}
}

In the above example, we have created a final method


named display() inside the FinalDemo class. Here, the Main class inherits
the FinalDemo class.
We have tried to override the final method in the Main class. When we run the
program, we will get a compilation error with the following message.

display() in Main cannot override display() in FinalDemo


public final void display() {
^
overridden method is final

BY LOVELEEN KAUR 24
INHERITANCE

3. Java final Class

In Java, the final class cannot be inherited by another class. For example,

// create a final class


final class FinalClass {
public void display() {
System.out.println("This is a final method.");
}
}

// try to extend the final class


class Main extends FinalClass {
public void display() {
System.out.println("The final method is overridden.");
}

public static void main(String[] args) {


Main obj = new Main();
obj.display();
}
}

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.

cannot inherit from final FinalClass


class Main extends FinalClass {
^

BY LOVELEEN KAUR 25
INHERITANCE

Dynamic method dispatch or Runtime


polymorphism in Java
Runtime Polymorphism in Java is achieved by Method overriding in which a child
class overrides a method in its parent. An overridden method is essentially hidden in
the parent class, and is not invoked unless the child class uses the super keyword
within the overriding method. This method call resolution happens at runtime and is
termed as Dynamic method dispatch mechanism.

Example
Let us look at an example.

class Animal {
public void move() {
System.out.println("Animals can move");
}
}

class Dog extends Animal {


public void move() {
System.out.println("Dogs can walk and run");
}
}

public class TestDog {

public static void main(String args[]) {

Animal a = new Animal(); // Animal reference and object


Animal b = new Dog(); // Animal reference but Dog object

a.move(); // runs the method in Animal class


b.move(); // runs the method in Dog class
}
}
This will produce the following result −

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:

char[] ch={'s','e','c','t', 'i','o','n'};


String s=new String(ch);

is same as:

String s="section";

Java String class provides a lot of methods to perform operations on strings


such as compare(), concat(), equals(), split(), length(), replace(), compareTo(),
intern(), substring() etc.

Java String class methods

1. Java String charAt()


The Java String class charAt() method returns a char value at the given index
number.

public class CharAtExample{


public static void main(String args[]){
String name="section";
char ch=name.charAt(4);//returns the char value at the 4th index
System.out.println(ch);
}}
2. Java String length()
The Java String class length() method finds the length of a string. The length
of the Java string is the same as the Unicode code units of the string.

Syntax
The signature of the string length() method is given below:

public int length()

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());
}}

3. Java String isEmpty()


The Java String class isEmpty() method checks if the input string is empty or
not. Note that here empty means the number of characters contained in a string
is zero.

Syntax
The signature or syntax of string isEmpty() method is given below:

public boolean isEmpty()


Example
public class IsEmptyExample{
public static void main(String args[]){
String s1="";
String s2="University";
System.out.println(s1.isEmpty());
System.out.println(s2.isEmpty());
}}

4. Java String replace()


The Java String class replace() method returns a string replacing all the old
char or CharSequence to new char or CharSequence.

public class ReplaceExample1{


public static void main(String args[]){
String s1="W3 school is a very good website";
String replaceString=s1.replace('a','e');//replaces all occurrences of 'a' to 'e'
System.out.println(replaceString);
}}

5. Java String split() method example


The given example returns total number of words in a string excluding space
only. It also includes special characters.

public class SplitExample{


public static void main(String args[]){
String s1="java string split method";
String[] words=s1.split("\\s");//splits the string based on whitespace
//using java foreach loop to print elements of string array
for(String w:words){
System.out.println(w);
}
}}

6. Java String compare

We can compare String in Java on the basis of content and reference.

It is used in authentication (by equals() method), sorting (by compareTo()


method), reference matching (by == operator) etc.

(a) By Using equals() Method

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.

Suppose s1 and s2 are two String objects. If:

o s1 == s2 : The method returns 0.


o s1 > s2 : The method returns a positive value.
o s1 < s2 : The method returns a negative value.

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 )
}
}

String Concatenation in Java


In Java, String concatenation forms a new String that is the combination of
multiple strings. There are two ways to concatenate strings in Java:

1. By + (String concatenation) operator


2. By concat() method
String Concatenation by + (String concatenation)
operator
Java String concatenation operator (+) is used to add strings. For Example:

class TestStringConcatenation1{
public static void main(String args[]){
String s="Sachin"+" Tendulkar";
System.out.println(s);//Sachin Tendulkar
}
}

String Concatenation by concat() method

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
}
}

How to reverse String in Java


public class TestStringFormatter {
public static void main(String[] args) {
System.out.println(StringFormatter.reverseString("my name is Ali"));
System.out.println(StringFormatter.reverseString("I am Arshad"));
}
}
Java Package
A java package is a group of similar types of classes, interfaces and sub-packages.

Package in java can be categorized in two form, built-in package and user-defined
package.

Advantage of Java Package

1) Java package is used to categorize the classes and interfaces so that they can be
easily maintained.

2) Java package provides access protection.

3) Java package removes naming collision

Simple example of java package

The package keyword is used to create a package in java.

//save as Simple.java
package mypack;
public class Simple{
public static void main(String args[]){
System.out.println("Welcome to package");
}
}

How to compile & run java package

To Compile: javac -d . Filename.java


To Run: java packageName.Classname
Importing PACKAGES:
Example of package that import the packagename.*

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.

The interface in Java is a mechanism to achieve abstraction. There can be only


abstract methods in the Java interface, not the method body. It is used to achieve
abstraction and multiple inheritance in Java. In other words, you can say that
interfaces can have abstract methods and variables. It cannot have a method
body. Java Interface also represents the IS-A relationship.

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.
}

// Java program to demonstrate working of


// interface

import java.io.*;

// A simple interface
interface In1 {

// public, static and final


final int a = 10;

// public and abstract


void display();
}

// A class that implements the interface.


class TestClass implements In1 {
// Implementing the capabilities of
// interface.
public void display(){
System.out.println("Geek");
}

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

S.
No. Class Interface

In an interface, you can’t


In class, you can instantiate
1. instantiate variables and create an
variables and create an object.
object.

The interface cannot contain


Class can contain concrete(with
2. concrete(with implementation)
implementation) methods
methods

The access specifiers used with


In Interface only one specifier is
3. classes are private, protected, and
used- Public.
public.
EXCEPTIONS HANDLING

Exception Handling in Java


The Exception Handling in Java is one of the powerful mechanisms to handle the
runtime errors so that the normal flow of the application can be maintained.

What is Exception in Java?


In Java, an exception is an event that disrupts the normal flow of the program. It is an
object which is thrown at runtime.

What is Exception Handling?


Exception Handling is a mechanism to handle runtime errors such as
ClassNotFoundException, IOException, SQLException, RemoteException, etc.

Advantage of Exception Handling

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;

Suppose there are 10 statements in a Java program and an exception occurs at


statement 5; the rest of the code will not be executed, i.e., statements 6 to 10 will not
be executed. However, when we perform exception handling, the rest of the
statements will be executed. That is why we use exception handling in Java.

BY LOVELEEN KAUR 1
EXCEPTIONS HANDLING

Hierarchy of Java Exception classes


The java.lang.Throwable class is the root class of Java Exception hierarchy inherited by
two subclasses: Exception and Error. The hierarchy of Java Exception classes is given
below:

Types of Java Exceptions


There are mainly two types of exceptions: checked and unchecked. An error is
considered as the unchecked exception. However, according to Oracle, there are three
types of exceptions namely:

1. Checked Exception
2. Unchecked Exception
3. Error

BY LOVELEEN KAUR 2
EXCEPTIONS HANDLING

Difference between Checked and Unchecked


Exceptions
1) Checked Exception

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

Error is irrecoverable. Some example of errors are OutOfMemoryError,


VirtualMachineError, AssertionError etc.

BY LOVELEEN KAUR 3
EXCEPTIONS HANDLING

Java Exception Keywords


Java provides five keywords that are used to handle the exception. The following table
describes each.

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.

throw The "throw" keyword is used to throw an exception.

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.

Java Exception Handling Example


Let's see an example of Java Exception Handling in which we are using a try-catch
statement to handle the exception.

JavaExceptionExample.java

public class JavaExceptionExample{


public static void main(String args[]){
try{
//code that may raise exception
int data=100/0;
}catch(ArithmeticException e){System.out.println(e);}
//rest code of the program
System.out.println("rest of the code...");
}
}
BY LOVELEEN KAUR 4
EXCEPTIONS HANDLING

Output:

Exception in thread main java.lang.ArithmeticException:/ by zero


rest of the code...

In the above example, 100/0 raises an ArithmeticException which is handled by a try-


catch block.

Common Scenarios of Java Exceptions


There are given some scenarios where unchecked exceptions may occur. They are as
follows:

1) A scenario where ArithmeticException occurs

If we divide any number by zero, there occurs an ArithmeticException.

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

If the formatting of any variable or number is mismatched, it may result into


NumberFormatException. Suppose we have a string variable that has characters;
converting this variable into digit will cause NumberFormatException.

1. String s="abc";
2. int i=Integer.parseInt(s);//NumberFormatException
4) A scenario where ArrayIndexOutOfBoundsException occurs

When an array exceeds to it's size, the ArrayIndexOutOfBoundsException occurs. there


may be other reasons to occur ArrayIndexOutOfBoundsException. Consider the
following statements.

1. int a[]=new int[5];


2. a[10]=50; //ArrayIndexOutOfBoundsException

BY LOVELEEN KAUR 5
EXCEPTIONS HANDLING

Java finally block


Java finally block is a block used to execute important code such as closing the
connection, etc.

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.

The finally block follows the try-catch block.

When an exception does not occur


Let's see the below example where the Java program does not throw any exception,
and the finally block is executed after the try block.

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");
}

System.out.println("rest of phe code...");


}
}

Output:

BY LOVELEEN KAUR 6
EXCEPTIONS HANDLING

Difference between throw and throws in Java


The throw and throws is the concept of exception handling where the throw keyword
throw the exception explicitly from a method or a block of code whereas the throws
keyword is used in signature of the method.

There are many differences between throw and throws keywords. A list of differences
between throw and throws are given below:

Sr. Basis of Differences throw throws


no.

1. Definition Java throw keyword is used Java throws keyword is


throw an exception explicitly in used in the method
the code, inside the function or signature to declare an
the block of code. exception which might be
thrown by the function
while the execution of the
code.

2. Type of exception Using Using throws keyword, we can


throw keyword, we can only declare both checked and
propagate unchecked unchecked exceptions.
exception i.e., the checked However, the throws keyword
exception cannot be can be used to propagate
propagated using throw checked exceptions only.
only.

3. Syntax The throw keyword is followed The throws keyword is


by an instance of Exception to followed by class names of
be thrown. Exceptions to be thrown.

4. Declaration throw is used within the throws is used with the


method. method signature.

BY LOVELEEN KAUR 7
EXCEPTIONS HANDLING

5. Internal implementation We are allowed to throw only We can declare multiple


one exception at a time i.e. we exceptions using throws
cannot throw multiple keyword that can be
exceptions. thrown by the method. For
example, main() throws
IOException,
SQLException.

Java throw Example


TestThrow.java

public class TestThrow {


//defining a method
public static void checkNum(int num) {
if (num < 1) {
throw new ArithmeticException("\nNumber is negative, cannot calcula
te square");
}
else {
System.out.println("Square of " + num + " is " + (num*num));
}
}
//main method
public static void main(String[] args) {
TestThrow obj = new TestThrow();
obj.checkNum(-3);
System.out.println("Rest of the code..");
}
}

Output:

BY LOVELEEN KAUR 8
EXCEPTIONS HANDLING

Java throws Example


TestThrows.java

public class TestThrows {


//defining a method
public static int divideNum(int m, int n) throws ArithmeticException {
int div = m / n;
return div;
}
//main method
public static void main(String[] args) {
TestThrows obj = new TestThrows();
try {
System.out.println(obj.divideNum(45, 0));
}
catch (ArithmeticException e){
System.out.println("\nNumber cannot be divided by 0");
}

System.out.println("Rest of the code..");


}
}

Output:

Java throw and throws Example


TestThrowAndThrows.java

public class TestThrowAndThrows


{
// defining a user-defined method

BY LOVELEEN KAUR 9
EXCEPTIONS HANDLING

// which throws ArithmeticException


static void method() throws ArithmeticException
{
System.out.println("Inside the method()");
throw new ArithmeticException("throwing ArithmeticException");
}
//main method
public static void main(String args[])
{
try
{
method();
}
catch(ArithmeticException e)
{
System.out.println("caught in main() method");
}
}
}

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.

// Java code for thread creation by extending

// the Thread class

class MultithreadingDemo extends Thread {


public void run()
{
try {
// Displaying the thread that is running
System.out.println(
"Thread " + Thread.currentThread().getId()
+ " is running");
}
catch (Exception e) {
// Throwing an exception
System.out.println("Exception is caught");
}
}
}

// 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

We create a new class which implements java.lang.Runnable interface and


override run() method. Then we instantiate a Thread object and call start()
method on this object.

// Java code for thread creation by implementing


// the Runnable Interface
class MultithreadingDemo implements Runnable {
public void run()
{
try {
// Displaying the thread that is running
System.out.println(
"Thread " + Thread.currentThread().getId()
+ " is running");
}
catch (Exception e) {
// Throwing an exception
System.out.println("Exception is caught");
}
}
}

// 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();
}
}
}

Thread Class vs Runnable Interface

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.

Types Of Threads In Java


1) User Thread :
User threads are threads which are created by the application or user. They are
high priority threads. JVM (Java Virtual Machine) will not exit until all user
threads finish their execution. JVM wait for these threads to finish their task.
These threads are foreground 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

Java Collections Framework

The Java collections framework provides a set of interfaces and classes to


implement various data structures and algorithms.
For example, the LinkedList class of the collections framework provides the
implementation of the doubly-linked list data structure.

Hierarchy of Collection 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

Interfaces of Collections FrameWork

The Java collections framework provides various interfaces. These interfaces include
several methods to perform different operations on collections.

Java Collection Interface

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 .

Collections Framework Vs. Collection Interface

People often get confused between the collections framework


and Collection Interface.
The Collection interface is the root interface of the collections framework. The
framework includes other interfaces as well: Map and Iterator. These interfaces may
also have subinterfaces.

BY LOVELEEN KAUR 2
COLLECTIONS FRAMEWORK

Subinterfaces of the Collection Interface

As mentioned earlier, the Collection interface includes subinterfaces that are


implemented by Java classes.
All the methods of the Collection interface are also present in its subinterfaces.
Here are the subinterfaces of the Collection Interface:
List Interface

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

Java Map Interface

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.

Java Iterator Interface

In Java, the Iterator interface provides methods that can be used to access elements
of collections.

Why the Collections Framework?

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

Example: ArrayList Class of Collections

The ArrayList class allows us to create resizable arrays. The class implements
the List interface (which is a subinterface of the Collection interface).

// The Collections framework is defined in the java.util package


import java.util.ArrayList;

class Main {
public static void main(String[] args){
ArrayList<String> animals = new ArrayList<>();
// Add elements
animals.add("Dog");
animals.add("Cat");
animals.add("Horse");

System.out.println("ArrayList: " + animals);


}
}
Output:

ArrayList: [Dog, Cat, Horse]

Access ArrayList Elements

To access an element from the arraylist, we use the get() method of


the ArrayList class. For example,
import java.util.ArrayList;

class Main {
public static void main(String[] args) {
ArrayList<String> animals = new ArrayList<>();

// add elements in the arraylist


animals.add("Cat");
animals.add("Dog");
animals.add("Cow");
System.out.println("ArrayList: " + animals);

// get the element from the arraylist


String str = animals.get(1);

BY LOVELEEN KAUR 5
COLLECTIONS FRAMEWORK

System.out.print("Element at index 1: " + str);


}
}
Output

ArrayList: [Cat, Dog, Cow]


Element at index 1: Dog

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.

Java Vector vs. ArrayList

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

Note: It is recommended to use ArrayList in place of Vector because vectors less


efficient.

Add Elements to Vector

 add(element) - adds an element to vectors


 add(index, element) - adds an element to the specified position
 addAll(vector) - adds all elements of a vector to another vector
For example,

import java.util.Vector;

class Main {
public static void main(String[] args) {
Vector<String> mammals= new Vector<>();

// Using the add() method


mammals.add("Dog");
mammals.add("Horse");

// Using index number


mammals.add(2, "Cat");
System.out.println("Vector: " + mammals);

// Using addAll()
Vector<String> animals = new Vector<>();
animals.add("Crocodile");

animals.addAll(mammals);
System.out.println("New Vector: " + animals);
}
}
Output

Vector: [Dog, Horse, Cat]


New Vector: [Crocodile, Dog, Horse, Cat]

Remove Vector Elements

 -remove(index)
removes an element from specified position

BY LOVELEEN KAUR 7
COLLECTIONS FRAMEWORK

 removeAll() - removes all the elements


 clear() - removes all elements. It is more efficient than removeAll()
For example,

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");

System.out.println("Initial Vector: " + animals);

// 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

Initial Vector: [Dog, Horse, Cat]


Removed Element: Horse
New Vector: [Dog, Cat]
Vector after clear(): []

Java Map Interface

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.

Note: The Map interface maintains 3 different sets:

 the set of keys

 the set of values

 the set of key/value associations (mapping).

Hence we can access keys, values, and associations individually.

Classes that implement Map

Since Map is an interface, we cannot create objects from it.


In order to use functionalities of the Map interface, we can use these classes:
 HashMap
 EnumMap
 LinkedHashMap
 WeakHashMap
 TreeMap

BY LOVELEEN KAUR 9
COLLECTIONS FRAMEWORK

These classes are defined in the collections framework and implement


the Map interface.

Java Map Subclasses


How to use Map?

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.

// Map implementation using HashMap


Map<Key, Value> numbers = new HashMap<>();

In the above code, we have created a Map named numbers. We have used
the HashMap class to implement the Map interface.
Here,

 Key - a unique identifier used to associate each element (value) in a map


 Value - elements associated by keys in a map

Implementation of the Map Interface

1. Implementing HashMap Class


import java.util.Map;
import java.util.HashMap;

class Main {

public static void main(String[] args) {


// Creating a map using the HashMap
Map<String, Integer> numbers = new HashMap<>();

BY LOVELEEN KAUR 10
COLLECTIONS FRAMEWORK

BY LOVELEEN KAUR 11
COLLECTIONS FRAMEWORK

// Insert elements to the map


numbers.put("One", 1);
numbers.put("Two", 2);
System.out.println("Map: " + numbers);

// Access keys of the map


System.out.println("Keys: " + numbers.keySet());

// Access values of the map


System.out.println("Values: " + numbers.values());

// Access entries of the map


System.out.println("Entries: " + numbers.entrySet());

// Remove Elements from the map


int value = numbers.remove("Two");
System.out.println("Removed Value: " + value);
}
}
Output

Map: {One=1, Two=2}


Keys: [One, Two]
Values: [1, 2]
Entries: [One=1, Two=2]
Removed Value: 2

Java Iterator Interface

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

Example: Implementation of Iterator

In the example below, we have implemented


the hasNext(), next(), remove() and forEachRemining() methods of
the Iterator interface in an array list.
import java.util.ArrayList;
import java.util.Iterator;

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);

// Creating an instance of Iterator


Iterator<Integer> iterate = numbers.iterator();

// Using the next() method


int number = iterate.next();
System.out.println("Accessed Element: " + number);

// Using the remove() method


iterate.remove();
System.out.println("Removed Element: " + number);

BY LOVELEEN KAUR 12
COLLECTIONS FRAMEWORK

System.out.print("Updated ArrayList: ");

// Using the hasNext() method


while(iterate.hasNext()) {
// Using the forEachRemaining() method
iterate.forEachRemaining((value) -> System.out.print(value + ", "));
}
}
}
Output

ArrayList: [1, 3, 2]
Acessed Element: 1
Removed Element: 1
Updated ArrayList: 3, 2,

In the above example, notice the statement:

iterate.forEachRemaining((value) -> System.put.print(value + ", "));

Here, we have passed the lambda expression as an argument of


the forEachRemaining() method.
Now the method will print all the remaining elements of the array list.

Access Vector Elements

 get(index) - returns an element specified by the index


 iterator() - returns an iterator object to sequentially access vector elements
For example,

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

String element = animals.get(2);


System.out.println("Element at index 2: " + element);

// Using iterator()
Iterator<String> iterate = animals.iterator();
System.out.print("Vector: ");
while(iterate.hasNext()) {
System.out.print(iterate.next());
System.out.print(", ");
}
}
}
Output

Element at index 2: Cat


Vector: Dog, Horse, Cat,

BY LOVELEEN KAUR 14

You might also like