0% found this document useful (0 votes)
4 views40 pages

Java

Uploaded by

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

Java

Uploaded by

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

JAVA SUMMER TRAINING REPORT

CHAPTER-1
BASICS OF JAVA

1,1 Introduction to Java

Java is a widely used programming language known for platform independence, robustness,
and strong object-oriented principles. Developed by Sun Microsystems in the 1990s, Java is
now maintained by Oracle Corporation. It has become crucial in developing enterprise
solutions, web, and mobile applications due to its versatility and scalability.

During this summer training, we explored Java's syntax, structure, and core programming
concepts, establishing a foundation for future development.

1.2 History of Java

Java originated in 1991 as part of the Green Project by James Gosling's team at Sun
Microsystems. Initially called "Oak," it was aimed at consumer electronics. In 1995, it was
renamed "Java" and gained popularity for its "Write Once, Run Anywhere" (WORA)
capability. Java 1.0 was launched in 1996, and Sun made it open-source in 2006. Oracle
acquired Sun Microsystems in 2010, continuing Java's evolution with regular updates.

1.3 Features of Java

Java's widespread use is due to features like:

• OOP: Enables modular and reusable code through inheritance, polymorphism, and
encapsulation.
• Platform Independence: Java bytecode can run on any system with a JVM.
• Simplicity: Clean syntax and the absence of pointers make it easy to learn.
• Security: Built-in security features protect against unauthorized access.
• Multithreading: Supports concurrent execution of multiple threads.
• Robustness: Strong error handling and memory management.
• High Performance: Just-In-Time (JIT) compiler improves performance.
• Distributed Computing: Supports RMI and EJB for distributed applications.
• Dynamic: Allows runtime linking of new code.

Figure 1-Features of Java

SAMRIDH PALLEDA 23100010095 1


JAVA SUMMER TRAINING REPORT

1.4 Comparison of Java with C++

Feature Java C++


Platform Requires recompilation for different
JVM enables WORA.
Independence platforms.
Memory
Automatic garbage collection. Manual memory management.
Management
No explicit pointers, enhancing Supports pointers, allowing direct
Pointers
security. memory access.
Direct multiple inheritance, adding
Multiple Inheritance Achieved via interfaces.
complexity.
Slower due to bytecode Faster due to direct machine code
Execution
interpretation. execution.
Multithreading Built-in support. Requires manual handling.

1.5 JDK, JRE, and JVM

To develop and run Java applications, it is essential to understand the Java environment's key
components: the Java Development Kit (JDK), Java Runtime Environment (JRE), and Java
Virtual Machine (JVM). These components work together to provide a comprehensive
development and execution environment for Java programs.

• JDK (Java Development Kit): A complete toolkit for Java development, including
the JRE, a compiler (javac), and tools for building, debugging, and packaging Java
applications.

• JRE (Java Runtime Environment): Provides the runtime environment for executing
Java applications, including the JVM and core libraries. It does not include development
tools.

• JVM (Java Virtual Machine): Executes Java bytecode by converting it to native


machine code. It manages memory, handles garbage collection, and ensures consistent
execution across platforms.

Figure 2 - Java Development Kit Diagram

SAMRIDH PALLEDA 23100010095 2


JAVA SUMMER TRAINING REPORT

1.6 Data Types in Java

Data types are fundamental to any programming language, as they define the type of data that
can be stored and manipulated in a program. Java supports both primitive and non-primitive
data types, each serving different purposes in application development.

• Primitive Data Types: Java has eight primitive data types, each designed to store a
specific type of data:
o byte: An 8-bit signed integer, ranging from -128 to 127. It is often used to save
memory in large arrays where memory savings are critical.
o short: A 16-bit signed integer, ranging from -32,768 to 32,767. It is used when a
wider range than byte is needed but memory savings are still important.
o int: A 32-bit signed integer, ranging from -2^31 to 2^31-1. It is the most
commonly used data type for numeric values.
o long: A 64-bit signed integer, ranging from -2^63 to 2^63-1. It is used when a
wider range than int is required.
o float: A single-precision 32-bit floating point, used for decimal values. It is less
precise than double but consumes less memory.
o double: A double-precision 64-bit floating point, used for precise decimal
values. It is the default choice for decimal values in Java.
o char: A single 16-bit Unicode character, used to store individual characters such
as letters and symbols.
o boolean: A data type with only two possible values: true and false. It is used
for conditional logic and control flow.
• Non-Primitive Data Types: Non-primitive data types, also known as reference types,
include classes, arrays, interfaces, and more. These types are created by the programmer
and can store complex data structures and objects. Unlike primitive types, non-primitive
types do not hold the actual data but rather a reference to the data in memory.
o Example: A class is a blueprint for creating objects that encapsulate data and
behavior. Arrays are collections of variables of the same type, stored in
contiguous memory locations.

1.7 Variables in Java

Variables are fundamental components of any programming language, acting as containers for
storing data values. In Java, variables must be declared with a specific type, ensuring that the
data stored in them is type-safe and consistent with the intended use.

• Variable Declaration and Initialization:

In Java, variables are declared by specifying the data type followed by the variable
name. They can be initialized with a value at the time of declaration or assigned a value
later in the program.

SAMRIDH PALLEDA 23100010095 3


JAVA SUMMER TRAINING REPORT

o Example:

int age = 25; // Declaration and initialization


String name = "John"; // Declaration and initialization
double salary; // Declaration without initialization
salary = 50000.50; // Assignment of value later

In this example, age is an integer variable initialized with the value 25, name is a
string variable initialized with "John," and salary is a double variable declared
first and assigned a value later.

• Types of Variables:

Java supports three types of variables:

o Local Variables: These are declared inside a method, constructor, or block and
are accessible only within that scope. Local variables must be initialized before
use.
o Instance Variables: Also known as non-static fields, instance variables are
declared within a class but outside any method or block. Each object of the class
has its own copy of instance variables.
o Class Variables: Also known as static fields, class variables are declared with
the static keyword within a class but outside any method or block. They are
shared among all instances of the class.

