Java Methods

🔹 Java Methods (Functions)

A method in Java is a block of code that performs a specific task. Methods help reuse code, improve readability, and make programs modular.


✅ 1. Syntax of a Method

modifier returnType methodName(parameters) {
// code to execute
return value; // if returnType is not void
}
  • modifier → public, private, static, etc.

  • returnType → data type returned (void if nothing is returned)

  • methodName → name of the method

  • parameters → optional input values


✅ 2. Example 1: Method without Parameters and Return Value

public class Main {
// Method definition
static void greet() {
System.out.println("Hello, welcome to Java Methods!");
}

public static void main(String[] args) {
greet(); // Method call
}
}

📌 Output:

Hello, welcome to Java Methods!

✅ 3. Example 2: Method with Parameters

public class Main {
// Method with parameters
static void greetUser(String name) {
System.out.println("Hello, " + name + "!");
}

public static void main(String[] args) {
greetUser("Alice"); // Hello, Alice!
greetUser("Bob"); // Hello, Bob!
}
}


✅ 4. Example 3: Method with Return Value

public class Main {
// Method that returns sum
static int addNumbers(int a, int b) {
return a + b;
}

public static void main(String[] args) {
int sum = addNumbers(5, 10);
System.out.println("Sum = " + sum);
}
}

📌 Output:

Sum = 15

✅ 5. Example 4: Method Overloading

Java allows multiple methods with the same name but different parameters (overloading).

public class Main {
static int add(int a, int b) {
return a + b;
}

static double add(double a, double b) {
return a + b;
}

public static void main(String[] args) {
System.out.println(add(5, 10)); // 15
System.out.println(add(5.5, 2.3)); // 7.8
}
}


✅ 6. Example 5: Calling One Method from Another

public class Main {
static void printHello() {
System.out.println("Hello!");
}

static void greet() {
printHello();
System.out.println("Welcome to Java Methods.");
}

public static void main(String[] args) {
greet();
}
}

📌 Output:

Hello!
Welcome to Java Methods.

🧠 Key Points

  • Methods improve code modularity and reusability.

  • A method can:

    • Take parameters (inputs)

    • Return a value

    • Be called from other methods

  • Use void if the method does not return anything.

  • Overloading allows methods with the same name but different parameters.

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *