← Java

Java · 05 / 18

Methods, parameters and results

Separate a calculation from its output.

  • Small
  • Basics
  • 15 min

Prerequisites: Loops and controlled repetition

In Java, functions inside classes are called methods. A method has a name, parameters and a return type. static means no instance of the class is required here. We check a file name. The method returns a decision rather than changing an interface itself.

Example files

01Read the signature

boolean before isPdf is the return type. String filename is the input. return ends the method with a result. Several callers can use the same rule.

Main.java · javaOpen file
import java.util.Locale;
public class Main {
  static boolean isPdf(String filename) {
    return filename != null && filename.toLowerCase(Locale.ROOT).endsWith(".pdf");
  }
  public static void main(String[] args) {
    System.out.println(isPdf("FORM.PDF"));
    System.out.println(isPdf(null));
  }
}

Run / check

java Main.java

02Handle missing inputs

filename != null protects the following method call. && does not evaluate the right side if the left is already false. Lowercasing uses Locale.ROOT so it is independent of the system language.

03See the rule’s boundary

The extension checks only the name. It does not prove that a file is a valid PDF. The real application also reads and validates document contents. A small method should explain exactly what it guarantees.

Expected result

true for FORM.PDF, false for null

Your exercise

Write a positiveCount method that accepts a number only when it is greater than 0.

Show the solution and explanation

static boolean positiveCount(int count) { return count > 0; } separates the rule from display. Check -1, 0 and 1. Only 1 returns true.

Project context and sources

The example is simplified for learning. The linked source version shows its use in the project and the checks applied there.