OBJECT ORIENTED PROGRAMMING THROUGH JAVA : Unit - 2 : Topic - 17 : Attributes: Final and Static in Java

 

Unit - 2

Topic - 17 : Attributes: Final and Static in Java


1. Final in Java

The final modifier can be used with variables, methods, and classes.

  • Final Variables
    If a variable is declared as final, it becomes a constant.
    Once assigned, its value cannot be changed throughout the program.
    The value is usually assigned during declaration.


Example – Final Variable

class PhyTest { final int Minmarks = 35; // final variable declaration void run() { // Minmarks = 40; // ❌ This will cause a compile-time error System.out.println("The subject is cleared with minimum marks: " + Minmarks); } public static void main(String args[]) { PhyTest obj = new PhyTest(); obj.run(); } }

Output

The subject is cleared with minimum marks: 35

Note:
Since Minmarks is declared as final, attempting to modify it will result in a compile-time error.


2. Static Methods in Java

When a method is declared as static, it becomes a class method.

  • It can be called without creating an object of the class.

  • Static methods belong to the class, not to individual objects.

  • Static methods can only access static variables directly.


Example – Static Method

class Computers { public static void main(String args[]) { show(); // Calling static method without an object Computers obj = new Computers(); obj.display(); // Calling instance method using an object } static void show() { System.out.println("Components details of computer"); } void display() { System.out.println("Main components of computer: CPU, RAM, Storage"); } }

Output

Components details of computer Main components of computer: CPU, RAM, Storage

Key Points:

  • final variable → Constant, cannot be modified.

  • static method → Belongs to class, can be called without an object.

  • Static methods can access only static variables directly.

Comments

Popular posts from this blog

Career Guide - B.Tech Students

Artificial Intelligence - UNIT - 1 Topic - 1 : Introduction to AI (Artificial Intelligence)

Financial Aid for Students: Scholarships from Government, NGOs & Companies