Strings in Java

  • Eclipse: Oxygen
  • Java: 1.8

A Sequence of characters inside double quotes is called String, for e.g., “Java” String is the sequence of 4 characters.

Initialization of String variable

In below example, we will create String. Here var is the reference of data “Hello World” of type String.

String var = “Hello World”;

Unicode symbols can also be stored as String. Unicode is a universal international standard character encoding which represents the most of the language in the world.

String var1 = “\u00BB”;

Concatenate two Strings

In below example, we join two Strings with the use of ‘+’ (plus) operator. This operator is an overloaded operator which will add two entities and also concatenate two entities. In our example, we have taken String entities so these will be concatenated.

Output: 1020

We can also plus operator to join two different data types. In below example we have joined two different data types.

Output: 1020

We have already studied the basics of the string datatype. Here we will see the basic methods such as equals to and replace being formed on the strings. These methods along with many more make the usage of string very efficient.

Check the below code snippet, and it explains the methods to perform string.

  • We have two strings x = “Study” and y = “easy”. If we concatenate these two strings, we should have a result as z = “Studyeasy”. We use “concat” method of String class without using arithmetic “+” operator. Both results will show the same
  • We have used the equals method to get proper output. The Java String equals() method compares the two given strings based on the content of the string. If all the characters match, it returns true; otherwise, it will return false. The main difference betweenequals method and the == operator in Java is that one of them is an operator and other is a method and == is used to compare both primitive type and objects while equals () method is used to verify the equality of objects.
  • we are using replace (Char oldChar, char newChar) method which returns a new String resulting from replacing all occurrences of oldChar in this string with newChar.



Text is not Studyeasy

Contributed by Poonam Tomar

Full stack Java Developer

   Buy me a coffee!



Download file

Leave a Reply

Notify of
Close Menu