0% found this document useful (0 votes)
36 views24 pages

Cos201 (Java)

The document provides an introduction to the Java programming language, detailing its history, key features, and various editions. It covers fundamental concepts such as data types, variables, operators, and control statements, along with examples of Java syntax and structure. Additionally, it includes simple Java program examples to illustrate the application of these concepts.
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)
36 views24 pages

Cos201 (Java)

The document provides an introduction to the Java programming language, detailing its history, key features, and various editions. It covers fundamental concepts such as data types, variables, operators, and control statements, along with examples of Java syntax and structure. Additionally, it includes simple Java program examples to illustrate the application of these concepts.
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

JAVA PROGRAMMING LANGUAGE

Module 1: Introduction to Java Programming Language

Java is a high-level, general-purpose programming language that was designed by James Gosling
at Sun Microsystems and first released in 1995. It is object-oriented and intended to let developers
“write once, run anywhere” (WORA) – Java code is compiled into platform-independent
bytecode that runs on any device with a Java Virtual Machine (JVM). Java quickly gained
popularity and is now owned by Oracle Corporation (after it acquired Sun in 2010). It remains
widely used, with more than 3 billion devices running Java.

Java was developed by James Gosling and his team at Sun Microsystems in the early 1990s.
Originally designed for interactive television, the language was initially called Oak, but it was later
renamed Java in 1995 due to trademark issues.

Key milestones in Java’s history:


1. 1991 – Project “Green” was initiated by Sun Microsystems to develop a language for embedded
systems.
2. 1995 – Java 1.0 was released with the slogan “Write Once, Run Anywhere (WORA)”,
emphasizing its platform independence via the Java Virtual Machine (JVM).
3. 1997–2006 – Java gained popularity for web development and enterprise applications.
4. 2010 – Oracle Corporation acquired Sun Microsystems and took over Java’s development.
5. Ongoing – Java continues to evolve, with recent versions focusing on performance
improvements, modularity, and new language features.

Key Features of Java Programming Language


1. Object-Oriented: Everything in Java is treated as an object, making it easy to build
modular programs and reusable code. Java is Object oriented in the sense that it supports
principles like inheritance, polymorphism, encapsulation, etc.
2. Platform Independent: Java code is compiled to bytecode, which can run on any
platform via the JVM (Java Virtual Machine). This feature enables Java programs to run
seamlessly on any platform, regardless of the hardware or operating system.
3. Simple & Familiar: Java has a clean and easy-to-understand syntax, primarily influenced
by C/C++, but without complex features like pointers or multiple inheritance
4. Secure: Java has built-in security features like bytecode verification, sandboxing, and
runtime security checks to protect against malicious code.
5. Robust: Java emphasizes early error checking, strong memory management, and exception
handling, making it reliable and stable.
6. Multithreaded: Java supports multithreading — the ability to run multiple threads (parts
of a program) concurrently, making it ideal for interactive and networked applications.
7. High Performance: While Java is not as fast as native C/C++, Java performance is
enhanced through Just-In-Time (JIT) compilers., making Java performance close to native
in many cases.
8. Distributed: Java supports networking and remote method invocation (RMI), making it
suitable for distributed applications.
9. Java supports dynamic loading of classes at runtime, meaning code can evolve and adapt
without recompilation.

Java Editions and Installation


Java is available in several editions, each tailored for specific types of application development.
The main Java Editions are:
1. Java Standard Edition (Java SE) is the core foundation of the Java programming language.
It provides all the essential libraries and APIs for general-purpose programming, including
utilities for data structures, input/output, networking, and multithreading. Java SE is
primarily used to develop standalone desktop applications and forms the base for other
Java editions.

2. Java Enterprise Edition (Java EE), now known as Jakarta EE, extends Java SE by adding
tools and libraries for building large-scale, distributed, and web-based enterprise
applications. It supports technologies like Servlets, JavaServer Pages (JSP), Enterprise
JavaBeans (EJB), and web services. This edition is widely used for developing enterprise-
level server-side applications and is popular in banking, e-commerce, and other large
organizations.

