0% found this document useful (0 votes)
2 views10 pages

Constants in Java

The document discusses various types of constants in Java, including final variables, compile-time constants, enum constants, string literals, and numeric literals. It categorizes constants into numeric and non-numeric types, explaining their usage with examples. The document emphasizes the importance of constants for maintainable and readable code in programming.

Uploaded by

sharmila.s
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views10 pages

Constants in Java

The document discusses various types of constants in Java, including final variables, compile-time constants, enum constants, string literals, and numeric literals. It categorizes constants into numeric and non-numeric types, explaining their usage with examples. The document emphasizes the importance of constants for maintainable and readable code in programming.

Uploaded by

sharmila.s
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 10

Types of Constants in Java

Constants play a pivotal role in programming as they allow developers to


assign meaningful names to fixed values that remain unchanged
throughout the execution of a program. In Java, a widely used object-
oriented programming language, constants are integral for creating
maintainable and readable code. This article delves into the different
types of constants in Java, providing clear examples and comprehensive
explanations.

Types of constants involve classifying them based on their nature and


usage. This categorization helps programmers better comprehend the
purpose of constants and choose the appropriate ones for specific
scenarios.

1. Final Variables:
A final variable is a variable that, once assigned a value, cannot be
changed. It's essentially a constant and is often used to represent values
that shouldn't be altered during the execution of a program. In Java, you
can declare a final variable using the final keyword.

FinalExample.java

1. public class FinalExample {


2. public static void main(String[] args) {
3. final int MAX_VALUE = 100;
4. // MAX_VALUE = 200; // This would result in a compilation error
5. System.out.println("Maximum allowed value: " + MAX_VALUE);
6. }
7. }

Output:

Maximum allowed value: 100

In the example above, MAX_VALUE is declared as a final variable, making


it immutable once assigned.

2. Compile-Time Constants:
Compile-time constants are constants that are evaluated by the compiler
during the compilation process. These constants are typically used in
situations where the value is known at compile-time and doesn't change
during runtime. The final modifier is often applied to indicate compile-time
constants.

Circle.java

1. public class Circle {


2. public static final double PI = 3.14159265359;
3. public static void main(String[] args) {
4. double radius = 5.0;
5. double area = PI * radius * radius;
6. System.out.println("Area of the circle: " + area);
7. }
8. }

Output:

Area of the circle: 78.53981633974999

In this example, PI is a compile-time constant representing the


mathematical constant pi. Since the value of pi is known and doesn't
change, it's marked as a compile-time constant.

3. Enum Constants:
Enums, short for enumerations, are a special data type used to define a
collection of constant values. Enum constants offer more structured and
type-safe alternatives to represent sets of related constants.

1. public enum DayOfWeek {


2. MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
, SUNDAY
3. }
4. public class EnumExample {
5. public static void main(String[] args) {
6. DayOfWeek today = DayOfWeek.FRIDAY;
7. System.out.println("Today is: " + today);
8. }
9. }

Output:

Today is: FRIDAY


In this code snippet, DayOfWeek is an enum that defines constants for
each day of the week. Enums enhance code readability and help prevent
invalid values.

4. String Literals:
String literals are sequences of characters enclosed in double quotes.
While not inherently considered constants, string literals are often used as
constants in Java.

1. public class Greeting {


2. public static final String MESSAGE = "Hello, World!";
3. public static void main(String[] args) {
4. System.out.println(MESSAGE);
5. }
6. }

Output:

Hello, World!

Here, the MESSAGE variable holds a string literal, effectively acting as a


constant greeting message.

5. Numeric Literals:
Numeric literals are constant values that represent numbers. They can be
integers, floating-point numbers, or scientific notation.

NumericLiterals.java

1. public class NumericLiterals {


2. public static void main(String[] args) {
3. int integerLiteral = 42;
4. double floatingPointLiteral = 3.14;
5. double scientificNotation = 5.67e2; // 567.0
6. }
7. }

