[go: up one dir, main page]

0% found this document useful (0 votes)
31 views17 pages

Chapter 2

The document is a Java programming course material focused on array data types, operators, and decision-making statements. It covers definitions, declarations, initialization, accessing elements, and common operations for arrays, as well as various operators and control flow statements in Java. The content is structured for Bachelor of Technology students specializing in Cyber Security at Rashtriya Raksha University.

Uploaded by

adityarajaj189
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)
31 views17 pages

Chapter 2

The document is a Java programming course material focused on array data types, operators, and decision-making statements. It covers definitions, declarations, initialization, accessing elements, and common operations for arrays, as well as various operators and control flow statements in Java. The content is structured for Bachelor of Technology students specializing in Cyber Security at Rashtriya Raksha University.

Uploaded by

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

RASHTRIYA RAKSHA UNIVERSITY

Pioneering National Security and Police University of India An


institute of national importance.
National Security is Supreme!
Lavad – Dahegam, Gandhinagar – 382305

School of Information Technology,


Artificial Intelligence
&
Cyber Security
(SITAICS)
BACHELOR OF TECHNOLOGY
IN
COMPUTER SCIENCE & ENGINEERING
(WITH SPECIALIZATION IN CYBER SECURITY)

Semester-III
(Session 2025-26)

Java Programming
(G3AD12JPM)

Submitted by: Adityaraj jadeja


Enrollment No:25003111062032001

0|Page
Chapter 2

I. Array Data Type in Java


A. Definition and Purpose

• Definition: An ordered collection of data items of the same type, stored in


consecutive memory locations. Elements are accessed by a common name and
zero-based index.
• Purpose:
o Efficiently store and manage multiple values of the same type under a single
variable.
o Faster data processing due to contiguous memory and cache locality.
o Can store primitive types (int, char) and object references (String).
o Strict type homogeneity ensures type safety.

B. Declaration and Initialization


1. One-Dimensional Arrays

• Declaration: DataType arrayName; or DataType arrayName;


o Example: int numbers; String names;
• Initialization:
o Direct (Compile-time): DataType arrayName = {value1, value2,...};
▪ Example: int scores = {10, 15, 1, 3, 20};
o With new Keyword: DataType arrayName = new DataType[size]; (Elements
default to 0, false, or null)
▪ Example: int ages = new int;
o Individual Assignment: arrayName[index] = value;
▪ Example: int data = new int[3]; data = 100;
o Partial Initialization: Remaining elements default to 0/false/null .
▪ Example: int arr = new int[5]; arr = 10; (arr to arr are 0)
o Runtime Initialization: Using input (e.g., Scanner) .

1|Page
• Key Point: Array length is fixed once created; cannot be changed.

2. Multi-Dimensional Arrays (e.g., 2D arrays)

• Concept: Arrays of arrays, visualized as grids/matrices.


• Declaration: DataType arrayName; (for 2D) or DataType arrayName; (for 3D).
o Example: int matrix; String grid = new String[3];
• Initialization:
o Direct: int a = {{0, 0, 0}, {1, 1, 1}};
o Individual Assignment: arrayName[rowIndex][columnIndex] = value;
▪ Example: int board = new int; board = 1;
o Jagged Arrays: Rows can have different lengths .
▪ Example: int jaggedArray = new int[3]; jaggedArray = new int;
• Total Elements: Product of all dimension sizes.
• Applications: Matrices, tabular data, image representation, algorithmic
problems .

C. Accessing Elements

• Zero-based Indexing: First element at index 0 .


• Syntax: arrayName[index] .
o Example (1D): int firstElement = numbers;
o Example (2D): int element = matrix;
• Modifying Elements: arrayName[index] = newValue; .
o Example: numbers = 25;
• Caution: ArrayIndexOutOfBoundsException if index is out of range .

D. Array Length Property

