What are Strings in Java?

For producing and modifying strings in Java, there is a class called String. Among the classes that implement this interface is the String class. As a result, a string is essentially an object that holds a string of character values. To handle various string operations, we have multiple String methods like concat(), length(), compareTo(), equals(), etc. A string in Java is a collection of characters that is an object of the java.lang class. Learn more about object class methods in Java. A string’s value cannot be altered once it has been formed. 

What is String in Java?

In Java, character-type variables are declared using the primitive data type char. It holds or represents a single character. Explore the top reasons why Java is still trending. However, what would happen if we had to save a name or a string of characters? There are two possible approaches (or techniques) to this:

Using char[] array in Java

public class Main 

{

public static void main(String args[]) 

{

     char[] ch = { ‘s’, ‘l’, ‘a’, ‘j’, ‘o’, ‘b’, ‘s’ };

     System.out.println(ch); 

   }

}

Output

slajobs

Using string class in Java

public class Main 

{

public static void main(String args[]) 

{

     String stdName = “slajobs”;

     System.out.println(stdName);

   }

}

Output

slajobs

How to Create a String Object?

There are two methods for creating a string object:

Using String Literal

In computer science, a literal is a notation that is used to express a value. Double quotes can be used to produce and represent Java string literals. You can insert any character or anything between the two quotations. 

Example

public class Main 

{

public static void main(String args[]) 

{

     String sJ= “SLA Jobs”; }

}

We have defined a string variable named sJ and initialized it with the string value “SLA Jobs” in the example above.

Try these basic Java programs:

Armstrong Number in Java

Factorial Program in Java

Reverse a String in Java

Reverse a Number in Java

Final Keyword in Java

String Constant Pool

String literals are kept in a storage space called the string constant pool in Java’s heap memory. The JVM verifies if the identical value already exists in the string pool before creating a new string. The reference to the already-existing object is returned if it does. If not, the reference to the newly formed string object is returned when it has been added to the string pool.

String str1 = “Soft”;

String str2 = “SLA”;

In the previous example, two strings are formed using the string literal function; why is only one string object created in the string constant pool?

The JVM searches the string constant pool for the string value “Soft” when str1 is initialized. If it is absent, a fresh string object is generated and kept within the pool.

The JVM looks for the string value “SLA” in the string constant pool when str2 is initialized. There is no need to construct a new string value because it already exists (because of str1). Rather, str2 references the current value.

Useful Information: What is the Java course fee in Chennai?

Using New Keyword

The new Java keyword can be used to construct strings, yes. A new instance of the String class is produced outside of the string constant pool in the heap memory when a string is formed using new. These objects are given their own memory space on the heap, unlike string literals, regardless of whether the identical value already exists there or not.

Syntax

String stringName = new String(“string_value”);

Example

String str = new String(“Welcome”);

System.out.println(str);

Example of Strings in Java

String val1 = “SLA “; 

System.out.println(val1); 

String val2 = new String(“Welcomes”); 

System.out.println(val2);

String val3 = val1 + val2;  

System.out.println(val3);

Output

SLA Welcomes

Suggested Article:

Java Full Stack vs Python Full Stack

Top 10 Software Courses in 2023

Zoho Salary for Freshers

Google Salary for Freshers

Methods of Java String

int length() method

To find the length of a string in Java, use the length() function. Programs can behave differently depending on how long the string is, therefore this technique is particularly helpful in those situations.

Syntax

stringName.length()

Example

String genre = “hello”;

int genreLength = genre.length();

System.out.println(genreLength);

Output: 5

char charAt(int Index) method

The Java string charAt() method returns the character at the specified index number after receiving an index number as an input.

The string’s length, length, is the indexing range from 0 to length-1.

‘StringIndexOutOfBoundsException’ is produced if the passed index number is not present in the string (If it is a negative integer or equal to or larger than the string’s length).

Syntax

stringName.charAt(index)

Example

String str = “SLA Jobs”;  

char ch = str.charAt(3);

System.out.println(ch);

Output: A

Exception Example

public class Main 

{

   public static void main(String args[]) 

{

     String str = “slajobs welcomes you”;

     char ch = str.charAt(21);

     System.out.println(ch);

   }

}

Output

Exception: java.lang.StringIndexOutOfBoundsException: String index out of range: 14

Explore trending software courses for non-IT graduates

String concat(String string1) Method

Two strings can be joined together using Java’s concat() function for strings.

Syntax

string.concat(anotherString)

Example

String str1 = “SLA”;

str1 = str1.concat(” Jobs”);

System.out.println(str1);

Output

SLA Jobs

String substring(int beginIndex, int endIndex[optional]) method

Java’s substring() function yields a specific portion of a string. The beginning index (inclusive) and the ending index (exclusive) are the two parameters required. The characters in the substring will go from beginIndex to endIndex – 1. It is considered that the endIndex is the string’s length if we do not supply it.

Syntax: string.substring(startIdx, endIdx)

Example

String str = “SLA Jobs”;

String str1 = str.substring(0, 6);

String str2 = str.substring(3);

System.out.println(str1);

System.out.println(str2);

Output

SLA Jo

Jobs

String equals(String anotherString) method

To determine whether two strings are equal or not, utilise Java’s equals() function. The equals method takes another string as a parameter and then determines whether the two strings are equal. True is returned if both strings are equal; otherwise, false is returned.

Syntax

string.equals(anotherString)

Example

String str = “sla”;  

String str1 = “sla”;

String str2 = “sLA”;  

String str3 = “welcomes”;  

System.out.println(str.equals(str1));

System.out.println(str.equals(str2));

