0% found this document useful (0 votes)
76 views122 pages

Java Full Notion Notes

The document provides an overview of Object-Oriented Programming (OOP) concepts in Java, including definitions of objects, classes, inheritance, polymorphism, abstraction, and encapsulation. It also outlines the features of Java, such as platform independence, security, and robustness, along with the different types of Java programs and the architecture of the Java Virtual Machine (JVM). Additionally, it describes the structure of a Java program, including documentation, package declarations, import statements, class definitions, and methods.
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)
76 views122 pages

Java Full Notion Notes

The document provides an overview of Object-Oriented Programming (OOP) concepts in Java, including definitions of objects, classes, inheritance, polymorphism, abstraction, and encapsulation. It also outlines the features of Java, such as platform independence, security, and robustness, along with the different types of Java programs and the architecture of the Java Virtual Machine (JVM). Additionally, it describes the structure of a Java program, including documentation, package declarations, import statements, class definitions, and methods.
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

󾠮

Java: Module 1

Object oriented programming concepts

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:

Object

Java: Module 1 1
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

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.

Java: Module 1 2
Polymorphism

If one task is performed in different ways, it is known as polymorphism.

For example: to convince the customer differently, to draw something, for example, shape,
triangle, rectangle, etc.

In Java, we use method overloading and method overriding to achieve polymorphism.

Abstraction

Hiding internal details and showing functionality 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.

Java: Module 1 3
Encapsulation

Binding (or wrapping) code and data together into a single unit are known as
encapsulation. For example, a capsule, it is wrapped with different medicines.

A java class is the example of encapsulation. Java bean is the fully


encapsulated class because all the data members are private here.

Features of Java language


Object Oriented

In Java, everything is an Object. Java can be easily extended since it is based on the
Object model.

Platform independent

Unlike many other programming languages including C and C++, when Java is compiled,
it is not compiled into platform specific machine, rather into platform independent byte

Java: Module 1 4
code. This byte code is distributed over the web and interpreted by virtual Machine (JVM)
on whichever platform it is being run.

Simple

Java is designed to be easy to learn. If you understand the basic concept of OOP, Java
would be easy to master.

Secure

With Java's secure feature, it enables to develop virus-free, tamper-free systems.


Authentication techniques are based on public-key encryption.

Architectural-neutral

Java compiler generates an architecture-neutral object file format, which makes the
compiled code to be executable on many processors, with the presence of Java runtime
system.

Portable

Being architectural-neutral and having no implementation dependent aspects of the


specification makes Java portable. Compiler in Java is written in ANSI C with a clean
portability boundary which is a POSIX subset.

Robust

Java makes an effort to eliminate error prone situations by emphasizing mainly on


compile time error checking and runtime checking.

Multithread

With Java's multithreaded feature, it is possible to write programs that can do many tasks

simultaneously. This design feature allows developers to construct smoothly running


interactive

applications.

interpreted

Java byte code is translated on the fly to native machine instructions and is not stored

anywhere. The development process is more rapid and analytical since the linking is an
incremental and
lightweight process.

High performance

With the use of Just-In-Time compilers, Java enables high performance.

Distributed

Java: Module 1 5
Java is designed for the distributed environment of the internet

Dynamic

Java is considered to be more dynamic than C or C++ since it is designed to adapt to an

evolving environment. Java programs can carry extensive amount of run-time information
that can be

used to verify and resolve accesses to objects on run-time.

Types of java programs


Java Platform, Standard Edition (Java SE)

Java SE platform consists of a virtual machine, development tools, deployment


technologies, and other class libraries and toolkits commonly used in Java technology
applications.

Java Platform, Enterprise Edition (Java EE)

The Java EE platform is built on top of the Java SE platform. The Java EE platform
provides an API and runtime environment for developing and running large-scale, multi-
tiered, scalable, reliable, and secure network applications.

Java Platform, Micro Edition (Java ME)

The Java ME platform provides an API and a small-footprint virtual machine for running
Java programming language applications on small devices, like mobile phones. The API
is a subset of the Java SE API, along with special class libraries useful for small device
application development. Java ME applications are often clients of Java EE platform
services.

Java FX

Java FX technology is a platform for creating rich internet applications written in Java FX
Script. Java FX Script is a statically-typed declarative language that is compiled to Java
technology bytecode, which can then be run on a Java VM. Applications written for the
Java FX platform can include and link to Java programming language classes, and may be
clients of Java EE platform services.

java architecture

Java: Module 1 6
JVM Architecture Full

JVM Tutorial - Java Virtual Machine Architecture Explained for Beginners


Whether you have used Java to develop programs or not, you might have heard
about the Java Virtual Machine (JVM) at some point or another. JVM is the core of
the Java ecosystem, and makes it possible for Java-based software programs to
[Link]
ure-explained-for-beginners/

Java Architecture combines the process of compilation and interpretation. It explains the
various processes involved whilst
formulating a Java program
.

Java Components
Java Virtual Machine

JVM is responsible for running or executing the code. Takes ‘.class files’ or the byte
code from the java compiler and converts to machine code then interprets it give the
output.
Java is platform-independent but JVM is platform dependent. since java follows
WORA (Write Once Run Anywhere) principle java code is supported in any platforms.

Java Runtime Environment

JRE (Java Runtime Environment) is a software package that provides Java class
libraries, Java Virtual Machine (JVM), and other components that are required to run
Java applications.

Java: Module 1 7
JRE is the minimum requirement to run a java program.

Java Development Kit

JDK (Java Development Kit) is a software development kit required to develop


applications in Java. When you download JDK, JRE is also downloaded with it.

In addition to JRE, JDK also contains a number of development tools (compilers,


JavaDoc, Java Debugger, etc. ).

What is java architecture?

[Link]

In Java, there is a process of compilation and interpretation.

The code written in Java, is converted into byte codes which is done by the Java
Compiler.

The byte codes, then are converted into machine code by the JVM.

The Machine code is executed directly by the machine.

Java: Module 1 8
The three main components of JVM architecture are :

Class Loader

Class loader is a subsystem of JVM which is used to load class files which are
converted from .java files by the compiler. Whenever we run the java program, it is
loaded first by the class loader.

The class Loader consists of Three main phases they are

Loading

The Three main class loaders are responsible for Loading :

Bootstrap Class Loader: It is first class loader, which is responsible for


loading class files from [Link] also called runtime jar.
Eg : the ‘System’ in

[Link]("Java");

is present in [Link] file

Extension Class Loader: It is responsible for loading the additional class files
from (jre/lib/ext) folder.

Eg: The third party connection files from databases like Oracle , Mongo DB etc.
are found in the ‘jre/lib/ext’ folder the extension class loader is responsible for
loading that files from folder to the memory

Application Class Loader: Application class loader is the one that loads the
class files from the application-specific jar. This is nothing but the application

Java: Module 1 9
that you created. Once your java program is compiled, the JVM creates class
files. The Application class loader loads these class files to the memory area.

Linking

Verify : Once the class files are loaded to the memory, there is a verify phase
where the bytecode class files are verified if they conform to standards.

Prepare: In prepare phase, memory is allocated for the static variables and
default values are assigned.

Resolve: All the symbolic references are replaced with actual references

Initialization

In the "Initialization phase" of class loader component, all the static variables are
assigned with the actual values and it
also executes the static initializers at this point of time

Runtime Memory data area

Method/class Area: The class level data are stored in this memory Area.

Class Employee{
static int count = 0;
}

Heap memory : All the objects and instance variables are stored in this memory.

new employee()

Java: Module 1 10
Stack Memory Area : Local Variable , Operand Stack, Frame Data

PC Register : This holds the current executing instructions.

Native Method Stack: This holds the native method information.

Execution Engine

This is the actual engine that converts the bytecode to machine code and executes the
instructions.

This part contains :

Interpreter

Interpreter is the one that reads the class files or bytecode and executes it one by
one. The problem with the interpreter is that, when a method is called multiple
times, it interprets those lines of bytecode again and again.

JIT Compiler

JIT compiler helps in overcoming the problem of the interpreter. When repeated
method calls occur, JIT compiler compiles the bytecode to native code. This native

Java: Module 1 11
code will be used directly for repeated method calls. JIT compiler contains few
components to achieve this feature

Intermediate code generator : Generates Intermediate Code.

Code Optimizer : Optimizes the intermediate code for better performance.

Target code generator : converts intermediate code to native machine code .

Profiler

Responsible for finding the hotspots, methods which are called repeatedly .

Garbage Collector

Garbage collector is responsible for destroying the objects that are no longer used.

program structure

A typical structure of a Java program contains the following elements:

Java: Module 1 12
Documentation Section
The documentation section is an important section but optional for a Java program. It
includes basic information about a Java program. The information can includes
the author's name, date of creation, version, program name, company name,
and description of the program. It improves the readability of the program.

