Nik88
Nik88

Reputation: 1022

Confused to understand program output

Here is a program

public class MovieTitle {
    public static void main(String[] args) {
        Movie one = new Movie();
        one.title = "I am title";
        one.playIt();
        System.out.println(one.title);
    }
}

class Movie {
    String title;
    void playIt() {
        this.title = "I am title of movie";
    }
}

The output is "I am title of movie" I am trying to understand it but till now I do not understand it properly. I want to know: Why does it not print "I am title"

Upvotes: 0

Views: 121

Answers (5)

paulsm4
paulsm4

Reputation: 121669

Does this illustrate why:

public class MovieTitle {
    public static void main(String[] args) {
        Movie one = new Movie();
        System.out.println(one.title);
        one.title = "I am title";
        System.out.println(one.title);
        one.playIt();
        System.out.println(one.title);
    }
}

class Movie {
    String title;
    void playIt() {
        this.title = "I am title of movie";
    }
}

Here's the corresponding output:

java MovieTitle
null
I am title
I am title of movie

Upvotes: 1

Efthymis
Efthymis

Reputation: 1326

You asign "I am title" to the title varible in object one of type Movie.

When you call method playIt() in the same object, varible title gets asigned another value "I am title of movie".

If you invert the lines like so

one.playIt(); 
one.title = "I am title";

The output is going to be "I am title", because you set this value, after you call playIt() method.

Upvotes: 0

Yuushi
Yuushi

Reputation: 26040

If you trace out the calls, it should become fairly obvious.

Movie one = new Movie();

title will be NULL at this point (ie, it has had no value assigned)

one.title = "I am title";

Now your Movie object one has the title "I am title"

one.playIt();

Calls the playIt() method on one, which sets the title of "this" (which is one) to "I am title of movie"

Upvotes: 0

Matthias Bruns
Matthias Bruns

Reputation: 900

Cause you set when you call playIt() the title to "I am title of movie"; Try changing the order of the two lines

one.title = "I am title";
one.playIt();

Upvotes: 0

Thilo
Thilo

Reputation: 262534

Sequence of events:

// create a new Movie called "one"
Movie one = new Movie();

// at this point, one.title is still null

// set the title to "I am title"
one.title = "I am title";

// call playIt, which in turn ...
one.playIt();
   // sets the title to something else again
   => this.title = "I am title of movie";

If you printed the title before calling playIt, it would still show as "I am title".

Upvotes: 5

Related Questions