Introduction
In this lab, you will learn how to check if a string has a specific length in Java. We will cover the fundamental steps involved, starting with using the length() method to obtain the string's length. You will then learn how to compare this length with an expected value and, importantly, how to handle potential null strings to prevent errors. By the end of this lab, you will have a solid understanding of how to perform robust string length checks in your Java applications.
Use length() to Get String Length
In this step, we will learn how to find the length of a string in Java using the length() method. The length() method is a built-in function in Java that returns the number of characters in a string.
First, let's create a new Java file named
StringLength.javain your~/projectdirectory. You can do this by right-clicking in the File Explorer on the left and selecting "New File", then typingStringLength.java.Open the
StringLength.javafile in the editor and add the following code:public class StringLength { public static void main(String[] args) { String greeting = "Hello, LabEx!"; int length = greeting.length(); System.out.println("The length of the string is: " + length); } }Let's look at the new parts:
String greeting = "Hello, LabEx!";: This line declares a variable namedgreetingof typeStringand assigns it the value"Hello, LabEx!".int length = greeting.length();: This is where we use thelength()method. We calllength()on thegreetingstring, and it returns the number of characters (including spaces and punctuation). This number is then stored in an integer variable namedlength.System.out.println("The length of the string is: " + length);: This line prints the text "The length of the string is: " followed by the value stored in thelengthvariable.
Save the file (Ctrl+S or Cmd+S).
Now, open the Terminal at the bottom of the WebIDE and make sure you are in the
~/projectdirectory. You can usecd ~/projectif needed.Compile the Java program using the
javaccommand:javac StringLength.javaIf there are no errors, you should see no output.
Run the compiled Java program using the
javacommand:java StringLengthYou should see the following output:
The length of the string is: 13This output confirms that the
length()method correctly calculated the number of characters in the string "Hello, LabEx!", which is 13.
You have successfully used the length() method to find the length of a string in Java!
Compare Length with Expected Value
In the previous step, we learned how to get the length of a string. Now, let's use this knowledge to compare the length of a string with an expected value. This is a common task in programming, for example, to check if a password meets a minimum length requirement.
We will modify the StringLength.java file we created in the previous step.
Open the
StringLength.javafile in the WebIDE editor.Modify the
mainmethod to include a comparison. Replace the existingmainmethod with the following code:public class StringLength { public static void main(String[] args) { String password = "mysecretpassword"; int minLength = 8; // Minimum required length int passwordLength = password.length(); System.out.println("Password: " + password); System.out.println("Password length: " + passwordLength); System.out.println("Minimum required length: " + minLength); if (passwordLength >= minLength) { System.out.println("Password meets the minimum length requirement."); } else { System.out.println("Password does NOT meet the minimum length requirement."); } } }Let's look at the changes:
- We've changed the string variable name to
passwordand assigned it a different value. - We introduced a new integer variable
minLengthto store the minimum required length. - We calculate the
passwordLengthusing thelength()method as before. - We added an
ifstatement. Theifstatement checks if thepasswordLengthis greater than or equal tominLength. - If the condition (
passwordLength >= minLength) is true, the code inside theifblock is executed, printing a success message. - If the condition is false, the code inside the
elseblock is executed, printing a failure message.
- We've changed the string variable name to
Save the file (Ctrl+S or Cmd+S).
Open the Terminal and make sure you are in the
~/projectdirectory.Compile the modified Java program:
javac StringLength.javaAgain, no output means successful compilation.
Run the program:
java StringLengthBased on the current
passwordandminLength, you should see output similar to this:Password: mysecretpassword Password length: 16 Minimum required length: 8 Password meets the minimum length requirement.Try changing the
passwordstring in the code to something shorter than 8 characters (e.g.,"short"), save the file, recompile, and run it again to see theelseblock being executed.
You have now learned how to compare the length of a string with a specific value using an if statement!
Handle Null Strings in Length Check
In the previous steps, we worked with strings that had actual character values. However, in programming, a string variable can sometimes have a special value called null. A null value means that the variable does not refer to any object. If you try to call a method like length() on a null string, your program will crash with a NullPointerException.
In this step, we will learn how to safely handle null strings before trying to get their length.
Open the
StringLength.javafile in the WebIDE editor.Modify the
mainmethod to include a check fornull. Replace the existingmainmethod with the following code:public class StringLength { public static void main(String[] args) { String potentialString = null; // This string is null int minLength = 5; // Minimum required length System.out.println("String to check: " + potentialString); System.out.println("Minimum required length: " + minLength); if (potentialString != null) { int stringLength = potentialString.length(); System.out.println("String length: " + stringLength); if (stringLength >= minLength) { System.out.println("String meets the minimum length requirement."); } else { System.out.println("String does NOT meet the minimum length requirement."); } } else { System.out.println("Cannot check length: The string is null."); } } }Let's look at the changes:
- We've changed the variable name to
potentialStringand initially set its value tonull. - We added an outer
ifstatement:if (potentialString != null). This checks if thepotentialStringvariable is NOTnull. - The code to get the length (
potentialString.length()) and the subsequent length comparison are now inside thisifblock. This ensures thatlength()is only called if the string is notnull. - The
elseblock of the outerifstatement handles the case where the string isnull, printing a message indicating that the length cannot be checked.
- We've changed the variable name to
Save the file (Ctrl+S or Cmd+S).
Open the Terminal and make sure you are in the
~/projectdirectory.Compile the modified Java program:
javac StringLength.javaNo output means successful compilation.
Run the program:
java StringLengthSince
potentialStringisnull, you should see the following output:String to check: null Minimum required length: 5 Cannot check length: The string is null.Now, try changing the value of
potentialStringto a non-null string, like"Java", save, recompile, and run again. You should see the length check being performed.String potentialString = "Java"; // This string is not nullAfter recompiling and running:
String to check: Java Minimum required length: 5 String length: 4 String does NOT meet the minimum length requirement.This demonstrates how to safely handle
nullstrings before attempting to call methods on them, preventing your program from crashing.
Summary
In this lab, we learned how to determine the length of a string in Java using the built-in length() method. We practiced creating a Java program, using the length() method to get the character count of a string, and then compiling and running the program to see the output. This fundamental skill is essential for various string manipulations and validations in Java programming.