Single-line Comment: It starts with a pair of forwarding slash (//)

//First Java Program

Multi-line Comment: It starts with a /* and ends with */. We write between these two
symbols.

/*It is an example of
multiline comment*/

Documentation Comment: It starts with the delimiter (/**) and ends with */.

/**It is an example of documentation comment*/

Package Declaration
The package declaration is optional. It is placed just after the documentation section. In this
section, we declare the package name in which the class is placed. Note that there can
be only one package statement in a Java program. It must be defined before any class
and interface declaration. It is necessary because a Java class can be placed in different
packages and directories based on the module they are used. For all these classes
package belongs to a single parent directory. We use the keyword package
to declare the package name.

package pkg; //where pkg is the package name


or
package [Link]; //where com is the root directory and jpkg is the subdir

Import statements

Java: Module 1 13
The package contains the many predefined classes and interfaces. If we want to use any
class of a particular package, we need to import that class. The import statement
represents the class stored in the other package. We use the import keyword to import the
class. It is written before the class declaration and after the package statement. We use the
import statement in two ways, either import a specific class or import all classes of a
particular package. In a Java program, we can use multiple import statements.

import [Link]; //it imports the Scanner class only


import [Link].*; //it imports all the class of the [Link] package

Interface statements
It is an optional section. We can create an interface in this section if required. We use
the interface keyword to create an interface. An interface is a slightly different from the
class. It contains only constants and method declarations. Another difference is that it
cannot be instantiated. We can use interface in classes by using the implements keyword.
An interface can also be used with other interfaces by using the extends
keyword.

interface car
{
void start();
void stop();
}

Class Definition
Class is a vital part of a Java program. Without the class, we cannot create any Java
program. A Java program may contain more than one class definition. We use the class
keyword to define the class. The class is a blueprint of a Java program. It contains
information about user-defined methods, variables, and constants. Every Java program has
at least one class that contains the main() method. For example:

class Student //class definition


{
}

Class Variables and Constants

Java: Module 1 14
In this section, we define variables and constants that are to be used later in the
program. In a Java program, the variables and constants are defined just after the class
definition. The variables and constants store values of the parameters. It is used during
the execution of the program. We can also decide and define the scope of variables by
using the modifiers. It defines the life of the variables.

class Student //class definition


{
String sname; //variable
int id;
double percentage;
}

Main Methods Class


The main() method. It is essential for all Java programs. Because the execution of all Java
programs starts from the main() method. In other words, it is an entry point of the class. It
must be inside the class. Inside the main method, we create objects and call the methods.
We use the following statement to define the main() method:

public static void main(String args[])


{
}

Methods and behavior


We define the functionality of the program by using the methods. The methods are the set
of instructions that we want to perform. These instructions execute at runtime and perform
the specified task.

public class Demo //class definition


{
public static void main(String args[])
{
void display()
{
[Link]("Welcome to javatpoint");
}
//statements
}
}

Java: Module 1 15
Literals
In Java, literal is a notation that represents a fixed value in the source code. In lexical
analysis, literals of a given type are generally known as tokens. In this section, we will discuss
the term literals in Java

Types of literals are :

Integer Literal
Integer literals are sequences of digits. There are three types of integer literals:

Decimal Integer: These are the set of numbers that consist of digits from 0 to 9. It may
have a positive (+) or negative (-) Note that between numbers commas and non-digit
characters are not permitted. For example, 5678, +657, -89, etc.

int decVal = 26;

Java: Module 1 16
Octal Integer: It is a combination of number have digits from 0 to 7 with a leading 0.
For example, 045, 026,

int octVal = 067;

Hexa-Decimal: The sequence of digits preceded by 0x or 0X is considered as


hexadecimal integers. It may also include a character from a to f or A to F that
represents numbers from 10 to 15, respectively. For example, 0xd, 0xf,

int hexVal = 0x1a;

• Binary Integer: Base 2, whose digits consists of the numbers 0 and 1 (you can
create binary literals in Java SE 7 and later). Prefix 0b represents the Binary system.
For example, 0b11010.

int binVal = 0b11010;

Character Literal
A character literal is expressed as a character or an escape sequence, enclosed in
a single quote ('') mark. It is always a type of char. For example, 'a', '%', '\u000d',
etc.

Single quote: We can specify literal to a char data type as a single character within the
single quote.

char ch = 'a';

Char literal as Integral literal: we can specify char literal as integral literal, which
represents the Unicode value of the character, and that integral literal can be specified
either in Decimal, Octal, and Hexadecimal forms. But the allowed range is 0 to 65535.

char ch = 062;

Java: Module 1 17
Unicode Representation:We can specify char literals in Unicode representation ‘\uxxxx’.
Here xxxx represents 4 hexadecimal numbers.

char ch = '\u0061';// Here /u0061 represent a.

Escape Sequence: Every escape character can be specified as char literals.

char ch = '\n';

// Java program to illustrate the


// application of char literals

public class Test {


public static void main(String[] args)
{
// single character literal within single quote
char ch = 'a';
// It is an Integer literal with octal form
char b = 0789;
// Unicode representation
char c = '\u0061';

[Link](ch);
[Link](b);
[Link](c);

// Escape character literal


[Link]("\" is a symbol");
}
}

Boolean Literal

Java: Module 1 18
Only two values are allowed for Boolean literals, i.e., true and false.

boolean b = true;

// Java program to illustrate the


// application of boolean literals

public class Test {


public static void main(String[] args)
{
boolean b = true;
boolean c = false;
boolean d = 0;
boolean b = 1;

[Link](b);
[Link](c);
[Link](d);
[Link](e);
}
}

String Literal
Any sequence of characters within double quotes is treated as String literals.

String s = "Hello";

// Java program to illustrate the


// application of String literals

public class Test {


public static void main(String[] args)

Java: Module 1 19
{
String s = "Hello";

// If we assign without "" then it treats


// as a variable and causes compiler error
String s1 = Hello;

[Link](s);
[Link](s1);
}
}

Data Types and variables


Data Types

Primitive Data type


1. boolean type
The boolean data type has two possible values, either true or false .

Java: Module 1 20
Default value: false .

They are usually used for true/false conditions.

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

boolean flag = true;


[Link](flag); // prints true
}
}

2. byte type
The byte data type can have values from 128 to 127 (8-bit signed two's
complement integer).

If it's certain that the value of a variable will be within -128 to 127, then it is used
instead of int to save memory.

Default value: 0

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

byte range;
range = 124;
[Link](range); // prints 124
}
}

3. short type
The short data type in Java can have values from 32768 to 32767 (16-bit signed
two's complement integer).

If it's certain that the value of a variable will be within -32768 and 32767, then it is
used instead of other integer data types ( int , long ).

Default value: 0

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

short temperature;
temperature = -200;
[Link](temperature); // prints -200
}
}

Java: Module 1 21
4. int type

Default value 0

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

int range = -4250000;


[Link](range); // print -4250000
}
}

5. long type

6. double type
The double data type is a double-precision 64-bit floating-point.

It should never be used for precise values such as currency.

Default value: 0.0 (0.0d).

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

double number = -42.3;


[Link](number); // prints -42.3
}
}

Java: Module 1 22
7. float type
The float data type is a single-precision 32-bit floating-point.(numbers having
decimal points).

It should never be used for precise values such as currency.

Default value: 0.0 (0.0f)

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

float number = -42.3f;


[Link](number); // prints -42.3
}
}

8. char type
It's a 16-bit Unicode character.

The minimum value of the char data type is '\u0000' (0) and the maximum value of
the is '\uffff' .

Default value: '\u0000'

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

char letter = '\u0051';


[Link](letter); // prints Q
}
}

Data Type Size Description


byte 1 byte Stores whole numbers from -128 to 127
short 2 bytes Stores whole numbers from -32,768 to 32,767
int 4 bytes Stores whole numbers from -2,147,483,648 to 2,147,483,647

Stores whole numbers from -9,223,372,036,854,775,808 to


long 8 bytes
9,223,372,036,854,775,807
Stores fractional numbers. Sufficient for storing 6 to 7 decimal
float 4 bytes
digits
Stores fractional numbers. Sufficient for storing 15 decimal
double 8 bytes
digits
boolean 1 bit Stores true or false values

Java: Module 1 23
char
2 bytes Stores a single character/letter or ASCII values

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

int data=50;//Here data is variable

Types of Variables
Local Variable

A variable defined within a block or method or constructor is called a local variable.

These variables are created when the block is entered, or the function is called
and destroyed after exiting from the block or when the call returns from the
function.

The scope of these variables exists only within the block in which the variables
are declared, i.e., we can access these variables only within that block.

Initialization of the local variable is mandatory before using it in the defined


scope.

Instance Variable

Instance variables are non-static variables and are declared in a class outside of
any method, constructor, or block.

Java: Module 1 24
As instance variables are declared in a class, these variables are created when
an object of the class is created and destroyed when the object is destroyed.

Unlike local variables, we may use access specifiers for instance variables. If
we do not specify any access specifier, then the default access specifier will be
used.

Initialization of an instance variable is not mandatory. Its default value is 0.

Instance variables can be accessed only by creating objects.

Static Variable

Static variables are also known as class variables.

These variables are declared similarly as instance variables. The difference is


that static variables are declared using the static keyword within a class outside
of any method, constructor or block.

Unlike instance variables, we can only have one copy of a static variable per
class, irrespective of how many objects we create.

Static variables are created at the start of program execution and destroyed
automatically when execution ends.

Initialization of a static variable is not mandatory. Its default value is 0.

If we access a static variable like an instance variable (through an object), the


compiler will show a warning message, which won’t halt the program. The
compiler will replace the object name with the class name automatically.

If we access a static variable without the class name, the compiler will
automatically append the class name.

example

public class A
{
static int m=100;//static variable
void method()
{
int n=90;//local variable
}
public static void main(String args[])
{
int data=50;//instance variable
}
}//end of class

Java: Module 1 25
Operators
Operator in Java is a symbol that is used to perform operations. For example: +, -, *, / etc.
Types of java operators are :

Unary Operators
The Java unary operators require only one operand. Unary operators are used to perform
various operations i.e.:

incrementing/decrementing a value by one

negating an expression

inverting the value of a boolean

The unary operators are :

Unary Plus

It is used to represent positive values. Usually, we do not write the operator


before the operand. Hence, it is optional.

+(operand)

Unary Minus

It is used to convert a positive value into a negative one.

-(operand)

Increment Operator

It is used to increment the value of an operand by one. The operator is


represented by a pair of plus operators (++). The operator can be applied
before or after an operand.

Pre-increment Operator: If an increment operator is written


before (prefix) the operand is known as pre-increment. In such a case, the
value is first incremented by 1 and then taken for the computing purpose.

++operand

Java: Module 1 26
Example:
Suppose x=9

y = ++x
then , y =10 and x =10

Post-increment Operator:If an increment operator is written after (postfix)


the operand is known as post-increment. In such a case, the value is first
processed and then incremented. It means the value that the variable holds
first used for the computing purpose and then incremented by 1.

operand++

Example:
Suppose x=9

y = x++
then , y =9 and x =10

Decrement Operator

It is used to decrement the value of an operand by 1. The operator is


represented by a pair of minus operators (--). The operator can be applied
before or after an operand.

Pre-decrement Operator: If a decrement operator is written


before (prefix) the operand is known as pre-decrement. In such a case, the
value is first decremented by 1 and then used for the computing purpose.

--operand

Example: Suppose x=9

y = - -x then,

y =9 and x =9

Post-decrement Operator: If a decrement operator is written


after (postfix)the operand is known as post-decrement. In such a case, the
value is first used and then decrements by 1

operand--

Java: Module 1 27
Example: Suppose x=9

y = x- - then,

y =8 and x =9

Logical Complement Operator

t is used to reverse the value of an operand. It means if an operand has value


true, the complement if the operator will be false and vice-versa. It is
represented by the exclamatory symbol (!).

!(operand)

Equivalent
Name Symbol Description Example
Expression

It is used to
Unary Plus + represent +a a
the positive value.
It is used to
Unary Minus - represent -a -
the negative value.
It increments the
Increment
++ value of a variable ++a or a++ a=a+1
Operator
by 1.
It decrements the
Decrement
-- value of a variable - - a or a - - a=a-1
Operator
by 1.
Logical It inverts the value
Complement ! of a boolean ! true -
Operator variable.

Arithmetic Operator
Java arithmetic operators are used to perform addition, subtraction, multiplication, and
division. They act as basic mathematical operations.

Java: Module 1 28
1. Addition(+): This operator is a binary operator and is used to add two operands.

Syntax:

num1 + num2

Example:

num1 = 10, num2 = 20


sum = num1 + num2 = 30

2. Subtraction(-): This operator is a binary operator and is used to subtract two operands.

Syntax:

num1 - num2

Example:

num1 = 20, num2 = 10


sub = num1 - num2 = 10

3. Multiplication(*): This operator is a binary operator and is used to multiply two


operands.

Syntax:

num1 * num2

Java: Module 1 29
Example:

num1 = 20, num2 = 10


mult = num1 * num2 = 200

4. Division(/): This is a binary operator that is used to divide the first operand(dividend) by
the second operand(divisor) and give the quotient as a result.

Syntax:

num1 / num2

Example:

num1 = 20, num2 = 10


div = num1 / num2 = 2

5. Modulus(%): This is a binary operator that is used to return the remainder when the first
operand(dividend) is divided by the second operand(divisor).

Syntax:

num1 % num2

Example:

num1 = 5, num2 = 2
mod = num1 % num2 = 1

Shift Operator
shift operators are the special type of operators that work on the bits of the data. These
operators are used to shift the bits of the numbers from left to right or right to left depending
on the type of shift operator used. There are three types of shift operators in Java:

Signed Left Shift Operator (<<)


The signed left shift operator is a special type of operator used to move the bits of the
expression to the left according to the number specified after the operator.

Java: Module 1 30
Example

Consider x =5.

Binary equivalent of 5 is 0101.

Signed Right Shift Operator (>>)

The signed right shift operator is a special type of operator used to move the bits of the
expression to the right according to the number specified after the operator.
Example

Consider x=80.

Binary equivalent of 80 is 1010000.

Java: Module 1 31
Assume that the statement is as follows:

x>>4, let y be 4

Unsigned Right Shift Operator (>>>)


The unsigned right shift operator is a special type of right shift operator that does not
use the signal bit to fill in the sequence. The unsigned sign shift operator on the right
always fills the sequence by 0.

Relational Operator
Java Relational Operators are a bunch of binary operators used to check for relations
between two operands, including equality, greater than, less than, etc. They return a
boolean result after the comparison and are extensively used in looping statements as well
as conditional if-else statements and so on. The general format of representing relational
operator is:

