Win a copy of Learn Spring Security (video course) this week in the Spring forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

why is the output strange..

 
ashu Suri
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Run this program and we get extra "Testclass" in the ouput.
Can anybody explain where is it coming from?


public class Test {

public static String text = new String();

public static void main(String args[]){

System.out.println(text.getClass());

System.out.println(text.getClass()+ " unknown " + new Test().test());
}

public String test(){
System.out.print(getClass());
return "";
}

}

Thanks,
Gagan
 
salvin francis
Bartender
Posts: 1263
10
Eclipse IDE Google Web Toolkit Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
1. use code tags.

2. This is the output i am getting:
 
Rob Spoor
Sheriff
Pie
Posts: 20492
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Order of execution:
- System.out.println(text.getClass()) // prints "class java.lang.String" with an enter
- retrieve text.getClass() // returns a Class object for String
- append that Class object with " unknown "; the Class object is turned into a String using its toString method, and the result is "class java.lang.String unknown "
- call new Test().test()
- inside that method, print out getClass() // prints "class Test" without an enter
- inside that method, return ""
- take the return value and append it to the previous String. It is know "class java.lang.String unknown "
- print out that String // prints "class java.lang.String unknown " with an enter

Since one of the print outs misses an enter (print is called, not println) the "class Test" and "class java.lang.String unknown " are printed directly after each other.
 
salvin francis
Bartender
Posts: 1263
10
Eclipse IDE Google Web Toolkit Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I agree with Rob,

try this version of your program:




output:


Does this answer your query?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic