Menu
Coddy logo textTech

Methods

Part of the Object Oriented Programming section of Coddy's Java journey — lesson 5 of 87.

Methods define actions an object can perform. They have a return type, a name, and optional parameters.

Method with no parameters

public class Greeter {
    public String sayHello() {
        return "Hello!";
    }
}

Method with parameters and return type

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

Void method (no return value)

public class Printer {
    public void printMessage(String msg) {
        System.out.println(msg);
    }
}

Calling methods

Calculator calc = new Calculator();
int result = calc.add(5, 3);
System.out.println(result);  // Output: 8

The return type tells Java what kind of data the method sends back. Use void when a method performs an action but doesn't return data.

challenge icon

Challenge

Medium

Create four methods in the StringHelper class:

  • toUpperCase() — returns the text in uppercase
  • getLength() — returns the length of the text
  • contains(String word) — returns true if the text contains the word
  • repeat(int times) — returns the text repeated with spaces

Cheat sheet

Methods define actions an object can perform. They have a return type, a name, and optional parameters.

Method with no parameters:

public class Greeter {
    public String sayHello() {
        return "Hello!";
    }
}

Method with parameters and return type:

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

Void method (no return value):

public class Printer {
    public void printMessage(String msg) {
        System.out.println(msg);
    }
}

Calling methods:

Calculator calc = new Calculator();
int result = calc.add(5, 3);
System.out.println(result);  // Output: 8

The return type tells Java what kind of data the method sends back. Use void when a method performs an action but doesn't return data.

Try it yourself

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String input = scanner.nextLine();
        
        StringHelper helper = new StringHelper(input);
        
        System.out.println("Original: " + input);
        System.out.println("Uppercase: " + helper.toUpperCase());
        System.out.println("Length: " + helper.getLength());
        System.out.println("Contains 'World': " + helper.contains("World"));
        System.out.println("Repeated: " + helper.repeat(3));
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming