0% found this document useful (0 votes)
6 views19 pages

02 Java String Level 1 Lab Practice

step

Uploaded by

ananyajha2005
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)
6 views19 pages

02 Java String Level 1 Lab Practice

step

Uploaded by

ananyajha2005
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
You are on page 1/ 19

Best Programming Practice

1. Use Variables including for Fixed, User Inputs, and Results


2. Use Methods instead of writing code in the main() function
3. Proper naming conventions for all variables and methods
4. Proper Program Name and Class Name
5. Handle Checked and Unchecked Exceptions wherever possible
6. Proper Method Name which indicates action taking inputs and providing result
Sample Program 1: Create a program to find all the occurrences of a character in a string
using charAt() method
a. Take user input for the String and occurrences of the Character to find
b. Write a method to find all the occurrences of the characters.
i. The logic used is to first find the number of occurrences of the character and
ii. then create an array to store the indexes of the character
c. Call the method in the main and display the result
// Program to find all the occurrences of a character in a string
import java.util.Scanner;
class StringAnalyzer {
// Method to find all the index of a character in a string using charAt()
// method and return them in an array
public static int[] findAllIndexes(String text, char ch) {
// The count is used to find the number of occurrences of the character
int count = 0;
for (int i = 0; i < text.length(); i++) {
if (text.charAt(i) == ch) {
count++;
}
}

// Create an array to store the indexes of the character


int[] indexes = new int[count];
int j = 0;
for (int i = 0; i < text.length(); i++) {
if (text.charAt(i) == ch) {
indexes[j] = i;
j++;
}
}
return indexes;
}
public static void main(String[] args) {
// Take user input for Text and Character to check Occurrences
Scanner sc = new Scanner(System.in);
System.out.print(Enter a text: ");
String text = sc.nextLine();

1
System.out.print("Enter a character to find the occurrences: ");
char ch = sc.next().charAt(0);

// Find the occurrences of the character


int[] indexes = findAllIndexes(text, ch);

// Display the occurrences of the character


System.out.println("Indexes of the character '" + ch + "': ");
for (int i = 0; i < indexes.length; i++) {
System.out.print(indexes[i] + " ");
}
}
}

2
Level 1 Practice Programs
1. Write a program to compare two strings using the charAt() method and check the result
with the built-in String equals() method
Hint =>
a. Take user input using the Scanner next() method for 2 String variables
b. Write a method to compare two strings using the charAt() method and return a boolean
result
c. Use the String Built-In method to check if the results are the same and display the result

import java.util.Scanner;

public class StringComparison {

// Method to compare two strings using charAt()


public static boolean compareWithCharAt(String str1, String str2)
{
// If lengths are different, strings can't be equal
if (str1.length() != str2.length()) {
return false;
}

// Compare each character


for (int i = 0; i < str1.length(); i++) {
if (str1.charAt(i) != str2.charAt(i)) {
return false;
}
}

// All characters matched


return true;
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

// Take user input


System.out.print("Enter first string: ");
String string1 = scanner.next(); // Takes input until space

System.out.print("Enter second string: ");

3
String string2 = scanner.next(); // Takes input until space

// Compare using charAt()


boolean resultCharAt = compareWithCharAt(string1, string2);

// Compare using built-in equals() method


boolean resultEquals = string1.equals(string2);

// Print both results


System.out.println("Comparison using charAt(): " +
resultCharAt);
System.out.println("Comparison using equals(): " +
resultEquals);

// Check if both methods gave the same result


if (resultCharAt == resultEquals) {
System.out.println("Both methods returned the SAME
result.");
} else {
System.out.println("The results from charAt() and
equals() are DIFFERENT.");
}

scanner.close();
}
}

2. Write a program to create a substring from a String using the charAt() method. Also, use
the String built-in method substring() to find the substring of the text. Finally Compare the
the two strings and display the results
Hint =>
a. Take user input using the Scanner next() method to take the String variable and also
the start and the end index to get the substring from the given text
b. Write a method to create a substring from a string using the charAt() method with the
string, start, and end index as the parameters
c. Write a method to compare two strings using the charAt() method and return a boolean
result
d. Use the String built-in method substring() to get the substring and compare the two
strings. And finally display the result

import java.util.Scanner;

4
public class SubstringComparison {

// Method to create a substring using charAt()


public static String createSubstringWithCharAt(String str, int
start, int end) {
String result = "";
for (int i = start; i < end && i < str.length(); i++) {
result += str.charAt(i); // Append each character to
result
}
return result;
}

// Method to compare two strings using charAt()


public static boolean compareWithCharAt(String str1, String str2)
{
if (str1.length() != str2.length()) {
return false;
}
for (int i = 0; i < str1.length(); i++) {
if (str1.charAt(i) != str2.charAt(i)) {
return false;
}
}
return true;
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

// Take string input


System.out.print("Enter a string: ");
String text = scanner.next();

// Take start and end index


System.out.print("Enter start index: ");
int start = scanner.nextInt();

System.out.print("Enter end index: ");


int end = scanner.nextInt();

5
// Create substring using charAt()
String substringCharAt = createSubstringWithCharAt(text,
start, end);

// Create substring using built-in substring()


String substringBuiltIn = "";
if (start >= 0 && end <= text.length() && start < end) {
substringBuiltIn = text.substring(start, end);
} else {
System.out.println("Invalid index range for built-in
substring().");
}

// Compare the two substrings using charAt()


boolean comparisonResult = compareWithCharAt(substringCharAt,
substringBuiltIn);

// Display results
System.out.println("\nSubstring using charAt(): " +
substringCharAt);
System.out.println("Substring using built-in substring(): " +
substringBuiltIn);
System.out.println("Are both substrings equal? " +
comparisonResult);

scanner.close();
}
}

3. Write a program to return all the characters in a string using the user-defined method,
compare the result with the String built-in toCharArray() method, and display the result
Hint =>
a. Take user input using the Scanner next() method to take the text into a String variable
b. Write a method to return the characters in a string without using the toCharArray()
c. Write a method to compare two string arrays and return a boolean result
d. In the main() call the user-defined method and the String built-in toCharArray() method,
compare the 2 arrays, and finally display the result

import java.util.Scanner;

public class CharArrayComparison {

6
// Method to get characters from a string without using
toCharArray()
public static char[] getCharsFromString(String str) {
char[] chars = new char[str.length()];
for (int i = 0; i < str.length(); i++) {
chars[i] = str.charAt(i);
}
return chars;
}

// Method to compare two character arrays


public static boolean compareCharArrays(char[] arr1, char[] arr2)
{
if (arr1.length != arr2.length) {
return false;
}

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


if (arr1[i] != arr2[i]) {
return false;
}
}

return true;
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

// Take string input


System.out.print("Enter a string: ");
String input = scanner.next();

// Get characters using user-defined method


char[] userDefinedChars = getCharsFromString(input);

// Get characters using built-in method


char[] builtInChars = input.toCharArray();

// Compare the two arrays


boolean areEqual = compareCharArrays(userDefinedChars,

7
builtInChars);

// Display the result


System.out.println("\nCharacters from user-defined method:");
for (char c : userDefinedChars) {
System.out.print(c + " ");
}

System.out.println("\nCharacters from built-in toCharArray()


method:");
for (char c : builtInChars) {
System.out.print(c + " ");
}

System.out.println("\n\nAre both character arrays equal? " +


areEqual);

scanner.close();
}
}

4. Write a program to demonstrate NullPointerException.


Hint =>
a. Write a Method to generate the Exception. Here define the variable text and initialize it to
null. Then call one of the String Method to generate the exception
e. Write the Method to demonstrate NullPointerException. Here define the variable text
and initialize it to null. Then write try catch block for handling the Exception while
accessing one of the String method
b. From the main Firstly call the method to generate the Exception then refactor the code to
call the method to handle the RuntimeException

public class NullPointerDemo {

// Method that generates NullPointerException


public static void generateException() {
String text = null; // text is initialized to null
// This will cause NullPointerException
System.out.println("Length of text: " + text.length());
}

8
// Method that handles NullPointerException using try-catch
public static void handleException() {
String text = null; // text is initialized to null
try {
// Attempting to access length() of a null String
System.out.println("Length of text: " + text.length());
} catch (NullPointerException e) {
// Handling the exception
System.out.println("Caught a NullPointerException: " +
e.getMessage());
}
}

public static void main(String[] args) {


System.out.println("Demonstrating NullPointerException (will
crash):");
try {
generateException(); // This will throw an exception
} catch (NullPointerException e) {
System.out.println("Exception caught in main: " +
e.getMessage());
}

System.out.println("\nHandling NullPointerException
safely:");
handleException(); // This will handle it gracefully
}
}

5. Write a program to demonstrate StringIndexOutOfBoundsException


Hint =>
a. Define a variable of type String and take user input to assign a value
b. Write a Method to generate the Exception. Access the index using charAt() beyond the
length of the String. This will generate a runtime exception and abruptly stop the
program.
c. Write the Method to demonstrate StringIndexOutOfBoundsException. Access the
index using charAt() beyond the length of the String. Then write try catch block for
Exception while accessing the String method
d. From the main Firstly call the method to generate the Exception then call the method to
handle the RuntimeException

9
import java.util.Scanner;

public class StringIndexOutOfBoundsDemo {

// Method that generates StringIndexOutOfBoundsException


public static void generateException(String input) {
// Trying to access a character beyond the string length
System.out.println("Character at position 100: " +
input.charAt(100));
}

// Method that handles StringIndexOutOfBoundsException


public static void handleException(String input) {
try {
// Attempting to access char at an index beyond string
length
System.out.println("Character at position 100: " +
input.charAt(100));
} catch (StringIndexOutOfBoundsException e) {
System.out.println("Caught a
StringIndexOutOfBoundsException: " + e.getMessage());
}
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

// Taking input from user


System.out.print("Enter a string: ");
String userInput = scanner.nextLine();

System.out.println("\nDemonstrating
StringIndexOutOfBoundsException (may crash):");
try {
generateException(userInput);
} catch (StringIndexOutOfBoundsException e) {
System.out.println("Exception caught in main: " +
e.getMessage());
}

System.out.println("\nHandling
StringIndexOutOfBoundsException safely:");

10
handleException(userInput);

scanner.close();
}
}

6. Write a program to demonstrate IllegalArgumentException


Hint =>
a. Define a variable of type String and take user input to assign a value
b. Write a Method to generate the Exception. Here use the subString() and set the start
index to be greater than the end index. This will generate a runtime exception and
abruptly stop the program.
c. Write the Method to demonstrate IllegalArgumentException. Here use the
subString() and set the start index to be greater than the end index. This will generate
a runtime exception. Use the try-catch block to handle the
IllegalArgumentException and the generic runtime exception
d. From the main Firstly call the method to generate the Exception then call the method to
handle the RuntimeException

import java.util.Scanner;

public class IllegalArgumentDemo {

// Method to generate IllegalArgumentException


public static void generateException(String input) {
// Intentionally setting start index > end index to trigger
exception
String result = input.substring(5, 2);
System.out.println("Substring: " + result);
}

// Method to handle IllegalArgumentException using try-catch


public static void handleException(String input) {
try {
// This will throw IllegalArgumentException
String result = input.substring(5, 2);
System.out.println("Substring: " + result);
} catch (IllegalArgumentException e) {
System.out.println("Caught an IllegalArgumentException: "
+ e.getMessage());
} catch (RuntimeException e) {

11
System.out.println("Caught a RuntimeException: " +
e.getMessage());
}
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

// Getting user input


System.out.print("Enter a string: ");
String userInput = scanner.nextLine();

System.out.println("\nDemonstrating IllegalArgumentException
(may crash):");
try {
generateException(userInput); // This might crash
} catch (IllegalArgumentException e) {
System.out.println("Exception caught in main: " +
e.getMessage());
}

System.out.println("\nHandling IllegalArgumentException
safely:");
handleException(userInput); // This handles it safely

scanner.close();
}
}

7. Write a program to demonstrate NumberFormatException


Hint =>
a. Define a variable to take user input as a String
b. Use Integer.parseInt() to generate this exception. Integer.parseInt() is a built-in
function in java.lang.Integer class to extract the number from text. In case the text does
not contain numbers the method will throw NumberFormatException which is a runtime
exception
c. Write a Method to generate the Exception. Use Integer.parseInt(text) to extract
number from the text. This will generate a runtime exception and abruptly stop the
program.
d. Write the Method to demonstrate NumberFormatException. Use
Integer.parseInt(text) to extract number from the text. This will generate a runtime

12
exception. Use the try-catch block to handle the NumberFormatException as well as
the generic runtime exception
e. From the main Firstly call the method to generate the Exception then call the method to
handle the RuntimeException

import java.util.Scanner;

public class NumberFormatDemo {

// Method that generates NumberFormatException


public static void generateException(String text) {
// This will throw NumberFormatException if text is not a
valid number
int number = Integer.parseInt(text);
System.out.println("Parsed number: " + number);
}

// Method that handles NumberFormatException using try-catch


public static void handleException(String text) {
try {
// Try parsing the input
int number = Integer.parseInt(text);
System.out.println("Parsed number: " + number);
} catch (NumberFormatException e) {
System.out.println("Caught a NumberFormatException: " +
e.getMessage());
} catch (RuntimeException e) {
System.out.println("Caught a RuntimeException: " +
e.getMessage());
}
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

// Taking input from user


System.out.print("Enter a number (or a word to cause an
error): ");
String userInput = scanner.nextLine();

System.out.println("\nDemonstrating NumberFormatException
(may crash):");
try {

13
generateException(userInput);
} catch (NumberFormatException e) {
System.out.println("Exception caught in main: " +
e.getMessage());
}

System.out.println("\nHandling NumberFormatException
safely:");
handleException(userInput);

scanner.close();
}
}

8. Write a program to demonstrate ArrayIndexOutOfBoundsException


Hint =>
a. Define a variable of array of names and take input from the user
b. Write a Method to generate the Exception. Here access index larger then the length of
the array. This will generate a runtime exception and abruptly stop the program.
c. Write the Method to demonstrate ArrayIndexOutOfBoundsException. Here access
index larger then the length of the array. This will generate a runtime exception. Use the
try-catch block to handle the ArrayIndexOutOfBoundsException and the generic
runtime exception
d. From the main Firstly call the method to generate the Exception then call the method to
handle the RuntimeException

import java.util.Scanner;

public class ArrayIndexOutOfBoundsDemo {

// Method to generate ArrayIndexOutOfBoundsException


public static void generateException(String[] names, int index) {
// Accessing an index that might be out of bounds
System.out.println("Name at index " + index + ": " +
names[index]);
}

// Method to handle ArrayIndexOutOfBoundsException using try-


catch
public static void handleException(String[] names, int index) {
try {

14
// Attempting to access an invalid index
System.out.println("Name at index " + index + ": " +
names[index]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Caught an
ArrayIndexOutOfBoundsException: " + e.getMessage());
} catch (RuntimeException e) {
System.out.println("Caught a RuntimeException: " +
e.getMessage());
}
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

// Creating an array of names


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

System.out.print("Enter an index to access (0-" +


(names.length - 1) + "): ");
int index = scanner.nextInt();

System.out.println("\nDemonstrating
ArrayIndexOutOfBoundsException (may crash):");
try {
generateException(names, index); // May throw exception
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Exception caught in main: " +
e.getMessage());
}

System.out.println("\nHandling ArrayIndexOutOfBoundsException
safely:");
handleException(names, index); // Will be handled

scanner.close();
}
}

9. Write a program to convert the complete text to uppercase and compare the results

15
Hint =>
a. Take user input using the Scanner nextLine() method to take the complete text into a
String variable
b. Write a method using the String built-in charAt() method to convert each character if it
is lowercase to the Upper Case. Use the logic ASCII value of 'a' is 97 and 'A' is 65 so the
difference is 32, similarly ASCII value of 'b' is 98 and 'B' is 66 so the difference is 32, and
so on
c. Write a method to compare two strings using the charAt() method and return a boolean
result
d. In the main() use the String built-in method toLowerCase() to get the Uppercase Text
and compare the two strings using the user-defined method. And finally display the
result

import java.util.Scanner;

public class UpperCaseComparison {

// Method to convert lowercase characters to uppercase using


ASCII logic
public static String convertToUpperCase(String input) {
StringBuilder result = new StringBuilder();

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


char ch = input.charAt(i);

// Check if the character is lowercase (between 'a' and


'z')
if (ch >= 'a' && ch <= 'z') {
// Convert to uppercase by subtracting 32 from ASCII
value
result.append((char) (ch - 32));
} else {
// Keep the character as it is
result.append(ch);
}
}

return result.toString();
}

// Method to compare two strings character by character


public static boolean compareStrings(String s1, String s2) {
if (s1.length() != s2.length()) {
return false;

16
}

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


if (s1.charAt(i) != s2.charAt(i)) {
return false;
}
}

return true;
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

// Taking full line of input


System.out.print("Enter a line of text: ");
String userInput = scanner.nextLine();

// Built-in uppercase conversion


String builtInUpper = userInput.toUpperCase();

// Manual uppercase conversion


String manualUpper = convertToUpperCase(userInput);

// Compare the strings


boolean isEqual = compareStrings(manualUpper, builtInUpper);

// Output results
System.out.println("\nManual Uppercase Conversion: " +
manualUpper);
System.out.println("Built-in Uppercase Conversion: " +
builtInUpper);
System.out.println("Are both strings equal? " + isEqual);

scanner.close();
}
}

10. Write a program to convert the complete text to lowercase and compare the results
Hint =>

17
a. Take user input using the Scanner nextLine() method to take the complete text into a
String variable
b. Write a method using the String built-in charAt() method to convert each character if it
is lowercase to the Upper Case. Use the logic ASCII value of 'a' is 97 and 'A' is 65 so the
difference is 32, similarly ASCII value of 'b' is 98 and 'B' is 66 so the difference is 32, and
so on
c. Write a method to compare two strings using the charAt() method and return a boolean
result
d. In the main() use the String built-in method toUpperCase() to get the Uppercase Text
and compare the two strings using the user-defined method. And finally display the
result

import java.util.Scanner;

public class LowerCaseComparison {

// Method to manually convert uppercase letters to lowercase


using ASCII
public static String convertToLowerCase(String input) {
StringBuilder result = new StringBuilder();

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


char ch = input.charAt(i);

// If character is uppercase (ASCII A-Z)


if (ch >= 'A' && ch <= 'Z') {
// Convert to lowercase by adding 32
result.append((char) (ch + 32));
} else {
// Leave other characters unchanged
result.append(ch);
}
}

return result.toString();
}

// Method to compare two strings character by character


public static boolean compareStrings(String s1, String s2) {
if (s1.length() != s2.length()) return false;

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


if (s1.charAt(i) != s2.charAt(i)) {
return false;

18
}
}

return true;
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

// Take full line input from user


System.out.print("Enter a line of text: ");
String userInput = scanner.nextLine();

// Built-in lowercase conversion


String builtInLower = userInput.toLowerCase();

// Manual lowercase conversion


String manualLower = convertToLowerCase(userInput);

// Compare the strings


boolean isEqual = compareStrings(manualLower, builtInLower);

// Output results
System.out.println("\nManual Lowercase Conversion: " +
manualLower);
System.out.println("Built-in Lowercase Conversion: " +
builtInLower);
System.out.println("Are both strings equal? " + isEqual);

scanner.close();
}
}

19

You might also like