class

Final arguments to function

In this example we shall show you how to use final arguments to a function. To use final arguments to a function we have performed the following steps:

  • We have created class FinalArgs, that has run() method and a myFunc(final Calendar d) method.
  • The first method calls the second one, that uses a final Calendar argument and changes the Calendar.YEAR field.
  • We create a new instance of FinalArgs and call its run() method. The myFunc(final Calendar d) method is called and the attibute YEAR of final Calendar is changed.
  • If we try to change the calendar though an error will occur, since it is final and cannot be assigned to another value,

as described in the code snippet below.

package com.javacodegeeks.snippets.core;

import java.util.Calendar;

/**
 * Experiment with "final" args to functions (new in 1.1)
 */

public class FinalArgs {

    public static void main(String argv[]) {

  new FinalArgs().run();
    }

    void run() {

  System.out.println("Hummm...");

  myFunc(Calendar.getInstance());

  System.out.println("Once upon a time...");
    }

    void myFunc(final Calendar d) {

  // d = null;  // this will not compile

  d.set(Calendar.YEAR, 1999); // this will compile, and changes the object
    }
}

Output:

Hummm...
Once upon a time...

  
This was an example of how to use final arguments to a function in Java.

Byron Kiourtzoglou

Byron is a master software engineer working in the IT and Telecom domains. He is an applications developer in a wide variety of applications/services. He is currently acting as the team leader and technical architect for a proprietary service creation and integration platform for both the IT and Telecom industries in addition to a in-house big data real-time analytics solution. He is always fascinated by SOA, middleware services and mobile development. Byron is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button