Java examples – fastest way to learn Java

String

What is a Java String class?

Java String class represents set of characters.
In this example:
String s = "This is some text."
variable s is a reference to the String object which keeps series of characters – “This is some text.”.
So, to assign a text to the variable, you will need to create a String object (not a primitive data type like int, double, boolean etc…).



Immutable String objects

Once you have assigned a value to the String object, that value can never change which means – it is immutable!
For example, if you have one String object and you want to add some text at the end
String s1 = "Java String class";
s1 = s1 + " example";
//now s1 has a value "Java String class example"

Even that we think that we have changed s1 object from “Java String class” to “Java String class example”, that is not true.
As we said, Java String objects can not be changed which means that Java VM did something else than just updating a value inside s1 object.
What Java VM did here is:

  • Second String object has been created with a value – ” example”.
  • Third String object has been created with a value of joined strings “Java String class example”.
  • Reference of the first String object (s1) now refers to the third String object.

Instead of updating only one object, Java will create three String objects where only one we need, but others are still in the memory (until Java garbage collector removes them). That means that if we need to join many String objects, Java will create many String objects which can occupy large amounts of program’s memory.
If you want to join many strings to create a large string, you should use StringBuilder or StringBuffer class.

String constant pool

Why JVM makes String objects as immutable? The answer is – due to memory efficiency.
JVM has a special area in the memory called “String constant pool” to reduce the number of String objects created in the JVM.
When the Java compiler encounters a string literal, it checks first the pool to see if an identical string already exists. If a match is found, the reference to the new literal is directed to the existing string, and no new string literal object is created.
String s1 = "Java";
String s2 = "Java";
if (s1 == s2) {
    System.out.println("s1 and s2 are referring to the same object!");
};

Important Java String methods

  • public char charAt(int index) – returns the character located at the String’s specified index.
  • public String concat(String s) – concatenates the string in the argument to the end of the string used to invoke this method.
  • public boolean equalsIgnoreCase(String s) – returns true or false depending on whether the string in the argument is the same as the string used to invoke this method.
  • public int length() – returns the length of the string.
  • public String replace(char old, char new) – the first argument is replaced by the character in the second argument.
  • public String substring(int begin) – returns a substring of the string used to invoke this method from the character located at specified location. The first index is 0.
  • public String substring(int begin, int end) – returns a substring of the string used to invoke this method from the character located at ‘begin’ location to the character at ‘end’ location. The first index is 0.
  • public String toLowerCase() – returns a string with all characters of the string used to invoke this method converted to lowercase using the rules of the given Locale.
  • public String toUpperCase() – returns a string with all characters of the string used to invoke this method converted to uppercase using the rules of the given Locale.
  • public String trim() – returns a string same as string used to invoke this method but without any leading or trailing spaces.
  • public String valueOf(/*any primitive type or object*/) – returns the string representation of the primitive type or object argument.

Java String class example

/**
 * Java String class example shows how to use
 * some of the most used methods of the String class
 */

public class JavaStringExample {

    public static void main(String[] args) {
        String s = "Java";
        System.out.println(s);
        System.out.println("Length: " + s.length());
        System.out.println("Lowercase: " + s.toLowerCase());
        System.out.println("Uppercase: " + s.toUpperCase());
        System.out.println("'a' replaced with '*': " + s.replace('a', '*'));
        System.out.println("Substring (2-4):" + s.subSequence(1, 3));
        System.out.println("Equals ignore case to 'JAVA': " + s.equalsIgnoreCase("JAVA"));
        System.out.println("Character at 3rd position: " + s.charAt(2));
    }

}

Output of the Java example of how to use Java String class

Tags: Class, Object, String

  • Similar Java examples

    • Array length
    • Create array
    • Creating a thread by implementing Runnable interface
    • Char data type
    • Collections basics
  • Recent Java examples

    • String
    • Finding min array element value
    • Finding max array element value
    • Main method
    • Multidimensional array
  • Follow @JavaCodeExample
  • Basics
    • Abstract class
    • Array
    • Classes and Objects
    • Flow control
    • Hello World
    • Interface
    • Keywords
    • OOP concepts
    • Operators
    • Primitive Types
    • Threads
    • Variables
  • Collections
    • Collection Interfaces
    • Introduction
    • List
    • Map
    • Set
  • I/O
    • File
    • Streams
  • Important classes
    • String
  • RSS Feed
  • facebook
  • twitter
Copyright © Java Code Examples   Log In