Java Optional Parameters Explained [Syntax & Examples]


Written By - Bashir Alam

Advertisement

Introduction to Java optional parameters

When we design a method in a Java class, some parameters may be optional for its execution. Optional parameters are defined at the end of the parameter list, after any required parameters. If the caller provides an argument for any one of a succession of optional parameters, it must provide arguments for all preceding optional parameters. In this tutorial, we will learn about java optional parameters. You can read about java arguments and parameters from our article on java arguments and java parameters.

We will learn how we can declare optional parameters in java through various examples. We will cover different methods to implement optional parameters in java including the overloading method, optional container object, built pattern, and varargs to implement java optional parameters.  All in all, this tutorial is going to have all the details about java optional parameters.

 

Getting started with Java optional parameters

Sometimes while defining the method, we may don't know the exact number of arguments that will be provided to the function. In such cases, we use java optional parameters which take parameters as optional. In simple words, the parameters become optional, which means even if we will not provide the arguments while calling that function, the function will be executed without any error.

In the following sections, we will discuss multiple ways to implement optional parameters in java.

 

Method overloading to have Java optional parameters

When working with optional parameters, method overloading is one of the more obvious and common approaches available. The idea here is that we start with a method that only takes the required parameters. We provide an additional method that takes a single optional parameter. We then provide yet another method that takes two of these parameters, and so on. It is actually defining the existing method with more parameters. In this section, we will see the basic syntax of method overloading and will solve an example as well.

 

Syntax of method overloading to have Java optional parameters

Now, let us see the basic syntax of the Java method overloading to have optional parameters. See the syntax below:

Function1(parameter){
	// statements of function
}

Function1(parameter1, parameter2){
	// statements of function
}
Function1(parameter1, parameter2, parameter3){
	// statements of function
}

Notice that in the above program, we are redefining the same method with more parameters that will act as optional parameters.

 

Example of method overloading to have optional parameters

Now we already have knowledge of the basic syntax of method overloading and know how it actually works. Let us now, take an example and practically implement the same idea of creating java optional parameters using the method overloading method. See the example below:

Advertisement
// java main class
public class Main{
	// java main method
	public static void main(String arg[]){
		// calling the function with required parameters
		System.out.println("With two arguments: "+Sum(10, 5));
		// calling the function with the java optional parameters
		System.out.println("With three arguments: "+Sum(10, 5,5));
		System.out.println("With four arguments: "+Sum(10, 5,5,5));
	}
	// function with requred parameters
	public static Integer Sum(Integer num1, Integer num2){
		// return the sum of the numbers
		return num1+num2;
	}
	// java overiding method to create optional parameters
	public static Integer Sum(Integer num1, Integer num2, Integer num3){
		// return the sum
		return num1+num2+num3;
	}
	// java overiding method to create optional parameters
	public static Integer Sum(Integer num1, Integer num2, Integer num3, Integer num4){
		// return the sum
		return num1+num2+num3+num4;
	}
}

Output:

With two arguments: 15
With three arguments: 20
With four arguments: 25

Notice that in the example above, we were able to call the same function with two, three, and four arguments which means the third and fourth parameters of the function were optional. Even without providing the third and fourth arguments, we were able to run execute the program without any error.

 

Optional container object to have Java optional parameters

In Java, optional is a container object that may or may not contain a non-null value. If a value is present, then the isPresent() method will return true, and the get() method will return the value. In case if we expect some null values, we can use the ofNullable() method of this class. It returns an empty Optional object and does not throw an exception. In this section, we will look at the basic syntax of creating an optional container object and will solve an example as well.

 

Syntax of Optional container object to have Java optional parameters

Now let us learn how we can create an optional container object in java. See the simple syntax below:

Sum(paramter1, parameter2){
	Optional<Datatype> ln = Optional.ofNullable(parameter2);
	// function statements
}

The program above is the simplest form of creating an optional parameter. We created a new optional object and then provide the second parameter as an optional parameter.

 

Example of optional container object to have java optional parameters

Now let us take an example and create an optional container object to have java optional parameters. Before writing the code, we have to import the Optional class as we will be using it in our program. See the example below:

// importing optional class
import java.util.Optional;
// java main class
public class Main{
		// java main method
 		public static void main(String args[]){
			// calling function with all arguments
			System.out.println("Calling the function with all parameters!!");
        	Info("Bashir","Alam",22);
			// calling function without optional parameters
			System.out.println("Calling the function without the optional parameter!!");
			Info("Bashir",null , 22);
    }
	// user defined method of type Info
    private static void Info(String fname, String lName, int age){
		// creating optional object
		// and making our argument lastname as optional
        Optional<String> lname = Optional.ofNullable(lName);
		// checking if the optional parameter is provided or not
        String optionalParameter = lname.isPresent() ? lname.get() : "Last name not given!";
		// printing out the information
        System.out.println("First Name : "+fname + "\nLast Name : "+optionalParameter +"\nThe age : "+age);
    }
}

Output:

