Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,895 questions

51,826 answers

573 users

How to set a default value to function parameters in Java

2 Answers

0 votes
// In Java, you can't directly set default values for function parameters. 
// However, you can achieve similar functionality by using method overloading.

public class Main {
    public static void print() {
        print("Java"); // Calling the overloaded method with a default value
    }

    public static void print(String str) {
        System.out.println(str);
    }

    public static void main(String[] args) {
        print();

        print("abcd");
    }
}


/*
run:

Java
abcd

*/

 



answered Jan 28, 2025 by avibootz
0 votes
// In Java, you can't directly set default values for function parameters. 
// However, you can achieve similar functionality by using method overloading.

public class Main {
    public static int add(int... args) {
        int a = 0;
        int b = 0;
        
        if (args.length > 0) {
          a = args[0];
        }
        
        if (args.length > 1) {
          b = args[1];
        }
        
        return a + b;
    }
    
    public static int add() {
        return add(20, 30); // Calling the overloaded method with a default value
}

    public static void main(String[] args) {
        System.out.println(add(4, 6));
        
        System.out.println(add());
    }
}


/*
run:

10
50

*/

 



answered Jan 28, 2025 by avibootz

Related questions

1 answer 90 views
1 answer 93 views
1 answer 75 views
1 answer 92 views
2 answers 90 views
2 answers 90 views
1 answer 91 views
...