• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • paul wheaton
  • Ron McLeod
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Piet Souris
Bartenders:

need help with question

 
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
public class ObjectTest2 {
String s;

public void ObjectTest2(){
s = "Constructor";
}

public void printString() {
System.out.println(s);
}

public static void main(String args[]) {
ObjectTest2 o = new ObjectTest2();
o.printString();
}
}



could someone please tell me why it is printing null in the question above ???
 
Ranch Hand
Posts: 809
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator


Its not a constructor rather its a method. Your s instance variable is assigned to null. There is nowhere explicit assignment of s. So SOP(s) prints null.

Its better not to use class name as a method. This will just create confusion.


Naseem
 
Ranch Hand
Posts: 92
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
it is because u have declared a method and not a constructor as ObjectTest2().so as of now the string reference has a value null.since there is no constructor for the class provided..s = "Constructor";won't happen..thus null is the output.

constructors don't have a return type...not even void.
following would work as u want....

public class ObjectTest2 {
String s;

public ObjectTest2(){
s = "Constructor";
}

public void printString() {
System.out.println(s);
}

public static void main(String args[]) {
ObjectTest2 o = new ObjectTest2();
o.printString();
}
}
 
reply
    Bookmark Topic Watch Topic
  • New Topic