3. Java Micro Edition (Java ME) is a stripped-down version of Java designed for resource-
constrained devices like feature phones, smart cards, embedded systems, and Internet of
Things (IoT) devices. It includes a subset of Java SE libraries and provides a lightweight
runtime environment optimized for mobile and embedded applications.
4. JavaFX is a platform for building rich desktop applications with advanced user interfaces,
media playback, and graphics. Though not an official standalone edition like the others,
JavaFX is often used alongside Java SE to develop modern, visually appealing desktop
applications with support for 2D/3D graphics and animation.

A Simple Java Program: Once Java is installed, you can write your first program. All Java code
is defined inside classes.
For example, here is a simple “Hello World” program to demonstrate the structure of a Java
application:
public class HelloWorld {
public static void main(String[] args) {
[Link]("Hello, Java!");
}
}
In this code:
• public class HelloWorld declares a class named HelloWorld. The file name should match
the class name (e.g., [Link]).
• Inside the class, the main method is defined as public static void main(String[] args). This
method is the entry point of any Java application – when you run the program, the code
inside main executes.
• [Link](...) prints text to the console. Here it will print Hello, Java!.

To compile this program, you would use javac [Link] which produces a
[Link] (bytecode). Then run it with java HelloWorld, which invokes the JVM to execute
the main method.

Java Syntax and Structure


Java’s syntax is derived from C/C++, making it familiar if you have experience with those
languages. However, Java enforces an object-oriented structure (all code resides in classes) and
strong typing. Let’s go over the basic building blocks of Java syntax:
Basic Structure of Java Programming Language
A Java source file contains at most one public class (whose name matches the file). Inside the class,
you define methods (functions) and variables. Execution of a Java program begins at the main
method as shown in the introduction.

Defining the Class: public class Main


• public: This is an access modifier, meaning that the class is accessible from any other class
in any package. It allows other parts of your application or even other applications to use
this class if needed.
• class: This keyword is used to declare a class in Java. A class serves as a blueprint for
objects.
• Main: The name of the class. In many simple programs and examples, the class containing
the main method is named Main. The file name must match the class name (for instance,
it should be saved as [Link]).

The main Method: public static void main(String[] args)


The main method is crucial because it serves as the entry point for any standalone Java application.
Let's break down each keyword and part:
• public: Again, this is an access modifier. When a method is declared as public, it can be
accessed from outside the class. For the main method, it must be public so that the Java
Virtual Machine (JVM) can access it to start the program.
• static: This indicates that the method belongs to the class itself, rather than to any
particular instance (object) of the class. The JVM calls this method without needing to
create an instance of the class.
• void: This is the return type of the method. In this case, void means that the method does
not return any value.
• main: This is the name of the method. The JVM looks for this particular method signature
to begin executing the program.
• String[] args: This parameter is an array of String objects. It allows you to pass command-
line arguments to your application. For example, if you run your program with additional
parameters, they will be stored in this array. If no arguments are passed, the array will be
empty.
Module 2: Java Fundamentals
Data Types in Java Programming Language
Java is a statically-typed language, meaning every variable and expression type is known at
compile time. There are primitive data types and reference types. Java has eight primitive data
types: byte, short, int, long, float, double, boolean, and char. These cover integers of various sizes,
floating-point numbers, boolean values (true/false), and single characters. For example:
1. int – 32-bit integer (e.g., 42, -7)
2. double – 64-bit floating-point number (e.g., 3.14)
3. boolean – can only be true or false
4. char – 16-bit Unicode character (e.g., 'A')
In addition to primitives, all other types in Java are objects (instances of classes). For example,
String (for text) is a commonly used non-primitive type (actually a class in Java’s API). Array types
(e.g., int[]) and classes you define yourself are also reference types.

Variables and Declarations in Java Programming Language


