Core Java Beginner Crash Course β Session 4
Welcome to Session 4 of the Core Java Beginner Crash Course by Madras Academy! π
In this session, weβll explore runtime input in Java, an essential concept for building interactive applications. Youβll learn how to take user input dynamically using command-line arguments (args) and the Scanner class.
π What You Will Learn
β
Understanding the args variable in Java
β
How to use command-line arguments
β
Taking user input with the Scanner class
β
Hands-on coding examples for better understanding
π Understanding the ‘args’ Variable (Command-Line Arguments)
When executing a Java program, you can pass values directly from the command line using command-line arguments.
Example: Using Command-Line Arguments
javaCopyEditpublic class CommandLineExample {
public static void main(String[] args) {
if (args.length > 0) {
System.out.println("You entered: " + args[0]);
} else {
System.out.println("No command-line argument provided.");
}
}
}
Execution:
shCopyEditjava CommandLineExample Hello
Output:
yamlCopyEditYou entered: Hello
Here, Hello is passed as an argument while running the program.
π Using Scanner Class for User Input
The Scanner class allows users to enter input at runtime.
Example: Using Scanner for User Input
javaCopyEditimport java.util.Scanner;
public class ScannerExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = scanner.nextLine();
System.out.print("Enter your age: ");
int age = scanner.nextInt();
System.out.println("Hello, " + name + "! You are " + age + " years old.");
scanner.close();
}
}
Explanation:
scanner.nextLine()reads a full line of text.scanner.nextInt()reads an integer input..close()is used to release resources after input is taken.
Sample Output:
yamlCopyEditEnter your name: John
Enter your age: 25
Hello, John! You are 25 years old.
π Why Should You Learn Runtime Input Handling?
β Allows dynamic user interaction in Java programs
β Essential for taking input in console-based applications
β Helps in data processing and interactive application development
πΊ Watch the Full Video Tutorial Here:
β
Subscribe to Madras Academy for more Java tutorials!
π Like & Share if you found this helpful!
π¬ Comment below with your questions.
π’ Stay Connected!
π Follow for more Java tutorials and coding tips!
π #Java #CoreJava #JavaTutorial #MadrasAcademy #JavaForBeginners #JavaProgramming
