0

I am trying to store students' data in main class, in the student class I did the following:

public class Student {
        public static String name = "UNKNOWN";
        Student(){

        }

        Student(String name) {
            this.name = name;}

While in main I did the following:

public class Main {

    public static void main (String[] args) {
        //s1 is short for student1
        Student s1 = new Student ("Chris");
        Student s2 = new Student ("Layla");
        Student s3 = new Student ("Mark");

This issue is, whenever I print a sx.name I'd always print the last one. So for the following code:

System.out.println(s1.name);

I'd get Mark, while it should be Chris.

1
  • Just remove static keyword in name field Commented May 7, 2021 at 0:49

2 Answers 2

2

Yes, Because static fields are shared by all the objects. Please change your code as follows:

public class Student {
        public String name;
        Student(){

        }

        Student(String name) {
            this.name = name;

}

public static void main (String[] args) {
        //s1 is short for student1
        Student s1 = new Student ("Chris");
        Student s2 = new Student ("Layla");
        Student s3 = new Student ("Mark");
}

When to use static in java?

Sometimes, you want to have variables that are common to all objects. This is accomplished with the static modifier. Fields that have the static modifier in their declaration are called static fields or class variables. They are associated with the class, rather than with any object. Every instance of the class shares a class variable, which is in one fixed location in memory. Any object can change the value of a class variable, but class variables can also be manipulated without creating an instance of the class.

Sign up to request clarification or add additional context in comments.

Comments

0

The static variable name is accessed by instances, which is not recommended in Java. You can make it non-static. The IDE, such as IDEA, will give you some hint/warning about this issue, like: enter image description here

So with the help of IDEs, you can easily find some potential issues.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.