To use data, you declare variables by specifying the type followed by the name. For instance: Java
variable names should start with a letter and can contain letters, digits, underscore, or dollar sign.
By convention, they start with a lowercase letter (e.g., studentName). Java is case-sensitive (count
and Count are different variables). Local variables (inside methods) must be initialized before use.
For object references, you use the new keyword to instantiate a class (e.g., Scanner sc = new
Scanner([Link]);). As of Java 10, you can use var for local variable type inference (the compiler
deduces the type), but using explicit types is recommended for clarity in learning.

Operators in Java programming language


Java operators are special symbols that perform operations on variables and values. They are used
to manipulate data and variables in expressions. Java provides a wide array of operators categorized
into several types based on their functionality
1. Arithmetic operators: Arithmetic operators are used to perform basic mathematical
operations.

• + (Addition)

• - (Subtraction)

• * (Multiplication)
• / (Division)

• % (Modulus)

Example:

int a = 10;
int b = 5;
[Link]("Addition: " + (a + b)); // Output: 15
[Link]("Subtraction: " + (a - b)); // Output: 5
[Link]("Multiplication: " + (a * b));// Output: 50
[Link]("Division: " + (a / b)); // Output: 2
[Link]("Modulus: " + (a % b)); // Output: 0

2. Assignment operators are used to assign values to variables.

• = (Simple assignment)

• += (Add and assign)

• -= (Subtract and assign)

• *= (Multiply and assign)

• /= (Divide and assign)

• %= (Modulus and assign)

Example:

int a = 10;
a += 5; // Equivalent to a = a + 5
[Link](a); // Output: 15
a -= 5; // Equivalent to a = a – 5
[Link](a); // Output: 5

3. Relational operators are used to compare two values.

• == (Equal to)

• != (Not equal to)

• > (Greater than)

• < (Less than)

• >= (Greater than or equal to)


• <= (Less than or equal to)

Example:

int a = 10;
int b = 5;
[Link](a == b); // Output: false
[Link](a > b); // Output: true
[Link](a < b); // Output: false

4. Unary Operators Unary operators operate on a single operand.

• + (Unary plus)

• - (Unary minus)

• ++ (Increment)

• -- (Decrement)

Example:

int a = 10;
[Link](++a); // Output: 11
[Link](--a); // Output: 10

5. Logical operators are used to combine multiple boolean expressions.

• && (Logical AND)

• || (Logical OR)

• ! (Logical NOT)

Example:

boolean x = true;
boolean y = false;
[Link](x && y); // Output: false
[Link](x || y); // Output: true
[Link](!x); // Output: false
Module 3: Control statements in Java Programming Language

Control statement in Java programming are the building blocks of any program that dictate the
flow of execution. They enable us to control how, when, and under what conditions different parts
of the program are executed. By utilizing control statements, we can make decisions, repeat actions,
or execute specific parts of the code based on certain conditions.

Decision making statement: if statements (and optional else/else if clauses) to execute code
based on conditions.

1. If Statement: The if statement evaluates a boolean expression and executes a block of code
only if the expression evaluates to true. It's used to make decisions in the program flow.

Example: Write a java program code to check if a number is positive

public class Main {


public static void main(String[] args) {
int number = 10;

if (number > 0) {
[Link]("The number is positive.");
}
}
}

2. If-else Statement: The if-else statement in Java is a fundamental control flow mechanism that
allows a program to execute certain code blocks based on whether a given condition is true or
false. It helps create decision-making paths in your programs, meaning your code can react
differently depending on inputs or program states.

Syntax:

if (condition) {
// Code to execute if condition is true
} else {
// Code to execute if condition is false
}

Example 1: Write a Java program to determine whether a person is eligible to vote

public class AgeCheck {


public static void main(String[] args) {
int age = 20; // You can change this value to test different
outcomes
if (age >= 18) {
[Link]("You are eligible to vote.");
} else {
[Link]("You are not eligible to vote yet.");
}
}
}

Example 2: Write a Java program to determine or check voter eligibility

import [Link];
public class VoterEligibility {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter your age: ");
int age = [Link]();
// Use if-else to determine eligibility
if (age >= 18) {
[Link]("You are eligible to vote.");
} else {
[Link]("You are not eligible to vote.");
}
[Link]();
}

3. The if-else if-else Ladder: The if-else if-else ladder in Java is a powerful control structure that
allows you to test multiple conditions sequentially. It evaluates conditions one by one and executes
the code block corresponding to the first true condition, skipping the rest. This structure is
particularly useful when you have several mutually exclusive conditions to handle.

Syntax:

if (condition1) {
// Code to execute if condition1 is true
} else if (condition2) {
// Code to execute if condition2 is true
} else {
// Code to execute if none of the above conditions are true
}

Example 1: Write a Java program to assign a grade based on a numberical score

import [Link];
public class GradeAssigner {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
// Prompt user for input
[Link]("Enter the student's score (0 - 100): ");
int score = [Link]();
String grade;
// Validate input and assign grade
if (score >= 70 && score <= 100) {
grade = "A";
} else if (score >= 60 && score <= 69) {
grade = "B";
} else if (score >= 50 && score <= 59) {
grade = "C";
} else if (score >= 45 && score <= 49) {
grade = "D";
} else if (score >= 40 && score <= 44) {
grade = "E";
} else if (score >= 0 && score <= 39) {
grade = "F";
} else {
grade = "Invalid score. Please enter a number between 0 and
100.";
}
// Display result
[Link]("Grade: " + grade);
[Link]();
}

Example 2: Write a Java program to develop a basic calculator that performs addition, subtraction,
multiplication, and division based on user input:

import [Link];
public class BasicCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
// Get first number from user
[Link]("Enter the first number: ");
double num1 = [Link]();
// Get operator from user
[Link]("Enter an operator (+, -, *, /): ");
char operator = [Link]().charAt(0);
// Get second number from user
[Link]("Enter the second number: ");
double num2 = [Link]();
double result;
// Perform calculation based on the operator
if (operator == '+') {
result = num1 + num2;
[Link]("Result: " + result);
} else if (operator == '-') {
result = num1 - num2;
[Link]("Result: " + result);
} else if (operator == '*') {
result = num1 * num2;
[Link]("Result: " + result);
} else if (operator == '/') {
if (num2 != 0) {
result = num1 / num2;
[Link]("Result: " + result);
} else {
[Link]("Error: Division by zero is not
allowed.");
}
} else {
[Link]("Invalid operator. Please use +, -, *, or
/.");
}
[Link]();
}
}

Example 3: Write a java program that determines the days of the week based on user input

import [Link];
public class DayOfWeek {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
// Ask the user to enter a number between 1 and 7
[Link]("Enter a number (1 to 7) to get the
corresponding day of the week: ");
int dayNumber = [Link]();
String day;
// Determine the day based on user input
if (dayNumber == 1) {
day = "Monday";
} else if (dayNumber == 2) {
day = "Tuesday";
} else if (dayNumber == 3) {
day = "Wednesday";
} else if (dayNumber == 4) {
day = "Thursday";
} else if (dayNumber == 5) {
day = "Friday";
} else if (dayNumber == 6) {
day = "Saturday";
} else if (dayNumber == 7) {
day = "Sunday";
} else {
day = "Invalid input. Please enter a number between 1 and
7.";
}
// Print result
[Link]("Day: " + day);
[Link]();
}
}

4. Switch Statement: The switch statement in Java is a control statement used to simplify
complex decision-making when multiple conditions are based on the same variable or
expression. It serves as a cleaner alternative to long if-else-if chains, especially when checking a
single variable against many constant values.
Syntax:

switch (expression) {
case value1:
// code block
break;
case value2:
// code block
break;
...
default:
// default code block
}

• The expression must evaluate to a byte, short, int, char, String, or enum (since Java 7, String
is supported).
• The case labels must be constant values.
• The break statement terminates the switch block; without it, fall-through occurs, meaning
execution continues to the next case even if it doesn't match.
• The default case is optional and acts as a fallback if no case matches.

