December 23, 2020

Published December 23, 2020 by

Find Maximum and Minimum Date in Java

Here is an example of determining maximum and minimum between two dates and among more than two dates.

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Collections;

public class MaxMinDate {

    public static void main(String[] args) {

        // First let's create two date objects
        LocalDate date1 = LocalDate.of(2020, 3, 12);
        LocalDate date2 = LocalDate.of(2020, 7, 15);

        // To determine the maximum or minimum date we can use method isAfter or isBefore method
        if (date1.isAfter(date2)) {
            System.out.println("Maximum Date : " + date1);
            System.out.println("Minimum Date : " + date2);
        } else {
            System.out.println("Maximum Date : " + date2);
            System.out.println("Minimum Date : " + date1);
        }

        // Now let's see how we can find the maximum and minimum date among more than two dates.
        // Let's create more date objects
        LocalDate date3 = LocalDate.of(2020, 1, 13);
        LocalDate date4 = LocalDate.of(2020, 3, 20);
        LocalDate date5 = LocalDate.of(2020, 7, 5);

        // Add all the date objects in an array list so that we can use utility methods of Collections class
        ArrayList<LocalDate> dateList = new ArrayList<>();
        dateList.add(date1);
        dateList.add(date2);
        dateList.add(date3);
        dateList.add(date4);
        dateList.add(date5);

        LocalDate maxDate = Collections.max(dateList);
        LocalDate minDate = Collections.min(dateList);

        System.out.println("The maximum date is " + maxDate);
        System.out.println("The minimum date is " + minDate);
    }

}
Read More

November 27, 2013

Published November 27, 2013 by

Read password (hidden) from Console


Generally all the texts given as input in a Java console application are visible. When we read a password from a Java console application, it will not be wise to display the input password. If we want to hide the password, we can use the readPassword method java.io.Console class to read password. This class is available since version 1.6.

Console class is used to access the character-based console device, if any, associated with the current Java virtual machine. If this virtual machine has a console then it is represented by a unique instance of this class which can be obtained by invoking the System.console() method. If no console device is available then an invocation of that method will return null.

An example below:
import java.io.Console;

public class ConsolePassword {

    public static void main(String[] args) {
        String username;
        char[] password;

        Console console = System.console();

        if (console != null) {
            System.out.print("Username: ");
            username = console.readLine();

            System.out.print("Password: ");
            password = console.readPassword();

            if (username.equalsIgnoreCase("admin")) {
                if (String.valueOf(password).equals("myPassword")) {
                    System.out.println("Username and password are correct");
                } else {
                    System.err.println("Wrong password");
                }
            } else {
                System.err.println("Wrong username");
            }

        } else {
            System.err.println("No console device is available");
        }
    }

}
You should press the “Enter” key when the password input is finished. The input password will not be shown and it will not show any progress as well.

Output of this code:



Read More

November 24, 2013

Published November 24, 2013 by

Java Variables

Variable is the named location of memory. Variable is used to store data, that’s why this is called the unit of storage. A value of a variable can be modified during the course of program execution. In Java, you must explicitly declare all variables before using them.

Variable declaration includes:
  1. Data type
  2. Variable name
  3. Initial value (optional)
  4. A ; (semi colon) at the end of declaration statement.

Syntax for declaring variables:

DateType variableName = value;
Example:
String name = “Shamsuddin”;
Here “String” is the data type, “name” is the variable name and “Shamsuddin” is the initial value.
double radius = 15.69;
Here “double” is the data type, “radius” is the variable name and “15.69” is the initial value.

Rules for naming a variable (identifier):
  • Only a limited number of characters can be used for naming a variable. The characters are upper or lowercase letters (a-z or A-Z), numerals (0-9), underscore (_), and dollar sign ($)
  • Variables name cannot start with digit (0-9)
  • A variable name cannot be same as a Java keyword.

Conventions for naming a variable:
  • Variable name should be meaningful
  • Should be in mixed case with the first letter lowercase, and then with the first letter of each internal word capitalized
  • Variable names should not start with underscore (_) or dollar sign ($) characters, even though both are allowed.
  • One-character variable names should be avoided except for temporary "throwaway" variables. Common names for temporary variables are i, j, k, m, and n for integers; c, d, and e for characters.

Examples:

Invalid Variable Name
Reason
Valid Variable Name
average  income
Contains whitespace
averageIncome
1stNumber
Starts with digit
firstNumber or number1
for
for is a java keyword
formula
sl.number
Contains dot (.)
slNumber

Common Errors while using variables:


Further reading:


Read More