File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes why is the output strange.. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "why is the output strange.." Watch "why is the output strange.." New topic
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: 917

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: 19654
    
  18

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 - OCEEJBD 6
How To Ask Questions How To Answer Questions
salvin francis
Ranch Hand

Joined: Jan 12, 2009
Posts: 917

I agree with Rob,

try this version of your program:




output:


Does this answer your query?
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: why is the output strange..
 
Similar Threads
Can someone explain the output of this code?
Object constructor and initialization
Help needed
practice question: what is the output?
can't call another constructor from no-arg constructor