Example 1: Using switch statement, write a Java program to determine the days of the week based
on user input

int day = 3;
switch (day) {
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;
case 6:
[Link]("Saturday");
break;
case 7:
[Link]("Sunday");
break;
default:
[Link]("Invalid day number");
}

Example 2: Using switch statement, write a java programming to generate remarks based on letter
grades

char grade = 'B';


switch (grade) {
case 'A':
[Link]("Excellent!");
break;
case 'B':
[Link]("Very Good!");
break;
case 'C':
[Link]("Good!");
break;
case 'D':
[Link]("Pass!");
break;
case 'F':
[Link]("Fail!");
break;
default:
[Link]("Invalid grade.");
}

Structure Use Case Syntax Simplicity Suitable For


if One condition Simple Basic decisions
if-else Two possible outcomes Simple True/false decisions
if-else-if Multiple mutually exclusive conditions Moderate Grading, classification logic
switch Comparing one variable to fixed Cleaner structure Menus, options, fixed categories
values

Module 4: Looping Contructs in Java Programming Language

Loops in Java Programming Language: In Java programming, loops are essential constructs that
allow a set of statements to execute repeatedly based on a condition. This process of repetition is
called iteration, and Java provides three primary types of loops: the for loop, the while loop, and
the do-while loop. Each of these loops is used in different scenarios, depending on the nature and
predictability of the condition that governs repetition.

1. The while Loop

The while loop is an entry-controlled loop. It checks the condition before executing the loop
body. If the condition is false from the beginning, the loop body will not execute even once.
Syntax

while (condition) {
// code block to be executed repeatedly
}

Flowchart Explanation:

1. Check the condition.


2. If true, execute the loop body.
3. After executing, re-check the condition.
4. Repeat steps 2 and 3 until the condition becomes false.

Examples of while Loop

Example 1: Print numbers from 1 to 5

int i = 1;
while (i <= 5) {
[Link](i);
i++;
}

Example 2: Sum of natural numbers up to 100

int sum = 0;
int i = 1;
while (i <= 100) {
sum += i;
i++;
}
[Link]("Sum is: " + sum);

2. The do-while Loop

The do-while loop is an exit-controlled loop. The loop body executes at least once, regardless
of the condition. After the first execution, the condition is checked.

Syntax:

do {
// loop body
} while (condition);
Flowchart Explanation:

1. Execute the loop body.


2. Check the condition.
3. If true, repeat step 1.
4. If false, exit the loop.

Example: Password retry system

import [Link];

Scanner scanner = new Scanner([Link]);


String password;

do {
[Link]("Enter password: ");
password = [Link]();
} while (![Link]("admin123"));

[Link]("Access Granted");

3. For Loop

The for loop is the most commonly used loop when the number of iterations is known ahead of
time. It is especially suitable for situations where a variable needs to be initialized, a condition
needs to be checked before every iteration, and a counter or iterator needs to be updated after
each pass.

Syntax:

for (initialization; condition; update) {


// block of code to be executed
}

Here, the initialization occurs once at the beginning of the loop. The condition is evaluated before
every iteration, and if it is true, the body of the loop is executed. After executing the body, the
update expression runs. Then the condition is evaluated again, and the cycle repeats until the
condition becomes false.

Example:

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


[Link]("Iteration: " + i);
}

This loop prints the numbers from 1 to 5. The variable i starts at 1 and increases by 1 on each
iteration until it exceeds 5.

Example 1: Write a java program to print the sum of First N Natural Numbers

public class SumUsingForLoop {


public static void main(String[] args) {
int n = 10;
int sum = 0;
for (int i = 1; i <= n; i++) {
sum += i;
}
[Link]("Sum of first " + n + " natural numbers is: "
+ sum);
}
}

Explanation: This program calculates the sum of the first 10 natural numbers using a for loop. The
loop starts at 1 and adds each number to sum until it reaches 10.

