Skip to content

Java String

Strings are sequences of characters—letters, numbers, symbols—that you can use to represent text in your programs. Strings are incredibly versatile and can be used for everything from printing messages to processing user input.

Example 1: Creating a String Using Double Quotes

java
public class StringExample1 {
    public static void main(String[] args) {
        // Create a string using double quotes
        String greeting = "Hello, world!";
        
        // Print the string
        System.out.println(greeting);  // Output: Hello, world!
    }
}

In this example, we create a string greeting using double quotes. This is the simplest way to create a string in Java. We then print out the string to see it in action.

Example 2: Creating a String Using the String Constructor

java
public class StringExample2 {
    public static void main(String[] args) {
        // Create a string using the String constructor
        String message = new String("Welcome to Java!");

        // Print the string
        System.out.println(message);   // Output: Welcome to Java!
    }
}

Here, we create a string message using the String constructor, passing the desired text as an argument. While this method is less common than using double quotes, it provides flexibility in certain situations.

Example 3: Creating a String from a Character Array

java
public class StringExample3 {
    public static void main(String[] args) {
        // Create a character array
        char[] chars = {'J', 'a', 'v', 'a'};
        
        // Create a string from the character array
        String word = new String(chars);

        // Print the string
        System.out.println(word);      // Output: Java
    }
}

In this example, we first create a character array chars representing the characters 'J', 'a', 'v', and 'a'. Then, we create a string word using the String constructor and passing the character array as an argument. Finally, we print out the string to see the result.

Strings are like the building blocks of your Java programs—they help you communicate with your users, store data, and perform all sorts of cool tricks. Whether you're printing a friendly greeting or processing user input, strings have got your back!

Waytojava is designed to make learning easier. We simplify examples for better understanding. We regularly check tutorials, references, and examples to correct errors, but it's important to remember that humans can make mistakes.