- Details
- Written by Nam Ha Minh
- Last Updated on 25 August 2019   |   Print Email
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:
- Specify the default value in a switch case statement
- Declare default values in a Java annotation
- 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:
Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on
Facebook and watch
his Java videos you YouTube.