Updated March 28, 2023
Introduction to String Class in Java
A string is a final class in Java that extends java.lang. An object which is represented as character strings. Serializable, Comparable and CharSequence interfaces are implemented by string class. All the string literals such as “string example” are treated as instances of the String class.
Working of String
- In case you want a string like this: I am at a “Palace” of Mumbai.
- In such cases, the java compiler will misunderstand and throw an error as “I am at “Palace” of Mumbai.”
- will create an ambiguous situation for the compiler.
- To deal with such a situation, The backslash ‘\’ character will come to the rescue.
Code:
public class test
{
public static void main(String[] args)
{
String s1 = "I am at a \"Palace \" of Mumbai.";
System.out.println(s1);
}
}
Output:
Example #1: Adding two strings.
If you add two strings, the result will be string concatenation.
Code:
public class test
{
public static void main(String[] args)
{
int a = 10;
int b = 20;
int c = a+b;
System.out.println(c);
String s = "10";
int d = 10;
String s1 = s+d;
System.out.println(s1);
}
}
Output:
Example #2: Strings are immutable.
A string, once created, its value cannot be changed. Strings are constant. Such a property is known as immutable.
Code:
class Test
{
public static void main(String args[])
{
String str="I am string";
str.concat(" I am instance of String class.");
System.out.println(str);
}
}
Output:
Explaination:
- First, you have created string str as “I am string”. Then concatenating with some string with the help of the concat method of string.
- But as strings are immutable, their value or state can’t be changed. The concatenated string will acquire another part of the memory.
- The reference str still refers to “I am string”.
- To update the same string’s value, we must assign the concatenated string to the particular reference, as shown in the following example.
Example #3
Code:
class Test
{
public static void main(String args[])
{
String str="I am string";
str = str.concat(" I am instance of String class.");
System.out.println(str);
}
}
Output:
To create a mutable string, you can use StringBuffer or StringBuilder Class.
Types of String Classes
There are two types of character sequence classes in Java. The immutable class which is the String class, and the mutable class which is StringBuilder and StringBuffer.
StringBuilder and StringBuffer have some differences.
- StringBuffer is thread-safe and synchronized. That means no two threads can simultaneously access methods of string buffer.
- StringBuilder is non-synchronized and is not thread-safe. That means two threads can simultaneously access methods of string buffer.
- When it comes to efficiency, StringBuilder is more efficient than StringBuffer.
Given below are the example of StringBuffer and StringBuilder
1. StringBuffer
Code:
class StringBufferExample
{
public static void main(String args[])
{
StringBuffer bufferstring=new StringBuffer("I am stringbuffer.");
bufferstring.append("I am thread safe.");
System.out.println(bufferstring);
}
}
Output:
2. StringBuilder
Code:
class StringBuilderExample
{
public static void main(String args[])
{
StringBuilder builderstring=new StringBuilder("I am stringbuilder.");
builderstring.append("I am more efficient than string buffer.");
System.out.println(builderstring);
}
Output:
How does String Class work in Java?
In Java, strings are the sequence of characters, and unlike c,c++, they are the objects of class String.
There are some constructors supported by this class which is as follows:
Important string constructors in Java
Given below are some important string constructors in java:
- String(): It initializes a string object with empty data.
- String(byte[] bytes): It constructs a string by decoding the array of bytes and assigning it to the reference created.
- String(char[] value): It constructs a string by the array of characters provided and assigning it to the reference created.
Important string methods in Java
Given below are some important string methods in java:
- charAt(int index): It returns the character present at the given index in a string.
- concat(String s): It concatenates the existing string with the string provided as an argument.
- equals(Object anObject): Compares this string to the given object and return boolean.
- substring(int beginIndex, int endIndex): It returns a string, i.e. substring of this string.
- toLowerCase(): Converts a string to lower case.
- toUpperCase(): Converts a string to upper case.
- startsWith(String prefix): Tests if the string starts with the prefix provided as an argument.
- trim(): It trims all leading and trailing whitespaces from the string.
Examples of String Class in Java
Given below are the examples of String Class in Java:
Example #1
Let us check whether the string contains only whitespaces.
Code:
class StringWhitespaceChecker
{
public static boolean isStringWithWhitespace(String s)
{
if(s.trim().isEmpty)
{
return true;
}
else
{
return false;
}
}
public static void main(String args[])
{
StringWhitespaceChecker s1 = new StringWhitespaceChecker();
String s =new String(" ");
String string = new String(" I am string. ");
boolean condition1 = s1.isStringWithWhitespace(s);
boolean condition2 = s1.isStringWithWhitespace(string);
System.out.println(condition1);
System.out.println(condition2);
}
}
Output:
Explaination:
- The function first trims all the whitespaces and then checks whether it is empty; if it is so, it will return true or false, respectively.
Example #2
String function.
Code:
class Test
{
public static void main(String args[])
{
String s = new String("hello");
s.toUpperCase();
System.out.println(s);
s = s.concat("world");
System.out.println(s);
System.out.println(s.charAt(1));
String s1 = new String("helllo");
boolean b = s.equals(s1);
System.out.println(b);
}
}
Output:
Example #3
Java String to toCharArray()
Code:
class Test
{
public static void main(String args[])
{
String s = new String("hello");
Char[] c1 = s.toCharArray()
for(int i=0;i<c1.length;i++)
{
System.out.println(c1[i]);
}
}
}
Output:
Conclusion
This article is focused upon the criteria such as introduction to the string, String constructors, String Methods, Types of String classes, String immutable, StringBuffer and StringBuilder. Examples of each property. A string is a very important class in Java. You will work with string manipulation in multiple ways in real-world projects.
Recommended Articles
This is a guide to String Class in Java. Here we discuss the introduction, working, types, and examples. You may also have a look at the following articles to learn more –