Online visitors

People learning around the world

Online

—

Visitors exploring W3Schools

Online visitors by country Circles show approximate country locations. The country list provides the visitor counts.

Circles represent countries, not exact visitor locations.

Country

Online

Loading country activity…

    Java Strings Class

    Java Programming Tutorials


    A string is a sequence of character in Java, widely used as an object.

    Strings Initialization in Java

    There are two ways to declare a string in Java, and the most common way to create a string is to write:

    Example:

    String name = "Alex";

    Through char array:

    public class Sample {
    
        public static void main(String args[]) {
            char[] nameArray = {'A', 'l', 'e', 'x'};
            String name = new String(nameArray);
            System.out.println(name);
        }
    }

    Program Output:

    java-string-class1

    Concatenating Strings

    concat() method can be used to attach strings.

    Example:

    public class Sample {
    
        public static void main(String args[]) {
            String str1 = "Hello ", str2 = "World!";
            System.out.println(str1.concat(str2));
        }
    }

    + operator is more commonly used to attach strings.

    "Hello," + " world" + "!"

    Program Output:

    java-string-concat

    Java String Case

    Java toUpperCase() and toLowerCase() method is used to change string case.

    Example:

    public class Sample {
    
        public static void main(String args[]) {
            String str1 = "Hello";
            System.out.println(str1.toUpperCase());
            System.out.println(str1.toLowerCase());
        }
    }
    

    Program Output:

    java-string-case

    Java Trim String

    Java trim() method is used to eliminates white spaces before and after a string.

    Example:

    public class Sample {
    
        public static void main(String args[]) {
            String str = " Hello ";
            System.out.println(str.trim());
        }
    }
    

    Program Output:

    java-string-trim

    Java String length

    Java length() method is used to get the length of the string.

    Example:

    public class Sample {
    
        public static void main(String args[]) {
            String str = "Cloud";
            System.out.println(str.length());
        }
    }
    

    Program Output:

    java-string-length



    Found This Page Useful? Share It!
    Get the Latest Tutorials and Updates
    Join us on Telegram

    Notifications

    Updates are enabled for this browser.

    Receive new tutorials, articles and learning resources. You can turn updates off anytime.