0% found this document useful (0 votes)
3 views26 pages

Java Programming

Java is a high-level, object-oriented programming language known for its platform independence, allowing code to run on any system with a Java Virtual Machine (JVM). It is widely used in various applications, including Android apps, enterprise systems, web applications, and big data technologies. Key features of Java include its simplicity, security, robustness, and a vast community that supports a rich ecosystem of libraries and tools.

Uploaded by

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

Java Programming

Java is a high-level, object-oriented programming language known for its platform independence, allowing code to run on any system with a Java Virtual Machine (JVM). It is widely used in various applications, including Android apps, enterprise systems, web applications, and big data technologies. Key features of Java include its simplicity, security, robustness, and a vast community that supports a rich ecosystem of libraries and tools.

Uploaded by

hiteshupadhya764
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Java Programming

UNIT – I

What is Java Programming?

In simple terms, Java is a high-level, object-oriented programming language.

Let's break that down:

● 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.

Key Characteristics of Java:

● Platform Independent: As explained above, it works on many different


operating systems.
● Robust: It's designed to be reliable and handle errors well, making
programs more stable.
● Secure: Java has built-in security features that help protect applications
from malicious attacks.
● Multithreaded: Java programs can do multiple tasks at the same time, which
makes applications faster and more responsive (e.g., a word processor can
check spelling while you're still typing).
● Simple (relatively): While powerful, Java tries to be straightforward to learn,
especially compared to some older languages like C++.
● Huge Community and Libraries: Because it's been around for a long time,
there's a vast community of Java developers and tons of pre-written code
(libraries and frameworks) that developers can use, saving time and
1
effort.

What is Java Programming Used For? (Its Applications)

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

5. Scientific Applications: Its robustness and strong mathematical libraries


make Java a good choice for scientific research, data analysis, and
simulations.

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).

In summary, Java is a powerful, reliable, and widely adopted programming language


that forms the backbone of countless applications across almost every industry,
from the smallest mobile app to the largest enterprise systems.
Or
Java programming refers to the process of developing software using the Java programming
language. Java is a high-level, object-oriented language known for its platform independence,
meaning compiled Java code can run on any platform that supports Java without recompilation.
This "write once, run
anywhere" capability is facilitated by the Java Virtual Machine (JVM).

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.

2. Platform Independent (WORA - Write Once, Run Anywhere):


○ Concept: Java code is compiled into an intermediate format called
bytecode. This bytecode is not specific to any operating system or
hardware.
○ Benefits: The same compiled Java code can run on Windows, macOS,
Linux, or any other platform that has a Java Virtual Machine (JVM)
installed, without needing modification. This is Java's most famous and
powerful feature.
3. Simple:
○ Concept: Java was designed to be relatively easy to learn and use,
especially compared to languages like C++. It removed complex
features like explicit pointers and operator overloading.
○ Benefits: Lowers the learning curve for new programmers and reduces
common programming errors.
4. Secure:
3
○ Concept: Java has built-in security features to protect systems from
malicious code (e.g., applets from untrusted sources). It uses a
"sandbox" model to restrict what untrusted code can do.
○ Benefits: Essential for network-centric applications and ensures data
integrity and system safety.
5. Robust:
○ Concept: Java is designed to be reliable and handle errors gracefully.
It has strong memory management (e.g., automatic garbage
collection) and exception handling mechanisms.
○ Benefits: Reduces the chances of program crashes and makes
applications more stable and dependable.
6. Multithreaded:
○ Concept: Java supports running multiple parts of a program
concurrently (at the same time) within a single process. Each part is
called a "thread."
○ Benefits: Improves application performance and responsiveness. For
example, a web browser can load images while still displaying text, or
a game can process user input while rendering graphics.
7. High Performance:
○ Concept: Java uses a "Just-In-Time (JIT) compiler" within the JVM. The
JIT compiler converts bytecode into native machine code during
runtime, which can execute much faster than interpreted code.

○ Benefits: While Java is typically slower than natively compiled


languages like C++, the JIT compiler significantly boosts its
performance, making it suitable for high-performance applications.

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

9. Interpreted & Compiled:


○ Concept: Java is both a compiled and an interpreted language.
Source code is first compiled into bytecode, which is then interpreted by
the JVM at runtime.
○ Benefits: This hybrid approach enables platform independence and
allows for runtime optimizations by the JIT compiler.

