Optional parameters might not be a big deal in many programming languages like Python, but that is not the case in Java. Java does not provide direct support for optional parameters in its methods. When a method is called in Java, you must supply only the variables defined during the declaration.
Table of Contents
In this article, we will be exploring different approaches to using Java optional parameters in your code. We will also discuss the highlight and trade-offs of each approach over another.
When a method is written in Java code, all the required parameters are listed. In certain situations, the developer may not know the exact number of arguments that will be provided to this function at the time of declaring it.
In such a case, Java optional parameter allow additional parameters that were initially not defined. In simple words, those parameters are optional, which means whether you provide those additional arguments or not while calling the function, the function will be executed in both of the cases without any error.
Following are some prominent approaches used to implement optional parameters in Java:
Method overloading is a very common feature in Java. It is also one of the most common approaches for implementing Java optional parameter. It works so that you start with a simple method that only takes the required parameters. After that, you can provide additional methods of the same name with optional parameters. It is just like defining the existing method again with more parameters.
See this basic syntax of the method overloading to implement the Java optional parameter:
originalFunction(parameter1){ // statements of function } originalFunction(parameter1, parameter2){ // statements of function } originalFunction(parameter1, parameter2, parameter3){ // statements of function }
We are just redefining the same method with more parameters, as discussed before. These parameters will act as the optional parameters whenever the method is called with two or three parameters.
The below demonstration of a java code practically implements this approach by creating java optional parameter:
01. // first function with 2 parameters 02. public static int Sum(int number1, int number2){ 03. int result = number1 + number2 04. Return result; 05. } 06. // overiding this method to create optional parameters 07. public static int Sum(int number1, int number2, int number3){ 08. int result = number1 + number2 + number3 09. return result; 10. } 11. // overiding this method once again for additional optional parameter 12. public static int Sum(int number1, int number2, int number3, int number4){ 13. Integer result = number1 + number2 + number3 + number 4 14. return result; 15. } 16. } 17. public class Main{ 18. public static void main(String arg[]){ 19. System.out.println("adding two numbers with original method: "+Sum(3, 6)); 20. // calling the methods with the java optional parameter 21. System.out.println("adding three numbers using optional parameters: "+Sum(3, 3,3)); 22. System.out.println("adding four numbers using optional parameters: "+Sum(5, 4,2,3)); 23. }
Output:
adding two numbers with original method: 9 adding three numbers using optional parameters: 9 adding four numbers using optional parameters: 14
optional container objects are those objects that might contain a null value. If a value is not null, then the isPresent() method will return true, and the get() method can be used to return that value. In case if the object contains some null values, the ofNullable() method can be used. It will return an empty Optional object and will not throw any exception.
The following code snippet is the basic syntax of creating an optional container object in Java:
Sum(paramter01, parameter02, parameter03){ Optional<Datatype> obj = Optional.ofNullable(parameter3); // function statements }
The code snippet above shows a simple way of creating Java optional parameter with an optional object. A new optional object is created that provides parameter3 as an optional parameter.
Now let’s implement this approach into a Java code. It is to be noted that you require to import the Optional class to use the optional objects:
01. import java.util.Optional; // required to import the optional class for creating optional objects 02. private static void StudentDetails(String fullName, int age, String drivingID){ 03. Optional<String> dID = Optional.ofNullable(drivingID); 04. // checking if the optional parameter is required or not 05. String optionalParameter = dID.isPresent() ? dID.get() : "The User does not have a Driving ID"; 06. // output the information 07. System.out.println("Name: "+fullName + "nAge: "+ age + "nDriving ID: " + optionalParameter); 08. } 09. } 10. public class Main{ 11. public static void main(String args[]){ 12. System.out.println("Calling the method with the optional parameters."); 13. Info("Shaharyar Lalani", 24, "D-123213"); 14. System.out.println("Calling the method with only the required parameters."); 15. Info("Shaharyar Lalani", 24, null); 16. }
Calling the method with the optional parameters. Name: Shaharyar Lalani Age: 24 Driving ID: D-123213 Calling the method with only the required parameters. Name: shaharyar Lalani Age: 24 Driving ID: The user does not have a Driving ID
Notice that the optional parameter is not provided in the second case, and the method has just been called with a null value. The code in the optional container is then executed, and the message showing “user does not have a Driving ID” will be shown.
Design patterns in Java also provide a very interesting approach to creating optional objects. It is a good alternative to construct objects with Java optional parameter. A practical implementation of creating patterns to create Java optional parameters is shown below.
We define the main class with a private constructor and then introduce a static nested class to function as a builder. myBuilder is our builder class. The builder class exposes methods for setting parameters and for building the instances. After that, a public constructor for the myBuilder is created with all the required data as parameters. Lastly, we will create methods in myBuilder class to set up optional Java parameters.
See this code demonstration below:
01. public class Main { 02. private String firstName; 03. private String lastName; 04. 05. // Following will be the Optional parameters 06. private int age; 07. private String drivingID; 08. 09. private Main() {} // constructor 10. // creating the myBuilder class 11. public static class myBuilder { 12. 13. private String firstName; 14. private String lastName; 15. private int age; 16. private String drivingID; 17. 18. // constuctor of myBuilder class 19. public myBuilder(String firstName, String lastName) 20. { 21. this.firstName = firstName; 22. this.lastName = lastName; 23. } 24. // constructor for age 25. public myBuilder withage(int age) { 26. this.age = age; 27. return this; 28. } 29. // constructor for drivingID 30. public StudentBuilder withdrivingID(String drivingID) { 31. this.drivingID = drivingID; 32. return this; 33. } 34. 35. public Main build() { 36. // creating new objects 37. Main myData = new Main(); 38. myData.fname = this.firstName; 39. myData.lname = this.lastName; 40. myData.age = this.age; 41. myData.drivingID = this.drivingID; 42. 43. return user01; 44. } 45. } 46. public static void main(String[] args) { 47. // First object has all the parameters including optional parameters 48. Main obj1 = new Main.myBuilder("Shaharyar","Lalani").withage(24).withdrivingID("D-123312").build(); 49. // Second object only has required parameters 50. Main obj2 = new Main.myBuilder("Shaharyar","Lalani").build(); 51. } 52. }
Varargs or variable-length arguments allow the Java methods to accept none or multiple arguments in a method. This approach is not recommended as it can lead to various maintenance issues in your code.
See Also: Types Of Exceptions In Java
You can use varargs in two possible ways. One is through the particular overloaded methods for every varargs, and another one is by using an array of varargs, which is then passed to the method. Both of these approaches work but are very error-prone and require complex code for implementation.
The syntax of varargs is demonstrated below. Three dots are used to declare varargs in Java:
public static void MethodName(int ... x) { // method statements }
The example below shows how to have optional parameters in java using varargs:
01. class Varargs { 02. static void mydata(String... args) { 03. // storing the arguments in an array 04. String myArr [] = args; 05. // printing the number of arguments 06. System.out.println("The number of arguments (optional parameters): "+array.length); 07. } 08. } 09. public class Main{ 10. public static void main (String args[]){ 11. Varargs.display(); 12. Varargs.display("hello", "world"); 13. } 14. }
The number of arguments provided were: 0 The number of arguments provided were: 2
We have covered all the commonly used approaches to implement Java optional parameters and various examples. It is very much likely that when writing a user-defined method, you might not be certain about the number of parameters to be provided with a method. In that cases, Java optional parameter come to the rescue as it smoothly allows users to provide Java optional parameter to a method.
Create a free profile and find your next great opportunity.
Sign up and find a perfect match for your team.
Xperti vets skilled professionals with its unique talent-matching process.
Connect and engage with technology enthusiasts.
© Xperti.io All Rights Reserved
Privacy
Terms of use