In this example, integerLiteral, floatingPointLiteral, and scientificNotation


are all numeric literals that represent constant values.
Numeric Constants
Numeric constants in Java are crucial for performing various arithmetic
operations, comparisons, and other calculations in your programs. By
using integer constants, floating-point constants, and even considering
character and boolean constants as numeric values in certain contexts,
you can handle numerical data effectively and accurately in your Java
code. Numeric constants are values that represent numbers and can be
used in various mathematical operations. They can be further divided into
subcategories:

1. Integer Constants: These are whole numbers without decimal


parts. Examples include decimal integers, octal integers, and
hexadecimal integers.
2. Floating-Point Constants: These represent numbers with decimal
parts. They can be written in standard or scientific notation.
3. Character Constants as Numeric Values: Characters have
corresponding Unicode code points that can be treated as numeric
values.
4. Boolean Constants as Numeric Values: In certain contexts, true
and false can be treated as numeric values representing 1 and 0
respectively.

Non-Numeric Constants:
Non-numeric constants represent data other than numbers and have
various applications in programming:

1. String Constants: These represent sequences of characters and


are used for textual information, such as messages and labels.
2. Character Constants: These represent individual characters and
are often used in text manipulation and encoding tasks.
3. Boolean Constants: These represent truth values (true or false)
and are used in decision-making and logical operations.
4. Enum Constants (Non-Numeric): Enums are used to define sets
of related constants, which can include non-numeric values
representing different states or options.
5. Null Constant: The null constant represents the absence of a value
and is commonly used for uninitialized references.
Numeric Constants
1. Integer Constants
Integer constants represent whole numbers without fractional or decimal
parts. They can be written in different formats, such as decimal, octal, or
hexadecimal.

Decimal Integer Constants:

DecimalIntegerConstantExample.java

1. public class DecimalIntegerConstantExample {


2. public static final int AGE = 25;
3. public static void main(String[] args) {
4. System.out.println("Age: " + AGE); // Output: "Age: 25"
5. }
6. }

Output:

Age: 25

Octal Integer Constants:

OctalIntegerConstantExample.java

1. public class OctalIntegerConstantExample {


2. public static final int OCTAL_NUMBER = 012; // Octal represent
ation
3. public static void main(String[] args) {
4. System.out.println("Octal number: " + OCTAL_NUMBER); // Out
put: "Octal number: 10"
5. }
6. }

Output:

Octal number: 10

Hexadecimal Integer Constants:

HexadecimalIntegerConstantExample.java
1. public class HexadecimalIntegerConstantExample {
2. public static final int HEX_NUMBER = 0x1A; // Hexadecimal rep
resentation
3. public static void main(String[] args) {
4. System.out.println("Hexadecimal number: " + HEX_NUMBER); //
Output: "Hexadecimal number: 26"
5. }
6. }

Output:

Hexadecimal number: 26

2. Floating-Point Constants:
Floating-point constants represent numbers with fractional parts. They
include a decimal point and can be written in scientific notation as well.

1. public class FloatingPointConstantExample {


2. public static final double PI = 3.14159;
3. public static final double SCIENTIFIC_NOTATION = 2.5e3; // 250
0.0
4. public static void main(String[] args) {
5. System.out.println("Value of PI: " + PI); // Output: "Value of PI:
3.14159"
6. System.out.println("Scientific notation: " + SCIENTIFIC_NOTATI
ON); // Output: "Scientific notation: 2500.0"
7. }
8. }

Output:

Value of PI: 3.14159


Scientific notation: 2500.0

3. Character Constants as Numeric Values:


Character constants can also be interpreted as numeric values based on
their Unicode code points.

CharacterAsNumericExample.java

