Java String Basics and Usage Guide
Java String Basics and Usage Guide
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:
// Main Function
public static void main(String args[])
{
[Link](str);
}
}
Output
Hello
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";
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
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) {
Output
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.: 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
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.
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"
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"
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"
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
Java
boolean startsWithWorldAtOffset = [Link]("World", 5); // true
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)
Java
boolean matchesRegionIgnoreCase = [Link](true, 5, s2, 0, 8);
The String class has a set of built-in methods that you can use on strings.
offsetByCodePoints() Returns the index within this String that is offset int
from the given index by codePointOffset code
points
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).
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
An exception can occur for many different reasons. Following are some scenarios where an exception
occurs.
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.
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.
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];
If you try to compile the above program, you will get the following exceptions.
Output
C:\>javac FilenotFound_Demo.java
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.
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.
[Link](num[5]);
If you compile and execute the above program, you will get the following exception.
Output
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.
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.
Exception handling lets you catch and handle errors during runtime - so your program doesn't crash.
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 −
Syntax
try {
catch(Exception e) {
}
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.
[Link](myNumbers[10]); // error!
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
try {
} catch (Exception e) {
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.
import [Link].*;
try {
} catch (ArrayIndexOutOfBoundsException e) {
}
Output
Syntax
try {
// Protected code
// Catch block
// Catch block
// 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
try {
x = (byte) [Link]();
} catch (IOException i) {
[Link]();
return -1;
return -1;
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 −
[Link](ex);
throw ex;
Finally
The finally statement lets you execute code, after try...catch, regardless of the result:
Example
try {
[Link](myNumbers[10]);
} catch (Exception e) {
} finally {
}
The output will be:
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 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":
else {
Exception in thread "main" [Link]: Access denied - You must be at least 18 years
old.
at [Link]([Link])
at [Link]([Link])
Example
checkAge(20);
Example
import [Link].*;
public class className {
Example
import [Link].*;
public class className {
The table below shows some of the most common errors and exceptions in Java, with a short description
of each:
Error/Exception Description
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
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.
import [Link].*;
[Link] = amount;
return amount;
To demonstrate using our user-defined exception, the following CheckingAccount class contains a
withdraw() method that throws an InsufficientFundsException.
import [Link].*;
[Link] = number;
balance += amount;
balance -= amount;
}else {
double needs = amount - balance;
return balance;
return number;
The following BankDemo program demonstrates invoking the deposit() and withdraw() methods of
CheckingAccount.
[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...
InsufficientFundsException
at [Link]([Link])
at [Link]([Link])
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]());
}
}
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.
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:
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.
They are used to store, search, sort, and organize data more easily - all using standardized methods and
patterns.
Interfaces like List define what tools can do, and classes like ArrayList are the actual tools that do the
work.
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