Easy way to IT Job

What are Strings in Java
Share on your Social Media

What are Strings in Java?

Published On: October 21, 2023

“Strings” are objects in Java that can contain character values. Each character is stored in 16 bits, specifically using UTF-16 encoding. This article will help you understand strings in Java and how you can create and work with them using various methods.

In Java, a “String” is essentially an array of characters.

char[] ch={‘S’,’O’,’F’,’T’,’L’,’O’,’G’,’I’,’C’};

String s=“SOFTLOGIC”;

The Java String class offers numerous functions for working with strings, including methods like compare(), concat(), equals(), split(), length(), replace(), compareTo(), substring(), and more.

How to create Strings in Java?

To create a String object in Java, you can use one of the following methods:

Strings in Java: Using String Literal:

A String object can be created directly by using a string literal enclosed in double quotes. For example:

String s1 = “Softlogic System”;

Strings in Java: Using the “new” Keyword:

A String object can be generated by using the “new” keyword, followed by the String class constructor. For instance:

String s2 = new String(“Java Programming”);

Strings in Java: Using the String Constructor:

You can also create a String object by using the String class constructor, which can take a character array or byte array as input. For instance:

char[] charArray = {‘S’, ‘o’, ‘f’, ‘t’, ‘l’, ‘o’, ‘g’, ‘i’, ‘c’}; String s3 = new String(charArray);

Strings in Java: Using StringBuilder or StringBuffer:

You can create a String object by first building the string with StringBuilder or StringBuffer and then converting it to a String. For example:

StringBuilder sb = new StringBuilder(“This is a StringBuilder”); String s4 = sb.toString();

Strings in Java: Using String Pool:

In Java, there is a pool of string literals, which means that if you create a string with the same content as an existing one, Java might reuse the existing object. For example:

String s5 = “Softlogic System”; // Reuses the existing object if it already exists

Using these techniques, you can generate String objects in Java for storing and working with text or character data.

Java String Methods

Java String Length Example:

In Java, the length() function can be used to determine the length of a String. This method counts and returns the amount of characters in the String. Here is an example using the String “Softlogic System”:

public class StringLengthExample {

public static void main(String[] args) {

     String text = “Softlogic System”;

     int length = text.length();

        System.out.println(“The length of the String is: ” + length);

}

}

Output:

The length of the String is: 15

In this example, the length() function is used in the String “Softlogic System,” resulting in a length of 15 characters.

Java String Concatenation:

Strings can be concatenated in Java by combining them with the + operator. This operation joins the content of the strings to form a new string.

String resultantStr = str1 + str2 + …

Consider the strings “Softlogic” and “System,” which we have. They can be concatenated as follows:

public class StringConcatenationExample {

public static void main(String[] args) {

     String str1 = “Softlogic “;

     String str2 = “System”;

     String concatenated = str1 + str2;

        System.out.println(concatenated);

}

}

Output:

Softlogic System

Java String compareTo() Method:

The compareTo() function in Java is used to compare the current string with another string. This function is a component of the Comparable interface, which is implemented by the String class. The compareTo() method returns one of three values: a positive number, a negative number, or zero.

public class CompareToExample {

public static void main(String[] args) {

     String word1 = “apple”;

     String word2 = “banana”;

     String word3 = “cherry”;

     String word4 = “apple”;

     int result1 = word1.compareTo(word2);

     int result2 = word1.compareTo(word3);

     int result3 = word1.compareTo(word4);

        System.out.println(“Comparison between ‘apple’ and ‘banana’: ” + result1);

        System.out.println(“Comparison between ‘apple’ and ‘cherry’: ” + result2);

        System.out.println(“Comparison between ‘apple’ and ‘apple’: ” + result3);

}

}

Output:

Comparison between ‘apple’ and ‘banana’: -1

Comparison between ‘apple’ and ‘cherry’: -2

Comparison between ‘apple’ and ‘apple’: 0

The compareTo() method is used in this program to compare various words. This is what the results mean:

  • If the result is positive, it means the first word is greater than the second word in lexicographical order.
  • If the result is negative, it means the first word is less than the second word.
  • If the result is 0, it means the two words are the same.

Java String split() Method:

In Java, a string can be divided using the split() function. This technique comes in two versions:

split(String regex) splits the string according to the pattern provided, producing an array of substrings.

split(String regex, int limit): This version, like the previous one, splits the string depending on the pattern, but limits the number of substrings in the array.

Here’s an example:

public class StringSplitExample { 

public static void main(String[] args) { 

     String s = “apple,banana,grape”;

     String[] fruits = s.split(“,”);   

        System.out.println(“Separated using pattern:”);

     for (String fruit : fruits) {

            System.out.println(fruit);

     }

     System.println(“Separated with a limit:”);

     String[] limitedFruits = s.split(“,”, 2);

     for (String fruit : limitedFruits) {

            System.out.println(fruit);

     }

}

}

Output of this program:

Separated using pattern:

apple

banana

grape

Separated with a limit:

apple

banana,grape

The original string “apple,banana,grape” is divided with a comma as a rule in this example. While the second section restricts the split to only two parts, the first part shows the split with no limitations.

Conclusion

In conclusion, Java provides a range of efficient methods for working with strings. This article has highlighted key methods of Strings in Java that let you concatenate, compare, measure length, and split strings. For manipulating text in Java and enhancing the functionality of your program, these functions are important.

Share on your Social Media

Just a minute!

If you have any questions that you did not find answers for, our counsellors are here to answer them. You can get all your queries answered before deciding to join SLA and move your career forward.

We are excited to get started with you

Give us your information and we will arange for a free call (at your convenience) with one of our counsellors. You can get all your queries answered before deciding to join SLA and move your career forward.