System.out.println(str.equals(str3));

Output

True

False

False

Also Read:

TCS Salary for Freshers

HP Salary for Freshers

String contains(String substring) Method

Java’s includes() function can be used to determine whether a string contains a given substring. If the substring is located, it returns true; if not, it returns false.

Syntax

string.contains(string)

Example

String str = “Welcome to SLA Jobs”; 

System.out.println(str.contains(“Welcome”)); 

System.out.println(str.contains(“Hello”)); 

System.out.println(str.contains(“TO”)); 

Output

True

False

False

String Join()

As the name implies, the Java join() method for strings is used to join a collection of strings by creating a joiner between them. Any character, string, or combination of characters can be the joiner variable.

Syntax

string.join(joiner, str1, str2, str3,..)

Example

String strJoin = String.join(” “,”Hi”,”Hello”,”Welcome”,”to SLA”);  

System.out.println(strJoin);

String str1Join = String.join(“-“,”Easy”,”way”,”to”,”IT Job”);  

System.out.println(str1Join);

String str2Join = String.join(“/”,”20″,”12″,”2023″); 

System.out.println(str2Join);

Output

Hi Hello Welcome to SLA

Easy-way-to-IT Job

20/12/2023

Enroll in our software courses and get hired for the highest-paying software jobs.

int compareTo(String string1, String string2) Method

Java’s compareTo() function for strings compares the supplied strings according to their occurrence order in the dictionary. The Unicode value of each character in the strings is the only basis for comparison.

Syntax

string.compareTo(str1, str2)

Example

String str1 = “SLA Jobs”;

String str2 = “SLA Jobs”;

String str3 = “Jobs SLA”;

int result1 = str1.compareTo(str2);

System.out.println(result1);  

int result2 = str1.compareTo(str3);

System.out.println(result2);  

int result3 = str3.compareTo(str1);

System.out.println(result3);  

Output

0

9

-9

String toUpperCase() Method

To convert a string’s lowercase characters to uppercase (or capital) characters in Java, use the toUpperCase() function.

Syntax

string.toUpperCase()

Example

String str = “get started”;  

String strUpper = str.toUpperCase();  

System.out.println(strUpper);  

Output

GET STARTED

It should be mentioned that the original string str remains unchanged.

String toLowerCase() Method

To convert every character in a string to lowercase (or minuscule) characters in Java, use the toLowerCase() function.

Syntax

string.toLowerCase()

Example

String str = “Get Started”;  

String strLower = str.toLowerCase();  

System.out.println(strLower);  

Output

get started

Example

String str = “KEYBOARD”;

str = str.toLowerCase();

System.out.println(str);

Output

get started

String trim() method

Java’s trim() function for strings is used to cut (or eliminate) unnecessary white spaces from both ends of the given string.

Syntax

string.trim()

Example

String str = ”       Find Job at        “;  

System.out.println(str + ” SLA “);

str = str.trim();

System.out.println(str + ” SLA”);  

Output

Find Job at SLA

Find Job at SLA

String replace(char oldChar, char newChar)

As the name indicates, the replace() function of the string in Java is used to replace every specified character in the string with a different character.

Syntax

string.replace(oldChar, newChar)

Example

String str = “Replace e with i”;  

str = str.replace(‘e’,’i’); 

System.out.println(str);  

Output

Riplaci i with i

String Concatenation

In Java, string concatenation is the process of joining two strings together via the + operator or the concat() function. It’s crucial to remember that unless specifically changed, the original string stays unaltered.

Syntax

String resultantStr = str1 + str2 + …

Example

String str1 = “SLA “;

String str2 = ” Courses”;

String concatenated = str1 + str2;

System.out.println(concatenated);

Output

SLA Courses

Do you want to know the IBM salary for freshers?

Creating Format Strings in Java

To format the string according to the provided argument, use the format() method. The formatted string is returned by this method, which first takes two arguments: the argument(s) and the format string.

Syntax

string.format(stringWithFormatSpecifier, anotherString)

Example

String str = “Computers”;

String str1 = String.format(“Domain: %s”, str);

System.out.println(str1);

Output

Domain: Computers

Escape Character() in Java Strings

The character that has a backslash \ preceding it is an escape character.

Example

public class Main 

{

public static void main(String args[]) 

{

     String escStr = “How to learn “coding” easily?”;

System.out.println(escStr);

   }

}

Output

Main.java:4: error: ‘;’ expected

    String escStr = “How to learn “coding” easily?”;

                                   ^

Main.java:4: error: ‘;’ expected

    String escStr = “How to learn “coding” easily?”;

                                         ^

2 errors

Strings in Java: Mutable or Immutable

Because strings in Java are immutable, once they are initialized, they cannot have their values modified. This is because a single string object in the pool of string constants can have more than one reference. Conflicts may arise if the value of one reference is changed and it impacts other strings or reference variables. Java makes string objects immutable to avoid these problems. Java’s string immutability is strongly related to the idea of the String Constant Pool.

The actual string value is unchangeable, despite what some earlier sections of this article may have said. 

Example

String str = “Dive Deep”;

System.out.println(str); 

str = str + ” into Strings in Java”;

System.out.println(str); 

Strings in Java are unchangeable. A new string value is produced when a string like “to all” is concatenated with str. Then, the old value is kept intact and str points to this newly produced value. This behavior illustrates Java’s string immutability.

Enhance your confidence for attending interviews in big IT companies by cross check your skills with our Top HR Interview questions and answers for 2023.

Conclusion

A fundamental element of both software development generally and the Java programming language is Java strings. Find out more by enrolling in Java training in Chennai at SLA Jobs.