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

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

✅ 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.");
    }
}

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:

  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.


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.

Theme images by 5ugarless. Powered by Blogger.