Arrays in Java

Arrays in Java are a powerful data structure that allows developers to store and manage
collections of elements of the same type. Arrays are particularly useful for storing large
quantities of data that need to be processed or manipulated in a consistent manner.

• Array Declaration and Initialization:

Arrays in Java are declared by specifying the data type of the elements followed by
square brackets. They can be initialized at the time of declaration or later in the
program.

o Example:

int[] numbers = {1, 2, 3, 4, 5}; // Declaration and


initialization
String[] names = new String[3]; // Declaration with specified
size
names[0] = "John"; // Initialization later
names[1] = "Jane";
names[2] = "Tom";

SAMRIDH PALLEDA 23100010095 4


JAVA SUMMER TRAINING REPORT

In this example, numbers is an array of integers initialized with values, while


names is an array of strings declared with a size of 3 and initialized later.

• Accessing Array Elements:

Array elements are accessed using an index, with the first element at index 0. Elements
can be retrieved or modified using this index.

o Example:

int firstNumber = numbers[0]; // Accessing the first element


names[1] = "Alice"; // Modifying the second
element

In this example, the first element of the numbers array is retrieved and stored in
firstNumber, and the second element of the names array is modified.

• Multi-Dimensional Arrays:

Java supports multi-dimensional arrays, which are arrays of arrays. The most common
type is a two-dimensional array, often used to represent matrices or grids.

o Example:

int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};

In this example, matrix is a two-dimensional array representing a 3x3 matrix.

1.8 Operators in Java

Operators are special symbols in Java that perform operations on variables and values. They are
an essential part of any programming language, allowing developers to perform arithmetic,
compare values, and control the flow of a program.

• Arithmetic Operators: Used for basic mathematical operations such as addition,


subtraction, multiplication, division, and modulus.
o Example:

int sum = 10 + 5; // Addition


int difference = 10 - 5; // Subtraction
int product = 10 * 5; // Multiplication
int quotient = 10 / 5; // Division
int remainder = 10 % 3; // Modulus

SAMRIDH PALLEDA 23100010095 5


JAVA SUMMER TRAINING REPORT

• Relational Operators: Used to compare two values and determine their relationship,
such as equal to, not equal to, greater than, less than, greater than or equal to, and less
than or equal to.
o Example:

boolean isEqual = (10 == 5); // false


boolean isNotEqual = (10 != 5); // true
boolean isGreater = (10 > 5); // true
boolean isLessOrEqual = (10 <= 5); // false

• Logical Operators: Used to combine multiple conditions, including AND, OR, and
NOT.
o Example:

boolean result = (10 > 5) && (5 < 8); // true


boolean orResult = (10 > 5) || (5 > 8); // true
boolean notResult = !(10 > 5); // false

• Assignment Operators: Used to assign values to variables. The basic assignment


operator is =, but Java also supports compound assignments, such as +=, -=, *=, /=, and
%=.
o Example:

int a = 10;
a += 5; // Equivalent to a = a + 5;

• Unary Operators: Used with a single operand to perform operations such as


increment, decrement, negation, and logical complement.
o Example:

int x = 10;
x++; // Increment
x--; // Decrement
int y = -x; // Negation
boolean z = !true; // Logical complement

1.9 Control Structures in Java

Control structures are fundamental constructs in programming that dictate the flow of execution
based on conditions and loops. Java provides several control structures that allow developers to
create complex and dynamic programs.

• If-Else Statement: The if-else statement allows the execution of specific code blocks
based on a condition. If the condition is true, the code within the if block is executed;
otherwise, the code within the else block is executed.

SAMRIDH PALLEDA 23100010095 6


JAVA SUMMER TRAINING REPORT

o Example:

int num = 10;


if (num > 0) {
System.out.println("Positive number");
} else {
System.out.println("Negative number");
}

In this example, the program checks whether the variable num is greater than 0
and prints the appropriate message.

• Switch Statement: The switch statement is used for selecting one of many code blocks
to be executed based on the value of a variable. It provides a cleaner alternative to
multiple if-else statements when dealing with multiple possible values.
o Example:

int day = 2;
String dayName;
switch (day) {
case 1:
dayName = "Monday";
break;
case 2:
dayName = "Tuesday";
break;
case 3:
dayName = "Wednesday";
break;
default:
dayName = "Invalid day";
break;
}
System.out.println(dayName);

In this example, the switch statement checks the value of day and assigns the
corresponding day name to the variable dayName.

• For Loop: The for loop is used to execute a block of code repeatedly for a fixed
number of times. It is commonly used when the number of iterations is known
beforehand.
o Example:

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


System.out.println("Iteration: " + i);
}

In this example, the for loop runs five times, printing the iteration number in
each pass.

SAMRIDH PALLEDA 23100010095 7


JAVA SUMMER TRAINING REPORT

• While Loop: The while loop executes a block of code as long as the specified condition
is true. It is typically used when the number of iterations is not known beforehand.
o Example:

int i = 1;
while (i <= 5) {
System.out.println("Iteration: " + i);
i++;
}

In this example, the while loop runs until the variable i exceeds 5.

• Do-While Loop: The do-while loop is similar to the while loop, but it guarantees that
the block of code is executed at least once before checking the condition.
o Example:

int i = 1;
do {
System.out.println("Iteration: " + i);
i++;
} while (i <= 5);

In this example, the do-while loop ensures that the code is executed once before
checking the condition.

1.10 Installing Java

Java is a widely used programming language, and before we start coding in Java, we need to
install the Java Development Kit (JDK). The JDK includes tools required for developing Java
applications, including the Java Runtime Environment (JRE), which allows Java programs
to run, and tools such as the compiler (javac) and the debugger.

➔ Steps to Install Java (JDK)

