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