Home > Java > javaTutorial > String Class in Java

String Class in Java

WBOY
Release: 2024-08-30 15:42:54
Original
355 people have browsed it

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.

ADVERTISEMENT Popular Course in this category JAVA MASTERY - Specialization | 78 Course Series | 15 Mock Tests

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);
}
}
Copy after login

Output:

String Class in Java

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);
}
}
Copy after login

Output:

String Class in Java

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);
}
}
Copy after login

Output:

String Class in Java

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);
}
}
Copy after login

Output:

String Class in Java

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);
}
}
Copy after login

Output:

String Class in Java

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);
}
Copy after login

Output:

String Class in Java

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);
}
}
Copy after login

Output:

String Class in Java

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);
}
}
Copy after login

Output:

String Class in Java

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]);
}
}
}
Copy after login

Output:

String Class in Java

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.

The above is the detailed content of String Class in Java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template