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

Java String Basics and Usage Guide

The document provides an overview of Java Strings, detailing their creation, manipulation, and characteristics such as immutability. It discusses different classes related to strings, including String, StringBuffer, and StringBuilder, along with methods for string comparison and conversion. Additionally, it explains how strings are stored in memory and provides examples of string operations and constructors.

Uploaded by

faijahaider01
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)
2 views32 pages

Java String Basics and Usage Guide

The document provides an overview of Java Strings, detailing their creation, manipulation, and characteristics such as immutability. It discusses different classes related to strings, including String, StringBuffer, and StringBuilder, along with methods for string comparison and conversion. Additionally, it explains how strings are stored in memory and provides examples of string operations and constructors.

Uploaded by

faijahaider01
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

Unit-3 java

Java Strings



In Java, a String is the type of object that can store a sequence of characters enclosed by double quotes
and every character is stored in 16 bits, i.e., using UTF 16-bit encoding. A string acts the same as an array
of characters. Java provides a robust and flexible API for handling strings, allowing for various operations
such as concatenation, comparison and manipulation.
Example:
String name = "Hello";
String num = "1234";

Program:

public class Geeks {

// Main Function
public static void main(String args[])
{

// creating Java string using a new keyword


String str = new String("Hello");

[Link](str);
}
}

Output

Hello

Ways of Creating a Java String


There are two ways to create a string in Java:
 String Literal
 Using new Keyword

1. String literal (Static Memory)


To make Java more memory efficient (because no new objects are created if it exists already in the string
constant pool).
Example:
String str = “Welcome Student”;

2. Using new keyword (Heap Memory)


 String s = new String("Welcome");
 In such a case, JVM will create a new string object in normal (non-pool) heap memory and the literal
"Welcome" will be placed in the string constant pool. The variable s will refer to the object in the
heap (non-pool)
In the given example only one object will be created. Firstly JVM will not find any string object with the
value "Welcome" in the string constant pool, so it will create a new object. After that it will find the string
with the value "Welcome" in the pool, it will not create a new object but will return the reference to the
same instance.
Example:
String str = new String (“Welcome Student”);
Interfaces and Classes in Strings in Java

CharSequence Interface
CharSequence Interface is used for representing the sequence of Characters in Java. Classes that are
implemented using the CharSequence interface are mentioned below and It provides basic methods such
as length(), charAt(), subSequence() and toString().
Classes that implement CharSequence include:
1. String
String is an immutable class in Java, which means that once a String object is created, its value cannot be
changed. If you want to modify a string a new String object is created and the original remains
unchanged.
Syntax:
// Method 1
String str= "Hello";
// Method 2
String str= new String("hello");

2. StringBuffer
StringBuffer is a peer class of String, it is mutable in nature and it is thread safe class , we can use it when
we have multi threaded environment and shared object of string buffer i.e, used by mutiple thread. As it is
thread safe so there is extra overhead, so it is mainly used for multithreaded program.
Syntax:
StringBuffer demoString = new StringBuffer("Welcome Student");
3. StringBuilder
StringBuilder in Java represents an alternative to String and StringBuffer Class, as it creates a mutable
sequence of characters and it is not thread safe. It is used only within the thread , so there is no extra
overhead , so it is mainly used for single threaded program.
Syntax:
StringBuilder demoString = new StringBuilder();
[Link]("GFG");

4. StringTokenizer
StringTokenizer class in Java is used to break a string into tokens.
A StringTokenizer object internally maintains a current position within the string to be tokenized. Some
operations advance this current position past the characters processed. A token is returned by taking a
substring of the string that was used to create the StringTokenizer object.
Syntax:
public StringJoiner(CharSequence delimiter)
Immutable String in Java
In Java, string objects are immutable. Immutable simply means unmodifiable or unchangeable. Once a
string object is created its data or state can't be changed but a new string object is created.
Example:

import [Link].*;

class Hello
{
public static void main(String[] args)
{
String s = "Sachin";

// concat() method appends the string at the end


[Link](" Tendulkar");

// This will print Sachin because strings are immutable objects


[Link](s);
}
}

Output

Sachin

