-3

In the code below, I've added two lines that print output. The first line prints junk as usual, but surprisingly the second one gives me a compilation error. Why?

class Student {

  private String name;

  public Student(String name){
         this.name = name;
  }
  public String getName(){
         return name;
  }
}

class StudentServer {

   public StudentServer(){

          Student[] s = new Student[30];
          s[0] = new Student("Nick");

          // LINE 01: This compiles, although prints junk
          System.out.println(s[0]); 

          // LINE 02: I get a error called cannot find symbol
          System.out.println(s[0].getName());
   }

  public static void main(){
         new StudentServer();
  }
}
double-beep
  • 5,031
  • 17
  • 33
  • 41
Haxed
  • 2,887
  • 14
  • 47
  • 73

2 Answers2

2

try this:

public static void main(String[] args)
Axel
  • 13,939
  • 5
  • 50
  • 79
2

The issue with main method not being a proper application entry point aside, this code should compile and run just fine. The problem seems to lie elsewhere, and there's not enough information at the moment to identify the source.

Related questions


On toString()

The reason why printing s[0] "prints junk as usual" is because you didn't @Override the toString() method inherited from Object.

If you had just added this method:

@Override public String toString() {
   return "Student : " + name;
}

then printing s[0] wouldn't print "junk"; it would print whatever the above toString() returns (which in this case, is something reasonably "not junk").

Related questions

Community
  • 1
  • 1
polygenelubricants
  • 376,812
  • 128
  • 561
  • 623