[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.

JDK Environment & Tools


The Java Development Kit (JDK) is a software development environment used for
developing Java applications and applets. It includes the Java Runtime Environment
(JRE), an interpreter/loader (java), a compiler (javac), an archiver (jar), a
documentation generator (javadoc), and other tools needed for Java development.

Let's look at some key tools included in the JDK:

1. java (Java Interpreter/Launcher):


○ Purpose: This tool is used to run Java applications. It launches the Java
Virtual Machine (JVM) and loads the specified Java class file
(containing bytecode) to execute its main() method.
○ How to use: java MyProgram (where MyProgram is the name of your
class file without the .class extension).
○ Example: If you compile [Link] to [Link], you
run it using java HelloWorld.

2. javac (Java Compiler):


○ Purpose: This tool is used to compile Java source code (.java files) into
Java bytecode (.class files). The bytecode is the platform-
independent code that the JVM understands.

○ How to use: javac [Link] (where [Link] is your


Java source code file).
○ Example: After writing your code in [Link], you compile it
with javac [Link] to create [Link].

3. appletviewer (Applet Viewer):


○ Purpose: (Primarily for older Java Applets) This tool is used to run Java
applets without needing a web browser. Applets were small Java
programs embedded in web pages. While applets are largely
deprecated now due to security concerns and the rise of web
technologies like HTML5 and JavaScript, appletviewer was a crucial
testing tool for them.
5
○ How to use: appletviewer [Link] (where
[Link]
contains the HTML <applet> tag referencing your Java applet).

4. javadoc (Java Documentation Generator):


○ Purpose: This tool generates HTML documentation from special
comments in your Java source code. Developers use specific
"Javadoc comments" (starting with /** and ending with */) to
describe classes, methods, and variables.
○ Benefits: Creates professional, browsable API documentation (like the
official
Java API documentation) that helps other developers understand and
use your code.
○ How to use: javadoc [Link] (or specify a package).

5. jdb (Java Debugger):


○ Purpose: This tool is a command-line debugger for Java applications. It
allows you to pause a running Java program, examine the values of
variables, step through code line by line, set breakpoints, and
identify errors.
○ Benefits: Essential for finding and fixing bugs in your Java code. While
many developers use integrated debuggers in IDEs (like IntelliJ IDEA
or Eclipse), jdb is the fundamental command-line tool.
○ How to use: Typically, you compile your code with debug
information (javac -g [Link]) and then launch the
debugger: jdb MyProgram.

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.

Object-Oriented Programming (OOP) Concepts

Object-Oriented Programming (OOP) is a programming paradigm that organizes software design


around data, or objects, rather than functions and logic. The core concepts of OOP are
fundamental to languages like Java and C++.

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:

 Method Overloading (Compile-time Polymorphism): Defining multiple methods with


the same name but different parameters within the same class.
 Method Overriding (Runtime Polymorphism): A subclass providing a specific
implementation of a method that is already defined in its superclass.

Why Use OOP?

OOP is used to make software development more organized, efficient, and reliable by:

 Modularity: Breaking down complex systems into smaller, manageable objects.


 Reusability: Reusing code through inheritance.
 Security: Protecting data with encapsulation.
 Flexibility: Allowing for adaptable and scalable code with polymorphism.

7
 Maintenance: Making debugging and updates easier.

Difference Between C++ and Java

Feature C++ Java


Platform-dependent. Code is Platform-independent. Code is
Platform
compiled into machine-specific compiled into bytecode, which runs
Dependency
code. on the Java Virtual Machine (JVM).
Memory Manual memory management Automatic memory management
Management using new and delete operators. using a garbage collector.
Does not support explicit pointers; all
Pointers Supports explicit pointers. object references are handled
internally.
Does not support multiple inheritance
Multiple Supports multiple inheritance
through classes, but it supports it
Inheritance through classes.
through interfaces.
Operator Does not support operator
Supports operator overloading.
Overloading overloading.
Object- Supports both procedural and Purely object-oriented (with the
Orientation object-oriented programming. exception of primitive data types).
Less secure due to explicit More secure due to the absence of
Security pointers and the absence of a pointers and running within the
secure runtime environment. secure JVM environment.
Go To
Supports the goto statement. Does not support the goto statement.
Statement
Uses header files (.h) to declare Uses packages and import statements
Header Files
classes and functions. to manage classes.
A C++ compiler directly A Java compiler converts source code
Compiler converts source code to to bytecode, which is then
machine code. interpreted/JIT-compiled by the JVM.

Structure of a Java Program

// Package Declaration (optional)

package [Link];

// Import Statements (optional)

8
import [Link];

// Class Declaration (mandatory)

public class MyProgram {

// Data members

// Constructor functions

// User-defined methods

// Main Method (entry point of the program)

public static void main(String[] args)

// Body of the main method

[Link]("Hello, World!");

// Other methods can be called here

// myMethod();

// Other methods (optional)

// public void myMethod()

//{

// Code for 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:

1. Primitive Data Types

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.

2. Non-Primitive Data Types (Reference Types)

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.

 String: A sequence of characters. It is an object in Java.

String name = "Alice";

 Arrays: An object that stores a collection of elements of the same data type.

int[] numbers = {1, 2, 3};

 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.

Key Differences Between Primitive and Non-Primitive Data Types:

Feature Primitive Data Types Non-Primitive Data Types


Default Have default values (e.g., 0,
Default value is null.
Value false).
Stored directly in the stack Stored in the heap memory; a reference is on
Memory
memory. the stack.
Size Fixed size for each type. Size is variable, depending on the object.
Functionali Have methods to perform operations (e.g.,
No additional methods.
ty [Link]()).
Initial Always start with a
Always start with an uppercase letter.
Letter lowercase letter.

Variables in Java

A variable is a fundamental concept in programming. In Java, a variable is a named container


that holds a value. It's essentially a memory location with a specific name and data type, where
you can store data that can be changed during program execution.

11
Key Characteristics of Variables:

 Name: A unique identifier that you use to refer to the variable.


 Data Type: Determines the type of data the variable can hold (e.g., int, String,
boolean). This also defines the size of the memory location and the set of operations that
can be performed on the value.
 Value: The actual data stored in the variable.

Declaring and Initializing 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;

// Declaration and Initialization in one line:


String name = "Alice";

Naming Conventions for Variables

 Variable names should start with a lowercase letter.


 Use camelCase for names with multiple words (e.g., firstName, myAge).
 Names can contain letters, digits, and the underscore _ and dollar sign $.
 They cannot start with a digit.
 They should be descriptive and meaningful (e.g., totalPrice is better than tp).

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.

public void myMethod() {


int x = 10; // Local variable
[Link](x);
}

2. Instance Variables (Non-Static Fields):


12
o Declared inside a class, but outside of any method, constructor, or block.
o They are specific to each object (instance) of the class. Each object has its own
copy of these variables.
o They are created when an object is created and destroyed when the object is
destroyed.
o They are stored in the heap memory.
o They have default values (e.g., 0 for int, null for String, false for boolean).

public class Car {


String color; // Instance variable
int speed; // Instance variable
}

3. Static Variables (Class Variables):


o Declared using the static keyword inside a class, but outside of any method.
o They are shared among all objects of the class. There is only one copy of a static
variable per class.
o They are created when the program starts and destroyed when the program ends.
o They are stored in a dedicated memory area called the "static memory."
o They have default values, just like instance variables.

public class Counter {


static int count = 0; // Static variable
// ...
}

Final Variables (Constants)

You can use the final keyword to make a variable a constant, which means its value cannot be
changed after it is initialized.

final int MY_CONSTANT = 100;

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.

Here is a breakdown of the different types of operators in Java:

1. Arithmetic Operators

Used to perform basic mathematical operations.

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

2. Relational (Comparison) Operators

Used to compare two values and return a boolean result (true or false).

Operato Exampl Resul


Description
r e t
== Equal to 10 == 5 false
!= Not equal to 10 != 5 true
> Greater than 10 > 5 true
< Less than 10 < 5 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

Used to perform operations on individual bits of an integer.

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

6. Ternary (Conditional) Operator

A shorthand for an if-else statement.

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.

Naming Conventions 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.

Here are the key conventions:

1. Classes:

• Start with an uppercase letter.


• Use PascalCase (the first letter of each word is capitalized).
• Should be nouns or noun phrases.
• Examples: MyClass, String, Car, DataStructure, HelloWorld

2. Methods:

• Start with a lowercase letter.


• Use camelCase (the first letter of the first word is lowercase, and the first letter of
subsequent words is capitalized).
• Should be verbs or verb phrases.
• Examples: main(), calculateSum(), startEngine(), getAge()

3. Variables:

• Start with a lowercase letter.


• Use camelCase.
• Should be short, meaningful, and descriptive.
• Examples: firstName, totalCount, age, isLoggedIn

4. Constants (Final Variables):


16
• Use all uppercase letters.
• Use underscores _ to separate words.
• Declared with the final keyword.
• Examples: MAX_VALUE, PI, MIN_HEIGHT, RED_COLOR

5. Packages:

• Use all lowercase letters.


• Should be the reverse of your domain name (e.g., [Link]).
• Avoid using underscores or special characters.
• Examples: [Link], [Link]

6. Interfaces:

• Same as class names (start with an uppercase letter, PascalCase).


• Should be adjectives or noun phrases.
• Examples: Runnable, Serializable, List

Decision-Making Statements in Java

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.

1. The if-else Statement

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:

int age = 20;


17
if (age >= 18) {
[Link]("You are an adult.");
} else {
[Link]("You are a minor.");
}

if-else if-else Ladder:

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.

int score = 85;

if (score >= 90) {


[Link]("Grade: A");
} else if (score >= 80) {
[Link]("Grade: B");
} else if (score >= 70) {
[Link]("Grade: C");
} else {
[Link]("Grade: D or F");
}

2. The switch Statement

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");
}

Key Differences: if vs. switch

Feature if-else Statement switch Statement


Expression Evaluates a boolean expression. Evaluates a single int, short, byte,
Type Can handle complex conditions. char, String, or enum value.
Can check for a range of values Checks for equality with discrete,
Logic
or multiple conditions. fixed values.
Can be slower for a long list of Generally more efficient than a long
Performance
conditions. if-else ladder for discrete values.
Good for complex, logical More readable for a clear set of
Readability
conditions. discrete choices.

Looping Statements in Java

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:

for (initialization; condition; update) {


// Code to be executed repeatedly
}

 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:

// Print numbers from 0 to 4


for (int i = 0; i < 5; i++) {
[Link](i);
}

Output:

0
1
2
3
4

Enhanced for Loop (for-each):

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:

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

for (int number : numbers) {


[Link](number);
}
20
Output:

1
2
3
4
5

2. The while Loop

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;

// Print numbers from 0 to 4


while (i < 5) {
[Link](i);
i++; // Must include an update statement to avoid an infinite loop
}

Output:

0
1
2
3
4

3. The do-while Loop

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 in Java

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:

1. Widening Casting (Implicit Casting)

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

[Link](myDouble); // Output: 9.78


[Link](myInt); // Output: 9
}
}

