Checking letter case (Upper/Lower) within a string in Java

check if character in string is lowercase java
how to check if a character is uppercase or lowercase in java
how to find uppercase letters in a string in java
how to check string contains special characters in java
how to find uppercase and lowercase in java
java program change a string such that first character is upper case second is lower case and so on
how to check special characters in java using regex
java check if string contains letters and numbers

The problem that I am having is that I can't get my Password Verification Program to check a string to ensure that, 1 of the characters is in upper case and one is in lower case, it will check the whole string for one of the other and print the error message based on which statement it is checking.

I have looked over this site and the internet for an answer and I am unable to find one. This is homework.

Below is my current code.

import java.util.Scanner;

public class password
{
    public static void main(String[] args)
    {
        Scanner stdIn = new Scanner(System.in);
        String password;
        String cont = "y";
        char ch;
        boolean upper = false;
        boolean lower = false;

        System.out.println("Setting up your password is easy. To view requirements enter Help.");
        System.out.print("Enter password or help: ");
        password = stdIn.next();
        ch = password.charAt(0);

        while (cont.equalsIgnoreCase("y"))
        {
            while (password.isEmpty())
            {
                System.out.print("Enter password or help: ");
                password = stdIn.next();       
            }

            if (password.equalsIgnoreCase("help"))
            {
                 System.out.println("Password must meet these requirements." +
                     "\nMust contain 8 characters.\nMust contain 1 lower case letter." +
                     "\nMust contain 1 upper case letter.\nMust contain 1 numeric digit." +
                     "\nMust contain 1 special character !@#$%^&*\nDoes not contain the word AND or NOT.");

                password = "";
            }
            else if (password.length() < 8)
            {
                System.out.println("Invalid password - Must contain 8 charaters.");
                password = "";
            }
            else if (!(Character.isLowerCase(ch)))
            {
                for (int i=1; i<password.length(); i++)
                {
                    ch = password.charAt(i);

                    if (!Character.isLowerCase(ch))
                    {  
                        System.out.println("Invalid password - Must have a Lower Case character.");
                        password = "";
                    }
                }
            }
            else if (!(Character.isUpperCase(ch)))
            {
                for (int i=0; i<password.length(); i++)
                {       
                    ch = password.charAt(i);

                    if (!Character.isUpperCase(ch))
                    {
                        System.out.println("Invalid password - Must have an Upper Case character.");
                        password = "";
                    }
                }
            }
            else
            {
                System.out.println("Your password is " + password);

                System.out.print("Would you like to change your password? Y/N: ");
                cont = stdIn.next();
                password = "";
            }

            while (!cont.equalsIgnoreCase("y") && !cont.equalsIgnoreCase("n"))
            {
                System.out.print("Invalid Answer. Please enter Y or N: ");
                cont = stdIn.next();
            }
        }
    }
}

To determine if a String contains an upper case and a lower case char, you can use the following:

boolean hasUppercase = !password.equals(password.toLowerCase());
boolean hasLowercase = !password.equals(password.toUpperCase());

This allows you to check:

if(!hasUppercase)System.out.println("Must have an uppercase Character");
if(!hasLowercase)System.out.println("Must have a lowercase Character");

Essentially, this works by checking if the String is equal to its entirely lowercase, or uppercase equivalent. If this is not true, then there must be at least one character that is uppercase or lowercase.

As for your other conditions, these can be satisfied in a similar way:

boolean isAtLeast8   = password.length() >= 8;//Checks for at least 8 characters
boolean hasSpecial   = !password.matches("[A-Za-z0-9 ]*");//Checks at least one char is not alpha numeric
boolean noConditions = !(password.contains("AND") || password.contains("NOT"));//Check that it doesn't contain AND or NOT

With suitable error messages as above.

Java Check a String for Lowercase/Uppercase Letter, Special , None of the chars are lower case. If your objective is to test a string to ensure it contains ONLY upper case chars then: Upper case characters are actually between  Stack Overflow for Teams is a private, secure spot for you and your coworkers to find and share information. Checking letter case (Upper/Lower) within a string in

A loop like this one:

