Java Programming Lesson-8 | Java Methods + Exception Handling + Advanced Input Parsing
Java Programming Lesson-8
✅ 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
-
-
Use methods for validation
-
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.");
}
}✅ 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.

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