Java Full Notion Notes
Java Full Notion Notes
Java: Module 1
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.
Class
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
For example: to convince the customer differently, to draw something, for example, shape,
triangle, rectangle, etc.
Abstraction
Hiding internal details and showing functionality is known as abstraction. For example
phone call, we don't know the internal processing.
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.
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
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
Robust
Multithread
With Java's multithreaded feature, it is possible to write programs that can do many tasks
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
Distributed
Java: Module 1 5
Java is designed for the distributed environment of the internet
Dynamic
evolving environment. Java programs can carry extensive amount of run-time information
that can be
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.
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
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.
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.
[Link]
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.
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.
Loading
[Link]("Java");
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
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
Execution Engine
This is the actual engine that converts the bytecode to machine code and executes the
instructions.
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
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
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.
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 */.
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.
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.
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:
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.
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
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.
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,
• 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.
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 = '\n';
[Link](ch);
[Link](b);
[Link](c);
Boolean Literal
Java: Module 1 18
Only two values are allowed for Boolean literals, i.e., true and false.
boolean b = true;
[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: Module 1 19
{
String s = "Hello";
[Link](s);
[Link](s1);
}
}
Java: Module 1 20
Default value: false .
class Main {
public static void main(String[] args) {
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) {
5. long type
6. double type
The double data type is a double-precision 64-bit floating-point.
class Main {
public static void main(String[] args) {
Java: Module 1 22
7. float type
The float data type is a single-precision 32-bit floating-point.(numbers having
decimal points).
class Main {
public static void main(String[] args) {
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' .
class Main {
public static void main(String[] args) {
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.
Types of Variables
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.
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.
Static Variable
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.
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.:
negating an expression
Unary Plus
+(operand)
Unary Minus
-(operand)
Increment Operator
++operand
Java: Module 1 26
Example:
Suppose x=9
y = ++x
then , y =10 and x =10
operand++
Example:
Suppose x=9
y = x++
then , y =9 and x =10
Decrement Operator
--operand
y = - -x then,
y =9 and x =9
operand--
Java: Module 1 27
Example: Suppose x=9
y = x- - then,
y =8 and x =9
!(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:
2. Subtraction(-): This operator is a binary operator and is used to subtract two operands.
Syntax:
num1 - num2
Example:
Syntax:
num1 * num2
Java: Module 1 29
Example:
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:
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:
Java: Module 1 30
Example
Consider x =5.
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.
Java: Module 1 31
Assume that the statement is as follows:
x>>4, let y be 4
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
var1 == var2
Illustration:
var1 = 20
var2 = 20
var1 == var2 results in true
Syntax:
var1 != var2
Illustration:
var1 = 12
var2 = 20
Syntax:
Java: Module 1 33
var1 > var2
Illustration:
var1 = 30
var2 = 20
Syntax:
Illustration:
var1 = 10
var2 = 20
Syntax:
Illustration:
var1 = 20
var2 = 20
var3 = 10
Java: Module 1 34
var1 >= var2 results in true
var2 >= var3 results in true
Syntax:
Illustration:
var1 = 10
var2 = 10
var3 = 9
[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:
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:
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)
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:
~ 0101
________
1010 = 10 (In decimal)
// 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);
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 ,
&& Logical and Returns true if both statements are true x < 5 && x < 10
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:
if(Expression1)
{
variable = Expression2;
}
else
{
variable = Expression3;
}
Assignment Operator.
Assignment operators are used in Java to assign values to variables
+= 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
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
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
Syntax:
if (condition)
{
Java: Module 1 41
// Executes this block if
// condition is true
}
else
{
// Executes this block if
// condition is false
}
Example
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
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
Syntax:
if (condition1)
{
// Executes when condition1 is true
if (condition2)
{
// Executes when condition2 is true
}
}
Example
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
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
class Main {
public static void main(String[] args) {
case 29:
size = "Small";
break;
case 42:
size = "Medium";
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 :
Syntax:
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.
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
import [Link].*;
class GFG {
public static void main (String[] args) {
for (int i=0;i<=10;i++)
{
[Link](i);
}
}
}
Syntax :
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
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
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
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.
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
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.
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.
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
.
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
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:
OR
Array Literal
In a situation where the size of the array and variables of the array are already known,
array literals can be used.
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.
Example
class GFG {
public static void main(String[] args)
{
// declares an Array of integers.
int[] arr;
// so on...
arr[2] = 30;
arr[3] = 40;
arr[4] = 50;
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
2. Class is not a real world entity. It is just a template or blueprint or prototype from which
objects are created.
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.
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.
Syntax:
Example
void barking() {
int local_var;//Local variable
}
void hungry() {
}
void sleeping() {
}
}
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
:
3. Identity: It gives a unique name to an object and enables one object to interact with
other objects.
Syntax
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.
int age;
//This is a constructor
public Dog(int k) {
age = k;
}
void DogAge() {
[Link]("Age 0f Dog = " + age);
}
// 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.
int age;
//This is a constructor
public Dog(int k) {
age = k;
}
void DogAge() {
[Link]("Age 0f Dog = " + age);
}
// Instatiating An object
Dog d = new Dog(5);
[Link]();
}
.
Rules for creating Java constructor
There are two rules defined for the constructor.
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
Example
import [Link].*;
class GFG {
GFG() { [Link]("Default constructor"); }
public static void main(String[] args)
{
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.
import [Link].*;
class Computer {
int num;
String name;
class main_class {
public static void main(String[] args)
{
// this would invoke default constructor.
Computer g = new Computer();
Output
Constructor called
null
0
Parameterized Constructor
A constructor which has a specific number of parameters is called a parameterized
constructor.
Java: Module 1 66
void display(){[Link](id+" "+name);}
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.
// 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 {
// Class 1
Java: Module 1 68
// Helper class
class Product {
int prod1 = a * b * c;
return prod1;
}
double prod2 = a * b * c;
return prod2;
}
}
class GFG {
public static void main(String[] args)
{
// 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 {
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:
Creating Sub-classes
//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
}
}
Single Inheritance
When a class inherits another class, it is known as a single inheritance.
class Animal{
void eat(){
[Link]("eating...");
}
}
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");
}
}
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.
output
parentNum * childNum1 = 10
parentNum * childNum2 = 20
parentNum * childNum3 = 30
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.");
}
}
java : Module 2 5
public void displayInfo() {
//Here the oveririding occurs
[Link]("I am a dog.");
}
}
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 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:
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
output
Here the compiler stated that we cant override the methods with Final keyword.
java : Module 2 8
packages
[Link]
built-in packages
user-defined 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.
Java package is used to categorize the classes and interfaces so that they can be easily maintained.
Accessing packages
There are three ways to access the package from outside the package.
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
Importing the Above mentioned package ‘pack’ into another java program.
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");}
}
package mypack;
import pack.A;
class B{
public static void main(String args[]){
A obj = new A();
[Link]();
}
}
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.
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.
2. protected means “only visible within the enclosing class and any subclasses”
Example
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
[Link]();
}
}
Output
Compile Time error
Protected
The methods or data members declared as protected are accessible within the same
package or subclasses in different packages.
Example
// 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 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
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.
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:
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>{
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:
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:
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:
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.
java : Module 2 16
Reading and writing files
Filtering Data
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.
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
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(byte[] array) - reads bytes from the stream and stores in the specified array
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
import [Link];
import [Link];
class Main {
public static void main(String args[]) {
java : Module 2 18
}
}
Output
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
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
import [Link];
import [Link];
}
}
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.
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];
}
}
}
/*This code will output 'File not Found' if in case the [Link] is
in the destination*/
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:
syntax
finally{
}
Example
import [Link].*;
class GFG {
public static void main(String[] args)
{
try {
[Link]("Inside try block");
[Link](
"catch : exception not handled.");
}
// Always execute
finally {
[Link](
"finally : i will execute always.");
}
// This will not execute
[Link]("i want to run");
}
}
ouput
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.
Syntax
Example
import [Link];
import [Link];
}
}
Java: Module 3 4
}
else {
[Link]("Access granted - You are old enough!");
}
}
x = -1;
assert x > 0 : "x is not positive"; // This assertion will fail and throw an AssertionError
[Link]("This line will not be reached");
}
}
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.
custom exception type that can be thrown and caught in your program.
Java: Module 3 5
Threads
What is a Thread?
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
Java: Module 3 6
Th create a new thread, you program will either extend Thread or
implement the Runnable interface.
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()
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.
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
States of Thread
[Link]
Java: Module 3 8
The States of a Thread are:
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.
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)
DEAD(terminated)
A thread reaches the termination state because of the following
reasons:
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
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.
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) 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.
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:
These applets use the Swing API to provide a more modern user interface.
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( ).
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
stop(): This method is called when the applet is stopped. It is used to stop the
applet's execution.
Applet Skeleton
import [Link].*;
import [Link].*;
import [Link].*;
import [Link];
Java: Module 4 3
// This is the last method executed
public void destroy() {
// called when applet is terminated
// perform shutdown activities
}
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.
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.
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.
Syntax:
addTypeListener()
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.
2. The object of the respective event class is created automatically after event
generation, and it holds all information of the event source.
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:
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.
Disadvantages:
Performance degraded because JDBC method call is converted into the ODBC
function calls.
Java: Module 4 11
Advantage:
Disadvantage:
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:
Java: Module 4 13
Advantage:
Disadvantage:
Java: Module 4 14
Java Socket programming is used for communication between the applications running on
different JRE.
Socket and ServerSocket classes are used for connection-oriented socket programming and
DatagramSocket and DatagramPacket classes are used for connection-less socket
programming.
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.
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
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.
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);}
}
}
Java: Module 4 18