Java String Length Sample Code

The following sample code will show you how to determine the length of a String. The String class represents character strings. The length() method will give us a numerical value as to the number of characters in a string, which does include spaces.


String Length Sample

We have defined a String called myString and then printed out the length of the string by calling the length() method.

package com.jcd.java.tutorials;

public class JavaStringLength 
{

	public static void main(String[] args) 
	{
		
		//Let's define a String literal
		String myString = "JavaCodeDepot is all about Java!";
		
		System.out.println("Length of myString: "+myString.length());

	}

}
Length of myString: 32


String Length Sample

This example is almost the same as the first example. The length of the string has been saved to an integer value and the integer value is used to when printing out the length.

package com.jcd.java.tutorials;

public class JavaStringLength 
{

	public static void main(String[] args) 
	{
		
		//Let's define a String literal
		String myString = "JavaCodeDepot is all about Java!";
		
		//Integer to hold length of String
		int myStringLen = myString.length();
		
		System.out.println("Length of myString: "+myStringLen);

	}

}
Length of myString: 44


String Length Sample

This short code example show that you can define a sequence of characters in double quotes and apply the same length() method without actually defining a String Object.

package com.jcd.java.tutorials;

public class JavaStringLength 
{

	public static void main(String[] args) 
	{
		
		System.out.println("Length of String: "+"Java Code Depot Sample Code".length());

	}

}
Length of String: 27


Concluding Comments

The built in method length() of the String class is the best way to determine the length of any string when using the Java programmiing language.



References:

Add a Comment

Your email address will not be published. Required fields are marked *