Java
Java
CHAPTER-1
BASICS OF 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.
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.
• 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.
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.
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.
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.
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.
o Example:
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:
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.
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:
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:
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}
};
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.
• 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:
• Logical Operators: Used to combine multiple conditions, including AND, OR, and
NOT.
o Example:
int a = 10;
a += 5; // Equivalent to a = a + 5;
int x = 10;
x++; // Increment
x--; // Decrement
int y = -x; // Negation
boolean z = !true; // Logical complement
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.
o Example:
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:
In this example, the for loop runs five times, printing the iteration number in
each pass.
• 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.
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.
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
java -version
o This will display the version of Java that is installed. If the version is displayed
correctly, the installation is successful.
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.
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.
Once VSCode is installed, you need to install the Java extension to enable Java development
features.
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.
CHAPTER-2
OBJECT-ORIENTED PROGRAMMING CONCEPTS
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
• Example:
In this example, dog1 is an object of the Dog class, and the method bark is called on it.
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;
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.");
}
}
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.
2.5 Polymorphism
class Calculator {
int add(int a, int b) {
return a + b;
}
class Animal {
void sound() {
System.out.println("This animal makes a sound.");
}
}
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:
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.
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
}
A class can implement an interface using the implements keyword and provide concrete
implementations of the methods declared in the interface.
• Example:
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:
Here, the Mammal interface extends Animal and adds a new method feed().
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();
}
In this example, the Person class implements both Walkable and Runnable interfaces,
providing implementations for both walk() and run() methods.
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.
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:
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:
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
}
• Output:
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.
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:
• Output:
Here, the inner try block handles the ArrayIndexOutOfBoundsException, while the outer
try block handles the ArithmeticException.
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:
• Output:
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
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.
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:
The start() method is used to start the execution of a thread, which calls the run() method
internally.
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;
t1.start();
t2.start();
t1.join();
t2.join();
In this example, the increment() method is synchronized to ensure that only one thread can
increment the counter at a time, preventing race conditions.
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:
daemonThread.setDaemon(true);
daemonThread.start();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
In this example, the daemonThread is a daemon thread that runs in the background until the
main thread finishes execution.
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.
AWT components are derived from the java.awt package. Below is a brief look at the
hierarchy of some essential classes in AWT:
5. List: Displays a list of items from which the user can select.
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.
import java.awt.*;
import java.awt.event.*;
public SimpleAWTApp() {
// Create components
Label label = new Label("Enter your name:");
label.setBounds(50, 50, 100, 30);
// Frame settings
setSize(400, 200);
setLayout(null);
setVisible(true);
}
In this example:
OUTPUT:
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.
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:
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.
• 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:
• Icons: Swing provides the ImageIcon class to display images in components like
labels, buttons, etc.
o Example:
Text Fields
• JTextField: A single-line text input component. Users can enter and edit text in a
JTextField.
o Example:
Check Boxes
• JCheckBox: A component that allows the user to make a binary choice (checked or
unchecked).
o Example:
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:
Combo Boxes
• JComboBox: A drop-down list that allows the user to select one item from a list of
options.
o Example:
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:
Scroll Panes
Trees
• JTree: A component that displays hierarchical data in a tree structure. Each node can
expand or collapse to reveal its children.
o Example:
root.add(child1);
root.add(child2);
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:
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:
//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:
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");
}
}
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:
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();
}
OUTPUT:
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);
OUTPUT:
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: