Search code examples
javastringmethodsstring-length

How to get a length of a String by using 1 method? SHORTER


It's really easy to get the length of a single string and return it's value!

public static int length(String s){//trys and returns length of any string
    try{//try code
    len = s.length();//gets the length of any string
    }catch (NullPointerException nullError){//checks for nulls
        len = 0;//if there is a null then there is 0 length of the string
    }
    return len;//return the integer length of any string
}

This simple code will catch an error! An example of an error would be if you use a JOptionPane and the user doesn't print anything just clicks the X. That would cause a null error! So if that's the case then then length would just be 0!

But now I just want to know how to make this a shorter code!


Solution

  • return str != null ? str.length() : 0