I'm encountering a NullPointerException in my Java code when trying to access the attributes of an object. I've created an instance of a class and assigned values to its attributes, but I'm still getting this error. Here's a simplified version of my code:
public class Student { String name; int age; public Student(String name, int age) { this.name = name; this.age = age; } } public class Main { public static void main(String[] args) { Student student = new Student("Alice", 20); System.out.println("Name: " + student.name); System.out.println("Age: " + student.age); // Some other code here } }
Surprisingly, the NullPointerException occurs at the System.out.println() lines. I've confirmed that the student object is not null, and I've also verified that the name and age attributes have been assigned values in the constructor.
What could be causing this error, and how can I fix it? Is there something else I should be looking out for when working with object attributes? Any assistance would be greatly appreciated. Thank you!