For enquiries call:

Phone

+1-469-442-0620

HomeBlogProgrammingStrings in Java with Examples

Strings in Java with Examples

Published
05th Sep, 2023
Views
view count loader
Read it in
12 Mins
In this article
    Strings in Java with Examples

    “Strings” are one of the basic data types in programming. They have a particular place in the world of programmers. By understanding the nuances of strings and utilizing their potential, Java developers can substantially improve their ability to manage and process text data effectively.  Strings are fundamental in many aspects of Java programming, from straightforward string operations to sophisticated text processing techniques. The main goal of this article is to provide you with a thorough understanding of strings in Java.

    While this article lays the basic groundwork, there is always more to learn about important concepts like, java programs on arrays and strings. For further exploration and in-depth knowledge, it is recommended to explore the Programming certification course, where you will find an extensive range of resources, tutorials, and courses to help you master programs on java strings and other important programming concepts.

    What are Strings in Java?

    Strings are one of the basic datatypes present in a programming language. They are used to represent and manipulate different sequences of characters combined. They basically store and handle text data, such as words, sentences, and even entire documents, which are made with characters and other lexical symbols.

    A string in Java is essentially an object that represents an array of different character values. As a result, simultaneously an array of character values functions similarly to a Java String. Also, there are a lot of string methods in Java, which allow for the easy manipulation of these string objects. Therefore, understanding strings in Java is essential for various important tasks in Java programming, such as input/output operations, data manipulation, text processing and other crucial aspects of Java programming. So, keep reading this article to answer different questions like, how to create strings, to why string is immutable in java?

    Using char[] Array in Java

    As stated before, strings are actually array of characters. So in simple terms, a string can be declared with the help of character array and, by initializing it with the necessary sequence of characters. Example:

    char[] charArray = {'H', 'e', 'l', 'l', 'o', ‘!’};
    String str = new String(charArray);
    System.out.println(str); // Output: Hello!

    So basically, this requires a user to create an array of characters using the `char[]` keyword. And, then finally creating a `String` object, and initializing it with the `new` keyword. To learn more about Java programs on strings and arrays, keep following this article!

    Using String Class in Java

    The most convenient and generally used way to work with string in Java is to use the built-in `String` class. It offers a range of methods and functions, which are exclusively used for string manipulation. You can also use the `String` class and double quotes, to create new string objects.

    Example:

    String str = "Hello";
    System.out.println(str); // Output: Hello

    The `String` class offers a wide range of built-in methods for string operations such as concatenation, comparison, extraction, substitution, and more. To know, in-detail about these functions and to learn, how to create java programs on strings for interview in an easier and efficient way, keep reading this article.

    How to Create a String Object?

    Now, this is same as asking the question “how to declare string in java?”. Well, there are lots of different methods to create string objects in Java, such as with the help of string literals, String constant pool, and the `new` keyword. Let us understand all of these things, in detail now, from the point of view of a beginner, along with the different java string syntax.

    String Literal

    The easiest way to create a string object in Java is by using a string literal. A string literal is basically a combination, or sequence of characters enclosed in double quotes. For example:

    String str = "Good";

    In this case, the string literal “Good”, is automatically converted into a String object. And, Java maintains a special area in memory, called the String Constant Pool. And, when you use a string, Java checks if an identical string already exists in the String Constant Pool. And, if such a string exists, then the already existing String object is reused, otherwise, a completely new String object is created. This is a really good mechanism that Java implements, to save memory, by reusing commonly used string values. This is also one of the main reasons why strings are immutable in java? To learn more about this, keep reading this article!!

    String Constant Pool:

    This is a memory area in Java, where completely unique string objects are stored. When a user creates a String object using the string literal, Java first checks the String Constant Pool. And, If a matching string already exists, the reference to that existing object is returned.

    Here is an example, to clearly understand this:

    String str1 = "Learn";
    String str2 = "Learn";

    So, in the above case, both the `str1` and `str2` refer to the same String object in the String Constant pool. When numerous string variables have the same string value, this optimization helps conserve memory.

    By New Keyword

    And finally, another way to create a String object, is with the help of the `new` keyword and the String class constructor. Regardless of whether the string already exists in the String Constant Pool, this method directly generates a new String object in heap memory.

    For example:

    String str1 = "LearnStrings";
    String str2 = new String("LearnStrings");

    Even though the string value is the same as one in the String Constant Pool, using the `new` keyword produces a new object in memory. This approach is handy when you require different instances of strings or when you need to generate string values dynamically. So, even though 'str1' and 'str2' have the identical values in the above example, they nonetheless point to separate locations in memory.

    Examples of Strings in Java

    Now let’s see some simple string program in Java, which provides a better insight into this basic datatype of Java.

    Example 1: Using String Literal

    In this example, we declare a string variable `val1` using a string literal, which is a sequence of characters enclosed in double quotes. The value "Knowledge" is assigned to `val1`.

    String val1 = "Knowledge";
    System.out.println(val1); // Output: Knowledge

    By printing the value of `val1`, we see that it displays "Knowledge" in the console.

    Example 2: Using the `new` keyword

    This example declares a string variable `val2` using the `new` keyword and the String class constructor. The value “Hut” is then assigned to `val2`.

    String val2 = new String("Hut");
    System.out.println(val2); // Output: Hut

    By printing the value of `val2`, we observe that it displays "Hut" in the console.

    Example 3: Simple String Concatenation

    Finally, we will combine both strings `val1` and `val2`, created in the previous examples, to create a new string variable `val3`.

    String val3 = val1 + val2;
    System.out.println(val3); // Output: KnowledgeHut

    Therefore, the value of val3, displays the concatenated result of "Knowledge" and "Hut," which is "KnowledgeHut."

    Methods of Java Strings

    Now, there are lots of string methods in Java. These are built-in functions, which can help us manipulate the String objects easily. And generally, information about these methods is very frequently asked in interview programs on strings in Java. 

    Using string methods in Java, we can get the length of a string, concatenate several strings, verify whether two strings are equal, transform the characters of a string to uppercase or lowercase, and much more. Also, generally a combination of these methods/functions are used to solve complex programs in Java. Let us have a look at some of the most popular and extensively used string methods in Java with examples.

    And most importantly, it should be noted that, all the string methods are provided in the `java.lang.String` class in Java.

    1. int length() Method

    The `length()` method returns the total number of characters, present in a string, or, in technical terms, it returns the total length of the string. In some circumstances, programs behave based on the length of the string, therefore this approach comes helpful at those times.

    Syntax:

    stringVariableName.length()

    Example:

    String str = "Hello, Java!";
    int length = str.length();
    System.out.println(length); // Output: 13

    2. char charAt(int index) Method

    This is a very important method for solving various programs on Strings in Java. The `charAt()` method of string takes an index number as an input and returns the character at that index number.

    The indexing ranges from 0 to str.length-1, where str.length is the string's length. And, `StringIndexOutOfBoundsException` is raised if the supplied index number is not present in the string (if it is equal to or larger than the length of the string, or if it is a negative value).

    Syntax:

    stringVariableName.charAt(index)

    Example:

    String str = "Hello, KnowledgeHut!";
    char ch = str.charAt(2);
    System.out.println(ch); // Output : l

    3. String concat(String string1) Method

    This method also helps in joining two strings together, to create a completely new string. 

    Syntax:

    String1.concat(string1)

    Example:

    String str1 = “Knowledge”;
    String str2 = str1.concat(“Hut”);
    System.out.println(str2); // Output: KnowledgeHut
    
    

    4. String substring(int beginIndex, int endIndex[optional]) Method

    In Java, the substring() method of string returns the requested segment of the string. It accepts two index numbers as input: beginning index and ending index. The beginning index is inclusive whereas the ending index is exclusive, which basically implies that the substring portion will begin at beginIndex and terminate at endIndex - 1.

    And, if we don’t specify the endIndex, then it is taken as the total length of the string.

    Syntax:

    string.substring(startIndex, endIndex)

    Example:

    String str = "KnowledgeHut";
    String str1 = str.substring(0, 5);
    String str2 = str.substring(7);
    System.out.println(str1); // Output: Knowl
    System.out.println(str2); // Output: geHut (from index 7 to 11 both inclusive)

    5. String equals(String anotherString) Method

    There is a built-in function to check the equality of two different String objects, which is known as the `equals()` function. The equals method will take a string as an input and compare it with another string. If both the strings are equal, the answer is true; otherwise, it is false. Now let’s see a java program to compare two strings character-wise.

    Syntax:

    String1.equals(string2)

    Example:

    String str = "hut"; 
    String str1 = "HUT";
    String str2 = "hut"; 
    String str3 = "learn"; 
    System.out.println(str.equals(str1)); // Output: false
    System.out.println(str.equals(str2)); // Output: true
    System.out.println(str.equals(str3)); // Output: false

    6. String contains(String substring) Method

    This is a built-in function in Java, which is used to check if a given string is a part of a bigger string. And it returns ‘true’ value, if the bigger string contains the smaller string, otherwise, it returns ‘false’.

    Syntax:

    bigString.contains(smallString)

    Example:

    String str = "Learn Java Strings"; 
    System.out.println(str.contains("Java Strings")); // Output: true
    System.out.println(str.contains("Hello")); // Output: false
    System.out.println(str.contains("Learn")); // Output: true
    System.out.println(str.contains("Hi")); // Output: false
    You can go for Python Programming course to master Python concepts and get experienced guidance.

    7. String join(CharSequence joiner, String st1, String str2, String str3...)

    In Java working with strings is very easy. So, this method is used to join various strings together, with a specified parameter, known as a ‘joiner’.

    Syntax:

    string.join(joiner, str1, str2, str3, str4, …)

    Example:

    String str1 = String.join("-","Hi","Good","Morning"); 
    System.out.println(str1); // Output: Hi-Good-Morning
    String str2 = String.join(" ","Hi","Good","Morning"); 
    System.out.println(str2); // Output: Hi Good Morning

    8. int compareTo(String string1, String string2) Method

    The java compare strings, `compareTo()` method compares two strings lexicographically. It actually returns an integer value, that represents the difference between two string objects.

    Syntax:

    string1.compareTo(string2)

    Example:

    String str1 = "Apple";
    String str2 = "Banana";
    int result = str1.compareTo(str2);
    System.out.println(result); // Output: -1

    9. String toUpperCase() Method

    This method converts all the characters present in each string to upper-case characters. 

    Syntax:

    string.toUpperCase()

    Example:

    String var = “knowledgeHut”;
    String res = var.toUpperCase(var);
    System.out.println(res); // Output: KNOWLEDGEHUT

    To know more about such methods, read this article, which has different string methods in java with examples.

    10. String toLowerCase() Method

    This method is as simple as it sounds, i.e., it converts all the characters present in each string to lower-case characters.

    Syntax:

    string.toLowerCase()

    Example:

    String var = “KNOWledGeHut”;
    String res = var.toLowerCase(var);
    System.out.println(res); // Output: knowledgehut

    11. String trim() Method

    This built-in method is very helpful for working on programs on java strings, as it removes trailing or extra white-spaces from both the ends of a string object.

    Syntax:

    string.trim()

    Example:

    String var = “ learn ”;
    String res = var.trim();
    System.out.println(res); // Output: learn

    12. String replace(char oldChar, char newChar) Method

    This method is used to replace all the specified characters of a string with another character.

    Syntax:

    string.replace(old, new)

    Example:

    String str = “Hello World”;
    str = str.replace(‘l’,’k’);
    System.out.println(str); // Output: Hekko Workd

    Java Strings: Mutable or Immutable

    Once Java strings are created, their values cannot be changed, i.e., strings are immutable in java.

    Now, why is this important or, why are strings immutable in java? Well as seen before, in Java a single object can have multiple references in the String Constant Pool. Thus, If the value of one reference variable is changed, it can affect other strings or reference variables, leading to problems. Java Programming will help you supplement theoretical learning with practical exercises and learn from leading Java experts.

    Conclusion

    Understanding strings and different ways of working with strings in java, is very important for a beginner, as well as for a professional.

    So, strings are basically a sequence of combined characters. Newly formed strings are kept in a specific heap memory location called the String Constant Pool. There are multiple ways of creating a string, with the `new` keyword, and with double quotes. Also, there are multiple ways to manipulate the string object, with `java.lang.String` class’s built-in methods. And finally, strings are immutable. The only way to create mutable strings is with the help of String Buffer in Java. Which is a completely different topic.

    Frequently Asked Questions (FAQs)

    1How do you find the length of a string in Java?

    In Java, you can find the length of a string using the `length()` method of the String class. For example: int length = stringVariable.length();

    2How do you compare two strings in Java?

    There are two different meaning to comparison. You can compare two or more strings using the `equals()` method for content comparison or the `compareTo()` method for lexicographical comparison.

    Example for content comparison: boolean isEqual = string1.equals(string2);

    Example for lexicographical comparison: int result = string1.compareTo(string2);

    3How do you format a string in Java?

    In Java, a string can be formatted using the `String.format()` method or by using the `printf()` method from the `System.out` object.

    4How do you concatenate strings in Java?

    There are two ways to combine or concatenate strings in Java. That is, by using the ‘+’ operator, and by using the `concat()` method.

    Example using ‘+’ operator: String result = string1 + string2;

    Example using `concat()` method: String result = string1.concat(string2);

    Profile

    Euhid Aman

    Blog Author

    Euhid Aman, is a freelance technical writer and web developer, who publishes technical articles on his Medium blog. He has also worked as a Research Intern in Taiwan, where he developed optimized deep learning applications for embedded systems. He has also interned at multiple companies and published research papers on AI-ML, highlighting his expertise in ANNs.

    Share This Article
    Ready to Master the Skills that Drive Your Career?

    Avail your free 1:1 mentorship session.

    Select
    Your Message (Optional)

    Upcoming Programming Batches & Dates

    NameDateFeeKnow more
    Course advisor icon
    Course Advisor
    Whatsapp/Chat icon