Which of the following is the correct way to declare a constant in Java?

Java MCQ: Which of the following is the correct way to declare a constant in Java?

a) const int MAX_VALUE = 100;
b) final int MAX_VALUE = 100;
c) static int MAX_VALUE = 100;
d) abstract int MAX_VALUE = 100;

Answer:

b) final int MAX_VALUE = 100;

Explanation:

In Java, the correct way to declare a constant is by using the final keyword. A final variable cannot be reassigned once it has been initialized, making it a constant. For example, final int MAX_VALUE = 100; declares a constant integer with a value of 100.

The const keyword is not used in Java, and the abstract keyword is used for abstract methods and classes, not for declaring constants. The static keyword can be used with final to create a constant that is shared across all instances of the class, but it cannot be used alone to create a constant.

Understanding how to declare constants is important for ensuring that certain values remain unchanged throughout the program, which can help prevent bugs and make the code easier to maintain.

Reference links:

https://www.rameshfadatare.com/learn-java-programming/
https://www.javaguides.net/p/java-tutorial-learn-java-programming.html

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top