Java Programming
Java Programming
UNIT – I
● High-level: This means it's designed to be easier for humans to read and
write, using words and structures closer to human language, rather than the
complex machine code that computers directly understand.
● Object-oriented (OOP): This is a programming style where you organize your
code around "objects." Think of objects as blueprints for real-world things
(like a "Car" object or a "Customer" object). Each object can have its own
data (like the car's color, speed) and actions it can perform (like accelerate,
brake). This makes code more organized, reusable, and easier to manage,
especially for large projects.
● "Write Once, Run Anywhere" (WORA): This is Java's most famous feature.
When you write Java code, it's first compiled into something called
"bytecode." This bytecode isn't specific to any one computer system (like
Windows or macOS). Instead, it runs on a special program called the Java
Virtual Machine (JVM). The JVM acts like a translator, allowing the same
bytecode to run on any device that has a JVM installed. This makes Java
incredibly versatile.
Java is incredibly versatile and powers a massive part of the digital world. Here are
some of its main uses:
1. Android Mobile Apps: A vast majority of Android applications are built using
Java. If you use an Android phone, many of the apps you interact with daily
likely have Java at their core.
2. Enterprise Applications: Large organizations (banks, insurance companies,
government agencies) use Java to build big, complex, and secure systems
for things like:
○ Financial trading platforms
○ Supply chain management
○ E-commerce platforms
○ Billing systems
3. Web Applications: While many newer technologies exist, Java is still very
strong in building the "backend" (server-side) of web applications,
especially for large-scale, high-traffic websites. Think of services like
Netflix, LinkedIn, and even parts of Twitter.
4. Big Data Technologies: Frameworks like Apache Hadoop and Apache Spark,
which are used to process and analyze massive amounts of data, are
largely built with Java
6. Internet of Things (IoT) Devices: Java's "Write Once, Run Anywhere" capability
makes it suitable for programming smart devices, sensors, and other
interconnected IoT gadgets.
7. Games: While not as dominant as C++ for high-end gaming, Java is used for
many popular games, especially mobile and indie games (e.g., Minecraft was
originally written in Java).
8. Desktop Applications: While less common now for new desktop apps, Java can
2
still be used to build cross-platform desktop software with graphical user
interfaces (GUIs).
Features of Java
Java's popularity stems from a set of core features that make it robust, versatile,
and widely adopted:
1. Object-Oriented (OOP):
○ Concept: Everything in Java is treated as an object, which bundles
data (attributes) and methods (behaviors) together. This mirrors
real-world entities.
○ Benefits: Promotes code reusability, modularity, easier maintenance,
and better organization of large programs. Key OOP principles like
Encapsulation, Inheritance, Polymorphism, and Abstraction are
central to Java.
8. Distributed:
○ Concept: Java provides features for building distributed
applications, where different parts of a program can run on
different computers across a network.
○ Benefits: Enables developers to create large-scale, scalable
applications like enterprise systems and web services that can span
multiple machines
[Link]:
4
○ Concept: Java can adapt to evolving environments. It can load
classes on demand, making it suitable for dynamic applications
that might change their behavior or load new components at
runtime.
○ Benefits: Supports reflective programming and dynamic changes in
application behavior.
These tools, along with the powerful features of the Java language itself, form the
foundation of the robust Java ecosystem that enables developers to build a vast array of
applications.
1. Class
A class is a blueprint or a template for creating objects. It defines the properties (data/attributes)
and behaviors (methods) that an object of that class will have. For example, a Car class might
have properties like color, brand, and model, and methods like startEngine() and
accelerate().
6
2. Abstraction
Abstraction is the concept of hiding the complex implementation details and showing only the
essential features of an object. It focuses on what an object does rather than how it does it. In
Java, abstraction is achieved using abstract classes and interfaces. For instance, when you use a
Remote to turn on a TV, you don't need to know the intricate electronic workings inside the TV.
The Remote provides a simple, abstract interface for controlling it.
3. Encapsulation
Encapsulation is the mechanism of binding data and the methods that operate on that data into a
single unit, which is a class. It also allows for controlling access to the data, protecting it from
external misuse. This is typically achieved by making the data members (variables) private and
providing public methods (getters and setters) to access and modify them. This ensures data
integrity and security.
4. Inheritance
Inheritance is the mechanism by which one class acquires the properties and behaviors of another
class. The class that inherits is called the child or subclass, and the class from which it inherits
is called the parent or superclass. This promotes code reusability and establishes a "is-a"
relationship (e.g., a Dog is an Animal).
5. Polymorphism
Polymorphism means "many forms." It is the ability of an object to take on many forms. In OOP,
it allows a single interface to be used for a general class of actions. Polymorphism is achieved in
two main ways:
OOP is used to make software development more organized, efficient, and reliable by:
7
Maintenance: Making debugging and updates easier.
package [Link];
8
import [Link];
// Data members
// Constructor functions
// User-defined methods
[Link]("Hello, World!");
// myMethod();
//{
// }
Explanation:
Package: A package groups related classes, interfaces, and sub-packages. To use pre-
defined classes from other packages, a programmer needs to import those packages. Java
automatically imports the [Link].* package by default.
Class: A class is a user-defined data type. Every Java program starts with at least one class
definition. If we declare a class as public, it means it is accessible from another package.
Class name: It is the name given to that class; it acts like a new data type that we can use
to create objects.
9
Data members: Data members are variables declared inside a class.
Constructor: A constructor is a special block of code that runs automatically when we create a
new object from a class. The main task of a constructor is to initialize the new object. Always
remember the constructor name must be the same as the class name, also it does not have any
return type.
Data Types
In Java, every variable must have a data type, which specifies the size and type of values it can
hold. This is a key feature of Java as a "statically-typed" language. Java's data types are
categorized into two main groups:
These are the most basic data types and are predefined by the language. They store simple values
directly in memory. Java has eight primitive data types:
Data Default
Size Range Example
Type Value
byte 8 bits -128 to 127 0 byte b = 100;
short 16 bits -32,768 to 32,767 0 short s = 5000;
Approximately -2 billion to 2
int 32 bits 0 int i = 100000;
billion
long l =
long 64 bits Extremely large range 0L 15000000000L;
Up to 7 decimal digits of
float 32 bits 0.0f float f = 12.34f;
precision
Up to 15 decimal digits of
double 64 bits 0.0d double d = 123.456;
precision
JVM-dependent boolean isAdult =
boolean true or false false
(usually 1 bit) true;
A single Unicode character
char 16 bits \u0000 char c = 'A';
(\u0000 to \uffff)
Integer Types: byte, short, int, and long are used for storing whole numbers. int is
the most commonly used.
10
Floating-Point Types: float and double are used for numbers with decimal points.
double is the default choice for decimal values due to its higher precision.
Character Type: char is used to store a single character.
Boolean Type: boolean is used for conditional logic and can only hold true or false.
These data types are not predefined but are created by the programmer. They do not store the
data directly but rather a reference (memory address) to the object that contains the data.
Arrays: An object that stores a collection of elements of the same data type.
Classes: A blueprint for creating objects. User-defined classes are non-primitive data
types.
class MyClass {
// Class members
}
MyClass obj = new MyClass();
Interfaces: A contract that defines a set of methods that a class must implement.
Variables in Java
11
Key Characteristics of Variables:
Before you can use a variable, you must declare it. Declaration involves specifying the variable's
data type and name. You can also assign an initial value to the variable during declaration, which
is called initialization.
// Declaration:
int age;
// Initialization:
age = 30;
Types of Variables
Based on where they are declared, variables in Java can be categorized into three main types:
1. Local Variables:
o Declared inside a method, constructor, or block.
o Their scope is limited to that method, constructor, or block.
o They must be initialized before use; they do not have a default value.
o They are stored in the stack memory.
You can use the final keyword to make a variable a constant, which means its value cannot be
changed after it is initialized.
Operators in Java
Operators are special symbols used to perform operations on variables and values. They are the
building blocks of any program and are used to manipulate data, make decisions, and control the
flow of execution.
1. Arithmetic Operators
13
Operato
Description Example Result
r
+ Addition 10 + 5 15
- Subtraction 10 - 5 5
* Multiplication 10 * 5 50
/ Division 10 / 5 2
% Modulus (Remainder) 10 % 3 1
i becomes
++ Increment (adds 1) int i = 5; i++;
6
Decrement j becomes
-- int j = 5; j--;
(subtracts 1) 4
Export to Sheets
Used to compare two values and return a boolean result (true or false).
>=
Greater than or 10 >= 5 true
equal to
<= Less than or equal to 10 <= 5 false
3. Logical Operators
Used to combine multiple boolean expressions and return a single boolean result.
Operato Descriptio
Example Result
r n
&&
Logical (10 > 5) && (12 > 10) true
AND
Logical
` `
OR
!
Logical !(10 == 5) true
NOT
4. Assignment Operators
Used to assign a value to a variable. The simple assignment operator is =. Other assignment
operators are shorthands for combining an arithmetic operation with assignment.
Operato Equivalent
Description Example
r to
= Assign int x = 10; -
14
Operato Equivalent
Description Example
r to
+= Add and assign x += 5; x = x + 5;
-=
Subtract and x -= 5; x = x - 5;
assign
*=
Multiply and x *= 5; x = x * 5;
assign
/= Divide and assign x /= 5; x = x / 5;
%=
Modulus and x %= 3; x = x % 3;
assign
5. Bitwise Operators
Operato
Description Example
r
5 & 1 (0101 & 0001) ->
& Bitwise AND 1
5 | 1 (0101 | 0001) ->
| Bitwise OR 5
5 ^ 1 (0101 ^ 0001) ->
^ Bitwise XOR 4
~ Bitwise NOT ~5 -> -6
<< Left shift 5 << 2 -> 20
>> Right shift 5 >> 2 -> 1
Unsigned right
>>> 5 >>> 2 -> 1
shift
Operato
Description Example
r
? :
Ternary String result = (age >= 18) ? "Adult" : "Minor";
operator
Keywords in Java
Keywords are reserved words in Java that have a predefined meaning to the compiler. They
cannot be used as identifiers (variable names, class names, method names, etc.). There are about
50 keywords in Java.
Here are some of the most common keywords, categorized by their use:
15
Access Modifiers: public, private, protected, final, static, abstract
Data Types: byte, short, int, long, float, double, char, boolean
Control Flow: if, else, switch, case, default, for, while, do, break, continue,
return
Object-Oriented Concepts: class, interface, enum, extends, implements, new,
this, super, instanceof
Exception Handling: try, catch, finally, throw, throws
Other: package, import, void, transient, volatile, strictfp, assert
Note: The keywords const and goto are reserved but not used in Java.
A naming convention is a set of rules for naming identifiers in your code. While the Java
compiler doesn't enforce these conventions, following them is a best practice that makes your
code more readable, understandable, and maintainable for other developers and for yourself. The
standard naming conventions in Java are defined by Oracle.
1. Classes:
2. Methods:
3. Variables:
5. Packages:
6. Interfaces:
Decision-making statements are used to execute a block of code only if a specific condition is
met. They allow your program to make choices and follow different paths of execution. The two
main decision-making statements in Java are if and switch.
The if-else statement is the most basic control flow statement. It evaluates a boolean condition
and executes a block of code if the condition is true. An optional else block can be used to
execute code if the condition is false.
Syntax:
if (condition) {
// Code to execute if the condition is true
} else {
// Code to execute if the condition is false
}
The else block is optional. You can have a simple if statement without an else.
Example:
You can chain multiple if-else statements to check a series of conditions. The first true
condition's block will be executed, and the rest will be skipped.
The switch statement is an alternative to a long if-else if-else ladder when you need to
compare a single variable against a list of possible values. It's often more readable and efficient
for such cases.
Syntax:
switch (expression) {
case value1:
// Code to execute if expression matches value1
break;
case value2:
// Code to execute if expression matches value2
break;
// ... more cases
default:
// Code to execute if expression doesn't match any case
}
expression: The variable to be evaluated. It can be of type char, byte, short, int,
String, or an enum.
case value: A specific value to be compared against the expression.
break: The break keyword is crucial. It terminates the switch statement once a case is
matched and executed. Without it, the program will "fall through" and execute the code
in all subsequent cases.
default: The default block is optional and is executed if none of the case values
match the expression.
18
Example:
int dayOfWeek = 3;
switch (dayOfWeek) {
case 1:
[Link]("Monday");
break;
case 2:
[Link]("Tuesday");
break;
case 3:
[Link]("Wednesday");
break;
case 4:
[Link]("Thursday");
break;
case 5:
[Link]("Friday");
break;
default:
[Link]("Weekend");
}
Loops are control structures that allow a block of code to be executed repeatedly. This is
essential for tasks that require repetitive actions, such as iterating over a collection of data,
performing a calculation multiple times, or waiting for a specific condition to be met.
Java provides several looping constructs, with the most common being for, while, and do-
while.
19
1. The for Loop
The for loop is ideal when you know exactly how many times you want to repeat a block of
code. It's concise and combines the initialization, condition, and iteration in a single line.
Syntax:
initialization: Executed once at the beginning of the loop. Used to declare and
initialize a loop counter variable.
condition: A boolean expression that is checked before each iteration. The loop
continues as long as this condition is true.
update: Executed after each iteration. Typically used to increment or decrement the loop
counter.
Example:
Output:
0
1
2
3
4
Java also has an enhanced for loop, or for-each loop, which is used to iterate over elements of
an array or a collection. It is more readable and less error-prone than a traditional for loop for
this specific purpose.
Syntax:
Java
for (dataType element : collection) {
// Code to be executed for each element
}
Example:
1
2
3
4
5
The while loop is used when the number of iterations is not known in advance. It repeatedly
executes a block of code as long as a specified condition remains true.
Syntax:
while (condition) {
// Code to be executed repeatedly
}
condition: A boolean expression that is checked before each iteration. If the condition is
initially false, the loop's body will never execute.
Example:
int i = 0;
Output:
0
1
2
3
4
The do-while loop is similar to the while loop, but with one crucial difference: its condition is
checked after the loop body has been executed. This guarantees that the loop will run at least
once, regardless of whether the condition is initially true or false.
21
Syntax:
do {
// Code to be executed at least once
} while (condition);
Example:
int i = 0;
// The code runs once, even though the condition is false from the start
do {
[Link](i);
i++;
} while (i > 5);
Output:
Type casting is the process of converting a value from one data type to another. It's an essential
operation when you need to store a value of one type in a variable of another type. Java provides
two main types of casting, which depend on the direction of the conversion:
Widening casting is the automatic conversion of a data type. It happens when you convert a
smaller data type to a larger one. This is a safe conversion because there is no loss of data. The
compiler performs this automatically without you having to write any code.
Order of Widening Conversion (from smallest to largest): byte -> short -> char -> int ->
long -> float -> double
Example:
Java
public class WideningCastingExample {
public static void main(String[] args) {
int myInt = 9;
double myDouble = myInt; // Automatic casting from int to double
[Link](myInt); // Output: 9
[Link](myDouble); // Output: 9.0
}
}
In this example, the int value 9 is automatically converted into the double value 9.0 because a
double can hold all possible int values without any data loss.
22
2. Narrowing Casting (Explicit Casting)
Narrowing casting is the manual conversion of a data type. It's required when you convert a
larger data type to a smaller one. This is a potentially risky conversion because there can be a
loss of data or precision. You must explicitly perform this conversion by placing the target type
in parentheses before the value.
Order of Narrowing Conversion (from largest to smallest): double -> float -> long -> int
-> char -> short -> byte
Example:
Java
public class NarrowingCastingExample {
public static void main(String[] args) {
double myDouble = 9.78;
int myInt = (int) myDouble; // Manual casting from double to int
Flexibility: It allows you to work with different data types in the same expression.
Compatibility: It's often necessary when calling methods that require a specific data type
as an argument. For instance, a method might only accept an int, and you need to pass it
a long.
Resource Management: Narrowing casting can be used to save memory by converting a
large data type to a smaller one when you know the value will fit.
Arrays in Java
An array is a data structure that stores a fixed-size, sequential collection of elements of the same
data type. It's a fundamental part of Java for managing and organizing related data.
Creating an Array
Java
23
// 2. Instantiation: Creates an array in memory with a specified size
numbers = new int[5]; // An array of 5 integers
Java
int[] numbers = {10, 20, 30, 40, 50}; // Declares, instantiates, and
initializes
Accessing Array Elements
Java
int[] numbers = {10, 20, 30};
[Link](numbers[0]); // Output: 10
[Link](numbers[2]); // Output: 30
Types of Arrays
1. One-Dimensional Arrays
Example:
Java
Creating a 2D array:
Java
24
// Using an array literal
int[][] matrixLiteral = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
Accessing elements:
Java
Strings
A String in Java is a sequence of characters. It's not a primitive data type but an object. The
String class is immutable, meaning once a String object is created, its value cannot be
changed.
Creating a String:
StringBuffer Class
Unlike the String class, the StringBuffer class is mutable, which means its objects can be
modified after they are created. It is used when you need to perform frequent modifications to a
string without creating a new object each time. StringBuffer is also thread-safe, making it
suitable for multi-threaded environments.
25
Creating a StringBuffer:
replace(int start, int end, String str): Replaces a portion of the string.
Note: For single-threaded environments where mutability is needed, the StringBuilder class is
often preferred over StringBuffer as it is faster because it is not synchronized.
26