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 the below example, we will create a 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 that represents most of the languages 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.
public static void main(String[] args) { String var1 = "10"; String var2 = "20"; System.out.println(var1 + var2); }
Output: 1020
We can also plus operator to join two different data types. In below example we have joined two different data types.
public static void main(String[] args) { int var1 = 10; String var2 = "20"; System.out.println(var1 + var2); }
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 the String class without using the 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 between equals method and the == operator in Java is that one of them is an operator and the other is a method and == is used to compare both primitive types 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.
public class App { public static void main(String[] args) { String x = "Study"; String y = "easy"; String z = x.concat(y); z = z.replace("easy", "hard"); System.out.println(z); if(z.equals("Studyeasy")){ System.out.println("Text is Studyeasy"); }else{ System.out.println("Text is not Studyeasy"); } } }
Output
Studyhard Text is not Studyeasy
Contributed by Poonam Tomar