Function also called as Methods, to perform a specific task.
To easily understand about functions, here categorizing as two parts
- Function Definition – defines the task ,
- Function Calling Statement – calls the defined method where it requires
all function definitions must be inside the class
public class testFunction {
public void add(int a, int b) { // non static method definition
int c= a+b;
System.out.println(“Sum of two integers:”+c);
}
public static void main(String args[]) {
testFunction tf=new testFunction(); // object creation
System.out.println(“Addition”);
tf.add(5,7); // method calling statement with object
}}
Output
Addition
Sum of two integers:12
Have a look to this program which explains why we used tf.add(5,7)
- tf is the object created for the class testFunction
- void add (int a, int b) is a non static method
- public static void main() is a static method
- with object reference,can access a non static method to a static method ,
- dot operator(.) used to access the members of class
Lets look into Static and Non static variables.
Static variables / Class variables:
Variables which are declared with a keyword static , is common to all the instances (objects) of the class because it is a class level variable, i.e. only a single copy of static variable is created and shared among all the instances of the class. Memory allocation for such variables only happens once when the class is loaded in the memory.
Static variable can access with class reference.
Syntax
class_name.variable_name; class_name.method_name();
Non-static variables/ Instance variables:
Non-static variable also known as instance variable while because memory is allocated whenever instance is created.
Non-static variable can access with object reference.
Syntax
obj_reference.variable_name; obj_reference.method_name();
Parameters
Actual Parameters – parameters appear in method calling statement
Formal Parameters – parameters appear in method definition
In the above program,
method name : add()
5,7 —- are actual parameters
int a, int b — are formal parameters