else if (!(Character.isLowerCase(ch)))
            {
                for (int i=1; i<password.length(); i++)
                {
                   ch = password.charAt(i);

                    if (!Character.isLowerCase(ch))
                       {  
                        System.out.println("Invalid password - Must have a Lower Case character.");
                        password = "";
                       }
                     // end if
                } //end for
            }

Has an obvious logical flaw: You enter it if the first character is not lowercase, then test if the second character is not lower case. At that point you throw an error.

Instead, you should do something like this (not full code, just an example):

boolean hasLower = false, hasUpper = false, hasNumber = false, hasSpecial = false; // etc - all the rules
for ( ii = 0; ii < password.length(); ii++ ) {
  ch = password.charAt(ii);
  // check each rule in turn, with code like this:
  if Character.isLowerCase(ch) hasLower = true;
  if Character.isUpperCase(ch) hasUpper = true;
  // ... etc for all the tests you want to do
}

if(hasLower && hasUpper && ...) {
  // password is good
} 
else {
  // password is bad
}

Of course the code snippet you provided, besides the faulty logic, did not have code to test for the other conditions that your "help" option printed out. As was pointed out in one of the other answers, you could consider using regular expressions to help you speed up the process of finding each of these things. For example,

hasNumber  : use regex pattern "\d+" for "find at least one digit"
hasSpecial : use regex pattern "[!@#$%^&*]+" for "find at least one of these characters"

In code:

hasNumber  = password.matches(".*\\d.*");  // "a digit with anything before or after"
hasSpecial = password.matches(".*[!@#$%^&*].*");
hasNoNOT   = !password.matches(".*NOT.*");
hasNoAND   = !password.matches(".*AND.*");

It is possible to combine these things in clever ways - but especially when you are a novice regex user, it is much better to be a little bit "slow and tedious", and get code that works first time (plus you will be able to figure out what you did six months from now).

A method to detect if string contains only uppercase letter in Java, 1) Check if the string is uppercase using a char array and the Character class. We can first //if any character is in lower case, return false. Basic idea is that we iterate through our String and check if its characters are of required types. By using Character class, we can easily check if a certain character is a digit, an uppercase or a lowercase character.

Although this code is likely beyond the understanding of a novice, it can be done in one line using a regex with positive and negative look-aheads:

boolean ok = 
    password.matches("^(?=.*[A-Z])(?=.*[!@#$%^&*])(?=.*\\d)(?!.*(AND|NOT)).*[a-z].*");

Check if String is uppercase in Java example, lowercase in Java? 1) Check if string is lowercase using a char array and the Character class //if any character is in upper case, return false. String is in lower case 3) Using the Apache Commons library If you are using the Apache Commons library, you can use the isAllLowerCase method of the StringUtils class to check if the string is lowercase as given below.

This is quite old and @SinkingPoint already gave a great answer above. Now, with functional idioms available in Java 8 we could give it one more twist. You would have two lambdas:

Function<String, Boolean> hasLowerCase = s -> s.chars().filter(c -> Character.isLowerCase(c)).count() > 0;
Function<String, Boolean> hasUpperCase = s -> s.chars().filter(c -> Character.isUpperCase(c)).count() > 0;

Then in code we could check password rules like this:

if (!hasUppercase.apply(password)) System.out.println("Must have an uppercase Character");
if (!hasLowercase.apply(password)) System.out.println("Must have a lowercase Character");

As to the other checks:

Function<String,Boolean> isAtLeast8 = s -> s.length() >= 8; //Checks for at least 8 characters
Function<String,Boolean> hasSpecial   = s -> !s.matches("[A-Za-z0-9 ]*");//Checks at least one char is not alpha numeric
Function<String,Boolean> noConditions = s -> !(s.contains("AND") || s.contains("NOT"));//Check that it doesn't contain AND or NOT

In some cases, it is arguable, whether creating the lambda adds value in terms of communicating intent, but the good thing about lambdas is that they are functional.