Example 2: Print even numbers between 1 and 20

for (int i = 2; i <= 20; i += 2) {


[Link](i + " ");
}

Example 3: Multiplication Table of 7

int num = 7;
for (int i = 1; i <= 10; i++) {
[Link](num + " x " + i + " = " + (num * i));
}

Example 4: Factorial of a number

int n = 5;
int factorial = 1;

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


factorial *= i;
}
[Link]("Factorial of " + n + " is " + factorial);
Use Cases of for Loops
• Iterating over a range of numbers.
• Looping through arrays or collections.
• Repeating actions with known iteration count.
• Implementing algorithms like searching, sorting, etc.

Comparison of for, while, and do-while Loops


Feature for Loop while Loop do-while Loop

Initialization Inside loop header Before loop Before loop

Condition checked Before each iteration Before each iteration After each iteration

Guaranteed 1st run? No No Yes

Best use case Known iterations Unknown, conditional Menu-driven programs


Module 5: Chapter 5: Methods and Recursion

Introduction to Methods

A method in Java is a block of code that performs a specific task. It is also known as a function
in other programming languages. Methods help break a program into smaller, manageable parts,
encourage reusability, and enhance readability.

Java methods are defined inside classes and can be called (invoked) to execute when needed.

Syntax for defining a method in Java

returnType methodName(parameter1, parameter2, ...) {


// method body
// return statement (if returnType is not void)
}

• returnType: The type of value the method returns (e.g., int, String, void).
• methodName: The name of the method (should follow Java naming conventions).
• parameters: Inputs passed to the method (optional).
• method body: The code that runs when the method is called.

Types of Methods in Java

1. Void methods: Perform a task but do not return a value.

void display() {
[Link]("This method returns nothing.");
}

2. Value-returning methods: Perform a task and return a result.

double square(double x) {
return x * x;
}

Method Overloading

Java allows multiple methods with the same name as long as they have different parameter
lists (number, type, or order of parameters). This is called method overloading.
Example: Overloaded methods

int multiply(int a, int b) {


return a * b;
}
double multiply(double a, double b) {
return a * b;
}

Why Use Methods?

• Modularity: Breaks a large program into smaller, manageable parts.


• Reusability: One method can be used in multiple places.
• Readability: Code is easier to read and maintain.
• Abstraction: Hides complex logic behind simple method calls

Recursion in Java

What is Recursion?

Recursion is the process where a method calls itself to solve a problem. A recursive method
solves a small part of a problem and relies on itself to solve the remaining part.

Key Components of Recursion:

1. Base Case – The condition at which the recursion stops.


2. Recursive Case – The part where the method calls itself.

Example: Factorial using recursion

int factorial(int n) {
if (n == 0 || n == 1) {
return 1; // Base case
} else {
return n * factorial(n - 1); // Recursive case
}
}
Advantages of Recursion

• Simplifies problems that have recursive nature (like tree traversal, backtracking, etc.).
• Reduces code length for complex algorithms.

Disadvantages of Recursion

• May consume more memory due to function call stack.


• Can lead to stack overflow if base case is not properly defined.
• Usually slower than iterative solutions due to overhead of function calls.

Comparison: Recursion vs Iteration

Feature Recursion Iteration

Concept Function calls itself Looping (for/while/do-while)

Termination Base case Loop condition

Memory use More (uses call stack) Less

Speed Slower due to overhead Generally faster

Clarity More natural for some problems More straightforward

Module 6: Arrays and Strings

What is an Array?

An array in Java is a container object that holds a fixed number of elements of the same data
type. The elements are stored in contiguous memory locations and accessed using indexing,
starting from index 0.

Declaring and Initializing an Array

There are two main steps in using arrays:

1. Declaration: Define the type of array.


2. Instantiation/Initialization: Allocate memory and optionally assign values.
Syntax:

int[] numbers; // Declaration


numbers = new int[5]; // Memory allocation for 5 integers

