Pages

Tuesday, February 12, 2019

Java String length method example

Java String length:


String length() is used to get the length of a Java String. The string length method returns the number of characters in String. The length is equal to the number of 16-bit Unicode characters in the string.


Syntax:

The signature of the String length() method is given below.


public int length()


This method returns int value for characters in string.





String length example 1:


In this example, will see a basic example program to demonstrate length method. First call length method and prints it's length.


package examples.java.w3schools.string;

public class StringLengthExample {
    public static void main(String[] args) {

        String input1 = "java-w3schools";
        int length1 = input1.length();
        System.out.println("Input String length1: " + length1);

        String input2 = "string length method";
        int length2 = input2.length();
        System.out.println("Input String length2: " + length2);

        String input3 = "";
        int length3 = input3.length();
        System.out.println("Input String length3: " + length3);
    }
}



Output:

Input String length1: 14
Input String length2: 20
Input String length3: 0

String length example 2:


Checking the pin code is valid or not. In India, Valid pin code length should be 6 digit number. Below code to check the length is valid or not.




package examples.java.w3schools.string;

public class StringLengthExample {
    public static void main(String[] args) {

        String pincode1 = "500001";

        if (pincode1.length() == 6) {
            System.out.println("given pincode " + pincode1 + " is valid");
        } else {
            System.out.println("given pincode " + pincode1 + " is not valid");
        }

        String pincode2 = "50000";

        if (pincode2.length() == 6) {
            System.out.println("given pincode " + pincode2 + " is valid");
        } else {
            System.out.println("given pincode " + pincode2 + " is not valid");
        }

    }
}


Output:



given pincode 500001 is valid
given pincode 50000 is not valid



Internal Implementation:



public int length() {
        return value.length >> coder();
    }

   
Here value is the byte array which is declared in String class as below.

 
    @Stable
    private final byte[] value;
   
The value is used for character storage.
This field is trusted by the VM, and is a subject to constant folding if String instance is constant. Overwriting this field after construction will cause problems.

Please post your questions in comments section.

No comments:

Post a Comment

Please do not add any spam links in the comments section.