Here, Sachin is not changed but a new object is created with “Sachin Tendulkar”. That is why a string is
known as immutable.
As we can see in the given figure that two objects are created but s reference variable still refers to
"Sachin" and not to "Sachin Tendulkar". But if we explicitly assign it to the reference variable, it will
refer to the "Sachin Tendulkar" object.
Example: Java program to assign the reference explicitly in String using [Link]() method.

import [Link].*;

class Hello
{
public static void main(String[] args)
{
String name = "Sachin";
name = [Link](" Tendulkar");
[Link](name);
}
}

Output

Sachin Tendulkar

How Strings are Stored in Java Memory


String literal
Whenever a String Object is created as a literal, the object will be created in the String constant pool. This
allows JVM to optimize the initialization of String literal. The string constant pool is present in the heap.
Using new Keyword

The string can also be declared using a new operator i.e. dynamically allocated. In case of String are
dynamically allocated they are assigned a new memory location in the heap . This string will not be added
to the String constant pool.
If we want to store this string in the constant pool then we will need to “intern” it.
Example 2: Using .intern() to add a string object in string constant pool.
// this will add the string to string constant pool.
String internedString = [Link]();
It is preferred to use String literals as it allows JVM to optimize memory allocation.
If we notice if we use new keyword or string literals both store the values in the string but the difference
is if we use the string literals or intern() the string object it will store the values in the string constant pool
which is present inside the heap as shown in the image.
Example that shows how to declare a String:
import [Link].*;
import [Link].*;

class Geeks
{
public static void main(String[] args) {

// Declare String without using new operator


String name = "Welcome Student";

// Prints the String.


[Link]("String name = " + name);

// Declare String using new operator


String newString = new String("Welcome Student");

// Prints the String.


[Link]("String newString = " + newString);
}
}

Output

String name = Welcome Student

String newString = Welcome Student

String Constructor in Java with Example


In Java, string class supports several types of constructors to create and initialize string objects based on
the various types of arguments. This is an example of polymorphism.
The most commonly used constructors of the String class are as follows:
 String()
 String(String str)
 String(char chars[ ])
 String(char chars[ ], int startIndex, int count)
 String(byte byteArr[ ])
 String(byte byteArr[ ], int startIndex, int count)
Let’s understand all the above constructors provided by Java string class one by one.
1. String(): To create an empty string, we will call the default constructor. The general syntax to create an
empty string in Java program is as follows:
String s = new String();
It will create a string object in the heap area with no value.
Discover more

ScientechEasy

Scientech Easy

Scientech Easy - Best Coding Classes with Certification & Placement Assistance in Dhanbad

2. String(String str): This is the most common string constructor that we generally use in the Java
program. This constructor will create a new string object in the heap area and stores the given value in it.
The general syntax to construct a string object with the specified string str is as follows:
String st = new String(String str);

For example:
String s2 = new String("Hello Java");
Here, the object str contains Hello Java.
3. String(char chars[ ]): This string constructor creates a string object and stores the array of characters
in it. The general syntax to create a string object with a specified array of characters is as follows:
String str = new String(char char[])

For example:
char chars[] = { 'a', 'b', 'c', 'd' };
String s3 = new String(chars);

The object reference variable s3 contains the address of the value stored in the heap area. Let’s take an
example program where we will create a string object and store an array of characters in it.
Converting Numbers to Strings:

 [Link](): This static method of the String class is a versatile option. It can convert various
primitive types (int, long, float, double, boolean, char) and objects to their string representation.
Java
int num = 123;
String str = [Link](num); // str will be "123"

 [Link](), [Link](), etc.: Wrapper classes for primitive types


(e.g., Integer, Double, Long) provide a static toString() method for converting their respective primitive
types to strings.
Java
int num = 456;
String str = [Link](num); // str will be "456"
 Concatenation with an Empty String: A simple and often used, though less efficient, method is to
concatenate the number with an empty string. Java's + operator performs string concatenation when one
operand is a string.
Java
int num = 789;
String str = "" + num; // str will be "789"

Converting Strings to Numbers:

 [Link](), [Link](), etc.: Wrapper classes provide static parseXxx() methods


(e.g., parseInt(), parseDouble(), parseLong()) to convert a string representation of a number into its
corresponding primitive type. These methods throw a NumberFormatException if the string cannot be
parsed into the target numeric type.
Java
String str = "123";
int num = [Link](str); // num will be 123

 [Link](), [Link](), etc.: These static methods of the wrapper classes convert a string
