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
Published November 24, 2013 by

Java Data Types

Data Types: A data type or simply type is a classification identifying one of various types of data, such as whole numbers or fractional numbers.

Data Type determines:
  • the possible values for that type
  • the operations that can be done on values of that type
  • the meaning of the data
  • the way values of that type can be stored
Java is a strongly typed language because when you declare a variable, you must specify the variable’s type. Then the compiler ensures that the wrong type data is not assigned to the variable.

Java data types are mainly of two types:
  • Primitive Types
  • Reference Types
Primitive Types:
  • Primitive types are defined by the language itself. 
  • The memory location of primitive type variable contains the actual value of the variable
Reference Types:
  • Reference types are defined by classes in Java API or by classes created by the developers rather than by the language itself.
  • The memory location of reference type variable contains an address that indicates the memory location of the actual object.

Primitive Types vs. Reference Type:
Primitive Types
Reference Types
1. Primitive types are the fundamental, built in (as keyword) types
1. Reference types are constructed from primitive types either through class definition, interface definition or the use of arrays.
2. A variable of any primitive type contains a single value of the appropriate size and format.
2. A variable of a reference type holds a null reference or a reference to an instance of a class
3. Values of these types cannot be decomposed
3. A reference type can be decomposed into several values.

List of Primitive Types:
Types
Characteristics
Memory Size (byte)
Minimum Value
Maximum Value
byte
Whole numbers
1
 -128
127 
short
2
-32768
32767
int
4
-2147483648
2147483647
long
8
-9223372036854775808
9223372036854775807
float
Fractional numbers
4
1.4E-45
3.4028235E38
double
8
4.9E-324
1.7976931348623157E308
char
Any single symbol
2
'\u0000', that is 0
'\uffff' that is 65535
boolean
true/false
1



Reference Types Example:
Java classes, interfaces and arrays are reference types.
  • String
  • Date
  • And many more …
Further reading:

Read More