Once you click post assignment, learners in the selected class will immediately be able to see and complete this assignment
Back to Classroom
String Length
Java String Course
Engineers From These Top Companies and Universities Trust EXLskills
1M+ Professionals | 100+ Institutions
This is the EXLskills free and open-source Java String Micro Course. It guides learners via explanation, demonstration, and thorough practice, from no more than a basic understanding of Java, to a moderate level of understanding regarding Java Strings.
Is this course FREE?
Yes, this a 100% free course that you can contribute to on GitHub here!
Let's dive into introducing the methods that exist in the String class. A fundamental method to start off with is one that finds the length of a String, which is also the number of characters, including punctuation and spaces, that make up the string. The syntax for finding the length of a String is stringname.length(). Look below to see an example of its use.
StringLengthExample.java
package exlcode;
public class StringLengthExample {
public static String exampleVariableOne = "Hello World!";
public static String exampleVariableTwo = "";
// returns the length of exampleVariableOne and exampleVariableTwo
// and assigns it to lengthOne and lengthTwo
public static int lengthOne = exampleVariableOne.length();
public static int lengthTwo = exampleVariableTwo.length();
public static void main(String[] args) {
System.out.println(lengthOne);
System.out.println(lengthTwo);
}
}
Did you run the program? Did you see how an empty String has a length of zero? Take note of the fact that the length method takes no parameters but the parenthesis are part of the necessary syntax to call the method, along with the dot which tells the program that you want to use the length method that exists in the String class.
Please keep in mind for future sections, that the length of the String has nothing to do with the index. You can just count up the number of characters inside the String to determine the accurate length.