The Java Scanner class is used to get input from user. It provides several methods to get input of different types and to validate the input as well. Here we will see some of these methods that can be used to get user input and do the input validation in java.
| Method | Description |
|---|---|
| boolean hasNext(String pattern) | It returns true if the next token matches the pattern constructed from the specified string. |
| boolean hasNext(Pattern pattern) | It returns true if the next complete token matches the specified pattern. |
| boolean hasNextBigDecimal() | It returns true if the next token in this scanner's input can be interpreted as a BigDecimal using the nextBigDecimal() method. |
| boolean hasNextBigInteger() | It returns true if the next token in this scanner's input can be interpreted as a BigInteger in the default radix using the nextBigInteger() method. |
| boolean hasNextBigInteger(int radix) | It returns true if the next token in this scanner's input can be interpreted as a BigInteger in the specified radix using the nextBigInteger() method. |
| boolean hasNextBoolean() | It returns true if the next token in this scanner's input can be interpreted as a boolean value using a case insensitive pattern created from the string "true|false". |
| boolean hasNextByte() | It returns true if the next token in this scanner's input can be interpreted as a byte value in the default radix using the nextByte() method. |
| boolean hasNextByte(int radix) | It returns true if the next token in this scanner's input can be interpreted as a byte value in the specified radix using the nextByte() method. |
| boolean hasNextDouble() | It returns true if the next token in this scanner's input can be interpreted as a double value using the nextDouble() method. |
| boolean hasNextFloat() | It returns true if the next token in this scanner's input can be interpreted as a float value using the nextFloat() method. |
| boolean hasNextInt() | It returns true if the next token in this scanner's input can be interpreted as an int value in the default radix using the nextInt() method. |
| boolean hasNextInt(int radix) | It returns true if the next token in this scanner's input can be interpreted as an int value in the specified radix using the nextInt() method. |
| boolean hasNextLine() | It returns true if there is another line in the input of this scanner. |
| boolean hasNextLong() | It returns true if the next token in this scanner's input can be interpreted as a long value in the default radix using the nextLong() method. |
| boolean hasNextLong(int radix) | It returns true if the next token in this scanner's input can be interpreted as a long value in the specified radix using the nextLong() method. |
| boolean hasNextShort() | It returns true if the next token in this scanner's input can be interpreted as a short value in the default radix using the nextShort() method. |
| boolean hasNextShort(int radix) | It returns true if the next token in this scanner's input can be interpreted as a short value in the specified radix using the nextShort() method. |
| Method | Description |
|---|---|
| String next(String pattern) | It returns the next token if it matches the pattern constructed from the specified string. |
| String next(Pattern pattern) | It returns the next token if it matches the specified pattern. |
| BigDecimal nextBigDecimal() | It scans the next token of the input as a BigDecimal. |
| BigInteger nextBigInteger() | It scans the next token of the input as a BigInteger. |
| BigInteger nextBigInteger(int radix) | It scans the next token of the input as a BigInteger. |
| boolean nextBoolean() | It scans the next token of the input into a boolean value and returns that value. |
| byte nextByte() | It scans the next token of the input as a byte. |
| byte nextByte(int radix) | It scans the next token of the input as a byte. |
| double nextDouble() | It scans the next token of the input as a double. |
| float nextFloat() | It scans the next token of the input as a float. |
| int nextInt() | It scans the next token of the input as an int. |
| int nextInt(int radix) | It scans the next token of the input as an int. |
| String nextLine() | it advances this scanner past the current line and returns the input that was skipped. |
| long nextLong() | It scans the next token of the input as a long. |
| long nextLong(int radix) | It scans the next token of the input as a long. |
| short nextShort() | It scans the next token of the input as a short. |
| short nextShort(int radix) | It scans the next token of the input as a short. |
We can do different type of input validation using different hasNextXXX() methods.
We can use hasNextInt() method to check whether the input is integer and then get that using nextInt() method. See the example below.
import java.util.Scanner;
public class Main
{
public static void main(String args[])
{
int input = 0;
System.out.println("Enter an Integer value ");
Scanner sc = new Scanner(System.in);
if(sc.hasNextInt()) {
input = sc.nextInt();
if(input>0)
System.out.println("You entered a positive integer "+input);
else {
System.out.println("You entered a negative integer "+input);
}
}else {
System.out.println("Please Enter Valid Integer");
}
}
}
Output
To validate floating-point values, we used hasNextDouble() method that returns true if the input is floating type and nextDouble() method is used to get the user input.
import java.util.Scanner;
public class Main
{
static Double input;
public static void main(String args[])
{
System.out.println("Enter a floating point value ");
Scanner sc = new Scanner(System.in);
if(sc.hasNextDouble()) {
input = sc.nextDouble();
if(input>0)
System.out.println("You entered a positive value "+input);
else {
System.out.println("You entered a negative value "+input);
}
}else {
System.out.println("Please Enter a Valid Value");
}
}
}
Output:
We can use hasNextBoolean() method to check whether the input is a valid boolean or not and nextBoolean() method is used to get the input value.
import java.util.Scanner;
public class Main
{
static Boolean input;
public static void main(String args[])
{
System.out.println("Enter a boolean value ");
Scanner sc = new Scanner(System.in);
if(sc.hasNextBoolean()) {
input = sc.nextBoolean();
System.out.println("You entered a boolean value "+input);
}else {
System.out.println("Please Enter a Valid Value");
}
}
}
Output
To validate a string value, we can use regex to get string in a specific format. Here, the hasNext() takes a regex to validate a string that can contain only alphabets. See the example below.
import java.util.Scanner;
public class Main
{
static String input;
public static void main(String args[])
{
System.out.println("Enter a String ");
Scanner sc = new Scanner(System.in);
if(sc.hasNext("[A-Za-z]*")) {
input = sc.next();
System.out.println("You entered a string value "+input);
}else {
System.out.println("Please Enter a Valid Value");
}
}
}
Output
That’s all about Input validation in java using Scanner.
]]>@#$%Here is standard regex for validating password.
^(?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%]).{8,20}$
Here is explanation for above regex
^ asserts position at start of a line(?=.*\\d).* matches any character (except for line terminators)\\ matches the character \ literally (case sensitive)d matches the character d literally (case sensitive)(?=.*[a-z]).* matches any character (except for line terminators)[a-z]a-z a single character in the range between a (index 97) and z (index 122) (case sensitive)(?=.*[A-Z]).* matches any character (except for line terminators)[A-Z]A-Z a single character in the range between A (index 65) and Z (index 90) (case sensitive)(?=.*[@#$%]).* matches any character (except for line terminators)[@#$%]@#$% matches a single character in the list @#$% (case sensitive).{8,20} matches any character (except for line terminators){8,20} Quantifier — Matches between 8 and 20 times, as many times as possible, giving back as needed (greedy)$ asserts position at the end of a line
Here is java program to implement it.
package org.arpit.java2blog;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexCurrencySymbol {
public static void main(String args[]) {
String password1 = "Java2blog@";
String regex = "^(?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%]).{8,20}$";
boolean validPassword = isValidPassword(password1,regex);
System.out.println("Java2blog@ is valid password:" +validPassword);
String password2 = "helloword#123";
String regex1 = "^(?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%]).{8,20}$";
boolean validPassword1 = isValidPassword(password2,regex1);
// No upper case
System.out.println("helloword#123 is valid password:" +validPassword1);
}
public static boolean isValidPassword(String password,String regex)
{
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(password);
return matcher.matches();
}
}
Output:
We can also use string’s matches() method to validate password in java.
Let’s see with the help of an example.
package org.arpit.java2blog;
public class PasswordValidatorMain {
public static void main(String args[]) {
String password1 = "Java2blog@";
boolean validPassword = isValidPassword(password1);
System.out.println("Java2blog@ is valid password:" +validPassword);
String password2 = "helloword#123";
boolean validPassword1 = isValidPassword(password2);
// No upper case
System.out.println("helloword#123 is valid password:" +validPassword1);
}
/**
* Method to check if password is valid or not.
* @param password
* @return boolean
*/
public static boolean isValidPassword(String password)
{
boolean isValid = true;
if (password.length() > 15 || password.length() < 8)
{
System.out.println("Password must be less than 20 and more than 8 characters in length.");
isValid = false;
}
String upperCaseChars = "(.*[A-Z].*)";
if (!password.matches(upperCaseChars ))
{
System.out.println("Password must have atleast one uppercase character");
isValid = false;
}
String lowerCaseChars = "(.*[a-z].*)";
if (!password.matches(lowerCaseChars ))
{
System.out.println("Password must have atleast one lowercase character");
isValid = false;
}
String numbers = "(.*[0-9].*)";
if (!password.matches(numbers ))
{
System.out.println("Password must have atleast one number");
isValid = false;
}
String specialChars = "(.*[@,#,$,%].*$)";
if (!password.matches(specialChars ))
{
System.out.println("Password must have atleast one special character among @#$%");
isValid = false;
}
return isValid;
}
}
Output:
That’s all about how to validate password in java.
]]>You can use below regex to find currency symbols in any text.
Each unicharacter belongs to certain category and you can search for it using /p. Sc is short code for current symbol, so using \p{Sc}, we are trying to find currency symbol in a text.
package org.arpit.java2blog;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexCurrencySymbol {
public static void main(String args[]) {
String text = "Currency symobols are : $ Dollar, ₹ Rupees ";
String regex = "\\p{Sc}";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
System.out.print("Start index: " + matcher.start());
System.out.print(" End index: " + matcher.end() + " ");
System.out.println(" : " + matcher.group());
}
}
}
Output:
That’s all about regex for currency symbols in java.
]]>Luhn algorithm, also known as modulus 10 or mod 10 algorithm, is a simple checksum process for validating various identification numbers such as credit card numbers, Canadian social securities numbers.
This algorithm is designed to protect again mistyped or accidental error rather than malicious attacks. Most credit card companies adopted this algorithm as this was available in the public domain and can be used by anyone.
Here are the steps involved in Luhn Algorithms.
Step 1:
From the rightmost digit, we should double every second digit.