1. Download JDK:
o Visit the official Oracle website to download the latest version of the JDK:
Oracle JDK Downloads.
o Select the appropriate version of the JDK for your operating system (Windows,
macOS, or Linux).
2. Run the Installer:
o After downloading the installer, run it. The installer will guide you through the
installation process.
o You may be prompted to set the installation path. The default location is
typically sufficient, but you can change it if necessary.
SAMRIDH PALLEDA 23100010095 8
JAVA SUMMER TRAINING REPORT

3. Set Up Environment Variables:


o After installation, you must set up the JAVA_HOME environment variable to point
to the JDK folder. This step is essential to ensure Java works properly with other
tools on your system.
▪ Windows:
▪ Right-click on "This PC" or "My Computer," select "Properties,"
then "Advanced system settings."
▪ Click "Environment Variables," then click "New" under "System
Variables."
▪ Name the variable JAVA_HOME and set the value to the path where
the JDK is installed (e.g., C:\Program Files\Java\jdk-
xx.x.x).

▪ Edit the Path variable and add %JAVA_HOME%\bin.


4. Verify the Installation:
o To confirm that Java has been installed correctly, open a command prompt (or
terminal) and run the following command:

java -version

o This will display the version of Java that is installed. If the version is displayed
correctly, the installation is successful.

1.11 Installing Visual Studio Code (VSCode) for Java

Visual Studio Code (VSCode) is a popular, lightweight Integrated Development Environment


(IDE) that supports various programming languages, including Java, through extensions. It is
free, open-source, and customizable, making it an excellent choice for Java development.

➔ Steps to Install Visual Studio Code

1. Download VSCode:
o Visit the official Visual Studio Code website: VSCode Downloads.
o Choose the version for your operating system (Windows, macOS, or Linux) and
download the installer.
2. Install VSCode:
o After downloading, run the installer and follow the setup instructions.

SAMRIDH PALLEDA 23100010095 9


JAVA SUMMER TRAINING REPORT

o During the installation process, you can choose to create a desktop shortcut and
register VSCode in the system's PATH for easier access from the command line.
o After installation, launch VSCode.

➔ Setting Up Java in VSCode

Once VSCode is installed, you need to install the Java extension to enable Java development
features.

1. Install Java Extensions in VSCode:


o Open VSCode and go to the Extensions panel (by clicking on the Extensions
icon in the sidebar or pressing Ctrl+Shift+X).
o Search for "Java Extension Pack" and click "Install." The Java Extension Pack
includes several tools like:
▪ Language Support for Java™ by Red Hat
▪ Debugger for Java
▪ Java Test Runner
▪ Maven for Java
o This extension pack provides features like IntelliSense (code completion),
debugging, testing, and project management for Java development.
2. Configure the Java Environment in VSCode:
o After installing the Java extension pack, VSCode will automatically detect the
JDK installed on your machine.
o If the JDK is not detected, ensure that the JAVA_HOME environment variable is
correctly set (as mentioned earlier in the JDK installation process).
o You can verify the JDK configuration in VSCode by opening the Command
Palette (Ctrl+Shift+P) and typing "Java: Configure Java Runtime." This will
show the detected JDKs and allow you to configure settings like runtime paths.
3. Creating Your First Java Project:
o To create a Java project, you can use the "Java: Create Java Project" command
from the Command Palette (Ctrl+Shift+P).
o Select a template for your project (No Build Tools, Maven, or Gradle).
o VSCode will create a basic structure for your Java project, and you can start
coding in the src folder.
4. Running Java Programs in VSCode:

SAMRIDH PALLEDA 23100010095 10


JAVA SUMMER TRAINING REPORT

o You can run Java programs directly from VSCode. Open the .java file
containing the main method and click the "Run" button at the top of the file or
press F5 to run your program.
o VSCode will compile and execute your code, and the output will be shown in
the integrated terminal.

Figure 3- Compilation of Java Program

SAMRIDH PALLEDA 23100010095 11


JAVA SUMMER TRAINING REPORT

CHAPTER-2
OBJECT-ORIENTED PROGRAMMING CONCEPTS

Object-Oriented Programming (OOP)

Object-Oriented Programming (OOP) is a programming paradigm that is based on the


concept of "objects." Objects are instances of classes, which encapsulate both data (attributes)
and methods (functions or procedures) that operate on the data. OOP allows developers to
structure their code in a more modular, reusable, and organized way.

The main concepts of OOP are:

2.1 Class

A class is a blueprint or template for creating objects. It defines the attributes and methods that
the objects of the class will have. A class provides structure but does not allocate memory for
any data.

• Example:

class Dog {
String name;
int age;

void bark() {
System.out.println(name + " is barking.");
}
}

In this example, Dog is a class with two attributes (name and age) and one method
(bark).

2.2 Object

An object is an instance of a class. When a class is defined, no memory is allocated until an


object of that class is created. Objects represent real-world entities with specific characteristics
and behaviors.

• Example:

Dog dog1 = new Dog(); // Object creation


dog1.name = "Buddy"; // Setting attribute values
dog1.age = 3;
dog1.bark(); // Calling a method

In this example, dog1 is an object of the Dog class, and the method bark is called on it.

SAMRIDH PALLEDA 23100010095 12


JAVA SUMMER TRAINING REPORT

2.3 Encapsulation

Encapsulation is the concept of wrapping data (variables) and code (methods) together as a
single unit. It restricts direct access to the data by using access modifiers like private, and
provides controlled access through getter and setter methods. This protects the integrity of the
object's data.

• Example:

class BankAccount {
private double balance;

public void deposit(double amount) {


balance += amount;
}

public double getBalance() {


return balance;
}
}

Here, the balance attribute is encapsulated within the BankAccount class, and access to
it is provided only through methods like getBalance().

2.4 Inheritance

