Methods & Parameters and Object

JavaJavaBeginner
Practice Now

Introduction

In this lab, we move forward to methods and objects. The task is to learn how to define a method with parameters. Object is a very important concept in OOP language, so having a good knowledge of it will be good for you.

Methods and Parameters

In some cases, you need some code that can be reused to solve some similar problems such as printing somebody's age and name. For different people, name and age are different. These two variables can be passed to a code block as parameters. There we introduce the concept of method, which would perform the task.

Example:

Write the following code in the /home/labex/project/methodTest.java file:

public class methodTest
{
    public static void main(String[] args)
    {
        // call our self-defined method
        printInfo("Mike", 18);
        // call our self-defined method
        System.out.println(fibonacci(10));
        System.out.println(fibonacciNormal(10));
    }
    // we define a class method to print personal info
    public static void printInfo(String name, int age){
        System.out.println("Hello " + name + ", your age is " + age);
    }
    // define a class method to compute fibonacci by recursion
    public static int fibonacci(int n){
        if(n<=2){
            return 1;
        }else{
            return fibonacci(n-1)+fibonacci(n-2);
        }
    }
    // define a class method to compute fibonacci by iteration loop
    public static int fibonacciNormal(int n){
        if(n<=2){
            return 1;
        }
        int n1=1,n2=1,sum=0;
        for(int i=0;i<n-2;i++){
            sum=n1+n2;
            n1=n2;
            n2=sum;
        }
        return sum;
    }
}

Output:

Run the methodTest.java file using the following commands:

javac /home/labex/project/methodTest.java
java methodTest

See the output:

Hello Mike, your age is 18
55
55

In the example above, we write a function named printInfo. You can name it whatever you want. There are two parameters and the return type is void, meaning nothing will be returned. You can determine the return type of your function as any type you need, and the number and the types of the parameters can be any. You can define your method as follows:

Example:

public/private static/final/{not necessary} RETURN_TYPE METHOD_NAME( LIST OF PARAMETERS ) {
    // STATEMENTS
}
public String getName(){}
public void setName(){}
public static void newInstance(){}
public final String msg(){}

Java provides many functions that perform the most common operations as built-in library methods, such as mathematical functions. These functions are called methods. The methods are invoked using a syntax that is similar to the print statements we have already seen:

Example:

double root = Math.sqrt(16.0);   // root = 4.0
double height = Math.sin(1.5);   // height = 0.9974949866040544

Object

There are two kinds of types in Java: primitive types and object types. Primitives, like int and boolean, begin with lower-case letters; object types begin with upper-case letters. This distinction is useful because it reminds us of some of the differences between them:

When you declare a primitive variable, you get storage space for a primitive value. When you declare an object variable, you get a space for a reference to an object. To get space for the object itself, you have to use new operator.

If you donโ€™t initialize a primitive variable, it is given a default value that depends on its type. For example, 0 for ints and false for booleans. The default value for object types is null, which indicates no object being referenced by the reference variables.

Primitive variables are well isolated in the sense that there is nothing you can do in one method that will affect a variable in another method. Object variables can be tricky to work with because they are not as well isolated. If you pass a reference to an object as an argument, the method you invoke might modify the object, in which case you will see the effect. Of course, that can be a good thing, but you have to be aware of it.

If we pass primitive variables to a method (passing parameter by value), we actually copy the values of the primitives and use the copies inside the method. All the operations inside the method work upon the copies; and, outside the method, the values of the primitive variables remain unaffected. But, if we pass non-primitive objects to a method (passing parameter by reference), we pass the reference variables to the method. All the operations will actually use and/or affect the original objects.

Example:

Write the following code in the /home/labex/project/objectTest.java file:

public class objectTest {
    public static void main(String[] args){
        // use new to create an Array object with two items
        int[] numbers = new int[2];
        // assign values to the array object
        numbers[0] = 1;
        numbers[1] = 2;
        // create primitive variables in this way
        int a = 1 , b = 2;

        // create a test object
        objectTest test = new objectTest();

        test.changeInt(a, b);
        System.out.println("Now a is " + a + ", b is " + b);

        test.changeArray(numbers);
        System.out.println("Now numbers contain:");

        for(int i : numbers){
            System.out.print(i + "\t");
        }
    }
    // define an object method, change int value
    public void changeInt(int a,int b){
        a = 2;
        b = 3;
        System.out.println("In changeInt method, a is " + a + ", b is " + b);
    }
    // define an object method, change array value
    public void changeArray(int[] number){
        for(int i = 0;i < number.length;i++){
            number[i] = number[i]+1;    // change value of array item increasing by 1
        }
        System.out.println("In changeArray method, numbers contain:");
        for(int i : number){
            System.out.print(i + "\t");
        }
        System.out.println();
    }
}

Output:

Run the objectTest.java file using the following command in the terminal:

javac /home/labex/project/objectTest.java
java objectTest

See the output:

In changeInt method, a is 2, b is 3
Now a is 1, b is 2
In changeArray method, numbers contain:
2    3
Now numbers contain:
2    3

There is one other difference between primitives and object types. You cannot add new primitives to Java (unless you get yourself on the standards committee), but you can create new object types! Weโ€™ll see how in the next chapter.

Summary

Methods are common in classes. A method is a code block that performs some special operations. Java provides many built-in classes which we can use directly. There are two ways to pass parameters to methods: by value and by reference. Their effects are different. In the next lab, we will introduce them to you. We hope that would be helpful.

Other Java Tutorials you may like