Step 2:
When we double the digits and get product in double digits, then we should add digits of the product.

Step 3:
Compute the sum of all the digits.

Step 4:
If total sum is divisible by 10 i.e. total sum modulo 10 is 0, then number is valid else it is not valid.

As 90 mod 10 is 0, hence this is valid credit card number.
Let’s create java program to implement the Luhn algorithm.
package org.arpit.java2blog;
import java.util.Arrays;
public class LuhnAlgorithmMain {
public static void main(String[] args) {
String cardNumber="1358954993914435";
boolean validCreditCardNumber = isValidCreditCardNumber(cardNumber);
if(validCreditCardNumber)
{
System.out.println(cardNumber+" is valid as per luhn algorithm");
}
else
{
System.out.println(cardNumber+" is not valid as per luhn algorithm");
}
}
public static boolean isValidCreditCardNumber(String cardNumber)
{
// int array for processing the cardNumber
int[] cardIntArray=new int[cardNumber.length()];
for(int i=0;i=0;i=i-2)
{
int num = cardIntArray[i];
num = num * 2; // step 1
if(num>9)
{
num = num%10 + num/10; // step 2
}
cardIntArray[i]=num;
}
int sum = sumDigits(cardIntArray); // step 3
System.out.println(sum);
if(sum%10==0) // step 4
{
return true;
}
return false;
}
public static int sumDigits(int[] arr)
{
return Arrays.stream(arr).sum();
}
}
Output:
Here are the steps involved in above java program for luhn algorithm.
cardNumber to int array cardIntArray for processingcardIntArray from rightmost side starting from cardIntArray.length-2 with step of i=i-2cardIntArray[i]cardIntArraysum%10 is 0 then credit card number is valid else not valid as per luhn algorithmIn case, you don’t want to implement luhn algorithm you can use Apache common validation library and validate credit card number using LuhnCheckDigit.LUHN_CHECK_DIGIT.isValid(creditCardNumber);
You need to add following dependency to pom.xml.
<!-- https://mvnrepository.com/artifact/commons-validator/commons-validator --> <dependency> <groupId>commons-validator</groupId> <artifactId>commons-validator</artifactId> <version>1.6</version> </dependency>
Let’s see with the help of example:
package org.arpit.java2blog;
import org.apache.commons.validator.routines.checkdigit.LuhnCheckDigit;
public class LuhnAlgorithmApache {
public static void main(String[] args) {
String cardNumber="79927398713";
boolean validCreditCardNumber = isValidCreditCardNumberLuhn(cardNumber);
if(validCreditCardNumber)
{
System.out.println(cardNumber+" is valid as per luhn algorithm");
}
else
{
System.out.println(cardNumber+" is not valid as per luhn algorithm");
}
}
public static boolean isValidCreditCardNumberLuhn(String creditCardNumber)
{
return LuhnCheckDigit.LUHN_CHECK_DIGIT.isValid(creditCardNumber);
}
}
Output:
That’s all about Luhn Algorithm in java
]]>Objects’s isNull() method is used to check if object is null or not. java.util.Objects class was introduced in java 7.
Here is simple example for Object's isNull method.
package org.arpit.java2blog;
import java.util.Objects;
public class ObjectsIsNullMain {
public static void main(String[] args) {
String str1="Java2blog";
String str2=null;
System.out.println("Is str1 null: "+Objects.isNull(str1));
System.out.println("Is str2 null: "+Objects.isNull(str2));
}
}
Output:
Let’s look at source code Object’s isNull() method.
/**
* Returns {@code true} if the provided reference is {@code null} otherwise
* returns {@code false}.
*
* @apiNote This method exists to be used as a
* {@link java.util.function.Predicate}, {@code filter(Objects::isNull)}
*
* @param obj a reference to be checked against {@code null}
* @return {@code true} if the provided reference is {@code null} otherwise
* {@code false}
*
* @see java.util.function.Predicate
* @since 1.8
*/
public static boolean isNull(Object obj) {
return obj == null;
}
As you can see, it just checks if obj is null or not.
In case, you are checking if boolean variable is null or not. You can make typo as below.
Boolean boolVar=true;
if(boolVar = null) // typo
{
}
You can use isNull() method to avoid this kind of typos.
Boolean boolVar=true;
if(Objects.isNull(boolVar)) // typo
{
}
Object’s isNull() method can be used with Java 8 lambda expressions.
It is cleaner and easier to write.
.stream().filter(Objects::isNull)
than to write:
.stream().filter(a -> a == null).
That’s all about isNull method in java.
]]>E.123 is a standards-based recommendation by the International Telecommunications Union sector ITU-T.
E.123 provides following specifications.
Java program to check phone number
package org.arpit.java2blog;
// Java program to check phone
// is valid as per E123
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ValidatePhoneNumberMain {
public static boolean isValidE123(String s)
{
Pattern p = Pattern.compile("^\\+(?:[0-9] ?){6,14}[0-9]$");
Matcher m = p.matcher(s);
return (m.find() && m.group().equals(s));
}
public static void main(String[] args)
{
String phone1 = "+91 3423 546443";
String phone2 = "+44 343 2324";
String phone3 = "91 4354 3454";
String[] phoneNumbers= {phone1,phone2,phone3};
for (int i = 0; i < phoneNumbers.length; i++) {
String phoneNumber=phoneNumbers[i];
if (isValidE123(phoneNumber))
System.out.print(phoneNumber+" is valid phone number");
else
System.out.print(phoneNumber+" is invalid Phone number");
System.out.println();
}
}
}
Output
Valid indian mobile numbers are:
I would recommend to go to site https://regex101.com/. Put the regex in regular expression. It will show you clear explanation of regex.
Here is java program for the validate indian mobile number
package org.arpit.java2blog;
// Java program to check phone
// is valid as per E123
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ValidatePhoneNumberMain {
public static boolean isValidIndianMobileNumber(String s)
{
Pattern p = Pattern.compile("^(?:(?:\\+|0{0,2})91(\\s*[\\-]\\s*)?|[0]?)?[789]\\d{9}$");
Matcher m = p.matcher(s);
return (m.find() && m.group().equals(s));
}
public static void main(String[] args)
{
String phone1 = "+91-7123456789";
String phone2 = "08123456789";
String phone3 = "9876543210";
String[] phoneNumbers= {phone1,phone2,phone3};
for (int i = 0; i < phoneNumbers.length; i++) {
String phoneNumber=phoneNumbers[i];
if (isValidIndianMobileNumber(phoneNumber))
System.out.print(phoneNumber+" is valid mobile number");
else
System.out.print(phoneNumber+" is invalid mobile number");
System.out.println();
}
}
}
Output
That’s all about validate phone number in java.
]]>There are times when you have to validate email address provided by user. You might want to write your own logic to validate email addresses but there are lots of standard regular expressions or libraries which can help you validate email address and provide great results.
Email address is made up of local part, @ and followed by domains. You can go through wiki page for format of email address.
We can use regular expression provided by OWASP Validation Regex Repository which is considered to be safe and will solve the purpose in most of the cases.
Here is the regular expression
Here is complete java program for email address validation in java
package org.arpit.java2blog;
import java.util.regex.Pattern;
public class EmailValidatorMain
{
public static boolean isValid(String email)
{
String emailRegex = "^[a-zA-Z0-9_+&*-]+(?:\\.[a-zA-Z0-9_+&*-]+)*@" + //part before @
"(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,7}$";
Pattern pat = Pattern.compile(emailRegex);
if (email == null)
return false;
return pat.matcher(email).matches();
}
/* driver function to check */
public static void main(String[] args)
{
String email1 = "[email protected]";
String email2 = "@java2blog.com";
String email3 = "[email protected]";
String[] emails= {email1,email2,email3};
for (int i = 0; i < emails.length; i++) {
String email=emails[i];
if (isValid(email))
System.out.print(email+" is valid email");
else
System.out.print(email+" is invalid email");
System.out.println();
}
}
}
When you run above program, you will get below output
You can also use inbuilt apache librabry to validate the address. If you are using maven, then you need to add below dependency in your pom.xml.
<!-- https://mvnrepository.com/artifact/commons-validator/commons-validator -->
<dependency>
<groupId>commons-validator</groupId>
<artifactId>commons-validator</artifactId>
<version>1.4.0</version>
</dependency>
Here is java program for the same.
package org.arpit.java2blog;
import org.apache.commons.validator.routines.EmailValidator;
public class EmailValidatorMain
{
public static boolean isValid(String email)
{
// Get an EmailValidator instance first
EmailValidator validator = EmailValidator.getInstance();
// check valid email address
if (!validator.isValid(email)) {
return false;
}
return true;
}
/* driver function to check */
public static void main(String[] args)
{
String email1 = "[email protected]";
String email2 = "@java2blog.com";
String email3 = "[email protected]";
String[] emails= {email1,email2,email3};
for (int i = 0; i < emails.length; i++) {
String email=emails[i];
if (isValid(email))
System.out.print(email+" is valid email");
else
System.out.print(email+" is invalid email");
System.out.println();
}
}
}
When you run above program, you will get below output
That’s all about validate email address in java.
]]>a-z, A-Zor 0-9.Here is the explaination of above regex.
^ : start of string[ : beginning of character groupa-z : any lowercase letterA-Z : any uppercase letter_ : underscore]: end of character group* : zero or more of the given characters$ : end of string
If you do not want to allow empty string, you can use + instead of *.
Java program to test regex alphanumeric characters.
package org.arpit.java2blog;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexExample {
public static void main(String args[])
{
List<String> listOfUserNames=new ArrayList<>();
listOfUserNames.add("Java2blog");
listOfUserNames.add("Java-2-blog");
listOfUserNames.add("Java2blog Tutorials");
listOfUserNames.add("Java2blogTutorials");
listOfUserNames.add("");
String regex = "^[a-zA-Z0-9]*$";
Pattern pattern = Pattern.compile(regex);
for (String name : listOfUserNames)
{
Matcher matcher = pattern.matcher(name);
System.out.println("Only Alphanumeric in "+name+" : "+ matcher.matches());
}
}
}
Output
That’s all about Java Regex – alphanumeric characters
]]>