Inheritance is a mechanism in which one class (child/subclass) inherits the properties and
behaviors (attributes and methods) of another class (parent/superclass). It promotes code
reusability.

• Example:

class Animal {
void eat() {
System.out.println("This animal is eating.");
}
}

class Dog extends Animal {


void bark() {
System.out.println("The dog is barking.");
}
}

In this example, the Dog class inherits from the Animal class, meaning that a Dog object
can use both the eat method from the Animal class and its own bark method.

SAMRIDH PALLEDA 23100010095 13


JAVA SUMMER TRAINING REPORT

2.5 Polymorphism

Polymorphism allows objects of different classes to be treated as objects of a common


superclass. It refers to the ability of different objects to respond in their own way to the same
method call. There are two types of polymorphism in Java:

• Compile-Time Polymorphism (Method Overloading): When multiple methods have


the same name but different parameter lists.
o Example:

class Calculator {
int add(int a, int b) {
return a + b;
}

double add(double a, double b) {


return a + b;
}
}

• Run-Time Polymorphism (Method Overriding): When a subclass provides its own


implementation of a method that is already defined in the superclass.
o Example:

class Animal {
void sound() {
System.out.println("This animal makes a sound.");
}
}

class Dog extends Animal {


@Override
void sound() {
System.out.println("The dog barks.");
}
}

class Cat extends Animal {


@Override
void sound() {
System.out.println("The cat meows.");
}
}

public class Main {


public static void main(String[] args) {
Animal myAnimal = new Dog(); // Upcasting
myAnimal.sound(); // Output: The dog barks.
}
}

SAMRIDH PALLEDA 23100010095 14


JAVA SUMMER TRAINING REPORT

2.6 Abstraction

Abstraction is the concept of hiding the complex implementation details of a system and
exposing only the essential features. It helps in reducing complexity and increasing efficiency.
In Java, abstraction can be achieved through abstract classes and interfaces.

• Abstract Class: A class that cannot be instantiated and may contain abstract methods
(methods without a body).
o Example:

abstract class Shape {


abstract void draw();
}

class Circle extends Shape {


@Override
void draw() {
System.out.println("Drawing a circle.");
}
}

public class Main {


public static void main(String[] args) {
Shape shape = new Circle();
shape.draw();
}
}

SAMRIDH PALLEDA 23100010095 15


JAVA SUMMER TRAINING REPORT

CHAPTER-3
INTERFACES

In Java, Interfaces and Packages are key components that enhance code structure,
organization, and reusability. Interfaces allow for multiple inheritance and abstraction, while
packages provide a way to group related classes and manage namespaces.

3.1 Interface Basics

An interface in Java is a reference type, similar to a class, that can contain only constants,
method signatures, default methods, static methods, and nested types. Methods in an interface
are implicitly abstract (unless they are default or static methods).

Interfaces define a contract that classes must adhere to but do not provide implementation.
They are particularly useful for achieving abstraction and enabling multiple inheritance.

• Defining an Interface:

interface Animal {
void sound(); // Method signature, no body
}

In this example, Animal is an interface with the abstract method sound().

Implementing and Extending Interfaces

A class can implement an interface using the implements keyword and provide concrete
implementations of the methods declared in the interface.

• Example:

class Dog implements Animal {


public void sound() {
System.out.println("Dog barks");
}
}

In this case, the Dog class implements the Animal interface and provides a body for the
sound() method.

Interfaces can also extend other interfaces, allowing for hierarchical inheritance.

• Example:

interface Mammal extends Animal {


void feed();
}

Here, the Mammal interface extends Animal and adds a new method feed().

SAMRIDH PALLEDA 23100010095 16


JAVA SUMMER TRAINING REPORT

Differences Between Classes and Interfaces

Feature Class Interface


Contains both data members (variables) Contains only method signatures
Implementation
and methods with implementation. (no implementation).
Can be instantiated (objects can be Cannot be instantiated directly
Instantiation
created). (no objects).
Multiple Supports multiple inheritance
Does not support multiple inheritance.
Inheritance through implements.
Access Modifiers Can have any access modifier. Methods are public by default.

Implementing Multiple Inheritance Using Interfaces

Java does not support multiple inheritance with classes, but it allows a class to implement
multiple interfaces, enabling a form of multiple inheritance. A class can implement more than
one interface by separating them with commas.

• Example:

interface Walkable {
void walk();
}

interface Runnable {
void run();
}

class Person implements Walkable, Runnable {


public void walk() {
System.out.println("Person is walking");
}

public void run() {


System.out.println("Person is running");
}
}

In this example, the Person class implements both Walkable and Runnable interfaces,
providing implementations for both walk() and run() methods.

SAMRIDH PALLEDA 23100010095 17


JAVA SUMMER TRAINING REPORT

CHAPTER-4
EXCEPTION HANDLING

In Java, Exception Handling is a mechanism that allows developers to manage runtime errors,
ensuring the normal flow of the application even when unexpected events occur. Exception
handling enables you to write more robust and error-tolerant programs.

Java uses five main keywords for exception handling: try, catch, throw, throws, and
finally. These keywords help manage exceptions gracefully without crashing the program.

4.1 Exception Handling Keywords

1. try:
o The try block contains the code that might throw an exception. If an exception
occurs within this block, it is handled by a corresponding catch block.
o Syntax:

try {
// code that may throw an exception
}

2. catch:
o The catch block is used to handle the exception. It specifies what to do when a
particular type of exception is thrown from the try block.
o Syntax:

catch (ExceptionType e) {
// handle exception
}

3. throw:
o The throw keyword is used to explicitly throw an exception. It can be used to
throw both checked and unchecked exceptions.
o Syntax:

throw new ExceptionType("Error Message");

4. throws:
o The throws keyword is used in the method signature to declare exceptions that a
method might throw. This alerts the caller of the method to handle the
exceptions.
o Syntax:

public void method() throws ExceptionType {


// code
}