Why is Type Casting Important?

 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

There are two main ways to create an array in Java:

1. Declaration, Instantiation, and Initialization:

Java

// 1. Declaration: Declares an array of integers


int[] numbers;

23
// 2. Instantiation: Creates an array in memory with a specified size
numbers = new int[5]; // An array of 5 integers

// 3. Initialization: Assigning values to each element


numbers[0] = 10;
numbers[1] = 20;
// ...and so on

2. Array Literal (Shorthand):

Java

int[] numbers = {10, 20, 30, 40, 50}; // Declares, instantiates, and
initializes
Accessing Array Elements

You access array elements using an index, which starts from 0.

Java
int[] numbers = {10, 20, 30};
[Link](numbers[0]); // Output: 10
[Link](numbers[2]); // Output: 30

Types of Arrays

1. One-Dimensional Arrays

A one-dimensional array is a simple list of elements.

 Example:

Java

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

// Loop through the array using a for loop


for (int i = 0; i < [Link]; i++) {
[Link](fruits[i]);
}
2. Two-Dimensional Arrays

A two-dimensional array is an array of arrays, often visualized as a grid or a matrix.

 Creating a 2D array:

Java

// Declaration, instantiation, and initialization


int[][] matrix = new int[3][3]; // A 3x3 matrix

