Home  >  Article  >  Java  >  String in Java

String in Java

WBOY
WBOYOriginal
2024-08-30 15:12:54625browse

A string is a sequence of characters, but in java, they are treated as objects and immutable in nature; java provides java.lang.String package with different methods available to operate on a string, but we can also create a mutable string in java.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

How to Define String in Java?

We can define it by using the string literal and new keywords. But the difference is literal will not be going to create the new object unless and until it is not available in the string pool. However, the new keyword will always create the new object irrespective of the string constant pool because it creates a string in the heap area.

  • Mutable string
  • Immutable string

How to Create String in Java?

In java, we can define string using two ways which are as follows:

  • By using a string literal
  • By using a new keyword

1. String literal

The string we create by using literal directly goes to the string constant pool. This means if the requested string is already present in the string pool, then the existing string will be returned if the requested string does not exist, then only a new instance of the string will be created and placed in the pool for future reference. The JVM performs all these things.

Syntax:

String s="abc";
String s1 = "abc" ;

In the above scenario, only one object would be created in the string pool because JVM will not be able to find the requested object, so it will make it and place it into the pool, and s1 will point to that reference only for further use. So string literal also save memory by not creating the same instance again. Hence they make our code memory efficient.

2. new keyword

In java, we use the new keyword to create a new object. Whenever we use a new keyword, it will create a new object for us. Also, an object created using a new keyword is placed into the heap memory area.

Syntax:

String s = new Stirng("abc");

In the above example, this object will be placed into the heap memory area, not the string pool, because we create it using the new keyword.

Example:

public class Main {
public static void main(String[] args) {
String s = "abc";
String s1 = "abc";
String ss = new String("abc");
System.out.println("Output will be :: " + s + " "+ s1 +" "+ ss);
}
}

Output:

String in Java

Rules and Regulations for String in Java

It is immutable, so we cannot change its value once assigned. So for creating a mutable string, we need to use a String buffer for this.

A few points need to remember:

  •  While defining a string, make sure it is always quoted with double quotes.
  • They are immutable, i.e., value cannot be changed once assigned.
  • The ‘+’ operator can concatenate two or more strings.
  • We can directly assign the string to a variable without calling its constructor.

Methods of String Class in Java

Various methods available are as follows:

  • trim()
  • toUpperCase
  • toLowerCase
  • valueOf(int value)
  • toLowerCase(Locale l)
  • intern()
  • indexOf(int ch)
  • indexOf(String substring, int fromIndex)
  • indexOf(String substring)
  • split(String regex, int limit)
  • concat(String str)
  • indexOf(int ch, int fromIndex)
  • length()
  • equals(Object another)
  • join(CharSequence delimiter, Iterable elements)
  • isEmpty()
  • replace(char old, char new)
  • equalsIgnoreCase(String another)
  • split(String regex)
  • toUpperCase(Locale l)
  • contains(CharSequence s)
  • charAt(int index)
  • replace(CharSequence old, CharSequence new)
  • join(CharSequence delimiter, CharSequence… elements)
  • substring(int beginIndex)
  • ubstring(int beginIndex, int endIndex)
  • String class in java implements a different interface named
  • Serializable
  • Comparable
  • CharSequence

Also, the string class implements one more interface, i.e., the CharSequence interface; StringBuilder and String Buffer also implement this interface. StringBuffer and StringBuilder are used to create the mutable string in java.

Example – Using StringBuffer

Code:

public class Demo{
public static void main(String[] args) {
StringBuffer sb=new StringBuffer("creating string ");
sb.append("executed");//original string will get chnage
System.out.println("Result is " +sb);//it will print creating string executed
}
}

Output :

String in Java

Example – Using StringBuilder

Code:

public class Main{
public static void main(String[] args) {
StringBuilder sb=new StringBuilder("Creating string");
sb.append(" using string Builder");//original will get change
System.out.println("Result is "+sb);
}
}

Output:

String in Java

Examples

Below are the examples :

Example #1

Code:

public class Main{
public static void main(String[] args) {
String s1="demoforsting";
System.out.println("String is " +s1.substring(2,4));
System.out.println( "with one parameter " +s1.substring(2));
}
}

Output:

String in Java

Example #2

Code:

public class Demo{
public static void main(String[] args) {
String s1="abc";
String s2="abc";
String s3="ABC";
String s4="java";
System.out.println("Result is " +s1.equals(s2));//true
System.out.println("Result is " +s1.equals(s3));//false
System.out.println("Result is " +s1.equals(s4));//false
}
}

Output:

String in Java

Example #3

Code:

public class Demo{
public static void main(String[] args) {
String s1="convert it into uppercase";
String upper=s1.toUpperCase();
System.out.println("result is "+upper);
}
}

Output:

String in Java

Example #4

Code:

public class Demo{
public static void main(String[] args) {
String s1="CONVERT IT INTO LOWER CASE";
String s1upper=s1.toLowerCase();
System.out.println("result is "+s1upper);
}
}

Output:

String in Java

Example #5

Code:

public class Main{
public static void main(String[] args) {
String name="Demo to check contains method";
System.out.println("Result for conatins mehtod is " +name.contains("check"));
System.out.println("Result for conatins mehtod is " +name.contains("method"));
System.out.println("Result for conatins mehtod is " +name.contains("move"));
}
}

Output:

String in Java

Example #6

Code:

public class Main{
public static void main(String[] args) {
String str1 = "Demo for";
String str2 = "Concat";
String str3 = "Method";
// doing for string one
String str4 = str1.concat(str2);
System.out.println("Result is "+str4);
// for multiple string
String str5 = str1.concat(str2).concat(str3);
System.out.println("Result is "+str5);
}
}

Output:

String in Java

Example #7

Code:

public class Main {
public static void main(String[] args) {
String s1 =" Provide space to see use of trim method in java ";
System.out.println(s1.length());
System.out.println("without trim output is "+s1); //Not using trim here
String tr = s1.trim();
System.out.println(tr.length());
System.out.println("with trim output is "+tr); //using trim here
}
}

Output:

String in Java

Conclusion

So java string is an immutable object that provides security in various aspects like URL reading, database username and password, port, and many other things. But if we want to create a mutable string, we should use a string buffer and builder.

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

Statement:
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
Previous article:Type Conversion in JavaNext article:Type Conversion in Java