String in Java

In this article, we are going to learn about strings in java.

A string is a sequence of characters, in java string is an object which represents a sequence of characters. An array of character works the same as a string. strings are immutable in java. In java every character is stored in 16-bits.

char[] gfc =(‘g’,’a’,’n’,’g’,’o’,’f’,’c’,’o’,’d’,’e’};

String str = new String(gfc);

How to declare string in java:-

we can declare string object in java in the following way-

  • By string literal
  • By new keyword

String literal in java:-

we can create string literals by using double quotes “”.

for example

String gangforcode = “new string in java”;

String by new keyword:-

we can create a string by using a new keyword in java.

for example

String gangforcode = new String(“string in java”);

String operations in java:-

length of string:-

we can find the length of a string by using the length() method. This method will return the number of characters present in the string. For example:-

String str=”abcd”;

int length= str.lenght();

In the above example variable length will store the length of string str. which is 4.

equals:-

we can compare two strings in java by using the equals() method. this method will return true or false this method will return true if both strings are similar otherwise it will return false. for example:-

String str1 =”code”;

String str2=”code”;

String str3 =”cod”;

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

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

In the above example first print statement will print true because str1 and str2 are same. the second print statement will print false because str1 and str3 are not same.

String concatenation:-

We can concatenate string in java in two ways. One is by using +(plus) operator and second one is by using concat() method.

String concatenation by + operator in java:-

We can concatenate strings in java by using + operator. This is implemented through string builder class and it’s append method.

public static void main(String[] args) {
		// TODO Auto-generated method stub
		String s1 = "gang for code";
		String s2 = "java code";
		System.out.println(s1+s2);
	}

String concatenation by concatenate method in java:-

we can also concatenate by using concatenate method. This method concatenate the second string at the end of first string.

public static void main(String[] args) {
		String s1 = "gang for code";
		String s2 = "java code";
		System.out.println(s1.concat(s2));

	}

The output of above concatenation example will be same because we are concatenating two strings in two different ways.

Similar Java Tutorials

1 thought on “String in Java”

Leave a Comment