Java 8 – How to get length of a String ?

In this article, we will understand with a Java program on how to get length of a String in Java 1.8 version

Already in one of the previous article, we discussed how to get length of a String using earlier versions of Java like 5 or 7, etc.

Get length of a String:

  • length() method of String
    • Calculates the length of the invoking String
    • Returns the length of the String if it consists characters
    • Returns 0 (Zero) if the invoking String is empty
    • If invoking string is null, then java.lang.NullPointerException is thrown

GetStringLength.java

package in.bench.resources.java8.string.methods;

import java.util.stream.Stream;

public class GetStringLength {

	public static void main(String[] args) {

		// 1. string
		String url = "BenchResources.Net";


		// 1.1 checking string is empty
		long lengthOfUrlStr = Stream.of(url).map(String::length).findFirst().get();
		System.out.println("Length of (" + url + ") is = " + lengthOfUrlStr);


		// 2. Empty string
		String str1 = "";


		// 2.1 checking string is empty
		long lengthOfStr1 = Stream.of(str1).map(String::length).findFirst().get();
		System.out.println("Length of (" + str1 + ") is = " + lengthOfStr1 + "\n\n");


		// 3. null string
		String str2 = null;


		// 3.1 checking empty on null string
		long lengthOfStr2 = Stream.of(str2).map(String::length).findFirst().get();
		System.out.println("Length of (" + str2 + ") is = " + lengthOfStr2);
	}
}

Output:

Length of (BenchResources.Net) is = 18
Length of () is = 0


Exception in thread "main" java.lang.NullPointerException
	at java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:197)
	at java.base/java.util.stream.Streams$StreamBuilderImpl.tryAdvance(Streams.java:397)
	at java.base/java.util.stream.ReferencePipeline.forEachWithCancel(ReferencePipeline.java:129)
	at java.base/java.util.stream.AbstractPipeline.copyIntoWithCancel(AbstractPipeline.java:527)
	at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:513)
	at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:499)
	at java.base/java.util.stream.FindOps$FindOp.evaluateSequential(FindOps.java:150)
	at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
	at java.base/java.util.stream.ReferencePipeline.findFirst(ReferencePipeline.java:647)
	at in.bench.resources.java8.string.methods.GetStringLength.main(GetStringLength.java:32)

Related Articles:

References:

Happy Coding !!
Happy Learning !!

Java 8 – How to convert a String into char[] Arrays ?
Java 8 - How to check whether a String is empty or not ?