File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes I am confused abt this code Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "I am confused abt this code" Watch "I am confused abt this code" New topic

I am confused abt this code

vuthlarhi donald
Ranch Hand

Joined: Jul 31, 2006
Posts: 76
public class Tux extends Thread{
static String sName = "Techno";
public static void main(String argv[]){
Tux t = new Tux();;
public void name(String sName){
sName = sName + " park";
public void run(){
for(int i=0;i < 4; i++){
sName = sName + " " + i; }} }
Panseer Kaur
Ranch Hand

Joined: Nov 01, 2007
Posts: 44
What are you confused about exactly?
vuthlarhi donald
Ranch Hand

Joined: Jul 31, 2006
Posts: 76
about what the program prints
vidya sagar
Ranch Hand

Joined: Mar 02, 2005
Posts: 580

These two lines has clue for you.
Sid Robin
Ranch Hand

Joined: Nov 24, 2007
Posts: 53
Kelvin Chenhao Lim
Ranch Hand

Joined: Oct 20, 2007
Posts: 513
Also, note that the formal parameter "sName" of name() shadows the class variable with the same name. In other words, within the body of name(), the variable "sName" refers only to the parameter passed to it, not the variable defined by 'static String sName = "Techno"'.

SCJP 5.0
mohan gavande
Ranch Hand

Joined: Oct 07, 2004
Posts: 39
I think o/p would be "Tachno park 3".
And also it will print after the thread execution.
Lukas Zuchowski

Joined: Jul 13, 2006
Posts: 12
It's concurency issue.
I usualy prints "Techno", but when I was following the execution in debuger,
the thread that program was starting by "start();" has finished execution before "System.out.println(sName)" was executed and the result was : "Techno 1 2 3 4".
In conclusion I think we can't be sure what will be printed in this case.

ps. but definitly nothing that starts from "Techno Park"
Hasitha Randika
Ranch Hand

Joined: Sep 04, 2007
Posts: 50
it will print techno until the loop ends what you want to remember is Strings are immutable so it will print techno
I agree. Here's the link:
subject: I am confused abt this code
It's not a secret anymore!