This article helps you understand how the default keyword is used in Java with code examples.

Basically, there are 3 places you can use the default keyword in Java:

  1. Specify the default value in a switch case statement
  2. Declare default values in a Java annotation
  3. Declare default method in an interface
Let’s see some code examples that use the default keyword.

In the following method, the default keyword is used in as switch case statement to return the default value for other cases:

public static int getDaysOfMonth(int month) {
	switch (month) {
		case 2:
			return 28;
		case 4:
		case 6:
		case 9:
		case 11:
			return 30;
		default:
			return 31;
	}
}
 

In the following example, the default keyword is used to declare default value for a method in a custom annotation class:

public @interface Editable {

	boolean value() default false;

	String name() default "Untitled";
}
 

And lastly, the default keyword is used to declare a default method in an interface. For example:

public interface Animal {

	public void eat();

	public void move();

	public default void sleep() {

		// implementation goes here...

	}
}
The purpose of default method is to add new methods to an interface that will not break the existing subtypes of that interface.



See all keywords in Java.

 

Related Tutorials:

Other Recommended Tutorials:


About the Author:

is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.



Add comment