2|Page
• Purpose: Returns the total number of elements in an array .
• Syntax: arrayName.length; .
o Example (1D): String colors = {"Red", "Blue"}; int len = colors.length; (len is
2)
o Example (2D): int numbers = {{1,2},{3,4}}; numbers.length; (returns number
of rows)
o numbers.length; (returns number of columns in first row)
• Distinctions:
o .length: Property for arrays.
o .length(): Method for String objects.
o .size(): Method for Collections (ArrayList, List).
• Immutability: Array length is fixed after creation.

E. Iterating Over Arrays (using loops)


1. for Loop

• Purpose: Used when the number of iterations is known . Entry-controlled.


• Syntax: for (initialization; condition; increment/decrement) { // code }
• Example (Array):
Java
int numbers = {10, 20, 30};
for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}

2. while Loop

• Purpose: Used when the number of iterations is not known beforehand. Entry-
controlled.
• Syntax: while (condition) { // code }

3|Page
• Example (Array):
Java
String names = {"Alice", "Bob"};
int i = 0;
while (i < names.length) {
System.out.println(names[i]);
i++;
}

3. do-while Loop

• Purpose: Guarantees execution at least once, then checks condition. Exit-


controlled.
• Syntax: do { // code } while (condition);
• Example (Array):
Java
double temps = {25.5, 26.1};
int i = 0;
if (temps.length > 0) {
do {
System.out.println(temps[i]);
i++;
} while (i < temps.length);
}

4. Nested Loops

• Definition: One loop entirely inside another. Inner loop completes all
iterations for each outer loop iteration.

4|Page
• Purpose: Processing multi-dimensional data (e.g., 2D arrays), generating
patterns .
• Example (2D Array):
Java
int arr = {{1, 2}, {3, 4}};
for (int i = 0; i < arr.length; i++) { // Outer loop for rows
for (int j = 0; j < arr[i].length; j++) { // Inner loop for columns
System.out.print(arr[i][j] + " ");
}
System.out.println();
}

• break Behavior: break terminates only the innermost loop.

5. Enhanced for Loop (for-each)

• Purpose: Simplified iteration over arrays/collections. No explicit index


management.
• Syntax: for (Type variableName : collectionName) { // Body of loop }
• Example:
Java
int numbers = {1, 2, 3};
for (int number : numbers) {
System.out.println(number);
}

• Use Cases: Accessing every element, when index is not needed, read-only
operations.
• Limitations: Cannot modify array elements, cannot access index, not suitable
for partial/non-sequential traversal.

F. Common Operations
1. Sorting

5|Page
• Arrays.sort() Method: Sorts arrays in ascending order .
o Usage: Primitive types (dual-pivot Quicksort), objects (Mergesort) .
o Syntax:
▪ Arrays.sort(array); (entire array)
▪ Arrays.sort(array, start, end); (subarray, end exclusive)
o Example:
Java
import java.util.Arrays;
int numbers = {5, 3, 8};
Arrays.sort(numbers); // numbers is now {3, 5, 8}

o Descending Order: For object arrays, use Collections.reverseOrder() (requires


wrapper classes like Integer) .
Java
import java.util.Collections;
Integer a = {2, -1, 3};
Arrays.sort(a, Collections.reverseOrder()); // a is now {3, 2, -1}

o Note: Modifies original array in-place .

2. Searching

• Arrays.binarySearch() Method: Efficiently locates a value in a sorted array .


o Requirement: Array must be sorted in ascending order . Undefined results if
unsorted .
o Algorithm: Divides search space in half repeatedly (O(log n) time complexity) .
o Syntax:
▪ Arrays.binarySearch(array, key);
▪ Arrays.binarySearch(array, startIndex, endIndex, key);
o Return Values:
▪ Found: Returns index of the key .
▪ Not Found: Returns (-(insertion point) - 1) .
▪ Insertion point: Index where key would be inserted to maintain sort order .

6|Page
o Example:
Java
import java.util.Arrays;
char vowels = {'a', 'e', 'i', 'o', 'u'};
int index = Arrays.binarySearch(vowels, 'i'); // index is 2
int notFound = Arrays.binarySearch(vowels, 'z'); // notFound is -6 (insertion
point 5)

3. Copying

• Arrays.copyOf() Method: Creates a new array that is a copy of an original


array with a specified new length.
o Syntax: public static <T> T copyOf(T original, int newLength).
o Behavior:
▪ newLength < original.length: Truncates array.
▪ newLength > original.length: Pads with default values (0, false, null).
o Shallow Copy: For object arrays, only references are copied, not objects
themselves.
o Efficiency: Uses System.arraycopy() internally for performance.
o Example:
Java
import java.util.Arrays;
int original = {1, 2, 3};
int copy = Arrays.copyOf(original, original.length); // {1, 2, 3}
int resized = Arrays.copyOf(original, 5); // {1, 2, 3, 0, 0}
int truncated = Arrays.copyOf(original, 2); // {1, 2}

• System.arraycopy(): Low-level, highly efficient native method for copying


elements between arrays.

II. Java Operators


1. Arithmetic Operators

7|Page
Used for basic mathematical operations.

Operator Description Example (A = 10, B = 20)

+ Addition A + B gives 30

- Subtraction A - B gives -10

* Multiplication A * B gives 200

/ Division B / A gives 2

% Modulus (remainder) B % A gives 0

2. Relational Operators
Used to compare two operands, returning true or false .

Operator Description Example (A = 10, B = 20)

== Equal to (A == B) is false

!= Not equal to (A!= B) is true

> Greater than (A > B) is false

< Less than (A < B) is true

>= Greater than or equal to (A >= B) is false

<= Less than or equal to (A <= B) is true

3. Logical Operators
Used to combine boolean expressions, returning true or false .

8|Page
Operator Description Example (A = true, B = false)

&& Logical AND (both true) (A && B) is false

` `

! Logical NOT (reverses boolean) !(A && B) is true

4. Bitwise Operators
Operate on individual bits of integer operands.

Operator Description Example (A = 60 (0011 1100), B = 13


(0000 1101))

& Bitwise AND (A & B) gives 12 (0000 1100) 25

` ` Bitwise OR

^ Bitwise XOR (A ^ B) gives 49 (0011 0001) 25

~ Bitwise Complement (~A) gives -61 (1100 0011) 25


(unary)

<< Left shift left_operand << number (multiplies by


2N, fills with 0s)

>> Signed Right shift left_operand >> number (divides by 2N,


fills with sign bit)

>>> Unsigned Right shift left_operand >>> number (fills with 0s,
regardless of sign)

5. Assignment Operators
Assign values to variables.

9|Page
Operator Description Example (C = 10, A = 20)

= Simple assignment C = A + B 25

+= Add AND assign C += A (C = C + A) 25

-= Subtract AND assign C -= A (C = C - A) 25

*= Multiply AND assign C *= A (C = C * A) 25

/= Divide AND assign C /= A (C = C / A) 25

%= Modulus AND assign C %= A (C = C % A) 25

<<= Left shift AND assign C <<= 2 (C = C << 2) 25

>>= Right shift AND assign C >>= 2 (C = C >> 2) 25

>>>= Unsigned right shift AND assign C >>>= 2 (C = C >>> 2) 23

&= Bitwise AND assign C &= 2 (C = C & 2) 25

^= Bitwise XOR assign C ^= 2 (C = C ^ 2) 25

` =` Bitwise OR assign

6. Unary Operators
Operate on a single operand.

Operator Description

+ Unary plus (indicates positive value) 28

- Unary minus (negates expression) 28

++ Increment (increases by 1) 28

10 | P a g e
-- Decrement (decreases by 1) 28

! Logical NOT (inverts boolean value) 28

• Prefix vs. Postfix: ++x (increments then uses), x++ (uses then increments).

7. Ternary Operator

• Purpose: Concise if-else for conditional expressions, returns a value.


• Syntax: condition? value_if_true : value_if_false;
• Example:
Java
int a = 10, b = 5;
int max = (a > b)? a : b; // max is 10

• Note: Cannot be used for void methods.16 Nesting is possible but reduces
readability.

8. Instanceof Operator

• Purpose: Checks if an object is an instance of a specific class/subclass or


implements an interface . Returns true or false .
• Syntax: object instanceof ClassName or object instanceof InterfaceName .
• Use Cases: Type safety before casting, polymorphism, checking interface
implementation .
• Note: Returns false if object is null . Overuse can indicate poor design .
• Example:
Java
String str = "Hello";
boolean isString = str instanceof String; // true
Object obj = new Integer(10);
boolean isInteger = obj instanceof Integer; // true

III. Decision-Making Statements

11 | P a g e
A. if statement

• Structure: if (condition) { // code }.


• Use Cases: Executes code block only if condition is true.
• Example:
Java
int speed = 10;
if (speed > 0) {
System.out.println("Moving.");
}

B. if-else statement

• Structure: if (condition) { // true code } else { // false code }.


• Use Cases: Provides alternative execution path when if condition is false.
• Example:
Java
int temp = 25;
if (temp > 30) {
System.out.println("Hot.");
} else {
System.out.println("Not too hot.");
}

C. if-else-if ladder

• Structure: Chained if-else statements.


• Use Cases: Evaluates multiple conditions sequentially; executes first matching
block, then skips rest.15 Ideal for mutually exclusive conditions (e.g., grading).
• Example:
Java
int score = 76;
char grade;

12 | P a g e
if (score >= 90) { grade = 'A'; }
else if (score >= 80) { grade = 'B'; }
else if (score >= 70) { grade = 'C'; } // This matches
else { grade = 'F'; }
System.out.println("Grade = " + grade); // Output: C

D. switch statement

• Purpose: Multi-way branch statement; executes one of many code blocks based
on an expression's value. Alternative to long
if-else-if for single variable comparison.
• Syntax:
Java
switch(expression) {
case value1: // code; break;
case value2: // code; break;
default: // code;
}

• Key Points:
o Expression Type: int, char, short, byte, String, wrapper classes, enum (JDK
7+).
o Case Values: Must be literal/constant, unique, same type as expression.
o break: Terminates switch block. Omitting causes "fall-through" to next case.
o default: Optional, executed if no case matches.
o Nesting: Allowed.
• Example:
Java
int month = 4;
switch (month) {
case 1: System.out.println("Jan"); break;
case 4: System.out.println("Apr"); break; // Matches
default: System.out.println("Other");
} // Output: Apr

13 | P a g e
IV. Looping Constructs
A. for loop

• Description: Iterates a known number of times . Entry-controlled.


• Syntax: for (initialization; condition; increment/decrement) { // code }
• Example:
Java
for (int i = 1; i <= 5; i++) {
System.out.print(i + " ");
} // Output: 1 2 3 4 5

B. while loop

• Description: Repeats as long as condition is true.12 Number of iterations


unknown.12 Entry-controlled.
• Syntax: while (condition) { // code }
• Example:
Java
int i = 0;
while (i < 3) {
System.out.print(i + " ");
i++;
} // Output: 0 1 2

C. do-while loop

• Description: Executes code block at least once, then checks condition. Exit-
controlled.
• Syntax: do { // code } while (condition);
• Example:
Java
int i = 0;

14 | P a g e
do {
System.out.print(i + " ");
i++;
} while (i < 3); // Output: 0 1 2

D. Nested loops

• Description: One loop inside another.Inner loop completes all iterations for
each outer loop iteration.
• Purpose: Processing multi-dimensional data (e.g., 2D arrays), generating
patterns .
• Example (2D Array):
Java
int matrix = {{1, 2}, {3, 4}};
for (int i = 0; i < matrix.length; i++) { // Rows
for (int j = 0; j < matrix[i].length; j++) { // Columns
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
/* Output:
12
34
*/

E. Enhanced for loop (for-each)

• Description: Simplified iteration over arrays/collections. No explicit index


management.
• Syntax: for (Type variableName : collectionName) { // Body of loop }
• Use Cases: Accessing every element, when index is not needed, read-only
operations.
• Limitations: Cannot modify array elements, cannot access index, not suitable
for partial/non-sequential traversal.

15 | P a g e
• Example:
Java
String names = {"Anna", "Ben"};
for (String name : names) {
System.out.println(name);
}

16 | P a g e

You might also like