DMCA.com Protection Status Java Programming Lesson-8 | Java Methods + Exception Handling + Advanced Input Parsing - ZAREEN TECH WAVE -Largest Tutorials Website For Freelancer ZAREEN TECH WAVE -Largest Tutorials Website For Freelancer

Header Ads

Java Programming Lesson-8 | Java Methods + Exception Handling + Advanced Input Parsing

Java Programming Lesson-8


📘 LESSON-8: Java Methods + Exception Handling + Advanced Input Parsing

✅ PART-1: Methods (Functions) — Core of OOP

✅ Method Syntax
returnType methodName(parameters) { // statements return value; // optional }

✅ Types of Methods in OOP

TypeExampleNotes
No return + No parametersvoid show()Simple action
Return + Parametersint sum(int a, int b)Most used
Method OverloadingSame name, different parametersVery important
Static MethodsstaticCall without object
Non-Static MethodsNeeds objectOOP behavior

✅ Good Example — Strong OOP Concept

public class Calculator { int add(int a, int b){ return a + b; } int sub(int a, int b){ return a - b; } public static void main(String[] args){ Calculator c = new Calculator(); System.out.println(c.add(5, 3)); System.out.println(c.sub(10, 4)); } }

✔ 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 ✅

✅ Syntax
try { // risky code } catch(Exception e) { System.out.println("Error: " + e.getMessage()); } finally { System.out.println("Always runs!"); }

✅ Example: Divide by Zero Error Handling

try { int a = 10/0; } catch(ArithmeticException e) { System.out.println("Cannot divide by zero!"); }

✅ Safe program
✅ No crash


✅ Multiple Exception Handling

try { int[] arr = new int[3]; System.out.println(arr[5]); } catch(ArrayIndexOutOfBoundsException e){ System.out.println("Index Error!"); } catch(Exception e){ System.out.println("Other Error!"); }

✔ Most specific exception first
Exception at bottom


✅ PART-3: Advanced Scanner Input Parsing

Parse = convert String → Number ✅
Useful in real apps 🔥

✅ Example: String → Integer
Scanner sc = new Scanner(System.in); System.out.print("Enter a number: "); String numStr = sc.nextLine(); try { int number = Integer.parseInt(numStr); System.out.println("You entered: " + number); } catch(NumberFormatException e){ System.out.println("Invalid Number!"); }

✔ If user enters text → program still safe ✅


✅ Example: Convert String to Double

String price = "99.99"; double value = Double.parseDouble(price); System.out.println(value);

✅ Combined Example Program (Best Practice)

import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); try { System.out.print("Enter age: "); int age = Integer.parseInt(sc.nextLine()); System.out.print("Enter score: "); double score = Double.parseDouble(sc.nextLine()); System.out.println("Age: " + age + ", Score: " + score); } catch(Exception e) { System.out.println("Invalid Input!"); } finally { sc.close(); System.out.println("Scanner Closed."); } } }

✔ Prevents crashes
✔ Proper parsing
✔ Resource closed ✅


🧠 Lesson-8 Summary (Very Important)

TopicYou Learned ✅
MethodsReusable code, static & non-static
OverloadingSame method name, different parameters
try-catch-finallySafe programs
Parsing InputString → 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)


Exercise 1 — Calculator with Exception Handling

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

// Example Method Structure 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; }

Goal:

  • User inputs safely → operations performed → output printed

  • Program never crashes even if input is wrong


Exercise 2 — Age Validation

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


Exercise 3 — Student Marks Calculator

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


Exercise 4 — Password Validator

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


Exercise 5 — Advanced Menu Program

Requirements:

  • Display Menu:

1. Greet User 2. Add Numbers 3. Exit
  • Take choice input safely using Scanner + parseInt()

  • Use methods for each choice

  • Handle invalid input without crashing program


🔹 Key Learning Outcomes from Exercises
  1. Methods → organize your code, reusable

  2. Exception handling → make programs safe

  3. Parsing input → convert String → numeric safely

  4. Combined skills → prepare for OOP concepts


💡 Pro Tip:
Try modifying each program to use static and non-static methods, then create objects to call them. This is a bridge to OOP.


Lesson-8 Exercise Solutions (Methods, Exception Handling, Advanced Input Parsing)


Exercise 1: Calculator with Exception Handling
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();
        }
    }
}

Exercise 2: Age Validation
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();
        }
    }
}

Exercise 3: Student Marks Calculator
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();
        }
    }
}

Exercise 4: Password Validator
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();
    }
}

Exercise 5: Advanced Menu Program
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:

  1. Calculator with Exception Handling

  2. Age Validation

  3. Student Marks Calculator

  4. Password Validator

  5. 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.

Theme images by 5ugarless. Powered by Blogger.