into an object of the corresponding wrapper type (e.g., Integer, Double).
Java
String str = "45.67";
Double dbl = [Link](str); // dbl will be a Double object representing 45.67

String manipulating character

In Java, strings are immutable, meaning their content cannot be changed after creation. To manipulate
characters within a string, you effectively create new strings or use mutable alternatives
like StringBuilder or StringBuffer.

Here are common ways to manipulate characters in Java strings:

1. Using String Class Methods:

 charAt(int index): Retrieves the character at a specified index.


Java
String str = "Hello";
char firstChar = [Link](0); // 'H'

 substring(int beginIndex, int endIndex): Extracts a portion of the string.


Java
String str = "HelloWorld";
String sub = [Link](5, 10); // "World"

 replace(char oldChar, char newChar): Replaces all occurrences of a character with another.
Java
String str = "banana";
String newStr = [Link]('a', 'o'); // "bonono"
 toUpperCase() / toLowerCase(): Converts the entire string to uppercase or lowercase.
Java
String str = "Java";
String upper = [Link](); // "JAVA"

 concat(String str): Appends one string to another, creating a new string.


Java
String s1 = "Hello";
String s2 = "World";
String combined = [Link](s2); // "HelloWorld"

2. Using StringBuilder or StringBuffer (for mutable operations):

For operations requiring frequent modifications, StringBuilder (non-synchronized, faster)


or StringBuffer (synchronized, thread-safe) are preferred.

 append(String str) / append(char c): Adds characters or strings to the end.


Java
StringBuilder sb = new StringBuilder("Hello");
[Link](" World"); // "Hello World"

 insert(int offset, String str) / insert(int offset, char c): Inserts characters or strings at a specific position.
Java
StringBuilder sb = new StringBuilder("World");
[Link](0, "Hello "); // "Hello World"

 delete(int start, int end): Removes a portion of the sequence.


Java
StringBuilder sb = new StringBuilder("HelloWorld");
[Link](5, 10); // "Hello"

 setCharAt(int index, char ch): Replaces a character at a specific index.


Java
StringBuilder sb = new StringBuilder("Java");
[Link](0, 'j'); // "java"

3. Converting to Character Array:

You can convert a string to a char[] array to manipulate individual characters directly, then convert it
back to a string if needed.

Java
String str = "Example";
char[] chars = [Link]();
chars[0] = 'e';
String newStr = new String(chars); // "example"

Comparing Entire Strings:


 equals() method: This method compares the content of two strings for equality, considering case
sensitivity.
Java
String str1 = "Hello";
String str2 = "Hello";
boolean areEqual = [Link](str2); // true

 equalsIgnoreCase() method: This method compares the content of two strings for equality, ignoring case
sensitivity.
Java
String str3 = "Hello";
String str4 = "hello";
boolean areEqualIgnoreCase = [Link](str4); // true

 compareTo() method: This method compares two strings lexicographically based on the Unicode value of
each character. It returns:
o 0 if the strings are equal.
o A negative value if the calling string is lexicographically less than the argument string.
o A positive value if the calling string is lexicographically greater than the argument string.
Java
String str5 = "apple";
String str6 = "banana";
int comparisonResult = [Link](str6); // negative value

 compareToIgnoreCase() method: Similar to compareTo(), but ignores case differences during


comparison.
Comparing Portions of Strings:

 startsWith() method: Checks if a string begins with a specified prefix.


Java
String mainStr = "HelloWorld";
boolean startsWithHello = [Link]("Hello"); // true
boolean startsWithWorld = [Link]("World"); // false

An overloaded version allows specifying an offset to begin the search:

Java
boolean startsWithWorldAtOffset = [Link]("World", 5); // true

 endsWith() method: Checks if a string ends with a specified suffix.


Java
String mainStr = "HelloWorld";
boolean endsWithWorld = [Link]("World"); // true
boolean endsWithHello = [Link]("Hello"); // false

 regionMatches() method: Compares a specific region of a string with a specific region of another string.
Java
String s1 = "java tutorial";
String s2 = "tutorial point";
boolean matchesRegion = [Link](5, s2, 0, 8); // true (compares "tutorial" from s1 with
"tutorial" from s2)

