String Class Tutorials

public int length()

In this tutorial I will discuss the length() method. The length method returns the number of characters (unicode) in the string.
For example,
String apples = "Apples";
int i = apples.length();
// 6
String oranges = new String("Oranges");
int x = oranges.length();
// 7
It is noteworthy to mention that an array has a variable named length. It is easy to confuse the two, a string object has a method .length() that returns the number of characters in a string, and an array has a public instance variable .length that returns the number of elements in an array.



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 StringLength
C:\Java>cd StringLength
C:\Java\StringLength>Notepad StringLength.java

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


class StringLength {
    public static void main(String args[]) {
        String apples = "Apples";
        System.out.println(apples + " length: " + apples.length());

        String oranges = new String("Oranges");
        System.out.println(oranges + " length: " + oranges.length());
       
        char oranges2[] = { 'O', 'r', 'a', 'n', 'g', 'e', 's' };
        System.out.println("Oranges2 length: " + oranges2.length); // notice the variable versus the method.
    }
}


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


C:\Java\StringLength>javac StringLength.java
C:\Java\StringLength>java StringLength
Apples length: 6
Oranges length: 7
Oranges2 length: 7


Final thoughts

One strategy that I regularly use to solidify my knowledge of Java is to browse through the actual source code. Due to some language in their copyright file, I can't actually show the source code in my videos. The source code is contained inside of a file called src.zip located in the folder where your JDK is installed. I recommend using notepad++ to browse the class files.


Tutorials