Syntax:

Java: Module 1 32
variable1relation_operator variable2

Operator 1: ‘Equal to’ operator (==)


This operator is used to check whether the two given operands are equal or not. The
operator returns true if the operand at the left-hand side is equal to the right-hand side,
else false.
Syntax:

var1 == var2

Illustration:

var1 = 20
var2 = 20
var1 == var2 results in true

Operator 2: ‘Not equal to’ Operator(!=)


This operator is used to check whether the two given operands are equal or not. It
functions opposite to that of the equal-to-operator. It returns true if the operand at the
left-hand side is not equal to the right-hand side, else false.

Syntax:

var1 != var2

Illustration:

var1 = 12
var2 = 20

var1 != var2 results in true

Operator 3: ‘Greater than’ operator(>)


This checks whether the first operand is greater than the second operand or not. The
operator returns true when the operand at the left-hand side is greater than the right-
hand side.

Syntax:

Java: Module 1 33
var1 > var2

Illustration:

var1 = 30
var2 = 20

var1 > var2 results in true

Operator 4: ‘Less than’ Operator(<)


This checks whether the first operand is less than the second operand or not. The
operator returns true when the operand at the left-hand side is less than the right-hand
side. It functions opposite to that of the greater-than operator.

Syntax:

var1 < var2

Illustration:

var1 = 10
var2 = 20

var1 < var2 results in true

Operator 5:Greater than or equal to (>=)


This checks whether the first operand is greater than or equal to the second operand or
not. The operator returns true when the operand at the left-hand side is greater than or
equal to the right-hand side.

Syntax:

var1 >= var2

Illustration:

var1 = 20
var2 = 20
var3 = 10

Java: Module 1 34
var1 >= var2 results in true
var2 >= var3 results in true

Operator 6: Less than or equal to (<=)


This checks whether the first operand is less than or equal to the second operand or
not. The operator returns true when the operand at the left-hand side is less than or
equal to the right-hand side.

Syntax:

var1 <= var2

Illustration:

var1 = 10
var2 = 10
var3 = 9

var1 <= var2 results in true


var2 <= var3 results in false

Java program to illustrate relational operator

public class Test {

public static void main(String args[]) {


int a = 10;
int b = 20;

[Link]("a == b = " + (a == b) );
[Link]("a != b = " + (a != b) );
[Link]("a > b = " + (a > b) );
[Link]("a < b = " + (a < b) );
[Link]("b >= a = " + (b >= a) );
[Link]("b <= a = " + (b <= a) );
}
}

Output

a == b = false
a != b = true
a > b = false
a < b = true

Java: Module 1 35
b >= a = true
b <= a = false

Bitwise Operator
Bitwise operators are used to performing the manipulation of individual bits of a number.
They can be used with any integral type (char, short, int, etc.). They are used when
performing update and query operations of the Binary indexed trees.

1. Bitwise OR (|)

This operator is a binary operator, denoted by ‘|’. It returns bit by bit OR of input values, i.e.,
if either of the bits is 1, it gives 1, else it shows 0.

Example:

a = 5 = 0101 (In Binary)


b = 7 = 0111 (In Binary)

Bitwise OR Operation of 5 and 7


0101
| 0111
________
0111 = 7 (In decimal)

2. Bitwise AND (&)

This operator is a binary operator, denoted by ‘&.’ It returns bit by bit AND of input values,
i.e., if both bits are 1, it gives 1, else it shows 0.

Example:

a = 5 = 0101 (In Binary)


b = 7 = 0111 (In Binary)

Bitwise AND Operation of 5 and 7


0101
& 0111
________
0101 = 5 (In decimal)

3. Bitwise XOR (^)

This operator is a binary operator, denoted by ‘^.’ It returns bit by bit XOR of input values,
i.e., if corresponding bits are different, it gives 1, else it shows 0.

Example:

Java: Module 1 36
a = 5 = 0101 (In Binary)
b = 7 = 0111 (In Binary)

Bitwise XOR Operation of 5 and 7


0101
^ 0111
________
0010 = 2 (In decimal)

4. Bitwise Complement (~)

This operator is a unary operator, denoted by ‘~.’ It returns the one’s complement
representation of the input value, i.e., with all bits inverted, which means it makes every 0
to 1, and every 1 to 0.

Example:

a = 5 = 0101 (In Binary)

Bitwise Complement Operation of 5

~ 0101
________
1010 = 10 (In decimal)

java program to demonstrate Bitwise operator example

// Java program to illustrate


// bitwise operators

public class operators {


public static void main(String[] args)
{
// Initial values
int a = 5;
int b = 7;

// bitwise and
// 0101 & 0111=0101 = 5
[Link]("a&b = " + (a & b));

// bitwise or
// 0101 | 0111=0111 = 7
[Link]("a|b = " + (a | b));

// bitwise xor
// 0101 ^ 0111=0010 = 2
[Link]("a^b = " + (a ^ b));

// bitwise not
// ~00000000 00000000 00000000 00000101=11111111 11111111 11111111 11111010

Java: Module 1 37
// will give 2's complement (32 bit) of 5 = -6
[Link]("~a = " + ~a);

// can also be combined with


// assignment operator to provide shorthand
// assignment
// a=a&b
a &= b;
[Link]("a= " + a);
}
}

Output

a&b = 5
a|b = 7
a^b = 2
~a = -6
a= 5

Logical Operator
The operators that are used to do logical operators ,

The types of Logical operators are :

Operator Name Description Example

&& Logical and Returns true if both statements are true x < 5 && x < 10

|| Logical or Returns true if one of the statements is true x < 5 || x < 4

Reverse the result, returns false if the result !(x < 5 && x <
! Logical not
is true 10)

Ternary Operator
Java ternary operator is the only conditional operator that takes three operands. It’s a one-
liner replacement for the if-then-else statement and is used a lot in Java programming. We
can use the ternary operator in place of if-else conditions or even switch conditions using
nested ternary operators.

Java: Module 1 38
Syntax:

variable = Expression1 ? Expression2: Expression3

If operates similarly to that of the if-else statement as in Exression2 is executed


if Expression1 is true else Expression3 is executed.

if(Expression1)
{
variable = Expression2;
}
else
{
variable = Expression3;
}

Assignment Operator.
Assignment operators are used in Java to assign values to variables

Operator Example Equivalent to


= a = b; a = b;

+= a += b; a = a + b;

-= a -= b; a = a - b;

*= a *= b; a = a * b;

/= a /= b; a = a / b;

%= a %= b; a = a % b;

Control statements

Java: Module 1 39
Java uses control statements to control the flow of execution of a program based on certain
conditions. These are used to cause the flow of execution to advance and branch based on
changes to the state of a program.
There are 3 Control statements in Java they are:

Decision-Making statements
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,.

if statements
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

Types of if Statements are

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

Java: Module 1 40
if(condition) {
statement 1; //executes when condition is true
}

example

// Java program to illustrate If statement


import [Link].*;

class IfDemo {
public static void main(String args[])
{
int i = 10;

if (i < 15)
[Link]("Inside If block");
[Link]("10 is less than 15");
// This statement will be executed
// as if considers one statement by default
[Link]("I am Not in if");
}
}

if-else statement

he if statement alone tells us that if a condition is true it will execute a block of


statements and if the condition is false it won’t. But what if we want to do something
else if the condition is false. Here comes the else statement. We can use the else
statement with if statement to execute a block of code when the condition is false.

Syntax:

if (condition)
{

Java: Module 1 41
// Executes this block if
// condition is true
}
else
{
// Executes this block if
// condition is false
}

Example

// Java program to illustrate if-else statement


import [Link].*;

class IfElseDemo {
public static void main(String args[])
{
int i = 10;

if (i < 15)
[Link]("i is smaller than 15");
else
[Link]("i is greater than 15");
}
}

if-else-if ladder

Here, a user can decide among multiple [Link] if statements are executed
from the top down. As soon as one of the conditions controlling the if is true, the
statement associated with that if is executed, and the rest of the ladder is bypassed.
If none of the conditions is true, then the final else statement will be executed.

Java: Module 1 42
Syntax

if (condition)
statement;
else if (condition)
statement;
.
.
else
statement;

Example

// Java program to illustrate if-else-if ladder


import [Link].*;

class ifelseifDemo {
public static void main(String args[])
{
int i = 20;

if (i == 10)
[Link]("i is 10");
else if (i == 15)
[Link]("i is 15");
else if (i == 20)
[Link]("i is 20");
else
[Link]("i is not present");

Java: Module 1 43
}
}

Nested if-statement

A nested if is an if statement that is the target of another if or else. Nested if


statements mean an if statement inside an if statement. Yes, java allows us to nest
if statements within if statements. i.e, we can place an if statement inside another if
statement.

Syntax:

if (condition1)
{
// Executes when condition1 is true
if (condition2)
{
// Executes when condition2 is true
}
}

Example

// Java program to illustrate nested-if statement


import [Link].*;

class NestedIfDemo {
public static void main(String args[])
{
int i = 10;

if (i == 10 || i<15) {
// First if statement
if (i < 15)
[Link]("i is smaller than 15");

Java: Module 1 44
// Nested - if statement
// Will only be executed if statement above
// it is true
if (i < 12)
[Link](
"i is smaller than 12 too");
} else{
[Link]("i is greater than 15");
}
}
}

Switch
The switch statement is a multi-way branch statement. It provides an easy way to
dispatch execution to different parts of code based on the value of the expression.

The case variables can be int, short, byte, char, or enumeration. String type is also
supported since version 7 of Java

Cases cannot be duplicate

Default statement is executed when any of the case doesn't match the value of
expression. It is optional.

Break statement terminates the switch block when the condition is [Link] is
optional, if not used, next case is executed.

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.

Java: Module 1 45
Syntax:

switch (expression)
{
case value1:
statement1;
break;
case value2:
statement2;
break;
.
.
case valueN:
statementN;

Java: Module 1 46
break;
default:
statementDefault;
}

Example

// Java Program to check the size


// using the switch...case statement

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

int number = 44;


String size;

// switch statement to check size


switch (number) {

case 29:
size = "Small";
break;

case 42:
size = "Medium";
break;

// match the value of week


case 44:
size = "Large";
break;

case 48:
size = "Extra Large";
break;

default:
size = "Unknown";
break;

}
[Link]("Size: " + size);
}
}

Loop Statements
Looping is a feature which facilitates the execution of a set of instructions/functions
repeatedly while some condition evaluates to true. Java provides three ways for executing
the loops.

Java: Module 1 47
The three types of java loops are :

For Loop(Entry Controlled Loop)


For loop provides a concise way of writing the loop structure. Unlike a while loop, a for
statement consumes the initialization, condition and increment/decrement in one line
thereby providing a shorter, easy to debug structure of looping.

Syntax:

for (initialization condition; testing condition;incrmnt/decrmnt)


{
statement(s)
}

Initialization condition: Here, we initialize the variable in use. It marks the start of
a for loop. An already declared variable can be used or a variable can be declared,
local to loop only.

Java: Module 1 48
Testing Condition: It is used for testing the exit condition for a loop. It must return
a boolean value. It is also an Entry Control Loop as the condition is checked prior
to the execution of the loop statements.

Statement execution: Once the condition is evaluated to true, the statements in


the loop body are executed.

Increment/ Decrement: It is used for updating the variable for next iteration.

Loop termination:When the condition becomes false, the loop terminates marking
the end of its life cycle.
Example

/*package whatever //do not write package name here */

import [Link].*;

class GFG {
public static void main (String[] args) {
for (int i=0;i<=10;i++)
{
[Link](i);
}
}
}

While Loop(Entry controlled Loop)


A while loop is a control flow statement that allows code to be executed repeatedly
based on a given Boolean condition. The while loop can be thought of as a repeating if
statement.

