π Day 5 of My Automation Journey β Instance, Static Variables & Operators in Java
Source: Dev.to
Instance Variables / Static Variables
- Static Variable: Belongs to the class, not to any individual object. It is common for all objects.
- Instance Variable: Each object gets its own copy.
Example β School Marks Program
package java_module_1;
public class School_Vikas {
// Instance variables
int tam_mark;
int eng_mark;
// Static variable
static String School_Name = "Vikas School";
public static void main(String[] args) {
School_Vikas rajiv = new School_Vikas();
rajiv.tam_mark = 60;
rajiv.eng_mark = 50;
System.out.println("Rajiv's Tamil mark is " + rajiv.tam_mark);
System.out.println("Rajiv's English mark is " + rajiv.eng_mark);
// Calling static variable
System.out.println("School Name " + School_Vikas.School_Name);
// Direct access inside the same class
System.out.println(School_Name);
School_Vikas kumar = new School_Vikas();
kumar.tam_mark = 55;
kumar.eng_mark = 45;
System.out.println("Kumar's Tamil mark is " + kumar.tam_mark);
System.out.println("Kumar's English mark is " + kumar.eng_mark);
}
}
What Happens Here?
- Instance Variables: Each object (
rajiv,kumar) has its own copy oftam_markandeng_mark.- Memory (Heap):
rajivβtam_mark = 60kumarβtam_mark = 55
- Memory (Heap):
- Static Variable: Only one copy of
School_Nameexists, shared by all objects.- Stored in the class area (Method Area).
How to Access a Static Variable
School_Vikas.School_Name // From outside the class
System.out.println(School_Name); // Directly inside the same class
Important Rule for Static Variables
- Created when the class is loaded.
- Does not require object creation.
- Stored in class memory (Method Area).
Why Use Static?
Use static when a value is common to all objects, e.g.:
- School name
- Interest rate (bank example)
Introduction to Operators in Java
An operator is a special symbol used to perform operations.
Types of Operators
-
Assignment Operator
int a = 10; -
Arithmetic Operators (
+,-,*,/,%)int total = 10 + 5; -
Unary Operators
int a = 5; a++; // Post Increment ++a; // Pre Increment a--; // Post Decrement --a; // Pre Decrement -
Relational Operators β used for comparison (
==,!=, β,=). -
Conditional (Logical) Operators
&&β AND||β OR
Key Takeaways β Day 5
- A static variable is shared by all objects of the class.
- Instance variables are unique to each object.
- Understanding operators is essential for performing calculations and logical checks in Java.
Note: I used ChatGPT to help structure and refine this blog.