JAVA
PROGRAMMING
THE BOOK FOR BEGINNERS!
WITH HANDS-ON EXCERISES
ARCHIES GURAV
JAVA
PROGRAMMING
THE BOOK FOR BEGINNERS!
ARCHIES GURAV
"It is not the language that makes
programs appear simple. It is the
programmer that make the language
appear simple!"
~ Robert C Martin
CONTENTS
INTRODUCTION..................................................................................1
HISTORY OF JAVA............................................................................2
FEATURES OF JAVA........................................................................3
SETTING UP THE DEVELOPMENT ENVIRONMENT.....4
FIRST JAVA PROGRAM.................................................................8
BEHIND THE SCENES OF JAVA CODE................................10
COMMENTS, DATA TYPES, VARIABLES AND
CONSTANTS.......................................................................................11
SCOPE AND LIFETIME OF VARIABLES...............................18
OPERATORS AND EXPRESSIONS.........................................19
TYPE CONVERSION, TYPE CASTING, COMMAND
LINE ARGUMENTS AND ENUMS............................................31
CONDITIONAL STATEMENTS.................................................35
LOOPS...................................................................................................39
CONTINUE AND BREAK STATEMENTS........................... 43
USING SCANNER CLASS............................................................46
TYPES OF FUNCTIONS...............................................................47
GARBAGE COLLECTION.............................................................51
STRINGS IN JAVA...........................................................................52
STRINGBUILDER AND STRINGBUFFER ..........................58
ARRAYS AND 2D ARRAYS........................................................61
ACCESS SPECIFIERS.....................................................................64
OOP CONCEPTS..............................................................................66
ARCHIES GURAV
CONTENTS
JAVA 8 FEATURES........................................................................79
INNER CLASSES..............................................................................86
PACKAGES.........................................................................................90
MULTI-THREADING IN JAVA................................................94
COLLECTIONS FRAMEWORK................................................98
JAVA GENERICS............................................................................102
EXCEPTION HANDLING...........................................................107
I/O AND FILE HANDLING..........................................................111
CONNECTING TO DATABASE (JDBC)................................121
GUI PROGRAMMING IN JAVA...............................................125
JAVA PROJECTS...........................................................................134
ARCHIES GURAV
INTRODUCTION
"Java Programming: The Book for Beginners" is the
perfect guide for those who are just starting out on
their programming journey.
This comprehensive e-book covers the fundamentals
of Java programming, helping you to gain a solid
understanding of the concepts and techniques you
need to know to be successful.
With clear explanations, practical examples, and
hands-on exercises, this e-book is the ideal resource
for anyone looking to learn Java programming.
Whether you're a complete newcomer to programming
or looking to build on your existing KNOWLEDGE, "Java
Programming: The Book for Beginners" is the perfect
place to start."
INTRODUCTION • 1
ARCHIES GURAV
HISTORY OF JAVA
The history of java starts from Green Team, java team
members (also known as Green Team), had a goal of
creating a language for digital devices such as
television and set-up boxes, etc.
James Gosling, Mike Sheridan, and Patrick Naughton
initiated the language project in June 1991. The small
team of sun engineers called Green Team.
Firstly, it was called "Green Talk" by James Gosling and
file extension was `.gt`.
After that, it was called "Oak" and was developed as a
part of the Green project.
It was officially released in 1995, and quickly gained
popularity due to its "write once, run anywhere"
capability and its robust library of pre-written code.
Currently, Java is used in Internet Programming, mobile
devices, games, e-business solutions, etc.
HISTORY OF JAVA • 2
ARCHIES GURAV
FEATURES OF JAVA
There are many features of Java. They are also known
as java buzzwords. The Features of Java are simple and
easy to understand.
1. Object-Oriented
2. Portable
3. Platform Independent
4. Secured
5. Robust
6. Architecture Neutral
7. Interpreted
8. Dynamic
9. High Performance
10. Multithreaded
Platform
Portable Independent
Object-Oriented Secured
Multithreaded Features of Java Robust
High Architectural
Performance Neutral
Dynamic Interpreted
FEATURES OF JAVA • 3
ARCHIES GURAV
SETTING UP THE
DEVELOPMENT ENVIRONMENT
- Installation Instructions for Windows
Download the JDK Installer
- Access Java SE and Click the link that corresponds
to `.exe` for your version of Windows.
- Download the `jdk-17_windows-x64_bin.exe` file.
Run the JDK Installer
- Start the JDK 17 installer by double-clicking the
installer's icon or file name in the download location.
- Follow the instructions provided by the
Installation wizard.
Setting the PATH Environment Variable
- Steps to set the PATH variable are:
1. To set the PATH variable permanently, add the full
path of the `jdk-17/bin` directory to the PATH variable.
The Full Path is `C:\Program Files\Java\jdk-17\bin`.
2. To set the PATH on Windows:
2.1. Select Control Panel and then System.
2.2. Click Advanced and then Environment Variables.
2.3. Add the location of the `bin` folder of the JDK to
the PATH variable in the System Variables.
SETTING UP THE DEVELOPMENT ENVIRONMENT • 4
ARCHIES GURAV
- Installation Instructions for Mac OS
Download the JDK Installer
- Download the JDK `.dmg` file, `jdk-17_macos-
x64_bin.dmg` from the Oracle Website.
Run the JDK Installer
- From either the browser Downloads window or
from the file browser, double-click the `.dmg` file to
start it.
- A Finder window appears that contains an icon of
an open box and the name of the `.pkg` file.
- Double-click the JDK 17 `.pkg` icon to start the
installation application.
- The installation application displays the
Introduction window.
- A window appears that displays the message:
`Installer is trying to install new software.` Enter your
password to allow this.
- Enter the Administrator username and password
and click Install Software.
- The software is installed, and a confirmation
window is displayed.
SETTING UP THE DEVELOPMENT ENVIRONMENT • 5
ARCHIES GURAV
- Installation Instructions for Linux
In this, there are two types of Instructions for
installing the JDK on Linux System.
1. Installing the 64-Bit JDK 17 on Linux Platforms
Download the 64-Bit JDK
- Download the file `jdk-17_linux-x64_bin.tar.gz`
from the Oracle Website.
- Anyone (not only by root users) can install the
archive binary in any location having write access.
installing the JDK Installer
- Change the directory to the location where you
want to install the JDK, then move the `.tar.gz` archive
binary to the current directory.
- Unpack the tarball and install the JDK
`tar zxvf jdk-17_linux-x64_bin.tar.gz`
- The Java Development Kit files are installed in a
directory called `jdk-17`.
- Delete the `.tar.gz` file if you want to save disk
space.
SETTING UP THE DEVELOPMENT ENVIRONMENT • 6
ARCHIES GURAV
2. Installing the 64-Bit JDK on RPM-Based Linux
Platforms
Download the 64-Bit JDK on an RPM based Linux
Platform
- Download the file, `jdk-17_linux-x64_bin.rpm`.
- In RPM based platform ensure that you have a root
user access by running the command `su` and entering
the superuser password.
installing the JDK Installer
- Install the package using the following command:
`$ rpm -ivh jdk-17_linux-x64_bin.rpm`
- Upgrade the package using the following
command:
`$ rpm -Uvh jdk-17_linux-x64_bin.rpm`
- Delete the .rpm file if you want to save disk space.
- Exit the root shell. Reboot is not required.
After completing installations of JDK. To verify the
installation of the JDK open the terminal and run the
following command `java --version`. This should
display the version of the JDK you have installed in the
system.
SETTING UP THE DEVELOPMENT ENVIRONMENT • 7
ARCHIES GURAV
FIRST JAVA PROGRAM
Here is our First Java Program
- Let's deep dive into our First Program.
- `public class App`: This is a class named as App which
is a blueprint for creating objects. The `public` keyword
makes the class accessible from anywhere in the code.
- `public static void main(String[] args)`: This is the
main method of the Java Program .
- The `public` and `static` keywords are used to
specify that the method can be called without using
the instance of the class.
FIRST JAVA PROGRAM• 8
ARCHIES GURAV
- The `void` keyword means that the method doesn't
returns a value.
- The `main` method is where the program starts
execution.
- The `args` parameter is an array of `String` objects
that can be passed to program when executed.
- 'System.out.println("Hello,World!");`: This line outputs
the text "Hello, World!" to the console.
- The `System.out.println` method is used to print the
text to the console.
- The `println` method automatically adds a newline
character at the end of the text.
- After this explanation of first program in Java. In the
next chapter we will learn about "Behind the Scenes of
this Java Code".
FIRST JAVA PROGRAM• 9
ARCHIES GURAV
BEHIND THE SCENES OF JAVA CODE
SOURCE JAVA BYTE
CODE COMPILER CODE
OS JVM
- The Java source code is compiled into bytecode
using the Java compiler (javac). The bytecode is a
platform-independent format that can be executed by
the Java Virtual Machine (JVM) on any device.
- The bytecode is loaded into the JVM, which verifies it
to ensure it follows the rules of the Java language.
- The JVM executes the bytecode by translating it into
machine-specific instructions and executing them.
- The program produces output and terminates when
it has completed execution or when it encounters an
error.
- The JVM handles any errors and exceptions that
occur during the execution of the program.
- In short, the Java source code is compiled into
bytecode, which is executed by the JVM to produce
output. The JVM provides a runtime environment for
executing the program and handling errors and
exceptions.
BEHIND THE SCENES OF JAVA CODE• 10
ARCHIES GURAV
COMMENTS, DATA TYPES,
VARIABLES AND CONSTANTS
Java Comments
- The java comments are statements that are not
executed by the compiler and interpreter. The
comments can be used to provide information or
explanation about the variable, method, class or any
statement. It can also be used to hide program code for
specific time.
Types of Java Comments
- There are 3 types of comments in Java.
1. Java Single Line Comment
- The Single Line Comment is used to comment
only one line.
- Syntax:
//This is a Single Line Comment
COMMENTS, DATA TYPES, VARIABLES AND CONSTANTS• 11
ARCHIES GURAV
2. Java Multi-Line Comment
- The Multi-Line Comment is used to comment
multiple lines of code.
- Syntax:
/*
This is a multi-line comment.
*/
3. Java Documentation Comment
- The Documentation Comment is used to create
documentation API. To create documentation API, you
need to use Javadoc tool.
- Syntax:
/**
This is a documentation comment.
*/
COMMENTS, DATA TYPES, VARIABLES AND CONSTANTS• 12
ARCHIES GURAV
- Compile the code using `javac` tool:
Command: `javac App.java`
- Create Documentation API by 'javadoc` tool
Command: `javadoc App.java`
- Now, there will be HTML files created for your App
class in the current directory.
- Opening the files, you will see the explanation of App
class provided through documentation comment.
COMMENTS, DATA TYPES, VARIABLES AND CONSTANTS• 13
ARCHIES GURAV
Data Types:
- Data Types represent the different values to be
stored in the variable.
- In Java, there are two types of data types:
Primitive Data Types
Non-Primitive Data Types
DATA TYPE
PRIMITIVE NON-PRIMITIVE
STRING
BOOLEAN NUMERIC ARRAY, ETC
CHARACTER INTEGRAL
INTEGER FLOATING-POINT
boolean char float double
byte short int long
COMMENTS, DATA TYPES, VARIABLES AND CONSTANTS• 14
ARCHIES GURAV
Size(Bits
Data Type Range
)
`byte` 8 -128 to 127
`short` 16 -32768 to 32767
`int` 32 -2147483648 to 2147483647
-9223372036854775808 to
`long` 64
9223372036854775807
`float` 32 Approx. ±3.40282347 x 10^38
`double` 64 Approx. ±1.7976931348623157 x 10^308
`char` 16 0 to 65535
Not
`boolean` `true` or `false`
Specifed
Variables in Java:
- A variable in Java is a named storage location in
memory that holds a value.
- Here, there are 3 types of variables in java:
Local Variable:
- A variable which is declared inside the method
is called local variable.
Instance Variable:
- A variable which is declared inside the class but
outside a method is called as Instance variable.
Static Variable:
- A variable that is declared as static using
`static` keyword is called a static variable.
COMMENTS, DATA TYPES, VARIABLES AND CONSTANTS• 15
ARCHIES GURAV
- A Small example to understand the types of variables
Constants in Java
- A constant in Java is a variable whose value cannot
be changed once it has been assigned. It uses `final`
keyword.
- A Small example to understand the constants in
Java:
COMMENTS, DATA TYPES, VARIABLES AND CONSTANTS• 16
ARCHIES GURAV
HANDS-ON ASSIGNMENTS
ON THIS TOPIC:
1. Write a program in Java that declares and
initializes a constant of type float and prints its value
to the console.
2. Write a program in Java that declares and
initializes three variables of different data types (e.g.
int, double, boolean), and prints their values to the
console.
3. Write a program in Java that declares and
initializes two variables of type char, concatenates
them and prints the result to the console.
4. Write a program in Java that declares and
initializes all types of data types, and print their
values to the console.
5. Write a program in Java to write a documentation
comment in your code and using the Javadoc tool
examine the output that comes out of it.
COMMENTS, DATA TYPES, VARIABLES AND CONSTANTS• 17
ARCHIES GURAV
SCOPE AND LIFETIME
OF VARIABLES
- In Java, the scope of a variable refers to the part of
the program where the variable can be accessed or
used, and lifetime of a variable refers to the duration of
time during which a variable exists in memory.
Local Variables:
- These are declared within a method and have a
scope limited to that method. The lifetime of local
variables is limited to the duration of the method call.
Instance Variables:
- These are declared outside of any method and are
part of an object. They have a scope throughout the
entire program. The lifetime of instance variables is as
long as the object that they belong to exists.
Static Variables:
- These are declared with the static keyword and are
associated with the class rather than with individual
objects. They have a scope throughout the entire
program. The lifetime of class/static variables is as long
as the program runs.
SCOPE AND LIFETIME OF VARIABLES• 18
ARCHIES GURAV
OPERATORS AND EXPRESSIONS
Operators:
- Operator is a symbol that is used to perform
operations.
- There are many types of operators in Java:
Unary Operator
- The operator that can be used to perform
operations on a single operand is called Unary
Operator.
1. Unary Minus (`-`): Negates the value of the
operand.
2. Unary Plus (`+`): Does not changes the value of
the operand.
3. Logical Negation (`!`): Reverses the value of a
boolean operand.
OPERATORS AND EXPRESSIONS• 19
ARCHIES GURAV
4. Increment (`++`): Increments the value of the
operand by 1.
5. Decrement (`--`): Decrements the value of the
operand by 1.
- Post/Pre Increment/Decrements.
- Pre-Increment/Decrement: The operator is
placed before the operand. The value of the operand is
incremented (or decremented) before its value is used
in the expression. Example: `++x`, `--x`
- Post-Increment/Decrement: The operator is
placed after the operand. The value of the operand is
used in the expression, and then incremented (or
decremented) afterwards. Example: `x++`, `x--`
OPERATORS AND EXPRESSIONS• 20
ARCHIES GURAV
Arithmetic Operator
- The operator that can be used to perform
mathematical operations is called Arithmetic Operator.
1. Addition (`+`): Adds two operands
2. Subtraction (`-`): Subtracts the second
operand from the first
3. Multiplication (`*`): Multiplies two operands.
4. Division (`/`): Divides the first operand by the
second.
OPERATORS AND EXPRESSIONS• 21
ARCHIES GURAV
5. Modulus (`%`): Returns the remainder of
dividing the first operand by the second operand.
Shift Operator
- The shift operators are used to shift the bits of
a binary representation of an integer value to the left
or right..
1. Left Shift (`<<`): Shifts the bits of the first
operand to the left by the number of positions
specified by the second operand.
2. Right Shift (`>>`): Shifts the bits of the first
operand to the right by the number of positions
specified by the second operand.
OPERATORS AND EXPRESSIONS• 22
ARCHIES GURAV
3. Unsigned Right Shift(`>>>`): Shifts the bits of
the first operand to the right by the number of
positions specified by the second operand, while
shifting in zeros on the left.
Relational Operator
- Relational operators are used to compare two
values and determine the relationship between them.
1. Equal to (`==`): Returns `true` if the values of
the operands are equal, and `false` otherwise.
2. Not Equal To (`!=`): Returns `true` if the values
of the operands are not equal, and `false` otherwise.
OPERATORS AND EXPRESSIONS• 23
ARCHIES GURAV
3. Less Than(`<`): Returns `true` if the value of the
first operand is less than the value of the second
operand, and `false` otherwise.
4. Less than or equal to (`>=`): Returns `true` if
the value of the first operand is less than or equal to
the value of the second operand, and `false` otherwise.
5. Greater than (`>`): Returns `true` if the value of
the first operand is greater than the value of the
second operand, and `false` otherwise
6. Greater than Equal To (`>=`): Returns true if the
value of the first operand is greater than or equal to
the value of the second operand, and false otherwise.
OPERATORS AND EXPRESSIONS• 24
ARCHIES GURAV
Logical Operators
- Logical operators are used to perform logical
operations on boolean values.
1. Logical AND (` `): Returns `true` if both
operands are `true`, and `false` otherwise.
A B A && B
true true true
true false false
false true false
false false false
2. Logical OR (` ||`): Returns `true` if either of the
operands is `true`, and `false` otherwise.
OPERATORS AND EXPRESSIONS• 25
ARCHIES GURAV
A B A || B
true true true
true false true
false true false
false false false
3. Logical NOT (` !`): Returns the opposite of the
operand.
A !A
true false
false true
Bitwise Operator
- Bitwise operators are used to perform bit-
level operations on integer values.
1. Bitwise AND(` `): Performs a bit-level AND
operation on two operands. The result is 1 if both
corresponding bits are 1, and 0 otherwise.
OPERATORS AND EXPRESSIONS• 26
ARCHIES GURAV
2. Bitwise OR (` |`): Performs a bit-level OR
operation on two operands. The result is 1 if either of
the corresponding bits is 1, and 0 otherwise.
3. Biwise NOT(`~`): Performs a bit-level NOT
operation on the operand. It inverts all the bits of the
operand, so that 0 becomes 1 and 1 becomes 0.
4. Bitwise XOR (`^`): Performs a bit-level XOR
operation on two operands. The result is `1` if exactly
one of the corresponding bits is `1`.
OPERATORS AND EXPRESSIONS• 27
ARCHIES GURAV
Ternary Operator(Conditional)
- The ternary operator is a shorthand for an if-
else statement.
Syntax:
condition ? expression1 : expression2
Example:
Assignment Operator
- The assignment operator `=` is used to assign
a value to a variable.
- For Example:
int x = 10;
- Java also supports compound assignment
operators that allow you to perform an operation and
assign the result in one step.
- These compound assignment operators are
shorthand for their equivalent operations and can
make the code more concise.
OPERATORS AND EXPRESSIONS• 28
ARCHIES GURAV
Expressions in Java
- In Java, an expression is a combination of values,
variables, and operators that can be evaluated to
produce a single value. Expressions are used to
perform operations, assign values to variables, and
control the flow of execution in a program.
- Here are some examples of expressions in Java:
10 + 20
x+y
x<y
- Expressions can be combined to create more
complex expressions, and they can be used in a variety
of contexts, such as in conditional statements, loop
conditions, and function calls. The order in which
operations are performed in an expression is
determined by the rules of operator precedence, and
parentheses can be used to explicitly control the order
of evaluation.
OPERATORS AND EXPRESSIONS• 29
ARCHIES GURAV
HANDS-ON ASSIGNMENTS
ON THIS TOPIC:
1. Create a Console based Calculator in java which
adds, subtracts, multiplies, divides, and finds
remainder and print the result on the console.
2. Write a Java program to determine if a number is
even or odd using ternary operator.
.
3. Write a Java program to determine if a number is
positive, negative, or zero using conditional
operator.
4. Write a Java program to find the average of 3
numbers and print the average on the console.
5. Write a Java program to swap the values of two
variables.
6. Write a Java program to find the maximum of
three numbers.
7. Write a Java program to find the bitwise AND,OR
and NOT of two numbers.
OPERATORS AND EXPRESSIONS• 30
ARCHIES GURAV
TYPE CONVERSION, TYPE
CASTING, COMMAND LINE
ARGUMENTS AND ENUMS
TYPE CONVERSION AND TYPE CASTING
Widening or Automatic Type Conversion
- Widening Conversion takes place when two
data types are automatically converted. This happens
when:
The 2 data types are compatible
When we assign value of smaller data type
to a bigger data type.
Byte -> Short -> Int -> Long -> Float -> Double
Narrowing or Explicit Conversion
- If we want to assign value of a larger data type
to a smaller data type we perform explicit type casting
or narrowing.
This is useful for incompatible data types
where automatic conversion cannot be
done.
Here, target-type specifies the desired
type to convert the specified value to.
Double -> Float -> Long -> Int -> Short -> Byte
TYPE CONVERSION, TYPE CASTING, COMMAND LINE ARGUMENTS AND ENUMS • 31
ARCHIES GURAV
COMMAND LINE ARGUMENTS(CLA)
- The concept of passing arguments to the main
method in Java is called "command line arguments."
Command line arguments are a way to pass additional
information to a Java program when it is executed.
These arguments are passed to the main method as an
array of strings, and they can be used to control the
behavior of the program or to specify data for the
program to operate on.
- Here's an example of a main method that takes
command line arguments:
- And here's an example of how you could call the
program with command line arguments:
- In this example, the `args` array in the main
method would contain the value `"archies"`.
TYPE CONVERSION, TYPE CASTING, COMMAND LINE ARGUMENTS AND ENUMS • 32
ARCHIES GURAV
ENUMS IN JAVA
- Enums in Java are a special type of class that
represent a fixed set of constant values. Enums are
used to define a set of named constants, and they
provide a convenient way to represent and work with
sets of related values.
- It is available from JDK 1.5.
- The Java Enums are static and final implicitly.
- Here is an example of an Enum definition:
- In this example, the enum `Season` defines a set of
constant values for the season in a year. The values of
an enum are instances of the enum type, and they are
created automatically when the enum is defined.
- Here's an example of how an enum might be used in
a for-each loop:
TYPE CONVERSION, TYPE CASTING, COMMAND LINE ARGUMENTS AND ENUMS • 33
ARCHIES GURAV
HANDS-ON ASSIGNMENTS
ON THIS TOPIC:
1. Write a program that takes a temperature in
Fahrenheit as a command line argument, converts it
to Celsius, and prints the result.
2. Write a program that takes two integer command
line arguments, converts them to double values, and
performs division, printing the result.
.
3. Write a Java program to determine if a number is
positive, negative, or zero using conditional
operator.
4. Write an enum type to represent the days of the
week and write a program that takes a day of the
week as a command line argument and prints the
next day of the week.
5. Write a program that takes two float command
line arguments, casts them to integers, adds them
together, converts the result back to a float, and
prints the result.
TYPE CONVERSION, TYPE CASTING, COMMAND LINE ARGUMENTS AND ENUMS • 34
ARCHIES GURAV
CONDITIONAL STATEMENTS
- Conditional statements in Java allow you to execute
certain parts of your code based on the result of a
boolean expression. The most commonly used
conditional statements in Java are the `if` statement,
`if-else` statement, and the `switch` statement.
If Statement:
- The if statement in Java is used to execute a
block of code if a specific condition is met.
- Syntax:
if(condition){
//code to be executed
}
- Here is an example of an if statement in Java:
- In this example, the condition x > 5 is evaluated, and if
it is true, the message "x is greater than 5" will be
printed.
CONDITIONAL STATEMENTS • 35
ARCHIES GURAV
If-else Statement:
- The if-else statement in Java is a type of
conditional statement that allows you to execute
different sections of code based on the result of a
boolean expression.
- Syntax:
if(condition){
//code to be executed if condition is true
}else {
// code to be executed if condition is false
}
- Here is an example of an if-else statement in
Java:
- In this example, the condition x > 5 is evaluated, and if
it is true, the message "x is greater than 5" will be
printed, otherwise if the condition x > 5 is false, the
message "x is not smaller than 5" will be printed.
CONDITIONAL STATEMENTS • 36
ARCHIES GURAV
Switch Statement:
- A switch statement in Java is a type of
conditional statement that allows you to execute
different blocks of code based on the value of an
expression. The switch statement is useful when you
have a limited number of possible values for a variable,
and you want to perform different actions based on
the value of that variable.
- Here is an example of a switch statement in
Java:
- In this example, the value of x is 3, so the message
"The value of x is 3" is printed. The break statement is
used to exit the switch statement after a match is
found, and the default case is used to handle values
that do not match any of the case labels.
CONDITIONAL STATEMENTS • 37
ARCHIES GURAV
HANDS-ON ASSIGNMENTS
ON THIS TOPIC:
1. Write a program to find the grade of a student
based on their marks using a switch statement.
2. Write a program to check if a character is a vowel
or not.
.
3. Write a program to find the largest of three
numbers using an if-else statement.
4. Write a program to check if a year is a leap year or
not.
5. Write a program that inputs a number and prints
the number of digits in the number.
6. Write a program that inputs a day of the week and
prints the corresponding day of the week.
CONDITIONAL OPERATORS • 38
ARCHIES GURAV
LOOPS
- In Java, loops are used to repeat a block of code for a
specified number of times or until a certain condition is
met.
For Loop:
- A `for` loop is used when you know the number
of times you want to repeat the loop, and it consists of
a loop header, loop body, and an optional update
clause. The loop header specifies the initialization,
condition, and update. The loop body contains the
statements that are executed repeatedly until the
condition is met
- Syntax:
for (initialization; condition; increment/decrement) {
// code to be executed
}
- Example:
- In this example, for loop is printing the numbers from
1 to 5 on the console. The loop terminates when the
condition `i <= 5` is false.
LOOPS • 39
ARCHIES GURAV
While Loop:
- A `while` loop is used when you don't know the
number of times you want to repeat the loop and you
want to keep looping as long as a certain condition is
true. The loop header specifies the condition, and the
loop body contains the statements that are executed
repeatedly until the condition is false.
- Syntax:
while(condition) {
// code to be executed
}
- Example:
- In this example, while loop is printing the numbers
from 1 to 5 on the console. The loop terminates when
the condition `i <= 5` is false.
LOOPS • 40
ARCHIES GURAV
Do-While Loop:
- The `do-while` loop in Java is similar to a while
loop, but the loop body is always executed at least
once, before the condition is evaluated.
- Syntax:
do{
//loop body
//code to be executed
}while(condition);
- Example:
- In this example, do-while loop is printing the
numbers from 1 to 5 on the console. The loop
terminates when the condition `i <= 5` is false.
LOOPS • 41
ARCHIES GURAV
HANDS-ON ASSIGNMENTS
ON THIS TOPIC:
1. Write a program that inputs an integer n and
prints the first n positive numbers.
2. Write a program that inputs an integer n and
calculates the sum of the first n positive numbers.
3. Write a program that inputs a number and prints
its multiplication table.
4. Write a program that inputs an integer n and
prints the factorial of n.
5. Write a program that inputs a string and prints the
reverse of the string.
6. Write a program that inputs two numbers a and b
and calculates their greatest common divisor (GCD).
7. Write a program that inputs an integer n and
calculates the sum of the squares of the first n
positive numbers.
LOOPS • 42
ARCHIES GURAV
CONTINUE AND BREAK
STATEMENTS
- The `continue` and `break` statements are control
flow statements in Java that allow you to change the
flow of execution in a loop.
Continue:
- The continue statement is used to skip the
current iteration of a loop and move on to the next
iteration.
- Example:
- In this code, the continue statement is used to skip
the iteration of the loop if the value of i is even. As a
result, only the odd numbers from 1 to 10 will be
printed.
CONTINUE AND BREAK STATEMENTS • 43
ARCHIES GURAV
Break:
- The break statement is used to exit a loop
prematurely. When a break statement is executed, the
loop terminates and the control flow moves to the
statement immediately following the loop.
- Example:
- In this code, the break statement is used to exit the
loop when the value of `i` is 5. As a result, only the
numbers 1 to 4 will be printed.
- Both the `continue` and `break` statements can be
used with all types of loops in Java, including for, while,
and do-while loops.
CONTINUE AND BREAK STATEMENTS • 44
ARCHIES GURAV
HANDS-ON ASSIGNMENTS
ON THIS TOPIC:
1. Write a program that inputs a sentence and prints
the first word that has more than 5 letters.
2. Write a program that inputs a sentence and
counts the number of words in the sentence.
3. Write a program that inputs two numbers a and b
and calculates their least common multiple (LCM).
4. Write a program that inputs a string and counts
the number of vowels in the string.
5. Write a program that inputs a number n and
calculates the sum of the first n positive numbers
that are divisible by 3.
6. Write a program that inputs an integer n and
calculates the sum of the cubes of the first n positive
numbers.
CONTINUE AND BREAK STATEMENTS • 45
ARCHIES GURAV
USING SCANNER CLASS
- The Scanner class in Java is part of the `java.util`
package and is used to read data from the keyboard or
other input sources, such as a file or a network socket.
- The Scanner class provides several methods for
reading different data types, including `nextInt()` for
reading integers, `nextDouble()` for reading floating-
point numbers, and `nextLine()` for reading strings.
- Here's an example of how to use the Scanner class to
read an integer from the keyboard:
- In this example, the Scanner class is imported and
then an instance of it is created using System.in as the
input source. The `nextInt()` method is then used to
read an integer from the keyboard, and the value is
stored in the num variable. Finally, the value of num is
printed to the console using `println()`.
USING SCANNER CLASS • 46
ARCHIES GURAV
TYPES OF FUNCTIONS
Function:
- Functions, also known as methods, are blocks of
code that perform a specific task and can be called
from other parts of the program. Functions in Java
help to modularize the code, make it easier to
understand, and reuse code in multiple places.
- Here's the syntax for a function in Java:
- modifiers: These specify the access level of the
method, such as public, private, protected, or default.
- return type: This is the data type of the value
returned by the function. If the function doesn't return
a value, the return type is void.
- functionName: This is the name of the function. The
name should follow the same naming conventions as
variables, and should be descriptive of what the
function does.
- parameters: These are the values passed to the
function when it's called. A function may have zero or
more parameters. Each parameter has a type and a
name.
TYPES OF FUNCTIONS • 47
ARCHIES GURAV
- There are two types of functions in Java.
Instance Methods:
- These are methods that are associated with
instances of a class and can access the instance
variables of the class.
- Here's an example of an instance method in
Java
- In this example, the area method calculates the area
of a Rectangle object. To call this method, you need to
create an instance of the Rectangle class and use the .
operator to access the method:
TYPES OF FUNCTIONS • 48
ARCHIES GURAV
Static Methods:
- These are methods that are associated with
the class itself, and don't require an instance of the
class to be created.
- Here's an example of a static method in Java
- In this example, the area method calculates the area
of a square. To call this method, you can use the class
name and the `. ` operator:
- Static methods are often used to provide utility
functions that can be called from anywhere in the
code, without having to create an instance of the class.
TYPES OF FUNCTIONS • 49
ARCHIES GURAV
HANDS-ON ASSIGNMENTS
ON THIS TOPIC:
1. Write a program that inputs a sentence and prints
the first word that has more than 5 letters.
2. Write a program that inputs a sentence and
counts the number of words in the sentence.
3. Write a program that inputs two numbers a and b
and calculates their least common multiple (LCM).
4. Write a program that inputs a string and counts
the number of vowels in the string.
5. Write a program that inputs a number n and
calculates the sum of the first n positive numbers
that are divisible by 3.
6. Write a program that inputs an integer n and
calculates the sum of the cubes of the first n positive
numbers.
TYPES OF FUNCTIONS • 50
ARCHIES GURAV
GARBAGE COLLECTION
- Garbage collection is an important feature of Java
that automatically manages the memory used by the
program. When a Java program creates an object, it is
stored in memory, but at some point, in the program's
execution, the object is no longer needed. Garbage
collection frees up the memory occupied by these
objects, allowing the memory to be reused by other
parts of the program.
- In this example, we create an object of the class
MyObject and assign it to a reference variable called
obj. We then use the object by calling its doSomething()
method. Once we're done using the object, we discard
the reference by setting obj to null. This means that
there are no longer any references to the object, and it
is now eligible for garbage collection.
GARBAGE COLLECTION • 51
ARCHIES GURAV
STRINGS IN JAVA
- In Java, a string is a sequence of characters,
represented as an object of the String class. Strings in
Java are immutable, which means that once a string is
created, its value cannot be changed.
- There are several ways to create a string in Java:
1. Using string literals: A string literal is a sequence of
characters enclosed in double quotes.
For Example:
2. Using the String constructor: The String class has
several constructors that can be used to create a new
string object.
For Example:
STRINGS IN JAVA • 52
ARCHIES GURAV
- Here are some common string functions in Java:
1. `length()`: Returns the length of the string.
2. `charAt(index)`: Returns the character at the
specified index in the string.
3. `substring(startIndex, endIndex)`: Returns a
substring of the original string, starting at the
startIndex and ending at the endIndex (exclusive).
4. `toUpperCase()`: Returns a new string with all
characters in uppercase.
5. `toLowerCase()`: Returns a new string with all
characters in lowercase.
STRINGS IN JAVA • 53
ARCHIES GURAV
6. `equals(Object obj)`: Returns true if the string is
equal to the specified object, false otherwise.
7. `equalsIgnoreCase(String anotherString)`:Returns
true if the string is equal to the specified string,
ignoring case differences.
8. `indexOf(int ch)`: Returns the index of the first
occurrence of the specified character in the string.
9. `indexOf(String str): Returns the index of the first
occurrence of the specified substring in the string.
10. `lastIndexOf(int ch)`: Returns the index of the last
occurrence of the specified character in the string.
STRINGS IN JAVA • 54
ARCHIES GURAV
11. `lastIndexOf(String str)`: Returns the index of the
last occurrence of the specified substring in the string.
12. `startsWith(String prefix)`:Returns true if the
string starts with the specified prefix, false otherwise.
13. `endsWith(suffix)`: Returns true if the string ends
with the specified suffix, false otherwise.
14. `contains(CharSequence s): Returns true if the
string contains the specified character sequence, false
otherwise.
15. `replace(char oldChar, char newChar)`: Returns a
new string with all occurrences of oldChar replaced by
newChar.
STRINGS IN JAVA • 55
ARCHIES GURAV
16. `replaceAll(String regex, String replacement)`:
Returns a new string with all occurrences of the regular
expression regex replaced by replacement.
17. `split(String regex)`:Splits the string into an array
of substrings, using the specified regular expression
regex as the delimiter.
STRINGS IN JAVA • 56
ARCHIES GURAV
HANDS-ON ASSIGNMENTS
ON THIS TOPIC:
1. Write a Java program to find the length of a string
without using the `length()` method.
2. Write a Java program to count the number of
vowels in a string.
3. Write a Java program to check if a string is a
palindrome.
4. Write a Java program to remove duplicate
characters from a string.
5. Write a Java program to find the first non-
repeated character in a string.
6. Write a Java program to find the most frequent
character in a string.
7. Write a Java program to check if two strings are
anagrams of each other.
8. Write a Java program to check if a string is a valid
shuffle of two other strings.
STRINGS IN JAVA • 57
ARCHIES GURAV
STRINGBUILDER AND
STRINGBUFFER
- `StringBuilder` and `StringBuffer` are both classes in
Java that provide mutable (modifiable) strings, which
means that you can modify the content of the string
without creating a new string object. They are useful
when you need to perform a large number of string
manipulations, such as concatenating multiple strings,
or removing or inserting characters in a string.
- `StringBuilder` was introduced in Java 5, and it is
preferred over `StringBuffer` in most cases, because it
is faster and more efficient.
- `StringBuffer` is a legacy class that was introduced in
Java 1.0, and it is still available for backward compatibi-
-lity.
- The main difference between `StringBuilder` and
`StringBuffer` is that,
- `StringBuffer` is thread-safe, which means that
multiple threads can safely access and modify the
same instance of the class at the same time, without
interfering with each other.
STRINGBUILDER AND STRINGBUFFER • 58
ARCHIES GURAV
- `StringBuilder` is not thread-safe, which means that
it is faster and more efficient, but it can cause problems
if multiple threads access and modify the same
instance of the class at the same time.
- Here is an example of how to use `StringBuilder` to
concatenate multiple strings.
- In this example, we create a new `StringBuilder`
instance, and then we use the `append()` method to
add multiple strings to the string builder. Finally, we
use the `toString()` method to convert the string
builder back to a regular string.
- Here is an example of how to use StringBuffer to
concatenate multiple strings:
- This example is similar to the previous one, but we are
using `StringBuffer` instead of StringBuilder. The code
is almost identical, except for the class name.
STRINGBUILDER AND STRINGBUFFER • 59
ARCHIES GURAV
HANDS-ON ASSIGNMENTS
ON THIS TOPIC:
1. Write a Java program to reverse a string using
StringBuilder.
2. Write a Java program to count the number of
occurrences of a substring in a string using
StringBuffer.
3. Write a Java program to remove all occurrences of
a substring from a string using StringBuilder.
4. Write a Java program to compare two strings
lexicographically using StringBuilder.
5. Write a Java program to check if a given
StringBuffer contains only digits
6.Write a Java program to check if a given string is a
palindrome using StringBuffer.
7. Write a Java program to check if a string is a
rotation of another string using StringBuilder.
STRINGBUILDER AND STRINGBUFFER • 60
ARCHIES GURAV
ARRAYS AND 2D ARRAYS
- In Java, an array is a collection of variables of the
same data type, referred to by a common name. It can
be thought of as a container that holds a fixed number
of elements of a specific data type. Arrays are used to
store multiple values in a single variable, making it easy
to access and manipulate the elements.
- For example, suppose you want to store the ages of
five people in a program. You can use an array to store
these values as follows:
- This creates an integer array named ages that holds
five values. Each value is accessed by its index, which
starts at 0 and goes up to `length - 1`.
- For example, to access the first element of the array,
you can use:
- This assigns the value 23 (the first element of the
array) to the variable `firstAge`.
- Arrays are a powerful and essential data structure in
Java understanding how to work with them is crucial
for developing applications.
ARRAYS AND 2D ARRAYS• 61
ARCHIES GURAV
- A 2D array is an array of arrays in which each element
is itself an array. This means that a 2D array can be
thought of as a table or a grid of elements arranged in
rows and columns. In Java, a 2D array is declared by
specifying two dimensions: the number of rows and
the number of columns.
- Here is an example of declaring and initializing a 2D
array in Java:
- This creates a 3x3 matrix with the values 1 through 9
arranged in rows and columns. You can access the
elements of the array using the row and column index,
like this:
- In this example, the value variable would be assigned
the value 6, which is the value in the second row, third
column of the matrix.
- 2D arrays are useful for representing data that is
naturally arranged in a table or grid format, such as
images, game boards, and matrices. They are also
commonly used in algorithms and data structures,
such as dynamic programming and graph algorithms
to store intermediate results and states.
ARRAYS AND 2D ARRAYS • 62
ARCHIES GURAV
HANDS-ON ASSIGNMENTS
ON THIS TOPIC:
1. Write a Java program to find the maximum and
minimum element in an array.
2. Write a Java program to find the sum of all
elements in an array.
3. Write a Java program to find the second largest
element in an array.
4. Write a Java program to sort an array in ascending
and descending order.
5. Write a Java program to find the sum of all
elements of a 2D array.
6. Write a Java program to find the transpose of a 2D
array.
7. Write a Java program to find the diagonal sum of a
2D array.
8. Write a Java program to check if a given 2D array is
a magic square or not.
ARRAYS AND 2D ARRAYS • 63
ARCHIES GURAV
ACCESS SPECIFIERS
- Access specifiers in Java are used to define the
visibility and accessibility of classes, methods, and
variables in a program.
- There are four access specifiers in Java:
1. Public: Public is the most commonly used access
specifier in Java. A public member can be accessed
from anywhere, both within and outside the package.
- Example:
2. Private: A private access specifier means that the
class, method, or variable can only be accessed from
within the same class. For example:
3. Protected: A protected access specifier means that
the class, method, or variable can only be accessed
from within the same class, any subclass of the class,
and any class in the same package. For example:
ACCESS SPECIFIERS• 64
ARCHIES GURAV
1. Default (No Keyword): A default or package-private
access specifier means that the class, method, or
variable can only be accessed from within the same
package. For example:
- Access specifiers are important in object-oriented
programming because they allow you to control the
visibility and accessibility of the various components of
your program. This helps to keep your code organized,
secure, and easy to maintain.
- Here's an example that demonstrates the use of
access specifiers in Java:
ACCESS SPECIFIERS• 65
ARCHIES GURAV
OBJECT ORIENTED PROGRAMMING
- Object-oriented programming (OOP) is a
programming paradigm that is used to organize
complex code into more manageable and reusable
components. In Java, OOP is a fundamental concept
that forms the basis of much of the language's
functionality.
- OOP is based on the concept of objects, which are
instances of classes.
- A class is a blueprint or template that defines the
attributes and behaviors of an object.
- An object is an instance of a class that has its own
unique set of attribute values.
- Here is an example of classes and objects:
OOP CONCEPTS• 66
ARCHIES GURAV
- In this example, the Car class has three instance
variables (make, model, and year) and a constructor
that initializes these variables. It also has an instance
method, drive(), which prints a message to the console.
- Created a new object of the Car class in main function
and assign it to the variable `myCar`. The constructor is
called with the arguments "Toyota", "Camry", and 2022,
which initializes the instance variables make, model,
and year.
- After creating the object of the class and assigning it
to the variable `myCar`, you can access the instance
methods and variables. using the dot notation and
calling the function and the variables you want.
- Let's also understand about the "this" keyword
- `this` keyword: In Java, the this keyword is a
reference to the current object. It is used to refer to the
instance variables and methods of the current object,
and can also be used to invoke one constructor from
another constructor in the same class.
- In this example, `this.make`, `this.model`and
`this.year` refers to the instance variable name of the
current object instance. This is useful when the
parameter of the constructor method has the same
name as the instance variable.
OOP CONCEPTS• 67
ARCHIES GURAV
- `super` keyword: In Java, the super keyword is used
to refer to the parent class or superclass of a subclass.
It can be used to access the members (fields and
methods) of the parent class, to invoke the parent
class constructor, and to differentiate between a
member of the subclass and a member of the parent
class with the same name.
Let's turn towards the OOP Concepts
- The four main concepts of OOP in Java are:
1. Encapsulation: Encapsulation is the practice of
hiding the internal details of an object from the outside
world and only exposing a public interface. This allows
the object to be used in a modular and reusable way
without exposing its internal workings. Encapsulation
is an important concept in object-oriented
programming because it helps to ensure that code is
more modular, maintainable, and secure.
OOP CONCEPTS• 68
ARCHIES GURAV
- Here is an example:
- In this example, we have a BankAccount class that
encapsulates the balance of a bank account. The
balance is stored as a private variable, which means
that it can only be accessed from within the
BankAccount class itself.
- To interact with the balance, the BankAccount class
provides three public methods: getBalance, withdraw
and deposit. The getBalance method allows the
balance to be read, while the deposit method allows
money to be added to the account and withdraw
method allows money to be subtracted from the
account.
- This makes the BankAccount class more secure and
easier to maintain, since any changes to the balance
can be made in a centralized and controlled way.
OOP CONCEPTS• 69
ARCHIES GURAV
2. Inheritance: Inheritance is a fundamental concept in
object-oriented programming that allows classes to
inherit properties and behaviors from their parent
classes. In Java, inheritance is implemented using the
"extends" keyword to specify a parent class.
- There are several types of inheritance, including:
Single Inheritance: Single inheritance is the
simplest form of inheritance and involves a child
class inheriting properties and behaviors from a
single parent class.
inherits
Class A Class B
- Here is an example:
- In this example, the Dog class extends the Animal
class, which means that it inherits the eat method. The
Dog class also adds its own method, bark.
OOP CONCEPTS• 70
ARCHIES GURAV
Multilevel Inheritance: Multilevel inheritance
involves a child class inheriting properties and
behaviors from a parent class, which in turn
inherits from another parent class.
Class A Class B Class C
- Here is an example:
- In this example, the Dog class extends the Mammal
class, which in turn extends the Animal class. The Dog
class inherits the eat method from the Animal class
and the move method from the Mammal class.
OOP CONCEPTS• 71
ARCHIES GURAV
Hierarchical Inheritance: Hierarchical inheritance
involves a child class inheriting properties and
behaviors from a single parent class, but multiple
child classes can inherit from the same parent
class.
Class A
Class B Class C
- Here is an example:
- In this example, both the Dog class and the Cat class
extend the Animal class. They both inherit the eat
method from the Animal class, but each class adds its
own unique method (bark for Dog and meow for Cat).
- Overall, inheritance is a powerful concept in Java that
allows developers to create more specialized classes
that share common properties and behaviors with
their parent classes.
OOP CONCEPTS• 72
ARCHIES GURAV
3. Polymorphism: Polymorphism is another
fundamental concept in object-oriented programming
and refers to the ability of an object to take on multiple
forms. In Java, polymorphism can be achieved through
method overloading and method overriding.
Method Overloading: Method overloading is a
technique that allows a class to have multiple
methods with the same name but different
parameters. The appropriate method is called
based on the arguments passed to the method.
Here is an example:
- In this example, the MathUtils class has two methods
with the same name, add, but they take different
parameter types (int and double). This allows the same
method name to be used for different data types,
making the code more flexible and easier to read.
OOP CONCEPTS• 73
ARCHIES GURAV
Method Overriding: Method overriding is a
technique that allows a subclass to provide a
specific implementation of a method that is
already provided by its parent class. The
overridden method has the same name, return
type, and parameters as the original method.
Here is an example:
- In this example, the Animal class has a method called
makeSound, and the Dog class overrides it with its own
implementation. When the makeSound method is
called on a Dog object, the overridden method in the
Dog class is called instead of the method in the Animal
class.
- Polymorphism allows us to write more flexible and
reusable code by creating classes and methods that
can be used in a variety of contexts.
OOP CONCEPTS• 74
ARCHIES GURAV
4. Abstraction: Abstraction is a fundamental concept
in object-oriented programming that allows you to
represent the essential features of an object without
showing the implementation details. It is achieved
through abstract classes and interfaces.
Abstract Classes: An abstract class is a class that is
declared with the abstract keyword, and it cannot
be instantiated. It can have abstract and non-
abstract methods, and it can also have instance
variables.
Here is an example:
- In this example, Shape is an abstract class that has a
constructor, a private instance variable, a non-abstract
method, and an abstract method. The abstract
method, getArea(), does not have an implementation in
the Shape class, and it is meant to be implemented in
the subclasses that extend the Shape class.
OOP CONCEPTS• 75
ARCHIES GURAV
Interfaces: An interface is a collection of abstract
methods, and it is used to define a contract that
specifies what a class must do without providing
any implementation details.
Here is an example:
- In this example, the Animal interface has only one
method, makeSound(), which is implemented in the Dog
class. By implementing the Animal interface, the Dog
class is required to provide an implementation for the
makeSound() method.
- You may have noticed that I didn't mention anything
about `Multiple Inheritance` in the previous Inheritance
section. This is because,
- Java supports single inheritance, which means that a
class can inherit from only one superclass.
- However, Java provides a way to achieve multiple
inheritance of interfaces through the use of interfaces.
- Let's understand it with help of an example.
OOP CONCEPTS• 76
ARCHIES GURAV
- An interface only defines the methods that a class
implementing it must have. A class can implement
multiple interfaces, which enables it to inherit the
abstract methods defined by each interface.
- For example, let's say we have two interfaces:
Drawable and Scalable. The Drawable interface defines
an abstract method draw(), and the Scalable interface
defines an abstract method scale(). Now, we can create
a class Circle that implements both of these interfaces,
like this:
- In this example, Circle implements both Drawable and
Scalable interfaces, and provides its own
implementation for the draw() and scale() methods.
- By using interfaces, we can achieve multiple
inheritance in Java without running into the problems
that arise with traditional multiple inheritance.
OOP CONCEPTS• 77
ARCHIES GURAV
HANDS-ON ASSIGNMENTS
ON THIS TOPIC:
1. Write a Java program to create a class hierarchy
with an abstract class as the base class and two
subclasses that inherit from it. The abstract class
should have at least one abstract method that is
implemented in the subclasses.
2. Write a Java program to create an interface with
one or more methods, and implement it in a class.
3. Write a Java program to demonstrate method
overloading, with multiple methods that have the
same name but different parameters.
4. Write a Java program to create a Shape class that
has two subclasses, Circle and Rectangle. The Shape
class should have an abstract method, getArea(),
that is implemented in the subclasses.
5. Write a Java program to create an interface that
defines a set of methods for a Vehicle, and
implement it in two classes, Car and Truck.
OOP CONCEPTS • 78
ARCHIES GURAV
JAVA 8 FEATURES
- Java 8 introduced a range of new features that
improved the language in several areas, including
performance, functionality, and ease of use. In this
chapter, we will explore some of the key features of
Java 8 with an example.
1. Lambda Expressions: Lambda expressions are a new
language feature introduced in Java 8 that provide a
concise way to express functionality in code. They are
used extensively in functional programming and
enable the creation of functional interfaces.
- Example: Suppose you want to sort a list of names
alphabetically using lambda expressions. You can use
the Comparator interface and lambda expressions as
follows:
- Here, we create a list of names and use the
`Collections.sort()` method to sort the names
alphabetically.
- We use a lambda expression (a, b) -> a.compareTo(b)
to define the comparison logic.
JAVA 8 FEATURES• 79
ARCHIES GURAV
- This lambda expression implements the Comparator
interface's `compare()` method, which compares two
strings and returns a negative integer, zero, or a
positive integer depending on whether the first string
is less than, equal to, or greater than the second string.
2. Stream API: The Stream API is another significant
addition to Java 8. It provides a powerful and flexible
way to process collections of data. The Stream API
allows you to perform operations such as filtering,
mapping, and reducing on collections in a concise and
readable way.
- Example: Suppose you want to filter a list of numbers
to find the even numbers and calculate their sum using
the Stream API. You can use the filter() and mapToInt()
methods as follows:
- Here, we create a list of numbers and use the stream()
method to convert it into a Stream. We then use the
filter() method to select only the even numbers, the
mapToInt() method to convert the stream of integers
to an IntStream, and the sum() method to calculate the
sum of the even numbers. JAVA 8 FEATURES• 80
ARCHIES GURAV
3. Date and Time API: Java 8 also introduced a new
Date and Time API that makes it easier to work with
dates and times. The new API provides classes such as
LocalDate, LocalTime, and LocalDateTime to represent
dates and times and provides a range of methods for
parsing, formatting, and calculating durations between
dates.
- Example: Suppose you want to format the current
date and time in a specific format using the Date and
Time API. You can use the DateTimeFormatter class as
follows:
- Here, we create a LocalDateTime object representing
the current date and time and use the ofPattern()
method to create a DateTimeFormatter object with the
desired format. We then use the format() method to
format the date and time into a string using the
DateTimeFormatter.
JAVA 8 FEATURES• 81
ARCHIES GURAV
4. Default Methods: Default methods are a new feature
in Java 8 that allow interface methods to have a
default implementation. This feature allows interfaces
to evolve without breaking the existing code that
implements them.
- Example: Suppose you have an interface MyInterface
with a method myMethod(). You can add a default
implementation for this method in Java 8 as follows:
- Here, we have added a default implementation for
the myDefaultMethod() method in the MyInterface
interface. If a class implements this interface and does
not provide its implementation for myDefaultMethod(),
the default implementation will be used.
5. Functional Interfaces: Functional interfaces are a
new addition to Java 8 that allow the use of lambda
expressions to create objects of an interface type. A
functional interface is an interface that has only one
abstract method, called the functional method. It can
have any number of default methods and static
methods.
JAVA 8 FEATURES• 82
ARCHIES GURAV
- Example: Suppose you have a functional interface
Calculator with a method calculate(int a, int b) that
takes two integers as input and returns an integer
result. You can use a lambda expression to create an
object of this interface as follows:
- Here, we define the Calculator functional interface
with a single abstract method calculate(int a, int b). We
then use lambda expressions to create three objects of
this interface - add, subtract, and multiply. We call the
calculate() method on each object with the input
parameters 10 and 5 and print the result.
- The @FunctionalInterface annotation is optional but
recommended to indicate that the interface is
intended to be a functional interface.
JAVA 8 FEATURES• 83
ARCHIES GURAV
6. Optional: The Optional class is a new addition to Java
8 that provides a way to handle null values. It can be
used to avoid NullPointerExceptions and make the
code more readable and maintainable.
- Example: Suppose you have a method getUserName()
that returns a user's name or null if the name is not
available. You can use the Optional class to handle the
null value as follows:
- Here, we use the getUserName() method to get the
user's name as an Optional<String> object. We then
check if the object is present using the isPresent()
method and print the user's name if it is available using
the get() method. If the object is not present, we print a
message indicating that the user's name is not
available.
- Functional interfaces and lambda expressions have
made Java 8 a more expressive and powerful language.
They allow us to write concise and readable code that
is easy to understand and maintain.
JAVA 8 FEATURES• 84
ARCHIES GURAV
HANDS-ON ASSIGNMENTS
ON THIS TOPIC:
1. Write a program that uses the Date and Time API
to calculate the duration between two dates in
years, months, and days.
2. Write a program that uses the Stream API to
convert a list of strings to uppercase and sort them
in alphabetical order.
3. Write a program that uses lambda expressions to
sort a list of integers in ascending order.
4. Write a program that uses the Date and Time API
to display the current date and time.
5. Write a program that uses the Optional class to
handle null values when accessing a map.
6. Write a program that uses default methods in an
interface to calculate the area of a rectangle.
7. Create a functional interface that takes a string as
input and returns the length of the string as output.
JAVA 8 FEATURES • 85
ARCHIES GURAV
INNER CLASSES
- Java provides a feature called inner classes that
allows us to define a class inside another class. Inner
classes can be used to logically group classes that are
only used in one place, increase encapsulation, and
improve code organization and readability.
1. Non-static Inner Classes: A non-static inner class,
also known as an inner class, is a class that is defined
inside another class without the static keyword. Non-
static inner classes have access to the variables and
methods of the outer class.
- Example:
- Here, we define an outer class OuterClass with a
private integer variable x and an inner class InnerClass
that has a method display() that prints the value of x.
We create an object of the outer class and use it to
create an object of the inner class, then call the
display() method on the inner object.
INNER CLASSES• 86
ARCHIES GURAV
2. Static Inner Classes: A static inner class is a class that
is defined inside another class with the static keyword.
Static inner classes can access only the static members
of the outer class.
- Example:
- Here, we define an outer class OuterClass with a
private static integer variable x and a static inner class
InnerClass that has a method display() that prints the
value of x. We create an object of the inner class and
call the display() method on it.
3. Local Inner Classes: A local inner class is a class that is
defined inside a method or block of code. Local inner
classes can access the variables and parameters of the
method or block of code, but only if they are declared
final or effectively final.
INNER CLASSES• 87
ARCHIES GURAV
- Example:
- Here, we define an outer class OuterClass with a
method display() that declares a final integer variable x
and a local inner class InnerClass that has a method
display() that prints the value of x. We create an object
of the inner class and call the display() method on it
inside the display() method of the outer class.
- Inner classes are a powerful feature of Java that can
be used to improve code organization and
encapsulation. In this chapter, we explored the three
types of inner classes - non-static, static, and local -
and demonstrated how they can be used in practice.
INNER CLASSES• 88
ARCHIES GURAV
HANDS-ON ASSIGNMENTS
ON THIS TOPIC:
1. Write a Java program to create a static inner class
that displays a message.
2. Write a Java program to create a nested class that
displays a message.
3. Write a Java program to access the variables of
the inner class from the outer class.
4. Write a Java program to create an anonymous
inner class that displays a message.
5. Write a Java program to implement an interface in
a non-static inner class.
6. Write a Java program to create a non-static inner
class and access it from another class.
7. Define a non-static inner class named InnerClass
inside a class named OuterClass that has a private
integer variable x. Add a method getX() to the inner
class that returns the value of x.
INNER CLASSES• 89
ARCHIES GURAV
PACKAGES
- Java packages are a mechanism for organizing
related classes and interfaces into a single unit of
reuse. Packages provide a way to group related classes
and interfaces together, making it easier to manage
and maintain large Java applications. In this chapter,
we will discuss the basics of packages in Java and how
to create, import and use packages in your Java
programs.
- Creating a package: To create a package in Java, you
need to include the package statement at the
beginning of your Java source file. The package
statement is the first non-comment statement in the
source file and specifies the name of the package in
which the class belongs. For example, the following
code snippet creates a package named
"com.example.mypackage" and includes a class named
"MyClass" in that package:
- In this example, the package statement indicates
that the "MyClass" class belongs to the
"com.example.mypackage" package.
PACKAGES• 90
ARCHIES GURAV
- Package Naming Conventions: Java package names
should follow a naming convention that helps to avoid
naming conflicts between different packages. The
recommended convention for package names is to use
the reverse domain name of the organization or
company that owns the package, followed by one or
more additional identifiers that describe the package.
For example, if your company's domain name is
"example.com" and you are creating a package for a
product named "myproduct", you might use the
following package name:
- Importing Packages: To use a class or interface from
another package, you need to import that package into
your Java program. The import statement should be
placed after the package statement and before the
class declaration. For example, the following code
snippet imports the "java.util" package and uses the
"ArrayList" class from that package:
PACKAGES• 91
ARCHIES GURAV
- In this example, the "java.util" package is imported
using the import statement, and the "ArrayList" class is
used to create a list of strings.
- Using Packages: Once you have created or imported
a package, you can use the classes and interfaces
defined in that package in your Java program. To use a
class or interface from another package, you need to
specify the fully qualified name of the class or
interface, which includes the package name and the
class or interface name. For example, the following
code snippet uses the "ArrayList" class from the
"java.util" package:
- In this example, the fully qualified name of the
"ArrayList" class is used to create a list of strings.
- Packages are an essential feature of the Java
programming language, providing a way to organize
and reuse code. By following the naming conventions
and best practices for packages, you can create
maintainable, scalable, and robust Java applications
PACKAGES• 92
ARCHIES GURAV
HANDS-ON ASSIGNMENTS
ON THIS TOPIC:
1. Create a package named "com.example.utils" and
add a class "StringUtils" to it with a static method
that reverses a given string.
2. Create a package named "com.example.shapes"
and add a class "Rectangle" to it that represents a
rectangle with width and height properties.
3. Create a package named "com.example.math" and
add a class "Calculator" to it that performs basic
arithmetic operations.
4. Create a package named "com.example.search"
and add a class "BinarySearch" to it that implements
a binary search algorithm.
5. Create a package named "com.example.utilities"
and add a class "RandomUtils" to it that generates
random numbers and strings.
6. Create a package named "com.example.data" and
add a class "Person" to it that represents a person
with a name, age, and address.
PACKAGES• 93
ARCHIES GURAV
MULTI-THREADING IN JAVA
- Java is a multi-threaded programming language,
which means it can handle multiple threads of
execution at the same time. Multi-threading is an
important concept in Java, as it allows programmers to
take advantage of multi-core processors and maximize
the performance of their applications. In this chapter,
we'll explore the basics of multi-threading in Java and
look at some examples.
What is a Thread?
- A thread is a lightweight process that can execute
independently and concurrently with other threads in
a Java program. Threads share the same memory
space, which allows them to communicate and
coordinate their activities.
Creating Threads in Java:
- Java provides two ways to create threads:
1. Extending the Thread Class: To create a thread by
extending the Thread class, you need to define a new
class that extends the Thread class and override the
run() method. The run() method contains the code that
will be executed when the thread is started.
MULTI-THREADING IN JAVA• 94
ARCHIES GURAV
- Example:
2. Implementing the Runnable interface: To create a
thread by implementing the Runnable interface, you
need to define a new class that implements the
Runnable interface and override the run() method. The
run() method contains the code that will be executed
when the thread is started.
- Example:
Thread Synchronization: Thread synchronization is
the process of controlling the access to shared
resources in a multi-threaded environment. In Java,
synchronization is achieved using the synchronized
keyword. When a method or a block of code is marked
as synchronized, only one thread can execute that
code at a time.
MULTI-THREADING IN JAVA• 95
ARCHIES GURAV
- Example:
- In this example, the increment() and getCount()
methods are marked as synchronized, which ensures
that only one thread can access the count variable at a
time.
Thread Pooling: Thread pooling is a technique that
allows a group of threads to be created and managed
together. Thread pooling is useful in situations where
creating and destroying threads frequently can be
costly.
- In this example, we create a fixed thread pool of size
10 and submit 100 tasks to be executed by the threads
in the pool. Once all the tasks have completed, we
shutdown the thread pool.
MULTI-THREADING IN JAVA• 96
ARCHIES GURAV
HANDS-ON ASSIGNMENTS
ON THIS TOPIC:
1. Write a program to create and start a new thread
by extending the Thread class.
2. Write a program to create and start a new thread
by implementing the Runnable interface.
3. Write a program to demonstrate thread
synchronization using the synchronized keyword.
4. Write a program to demonstrate the join(), sleep(),
and interrupt() method of the Thread class.
5. Write a program to demonstrate the wait(), notify()
and notifyAll() methods of the Object class.
6. Write a program to avoid deadlock by using the
tryLock() method of the ReentrantLock class.
7. Write a program to create a thread-safe singleton
class.
8. Write a program to create a deadlock between two
threads.
MULTI-THREADING IN JAVA• 97
ARCHIES GURAV
COLLECTIONS FRAMEWORK
- The Collection Framework in Java is a group of
interfaces, classes, and algorithms that provide
support for storing, retrieving, and manipulating a
group of objects in Java. The collection framework has
been designed to simplify the task of working with
collections of objects, and it is a key feature of the Java
programming language.
- The Collection Framework in Java includes the
following components:
1. Interfaces: The Collection Framework provides a
number of interfaces that define common behaviors
for collections of objects. These interfaces include:
List: A collection that maintains the order of its
elements and allows duplicates.
Set: A collection that does not allow duplicates.
Queue: A collection used to hold elements prior to
processing. Queues typically, but do not
necessarily, order elements in a FIFO (first-in-first-
out) manner.
Dequeue: A collection that allows insertion and
removal of elements at both ends.
Map: A collection that stores key-value pairs, with
no duplicate keys allowed.
COLLECTIONS FRAMEWORK• 98
ARCHIES GURAV
2. Classes: The Collection Framework provides a set of
concrete classes that implement the interfaces. These
classes include:
ArrayList: A resizable array implementation of the
List interface.
LinkedList: A doubly linked list implementation of
the List interface.
HashSet: A set implementation that uses a hash
table to store elements.
TreeSet: A set implementation that uses a binary
tree to store elements in sorted order.
HashMap: A set implementation that uses a binary
tree to store elements in sorted order.
TreeMap: A map implementation that uses a binary
tree to store key-value pairs in sorted order.
3. Algorithms: The Collection Framework also provides
a set of algorithms, such as sorting and searching, that
can be used with any collection that implements the
appropriate interface.
- Example: Let's consider an example of how the
Collection Framework can be used to sort a list of
names in alphabetical order.
COLLECTIONS FRAMEWORK• 99
ARCHIES GURAV
- In the above example, we create an ArrayList to store
a list of names. We then use the Collections.sort()
method to sort the list in alphabetical order. Finally, we
loop through the sorted list and print out each name.
- The Collection Framework provides a powerful and
flexible set of tools for working with collections of
objects. Whether you're working with lists, sets, maps,
or other types of collections, the Collection Framework
provides a consistent and intuitive interface for
accessing and manipulating the data.
COLLECTIONS FRAMEWORK• 100
ARCHIES GURAV
HANDS-ON ASSIGNMENTS
ON THIS TOPIC:
1. Write a Java program to sort an ArrayList of
integers using the Collections Framework.
2. Write a Java program to remove duplicates from
an ArrayList of strings using the Collections
Framework.
3. Write a Java program to create a priority queue of
integers and add some elements to it.
4. Write a Java program to find the keys and values
of a HashMap of strings and integers using the
Collections Framework.
5. Write a Java program to copy one ArrayList of
integers to another using the Collections
Framework.
6. Write a Java program to merge two ArrayLists of
strings using the Collections Framework.
7. Write a Java program to create a TreeMap of
integers and strings and add some key-value pairs
to it. COLLECTIONS FRAMEWORK• 101
ARCHIES GURAV
JAVA GENERICS
- Generics are used to make Java code more type-safe
and to avoid runtime errors caused by type casting.
Java generics were introduced in Java 5 and have since
become an integral part of Java programming.
- Generics provide a way to create a single method,
class, or interface that can work with different types of
objects, without requiring the programmer to explicitly
cast the objects to the correct type. By using generics,
we can write code that is more concise, readable, and
maintainable.
Syntax of Generics: The syntax of generics involves the
use of angle brackets (<>) and a type parameter. The
type parameter specifies the type of object that the
class, method, or interface can work with.
- For Example, consider the following generic class:
- In the above example, we have created a generic class
called Box, which can work with any type of object. The
type parameter T specifies the type of object that the
class can work with.
JAVA GENERICS• 102
ARCHIES GURAV
- Let's see how we can use this class:
- In the above example, we have created two instances
of the Box class - one that works with integers and
another that works with strings. We have used the set()
method to set the value of the object and the get()
method to retrieve the value.
- Here are some more concepts related to Java
Generics:
- Wildcards in Generics: The wildcard '?' in Java
Generics represents an unknown type. It is used to
write generic code that can work with any type. The '?'
can be used as an upper bound or a lower bound to
restrict the type of objects that can be used.
- Bounded Type Parameters: Java Generics allow us to
define bounded type parameters that restrict the type
of objects that can be used with a generic class or
method. Bounded type parameters can be used as
upper bounds or lower bounds.
JAVA GENERICS• 103
ARCHIES GURAV
- Type Erasure: Java Generics use type erasure to
ensure backward compatibility with pre-existing code
that does not use generics. Type erasure replaces the
type parameter with its upper bound, which means
that the type information is lost at runtime.
- Generic Methods: Java Generics also allow us to
define generic methods that work with any data type.
Generic methods can be defined in generic and non-
generic classes.
- Example: Consider the following code snippet that
demonstrates the use of wildcards and bounded type
parameters in Java Generics:
JAVA GENERICS• 104
ARCHIES GURAV
- In the above example, we have defined a generic
class 'MyGenericsClass' with a bounded type parameter
'T extends Number'. The class has a constructor that
accepts a list of type 'T'. The 'getAverage' method
calculates the average of the numbers in the list, and
the 'printList' method prints the elements of a list of
any type using the wildcard '?'. We have created
instances of the 'MyGenericsClass' class with Integer
and Double data types and passed them to the
'getAverage' method. Finally, we have called the
'printList' method with a list of strings, which will not
compile due to type safety.
- Java Generics provide a powerful way to write
generic code that is type-safe, reusable, and
maintainable. By using Generics, we can write code that
works with any data type and can be reused in
different scenarios. The use of wildcards, bounded
type parameters, and generic methods adds flexibility
to the generic code and makes it more powerful.
JAVA GENERICS• 105
ARCHIES GURAV
HANDS-ON ASSIGNMENTS
ON THIS TOPIC:
1. Write a program to create a generic method that
can swap two elements of an array.
2. Write a program to create a generic method that
can print the elements of a list of any type.
3. Write a program to create a generic interface that
can be implemented by any class.
4. Write a program to create a generic class that can
implement a binary search tree of any type.
5. Write a program to create a generic method that
can concatenate two lists of any type.
6. Write a program to create a generic method that
can return the median of an array of any type.
7. Write a program to create a generic method that
can remove duplicates from a list of any type.
8. Write a program to create a generic method that
can sort a list of any type.
JAVA GENERICS• 106
ARCHIES GURAV
EXCEPTION HANDLING
- Exception handling is the process of handling the
runtime errors that may occur while executing a
program. These errors can be caused by various
reasons, such as user input, network issues, or bugs in
the code. To handle these errors effectively, Java
provides a set of keywords and constructs that help us
to identify and handle exceptions.
Types of Exceptions:
- In Java, there are two types of exceptions: checked
and unchecked exceptions.
1. Checked Exception: These are exceptions that the
compiler checks during compilation. The programmer
must handle these exceptions either by using try-
catch blocks or by declaring them in the method
signature using the throws keyword. Examples of
checked exceptions include IOException,
ClassNotFoundException, and SQLException.
2. Unchecked Exception: These are exceptions that the
compiler does not check during compilation. They are
thrown at runtime and can be handled by using try-
catch blocks. Examples of unchecked exceptions
include NullPointerException, ArrayIndexOutOfBound-
-Exception and ClassCastException.
EXCEPTION HANDLING• 107
ARCHIES GURAV
Try-Catch Blocks: The try-catch block is used to handle
exceptions in Java. The try block contains the code
that may throw an exception, and the catch block
contains the code that handles the exception. If an
exception is thrown in the try block, the catch block is
executed, and the exception is handled.
- Syntax:
- Example:
- In this example, we have a try block that contains the
code that may throw an ArithmeticException. If an
exception occurs, the catch block is executed, and the
exception is handled. In this case, we are printing the
exception message to the console.
Throwing Exceptions: In Java, we can also throw our
own exceptions using the throw keyword. This is useful
when we want to indicate that an error has occurred in
our program.
EXCEPTION HANDLING• 108
ARCHIES GURAV
- Syntax:
- Example:
- In this example, we have defined our own custom
exception class called CustomException. We are
throwing this exception in the main method and
catching it in the catch block. When we catch the
exception, we print the exception message to the
console.
- Exception handling is an essential feature in Java
that allows us to handle and manage errors effectively.
By using try-catch blocks and throwing exceptions, we
can write code that is more robust and reliable.
EXCEPTION HANDLING• 109
ARCHIES GURAV
HANDS-ON ASSIGNMENTS
ON THIS TOPIC:
1. Write a program to handle the ArithmeticExceptio-
-n that can be thrown when dividing two numbers.
2. Write a program that reads input from the user
and handles the InputMismatchException that can
be thrown if the input is of the wrong type.
3. Write a program that handles the ClassNotFound-
-Exception that can be thrown when a class is not
found.
4. Write a program that handles the
NoSuchElementException that can be thrown when
trying to access an element of an empty collection.
5. Write a program that handles the ClassCastExcep-
-tion that can be thrown when trying to cast an
object to a class that it is not an instance of.
6. Write a program that handles the
IllegalArgumentException that can be thrown when
an illegal argument is passed to a method.
EXCEPTION HANDLING• 110
ARCHIES GURAV
I/O & FILE HANDLING
- In Java, input/output (I/O) operations and file
handling are essential features that allow us to interact
with the external world. The java.io package provides
classes and interfaces for performing I/O operations in
Java.
- This chapter will cover the following topics:
1. Overview of I/O and File Handling in Java
2. Reading and Writing to Files
3. Reading and Writing to Text Files
4. Reading and Writing to Binary Files
5. Buffered I/O
6. Serialization
7. Compression and Decompression
1. Overview of I/O and File Handling in Java:
- In Java, the I/O operations can be categorized into
two types: character-based I/O and byte-based I/O.
The character-based I/O is used to read and write text
data, whereas byte-based I/O is used to read and write
binary data.
- The java.io package contains a variety of classes that
can be used for I/O operations. The most commonly
used classes include InputStream, OutputStream,
Reader, and Writer.
I/O AND FILE HANDLING• 111
ARCHIES GURAV
- These classes are the abstract base classes for all
input and output streams in Java.
2. Reading and Writing to Files:
- In Java, files can be read and written using the
FileReader and FileWriter classes, respectively. The
FileReader and FileWriter classes are used to read and
write character-based data to a file.
- Example:
- In the above example, we are using FileReader to read
data from the file "input.txt" and FileWriter to write
data to the file "output.txt".
I/O AND FILE HANDLING• 112
ARCHIES GURAV
3. Reading and Writing to Text Files:
- The Java BufferedReader and BufferedWriter classes
are used to read and write text files.
- The BufferedReader class is used to read character-
based data from a file, and the BufferedWriter class is
used to write character-based data to a file.
- Example:
- In the above example, we are using BufferedReader
to read data from the file "input.txt" and
BufferedWriter to write data to the file "output.txt".
The readLine() method of BufferedReader reads a line
of text from the file, and the newLine() method of
BufferedWriter inserts a new line character after each
line.
I/O AND FILE HANDLING• 113
ARCHIES GURAV
4. Reading and Writing to Binary Files:
- Reading and writing binary files in Java involves
reading and writing data in binary format. This is
different from reading and writing text files, which are
stored in human-readable format.
- Here's an example that demonstrates how to read
and write binary data using Java's I/O classes:
- In this example, we create a binary file using
FileOutputStream and DataOutputStream, and write
three values to it: an int, a double, and a String. We then
close the DataOutputStream, and open the file again
using FileInputStream and DataInputStream. We use
the DataInputStream to read the values back from the
file in the same order as they were written, and store
them in variables. Finally, we print out the values that
were read from the file.
I/O AND FILE HANDLING• 114
ARCHIES GURAV
5. Buffered I/O:
- Buffered streams in Java allow for efficient reading
and writing of data. They use an internal buffer to
store data, so that multiple I/O operations can be
combined into a single operation.
- Here's an example that demonstrates how to read
and write data using buffered streams:
- In this example, we create a BufferedOutputStream
to write data to a file, and a BufferedInputStream to
read data from the same file. We write a message to
the output stream, and then read the message back
from the input stream. Finally, we print the received
message to the console.
I/O AND FILE HANDLING• 115
ARCHIES GURAV
6. Serialization:
- Serialization is a process in which an object in Java is
converted into a stream of bytes so that it can be
saved to a file or transmitted over a network. It is used
to store and retrieve the state of an object. The
process of serialization involves converting the object
into a byte stream, and then deserialization is the
reverse process of converting the byte stream back
into the object.
- Serialization can be used in various scenarios, such as
caching and sharing objects across the network.
However, it is important to note that not all objects can
be serialized, such as objects that have references to
non-serializable objects. Additionally, the serialized
data is platform-independent, meaning that it can be
deserialized on any platform that supports Java.
- In Java, serialization is supported by the Serializable
interface, which is a marker interface that indicates
that the class can be serialized. To serialize an object,
we need to implement the Serializable interface and
override the default serialization behavior using the
readObject() and writeObject() methods.
- Here is an example:
I/O AND FILE HANDLING• 116
ARCHIES GURAV
- In the above example, we have a Student class that
implements the Serializable interface. We create an
object of the Student class and serialize it to a file
named "student.ser" using the ObjectOutputStream
class. We then deserialize the object using the
ObjectInputStream class and print the deserialized
object's properties. I/O AND FILE HANDLING• 117
ARCHIES GURAV
7. Compression and Decompression:
- In Java, the I/O and File Handling API provides a way
to compress and decompress data. This can be
particularly useful when dealing with large amounts of
data, as compression can significantly reduce the
amount of disk space or network bandwidth required
to store or transmit the data.
- Java provides two main classes for compression and
decompression: java.util.zip.ZipOutputStream and
java.util.zip.ZipInputStream. These classes provide a
simple way to compress and decompress data using
the popular ZIP file format.
To compress data, you create an instance of
ZipOutputStream and use it to write data to a new ZIP
file. Here's an example that compresses a file:
I/O AND FILE HANDLING• 118
ARCHIES GURAV
- In this example, we create a new ZipOutputStream
object and add a new entry to it using the
putNextEntry method. We then read the contents of
the input file using a FileInputStream and write the
data to the ZIP file using the write method of the
ZipOutputStream. Finally, we close the entry using the
closeEntry method and close the ZipOutputStream and
FileInputStream.
- To decompress data, you create an instance of
ZipInputStream and use it to read data from a ZIP file.
Here's an example that decompresses a file:
- In this example, we create a new ZipInputStream
object and use it to read the contents of the input ZIP
file. We then create a new FileOutputStream object and
write the data to a new file using the write method.
Finally, we close the ZipInputStream and
FileOutputStream. I/O AND FILE HANDLING• 119
ARCHIES GURAV
HANDS-ON ASSIGNMENTS
ON THIS TOPIC:
1. Write a program to read a file line by line and print
its content to the console.
2. Write a program to read a binary file and display its
content in hexadecimal format.
3. Write a program to create a new directory and file
inside it.
4. Write a program to create a zip file and add
multiple files to it.
5. Write a program to extract the content of a zip file.
6. Write a program to write data to a file using
FileWriter and read data from a file using FileReader.
7. Write a program to copy a directory and its
content to a new location.
8. Write a program to serialize and deserialize an
object to a file.
I/O AND FILE HANDLING• 120
ARCHIES GURAV
CONNECTING TO DATABASE
(JDBC)
- Java Database Connectivity (JDBC) is an API for Java
that enables Java programs to interact with relational
databases like MySQL, Oracle, and SQL Server. It
provides a standard interface for Java programs to
communicate with databases and execute SQL queries.
JDBC Architecture:
- The JDBC architecture consists of two main layers:
1. JDBC API: The JDBC API provides a set of classes
and interfaces that allow Java programs to
interact with databases. Some of the important
interfaces in JDBC API are:
i. Connection: It represents a connection to a
database.
ii. Statement: It is used to execute SQL queries.
iii. PreparedStatement: It is used to execute
parameterized SQL queries.
iv.. ResultSet: It represents the result set of a SQL
query.
2. JDBC Driver: A JDBC driver is a software component
that allows Java programs to connect to a database.
There are four types of JDBC drivers:
CONNECTING TO DATABASE (JDBC)• 121
ARCHIES GURAV
a. JDBC-ODBC Bridge Driver: This driver acts as a
bridge between the JDBC API and the ODBC API. It
translates JDBC calls into ODBC calls, which are then
sent to the database. This driver requires an ODBC
driver to be installed on the system.
b. Native API Driver: This driver communicates directly
with the database system using the vendor's native
API. It requires the vendor-specific libraries to be
installed on the system where the application is
running.
c. Network Protocol Driver: This driver uses a
middleware to communicate with the database
system. It sends requests to the middleware, which
then communicates with the database using the
appropriate protocol. This driver is useful when the
application needs to access databases on remote
systems.
d. Thin Driver: This driver is similar to the network
protocol driver, but it communicates with the database
system using a lightweight protocol. It does not require
any middleware to be installed on the system, making
it easier to deploy and use.
- Choosing the right JDBC driver depends on the
specific requirements of the application.
CONNECTING TO DATABASE (JDBC)• 122
ARCHIES GURAV
- If the application needs to access a local database,
then a Native API Driver or a JDBC-ODBC Bridge Driver
may be the best choice. If the database is located on a
remote system, then a Network Protocol Driver or a
Thin Driver may be more suitable.
- Let's understand with an example, we will establish a
connection to a MySQL database and execute a simple
SQL query to retrieve data from a table.
1. First, we need to load the MySQL JDBC driver:
2. Next, we need to establish a connection to the
database:
3. Once we have a connection, we can execute SQL
queries using Statement or PreparedStatement:
4. Finally, we can process the result set:
- This is a basic example of how to use JDBC to interact
with a database in Java.
CONNECTING TO DATABASE (JDBC)• 123
ARCHIES GURAV
HANDS-ON ASSIGNMENTS
ON THIS TOPIC:
1. Write a Java program to perform CRUD operations
into a MySQL database using JDBC.
2. Write a Java program to create/drop a table
in/from a MySQL database using JDBC.
3. Write a Java program to execute a SQL query with
parameters in a MySQL database using JDBC.
4. Write a Java program to execute a SQL query with
a where clause in a MySQL database using JDBC.
5. Write a Java program to execute a SQL query with
a join in a MySQL database using JDBC.
6. Write a Java program to execute a SQL query with
a group by clause in a MySQL database using JDBC.
7. Write a Java program to execute a SQL query with
an order by clause in a MySQL database using JDBC.
8. Write a Java program to execute a SQL query with
a like clause in a MySQL database using JDBC.
CONNECTING TO DATABASE (JDBC)• 124
ARCHIES GURAV
GUI PROGRAMMING
- Graphical User Interface (GUI) is a type of user
interface that allows users to interact with programs
or software visually. Java provides a rich set of libraries
and APIs for creating GUI-based applications. In this
chapter, we will discuss how to create GUI applications
in Java using Swing and AWT libraries.
Introduction to AWT:
- AWT stands for Abstract Window Toolkit.
- AWT was introduced with the initial release of Java,
and it provides the basic set of tools for creating a
graphical user interface.
- AWT uses the native platform's widgets and
components to create the interface.
- Let's know what do each interface and class of AWT
toolkit perform:
1. Component: The base class for all AWT
components that can be added to a container.
2. Container: A component that can hold other
components.
3. LayoutManager: An interface for objects that
manage the layout of components within a
container.
4. Event: A base class for all AWT events.
GUI PROGRAMMING• 125
ARCHIES GURAV
5. EventQueue: A queue that manages AWT events.
6. Window: A top-level container that represents a
window on the screen.
7. Dialog: A window that is designed to be used as a
dialog box.
8. Frame: A window with a title bar and other
decorations.
9. Menu: A menu bar or pop-up menu.
10. MenuBar: A container for menus that can be added
to a window.
11. MenuItem: An item in a menu.
12. PopupMenu: A pop-up menu that can be attached
to a component.
13. Button: A component that represents a button.
14. Label: A component that displays a text label.
15. TextField: A component that allows the user to
enter text.
16. TextArea: A component that displays multiple lines
of text.
17. Checkbox: A component that represents a
checkbox.
18. List: A component that displays a list of items.
19.Scrollbar: A component that provides a scrollbar
for a container.
20. Canvas: A component that provides a drawing
surface.
GUI PROGRAMMING• 126
ARCHIES GURAV
- Let's Create a GUI with AWT: To create a GUI with
AWT, we need to create instances of various classes
such as Frame, Button, Label, TextField, etc. Here is an
example of how to create a simple GUI with AWT:
- Here, we have created a Frame object that
represents the main window of the application. We
have also created a Button, a Label, and a TextField.
Then, we have added these components to the Frame
using the add() method. Finally, we have set the layout
of the Frame to FlowLayout and set its size and
visibility.
Introduction to Swing:
- Swing was introduced later, and it provides a
complete set of tools to create a more sophisticated
and flexible interface.
- Swing is built on top of AWT, and it uses its own set of
components, which makes it platform-independent.
GUI PROGRAMMING• 127
ARCHIES GURAV
- Let's know what do each interface and class of AWT
toolkit perform:
1. JFrame - A top-level container that represents the
main window of a GUI application.
2. JPanel - A container that holds other Swing
components.
3. JButton - A component that represents a clickable
button.
4. JLabel - A component that displays text or an
image.
5. JTextField - A component that allows the user to
input a single line of text.
6. JPasswordField - A component that allows the
user to input a password.
7. JComboBox - A component that allows the user to
select an item from a list.
8. JList - A component that displays a list of items.
9. JTable - A component that displays data in a
tabular format.
10. JScrollPane - A container that provides scrolling
capabilities for a component that is too large to fit
in a container.
11. ActionListener - An interface that defines a
method for handling action events, such as button
clicks.
GUI PROGRAMMING• 128
ARCHIES GURAV
12. MouseListener - An interface that defines
methods for handling mouse events, such as mouse
clicks and mouse movement.
13. KeyListener - An interface that defines methods
for handling keyboard events, such as key presses and
releases.
14. SwingUtilities - A utility class that provides
methods for working with Swing components on the
event dispatch thread.
15. UIManager - A class that provides access to the
look and feel of a Swing application.
- Let's create a GUI with Swing: To create a GUI with
Swing, we need to create instances of various classes
such as JFrame, JButton, JLabel, JTextField, etc. Here is
an example of how to create a simple GUI with Swing:
- Here, we have created a JFrame object that
represents the main window of the application. We
have also created a JButton, a JLabel, and a JTextField.
GUI PROGRAMMING• 129
ARCHIES GURAV
- Then, we have added these components to the
JFrame using the add() method. Finally, we have set the
layout of the JFrame to FlowLayout and set its size and
visibility.
Difference between AWT and Swing:
AWT
- AWT is the oldest GUI library introduced by Java.
- AWT is based on native components, which means
that it uses the platform's native components to
create a GUI. This makes it more efficient in terms of
performance, but it also means that the look and feel
of the GUI can vary between platforms.
- AWT components are heavyweight.
- AWT is more efficient in terms of performance.
Swing
- Swing is a more advanced and newer GUI library.
- Swing is based on a set of Java classes and
provides a consistent look and feel across all platforms.
- This is because the components are created using
pure Java code, rather than relying on the platform's
native components
- Swing components are lightweight and offers a
more consistent look and feel and greater flexibility in
creating a GUI.
GUI PROGRAMMING• 130
ARCHIES GURAV
Event Handling in Swing and AWT
- Event handling is an important part of GUI
programming in Java. Events are user actions such as
button clicks, mouse movements, and key presses. In
Swing and AWT, events are handled using event
listeners. An event listener is an object that is notified
when an event occurs.
- Here's an example of how to add an event listener to
a button in Swing:
- In this example, an anonymous inner class is used to
define an ActionListener object and pass it to the
addActionListener() method of the button. The
actionPerformed() method of the ActionListener object
will be called when the button is clicked.
Layout Managers in Swing and AWT
- Layout managers are used to arrange the
components in a GUI. Swing and AWT provide several
layout managers that can be used to arrange
components in different ways. Some of the commonly
used layout managers are:
GUI PROGRAMMING• 131
ARCHIES GURAV
BorderLayout: Arranges the components in the
north, south, east, west, and center regions of the
container.
FlowLayout: Arranges the components in a row,
wrapping them to the next row when the
container's width is exceeded.
GridLayout: Arranges the components in a grid of
rows and columns.
BoxLayout: Arranges the components in a row or
column.
- Here's an example of how to use the BorderLayout
manager to arrange components in a frame:
- In this example, the buttons are added to different
regions of the frame using the add() method and
specifying the region using the constants provided by
BorderLayout.
GUI PROGRAMMING• 132
ARCHIES GURAV
HANDS-ON ASSIGNMENTS
ON THIS TOPIC:
1. Create a swing application to display a list of
customers with their details such as name, address,
and phone number. Allow the user to add, edit, and
delete customers.
2. Create a swing application to display username
textfield and password field with a Login Button.
3. Create a swing application that allows the user to
enter a time in hours, minutes, and seconds, and
then display the time in 24-hour format.
4. Create a swing application that allows the user to
enter a sentence and then display the sentence with
each word reversed.
5. Create a swing application that allows the user to
enter a number and then display the binary, octal,
and hexadecimal representations of that number.
6. Create a swing application that allows the user to
enter a number and then display the factorial of that
number.
GUI PROGRAMMING• 133
ARCHIES GURAV
JAVA PROJECTS
1. Employee Management System: Create a system
that allows the user to add, edit, and delete
employees, and search for employees by name,
department, or position using Collection Framework
2. Currency Convertor: Create a program that can
convert between different currencies using
exchange rates
3. Contact Management System: Create a system
that allows the user to add, edit, and delete contacts,
and search for contacts by name using JDBC.
4. Quiz Game: Create a multiple-choice quiz game
where the user has to select the correct answer from
a set of options.
JAVA PROJECTS• 134
ARCHIES GURAV