0% found this document useful (0 votes)
2 views11 pages

3. Arrays and Strings in Java

array

Uploaded by

Aditya kr. Singh
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)
2 views11 pages

3. Arrays and Strings in Java

array

Uploaded by

Aditya kr. Singh
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/ 11

Arrays and Strings in Java

Learning Objectives
By the end of this session, trainees will be able to:
 Declare, initialize, and manipulate one-dimensional and two-dimensional arrays in Java.
 Apply array operations such as traversal, searching, and sorting.
 Understand the nature of String immutability and how to use StringBuffer and
StringBuilder for mutable strings.

 Differentiate between performance and use cases of String, StringBuffer, and


StringBuilder.

1. ARRAYS IN JAVA
1.1 What is an Array?
 An array is a container object that holds a fixed number of values of a single type.
 Arrays are zero-indexed.

Why Arrays?
 Useful for storing multiple values of the same type.
 Avoids declaring multiple variables.

1.2 Declaring and Initializing Arrays


📍 One-Dimensional Array (1D)
int[] marks = new int[5]; // declaration + memory allocation
marks[0] = 95; // initialization

📍 Combined Declaration + Initialization


int[] scores = {90, 80, 70, 85, 60};

🔧 1.3 Common Array Operations (1D)


Operation Code Snippet
Traversal for(int i=0;i<marks.length;i++)
Enhanced For Loop for(int mark : marks)
Finding Max Use if(arr[i] > max)
Sum & Average Loop + sum / length

1 | 11
Arrays and Strings in Java

Operation Code Snippet


Searching Linear search: if(arr[i] == target)
Sorting Arrays.sort(arr);

1.4 Two-Dimensional Array (2D)


int[][] matrix = new int[2][3]; // 2 rows, 3 columns
matrix[0][0] = 10;
matrix[0][1] = 20;

📍 Looping through 2D Array


for(int i=0; i < matrix.length; i++) {
for(int j=0; j < matrix[i].length; j++) {
System.out.print(matrix[i][j] + " ");
}
}

🧪 Hands-on Activity – Array Tasks


Write a Java program to:

 Accept 5 integers from user and print them in reverse.


 Find the maximum and minimum value from an array.

2. STRINGS IN JAVA
2.1 What is a String?
A String is a sequence of characters, treated as an object in Java (java.lang.String).

🔒 Immutability of Strings
String str = "Hello";
str.concat("World"); // does NOT change original
System.out.println(str); // Output: Hello

 Because Strings are immutable, methods like concat() return a new object.

Common String Methods


Method Description
length() Returns length
charAt(index) Returns character at index

2 | 11
Arrays and Strings in Java

Method Description
substring(start, end) Extracts part
equals(str2) Value comparison
== Reference comparison
toLowerCase() / toUpperCase() Casing
contains(), indexOf() Search

2.2 StringBuffer vs StringBuilder


Feature StringBuffer StringBuilder
Mutability Mutable Mutable
Thread-Safe ✅ Yes (synchronized) ❌ No
Speed Slower Faster
Use Case Multi-threaded apps Single-threaded apps

🔧 Code Example:
StringBuffer sb = new StringBuffer("Hello");
sb.append(" World");
System.out.println(sb); // Output: Hello World

StringBuilder sb2 = new StringBuilder("Java");


sb2.insert(4, " Programming");
System.out.println(sb2); // Output: Java Programming

Hands-on Activity – String Tasks


Write Java programs to:

 Count vowels and consonants in a string.


 Reverse a string using StringBuilder.

 Check if a string is a palindrome.


 Use StringBuffer to remove all spaces from a sentence.

Recap Questions
1. What is the difference between String, StringBuffer, and StringBuilder?

3 | 11
Arrays and Strings in Java

2. How do you reverse a string in Java?


3. Write a Java program to find the highest number in a 1D array.
4. What is the default value of an int array in Java?
5. What happens when you try to access an array element beyond its length?

📚 Self-Learning Task
Assign as homework or self-study:

 Solve 5 string-based coding problems (Anagram, Remove Duplicates, Frequency Counter,


etc.)
 Solve 3 array problems (Sorting, Linear Search, Matrix Addition)
-----------------------------------------------------------------

Example 1: Healthcare Sector – Patient Temperature Tracker


