| Author |
why is the output strange..
|
ashu Suri
Greenhorn
Joined: Oct 22, 2008
Posts: 18
|
|
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
Ranch Hand
Joined: Jan 12, 2009
Posts: 915
|
|
1. use code tags.
2. This is the output i am getting:
|
My Website: [Salvin.in] Cool your mind:[Salvin.in/painting] My Sally:[Salvin.in/sally]
|
 |
Rob Spoor
Sheriff
Joined: Oct 27, 2005
Posts: 19216
|
|
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.
|
SCJP 1.4 - SCJP 6 - SCWCD 5
How To Ask Questions How To Answer Questions
|
 |
salvin francis
Ranch Hand
Joined: Jan 12, 2009
Posts: 915
|
|
I agree with Rob,
try this version of your program:
output:
Does this answer your query?
|
 |
 |
|
|
subject: why is the output strange..
|
|
|