Calling the function with all parameters!!
First Name : Bashir
Last Name : Alam
The age : 22
Calling the function without the optional parameter!!
First Name : Bashir
Last Name : Last name not given!
The age : 22

Notice that in the second case, when we did not provide the optional parameter and just call the function with a null value, then the code in the optional container was executed and we get output saying the last name is not given.

 

Built Pattern to have Java optional parameters

This design pattern provides a very interesting way to create a complex object. The main purpose is to separate the construction of an object from its representation! The builder pattern is yet another approach to handle Java optional parameters! It is a good alternative to consider in order to construct objects with optional parameters. Let solve an example and see how the pattern building works in java to create optional parameters.

 

Example of Pattern building to have Java optional parameters

Let us now take a practical example of creating patterns to have optional java parameters. First, we will create a public static nested class inside our Main class. StudentBuilder is our builder class. Then we will define all the fields of the outer class of the StudentBuilder. After that, we will create a public constructor for the StudentBuilder with all the required properties as arguments. Finally, we will also create methods in StudentBuilder class for setting optional parameters. See the example below.

public class Main {
	// Required parameters
	private String fname;
    private String lname;
    // Optional properties
	private String email; 
    private String address; 
    private String phone;
	// constructor
	private Main() {
	}
	// creating studentBuilder class
	public static class StudentBuilder {
		// instance variables 
		private String firstname;
		private String lastname;
		private String email;
		private String address;
		private String phone;
		// constuctor of StudentBuilder class
		public StudentBuilder(String firstname,String lastname){ 
			this.firstname = firstname;
			this.lastname  = lastname;
		}
		// constructor for email
		public StudentBuilder withEmail(String email) {
			this.email = email;
			return this;
		}
		// constructor for email
		public StudentBuilder withAddress(String address) {
			this.address = address;
			return this;
		}
		// constuctor for phone number
		public StudentBuilder withPhone(String phone) {
			this.phone = phone;
			return this;
		}
		public Main build() {
			// creating new object
			Main student = new Main();
			student.fname = this.firstname;
			student.lname = this.lastname;
			student.email = this.email;
			student.address = this.address;
			student.phone  = this.phone;
			// return the student object
			return student;
		}
	}
	// java main method
	public static void main(String[] args) { 
		// First Student object, with all parameters including optional parameters
		Main student1 = new  Main.StudentBuilder("Bashir","Alam")
									.withEmail("bashiralam@gmail.com")
									.withAddress("University of central asia")
									.withPhone("123-456786")
									.build();
		// Second Student object with required parameters!
		Main student2 = new  Main.StudentBuilder("Bashir","Alam")
									.build();
	}
}

When we run the above program, it will run without giving any error. Notice that in the first Object typed StudentBuilder, we passed all the parameters including the optional, and in the second StudentBuilder typed object, we just passed the first two arguments. Still, the code runs without giving any error that means we successfully created optional parameters using the pattern building method in java.

 

Varargs to have Java optional parameters

In Java, varargs (variable-length arguments) allow the method to accept zero or multiple arguments. The use of this particular approach is not recommended as it creates maintenance problems. variable-length arguments could be handled two ways. One using an overloaded method(one for each) and another is to put the arguments into an array, and then pass this array to the method. Both of them are potentially error-prone and require more code. In this section, we will have a look at the simple syntax and will solve an example as well using the java varargs method.

 

Syntax of Varargs to have Java optional parameters

The syntax of varargs to have optional parameters in java is very simple. Three dots are used to declare varargs in Java programming language. The simple syntax looks like this.

public static void FunctionName(int ... a) {
   // method statements
} 

This syntax tells the compiler that FunctionName() can be called with zero or more arguments. As a result, here a is implicitly declared as an array of type int[].

 

Example of varargs to have Java optional parameters

Now we are already familiar with varargs to have optional parameters. Let us take an example and see how it actually works. See the java program below:

// Java main class
public class Main{
	// java main method
    public static void main (String args[]){
		// calling the Varargs function without any arguments
        Varargs.display();
		// calling the Varargs function with arguments
        Varargs.display("welcome", "to", "golinuxcloud");
    }
}
// user defined class
class Varargs {
	// display method
     static void display(String... args) {
		//  storing the arguments in array
        String array[] = args;
		// printing the arguments
        System.out.println("The number of arguments provided were:  "+array.length);
    }
}

Output:

The number of arguments provided were: 0
The number of arguments provided were: 3

Notice that the program runs without giving any error. In the first call, we provided no arguments and we get the result as zero and in the second call, we provided three arguments and get result 3.

 

Summary

Sometimes while writing a java program and creating user-defined functions, we might be not sure about the number of arguments that will be provided by the user. In such cases, we can use java optional parameters so that it will not raise any issue if the user provides more arguments than the required ones. In this tutorial, we learned about Java optional parameters.

We covered different methods through which we can implement java optional parameters. We covered Method overloading, optional object, pattern building, and Varargs along with various examples to get optional parameters. All in all, this tutorial covers all the basic and popular ways to create java optional parameters.

 

Further Reading

Java optional parameters
Java parameters
Java arguments

 

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

Leave a Comment