An overloaded version allows specifying whether to ignore case:

Java
boolean matchesRegionIgnoreCase = [Link](true, 5, s2, 0, 8);

 contains() method: Checks if a string contains a specified sequence of characters (a substring).


Java
String text = "This is a sample string.";
boolean containsSample = [Link]("sample"); // true

All String Methods

The String class has a set of built-in methods that you can use on strings.

Method Description Return Type

charAt() Returns the character at the specified index char


(position)

codePointAt() Returns the Unicode of the character at the int


specified index

codePointBefore() Returns the Unicode of the character before the int


specified index

codePointCount() Returns the number of Unicode values found in a int


string.

compareTo() Compares two strings lexicographically int

compareToIgnoreCase() Compares two strings lexicographically, ignoring int


case differences

concat() Appends a string to the end of another string String

contains() Checks whether a string contains a sequence of boolean


characters
contentEquals() Checks whether a string contains the exact same boolean
sequence of characters of the specified
CharSequence or StringBuffer

copyValueOf() Returns a String that represents the characters of String


the character array

endsWith() Checks whether a string ends with the specified boolean


character(s)

equals() Compares two strings. Returns true if the strings boolean


are equal, and false if not

equalsIgnoreCase() Compares two strings, ignoring case boolean


considerations

format() Returns a formatted string using the specified String


locale, format string, and arguments

getBytes() Converts a string into an array of bytes byte[]

getChars() Copies characters from a string to an array of void


chars

hashCode() Returns the hash code of a string int

indexOf() Returns the position of the first found occurrence int


of specified characters in a string

intern() Returns the canonical representation for the string String


object

isEmpty() Checks whether a string is empty or not boolean

join() Joins one or more strings with a specified String


separator

lastIndexOf() Returns the position of the last found occurrence int


of specified characters in a string

length() Returns the length of a specified string int

matches() Searches a string for a match against a regular boolean


expression, and returns the matches

offsetByCodePoints() Returns the index within this String that is offset int
from the given index by codePointOffset code
points

regionMatches() Tests if two string regions are equal boolean

replace() Searches a string for a specified value, and String


returns a new string where the specified values
are replaced

replaceAll() Replaces each substring of this string that String


matches the given regular expression with the
given replacement

replaceFirst() Replaces the first occurrence of a substring that String


matches the given regular expression with the
given replacement

split() Splits a string into an array of substrings String[]

startsWith() Checks whether a string starts with specified boolean


characters

subSequence() Returns a new character sequence that is a CharSequence


subsequence of this sequence

substring() Returns a new string which is the substring of a String


specified string

toCharArray() Converts this string to a new character array char[]

toLowerCase() Converts a string to lower case letters String


toString() Returns the value of a String object String

toUpperCase() Converts a string to upper case letters String

trim() Removes whitespace from both ends of a string String

valueOf() Returns the string representation of the specified String


value

Java Exceptions
When an error occurs, Java will normally stop and generate an error message. The technical term for this
is: Java will throw an exception (throw an error).

What Is an Exception in Java?

An exception (or exceptional event) is a problem that arises during the execution of a program. When
an Exception occurs the normal flow of the program is disrupted and the program/Application terminates
abnormally, which is not recommended, therefore, these exceptions are to be handled.

Advertisement

Why Exception Occurs?

An exception can occur for many different reasons. Following are some scenarios where an exception
occurs.

A user has entered an invalid data.

A file that needs to be opened cannot be found.

A network connection has been lost in the middle of communications or the JVM has run out of memory.

Some of these exceptions are caused by user error, others by programmer error, and others by physical
resources that have failed in some manner.

Java Exception Categories

Based on these, we have the following categories of Exceptions. You need to understand them to
know how exception handling works in Java.

Checked exceptions

Unchecked exceptions

Errors
Java Checked Exceptions

A checked exception is an exception that is checked (notified) by the compiler at compilation-time, these
are also called as compile time exceptions. These exceptions cannot simply be ignored, the programmer
should take care of (handle) these exceptions.

Example: Checked Exceptions in Java

For example, if you use FileReader class in your program to read data from a file, if the file specified in
its constructor doesn't exist, then a FileNotFoundException occurs, and the compiler prompts the
programmer to handle the exception.

import [Link];

import [Link];

