Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Simple program(but cofusion with output)  RSS feed

 
Shiva Mohan
Ranch Hand
Posts: 486
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


Why s=null is printing without printing s=Constructor.Please help me.
 
Tim McGuire
Ranch Hand
Posts: 820
IntelliJ IDE Tomcat Server VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
the method objective14 is never called. You might think it is a constructor,
but a constructor would be

public objective14(){
....
}
 
Cameron Wallace McKenzie
author and cow tipper
Saloon Keeper
Posts: 4968
1
Hibernate Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Returning void on a constructor makes the constructor not a constructor. Instead, you had a method with the same name as the constructor, which is immensely confusing. To be honest, I didn't think it would compile like that, but it does. IRAD does indeed give a warning.

The code below has the void removed. This will give you the results you expect.

Regards,

-Cameron McKenzie


public class Objective14 {
String s;

/*Constructor does NOT have a return type*/
public Objective14(){
s = "Constructor";
}
public void printString() {
System.out.println("s="+s);
}
public static void main(String args[]) {
Objective14 o = new Objective14();
o.printString();
}
}
 
Shiva Mohan
Ranch Hand
Posts: 486
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks.I got it.
 
Srinivas Kalvala
Ranch Hand
Posts: 257
Firefox Browser Hibernate Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Shiva Mohan:


Why s=null is printing without printing s=Constructor.Please help me.



Java will provide default constructor , if you don't provide one. That is what happening in your case. There is no constructor. So the "s" will be null even after default constructor has been called.

: remove void ( return type in your method , it will act as constructor).

Thank you.
 
vijaya bharath
Ranch Hand
Posts: 66
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There is no return type for constructor , even it doesn't allow void,when you declare it void it assumes it as normal method not as a constructor.It will be get called only when you call explicitly using the object created.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!