User inputs via Command Prompt using arguments of main() method of a class.

There is also a third way to take user input via using Console class. This method helps a user to take inputs via Command Prompt.

Before reading this post, would request you to visit below tutorial first to get more understanding on Console Class:

Basic Java – 17 || Runtime User Input using Console Class (Part-3).



Console Class
Console Class

Console Class Code Example

/**
 * 
 */

import java.io.Console;

/**
 * @author ashok.kumar
 *
 */
public class UserInputConsole2 {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		/* To run this code follow below steps:
		1. Copy the entire code and paste it new Word or notepad Document.
		2. Save the document with the Class name, UserInputConsole.java
		3. Open the command prompt.
		4. Locate folder which contains UserInputConsole.java file.
		5. type, javac UserInputConsole.java and press Enter.
		6. type, java UserInputConsole and press Enter.
		7. enter the values and observe the output. 
		*/
		Console con=System.console();
		
		System.out.print("Enter user name: ");
		String uName=con.readLine();
		
		System.out.print("Enter Password: ");
		char[] uPwd=con.readPassword();
		
		System.out.println("User Name: "+uName);
		
		// We cann't directly use value read by the readPassword() as it stored in encoded format.
		System.out.println("Password in encoded form: "+ uPwd);
		
		// To decode the value in Password variable use below syntax
		String password=String.valueOf(uPwd);
		System.out.println("Password in decoded form: "+ password);
		
		if(uName.equalsIgnoreCase("allinoneblogs") && password.equalsIgnoreCase("1234"))
		{
			System.out.println("\nValid UserID and Password.");
		}
		else
		{
			System.out.println("\nInvalid UserID or Password.");
		}
	}
}
Output with valid inputs:

UserName: allinoneblogs
Password: 1234

Output with Invalid inputs:

UserName: allinoneblogs
Password: 786


Related Links:

Java File Handling:

OOPs Concept:

Java Question And Answer:

Java Programs:




2471total visits,4visits today

Leave a Reply

Your email address will not be published. Required fields are marked *