Syntax :

while (boolean condition)


{
loop statements...
}

Java: Module 1 49
While loop starts with the checking of Boolean condition. If it evaluated to true, then
the loop body statements are executed otherwise first statement following the loop
is executed. For this reason it is also called Entry control loop

Once the condition is evaluated to true, the statements in the loop body are
executed. Normally the statements contain an update value for the variable being
processed for the next iteration.

When the condition becomes false, the loop terminates which marks the end of its
life cycle.

Example

/*package whatever //do not write package name here */

import [Link].*;

class GFG {
public static void main (String[] args) {
int i=0;
while (i<=10)
{
[Link](i);
i++;
}
}
}

Output

0
1
2
3
4
5
6

Java: Module 1 50
7
8
9
10

Do-While(Exit Controlled Loop)


do while loop is similar to while loop with only difference that it checks for condition
after executing the statements, and therefore is an example of Exit Control Loop.

Syntax:

do
{
statements..
}
while (condition);

do while loop starts with the execution of the statement(s). There is no checking of
any condition for the first time.

After the execution of the statements, and update of the variable value, the
condition is checked for true or false value. If it is evaluated to true, next iteration of
loop [Link] the condition becomes false, the loop terminates which marks the
end of its life cycle.

It is important to note that the do-while loop will execute its statements atleast once
before any condition is checked, and therefore is an example of exit control loop.

Example

/*package whatever //do not write package name here */

Java: Module 1 51
import [Link].*;

class GFG {
public static void main (String[] args) {
int i=0;
do
{
[Link](i);
i++;
}while(i<=10);
}
}

Output

0
1
2
3
4
5
6
7
8
9
10

Jump Statements
Jumping statements are control statements that transfer execution control from one point to
another point in the program. There are two Jump statements that are provided in the Java
programming language:

Break Statement
1. Using Break Statement to exit a loop:

In java, the break statement is used to terminate the execution of the nearest looping
statement or switch statement. The break statement is widely used with the switch
statement, for loop, while loop, do-while loop.

Syntax

break;

When a break statement is found inside a loop, the loop is terminated, and the control
reaches the statement that follows the loop.

Java: Module 1 52
// Java program to illustrate the
// break keyword in Java
import [Link].*;

class GFG {
public static void main(String[] args)
{
int n = 10;
for (int i = 0; i < n; i++) {
if (i == 6)
break;
[Link](i);
}
}
}

Output

0
1
2
3
4
5

As you see, the code is meant to print 1 to 10 numbers using for loop, but it prints only 1
to 5 . as soon as i is equal to 6, the control terminates the loop.

In a switch statement, if the break statement is missing, every case label is executed till
the end of the switch.

2. Use Break as a form of goto

Java does not have a goto statement because it produces an unstructured way to alter
the flow of program execution. Java illustrates an extended form of the break statement.
This form of break works with the label. The label is the name of a label that identifies
a statement or a block of code.

Syntax:

break label;

When this form of break executes, control jumps out of the labeled statement or block.
Example

Java: Module 1 53
// Java program to illustrate the
// break keyword as a Goto statement in Java
import [Link].*;

class GFG {
public static void main(String[] args)
{
for (int i = 0; i < 3; i++) {
one : { // label one
two : { // label two
three : { // label three
[Link]("i=" + i);
if (i == 0)
break one; // break to label one
if (i == 1)
break two; // break to label two
if (i == 2)
break three; // break to label three
}
[Link]("after label three");
}
[Link]("after label two");
}
[Link]("after label one");
}
}
}

Output

i=0
after label one
i=1
after label two
after label one
i=2
after label three
after label two
after label one

In the above program, when i=0, the first if statement succeeds, and cause a break to
label one and then prints the statement. When i=1, the second if statement succeeds,
and cause a break to label two and then prints the statements. When i=2, the third if
statement succeeds, and cause a break to the to label three and then prints all the three
statements.

Continue Statement
The continue statement pushes the next repetition of the loop to take place, hopping
any code between itself and the conditional expression that controls the loop.

Java: Module 1 54
Example

// Java program to illustrate the


// continue keyword in Java
import [Link].*;

class GFG {
public static void main(String[] args)
{
for (int i = 0; i < 10; i++) {
if (i == 6){
[Link]();
// using continue keyword
// to skip the current iteration
continue;
}
[Link](i);
}
}
}

Output

0
1
2
3
4
5

7
8
9

In the program, when the value of i is 6, the compiler encounters the continue
statement, then 6 is skipped.

Arrays
Array in java is a group of like-typed variables referred to by a common name.

In Java, all arrays are dynamically allocated.

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.

Java: Module 1 55
The variables in the array are ordered, and each has an index beginning from 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 [Link].

This storage of arrays helps us randomly accessing 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
.

Creating an Array (one Dimensional Array)


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.

Java: Module 1 56
Example

int Array1[];
or
int[] Array1;
//Array 1 is the arrray name

Initializing an Array(One Dimensional Array)


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 using new keyword.
Syntax

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, we 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

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

Java: Module 1 57
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.

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

// accessing the elements of the specified array


for (int i = 0; i < [Link]; i++)
[Link]("Element at index " + i + " : "+ arr[i]);

Example

// Java program to illustrate creating an array


// of integers, puts some values in the array,
// and prints each value to standard output.

class GFG {
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 < [Link]; i++)
[Link]("Element at index " + i
+ " : " + arr[i]);
}
}

Output

Java: Module 1 58
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

Classes and objects


Class
1. Class is a set of object which shares common characteristics/ behavior and common
properties/ attributes.

2. Class is not a real world entity. It is just a template or blueprint or prototype from which
objects are created.

3. Class does not occupy memory.

4. Class is a group of variables of different data types and group of methods.

A class in java can contain:

data member

method

constructor

nested class

interface

Defining a class
Java provides a reserved keyword class to define a class. The keyword must be followed
by the class name. Inside the class, we declare methods and variables.

In general, class declaration includes the following in the order as it appears:

1. Modifiers: A class can be public or has default access.

2. class keyword: The class keyword is used to create a class.

3. Class name: The name must begin with an initial letter (capitalized by convention).

4. Super-class (if any): The name of the class's parent (superclass), if any, preceded by
the keyword extends. A class can only extend (subclass) one parent.

Java: Module 1 59
5. Interfaces (if any): A comma-separated list of interfaces implemented by the class, if
any, preceded by the keyword implements. A class can implement more than one
interface.

6. Body: The class body surrounded by braces, { }.

Syntax:

<access specifier> class class_name


{
// member variables
// class methods
}

Example

public class Dog {


String breed;
int age;//these are instance variables
String color;
static String food;//Static variable

void barking() {
int local_var;//Local variable
}

void hungry() {
}

void sleeping() {
}
}

A class can contain any of the following variable types.

Local variables − Variables defined inside methods, constructors or blocks are called
local variables. The variable will be declared and initialized within the method and the
variable will be destroyed when the method has completed.

Instance variables − Instance variables are variables within a class but outside any
method. These variables are initialized when the class is instantiated. Instance
variables can be accessed from inside any method, constructor or blocks of that
particular class.

Class variables or Static Variables− Class variables are variables declared within a
class, outside any method, with the static keyword.

Java: Module 1 60
Objects
An Object is a real world entity , also the it is a blueprint of a class , an object must contain
:

1. State: It is represented by attributes of an object. It also reflects the properties of an


object.

2. Behavior: It is represented by methods of an object. It also reflects the response of an


object with other objects.

3. Identity: It gives a unique name to an object and enables one object to interact with
other objects.

There are three steps when creating an object from a class −

Declaration − A variable declaration with a variable name with an object type.

Instantiation − The 'new' keyword is used to create the object.

Initialization − The 'new' keyword is followed by a call to a constructor. This call


initializes the new object.

Syntax

ClassName object = new ClassName();

When an object of a class is created, the class is said to be instantiated. All the instances
share the attributes and the behavior of the class. But the values of those attributes, i.e. the
state are unique for each object. A single class may have any number of instances.

Java: Module 1 61
As we declare variables like (type name;). This notifies the compiler that we will use the
name to refer to data whose type is type. With a primitive variable, this declaration also
reserves the proper amount of memory for the variable. So for reference variable, the type
must be strictly a concrete class name. In general, we can’t create objects of an abstract
class or an interface.
Initializing an object

The new operator instantiates a class by allocating memory for a new object and returning
a reference to that memory. The new operator also invokes the class constructor.

public class Dog {

int age;

//This is a constructor
public Dog(int k) {
age = k;
}

void DogAge() {
[Link]("Age 0f Dog = " + age);
}

public static void main(String[] args) {

// Instatiating An object
Dog d = new Dog(5);

[Link]();
}

Java: Module 1 62
Method declaration
The method declaration provides information about method attributes, such as visibility,
return-type, name, and arguments. It has six components that are known as method
header.

Method Signature: Every method has a method signature. It is a part of the method
declaration. It includes the method name and parameter list.

Access Specifier: Access specifier or modifier is the access type of the method. It
specifies the visibility of the method. Java provides four types of access specifier:

Public: The method is accessible by all classes when we use public specifier in our
application.

Private: When we use a private access specifier, the method is accessible only in the
classes in which it is defined.

Protected: When we use protected access specifier, the method is accessible within
the same package or sub-classes in a different package.

Default: When we do not use any access specifier in the method declaration, Java
uses default access specifier by default. It is visible only from the same package only.

Return Type: Return type is a data type that the method returns. It may have a primitive
data type, object, collection, void, etc. If the method does not return anything, we use void
keyword.

Method Name: It is a unique name that is used to define the name of a method. It must be
corresponding to the functionality of the method. Suppose, if we are creating a method for
subtraction of two numbers, the method name must be subtraction(). A method is invoked
by its name.

Java: Module 1 63
Parameter List: It is the list of parameters separated by a comma and enclosed in the pair
of parentheses. It contains the data type and variable name. If the method has no
parameter, left the parentheses blank.
Method Body: It is a part of the method declaration. It contains all the actions to be
performed. It is enclosed within the pair of curly braces.

Constructor
In Java, a constructor is a block of codes similar to the method. It is called when an
instance of the class is created. At the time of calling constructor, memory for the object is
allocated in the memory.

Every time an object is created using the new keyword, at least one constructor is called.

It calls a default constructor if there is no constructor available in the class. In such case,
Java compiler provides a default constructor by default.

public class Dog {

int age;

//This is a constructor
public Dog(int k) {
age = k;
}

void DogAge() {
[Link]("Age 0f Dog = " + age);
}

public static void main(String[] args) {

// Instatiating An object
Dog d = new Dog(5);

[Link]();
}

.
Rules for creating Java constructor
There are two rules defined for the constructor.

1. Constructor name must be the same as its class name

2. A Constructor must have no explicit return type

3. A Java constructor cannot be abstract, static, final, and synchronized

Java: Module 1 64
Types of java Constructors:
Default Constructor
A constructor that has no parameters is known as default the constructor. A default
constructor is invisible. And if we write a constructor with arguments or no arguments
then the compiler does not create a default constructor. It is taken out. It is being
overloaded and called a parameterized constructor. The default constructor changed
into the parameterized constructor. But Parameterized constructor can’t change the
default constructor.
Syntax

<class_name>(){}//no need to write this code in program to invoke default constructor

Example

import [Link].*;

class GFG {
GFG() { [Link]("Default constructor"); }
public static void main(String[] args)
{

GFG hello = new GFG();


}
}

Output

Default constructor

Note: Default constructor provides the default values to the object like 0, null, etc.
depending on the type.

Non-Parameterized Constructor
A constructor that has no parameter is known as the Non-parameterized Constructor or
Zero argument constructor. If we don’t define a constructor in a class, then the compiler
creates a constructor(with no arguments)

Java: Module 1 65
for the class. And if we write a constructor with arguments or no arguments then the
compiler does not create a default constructor.

// Java Program to illustrate calling a


// Zero argument constructor

import [Link].*;

class Computer {
int num;
String name;

// this would be invoked while an object


// of that class is created.
Computer() { [Link]("Constructor called"); }
}

class main_class {
public static void main(String[] args)
{
// this would invoke default constructor.
Computer g = new Computer();

// Default constructor provides the default


// values to the object like 0, null
[Link]([Link]);
[Link]([Link]);
}
}

Output

Constructor called
null
0

Parameterized Constructor
A constructor which has a specific number of parameters is called a parameterized
constructor.

//Java Program to demonstrate the use of the parameterized constructor.


class Student4{
int id;
String name;
//creating a parameterized constructor
Student4(int i,String n){
id = i;
name = n;
}
//method to display the values

Java: Module 1 66
void display(){[Link](id+" "+name);}

public static void main(String args[]){


//creating objects and passing values
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
//calling method to display the values of object
[Link]();
[Link]();
}
}

Output

111 Karan
222 Aryan

Method overloading
Method Overloading allows different methods to have the same name, but different
signatures where the signature can differ by the number of input parameters or type of
input parameters, or a mixture of both.

Method overloading is also known as Compile-time Polymorphism, Static


Polymorphism, or Early binding in Java. In Method overloading compared to parent
argument, child argument will get the highest priority.

Different Ways of Method Overloading in Java

Changing the Number of Parameters.


Method overloading can be achieved by changing the number of parameters while
passing to different methods.

// Java Program to Illustrate Method Overloading


// By Changing the Number of Parameters

// Importing required classes


import [Link].*;

// Class 1
// Helper class
class Product {

// Method 1

Java: Module 1 67
// Multiplying two integer values
public int multiply(int a, int b)
{
int prod = a * b;
return prod;
}

// Method 2
// Multiplying three integer values
public int multiply(int a, int b, int c)
{
int prod = a * b * c;
return prod;
}
}

// Class 2
// Main class
class GFG {

// Main driver method


public static void main(String[] args)
{

// Creating object of above class inside main()


// method
Product ob = new Product();

// Calling method to Multiply 2 numbers


int prod1 = [Link](1, 2);

// Printing Product of 2 numbers


[Link](
"Product of the two integer value :" + prod1);

// Calling method to multiply 3 numbers


int prod2 = [Link](1, 2, 3);

// Printing product of 3 numbers


[Link](
"Product of the three integer value :" + prod2);
}
}

Changing Data Types of the Arguments.


In many cases, methods can be considered Overloaded if they have the same name
but have different parameter types, methods are considered to be overloaded.

// Java Program to Illustrate Method Overloading


// By Changing Data Types of the Parameters

// Importing required classes


import [Link].*;

// Class 1

Java: Module 1 68
// Helper class
class Product {

// Multiplying three integer values


public int Prod(int a, int b, int c)
{

int prod1 = a * b * c;
return prod1;
}

// Multiplying three double values.


public double Prod(double a, double b, double c)
{

double prod2 = a * b * c;
return prod2;
}
}

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

Product obj = new Product();

int prod1 = [Link](1, 2, 3);


[Link]("Product of the three integer value :" + prod1);
double prod2 = [Link](1.0, 2.0, 3.0);
[Link]("Product of the three double value :" + prod2);
}
}