Problem Statement:
In a hospital, a nurse records each patient's temperature readings (in Celsius) taken every hour over
a 6-hour period. You are tasked to write a program that:
 Stores the hourly temperature readings in a 1D array
 Calculates the average temperature
 Checks if the temperature ever exceeded 38°C (fever alert)

Java Code:
import java.util.Scanner;

public class TemperatureTracker {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double[] temperatures = new double[6];
double sum = 0;
boolean fever = false;

System.out.println("Enter temperature readings (°C) for 6 hours:");

for (int i = 0; i < temperatures.length; i++) {


System.out.print("Hour " + (i + 1) + ": ");
temperatures[i] = sc.nextDouble();
sum += temperatures[i];
if (temperatures[i] > 38.0) {
fever = true;
}
}

4 | 11
Arrays and Strings in Java

double average = sum / temperatures.length;

System.out.println("\nAverage Temperature: " + average + "°C");


if (fever) {

doctor!");
System.out.println(" ⚠️
Fever detected during the period. Inform

} else {
System.out.println("No fever detected.");
}

sc.close();
}
}

Concepts Used:
 1D Arrays
 Enhanced logic with if condition

 Sum/Average operations
 Input from user

Example 2: Financial Sector – Transaction Summary with Masked


Account Numbers
Problem Statement:
A banking application needs to display a transaction log where:
 User account numbers are masked except the last 4 digits.
 Each transaction is appended to a growing summary message using StringBuilder for
efficient concatenation.

Java Code:
public class TransactionLog {
public static void main(String[] args) {
String[] accountNumbers = {
"1234567890123456",
"9876543210987654"
};

double[] transactionAmounts = {1500.00, -700.00}; // positive = credit,


negative = debit

n");
StringBuilder logSummary = new StringBuilder(" 📋 Transaction Summary:\
for (int i = 0; i < accountNumbers.length; i++) {
String maskedAcc = maskAccount(accountNumbers[i]);
String type = transactionAmounts[i] >= 0 ? "Credit" : "Debit";

5 | 11
Arrays and Strings in Java

logSummary.append("Account: ").append(maskedAcc)
.append(" | Type: ").append(type)
.append(" | Amount:
₹").append(Math.abs(transactionAmounts[i]))
.append("\n");
}

System.out.println(logSummary.toString());
}

public static String maskAccount(String accountNumber) {


String last4 = accountNumber.substring(accountNumber.length() - 4);
return "XXXX-XXXX-XXXX-" + last4;
}
}

Sample Output:
📋Account:
Transaction Summary:
XXXX-XXXX-XXXX-3456 | Type: Credit | Amount: ₹1500.0
Account: XXXX-XXXX-XXXX-7654 | Type: Debit | Amount: ₹700.0

📌 Concepts Used:
 Arrays (for storing multiple accounts and transactions)
 String manipulation with substring()

 Efficient appending using StringBuilder

 Data masking for security (a real-world compliance requirement)


-----------------------------------------------------------------

MCQs: Arrays, Strings, StringBuffer, and StringBuilder

1. What is the index range of an array in Java?


A) 1 to length
B) 0 to length
C) 0 to length-1
D) 1 to length-1
Answer: C) 0 to length-1
Explanation: Java arrays are zero-indexed, so the first element is at index 0.

2. Which of the following is the correct way to declare and initialize a 2D array?
A) int[][] arr = new int[3][3];
B) int arr[][] = new int();
C) int arr[3][3];

6 | 11
Arrays and Strings in Java

D) int arr = new int[3][3];


Answer: A) int[][] arr = new int[3][3];
Explanation: This is the correct syntax for a 2D array declaration in Java.

3. What is the default value of an int array element in Java?


A) null
B) 0
C) garbage
D) -1
Answer: B) 0
Explanation: Default values for numeric types in Java arrays are zero.

4. Which class is mutable and thread-safe in Java?


A) String
B) StringBuilder
C) StringBuffer
D) CharSequence
Answer: C) StringBuffer
Explanation: StringBuffer is synchronized (thread-safe) and mutable.

5. Which method is used to find the length of a string?


A) length
B) len()
C) size()
D) length()
Answer: D) length()
Explanation: length() is the correct method for finding string length.

6. What is the output of the following code?


String s1 = "Java";
String s2 = "Java";
System.out.println(s1 == s2);

A) true
B) false
C) Compilation error
D) Runtime error
Answer: A) true

7 | 11
Arrays and Strings in Java

Explanation: String literals are stored in the string pool, so both references point to the same
object.