1. public class CharacterAsNumericExample {


2. public static final char CHAR_VALUE = 'A';
3. public static void main(String[] args) {
4. int numericValue = CHAR_VALUE; // Implicit conversion to Unic
ode code point
5. System.out.println("Numeric value of 'A': " + numericValue); //
Output: "Numeric value of 'A': 65"
6. }
7. }

Output:

Numeric value of 'A': 65

4. Boolean Constants as Numeric Values:


In Java, boolean constants true and false can be considered as numeric
values, where true is equivalent to 1 and false is equivalent to 0.

1. public class BooleanAsNumericExample {


2. public static final boolean HAS_PERMISSION = true;
3. public static final boolean NO_PERMISSION = false;
4. public static void main(String[] args) {
5. int permissionValue = HAS_PERMISSION ? 1 : 0;
6. System.out.println("Permission value: " + permissionValue); //
Output: "Permission value: 1"
7. }
8. }

Output:

Permission value: 1

Non-Numeric Constants
Non-numeric constants in Java refer to constants that are not directly
associated with numeric values. These constants are used to represent
non-numeric data, such as textual information, characters, boolean
values, and more. Let's explore some common types of non-numeric
constants and their explanations.

String Constants:
String constants are used to represent sequences of characters or textual
data. They are enclosed within double quotes and can include letters,
numbers, symbols, and spaces. String constants are often used for
displaying messages, labels, prompts, and any other form of textual
information.

StringConstantExample.java

1. public class StringConstantExample {


2. public static final String WELCOME_MESSAGE = "Welcome to ou
r application!";
3. public static void main(String[] args) {
4. System.out.println(WELCOME_MESSAGE); // Output: "Welcome
to our application!"
5. }
6. }

Output:

Welcome to our application!

2. Character Constants:
Character constants represent single characters and are enclosed within
single quotes. They are commonly used to represent individual characters,
such as letters, digits, and symbols.

CharacterConstantExample.java

1. public class CharacterConstantExample {


2. public static final char FIRST_LETTER = 'A';
3. public static void main(String[] args) {
4. char secondLetter = 'B';
5. System.out.println("First letter: " + FIRST_LETTER); // Output: "
First letter: A"
6. System.out.println("Second letter: " + secondLetter); // Output:
"Second letter: B"
7. }
8. }

Output:

First letter: A
Second letter: B
3. Boolean Constants:
Boolean constants represent the two possible truth values: true and false.
They are often used in conditional statements and logic operations to
control the flow of a program.

BooleanConstantExample.java

1. public class BooleanConstantExample {


2. public static final boolean IS_ACTIVE = true;
3. public static final boolean HAS_PERMISSION = false;
4. public static void main(String[] args) {
5. if (IS_ACTIVE) {
6. System.out.println("User is active.");
7. } else {
8. System.out.println("User is inactive.");
9. }
10. if (!HAS_PERMISSION) {
11. System.out.println("User does not have permission.");
12. }
13. }
14. }

Output:

User is active.
User does not have permission.

4. Enum Constants (Non-Numeric):


While enums can represent numeric constants, they can also represent
non-numeric constants. Enums provide a structured way to define a set of
related constants with distinct names.

Gender.java

1. public enum Gender {


2. MALE, FEMALE, OTHER
3. }

EnumConstantNonNumericExample.java

1. public class EnumConstantNonNumericExample {


2. public static void main(String[] args) {
3. Gender userGender = Gender.FEMALE;
4. System.out.println("User gender: " + userGender); // Output: "U
ser gender: FEMALE"
5. }
6. }

Output:

User gender: FEMALE

5. Null Constant:
The null constant is a special constant that represents the absence of a
value. It is often used to indicate that a reference type variable doesn't
point to any object.

1. public class NullConstantExample {


2. public static final String NO_VALUE = null;
3. public static void main(String[] args) {
4. String value = NO_VALUE;
5. if (value == null) {
6. System.out.println("No value available.");
7. }
8. }
9. }

Output:

No value available.

Next Topic Execute the Main Method M

You might also like