Changing the Order of the Parameters of Methods


Method overloading can also be implemented by rearranging the parameters of two or
more overloaded methods. For example, if the parameters of method 1 are (String
name, int roll_no) and the other method is (int roll_no, String name) but both have the
same name, then these 2 methods are considered to be overloaded with different
sequences of parameters.

// Java Program to Illustrate Method Overloading


// By changing the Order of the Parameters

// Importing required classes


import [Link].*;

// Class 1
// Helper class

Java: Module 1 69
class Student {

// Method 1
public void StudentId(String name, int roll_no)
{
[Link]("Name :" + name + " " + "Roll-No :" + roll_no);
}
// Method 2
public void StudentId(int roll_no, String name)
{
// Again printing name and id of person
[Link]("Roll-No :" + roll_no + " " + "Name :" + name);
}
}

// Class 2
// Main class
class GFG {

public static void main(String[] args)


{

// Creating object of above class


Student obj = new Student();

// Passing name and id


// Note: Reversing order
[Link]("Spyd3r", 1);
[Link](2, "Kamlesh");
}
}

Java: Module 1 70
󾠯
java : Module 2

Inheritance
Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors of a parent
object. It is an important part of OOPs (Object Oriented programming system).

In Java, it is possible to inherit attributes and methods from one class to another. We group the "inheritance
concept" into two categories:

subclass (child) - the class that inherits from another class

superclass (parent) - the class being inherited from

To inherit from a class, use the extends keyword.

Creating Sub-classes

class Subclass-name extends Superclass-name


{
//methods and fields
}

Eg: inherting a subclass (single inheritance)

//This is a superclass
class Employee {
void salary() {
[Link]("Salary= 200000");
}
}
//This is a subclass
class Programmer extends Employee {
// Programmer class inherits from Employee class
void bonus() {

java : Module 2 1
[Link]("Bonus=50000");
}
}

class single_inheritance {
public static void main(String args[]) {
Programmer p = new Programmer();
[Link](); // calls method of super class
[Link](); // calls method of sub class
}
}

Types of java Inheritance


On the basis of class, there can be three types of inheritance in java: single, multilevel and [Link]
java programming, multiple and hybrid inheritance is supported through interface only.

Single Inheritance
When a class inherits another class, it is known as a single inheritance.

class Animal{

void eat(){
[Link]("eating...");
}
}

class Dog extends Animal{


void bark(){
[Link]("barking...");
}
}

class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
[Link]();
[Link]();
}
}

Output:

java : Module 2 2
barking...
eating...

Dog class inherits the Animal class, so there is the single inheritance.

Multilevel Inheritance
The multi-level inheritance includes the involvement of at least two or more than two classes. One class
inherits the features from a parent class and the newly created sub-class becomes the base class for
another new class.

Class SuperClass
{
public void methodA()
{
[Link]("SuperClass");
}
}

Class SubClassB extends SuperClass


{
public void methodB()
{
[Link]("SubClassB ");
}
}

Class SubClassC extends SubClassB


{
public void methodC()
{
[Link]("SubClassC");
}

public static void main(String args[])


{
SubClassB obj = new SubClassB();
[Link](); //calling super class method
[Link](); //calling subclass 1 method
[Link](); //calling own method
}

Output

SuperClass

SubClassB

SubClassC

Hierarchical Inheritance

java : Module 2 3
"Hierarchical inheritance" occurs when multiple child classes
inherit the methods and properties of the same parent class. This simply means we have only one
super-class and multiple sub-classes in hierarchical inheritance in Java.

// creating the base class(or superclass)


class BaseClass
{
int parentNum = 10;
}

// creating the subclass1 that inherits the base class


class SubClass1 extends BaseClass
{
int childNum1 = 1;
}

// creating the subclass2 that inherits the base class


class SubClass2 extends BaseClass
{
int childNum2 = 2;
}

// creating the subclass3 that inherits the base class


class SubClass3 extends BaseClass
{
int childNum3 = 3;
}
public class Main
{
public static void main(String args[])
{
SubClass1 childObj1 = new SubClass1 ();
SubClass2 childObj2 = new SubClass2 ();
SubClass3 childObj3 = new SubClass3 ();

[Link]("parentNum * childNum1 = " + [Link] * childObj1.childNum1); // 10 * 1 = 10


[Link]("parentNum * childNum2 = " + [Link] * childObj2.childNum2); // 10 * 2 = 20
[Link]("parentNum * childNum3 = " + [Link] * childObj3.childNum3); // 10 * 3 = 30
}
}

output

parentNum * childNum1 = 10
parentNum * childNum2 = 20
parentNum * childNum3 = 30

Q) Why multiple inheritance is not supported in java?

java doesn’t provide support for multiple inheritance in classes. Java doesn’t support multiple
inheritances in classes because it can lead to diamond problem and rather than providing some
complex way to solve it, there are better ways through which we can achieve the same result as multiple
inheritances or via implementing interfaces.

java : Module 2 4
Method overriding
Overriding is a feature that allows a subclass or child class to provide a specific implementation of a method
that is already provided by one of its super-classes or parent classes. When a method in a subclass has the
same name, same parameters or signature, and same return type(or sub-type) as a method in its super-
class, then the method in the subclass is said to override the method in the super-class.

class Animal {
public void displayInfo() {
[Link]("I am an animal.");
}
}

class Dog extends Animal {

java : Module 2 5
public void displayInfo() {
//Here the oveririding occurs
[Link]("I am a dog.");
}
}

public class Main {


public static void main(String[] args) {
Dog d1 = new Dog();
[Link]();
}
}

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.

Super Keyword
Super keyword is the alternative of virtual keyword in cpp

Super keyword is introduced in java for accesssing the superclass methods after overriding .

class Animal {
public void displayInfo() {
[Link]("I am an animal from super class.");
}
}

class Dog extends Animal {


//This function is first overrided from the superclass
public void displayInfo() {
//calling the exact same function but it is mentioned in the super class
[Link]();
[Link]("I am a dog from subclass.");
}
}

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

Output

java : Module 2 6
Final keyword

[Link]

While inheritance enables us to reuse existing code, sometimes we do need to set limitations on
extensibility for various reasons; the final keyword allows us to do exactly that.

Final Classes
Classes marked as final can’t be extended.
Eg:

public final class Cat {

private int weight;

// standard getter and setter


}
public class BlackCat extends Cat {
}
//here we used are trying to inherit the supercalss with final keyword

output
The type BlackCat cannot subclass the final class Cat

Here the Java compiler restricted the class inhertance due to the consideration of the Final keyword .

Final variables
Variables marked as final can't be reassigned. Once a final variable is initialized, it can’t be altered.

java : Module 2 7
class Bike9{
final int speedlimit=90;//final variable
void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike9 obj=new Bike9();
[Link]();
}

Final Methods
Methods marked as final cannot be overridden.
When we design a class and feel that a method shouldn’t be overridden, we can make this method
final

public class Dog {


public final void sound() {
// ...
}
}

Inherting this class and overriding the method sound()

public class BlackDog extends Dog {


public void sound() {
}
}

output

Cannot override the final method from Dog

sound() method is final and can’t be overridden

Here the compiler stated that we cant override the methods with Final keyword.

Packages and Interfaces

java : Module 2 8
packages

[Link]

A Java package is a collection of similar types of sub-packages, interfaces, and classes.


In Java, there are two types of packages:

built-in packages

user-defined packages.

The package keyword is used in Java to create Java packages.

Many in-built packages are available in Java, including util, lang, awt, javax, swing, net, io, sql, etc. We can
import all members of a package using packagename.* statement.

Advantages of Java Packages

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

Java package provides access protection.

Java package removes naming collisions.

Accessing packages
There are three ways to access the package from outside the package.

Using package name.*

If you use package.* then all the classes and interfaces of this package will be accessible
but not subpackages.
The import keyword is used to make the classes and interface of another package
accessible to the current package.

Example

//Here we are creating a package using the below line of code


package pack;
public class A{
public void msg(){[Link]("Hello");}
}
//This file is saved as [Link]

Importing the Above mentioned package ‘pack’ into another java program.

//We are also creatinga package 'mypack' here.


package mypack;//importing the user defined pacakge of above
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
[Link]();
}
}

java : Module 2 9
Using package name .class

If you import [Link] then only declared class of this package will be
accessible.

Example

package pack;
public class A{
public void msg(){[Link]("Hello");}
}

using import pack.A;

package mypack;
import pack.A;
class B{
public static void main(String args[]){
A obj = new A();
[Link]();
}
}