24
// Using an array literal
int[][] matrixLiteral = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};

 Accessing elements:

Java

[Link](matrixLiteral[1][2]); // Accesses element at row 1,


column 2. Output: 6

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:

String greeting = "Hello, World!";


Common String Methods:

 length(): Returns the number of characters in the string.


 charAt(index): Returns the character at the specified index.
 concat(anotherString): Appends another string to the end.
 equals(anotherString): Compares two strings for equality.
 indexOf(substring): Returns the index of the first occurrence of a substring.
 substring(startIndex, endIndex): Extracts a part of the string.
 toUpperCase(), toLowerCase(): Converts the case of the string.

String Array Example:

String[] names = {"Alice", "Bob", "Charlie"};


[Link](names[0]); // Output: Alice

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:

StringBuffer sb = new StringBuffer("Java");

Common StringBuffer Methods:

 append(String s): Appends a string to the end.

[Link](" is great"); // sb is now "Java is great"

 insert(int offset, String s): Inserts a string at a specific position.

[Link](4, " is"); // sb is now "Java is"

 replace(int start, int end, String str): Replaces a portion of the string.

[Link](0, 4, "Python"); // sb is now "Python is great"

 delete(int start, int end): Deletes characters from the buffer.

[Link](4, 7); // sb is now "Java great"

 reverse(): Reverses the sequence of characters.

[Link](); // sb is now "taerg si avaj"

 capacity(): Returns the current capacity of the buffer.

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

You might also like