Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does my program print the method before the variable? [duplicate]

Tags:

java

When I run this program:

class Baap {
    public int h = 4;

    public int getH() {
        System.out.println("Baap " + h);
        return h;
    }
}
public class Beta extends Baap {
    public int h = 44;

    public int getH() {
        System.out.println("Beta " + h);
        return h;
    }

    public static void main(String[] args) {
        Baap b = new Beta();
        System.out.println(b.h + " " + b.getH());
        Beta bb = (Beta) b;
        System.out.println(bb.h + " " + bb.getH());
    }
}

I get the following output:

Beta 44
4 44
Beta 44
44 44

If you look carefully at the first System.out.println(b.h + " " + b.getH());, doesn't this command tell Java to print out the value of h before the value of the getH() method? Shouldn't the first part of the printout be 4 instead of Beta 44?

like image 317
Suliman2972 Avatar asked Mar 12 '26 11:03

Suliman2972


2 Answers

Before println is called, its argument - b.h + " " + b.getH() - is evaluated. During that evaluation Beta 44 is printed due to the call to getH(). Only after the evaluation, println is passed the result of the evaluation (4 44) and prints it.

like image 169
Eran Avatar answered Mar 19 '26 01:03

Eran


Shouldn't the first part of the printout be 4 instead of Beta 44?

No because calling getH() first calls

System.out.println("Beta " + h);

then

return h;

which then allows the rest of the calling line

System.out.println(b.h + " " + b.getH());

to be evaluated.

like image 30
dav_i Avatar answered Mar 19 '26 02:03

dav_i