Using fully qualified name


If you use fully qualified name then only declared class of this package will be
accessible. Now there is no need to import. But you need to use fully qualified name
every time when you are accessing the class or interface.

It is generally used when two packages have same class name e.g. [Link] and
[Link] packages contain Date class.

Example

package pack;
public class A{
public void msg(){[Link]("Hello");}
}

//save as [Link]

package mypack;
class B{
public static void main(String args[]){
pack.A obj = new pack.A();//using fully qualified name
[Link]();
}
}

java : Module 2 10
Access Modifiers
The access modifiers in Java specifies the accessibility or scope of a field, method,
constructor, or class. We can change the access level of fields, constructors, methods,
and class by applying the access modifier on it.

Access Modifiers in Java are :

Private
The private access modifier is specified using the keyword private.

The methods or data members declared as private are accessible only within the class in
which they are declared.

Any other class of the same package will not be able to access these members.

Top-level classes or interfaces can not be declared as private because

1. private means “only visible within the enclosing class”.

2. protected means “only visible within the enclosing class and any subclasses”

Example

// Java program to illustrate error while


// using class from different package with
// private modifier
package p1;

class A
{
private void display()
{
[Link]("Hello World !");
}
}

class B
{
public static void main(String args[])
{
A obj = new A();
// Trying to access private method
// of another class
[Link]();
}
}

Output

Default
The access level of a default modifier is only within the package. It cannot be
accessed from outside the package. If you do not specify any access level, it will be the
default.

java : Module 2 11
Example

// Java program to illustrate default modifier


package p1;

// Class Geeks is having Default access modifier


class Geek
{
void display()
{
[Link]("Hello World!");
}
}

// Java program to illustrate error while


// using class from different package with
// default modifier
package p2;
import p1.*;

// This class is having default access modifier


class GeekNew
{
public static void main(String args[])
{
// Accessing class Geek from package p1
Geeks obj = new Geek();

[Link]();
}
}

Output
Compile Time error

Protected

The protected access modifier is specified using the keyword protected.

The methods or data members declared as protected are accessible within the same
package or subclasses in different packages.

Example

// Java program to illustrate


// protected modifier
package p1;

// Class A
public class A
{
protected void display()
{
[Link]("hello World");
}
}

java : Module 2 12
// Java program to illustrate
// protected modifier
package p2;
import p1.*; // importing all classes in package p1

// Class B is subclass of A
class B extends A
{
public static void main(String args[])
{
B obj = new B();
[Link]();
}

Output:

hello World

Public

The public access modifier is specified using the keyword public.

The public access modifier has the widest scope among all other access modifiers.

Classes, methods, or data members that are declared as public are accessible from
everywhere in the program. There is no restriction on the scope of public data members.

Example

// Java program to illustrate


// public modifier
package p1;
public class A
{
public void display()//here we used the public keyword
{
[Link]("HelloWorld");
}
}

package p2;
import p1.*;
class B {
public static void main(String args[])
{
A obj = new A();
[Link]();
}
}

Output
HelloWorld

java : Module 2 13
outside package
Access Modifier within class within package outside package
by subclass only

Private Y N N N

Default Y Y N N

Protected Y Y Y N

Public Y Y Y

Interfaces
What is an interface in java ?

In Java, an interface is a collection of abstract methods and constant variables that define a set of
behaviors that a class can implement. Interfaces allow you to specify what a class should do, but not
how it should do it.

Here is an example of an interface in Java:

public interface Animal {


public void makeSound();
public void move();
}

in this example, theAnimal interface defines two abstract methods: makeSound and move . These methods

do not have any implementation, they just specify that any class that implements the Animal interface
must have these two methods.
To implement an interface in a class, you use the implements keyword, like this:

public class Dog implements Animal {


public void makeSound() {
[Link]("Bark!");
}
public void move() {
[Link]("Walking on four legs.");
}
}

In this example, the class implements the


Dog Animal interface and provides an implementation for the
two abstract methods defined in the interface.
Interfaces are a useful feature in Java because they allow you to define a set of behaviors that a class
must implement, without having to specify how those behaviors are implemented. This allows you to
create flexible and reusable code.

Uses of java interfaces


There are mainly three reasons to use interface. They are

It is used to achieve abstraction.

By interface, we can support the functionality of multiple inheritance.

java : Module 2 14
It can be used to achieve loose coupling.

Declaration of interfaces
To declare an interface in Java, you use the keyword, followed by the name of the interface
interface

and a set of abstract methods. An abstract method is a method that is declared in an interface or
abstract class but does not have an implementation.

interface <interface_name>{

// declare constant fields


// declare methods that abstract
// by default.
}

Relationship between classes and Inheritance

1. A class can implement an interface: When a class implements an interface, it must provide an
implementation for all the abstract methods declared in the interface. This allows the class to
conform to the contract defined by the interface and use the interface's methods. To implement an
interface in a class, you use the implements keyword, like this:

public class Dog implements Animal {


public void makeSound() {
[Link]("Bark!");
}
public void move() {
[Link]("Walking on four legs.");
}
}

2. A class can extend another class and implement one or more interfaces: In Java, a class can only
inherit from one super-class, but it can implement multiple interfaces. This allows you to reuse
code from multiple sources and create classes with a variety of behaviors. To extend a class and
implement an interface, you use the extends and implements keywords, like this:

public class Cat extends Pet implements Animal {


public void makeSound() {

java : Module 2 15
[Link]("Meow!");
}
public void move() {
[Link]("Walking on four legs.");
}
}

3. An interface can extend one or more interfaces: An interface can extend one or more interfaces to
inherit their abstract methods and constant variables. This allows you to create a hierarchy of
interfaces and reuse code in a structured way. To extend an interface, you use the extends keyword,
like this:

public interface DomesticAnimal extends Animal {


public void beDomestic();
}

In this example, the DomesticAnimal interface extends the Animal interface and inherits its abstract
methods and constant variables. It also declares a new abstract method called beDomestic .

Overall, the relationship between classes and interfaces in Java allows you to create flexible and
reusable code, and it enables a variety of design patterns and programming techniques.

IO packages

[Link]

Java I/O (Input and Output) is used to process the input and produce the output.
Java uses the concept of a stream to make I/O operation fast. The [Link] package contains all the classes
required for input and output operations.
We can perform file handling in Java by Java I/O API.

What can you do with I/O

java : Module 2 16
Reading and writing files

Communicating over network sockets

Filtering Data

Compress and Decompress data

Writing objects to streams

Java I/O
The [Link] package consists of input and output streams used to read and write data to files or other input
and output sources.

There are 3 categories of classes in [Link] package:

Input Streams
It is an abstract super-class of the [Link] package and is used to read the data from an input source. In
other words, reading data from files or from a keyboard, etc. We can create an object of the input stream
class using the new keyword. The input stream class has several types of constructors.

Since InputStream is an abstract class, it is not useful by itself. However, its sub-classes can be used to
read data.

Input streams are opened implicitly as soon as it is created. To close the input stream, we use a close()
method on the source object.

In order to use the functionality of InputStream , we can use its sub-classes. Some of them are:

FileInputStream

ByteArrayInputStream

ObjectInputStream

Create an InputStream

InputStream f = new FileInputStream("[Link]");

java : Module 2 17
Here, we have created an input stream using FileInputStream . It is because InputStream is an abstract
class. Hence we cannot create an object of InputStream .

Note: We can also create an input stream from other subclasses of InputStream .

Methods of InputStream
The InputStream class provides different methods that are implemented by its subclasses. Here are some
of the commonly used methods:

read() - reads one byte of data from the input stream

read(byte[] array) - reads bytes from the stream and stores in the specified array

available() - returns the number of bytes available in the input stream

mark() - marks the position in the input stream up to which data has been read

reset() - returns the control to the point in the stream where the mark was set

markSupported() - checks if the mark() and reset() method is supported in the stream

skips() - skips and discards the specified number of bytes from the input stream

close() - closes the input stream.

Example: InputStream Using FileInputStream


Suppose we have a file named [Link] with the following content.

Reading this file using FileInputStream (a subclass of InputStream ).

import [Link];
import [Link];

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

byte[] array = new byte[100];

InputStream input = new FileInputStream("[Link]");

[Link]("Available bytes in the file: " + [Link]());

// Read byte from the input stream


[Link](array);
[Link]("Data read from the file: ");

// Convert byte array into string


String data = new String(array);
[Link](data);

// Close the input stream


[Link]();

java : Module 2 18
}
}

Output

Available bytes in the file: 39


Data read from the file:
This is a line of text inside the file

Output Streams.
OutputStream: OutputStream is an abstract class of Byte Stream that describes stream output and it is
used for writing data to a file, image, audio, etc. Thus, OutputStream writes data to the destination
one at a time.

Subclasses of OutputStream
In order to use the functionality of OutputStream , we can use its subclasses. Some of them are:

FileOutputStream

ByteArrayOutputStream

ObjectOutputStream

Create an OutputStream
In order to create an OutputStream , we must import the [Link] package first. Once we
import the package.

java : Module 2 19
// Creates an OutputStream
OutputStream object = new FileOutputStream();

Here, we have created an object of output stream using FileOutputStream . It is because OutputStream is an
abstract class, so we cannot create an object of OutputStream .

Methods of OutputStream
The OutputStream class provides different methods that are implemented by its subclasses. Here are

some of the methods:

write() - writes the specified byte to the output stream

write(byte[] array) - writes the bytes from the specified array to the output stream

flush() - forces to write all data present in output stream to the destination

close() - closes the output stream

Example: OutputStream Using FileOutputStream

import [Link];
import [Link];

public class Main {

public static void main(String args[]) {


String data = "This is a line of text inside the file.";

OutputStream out = new FileOutputStream("[Link]");

// Converts the string into bytes


byte[] dataBytes = [Link]();

// Writes data to the output stream


[Link](dataBytes);
[Link]("Data is written to the file.");

// Closes the output stream


[Link]();

}
}

To write data to the [Link]


file, we have implemented these methods

[Link](); // To write data to the file


[Link](); // To close the output stream

OUTPUT
This is a line of text inside the file.

java : Module 2 20
java : Module 2 21
󾠰
Java: Module 3

Exception
Introduction
An exception (or exceptional event) is a problem that arises during the
execution of a program. When an Exception occurs the normal flow of the
program is disrupted and the program/Application terminates abnormally,
which is not recommended, therefore, these exceptions are to be handled.
An exception can occur for many different reasons. Following are some
scenarios where an exception occurs.

A user has entered an invalid data.

A file that needs to be opened cannot be found.

A network connection has been lost in the middle of communications or


the JVM has run out of memory.

Exception Handling Techniques


There are several techniques for handling exceptions in Java:

1. Try-catch blocks:

Try-catch blocks allow you to "try" a block of code and "catch" any
exceptions that are thrown. This is the most common technique for

Java: Module 3 1
handling exceptions in Java.

Syntax

try {
// Code that may throw an exception
} catch (ExceptionType1 e) {
// Code to handle ExceptionType1
} catch (ExceptionType2 e) {
// Code to handle ExceptionType2
} catch (ExceptionType3 e) {
// Code to handle ExceptionType3
}
}

Example

import [Link];
import [Link];

public class TryCatchExample {


public static void main(String[] args) {
try {
FileInputStream fis = new FileInputStream("[Link]");
// code that might throw an exception goes here
} catch (FileNotFoundException e) {
// code to handle the FileNotFoundException goes here
[Link]("File not Found");

}
}
}
/*This code will output 'File not Found' if in case the [Link] is
in the destination*/

In this example, the "try" block contains a statement that creates a


new FileInputStream object. If the file "[Link]" does not exist,
this will throw a FileNotFoundException. The catch block catches this
exception and executes the code inside it.

