Start learning free

LESSON 197 OF 291 · PROJECTS: EVERYDAY PROGRAMS

Password Strength V3 in Kotlin: Character Classes

Practice Read the full explanation

Track four boolean flags for a password: does it contain an uppercase letter, a lowercase letter, a digit, and a symbol (non-alphanumeric)?

You start with:

val password = "Secret!99"

Build:

Length: 9
Upper: True
Lower: True
Digit: True
Symbol: True
Strong

Rules:

  • Print "Length: " followed by the number of characters.
  • Start four flags (hasUpper, hasLower, hasDigit, hasSymbol) at false. Loop over every character and set the matching flag to true.
  • A symbol is any character that is not a letter and not a digit.
  • Print one line per flag, in this order: "Upper: ", "Lower: ", "Digit: ", "Symbol: ", each followed by the flag. Write it as True or False with a capital letter, exactly as in the example (your language's own boolean prints differently, so choose the text yourself).
  • If the length is at least 8 and all four flags are true (stricter than the last lesson), print Strong; otherwise print Weak.

Try other passwords: with secret99 the output is

Length: 8
Upper: False
Lower: True
Digit: True
Symbol: False
Weak

Use c.isUpperCase(), c.isLowerCase(), c.isDigit() and c.isLetterOrDigit() inside for (c in password).

val password = "Secret!99"

val length = password.length
println("Length: $length")
var hasUpper = false
var hasLower = false
var hasDigit = false
var hasSymbol = false
for (c in password) {
    if (c.isUpperCase()) {
        hasUpper = true
    }
    if (c.isLowerCase()) {
        hasLower = true
    }
    if (c.isDigit()) {
        hasDigit = true
    }
    if (!c.isLetterOrDigit()) {
        hasSymbol = true
    }
}
println("Upper: " + (if (hasUpper) "True" else "False"))
println("Lower: " + (if (hasLower) "True" else "False"))
println("Digit: " + (if (hasDigit) "True" else "False"))
println("Symbol: " + (if (hasSymbol) "True" else "False"))
if (length >= 8 && hasUpper && hasLower && hasDigit && hasSymbol) {
    println("Strong")
} else {
    println("Weak")
}

STEP 1 OF 13
    Ctrl + Enter to check

    KOTLIN · PROJECTS: EVERYDAY PROGRAMS

    Password Strength V3 in Kotlin, explained

    Problem overview

    The checker now looks at four kinds of character. For the password Secret!99 the program reports whether it contains an uppercase letter, a lowercase letter, a digit and a symbol, and gives the verdict Strong only when all four are present and the length is at least 8. A symbol is any character that is neither a letter nor a digit.

    Length: 9
    Upper: True
    Lower: True
    Digit: True
    Symbol: True
    Strong

    For secret99 the output shows which classes are missing:

    Length: 8
    Upper: False
    Lower: True
    Digit: True
    Symbol: False
    Weak

    This is stricter than the previous version, which required only length and a digit. Each flag line is printed as True or False with a capital letter.

    Approach: four flags, one pass

    The previous version used one boolean flag and one test. This one needs four flags, one per class, all starting at false. A single loop over the characters can set all four: for each character, run four independent tests, and each test that succeeds flips its own flag.

    The tests are four separate if statements, not an if/else if chain. A character belongs to at most one of the first three classes, so a chain would look natural, but the symbol test is "not a letter and not a digit", and writing every class as its own check keeps the loop uniform and makes each rule easy to read. An else if chain would also silently skip later tests whenever an earlier one matched, which is a trap when the classes are later changed.

    Collecting the answers first and printing afterwards separates the two jobs. The loop gathers facts about the password, and the code after it reports them and decides. That split keeps the verdict condition readable: it names the flags instead of repeating character tests.

    Step by step

    1. Store length from password.length.
    2. Print the first line. The reference uses the template "Length: $length", where $length inserts the value of the variable into the text.
    3. Create hasUpper and hasLower as vars starting at false.
    4. Create hasDigit and hasSymbol the same way.
    5. Loop over the characters with for (c in password).
    6. Uppercase test. If c.isUpperCase(), set hasUpper.
    7. Lowercase test. If c.isLowerCase(), set hasLower.
    8. Digit test. If c.isDigit(), set hasDigit.
    9. Symbol test. If !c.isLetterOrDigit(), set hasSymbol. The ! flips the answer, so the test is true for anything that is neither a letter nor a digit.
    10. Print the first two flag lines after the loop, Upper then Lower.
    11. Print the last two, Digit then Symbol, keeping the order.
    12. Write the verdict. It joins five conditions with &&: the length and the four flags.
    13. Add the else that prints Weak.

    The solution in Kotlin

            val password = "Secret!99"
    
            val length = password.length
            println("Length: $length")
            var hasUpper = false
            var hasLower = false
            var hasDigit = false
            var hasSymbol = false
            for (c in password) {
                if (c.isUpperCase()) {
                    hasUpper = true
                }
                if (c.isLowerCase()) {
                    hasLower = true
                }
                if (c.isDigit()) {
                    hasDigit = true
                }
                if (!c.isLetterOrDigit()) {
                    hasSymbol = true
                }
            }
            println("Upper: " + (if (hasUpper) "True" else "False"))
            println("Lower: " + (if (hasLower) "True" else "False"))
            println("Digit: " + (if (hasDigit) "True" else "False"))
            println("Symbol: " + (if (hasSymbol) "True" else "False"))
            if (length >= 8 && hasUpper && hasLower && hasDigit && hasSymbol) {
                println("Strong")
            } else {
                println("Weak")
            }
    

    Kotlin details worth a closer look:

    • String templates. "Length: $length" and "Length: " + length give the same text. The template form is the usual Kotlin style for putting a variable inside text. For an expression rather than a plain name, use braces: "${length + 1}".
    • The Char methods. isUpperCase(), isLowerCase(), isDigit() and isLetterOrDigit() all follow Unicode, not just ASCII. A letter such as an accented e counts as a lowercase letter, and a letter from another alphabet counts as a letter. Characters that have no case, such as many non-Latin letters, are neither upper nor lower case, although isLetterOrDigit() is still true for them.
    • A space is a symbol. It is not a letter or a digit, so Secret 99 gets Symbol: True and, with 9 characters, the verdict Strong.
    • Boolean text. Kotlin's own Boolean prints as true and false, so each flag line picks "True" or "False" with an if expression. The parentheses keep the whole if/else as one operand of +.
    • && chains. All five conditions must be true. One false flag, or a length under 8, sends the program to the else.

    Complexity

    The loop makes four constant-time tests per character, so the running time is proportional to the password length. The space used is a handful of variables, regardless of the password.

    Edge cases and common mistakes

    • Using else if between the tests. A character that matches an earlier test would skip the rest. That happens to be harmless with these four classes, but it makes the code depend on the classes never overlapping.
    • Defining a symbol by a list. Listing symbols such as ! and # misses the others. "Not a letter and not a digit" covers every remaining character.
    • Forgetting the length rule. A password with all four classes but only 4 characters is still weak.
    • Mixing up the order of the output lines. They must be Upper, Lower, Digit, Symbol.

    Testing

    The 4-character password Ab1! has every class and is still too short:

    Length: 4
    Upper: True
    Lower: True
    Digit: True
    Symbol: True
    Weak

    The password Secret 99, with a space instead of the exclamation mark, prints the same lines as the starting example, with Length: 9 and Strong.

    Keep going with Kotlin1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free