7. Which of these is NOT a valid String method in Java?


A) concat()
B) append()
C) toLowerCase()
D) charAt()
Answer: B) append()
Explanation: append() belongs to StringBuilder/StringBuffer, not String.

8. Which loop is best suited to traverse an array when you don’t need index values?
A) while loop
B) for loop
C) do-while loop
D) enhanced for loop
Answer: D) enhanced for loop
Explanation: Enhanced for loop simplifies traversal when index is not needed.

9. What will StringBuilder sb = new StringBuilder("abc");


sb.reverse(); result in?
A) abc
B) cba
C) bca
D) Compilation error
Answer: B) cba
Explanation: reverse() method reverses the character sequence in-place.

10. What happens when you try to access an index beyond the array length?
A) Returns null
B) Returns 0
C) ArrayIndexOutOfBoundsException
D) Compiles successfully
Answer: C) ArrayIndexOutOfBoundsException
Explanation: Accessing out-of-bound indices throws a runtime exception.

8 | 11
Arrays and Strings in Java

11. Which method inserts a value into a StringBuilder at a given index?


A) add()
B) insert()
C) put()
D) concat()
Answer: B) insert()
Explanation: insert(int offset, String str) inserts text into a StringBuilder.

12. Choose the correct way to sort an integer array in ascending order.
A) Collections.sort(array);
B) array.sort();
C) sort(array);
D) Arrays.sort(array);
Answer: D) Arrays.sort(array);
Explanation: Arrays.sort() from java.util.Arrays is used to sort primitive arrays.
-----------------------------------------------------------------

Practice Questions – Healthcare & Financial


Domain

🩺 Healthcare – Q1: Vital Signs Monitor


Problem:
A patient’s systolic blood pressure is measured every hour for 8 hours.
 Store the readings in a 1D array.
 Display all readings.
 Calculate and display the average systolic pressure.
 Raise an alert if any value is above 140 (high BP alert).
💡 Use: 1D Array, Loop, Conditional Statements
💊 Healthcare – Q2: Lab Test String Report
Problem:
A pathology lab needs to process lab test data. Given the name of the test in lowercase (e.g.,
"glucose"), write a program to:

 Convert the name to uppercase.

9 | 11
Arrays and Strings in Java

 Append the word " TEST" using StringBuffer.

 Display the full formatted test name (e.g., GLUCOSE TEST).

💡 Use: String, StringBuffer, toUpperCase(), append()


💰 Financial – Q3: ATM Mini Statement Generator
Problem:
Accept the last 5 transactions (amounts) from the user and store them in an array.
 Display them in reverse order to simulate a mini statement.
 Calculate total credited and debited amounts separately (positive = credit, negative =
debit).
💡 Use: 1D Array, Loop, Conditions, Math.abs()
Example:
Suppose the last 5 transaction amounts (entered in order from oldest to latest) are:
[+1000, -500, +2000, -1000, +1500]

These represent:
1. ₹1000 credited (oldest)
2. ₹500 debited
3. ₹2000 credited
4. ₹1000 debited
5. ₹1500 credited (most recent)

📋 Reverse Order Display (Mini Statement):


To simulate a real mini statement, your program should print:
Transaction 5: ₹1500.0 (Credit)
Transaction 4: ₹1000.0 (Debit)
Transaction 3: ₹2000.0 (Credit)
Transaction 2: ₹500.0 (Debit)
Transaction 1: ₹1000.0 (Credit)

10 | 11
Arrays and Strings in Java

💼 Financial – Q4: Customer Account Masking Tool


Problem:
Given a list of 3 account numbers (String), display them with all digits masked except the last 4.
For example:
1234567890123456 → XXXX-XXXX-XXXX-3456
💡 Use: String.substring(), StringBuilder, for loop
📊 Financial – Q5: Investment Portfolio Summary
Problem:
A user’s investment portfolio contains 3 asset classes: Stocks, Bonds, Real Estate. Store the
investment value (in lakhs) in an array.
 Print the total value.
 Calculate the percentage contribution of each asset class to the total.
📝 Sample Output:
Total Investment: ₹30 Lakhs
Stocks: ₹15 Lakhs (50%)
Bonds: ₹10 Lakhs (33.33%)
Real Estate: ₹5 Lakhs (16.67%)

💡 Use: 1D Array, Math operations, Formatting output


-----------------------------------------------------------------

11 | 11

You might also like