In this case, the catch block simply handles the exception, but you
could also use it to log the exception, display an error message to
the user, or take other appropriate action.
It's important to note that the catch block must specify the type of
exception it is catching. In this example, the catch block catches a
FileNotFoundException, which is a specific type of exception that is
thrown when a file cannot be found. If you want to catch any
exception, you can use the general-purpose Exception class as the
catch parameter.

Java: Module 3 2
2. The "finally" block:

The "finally" block is an optional block of code that can be used in


conjunction with a try-catch block. The code in the finally block
will always be executed, whether or not an exception is thrown. This
can be useful for cleaning up resources or performing other tasks
that need to be done regardless of whether an exception occurs.

syntax

finally{
}

Example

// Java program to demonstrate finally block


// When exception rise and not handled by catch

import [Link].*;

class GFG {
public static void main(String[] args)
{
try {
[Link]("Inside try block");

// Throw an Arithmetic exception


[Link](34 / 0);
}

// Can not accept Arithmetic type exception


// Only accept Null Pointer type Exception
catch (NullPointerException e) {

[Link](
"catch : exception not handled.");
}

// Always execute
finally {

[Link](
"finally : i will execute always.");
}
// This will not execute
[Link]("i want to run");
}
}

ouput

Inside try block


finally : i will execute always.
Exception in thread "main" [Link]: / by zero
at [Link]([Link])

Java: Module 3 3
Here, the program throws an exception but not handled by catch so
finally block execute after the try block and after the execution of
finally block program terminate abnormally, But finally block execute
fine.

3. The "throws" clause:

If you do not want to handle an exception in a try-catch block, you


can use the "throws" clause in the method declaration to specify that
the method may throw an exception. This will cause the exception to
propagate up the call stack until it is caught and handled by another
method or by the top level of the program.

Syntax

returnType methodName(parameterList) throws exceptionList {


// method body
}

Example

import [Link];
import [Link];

public class ThrowsExample {


public static void main(String[] args) throws FileNotFoundException {
FileInputStream fls = new FileInputStream("[Link]");

}
}

Here the previous code is converted to enable the throws expression,,


whenever the code execute without the throws FileNotFoundException it shoots
an exception, if there is no file named “[Link]” in the file
location . Here the throws clause throws out the exceptional case of
File not found.

4. The "throw" statement:

The "throw" statement allows you to throw an exception manually. This


can be useful if you want to throw a custom exception or if you want
to throw an exception that has been caught and modified in some way.

