DEV Community

Pavithraarunachalam
Pavithraarunachalam

Posted on

Method Overloading,Default Values..

Method Overloading:

  • Method Overloading in Java means defining multiple methods with the same name in a class, but with different parameter lists.

  • It allows a class to perform similar actions in different ways based on the type or number of inputs.

Example:

public class SuperMarket { static String shopName="Pavithra"; String prodname; int price; public static void main(String []args) { SuperMarket Product1=new SuperMarket(); Product1.buy(10); Product1.buy(15,100); Product1.buy(10.5); Product1.buy(10.5f); System.out.println(10); System.out.println(10.5f); System.out.println("hii"); } void buy(double dd) { System.out.println("buy one double arg"+dd); } void buy(int no) { System.out.println("buy one arg"+no); } void buy(int n01,int n02) { System.out.println("buy two args"+n01+""+n02); } } ` 
Enter fullscreen mode Exit fullscreen mode

Output:

buy one arg10 buy two args15100 buy one double arg10.5 buy one double arg10.5 10 10.5 hii 
Enter fullscreen mode Exit fullscreen mode

Default values:

In Java, default values are the values that Java automatically assigns to instance variables if you don’t give them a value.

  • For example, numbers get 0, booleans get false, and objects (like String) get null.
  • This happens only for variables declared in a class, not inside methods.

Local variables must be given a value before you use them — Java will show an error if you don’t.

Top comments (0)