Search code examples
javastringreturn

Return new String(password); Can somebody explain, how this is returning of String works here?


I got the logic but I din't understood that why we are returning new String(password), is it converting the char[] to string, if so, how? I am always confused in casting and converting. Give me simple and detailed answer to understand the concept clearer.

private String randomPass(int length)
    {
        String passwordSet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890@#";
        char[] password = new char[length];
        for(int i = 0; i < length; i++)
        {
            int rand = (int) (Math.random() * passwordSet.length());
            password[i] = passwordSet.charAt(rand);
        }
        return new String (password);
    }

Solution

  • Yes, new String(someCharArray) returns a string whose value is just concatenating each char in the array together. So:

    char[] example = new char[] {'H', 'e', 'y', '!'};
    String s = new String(example);
    System.out.println(s);
    

    Would print Hey!.

    How does it work? ... it does. The source is available if you really want to know, but how strings are represented in memory depends on JVM version, is somewhat complicated, and most importantly, is irrelevant to day to day coding exercises. A string with the value Hey! operates as one would expect. s.length() would return 4. s.indexOf('e') would return 1. etcetera.