Check if String is lowercase in Java example, Java.lang.Character.isUpperCase() Method - The java.lang.Character.​isUpperCase(char ch) determines if the specified character is an uppercase character. public static void main(String[] args) { // create 2 char primitives ch1, ch2 char ch1, check if ch1, ch2 are uppercase and assign results to b1, b2 b1 = Character. In order to find number of uppercase letters in a string of all capital letters in a string we need to iterate all characters of a string in a loop and check individual characters are uppercase letters or not using Character class provided isUpperCase () method. Program #1: Java example program to find all capital letters / Uppercase letters in

I have streamlined the answer of @Quirliom above into functions that can be used:

private static boolean hasLength(CharSequence data) {
    if (String.valueOf(data).length() >= 8) return true;
    else return false;
}

private static boolean hasSymbol(CharSequence data) {
    String password = String.valueOf(data);
    boolean hasSpecial = !password.matches("[A-Za-z0-9 ]*");
    return hasSpecial;
}

private static boolean hasUpperCase(CharSequence data) {
    String password = String.valueOf(data);
    boolean hasUppercase = !password.equals(password.toLowerCase());
    return hasUppercase;
}

private static boolean hasLowerCase(CharSequence data) {
    String password = String.valueOf(data);
    boolean hasLowercase = !password.equals(password.toUpperCase());
    return hasLowercase;
}

Java.lang.Character.isUpperCase() Method, This method determines whether the specified char value is uppercase. public class Test { public static void main(String args[]) { System.out.println(Character. char character = characters.charAt (i); // checking for each character that its a Upper-case or Lower-case. // letter or not by calling Character class isUpperCase () method, // and isLowerCase () by passing the character. It returns true. // if the character passed is lower-case or upper-case and false. // if not separately.

Java - isUpperCase() Method, Another way to check if a letter is in uppercase form is by comparing static void main(String[] args) { char a = 'A'; // Checks to see if a letter is a  Java Character API comes with many methods to check the case of a letter – lowercase or uppercase. After checking, the character can be converted from lowercase to uppercase or uppercase to lowercase as per the need of the logic. Following is the method signature as defined in java.lang.Character class.

How do I know if a character is uppercase?, Check whether the given character is in upper case, lower case or non Java implementation of the above approach public static void main(String []args). Consider the program: It will take number of inputs, string and print total number of uppercase and lowercase letters. import java . util . Scanner ; public class CountUpperAndLowerCaseLetters { public static void main ( String [ ] args ) { //Scanner is a class used to get the output from the user Scanner Kb = new Scanner ( System . in ) ; System . out . println ( "How man strings u want to check?"

Check whether the given character is in upper case, lower case or , The second print statement displayed false because the contains() method is case sensitive. You can also use the contains() method for case insensitive check​,  Use Character.isDigit to check the if a char is a digit: 7. Validate if a String contains only numbers: 8. Check if a character representing a number: 9. Check if a character representing an alphabet: 10. If a character is uppercase: 11. if a character is lowercase: 12. Is character a digit, letter, white space, lower case or upper case

Comments
  • I imagine you want to apply all of these restrictions to the passwords, and else if isn't the construct for that.
  • Small edit: password.length() >= 8 since length = 8 should be enough. This is becoming my favorite answer.
  • Fixed :) Thanks for the spot.
  • And thank you for yours. Since I feel this should become the accepted answer there ought to be no bugs in it. Not sure that your special character test is correct... it will let a password with, among others, any of ~()-_=+ through but those weren't in the list of "special" characters.
  • Thanks again to both of you. Really helped get me on the right track. I'm enjoying programming but thought I was going to lose my mind there for a second. (Still really new only my 5th week programming and they started with Java at my school.)
  • Hope you stick with it. Good luck in the future :D
  • Thank you very much for your quick response. This makes total sense. Got down the wrong path, been staring at it for an hour thinking on how I could change it.
  • Although this is far lengthy-er then it needs to be, and only checks the first 8 characters of the password.
  • @Quirliom - the requirement is that the password is eight characters long, according to the "help" text. Not 9, not 10. It says "\nMust contain 8 characters." Maybe I took that too literally. I will update accordingly.
  • The password length was my own error in working out the program, left out "At Least" easy enough change to password.length to check all characters within the string.
  • Also a quick point, your check for a number will complaint about an invalid escape character, you need to escape the \ :)
  • "Does not contain NOT or AND, has one of these special characters !@#$%^&*, contains a number. Are all those conditions tested for? I don't consider myself a novice, but I don't see it.
  • @Floris The question asks for assertion that the string contains at least 1 upper and at least 1 lower care letter. That's precisely what my code does. I notice now thar the code (only) requires a number and a special character. Answer edited to cater for that.