Java Methods
A method in Java is a named block of code that performs a specific task and can be called whenever that task needs to be executed. Methods help you avoid r...
What Is a Method in Java?
A method in Java is a named block of code that performs a specific task and can be called whenever that task needs to be executed. Methods help you avoid repeating the same code in multiple places, making programs shorter, easier to read, and simpler to fix. Every method belongs to a class in Java, and the language's entire execution model is built around calling methods on objects or classes.
The basic syntax of a method looks like this: returnType methodName(parameterList) { body }
For example: int add(int a, int b) { return a + b; }
The return type tells Java what kind of value the method sends back. If a method does not return anything, you write void. The method name should be a verb that clearly describes what the method does. Parameters are the inputs the method needs to do its job.
Understanding Method Signatures A method's signature consists of its name and its parameter list. The return type is not part of the signature. Java uses signatures to distinguish between methods in the same class, which is the foundation of method overloading. When you call a method, Java looks at the number and types of arguments you pass to find the right match.
Static vs Instance Methods Static methods belong to the class itself and are called using the class name: Math.sqrt(16). Instance methods belong to a specific object and are called on that object: myString.length(). Static methods cannot access instance variables directly because they do not operate on a particular object.
Passing Arguments Java always passes arguments by value. For primitive types like int or double, the method receives a copy, so changes inside the method do not affect the original variable. For objects, the method receives a copy of the reference, meaning it can change the object's fields but cannot make the original reference point to a different object.
Code Example: public class Calculator { static int multiply(int x, int y) { return x * y; } public static void main(String[] args) { System.out.println(multiply(4, 5)); // 20 } }
Interview Tip: Interviewers often ask whether Java is pass-by-value or pass-by-reference. The correct answer is always pass-by-value, even for object references. Be prepared to explain the difference between copying a primitive value and copying an object reference.