5. finally:
SAMRIDH PALLEDA 23100010095 18
JAVA SUMMER TRAINING REPORT

o The finally block contains code that is always executed after the try block,
regardless of whether an exception occurred or not. It is typically used for
resource cleanup, like closing files or releasing memory.
o Syntax:

finally {
// code that will always execute
}

4.2 Basic Example of Exception Handling

public class ExceptionExample {


public static void main(String[] args) {
try {
int division = 10 / 0; // This will throw ArithmeticException
System.out.println(division);
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero!");
} finally {
System.out.println("Execution completed.");
}
}
}

• Output:

Cannot divide by zero!


Execution completed.

In this example:

• The try block contains code that may throw an exception (10 / 0).
• The catch block handles the ArithmeticException by displaying a message.
• The finally block ensures that the message "Execution completed." is printed
regardless of the exception.

Nested try Blocks

In Java, try blocks can be nested, meaning that you can place a try block within another try
block. This is useful when you need to handle different exceptions separately within the same
method.

• Example:

public class NestedTryExample {


public static void main(String[] args) {
try {
try {
int array[] = new int[5];
array[7] = 10; // This will throw
ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array index out of bounds!");

SAMRIDH PALLEDA 23100010095 19


JAVA SUMMER TRAINING REPORT

int division = 10 / 0; // This will throw


ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero!");
}
}
}

• Output:

Array index out of bounds!


Cannot divide by zero!

Here, the inner try block handles the ArrayIndexOutOfBoundsException, while the outer
try block handles the ArithmeticException.

Multiple catch Statements

A single try block can have multiple catch blocks to handle different types of exceptions.
Each catch block is used to handle a specific exception type.

• Example:

public class MultipleCatchExample {


public static void main(String[] args) {
try {
int[] array = new int[5];
array[7] = 10; // This will throw
ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array index out of bounds!");
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero!");
} catch (Exception e) {
System.out.println("A general exception occurred!");
}
}
}

• Output:

Array index out of bounds!

In this case, the ArrayIndexOutOfBoundsException is caught by the first catch block, and
the program continues without interruption. If any other exception occurs, it would be caught
by the relevant catch block.

CHAPTER-5

SAMRIDH PALLEDA 23100010095 20


JAVA SUMMER TRAINING REPORT

MULTITHREADING

Multithreading is a feature of Java that allows concurrent execution of two or more parts of a
program, known as threads. Each thread runs in parallel, enabling more efficient utilization of
the CPU and improving the overall performance of applications, especially those requiring
multitasking.

5.1 Differences Between Multithreading and Multitasking

Feature Multithreading Multitasking


Involves running multiple threads Involves running multiple processes
Definition
within a single process. simultaneously.
Resource Threads share the same memory and Each process runs independently with
Usage resources of the process. its own memory space.
Less overhead since threads are lighter More overhead due to process creation
Overhead
and share resources. and resource allocation.
Faster as threads share memory and Slower due to process isolation and
Speed
resources. memory management.
Context Switching between threads is quicker Switching between processes is
Switching than switching between processes. relatively slow.
A web browser running multiple tabs Running multiple applications like a
Example
as threads. browser, editor, etc., simultaneously.

5.2 Thread Life Cycle

In Java, threads go through various states during their execution, collectively known as the
Thread Life Cycle. The five main states of a thread are:

1. New: The thread is created but not yet started.


2. Runnable: The thread is ready to run and waiting for CPU time.
3. Running: The thread is actively executing.
4. Blocked (Waiting): The thread is waiting for some condition to be met or for resources
to be released.
5. Terminated: The thread has completed its execution or is stopped due to an error.

SAMRIDH PALLEDA 23100010095 21


JAVA SUMMER TRAINING REPORT

The following diagram illustrates the thread life cycle:

Figure 4- Lifecycle of a Java Thread

5.3 Creating Threads

In Java, threads can be created in two ways:

1. By Extending the Thread Class


o Example:

class MyThread extends Thread {


public void run() {
System.out.println("Thread is running...");
}
}

public class Main {


public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start(); // Starts the thread
}
}

2. By Implementing the Runnable Interface


o Example:

class MyRunnable implements Runnable {


public void run() {
System.out.println("Thread is running...");
}
}

public class Main {


public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable);
thread.start(); // Starts the thread
}

SAMRIDH PALLEDA 23100010095 22


JAVA SUMMER TRAINING REPORT

The start() method is used to start the execution of a thread, which calls the run() method
internally.

5.4 Synchronizing Threads

When multiple threads try to access shared resources, there can be conflicts that result in
inconsistent data. Synchronization in Java is used to control access to shared resources by
multiple threads, ensuring that only one thread can access the resource at a time.

• Synchronized Block: You can use a synchronized block to lock a particular section of
code that accesses the shared resource.
o Example:

class Counter {
private int count = 0;

public synchronized void increment() {


count++;
}

public int getCount() {


return count;
}
}

public class Main {


public static void main(String[] args) throws
InterruptedException {
Counter counter = new Counter();

Thread t1 = new Thread(() -> {


for (int i = 0; i < 1000; i++) {
counter.increment();
}
});

Thread t2 = new Thread(() -> {


for (int i = 0; i < 1000; i++) {
counter.increment();
}
});

t1.start();
t2.start();

t1.join();
t2.join();

System.out.println("Count: " + counter.getCount());


//Output:2000
}
}

In this example, the increment() method is synchronized to ensure that only one thread can
increment the counter at a time, preventing race conditions.

SAMRIDH PALLEDA 23100010095 23


JAVA SUMMER TRAINING REPORT

5.5 Daemon Threads

A daemon thread in Java is a background thread that runs in parallel with the main thread. Its
lifecycle depends on the main thread. Once all non-daemon threads finish execution, the JVM
automatically terminates daemon threads.

Daemon threads are typically used for background tasks such as garbage collection,
monitoring, or other low-priority tasks.

