Java Programming — Study Notes

Unit 03

String Handling & Exception Handling in Java

4 Questions 6 Marks Each
01
6 Marks Question

String Class and Creation of String in Java

In Java, the String class is used to create and manipulate strings. A string represents a sequence of characters and is widely used in Java programs.

Definition of String

A string in Java is an object that represents a sequence of character values. Java provides the String class to handle text data easily.

Java also has the primitive type char for single characters, but for storing multiple characters (like names), the String class is used.

Ways to Create String in Java

There are two ways to create a String object:

  • Using String Literal
  • Using new keyword

1. Using String Literal

A string literal is created using double quotes. The string is stored in a special memory area called the String Constant Pool in the heap.

String s1 = "Hello";
Important Point: If the same string already exists in the pool, JVM returns the reference of the existing object instead of creating a new one.
String str1 = "Scaler";
String str2 = "Scaler";  // no new object created

2. Using new Keyword

When a string is created using the new keyword, a new object is always created in heap memory, outside the string constant pool.

String stringName = new String("value");
String s2 = new String("Program");
Important Point: A new memory location is allocated even if the same value already exists.

Example Program

class TestString {
    public static void main(String[] args) {
        String s1 = "Personal";              // literal
        String s2 = new String("Computer");  // new keyword
        String s3 = s1 + s2;                 // concatenation
        System.out.println(s3);
    }
}
Conclusion The String class in Java is used to store and manipulate sequences of characters. Strings can be created using string literals (stored in the string pool) or using the new keyword (stored in heap memory). Proper understanding of string creation helps in efficient memory usage and better Java programming.
02
6 Marks Question

StringBuffer Class in Java

The StringBuffer class in Java is used to create mutable (modifiable) string objects. Unlike the String class, the content of a StringBuffer object can be changed without creating a new object, which makes it memory efficient.

Definition

The StringBuffer class is used for storing a mutable sequence of characters and allows efficient modification of strings. It provides methods for appending, deleting, and updating the sequence.

Why StringBuffer is Needed

In the String class, whenever we modify a string, a new object is created, which causes memory wastage. But in StringBuffer, the original object is modified without allocating new memory. This property is called mutability.

Syntax

StringBuffer objectName = new StringBuffer();
Important Features
  • Mutable (can be modified)
  • Memory efficient
  • Stored in heap memory
  • Faster than String for frequent modifications
  • Provides many built-in methods

Common Methods of StringBuffer

1. append() Method

Used to add data at the end of the existing sequence.

Syntax
StringBuffer.append(data);
Example
StringBuffer sb = new StringBuffer("Hello");
sb.append(" World");
System.out.println(sb);
OutputHello World

2. capacity() Method

Returns the current capacity of the StringBuffer object. Default capacity is 16 bytes.

Syntax
int capacity();

3. Other Useful Operations

StringBuffer also supports insert(), delete(), replace(), and reverse(), which help in efficient string manipulation.

Example Program

class TestBuffer {
    public static void main(String[] args) {
        StringBuffer sb = new StringBuffer("Java");
        sb.append(" Programming");
        System.out.println(sb);
    }
}
Conclusion The StringBuffer class is an important Java class used for mutable strings. It improves performance and memory efficiency when frequent string modifications are required, making it preferable over the String class in such situations.
03
6 Marks Question

Various String Methods for String and StringBuffer Class

Java provides many built-in methods in the String and StringBuffer classes to manipulate character data such as comparing, searching, modifying, and formatting strings.

String Class Methods

The String class provides methods to operate on immutable strings.

01 equals() Compares string contents
Syntax
boolean equals(Object another)
Example
String s1 = "Sachin";
String s2 = "Sachin";
System.out.println(s1.equals(s2));
Outputtrue

Compares the contents of two strings.

02 equalsIgnoreCase() Compares ignoring case
Syntax
boolean equalsIgnoreCase(String another)
Example
String s1 = "Ram";
String s2 = "rAm";
System.out.println(s1.equalsIgnoreCase(s2));
Outputtrue

Compares strings ignoring case.

03 compareTo() Lexicographic comparison
Syntax
int compareTo(String str)
Example
String s1 = "Sachin";
String s2 = "Sachin";
System.out.println(s1.compareTo(s2));
Output0

Returns 0 if equal, positive if greater, negative if smaller.

04 length() Number of characters
Syntax
int length()
Example
String s = "Sachin";
System.out.println(s.length());
Output6

Returns number of characters.

05 charAt() Character at given index
Syntax
char charAt(int index)
Example
String s = "Sachin";
System.out.println(s.charAt(0));
OutputS

Returns character at given index.

06 toUpperCase() & toLowerCase() Converts string case
Syntax
String toUpperCase()
String toLowerCase()
Example
String s = "Sachin";
System.out.println(s.toUpperCase());
System.out.println(s.toLowerCase());
OutputSACHIN sachin

Converts the string to all uppercase or all lowercase.

