Understanding Methods in Java
Methods in Java
I sometimes struggle with remembering how to properly write methods on the fly (especially with AI autocomplete turned off in my IDE), so I figured writing a blog post about it would help me properly memorize the core concepts.
Methods are one of the main building blocks of Java programming. They allow you to write reusable blocks of code that perform specific tasks, making your programs more organized and efficient. Instead of repeating the same lines of code, you can wrap them in a method and call them whenever needed.
A method typically consists of four parts: an access modifier, a return type, a method name, and optional parameters. The structure of your standard method would look something like this:
1
2
3
<access modifier> <return type> <method name>(<parameters>) {
<method body>
}
or
1
2
3
public int addNumbers(int a, int b) {
return a + b;
}
Let’s break each component down and explore how they work.
Access Modifiers: Controlling Visibility
An access modifier defines where a method can be accessed from. Java provides four different levels of access:
public
– The method is accessible from anywhere in the program.private
– The method is accessible only within the class it is defined in.protected
– The method is accessible within the same package and by subclasses.- default (no modifier) – The method is accessible only within the same package.
Example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class Example {
public void publicMethod() {
System.out.println("I am public!");
}
private void privateMethod() {
System.out.println("I am private!");
}
protected void protectedMethod() {
System.out.println("I am protected!");
}
void defaultMethod() {
System.out.println("I have default access!");
}
}
The access level you choose depends on how much you want to expose the method to other parts of your program. Public methods are used when you want a method to be accessible from anywhere, while private methods are typically helper methods used only within the class itself.
Return Type: What the Method Gives Back
The return type specifies what type of value a method will produce after it is executed. If a method doesn’t return anything, you use void
. Otherwise, you have to specify the type of data it will return (e.g., int
, String
, boolean
, etc.).
Common Return Types:
void
– The method performs an action but doesn’t return anything.int
– The method returns an integer.double
– The method returns a decimal number.boolean
– The method returns true or false.String
– The method returns a text value.- Custom objects – The method returns an instance of a user-defined class.
Example:
1
2
3
4
5
6
7
8
9
10
11
12
13
public class Calculator {
public int add(int a, int b) {
return a + b;
}
public double multiply(double x, double y) {
return x * y;
}
public boolean isEven(int number) {
return number % 2 == 0;
}
}
Each of these methods takes input parameters, processes them, and returns a result. When calling the method, you can store its return value in a variable:
1
2
3
Calculator calc = new Calculator();
int sum = calc.add(5, 10);
System.out.println("Sum: " + sum);
The above code snippet will add up 5 + 10
, store the answer in sum
, and then print it out for us.
Writing and Calling Methods
Once you’ve got the structure of a method down, it’s easy to put it all together.
Here’s a Simple Example:
1
2
3
4
5
public class Greetings {
public void sayHello() {
System.out.println("Hello, world!");
}
}
To call this method, you need to create an instance of the class:
1
2
Greetings greet = new Greetings();
greet.sayHello();
If a method is static
, you can call it without creating an instance:
1
2
3
4
5
6
7
8
public class MathUtils {
public static int square(int num) {
return num * num;
}
}
int result = MathUtils.square(4);
System.out.println(result); // Output: 16
When a method is declared as static
, it means that the method belongs to the class itself, rather than to any specific instance of the class. This allows you to call the method directly using the class name (i.e., MathUtils.square(4)
), without needing to create an object of that class.
Using static methods is beneficial because they eliminate the need for creating unnecessary objects, which improves memory efficiency and performance. They also make code cleaner and more readable, especially for utility functions that don’t rely on instance-specific data.
There are other method-related modifiers that affect how methods behave, like abstract
, final
, and synchronized
, but I’ll cover those in another post.
Conclusion
Methods are an essential part of Java that allow for code reusability and better organization. By understanding access modifiers, return types, and method calls, you can write more efficient and structured Java programs.