• Example:

public class DaemonThreadExample {


public static void main(String[] args) {
Thread daemonThread = new Thread(() -> {
while (true) {
System.out.println("Daemon thread running...");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});

daemonThread.setDaemon(true);
daemonThread.start();

try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}

System.out.println("Main thread finished");


}
}

In this example, the daemonThread is a daemon thread that runs in the background until the
main thread finishes execution.

SAMRIDH PALLEDA 23100010095 24


JAVA SUMMER TRAINING REPORT

CHAPTER-6
AWT

Abstract Window Toolkit (AWT) is a Java package that provides classes for creating
graphical user interfaces (GUIs) and handling user input through events. AWT is part of the
Java Foundation Classes (JFC) and was the first set of APIs in Java used for GUI development.
It allows developers to create windows, buttons, menus, and other UI elements.

While AWT was one of the earliest GUI frameworks in Java, it has limitations, such as being
platform-dependent, meaning that the appearance of components can vary across different
operating systems. Later, Swing was introduced to address these limitations, but AWT remains
important for creating lightweight applications.

6.1 Key Features of AWT

1. Platform-Dependent Components: AWT uses native GUI components of the


operating system, leading to differences in appearance and behavior across platforms.
2. Lightweight: AWT provides basic GUI components, making it suitable for smaller, less
complex applications.
3. Event-Driven Programming: AWT follows an event-driven programming model
where user actions, like clicks or key presses, generate events that the program handles.
4. Event Delegation Model: AWT uses the Delegation Event Model, where events are
passed to listeners (handlers) responsible for processing them.

6.2 AWT Class Hierarchy

AWT components are derived from the java.awt package. Below is a brief look at the
hierarchy of some essential classes in AWT:

• Component: The base class for all AWT components.


• Container: A subclass of Component, this class can contain other components.
o Panel: A generic container for holding components.
o Window: The top-level container for windows.
▪ Frame: A window with a title and border.
▪ Dialog: A pop-up window for user interaction.
• Button: Represents a clickable button.
• TextField: A single-line text input field.
• Label: A non-editable text or image display.
• Checkbox: A box that can be checked or unchecked.
• List: A component that allows the user to select one or more items from a list.

6.3 Basic AWT Components

Here are some commonly used AWT components:

1. Button: A button component that can trigger an action when clicked.

Button button = new Button("Click Me");

SAMRIDH PALLEDA 23100010095 25


JAVA SUMMER TRAINING REPORT

2. Label: Displays a text label.

Label label = new Label("This is a label");

3. TextField: Allows the user to enter text.

TextField textField = new TextField("Enter text here", 20);

4. Checkbox: Allows the user to select/deselect an option.

Checkbox checkbox = new Checkbox("Accept Terms");

5. List: Displays a list of items from which the user can select.

List list = new List();


list.add("Item 1");
list.add("Item 2");

6.4 Creating GUI Applications Using AWT

To create GUI applications using AWT, you can combine components like buttons, labels, text
fields, and panels to form a user interface. You can also handle user actions using event
listeners.

• Example of a Simple AWT GUI Application:

import java.awt.*;
import java.awt.event.*;

public class SimpleAWTApp extends Frame implements ActionListener {


TextField textField;

public SimpleAWTApp() {
// Create components
Label label = new Label("Enter your name:");
label.setBounds(50, 50, 100, 30);

textField = new TextField();


textField.setBounds(160, 50, 150, 30);

Button button = new Button("Submit");


button.setBounds(160, 100, 80, 30);

// Register listener for the button


button.addActionListener(this);

// Add components to the frame


add(label);
add(textField);
add(button);

// Frame settings
setSize(400, 200);
setLayout(null);
setVisible(true);
}

SAMRIDH PALLEDA 23100010095 26


JAVA SUMMER TRAINING REPORT

public void actionPerformed(ActionEvent e) {


String name = textField.getText();
System.out.println("Name entered: " + name);
}

public static void main(String[] args) {


new SimpleAWTApp();
}
}

In this example:

• A Frame is created with a Label, TextField, and Button.


• The Button has an ActionListener that handles the button click event.
• When the button is clicked, the entered text is printed to the console.

OUTPUT:

Figure 5 - Output of ActionListener and Frame Program

SAMRIDH PALLEDA 23100010095 27


JAVA SUMMER TRAINING REPORT

CHAPTER-7
JAVA SWING

Swing is a part of Java’s Java Foundation Classes (JFC) used to create window-based
applications. Unlike AWT, which is platform-dependent, Swing is built on top of AWT and
provides a more flexible, lightweight, and platform-independent framework for building
graphical user interfaces (GUIs). Swing offers more sophisticated and customizable
components for creating rich, user-friendly interfaces.

7.1 Introduction to Swing

Swing is a powerful GUI toolkit that extends AWT and includes a wide range of components
such as buttons, checkboxes, labels, and more complex components like trees and tables. Some
features of Swing include:

• Lightweight Components: Swing components are entirely written in Java, making


them platform-independent.
• Pluggable Look and Feel: Swing allows users to change the appearance of applications
at runtime.
• MVC Architecture: Swing follows the Model-View-Controller (MVC) architecture,
ensuring separation of data and UI components.

7.2 Exploring Swing

Swing provides various components that are subclasses of JComponent, a base class for all
Swing components. Some of the key Swing components include JApplet, JFrame, and
JComponent.

• JApplet: A Swing version of AWT's Applet. It is used for creating applets (though
modern applications generally use JavaFX for this).
• JFrame: The top-level container for creating a window. It contains other Swing
components and can have a title bar, border, and buttons to close, minimize, or
maximize.
• JComponent: The base class for all Swing components. Most Swing components, such
as buttons, labels, and text fields, inherit from JComponent.

7.3 Icons and Labels

• JLabel:
A label in Swing is a display area for a string of text, image, or both. It is
commonly used for displaying information to the user.
o Example:

JLabel label = new JLabel("Hello, World!");

• Icons: Swing provides the ImageIcon class to display images in components like
labels, buttons, etc.
o Example:

ImageIcon icon = new ImageIcon("path/to/image.jpg");


JLabel labelWithIcon = new JLabel(icon);

SAMRIDH PALLEDA 23100010095 28


JAVA SUMMER TRAINING REPORT

Text Fields

• JTextField: A single-line text input component. Users can enter and edit text in a
JTextField.
o Example:

JTextField textField = new JTextField(20); // 20 columns

Buttons – The JButton Class

• JButton: A clickable button in Swing. It can be associated with an ActionListener to


perform actions when clicked.
o Example:

JButton button = new JButton("Click Me");


button.addActionListener(e -> System.out.println("Button
Clicked!"));

Check Boxes

• JCheckBox: A component that allows the user to make a binary choice (checked or
unchecked).
o Example:

JCheckBox checkBox = new JCheckBox("Accept Terms");

Radio Buttons

• JRadioButton: Allows the user to select one option from a group of radio buttons.
These buttons should be added to a ButtonGroup to ensure that only one can be
selected at a time.
o Example:

JRadioButton option1 = new JRadioButton("Option 1");


JRadioButton option2 = new JRadioButton("Option 2");

ButtonGroup group = new ButtonGroup();


group.add(option1);
group.add(option2);

Combo Boxes

• JComboBox: A drop-down list that allows the user to select one item from a list of
options.
o Example:

String[] choices = { "Apple", "Banana", "Cherry" };


JComboBox<String> comboBox = new JComboBox<>(choices);

SAMRIDH PALLEDA 23100010095 29


JAVA SUMMER TRAINING REPORT

Tabbed Panes

• JTabbedPane: A component that allows the user to switch between different panels
using tabs. It provides a way to organize content into multiple sections.
o Example:

JTabbedPane tabbedPane = new JTabbedPane();


tabbedPane.addTab("Tab 1", new JPanel());
tabbedPane.addTab("Tab 2", new JPanel());

Scroll Panes

• JScrollPane: Provides a scrollable view of a component, such as a large text area or a


list. It adds horizontal and vertical scroll bars as needed.
o Example:

JTextArea textArea = new JTextArea(20, 30);


JScrollPane scrollPane = new JScrollPane(textArea);

Trees

• JTree: A component that displays hierarchical data in a tree structure. Each node can
expand or collapse to reveal its children.
o Example:

DefaultMutableTreeNode root = new


DefaultMutableTreeNode("Root");
DefaultMutableTreeNode child1 = new
DefaultMutableTreeNode("Child 1");
DefaultMutableTreeNode child2 = new
DefaultMutableTreeNode("Child 2");

root.add(child1);
root.add(child2);

JTree tree = new JTree(root);

Tables

• JTable: A component that displays data in a tabular format (rows and columns). It is
highly flexible and allows for customization of cells, rows, and columns.
o Example:

String[] columnNames = { "Name", "Age", "Gender" };


Object[][] data = {
{ "Alice", 25, "Female" },
{ "Bob", 30, "Male" }
};

JTable table = new JTable(data, columnNames);


JScrollPane tableScrollPane = new JScrollPane(table);

SAMRIDH PALLEDA 23100010095 30


JAVA SUMMER TRAINING REPORT

CHAPTER-8
PRACTICAL PROGRAMS
PROGRAM 1: Write a java program to find the Fibonacci series.
SOLUTION:
import java.util.*;
public class Program_1
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter the range: ");
int n=sc.nextInt();
int first=0;
int second=1;
int third=0;
for(int i=1;i<=n;i++)
{
if(i==1)
System.out.print(first+",");
if(i==2)
System.out.print(second+",");
else
{
third=first+second;
System.out.print(third+",");
}
first=second;
second=third;
}
}

OUTPUT:

Figure 6 - FIbonacci Series Output

SAMRIDH PALLEDA 23100010095 31


JAVA SUMMER TRAINING REPORT

PROGRAM 2: Write a java program to multiply two given matrices.


SOLUTION:
import java.util.*;
public class Program_1
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter rows and columns for 1st matrix: ");
int r1=sc.nextInt();
int c1=sc.nextInt();
System.out.print("Input first matrix: ");
int arr1[][] = new int[r1][c1];
for(int i=0;i<r1;i++)
{
for(int j=0;j<c1;j++)
{
arr1[i][j]=sc.nextInt();
}
}

//Displaying first matrix


for(int i=0;i<r1;i++)
{
for(int j=0;j<c1;j++)
{
System.out.print(arr1[i][j]+" ");
}
System.out.println();
}

System.out.print("Enter rows and columns for 2nd matrix: ");


int r2=sc.nextInt();
int c2=sc.nextInt();
System.out.print("Input second matrix: ");
int arr2[][] = new int[r2][c2];
for(int i=0;i<r2;i++)
{
for(int j=0;j<c2;j++)
{
arr2[i][j]=sc.nextInt();
}
}

SAMRIDH PALLEDA 23100010095 32


JAVA SUMMER TRAINING REPORT

//Displaying second matrix


for(int i=0;i<r2;i++)
{
for(int j=0;j<c2;j++)
{
System.out.print(arr2[i][j]+" ");
}
System.out.println();
}

//MULTIPLYING MATRICES
System.out.println("Resultant matrix:");
if(c1==r2)
{
int arr3[][] = new int[r1][c2];
for(int i=0;i<r1;i++)
{
for(int j=0;j<c2;j++)
{
arr3[i][j]=0;
for(int k=0;k<c1;k++)
{
arr3[i][j]+=arr1[i][k]*arr2[k][j];
}
System.out.print(arr3[i][j]+" ");
}
System.out.println();
}
}
else
System.out.println("Matrix multiplication not possible");
sc.close();
}
}

OUTPUT:

Figure 7 - Matrix Multiplication Output


SAMRIDH PALLEDA 23100010095 33
JAVA SUMMER TRAINING REPORT

PROGRAM 3: Write a java program for Method overloading and Constructor overloading.
SOLUTION:
//METHOD OVERLOADING
class Program_2 {
public int add(int a, int b) {
return a + b;
}
public int add(int a, int b, int c) {
return a + b + c;
}
public double add(double a, double b) {
return a + b;
}
public static void main(String args[])
{
Program_2 obj = new Program_2();
System.out.println("Sum of 2 and 3: " + obj.add(2, 3));
System.out.println("Sum of 1, 2 and 3: " + obj.add(1, 2, 3));
System.out.println("Sum of 2.5 and 3.5: " + obj.add(2.5, 3.5));
}
} */

//CONSTRUCTOR OVERLOADING
class Hello
{
public Hello()
{
System.out.println("Default constructor");
}
public Hello(String name)
{
System.out.println("Hello "+name);
}
public Hello(String first,String last)
{
System.out.println("Hello "+first+" "+last);
}
@SuppressWarnings("unused")
public static void main(String args[])
{
Hello obj = new Hello();
Hello obj1 = new Hello("John");
Hello obj2 = new Hello("Peter","Parker");
}
}

SAMRIDH PALLEDA 23100010095 34


JAVA SUMMER TRAINING REPORT

OUTPUT:

Figure 8 - Constructor Overloading Output Figure 9 - Method Overloading Output

PROGRAM 4: Write a Java program that checks whether a given string is a palindrome or not.
Ex: MADAM is a palindrome..
SOLUTION:
import java.util.*;
public class Program_2
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter a string: ");
String s = sc.next();
String rev="";
for(int i=1;i<=s.length();i++)
{
char ch = s.charAt(s.length()-i);
rev=rev+ch;
}
System.out.println("Reverse of string is: "+rev);
if(s.equals(rev))
System.out.print("The string is palindrome.");
else
System.out.print("Not a palindrome.");
}
}

OUTPUT:

Figure 10 - Palindrome Output

SAMRIDH PALLEDA 23100010095 35


JAVA SUMMER TRAINING REPORT

PROGRAM 5: Write a Java program to create an abstract class named Shape that contains two
integers and an empty method named print Area (). Provide three classes named Rectangle,
Triangle, and Circle such that each one of the classes extends the class Shape. Each one of the
classes contains only the method print Area () that prints the area of the given shape.
SOLUTION:
abstract class Shape {
int dimension1;
int dimension2;
abstract void printArea();
}

class Rectangle extends Shape {


public Rectangle(int length, int breadth) {
this.dimension1 = length;
this.dimension2 = breadth;
}

// Method to print the area of a rectangle


void printArea() {
int area = dimension1 * dimension2;
System.out.println("Rectangle Area: " + area);
}
}

class Triangle extends Shape {


public Triangle(int base, int height) {
this.dimension1 = base;
this.dimension2 = height;
}

// Method to print the area of a triangle


void printArea() {
double area = 0.5 * dimension1 * dimension2;
System.out.println("Triangle Area: " + area);
}
}

class Circle extends Shape {


public Circle(int radius) {
this.dimension1 = radius;
this.dimension2 = radius;
}

SAMRIDH PALLEDA 23100010095 36


JAVA SUMMER TRAINING REPORT

// Method to print the area of a circle


void printArea() {
double area = Math.PI * dimension1 * dimension1;
System.out.println("Circle Area: " + area);
}
}

public class Main {


public static void main(String[] args) {
// Creating objects of Rectangle, Triangle, and Circle
Shape rectangle = new Rectangle(10, 5);
Shape triangle = new Triangle(10, 8);
Shape circle = new Circle(7);

// Printing the areas of the shapes


rectangle.printArea();
triangle.printArea();
circle.printArea();
}
}

OUTPUT:

Figure 11 - Abstract Class Output

SAMRIDH PALLEDA 23100010095 37


JAVA SUMMER TRAINING REPORT

PROGRAM 6: Write a program which will explain the concept of try, catch and throw.
SOLUTION:
public class ExceptionDemo {
public static double divideNumbers(double a, double b) throws ArithmeticException {
if (b == 0) {
throw new ArithmeticException("Cannot divide by zero");
}
return a / b;
}
public static void main(String[] args) {
try {
double result = divideNumbers(10, 2);
System.out.println("Result: " + result);

result = divideNumbers(10, 0);


System.out.println("Result: " + result); // This line won't be executed
} catch (ArithmeticException e) {
System.out.println("Error: " + e.getMessage());
} catch (Exception e) {
System.out.println("An unexpected error occurred: " + e.getMessage());
} finally {
System.out.println("Execution completed");
}
}
}

OUTPUT:

Figure 12 - Exception Handling Output

SAMRIDH PALLEDA 23100010095 38


JAVA SUMMER TRAINING REPORT

PROGRAM 7: Write a java program showing concept of threads by importing thread class.
SOLUTION:
class A extends Thread
{
public void run()
{
for(int i=1;i<=5;i++)
{
System.out.println("Thread 1");
try{
Thread.sleep(10);
}
catch(InterruptedException e){
e.printStackTrace();
}

}
}
}
class B extends Thread
{
public void run()
{
for(int i=1;i<=5;i++)
{
System.out.println("Thread 2");
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class MyThread
{
public static void main(String args[])
{
A obj1 = new A();
B obj2 = new B();

obj1.start();
try {
Thread.sleep(3);
SAMRIDH PALLEDA 23100010095 39
JAVA SUMMER TRAINING REPORT

} catch (InterruptedException e) {
e.printStackTrace();
}
obj2.start();
}
}

OUTPUT:

Figure 13 – Multithreading Output

SAMRIDH PALLEDA 23100010095 40

You might also like