OBJECT ORIENTED PROGRAMMING THROUGH JAVA : Unit - 1 : Literal constants and Symbolic constants

What is a Constant?

A constant is a value that does not change during the execution of a program. It remains fixed.

Java supports two main types of constants:

1. Literal Constants

2. Symbolic Constants

1. Literal Constants

Definition:

Literal constants are the actual fixed values directly used in Java code. They are also called literals.

Key Point:

They are raw values written directly in the program and used without a name.

Types of Literal Constants:

Type
Description
Example
Integer Literal
Whole numbers without decimal. Can be in decimal, octal, or hexadecimal.
10, -99, 0x1A, 075
Floating Literal
Numbers with decimal or exponent.
3.14, 1.2e3, -0.5
Character Literal
Single character enclosed in single quotes.
'A', '9', '#'
String Literal
Group of characters enclosed in double quotes.
"Java", "123", " "
Boolean Literal
Logical constants for decision-making.
true, false
Null Literal
Special literal that represents "no object".
null

Examples of Literal Constants:

    int a = 10; // 10 is an integer literal
    double pi = 3.14; // 3.14 is a floating literal char ch = 'A'; // 'A' is a character literal String str = "Hello"; // "Hello" is a string literal boolean flag = true; // true is a boolean literal

2. Symbolic Constants

Definition:

A symbolic constant is a named constant declared using the final keyword, which makes the value unchangeable after assignment.

Key Point:

It gives a name (symbol) to a value that doesn’t change – increasing readability and reusability.

🔸 Declaration Syntax:


final datatype CONSTANT_NAME = value;

🔸 Example:


final double PI = 3.14159; final int MAX_AGE = 100;

🔸 Usage in Program:


public class CircleArea { public static void main(String[] args) { final double PI = 3.14159; int radius = 7; double area = PI * radius * radius; System.out.println("Area = " + area); } }

🔸 Difference Between Literal and Symbolic Constants

FeatureLiteral ConstantSymbolic Constant
What it isFixed value written directlyFixed value assigned to a named variable
Keyword usedNonefinal
ReadabilityLower in complex codeHigher due to meaningful names
ReusabilityNot reusableReusable throughout the code
Best Use CaseFor single-use valuesFor values used multiple times
Example3.14, "Hello"final double PI = 3.14;

Naming Convention for Symbolic Constants

                Use all uppercase letters.
     Use underscores to separate words.

✅ Examples:

final int MAX_MARKS = 100;

final double GRAVITY = 9.8;


✅ Advantages of Symbolic Constants

✔ Improved readability of code.
✔ Avoids magic numbers (hard-coded values).
✔ Easier to update values in one place.
✔ Prevents accidental changes (value can't be modified).

Comments

Popular posts from this blog

How to Get a Job in Top IT MNCs (TCS, Infosys, Wipro, Google, etc.) – Step-by-Step Guide for B.Tech Final Year Students

Common HR Interview Questions

How to Get an Internship in a MNC