course content

Course Content

Introduction to Java

Strings in DetailsStrings in Details

In Java, a String is an object which contains a sequence of characters. The String class is immutable, meaning that once a String object is created, you cannot change it. All String methods are designed to create new String objects rather than modify existing ones. The String class has several useful methods, some of which are listed below.

How to define String?

You can define strings in Java using the string literal. This method is very similar to how you define primitive data type variables like int.


However, as String is a class using which you can create objects, there is another way to create strings. That's by using the new keyword, as shown below.


So what is the difference between these two methods? When we use the new keyword, Java always creates a new object. For example, if you execute the below code, it will create two new string objects with the value "Hello World":


However, if you run the following code, both the s1 and s2 reference variables will use the same String object.


The literal string method doesn't create new objects if the String already exists in the String pool. String Pool in Java is a pool of Strings stored in Java Heap Memory.

Operating on string

Java has a rich set of functions for operating on strings. The String class has a number of useful methods, some of which are listed below:

1. Boolean equals(str)

The equals(str) boolean method in Java is used to compare two strings. The comparison is case sensitive, meaning that if two strings are not exactly the same when it comes to uppercase and lowercase letters (for example, "Hello" and "hello"), they will not be considered equal. The equals(str) method returns True if the two strings are equal and False if they are not equal.

In this example, we use if-else. Don't worry! We will learn about this construction in the next chapter.


2. int length

The length() method is a built-in method in Java that returns the number of characters in a string. This method is available in all java String classes. For example, the length of "Well done" is 9. An empty string's length is 0.

The + operator can be used between strings to combine them.

For example:


3. char charAt(index)

The charAt(index) method is a built-in method in Java that returns the character at a specified index in a string. The index of the first character is 0, and the index of the last character is nameOfString.length() - 1. If the specified index is less than 0 or greater than or equal to the length of the string, then the charAt(index) method returns the empty string.

For example:


Section 1.

Chapter 5