In Java, what we commonly call a function in other programming languages is actually called a method. A method is a block of code that performs a specific task and is defined within a class. Methods can be either static, belonging to the class itself, or instance methods, belonging to objects created from the class. They have a return type, a name, parameters, and a body containing the code to execute.
Every Java method follows a specific structure. It starts with an access modifier like public, private, or protected, which controls visibility. Next comes the optional static keyword if the method belongs to the class rather than an instance. Then we specify the return type, which can be void for no return value, or any data type like int, String, or custom objects. The method name follows camelCase convention, followed by parameters in parentheses, and finally the method body enclosed in curly braces.
Java methods can be either static or instance methods. Static methods belong to the class itself and are called using the class name, like Student dot getTotalStudents. They cannot access instance variables and are shared among all instances, making them memory efficient. Instance methods belong to specific object instances and are called using the object name. They can access instance variables and provide object-specific behavior. Each object has its own copy of instance methods.
Java methods can accept parameters as input values and return results. Parameters are defined with a type and name, and methods can have zero or multiple parameters. Each parameter is local to the method. Return types specify what kind of value the method sends back. This can be void for no return value, primitive types like int or double, or object types like String or custom classes. The return statement is used to send values back to the caller, and the returned value must match the declared return type.