Breakdown of the Code Components

Let’s look at your example piece by piece:

A. The Class (The Blueprint)

Java

 
class Student {
    String name;  // Attribute
    int age;     // Attribute
}
  • class: The keyword used to define a new data type.

  • String name and int age: These are called Instance Variables or Fields. Every student you create will have their own version of these variables.

B. The Object Creation (The Main Method)

Java

 
Student s1 = new Student();

This single line consists of three parts:

  1. Student s1: Declares a Reference Variable. It tells Java, “I want a variable named s1 that can point to a Student object.”

  2. new: This is a powerful keyword that allocates memory on the Heap.

  3. Student(): This is the Constructor. It initializes the new object.


2. Accessing and Assigning Data

Once the object is created, you use the Dot Operator (.) to access its fields.

Java

 
s1.name = "Ali"; // Assigning "Ali" to the name field of s1
s1.age = 15;     // Assigning 15 to the age field of s1

Note for University Students: If you create a second object Student s2 = new Student();, it will have its own separate memory. Changing s1.name will not change s2.name.


3. Step-by-Step Memory Execution

For a 1000-word understanding, you must know what happens inside the RAM:

  1. Declaration: Student s1 creates a space in the Stack memory.

  2. Instantiation: new Student() creates a block of memory in the Heap memory large enough to hold a String and an int.

  3. Initialization: The dot operator links the data (“Ali”, 15) to that specific block in the Heap.

StepCodeLocationResult
1Student s1StackPointer variable s1 is created.
2new Student()HeapA physical object is born.
3s1 = ...Connections1 now stores the address of the object.

4. Why is this better than just using variables?

Imagine you have 50 students in a class.

  • Procedural way: You would need 50 variables for names (name1, name2…) and 50 for ages.

  • OOP way: You create one Student class and an Array of Objects. This makes the code organized and much easier to manage for large-scale university systems like a Registration Portal.


5. Common Mistake: NullPointerException

If you write Student s1; and then try to do s1.name = "Ali"; without using the new keyword, your program will crash. This is because s1 exists in the Stack but it is “null”—it isn’t pointing to anything in the Heap yet.


Summary Table

Keyword/SymbolMeaning
classThe template definition.
newThe command to create space in memory.
. (Dot)The “bridge” used to enter an object and access its data.
ReferenceThe variable (s1) that holds the address of the object.