Java Programming Lesson-8 | Java Methods + Exception Handling + Advanced Input Parsing
Java Programming Lesson-8
In this lesson of the Java Programming series, we dive into three essential and highly practical topics: Methods, Exception Handling, and Advanced Input Parsing.
These concepts help you write cleaner, safer, and more professional Java code — whether you're preparing for interviews, building projects, or strengthening your foundations.
1. Understanding Java Methods
A method is a reusable block of code that performs a specific task.
Instead of writing the same code repeatedly, you wrap it inside a method and call it whenever needed.
✔ Why Methods Are Important?
- Reduce code duplication
- Improve readability
- Make programs modular
- Allow easy debugging and maintenance
✅ PART-1: Methods (Functions) — Core of OOP
✅ Types of Methods in OOP
| Type | Example | Notes |
|---|---|---|
| No return + No parameters | void show() | Simple action |
| Return + Parameters | int sum(int a, int b) | Most used |
| Method Overloading | Same name, different parameters | Very important |
| Static Methods | static | Call without object |
| Non-Static Methods | Needs object | OOP behavior |
✅ Good Example — Strong OOP Concept
✔ Object created → Methods used
✔ This is how OOP works ✅
✅ PART-2: Exception Handling — (try, catch, finally)
Exceptions = Errors at Runtime ⚠
We use try-catch to handle problems without crashing program ✅
✅ Example: Divide by Zero Error Handling
✅ Safe program
✅ No crash
✅ Multiple Exception Handling
✔ Most specific exception first
✔ Exception at bottom
✅ PART-3: Advanced Scanner Input Parsing
Parse = convert String → Number ✅
Useful in real apps 🔥
✔ If user enters text → program still safe ✅
✅ Example: Convert String to Double
✅ Combined Example Program (Best Practice)
✔ Prevents crashes
✔ Proper parsing
✔ Resource closed ✅
🧠 Lesson-8 Summary (Very Important)
| Topic | You Learned ✅ |
|---|---|
| Methods | Reusable code, static & non-static |
| Overloading | Same method name, different parameters |
| try-catch-finally | Safe programs |
| Parsing Input | String → Number conversions |
✅ Practice Tasks (Very Useful)
1️⃣ Create ATM Program
- deposit(), withdraw(), checkBalance() methods
- Try-catch for wrong inputs
2️⃣ Take user age as String
→ convert to integer → if invalid show error
3️⃣ Student Marks Calculator
- 3 subjects
- total marks + average
- try-catch for wrong input
✅ Let’s dive into more exercises from Lesson-8 (Methods, Exception Handling, Advanced Input Parsing) so you can master the concepts before moving to OOP.
📘 Lesson-8: Practice Exercises (Advanced)
Requirements:
- Take two numbers from user input (as String)
- Take operation choice: +, -, *, /
- Use try-catch to handle invalid numbers and division by zero
- Use methods for each operation
Goal:
- User inputs safely → operations performed → output printed
- Program never crashes even if input is wrong
Requirements:
- Input age as String
- Convert to integer using
Integer.parseInt() - If invalid input → show
"Invalid age" - If valid → check if age ≥ 18 →
"Adult"else"Minor"
Hint: Use try-catch
Requirements:
- Input marks for 3 subjects (as String)
- Convert to integer using
Integer.parseInt() - Calculate total and average
- Print result
Use methods:
int total(int a, int b, int c)- double average(int total)
- Use try-catch to handle wrong input
Requirements:
- Input password as String
Check:
- Minimum 6 characters
- Must contain a number
- Handle exceptions if input is empty or null
Requirements:
Display Menu:
- Take choice input safely using Scanner + parseInt()
- Use methods for each choice
- Handle invalid input without crashing program
- Methods → organize your code, reusable
- Exception handling → make programs safe
- Parsing input → convert String → numeric safely
- Combined skills → prepare for OOP concepts
Lesson-8 Exercise Solutions (Methods, Exception Handling, Advanced Input Parsing)
import java.util.Scanner;
public class Calculator {
static int add(int a, int b){ return a + b; }
static int sub(int a, int b){ return a - b; }
static int mul(int a, int b){ return a * b; }
static double div(int a, int b){ return a / (double)b; }
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
try{
System.out.print("Enter first number: ");
int num1 = Integer.parseInt(sc.nextLine());
System.out.print("Enter second number: ");
int num2 = Integer.parseInt(sc.nextLine());
System.out.print("Choose operation (+,-,*,/): ");
char op = sc.nextLine().charAt(0);
switch(op){
case '+': System.out.println("Result: " + add(num1,num2)); break;
case '-': System.out.println("Result: " + sub(num1,num2)); break;
case '*': System.out.println("Result: " + mul(num1,num2)); break;
case '/': System.out.println("Result: " + div(num1,num2)); break;
default: System.out.println("Invalid operation");
}
}catch(NumberFormatException e){
System.out.println("Invalid number input!");
}catch(ArithmeticException e){
System.out.println("Cannot divide by zero!");
}finally{
sc.close();
}
}
}
import java.util.Scanner;
public class AgeValidation {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.print("Enter your age: ");
try{
int age = Integer.parseInt(sc.nextLine());
if(age >= 18){
System.out.println("Adult");
} else {
System.out.println("Minor");
}
}catch(NumberFormatException e){
System.out.println("Invalid age input!");
}finally{
sc.close();
}
}
}
import java.util.Scanner;
public class StudentMarks {
static int total(int a,int b,int c){ return a+b+c; }
static double average(int total){ return total/3.0; }
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
try{
System.out.print("Enter marks of subject 1: ");
int s1 = Integer.parseInt(sc.nextLine());
System.out.print("Enter marks of subject 2: ");
int s2 = Integer.parseInt(sc.nextLine());
System.out.print("Enter marks of subject 3: ");
int s3 = Integer.parseInt(sc.nextLine());
int t = total(s1,s2,s3);
double avg = average(t);
System.out.println("Total Marks: " + t);
System.out.println("Average Marks: " + avg);
}catch(NumberFormatException e){
System.out.println("Invalid input! Please enter numbers only.");
}finally{
sc.close();
}
}
}
import java.util.Scanner;
public class PasswordValidator {
static boolean isValid(String pwd){
if(pwd.length() < 6) return false;
for(char c: pwd.toCharArray()){
if(Character.isDigit(c)) return true;
}
return false;
}
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.print("Enter password: ");
String pwd = sc.nextLine();
if(isValid(pwd)){
System.out.println("Password is valid.");
} else {
System.out.println("Password invalid! Must be 6+ chars and contain a number.");
}
sc.close();
}
}
import java.util.Scanner;
public class MenuProgram {
static void greet(){
System.out.println("Hello User!");
}
static void addNumbers(Scanner sc){
try{
System.out.print("Enter first number: ");
int a = Integer.parseInt(sc.nextLine());
System.out.print("Enter second number: ");
int b = Integer.parseInt(sc.nextLine());
System.out.println("Sum = " + (a+b));
}catch(NumberFormatException e){
System.out.println("Invalid input!");
}
}
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
boolean running = true;
while(running){
System.out.println("1. Greet User");
System.out.println("2. Add Numbers");
System.out.println("3. Exit");
System.out.print("Enter choice: ");
try{
int choice = Integer.parseInt(sc.nextLine());
switch(choice){
case 1: greet(); break;
case 2: addNumbers(sc); break;
case 3: running = false; break;
default: System.out.println("Invalid choice!");
}
}catch(NumberFormatException e){
System.out.println("Invalid input! Enter a number.");
}
}
sc.close();
System.out.println("Program Terminated.");
}
}Conclusion
In Java Lesson-8, you learned:
✔ How methods make your code modular and reusable
✔ How exception handling protects your program
✔ How advanced input parsing makes user input flexible and error-free
These concepts are essential for writing professional-level Java applications.
Master them, and you’ll be ready for more advanced topics like file handling, OOP, and multi-threading in the next lessons.
✅ Done!
I have created the Lesson-8 Exercise Solutions Guide with full working Java programs for:
- Calculator with Exception Handling
- Age Validation
- Student Marks Calculator
- Password Validator
- Advanced Menu Program
All solutions include methods, exception handling, and input parsing — perfect for practicing before moving to OOP.
Frequently Asked Questions (FAQs)
What are methods in Java?
Methods are reusable blocks of code designed to perform specific tasks. They improve code structure, reduce repetition, and increase readability in Java programs.
What is the difference between a method and a function?
In Java, all functions belong to a class; therefore, they are called methods. Java doesn't support standalone functions like some other programming languages.
What are the types of methods in Java?
Java supports user-defined methods, built-in methods, static methods, and instance methods, each serving different programming needs.
What is method overloading in Java?
Method overloading allows multiple methods to share the same name but have different parameter lists. It enhances flexibility and improves code readability.
Why are methods important in Java?
Methods break a program into smaller, manageable parts, improve code reusability, reduce duplication, and make maintenance easier.
What is exception handling in Java?
Exception handling prevents runtime errors from crashing the program. Java uses try, catch, finally, throw, and throws keywords to handle exceptions.
What is the purpose of try–catch blocks?
Try–catch blocks allow you to detect potential errors and handle them gracefully without stopping the program.
What is the finally block used for?
The finally block runs whether an exception occurs or not. It is typically used to close scanners, files, or database connections.
What is the difference between checked and unchecked exceptions?
Checked exceptions must be handled or declared, while unchecked exceptions occur at runtime and do not require mandatory handling.
What is input parsing in Java?
Input parsing converts raw user input (usually Strings) into numbers or structured values using parsing methods.
How do you parse integers or doubles from user input?
Use parsing methods such as Integer.parseInt() or Double.parseDouble() to convert textual input into numeric values.
Why does Scanner sometimes skip input?
Scanner leaves a newline character in the buffer after reading numbers. Clearing the buffer with an extra nextLine() prevents skipped input.
How do I validate user input in Java?
Use loops combined with exception handling. Ask for input repeatedly until valid data is received.
Why is exception handling important while parsing input?
Users often enter invalid data. Exception handling keeps the program running and ensures users receive helpful error messages.
How can advanced input parsing improve reliability?
Advanced parsing ensures that only valid and correctly formatted data is accepted, improving accuracy and preventing errors.

No comments
Thank You For Visit My Website.
I Will Contact As Soon As Possible.