public class Main {


static void checkAge(int age) {
if (age < 18) {
throw new ArithmeticException("Access denied - You must be at least 18 years old.");

Java: Module 3 4
}
else {
[Link]("Access granted - You are old enough!");
}
}

public static void main(String[] args) {


checkAge(15); // Set age to 15 (which is below 18...)
}

5. The "assert" statement:

The "assert" statement can be used to test a boolean expression and


throw an Assertion-Error if the expression evaluates to false. This
is typically used for debugging and testing purposes.

public class AssertDemo {


public static void main(String[] args) {
int x = 10;
assert x > 0; // This assertion will succeed
[Link]("x is positive");

x = -1;
assert x > 0 : "x is not positive"; // This assertion will fail and throw an AssertionError
[Link]("This line will not be reached");
}
}

In this example, the first statement tests whether x is greater


assert

than 0, and since it is, the assertion succeeds and the program
continues to the next line. The second assert statement tests whether
x is positive, and since it is not, the assertion fails and an
AssertionError is thrown.

Note that statements are disabled by default in Java, so they


assert

will not be executed unless the -enableassertions or -ea flag is passed to


the java command when running the program.

Creating your own exceptions


In Java, you can create your own exception class by extending the
class or one of its sub-classes. This allows you to define a
Exception

custom exception type that can be thrown and caught in your program.

public class CustomException extends Exception {


public CustomException(String message) {
super(message);
}
}

Java: Module 3 5
Threads

What is a Thread?

A Thread is an individual, light-weight, and a smallest unit


of a given process. There are multiple threads in a single
process and each thread is independent of the other.

Threads are inter dependent, sometimes it is necessary to switch between


processes to another or one thread to another .

Multitasking
In Java, multitasking refers to the ability of a central processing unit
(CPU), or a single core in a multi-core processor, to execute multiple
processes or threads concurrently. This is achieved by allowing each
process or thread to run for a short period of time before interrupting
it and running the next process or thread. This process is known as
"context switching.”

To create a multi-threaded program in Java, you can use the Thread class

Example

public class MyThread extends Thread {


public void run() {
// code to be executed in the new thread
}
}

// Create a new thread


MyThread t = new MyThread();

// Start the new thread


[Link]();

Creation of new Threads

Java: Module 3 6
Th create a new thread, you program will either extend Thread or
implement the Runnable interface.

By Extending the thread class


Extend the Thread class and override the run() method. Then, create an
instance of the class and call the start() method to start the new thread.

public class MyThread extends Thread {


public void run() {
// code to be executed in the new thread
}
}

// Create a new thread


MyThread t = new MyThread();

// Start the new thread


[Link]();

Here,the code creates a new thread by extending the Thread class and
overriding the method. The start() method is then called to start
run()

the new thread, which will execute the code in the run() method.

But calling the start() method does not actually cause the code in the
method to be executed immediately. Instead, it causes the new
run()

thread to be scheduled for execution as soon as possible. The actual


execution of the thread depends on the scheduling policies of the
operating system and the availability of CPU resources.

By Implementing the Runnable interface

Implement the Runnable interface and pass an instance of the class to the
Thread constructor. Then, call the start() method to start the new thread.

public class MyRunnable implements Runnable {


public void run() {
// code to be executed in the new thread
}
}

// Create a new runnable


MyRunnable r = new MyRunnable();

// Create a new thread and pass the runnable as an argument


Thread t = new Thread(r);

// Start the new thread


[Link]();

The code creates a new thread by implementing the Runnable interface and
passing an object of the class to the Thread constructor. The start()

Java: Module 3 7
method is then called to start the new thread, which will execute the
code in the run() method.
But calling the start() method does not actually cause the code in the
run() method to be executed immediately. Instead, it causes the new

thread to be scheduled for execution as soon as possible. The actual


execution of the thread depends on the scheduling policies of the
operating system and the availability of CPU resources.

States of Thread

[Link]

Thread Life cycle

Java: Module 3 8
The States of a Thread are:

New (new born state)

In this state, Thread object is created but it cannot execute any


program statement because it is not in an execution state of the
thread. Only start() method can be called on a new thread; otherwise,
an IllegalThreadStateException will be thrown.

Runnable

Java: Module 3 9
The second phase of a new-born thread is the execution phase. When the
start() method is called on a the new instance of a thread, it enters
into a runnable [Link] the runnable state, thread is ready for
execution and is waiting for availability of the processor (CPU time).
There are many threads that are ready for execution, they all are
waiting in a queue (line).

If all threads have equal priority, a time slot is assigned for each
thread execution on the basis of first-come, first-serve manner by
CPU. The process of allocating time to threads is known as time
slicing. A thread can come into runnable state from running, waiting,
or new states.

Running

Running means Processor (CPU) has allocated time slot to thread for
its execution. When thread scheduler selects a thread from the
runnable state for execution, it goes into running state. Look at the
above figure.
In running state, processor gives its time to the thread for execution
and executes its run method. It is the state where thread performs its
actual functions. A thread can come into running state only from
runnable state.
A running thread may give up its control in any one of the following
situations and can enter into the blocked state.

Java: Module 3 10
1. When sleep() method is invoked on a thread to sleep for specified
time period, the thread is out of queue during this time period.
The thread again reenters into the runnable state as soon as this
time period is elapsed.

2. When a thread is suspended using suspend() method for some time in

order to satisfy some conditions. A suspended thread can be


revived by using resume() method.

3. When wait() method is called on a thread to wait for some time. The
thread in wait state can be run again using notify() or notifyAll()

method.

Waiting (Blocked)

A thread which is alive but not in runnable or running state will be


in waiting(blocked) state. A thread can be in blocked state because of
suspend(), sleep(), wait() methods or implicitly by JVM to perform I/O
operations.

DEAD(terminated)
A thread reaches the termination state because of the following
reasons:

When a thread has finished its job, then it exists or terminates


normally.

Abnormal termination: It occurs when some unusual events such as an


unhandledException or segmentation fault .

A terminated thread means the thread is no more in the system. In


other words, the thread is dead, and there is no way one can respawn
(active after kill) the dead thread.

Multi-threaded programming

Java: Module 3 11
Multithreaded programming is a programming paradigm in which a single
process is broken up into two or more threads that can be executed
concurrently, in parallel. Each thread represents a separate flow of
control, and each thread can run a different part of the program, or the
same part of the program with different input data. Multithreaded
programming can be used to increase the performance of a program by
taking advantage of multiple processors or cores, or to allow a program
to perform multiple tasks concurrently, such as downloading data from
the internet while also performing calculations. It can also be used to
simplify the design of a program by allowing different parts of the
program to run concurrently and asynchronously.

Example

class WorkerThread extends Thread {


public void run() {
// code to be executed by the worker thread
[Link]("Worker thread running!!!");
}
}

public class Main {


public static void main(String[] args) {
WorkerThread worker = new WorkerThread();
[Link]();
}
}

This program creates a new WorkerThread and starts it when the main method
is called. The method of the WorkerThread class will be executed by the
run

worker thread when it is started. The output of the program will be:

output
Worker thread running!!!

Thread Priorities
In Java, each thread has a priority that determines how much CPU time it
is allocated. Threads with higher priority will be allocated more CPU
time than threads with lower priority. The priority of a thread can be
set using the setPriority

method of the Thread class, and can be any value between MIN_PRIORITY (which
is 1) and MAX_PRIORITY (which is 10). The default priority for a thread is
NORM_PRIORITY ,which is 5.

public class Main {


public static void main(String[] args) {
Thread thread = new Thread(new Runnable() {
public void run(){

Java: Module 3 12
// code to be executed by the worker thread
[Link]("Worker thread running");
}
});
[Link](Thread.MAX_PRIORITY);
[Link]();
}
}

When the program is run, a new thread will be created and the code in
the run method of the Runnable will be executed by the worker thread. The
priority of the thread is set to (10), which means that it
MAX_PRIORITY

will be allocated more CPU time than threads with lower priority.
However, it is important to note that the actual allocation of CPU time
to threads is not guaranteed and can depend on various factors, such as
the operating system and the availability of other resources.

Java: Module 3 13
󾠱
Java: Module 4
Applets
Introduction
A java applet is a small dynamic java program that can be transferred via the internet and
run by a java-compatible web browser.

All applets are sub-classes (either directly or indirectly) of Applet , and they are not stand-
alone programs.

The main difference between java-based applications and applets is that applets are
typically executed in an applet viewer or java-compatible web browser.

Types of Applets

AWT(Abstract Window Toolkit)

AWT (Abstract Window Toolkit) applets are based directly on the Applet class. These
applets use AWT to provide GUI components, such as buttons and text fields. The
AWT applet life cycle is composed of the following methods: init() , start() ,
paint(Graphics g) , stop() , and destroy() . The init() method is the first method to be

called and is used to initialize variables. The start() method is called after init()
and is used to restart an applet after it has been stopped. The paint(Graphics g)
method is called when the applet needs to be redrawn. The stop() method is called
when the applet is stopped and the destroy() method is called when the applet is
unloaded. A skeleton of an AWT applet is given below:

Java: Module 4 1
Directly based on the Applet class.

These applets use AWT to provide GUI.

Swing based

Swing applets are based on the [Link] class. These applets use the
Swing API to provide a more modern user interface. Swing applets have a slightly
different life cycle than AWT applets, with the following methods: init() , start() ,
stop() , destroy() , and paint(Graphics g) . The init() method is the first method to be

called and is used to initialize variables. The start() method is called after init()
and is used to restart an applet after it has been stopped. The stop() method is
called when the applet is stopped and the destroy() method is called when the applet
is unloaded. The paint(Graphics g) method is called when the applet needs to be
redrawn. A skeleton of a Swing applet is given below:

Based on the [Link] class.

These applets use the Swing API to provide a more modern user interface.

Life cycle of an Applet


It is important to understand the order in which the various methods shown in the
skeleton are called.

When an applet begins, the following methods are called, in this sequence:

Java: Module 4 2
: The init( ) method is the first method to be called. This is where you
init()

should initialize variables. This method is called only once during the run time of
your applet.

start(): The start( ) method is called after init( ). It is also called to restart an
applet after it has been stopped. Note that init( ) is called once i.e. when the first
time an applet is loaded whereas start( ) is called each time an applet’s HTML
document is displayed onscreen. So, if a user leaves a web page and comes
back, the applet resumes execution at start( ).

: This method is called when the applet needs to be redrawn.


paint(Graphics g)

The single parameter, g, is a Graphics object that provides the applet with
methods for drawing. This method is called whenever the applet needs to be
repainted, such as when the applet is first loaded and resized

When an applet is terminated, the following sequence of method calls takes


place:

stop(): This method is called when the applet is stopped. It is used to stop the
applet's execution.

: This method is called just before the applet is unloaded. It is used to


destroy()

perform any necessary cleanup tasks, such as releasing resources.

Applet Skeleton

import [Link].*;
import [Link].*;
import [Link].*;

//[Link] is deprecated [Link] is the alternative

import [Link];

public class AppletExample extends JApplet {

public void init() {


// initialization
}

public void start() {


// start or resume execution
}

// called when the applet is stopped


public void stop() {
// suspend execution
}

Java: Module 4 3
// This is the last method executed
public void destroy() {
// called when applet is terminated
// perform shutdown activities
}

public void paint(Graphics g) {


//redisplay the window contents
}
}

How does the java applets works ?


The Java applet works by being transferred to the user's computer via the internet. It
is then run by a Java-compatible web browser. The applet interacts with the user by
responding to user input and performing specific tasks. The applet is able to do this
by utilizing the Java language, which is a high-level programming language. The Java
language allows applets to run faster, with fewer errors, than traditional programming
languages.

When a Java applet is first loaded, the init() method is called. This method is used
to initialize variables and prepare the applet for execution. After the init() method is
called, the start() method is called. This method is used to restart the applet after it
has been stopped.

The paint(Graphics g) method is called when the applet needs to be redrawn. This
method is used to display the contents of the applet on the user's screen. When the
applet is stopped, the stop() method is called. This method is used to stop the
applet's execution. Finally, the destroy() method is called when the applet is
unloaded. This method is used to perform any necessary cleanup tasks, such as
releasing resources.

Java Event Handling


Changing the state of an object is known as an event. For example, click on button,
dragging mouse etc. The [Link] package provides many event classes and
Listener interfaces for event handling.

Event types

Java: Module 4 4
1. Foreground Events
Foreground events are the events that require user interaction to generate, i.e.,
foreground events are generated due to interaction by the user on components in
Graphic User Interface (GUI). Interactions are nothing but clicking on a button,
scrolling the scroll bar, cursor moments, etc.

2. Background Events
Events that don’t require interactions of users to generate are known as
background events. Examples of these events are operating system
failures/interrupts, operation completion, etc.

Event Handling is a mechanism to control the events and to decide what should
happen after an event occur. To handle the events, Java follows the Delegation
Event model.

Delegation Event Model

Java: Module 4 5
Source: Events are generated from the source. There are various sources like
buttons, check-boxes, list, menu-item, choice, scrollbar, text components,
windows, etc., to generate events.

Listeners: Listeners are used for handling the events generated from the
source. Each of these listeners represents interfaces that are responsible for
handling events.

To perform Event Handling, we need to register the source with the listener.

Registering the Source With Listener


Different Classes provide different registration methods.

Syntax:

addTypeListener()

where Type represents the type of event.

Example 1: For KeyEvent we use addKeyListener() to register.

Example 2:that For ActionEvent we use addActionListener() to register.

Event Classes ,interfaces and methods in Java


Event Class Listener Interface Description Methods

An event that
indicates that a
component-
defined action
ActionEvent ActionListener occurred like a actionPerformed()

button click or
selecting an
item from the
menu-item list.
The adjustment
event is emitted
AdjustmentEvent AdjustmentListener by an Adjustable adjustmentValueChanged()

object like
Scrollbar.

Java: Module 4 6
Event Class Listener Interface Description Methods

An event that
indicates that a
component componentResized()
componentShown()
ComponentEvent ComponentListener moved, the size componentMoved()
changed or componentHidden()

changed its
visibility.
When a
component is
added to a
container (or)
componentAdded()
ContainerEvent ContainerListener removed from it, componentRemoved()
then this event
is generated by
a container
object.
These are
focus-related
events, which
focusGained()
FocusEvent FocusListener include focus, focusLost()
focusin,
focusout, and
blur.
An event that
indicates
ItemEvent ItemListener whether an item itemStateChanged()

was selected or
not.
An event that
occurs due to a
keyTyped() keyPressed()
KeyEvent KeyListener sequence of keyReleased()
keypresses on
the keyboard.
The events that
occur due to the mousePressed()
mouseClicked()
user interaction
MouseEvent MouseListener mouseEntered()
with the mouse mouseExited()
mouseReleased()
(Pointing
Device).
mouseMoved()
MouseEvent MouseMotionListener mouseDragged()

Java: Module 4 7
Event Class Listener Interface Description Methods

An event that
specifies that
the mouse
MouseWheelEvent MouseWheelListener mouseWheelMoved()
wheel was
rotated in a
component.
An event that
occurs when an
TextEvent TextListener textChanged()
object’s text
changes.
An event which
windowActivated()
indicates windowDeactivated()
windowOpened()
whether a
WindowEvent WindowListener windowClosed()
window has windowClosing()
windowIconified()
changed its
windowDeiconified()
status or not.

Note: As Interfaces contains abstract methods which need to implemented by


the registered class to handle events.

Flow of Event Handling


1. User Interaction with a component is required to generate an event.

2. The object of the respective event class is created automatically after event
generation, and it holds all information of the event source.

3. The newly created object is passed to the methods of the registered


listener.

4. The method executes and returns the result.

JDBC(Java Data Base Connectivity)


JDBC stands for Java Database Connectivity. JDBC is a Java API to connect and execute the
query with the database. It is a part of JavaSE (Java Standard Edition). JDBC API uses JDBC
drivers to connect with the database.

JDBC Architectural Model


Two-tier Model

Java: Module 4 8
In this model the Java applets and application are directly connected with any type of
database. The client directly communicates with database server through JDBC driver.

Three-tier Model

Java: Module 4 9
In this, there is no direct communication. Requests are sent to the middle tier i.e. HTML
browser sends a request to java application which is then further sent to the database.
Database processes the request and sends the result back to the middle tier which then
communicates with the user. It increases the performance and simplifies the application
deployment.

JDBC Drivers
JDBC Driver is a software component that enables java application to interact with the
database. There are 4 types of JDBC drivers:

JDBC-ODBC bridge driver


ODBC is a standard Microsoft Windows® interface that enables communication between
database management systems and applications typically written in C or C++. JDBC is a
standard interface that enables communication between database management systems
and applications written in Oracle Java.

Java: Module 4 10
ODBC refers to the Open Database connectivity .The JDBC-ODBC bridge driver uses
ODBC driver to connect to the database. The JDBC-ODBC bridge driver converts JDBC
method calls into the ODBC function calls. This is now discouraged because of thin driver.

Advantages:

easy to use.

can be easily connected to any database.

Disadvantages:

Performance degraded because JDBC method call is converted into the ODBC
function calls.

The ODBC driver needs to be installed on the client machine.

Native-API driver (partially java driver)


The Native API driver uses the client-side libraries of the database. The driver converts
JDBC method calls into native calls of the database API. It is not written entirely in java.

Java: Module 4 11
Advantage:

performance upgraded than JDBC-ODBC bridge driver.

Disadvantage:

The Native driver needs to be installed on the each client machine.

The Vendor client library needs to be installed on client machine.

Network Protocol driver (fully java driver)


The Network Protocol driver uses middle-ware (application server) that converts JDBC
calls directly or indirectly into the vendor-specific database protocol. It is fully written in
java.

Java: Module 4 12
Advantage:

No client side library is required because of application server that can perform many
tasks like auditing, load balancing, logging etc.

Disadvantages:

Network support is required on client machine.

Requires database-specific coding to be done in the middle tier.

Maintenance of Network Protocol driver becomes costly because it requires database-


specific coding to be done in the middle tier.

Thin driver (fully java driver)


The thin driver converts JDBC calls directly into the vendor-specific database protocol.
That is why it is known as thin driver. It is fully written in Java language.

Java: Module 4 13
Advantage:

Better performance than all other drivers.

No software is required at client side or server side.

Disadvantage:

Drivers depend on the Database.

Socket Programming Socket class

Java: Module 4 14
Java Socket programming is used for communication between the applications running on
different JRE.

Java Socket programming can be connection-oriented or connection-less.

Socket and ServerSocket classes are used for connection-oriented socket programming and
DatagramSocket and DatagramPacket classes are used for connection-less socket
programming.

The client in socket programming must know two information:

1. IP Address of Server, and

2. Port number.

Here, we are going to make one-way client and server communication. In this application, client
sends a message to the server, server reads the message and prints it. Here, two classes are
being used: Socket and ServerSocket. The Socket class is used to communicate client and
server. Through this class, we can read and write message. The ServerSocket class is used at
server-side. The accept() method of ServerSocket class blocks the console until the client is
connected. After the successful connection of client, it returns the instance of Socket at server-
side.

Java: Module 4 15
Socket class
A socket is simply an endpoint for communications between the machines. The Socket class can
be used to create a socket.

Important methods
Method Description

1) public InputStream getInputStream() returns the InputStream attached with this socket.

2) public OutputStream getOutputStream() returns the OutputStream attached with this socket.

3) public synchronized void close() closes this socket

ServerSocket class
The ServerSocket class can be used to create a server socket. This object is used to establish
communication with the clients.

Java: Module 4 16
Important methods
Method Description

returns the socket and establish a connection between server and


1) public Socket accept()
client.

2) public synchronized void


closes the server socket.
close()

Example of Java Socket Programming


Creating Server:

To create the server application, we need to create the instance of ServerSocket class. Here, we
are using 6666 port number for the communication between the client and server. You may also
choose any other port number. The accept() method waits for the client. If clients connects with
the given port number, it returns an instance of Socket.

ServerSocket ss=new ServerSocket(6666);


Socket s=[Link]();//establishes connection and waits for the client

eg: a simple of Java socket programming where client sends a text and server receives
and prints it.

//[Link]

import [Link].*;
import [Link].*;
public class MyServer {
public static void main(String[] args){
try{
ServerSocket ss=new ServerSocket(6666);
Socket s=[Link]();//establishes connection
DataInputStream dis=new DataInputStream([Link]());
String str=(String)[Link]();
[Link]("message= "+str);
[Link]();
}catch(Exception e){[Link](e);}
}
}

//[Link]

import [Link].*;
import [Link].*;

Java: Module 4 17
public class MyClient {
public static void main(String[] args) {
try{
Socket s=new Socket("localhost",6666);
DataOutputStream dout=new DataOutputStream([Link]());
[Link]("Hello Server");
[Link]();
[Link]();
[Link]();
}catch(Exception e){[Link](e);}
}
}

After running the command the output will be;

Java: Module 4 18

You might also like