Why do programmers use methods in Java programs?
Think about how methods help avoid writing the same instructions many times.
Methods let you write a block of code once and use it many times, which saves effort and makes programs easier to read and maintain.
What is the output of this Java program?
public class Test { public static void greet() { System.out.println("Hello, friend!"); } public static void main(String[] args) { greet(); greet(); } }
Look at how many times the greet() method is called.
The greet() method prints the message once each time it is called. Since it is called twice, the message appears twice.
What error does this Java code produce and why?
public class Test { public static void printMessage() { System.out.println("Hi there!"); } public static void main(String[] args) { printMessage(); } }
Check punctuation carefully after each statement.
Java requires a semicolon at the end of each statement. Missing it after println causes a syntax error.
Which option shows the correct way to declare a method named calculate that returns an integer and takes no parameters?
Remember method syntax: access modifier, return type, name, parentheses, and body.
Option A correctly declares a public method returning int with empty parameters and a return statement.
Imagine you are writing a program that calculates the area of different shapes. Why is it better to use separate methods for each shape's area calculation instead of writing all code in main?
Think about how breaking code into parts helps programmers work better.
Using methods separates tasks clearly, making code easier to understand, fix, and reuse in other programs.