public class FilenotFound_Demo {

public static void main(String args[]) {

File file = new File("E://[Link]");

FileReader fr = new FileReader(file);

If you try to compile the above program, you will get the following exceptions.

Output

C:\>javac FilenotFound_Demo.java

FilenotFound_Demo.jav[Link] error: unreported exception FileNotFoundException; must be caught or


declared to be thrown

FileReader fr = new FileReader(file);

1 error

Note − Since the methods read() and close() of FileReader class throws IOException, you can observe
that the compiler notifies to handle IOException, along with FileNotFoundException.

Java Unchecked Exceptions

An unchecked exception is an exception that occurs at the time of execution. These are also called as
Runtime Exceptions. These include programming bugs, such as logic errors or improper use of an API.
Runtime exceptions are ignored at the time of compilation.
Example: Unchecked Exceptions in Java

For example, if you have declared an array of size 5 in your program, and trying to call the 6th element of
the array then an ArrayIndexOutOfBoundsExceptionexception occurs.

public class Unchecked_Demo {

public static void main(String args[]) {

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

[Link](num[5]);

If you compile and execute the above program, you will get the following exception.

Output

Exception in thread "main" [Link]: 5

at Exceptions.Unchecked_Demo.main(Unchecked_Demo.java:8)

Java Errors

These are not exceptions at all, but problems that arise beyond the control of the user or the programmer.
Errors are typically ignored in your code because you can rarely do anything about an error. For example,
if a stack overflow occurs, an error will arise. They are also ignored at the time of compilation.

Java Exception Hierarchy

All exception classes are subtypes of the [Link] class. The exception class is a subclass of
the Throwable class. Other than the exception class there is another subclass called Error which is derived
from the Throwable class.

Errors are abnormal conditions that happen in case of severe failures, these are not handled by the Java
programs. Errors are generated to indicate errors generated by the runtime environment. Example: JVM is
out of memory. Normally, programs cannot recover from errors.

The Exception class has two main subclasses: IOException class and RuntimeException Class.
Following is a list of most common checked and unchecked Java's Built-in Exceptions.

Java Exception Class Methods


Following is the list of important methods available in the Throwable class.

[Link]. Method & Description

public String getMessage()


1 Returns a detailed message about the exception that has occurred. This message is initialized in
the Throwable constructor.

public Throwable getCause()


2
Returns the cause of the exception as represented by a Throwable object.

public String toString()


3
Returns the name of the class concatenated with the result of getMessage().

public void printStackTrace()


4
Prints the result of toString() along with the stack trace to [Link], the error output stream.

5 public StackTraceElement [] getStackTrace()


Returns an array containing each element on the stack trace. The element at index 0 represents the
top of the call stack, and the last element in the array represents the method at the bottom of the
call stack.

public Throwable fillInStackTrace()


6 Fills the stack trace of this Throwable object with the current stack trace, adding to any previous
information in the stack trace.

Exception Handling (try and catch)

Exception handling lets you catch and handle errors during runtime - so your program doesn't crash.

It uses different keywords:

The try statement allows you to define a block of code to be tested for errors while it is being executed.

The catch statement allows you to define a block of code to be executed, if an error occurs in the try
block.

A method catches an exception using a combination of the try and catch keywords. A try/catch block is
placed around the code that might generate an exception. Code within a try/catch block is referred to as
protected code, and the syntax for using try/catch looks like the following −

The try and catch keywords come in pairs:

Syntax

try {

// Block of code to try

catch(Exception e) {

// Block of code to handle errors

}
The code which is prone to exceptions is placed in the try block. When an exception occurs, that
exception occurred is handled by catch block associated with it. Every try block should be immediately
followed either by a catch block or finally block.

A catch statement involves declaring the type of exception you are trying to catch. If an exception occurs
in protected code, the catch block (or blocks) that follows the try is checked. If the type of exception that
occurred is listed in a catch block, the exception is passed to the catch block much as an argument is
passed into a method parameter.

Consider the following example:

This will generate an error, because myNumbers[10] does not exist.

public class Main {

public static void main(String[ ] args) {

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

[Link](myNumbers[10]); // error!

The output will be something like this:

Exception in thread "main" [Link]: 10


at [Link]([Link])

Note: ArrayIndexOutOfBoundsException occurs when you try to access an index number that does not
exist.

If an error occurs, we can use try...catch to catch the error and execute some code to handle it:

Example

public class Main {

public static void main(String[ ] args) {

try {

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


[Link](myNumbers[10]);

} catch (Exception e) {

[Link]("Something went wrong.");

The output will be:

Something went wrong.

Example: Demonstrating Exception Handling

In following example, an array is declared with 2 elements. Then the code tries to access the 3rd element
of the array which throws an exception.

// File Name : [Link]

import [Link].*;

public class ExcepTest {

public static void main(String args[]) {

try {

int a[] = new int[2];

[Link]("Access element three :" + a[3]);

} catch (ArrayIndexOutOfBoundsException e) {

[Link]("Exception thrown :" + e);

[Link]("Out of the block");

}
Output

Exception thrown :[Link]: 3

Out of the block

Multiple Catch Blocks


A try block can be followed by multiple catch blocks. The syntax for multiple catch blocks looks like the
following −

Syntax

try {

// Protected code

} catch (ExceptionType1 e1) {

// Catch block

} catch (ExceptionType2 e2) {

// Catch block

} catch (ExceptionType3 e3) {

// Catch block

The previous statements demonstrate three catch blocks, but you can have any number of them after a
single try. If an exception occurs in the protected code, the exception is thrown to the first catch block in
the list. If the data type of the exception thrown matches ExceptionType1, it gets caught there. If not, the
exception passes down to the second catch statement. This continues until the exception either is caught
or falls through all catches, in which case the current method stops execution and the exception is thrown
down to the previous method on the call stack.

Example

Here is code segment showing how to use multiple try/catch statements.

try {

file = new FileInputStream(fileName);

x = (byte) [Link]();

} catch (IOException i) {

[Link]();

return -1;

} catch (FileNotFoundException f) // Not valid! {


[Link]();

return -1;

Catching Multiple Type of Exceptions

Since Java 7, you can handle more than one exception using a single catch block, this feature simplifies
the code. Here is how you would do it −

catch (IOException|FileNotFoundException ex) {

[Link](ex);

throw ex;

Finally

The finally statement lets you execute code, after try...catch, regardless of the result:

Example

public class Main {

public static void main(String[] args) {

try {

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

[Link](myNumbers[10]);

} catch (Exception e) {

[Link]("Something went wrong.");

} finally {

[Link]("The 'try catch' is finished.");

}
The output will be:

Something went wrong.


The 'try catch' is finished.

The throw keyword


The Throws/Throw Keywords
If a method does not handle a checked exception, the method must declare it using the throws keyword.
The throws keyword appears at the end of a method's signature.

You can throw an exception, either a newly instantiated one or an exception that you just caught, by using
the throw keyword.

Try to understand the difference between throws and throw keywords, throws is used to postpone the
handling of a checked exception and throw is used to invoke an exception explicitly.

The throw statement allows you to create a custom error.

The throw statement is used together with an exception type. There are many exception types available in
Java: ArithmeticException, FileNotFoundException, ArrayIndexOutOfBoundsException, SecurityExcepti
on, etc:

Example

Throw an exception if age is below 18 (print "Access denied"). If age is 18 or older, print "Access
granted":

public class Main {

static void checkAge(int age) {

if (age < 18) {

throw new ArithmeticException("Access denied - You must be at least 18 years old.");

else {

[Link]("Access granted - You are old enough!");


}

public static void main(String[] args) {

checkAge(15); // Set age to 15 (which is below 18...)

The output will be:

Exception in thread "main" [Link]: Access denied - You must be at least 18 years
old.
at [Link]([Link])
at [Link]([Link])

If age was 20, you would not get an exception:

Example

checkAge(20);

The output will be:

Access granted - You are old enough!

Example

import [Link].*;
public class className {

public void deposit(double amount) throws RemoteException {


// Method implementation
throw new RemoteException();
}
// Remainder of class definition
}
A method can declare that it throws more than one exception, in which case the exceptions are declared in
a list separated by commas. For example, the following method declares that it throws a
RemoteException and an InsufficientFundsException −

Example

import [Link].*;
public class className {

public void withdraw(double amount) throws RemoteException,


InsufficientFundsException {
// Method implementation
}
// Remainder of class definition
}

Errors and Exception Types

The table below shows some of the most common errors and exceptions in Java, with a short description
of each:

Error/Exception Description

ArithmeticError Occurs when a numeric calculation goes wrong

ArrayIndexOutOfBoundsException Occurs when trying to access an index number that


does not exist in an array

ClassNotFoundException Occurs when trying to access a class that does not


exist

FileNotFoundException Occurs when a file cannot be accessed

InputMismatchException Occurs when entering wrong input (e.g. text in a


numerical input)

IOException Occurs when an input or output operation fails


NullPointerException Occurs when trying to access an object referece that
is null

NumberFormatException Occurs when it is not possible to convert a specified


string to a numeric type

StringIndexOutOfBoundsException Occurs when trying to access a character in a String


that does not exist

User-defined Exceptions in Java


We can create your own exceptions in Java. Keep the following points in mind when writing your own
exception classes −

All exceptions must be a child of Throwable.

If you want to write a checked exception that is automatically enforced by the Handle or Declare Rule,
you need to extend the Exception class.

If you want to write a runtime exception, you need to extend the RuntimeException class.

Syntax

We can define our own Exception class as below −

class MyException extends Exception {

You just need to extend the predefined Exception class to create your own Exception. These are
considered to be checked exceptions. The following InsufficientFundsException class is a user-defined
exception that extends the Exception class, making it a checked exception. An exception class is like any
other class, containing useful fields and methods.

Example: Creating user-defined exception

// File Name [Link]

import [Link].*;

public class InsufficientFundsException extends Exception {

private double amount;


public InsufficientFundsException(double amount) {

[Link] = amount;

public double getAmount() {

return amount;

To demonstrate using our user-defined exception, the following CheckingAccount class contains a
withdraw() method that throws an InsufficientFundsException.

// File Name [Link]

import [Link].*;

public class CheckingAccount {

private double balance;

private int number;

public CheckingAccount(int number) {

[Link] = number;

public void deposit(double amount) {

balance += amount;

public void withdraw(double amount) throws InsufficientFundsException {

if(amount <= balance) {

balance -= amount;

}else {
double needs = amount - balance;

throw new InsufficientFundsException(needs);

public double getBalance() {

return balance;

public int getNumber() {

return number;

The following BankDemo program demonstrates invoking the deposit() and withdraw() methods of
CheckingAccount.

// File Name [Link]

public class BankDemo {

public static void main(String [] args) {

CheckingAccount c = new CheckingAccount(101);

[Link]("Depositing $500...");

[Link](500.00);

try {

[Link]("\nWithdrawing $100...");

[Link](100.00);

[Link]("\nWithdrawing $600...");

[Link](600.00);

} catch (InsufficientFundsException e) {
[Link]("Sorry, but you are short $" + [Link]());

[Link]();

Compile all the above three files and run BankDemo. This will produce the following result −

Output

Depositing $500...

Withdrawing $100...

Withdrawing $600...

Sorry, but you are short $200.0

InsufficientFundsException

at [Link]([Link])

at [Link]([Link])

Hierarchy of Exception Classes:


 Throwable: The root of the exception class hierarchy. It has two direct subclasses:
o Error: Represents serious problems that a reasonable application should not try to catch. These typically
indicate issues with the Java Virtual Machine (JVM) itself, such
as OutOfMemoryError or StackOverflowError.
o Exception: Represents conditions that a reasonable application might want to catch and handle. This class
further branches into two main categories:
 Checked Exceptions: These are subclasses of Exception but not subclasses of RuntimeException. The
compiler enforces that these exceptions must be either caught using a try-catch block or declared in the
method signature using a throws clause. Examples include IOException, FileNotFoundException,
and SQLException.
 Unchecked Exceptions (Runtime Exceptions): These are subclasses of RuntimeException. They
typically indicate programming errors and are not checked at compile time. The compiler does not force
handling of these exceptions. Examples
include NullPointerException, ArithmeticException, ArrayIndexOutOfBoundsException,
and IllegalArgumentException.
Key Exception Classes and Examples:
 IOException: Occurs during input/output operations, like reading from a file that doesn't exist.
 FileNotFoundException: A specific type of IOException when a file cannot be found.
 SQLException: Occurs during database operations.
 NullPointerException: Raised when attempting to use a reference variable that points to null.
 ArithmeticException: Occurs during illegal arithmetic operations, such as division by zero.
 ArrayIndexOutOfBoundsException: Occurs when trying to access an array element with an invalid index.
 NumberFormatException: Occurs when attempting to convert a string into a numeric format that is not
valid.
 IllegalArgumentException: Indicates that a method has been passed an illegal or inappropriate argument.
Example of using an exception class:

Java
public class ExceptionExample {
public static void main(String[] args) {
try {
int result = divide(10, 0); // This will throw an ArithmeticException
[Link]("Result: " + result);
} catch (ArithmeticException e) {
[Link]("Error: Cannot divide by zero. " + [Link]());
}
}

public static int divide(int numerator, int denominator) {


if (denominator == 0) {
throw new ArithmeticException("Division by zero is not allowed.");
}
return numerator / denominator;
}
}

Types of Exception

In Java programming, exceptions serve as crucial indicators of abnormal program behaviour, facilitating
graceful error handling. Java offers a rich array of exception types, primarily categorised into built-in
exceptions and user-defined exceptions.

 Built-in Exceptions:These exceptions are predefined within Java libraries designed to elucidate
specific error scenarios encountered during program execution.
 Checked Exceptions:These exceptions, also known as compile-time exceptions, undergo
scrutiny by the compiler at compile-time. Examples include IOException, SQLException, and
ClassNotFoundException. Developers are obliged to either handle these exceptions using try-
catch blocks or declare them in the method signature using the throws keyword.

 Unchecked Exceptions:In contrast to checked exceptions, unchecked exceptions are not subject
to compile-time verification by the compiler. If a program throws an unchecked exception, such
as NullPointerException or ArrayIndexOutOfBoundsException, it does not mandate explicit
handling. However, it’s prudent for developers to address potential unchecked exceptions to
prevent runtime errors.

 User-Defined Exceptions:Despite the breadth of built-in exceptions, there are instances where
predefined exceptions fail to adequately capture specific error scenarios. In such cases, Java
empowers developers to define their own exceptions, aptly termed ‘user-defined exceptions’.
This customisation allows for tailored error-handling mechanisms, ensuring precise identification
and resolution of exceptional situations unique to the application’s context.

Understanding the nuances of these exception categories equips Java developers with the proficiency to
anticipate, intercept, and effectively manage runtime errors, thereby fortifying the robustness and
reliability of their software solutions.

Advantages of Exception Handling in Java

Exception handling in Java is a crucial aspect of robust programming, providing a structured approach to
dealing with errors and unexpected situations that may arise during program execution. Here are several
advantages of employing exception handling in Java:

 Provision to Complete Program Execution


 Easy Identification of Program Code and Error-Handling Code
 Propagation of Errors
 Meaningful Error Reporting
 Identifying Error Types

The Collections Framework


Before we explore ArrayList, HashSet, HashMap, and other data structures in more detail, it's important
to understand that all of these are part of something bigger - the Java Collections Framework.

The Java Collections Framework provides a set of interfaces (like List, Set, and Map) and a set
of classes (ArrayList, HashSet, HashMap, etc.) that implement those interfaces.

All of these are part of the [Link] package.

They are used to store, search, sort, and organize data more easily - all using standardized methods and
patterns.

Tip: Think of the Collections Framework as a toolbox.

Interfaces like List define what tools can do, and classes like ArrayList are the actual tools that do the
work.

Core Interfaces in the Collections Framework

Here are some common interfaces, along with their classes:

Interface Common Classes Description

List ArrayList, LinkedList Ordered collection that allows duplicates

Set HashSet, TreeSet, LinkedHashSet Collection of unique elements

Map HashMap, TreeMap, LinkedHashMap Stores key-value pairs with unique keys

Overview of Classes

The table below gives an overview of the common data structure classes and their characteristics:
Interface Class Description

List ArrayList Resizable array that maintains order and allows duplicates

LinkedList List with fast insert and remove operations

Set HashSet Unordered collection of unique elements

TreeSet Sorted set of unique elements (natural order)

LinkedHashSet Maintains the order in which elements were inserted

Map HashMap Stores key/value pairs with no specific order

TreeMap Sorted map based on the natural order of keys

LinkedHashMap Maintains the order in which keys were inserted

You might also like