// Or combined:
int[] numbers = new int[5];

Assigning Values:

numbers[0] = 10;
numbers[1] = 20;
...

Or use array initializer:

int[] numbers = {10, 20, 30, 40, 50};

Types of Arrays

1. One-Dimensional Arrays

A one-dimensional array stores data in a single row or line.

Example: Sum of elements

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


int sum = 0;
for (int i = 0; i < [Link]; i++) {
sum += nums[i];
}
[Link]("Sum: " + sum); // Output: 15

2. Multidimensional Arrays (2D Arrays)

A 2D array is like a table or matrix with rows and columns.

Declaration and Initialization:

int[][] matrix = new int[3][3]; // 3 rows, 3 columns


// Or:

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

Common Array Algorithms

1. Linear Search: This is the simplest searching technique used in arrays. It works by checking each
element of the array one after the other until it finds the element being searched for or reaches the
end of the array. If the element is found, its index is returned or printed; otherwise, a message
indicates that the element is not present. This method is ideal for unsorted arrays.

Searches for an element by checking each index.

int[] arr = {5, 8, 2, 7};


int key = 7;
boolean found = false;
for (int i = 0; i < [Link]; i++) {
if (arr[i] == key) {
found = true;
break;
}
}

[Link](found ? "Found" : "Not Found");

2. Bubble Sort (Ascending Order): This is a basic sorting technique used to arrange elements in
ascending or descending order. It repeatedly compares adjacent elements and swaps them if they
are in the wrong order. This process is repeated for each pass through the array until the entire
array is sorted. Although simple, bubble sort is not efficient for large datasets.

int[] arr = {5, 3, 8, 4, 2};


for (int i = 0; i < [Link] - 1; i++) {
for (int j = 0; j < [Link] - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
3. Finding Maximum or Minimum element: Finding the Maximum and Minimum in an array
involves comparing elements to determine the largest or smallest value. The process typically starts
by assuming the first element is the maximum or minimum, and then iterating through the rest of
the array to update this value whenever a larger or smaller element is found. These algorithms are
useful in real-life scenarios like finding the highest score, the lowest price, or the longest distance.

int[] nums = {10, 30, 20, 50, 40};


int max = nums[0];
for (int i = 1; i < [Link]; i++) {
if (nums[i] > max) {
max = nums[i];
}
}
[Link]("Maximum: " + max);

4. Merging Two Arrays: This combines two different arrays into a single one. This is done by
creating a new array large enough to hold all the elements from both arrays and then copying the
elements from the first and second arrays in sequence. Merging is used in data integration or
sorting procedures.

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


int[] b = {4, 5, 6};
int[] merged = new int[[Link] + [Link]];
for (int i = 0; i < [Link]; i++) {
merged[i] = a[i];
}
for (int i = 0; i < [Link]; i++) {
merged[[Link] + i] = b[i];
}
[Link]([Link](merged)); // Output: [1, 2, 3, 4, 5,
6]

5. Removing Duplicate Elements from an array involves checking whether an element has already
occurred earlier in the array. If it has, it is skipped; otherwise, it is printed or stored. This approach
helps in filtering unique values from data.

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

[Link]("Unique elements: ");


for (int i = 0; i < [Link]; i++) {
boolean isDuplicate = false;
for (int j = 0; j < i; j++) {
if (arr[i] == arr[j]) {
isDuplicate = true;
break;
}
}
if (!isDuplicate) {
[Link](arr[i] + " ");
}
}

Sum and Average: Sum and Average calculation in an array is used when the total or the mean of
all values is needed. The sum is obtained by adding all elements in a loop, and the average is then
calculated by dividing the sum by the number of elements in the array. This is commonly used in
applications like report cards or statistics.

int[] nums = {10, 20, 30, 40, 50};


int sum = 0;

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


sum += nums[i];
}

double average = (double) sum / [Link];

[Link]("Sum: " + sum); // Output: 150


[Link]("Average: " + average); // Output: 30.0

You might also like