Java String Introduction Tutorial

Java is a strongly typed language. Java data types directly describe what the identifier's data will hold. Various data manipulations can be performed based on the data type the identifier is declared as. There are two categories of built-in data types: the eight primitive data types and object-oriented data types. This tutorial will introduce you to one of the most commonly used object-oriented data types, the String class. I will teach objects in a later tutorial, so don't worry about understanding what they are just yet.



Open the command prompt (CMD - see the Getting Started ) and type in the following commands.

C:\Windows\System32>cd \
C:\>md Java
C:\>cd Java
C:\Java>
C:\Java>md StringIntro
C:\Java>cd StringIntro
C:\Java\StringIntro>Notepad StringIntro.java

Copy and Paste, or type the following code into Notepad and be sure to save the file when you are done.


class StringIntro {
    public static void main(String args[]) {
        String s1 = "The String class ";
        String s2 = "has many methods.";
        String s3 = s1+s2;
        String s4 = "0123456789";
        String s5 = "  Car    ";
        String s6 = "  pet";
        int stringLength;

        System.out.println(s1+s2);
        System.out.println(s3);
    
        System.out.println(s3.length()); //display the length of s3;
    
        System.out.println(s3.charAt(2)); //display character at index position 2
        System.out.println(s3.charAt(0)); //charAt index begins at 0

        //substring includes the first index character up until, but not including the last index character
        System.out.println(s4.substring(3,8)); 

        System.out.println(s3.toUpperCase());
        System.out.println(s3.toLowerCase());

        System.out.println(s5.trim()+s6.trim());

    }
}

Now switch back to the command prompt (CMD) and type in javac StringIntro.java and press Enter.
Now type in java StringIntro and press Enter.


C:\Java\StringIntro>javac StringIntro.java
C:\Java\StringIntro>java StringIntro
The String class has many methods.
The String class has many methods.
34
e
T
34567
THE STRING CLASS HAS MANY METHODS.
the string class has many methods.


Final thoughts

In a future tutorial I will discuss the String class more in depth. At first glance the String class seems fairly simple, but in truth the String class has certain limitations and memory based complications.


Tutorials