07 trim() Removes leading and trailing spaces
Syntax
String trim()
Example
String s = " Sachin ";
System.out.println(s.trim());
OutputSachin

Removes leading and trailing spaces.

08 substring() Extracts part of string
Syntax
String substring(int start, int end)
Example
String s = "SachinTendulkar";
System.out.println(s.substring(0, 6));
OutputSachin

Extracts part of string.

09 concat() Joins two strings
Syntax
String concat(String another)
Example
String s1 = "Sachin ";
String s2 = "Tendulkar";
System.out.println(s1.concat(s2));
OutputSachin Tendulkar

Joins two strings.

StringBuffer Class Methods

StringBuffer is mutable and efficient for frequent modifications.

01 append() Adds data at the end
Syntax
StringBuffer append(data)
Example
StringBuffer sb = new StringBuffer("Hello");
sb.append(" Java");
System.out.println(sb);
OutputHello Java

Adds data at the end.

02 insert() Inserts data at specified position
Syntax
StringBuffer insert(int index, data)
Example
StringBuffer sb = new StringBuffer("Hello");
sb.insert(5, " World");
System.out.println(sb);
OutputHello World

Inserts data at specified position.

03 delete() Removes characters from range
Syntax
StringBuffer delete(int start, int end)
Example
StringBuffer sb = new StringBuffer("Hello World");
sb.delete(5, 11);
System.out.println(sb);
OutputHello

Removes characters from range.

04 replace() Replaces characters in range
Syntax
StringBuffer replace(int start, int end, String str)
Example
StringBuffer sb = new StringBuffer("Hello World");
sb.replace(6, 11, "Java");
System.out.println(sb);
OutputHello Java

Replaces characters from start to end with the given string.

05 reverse() Reverses the sequence
Syntax
StringBuffer reverse()
Example
StringBuffer sb = new StringBuffer("Java");
sb.reverse();
System.out.println(sb);
OutputavaJ

Reverses the character sequence of the StringBuffer.

06 capacity() Returns current capacity
Syntax
int capacity()
Example
StringBuffer sb = new StringBuffer();
System.out.println(sb.capacity());
Output16

Default capacity is 16 bytes.

Conclusion The String class provides methods for immutable text operations, while StringBuffer provides mutable and efficient string manipulation methods. Choosing between them depends on whether frequent modifications are required.
04
6 Marks Question

Exception Handling in Java

Exception handling in Java is a powerful mechanism used to handle runtime errors so that the normal flow of the program can be maintained. An exception is an abnormal condition that disrupts program execution.

What is Exception Handling?

Exception handling is the process of handling runtime errors such as ArithmeticException, IOException, etc., to prevent program termination and allow the remaining code to execute normally.

Keywords Used in Exception Handling

Java provides five main keywords:

  • try
  • catch
  • finally
  • throw
  • throws
try Encloses code that may throw an exception

The try block is used to enclose the code that may generate an exception. It must be followed by either catch or finally.

Syntax
try {
    // code that may throw exception
}
Example
try {
    int a = 10 / 0;
}
catch Handles the exception from the try block

The catch block is used to handle the exception generated in the try block. It must be placed immediately after the try block.

Syntax
catch(ExceptionType e) {
    // handling code
}
Example
catch(ArithmeticException e) {
    System.out.println("Exception handled");
}

Important Points: Multiple catch blocks are allowed. Only one catch block executes at a time.

finally Always executes, with or without an exception

The finally block is used to execute important code such as closing files or releasing resources. It executes whether an exception occurs or not.

Syntax
finally {
    // cleanup code
}
Example
finally {
    System.out.println("Always executed");
}
throw Explicitly throws an exception

The throw keyword is used to explicitly throw an exception by the programmer. It is mainly used to create custom exceptions.

Syntax
throw new ExceptionType("message");
Example
if(age < 18) {
    throw new ArithmeticException("Not eligible");
}
throws Declares exceptions a method may throw

The throws keyword is used in the method declaration to declare that a method may throw exceptions. It informs the caller about possible exceptions.

Syntax
returnType methodName() throws ExceptionType
Example
void readFile() throws IOException {
    // code
}

Simple Program Using Exception Handling Keywords

class ExceptionDemo {
    static void checkAge(int age) throws ArithmeticException {
        if (age < 18) {
            throw new ArithmeticException("Not eligible to vote");
        } else {
            System.out.println("Eligible to vote");
        }
    }

    public static void main(String[] args) {
        try {
            checkAge(16);
        }
        catch (ArithmeticException e) {
            System.out.println("Caught Exception: " + e.getMessage());
        }
        finally {
            System.out.println("Program finished");
        }
    }
}
Output Caught Exception: Not eligible to vote
Program finished
Conclusion Exception handling in Java ensures that runtime errors do not abruptly terminate the program. Using the keywords try, catch, finally, throw, and throws, programmers can write robust and reliable applications.