Win a copy of Micro Frontends in Action this week in the Server-Side JavaScript and NodeJS forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Bear Bibeault
  • Junilu Lacar
Sheriffs:
  • Jeanne Boyarsky
  • Tim Cooke
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • salvin francis
  • Frits Walraven
Bartenders:
  • Scott Selikoff
  • Piet Souris
  • Carey Brown

Operator and Assignment Mock Question

 
Ranch Hand
Posts: 67
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi,
could someone explain me how the output of the following program is 2020

class Base{
public static int iAge;

}
public class CSturt{
public static void main(String argv[]){
CSturt cs = new CSturt();
cs.ww();
}
public void ww(){
Base b = new Base();
Base b2 = new Base();
b.iAge = 10;
b2.iAge = 20;
System.out.print(b.iAge);
Integer iw = new Integer(b.iAge);
col(iw);


}
public static void col(Object o){
Integer iw = (Integer) o;
System.out.print(iw.intValue());
}
}



thanks in advance.
 
Ranch Hand
Posts: 2410
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Note that iAge is a static variable.

So even though you have two instances of the class, using either instance to access iAge accesses the same variable.
 
Ranch Hand
Posts: 1710
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Saurav,

You may try the following code:

 
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Absolutely a good question with a trap ;-)
 
Rototillers convert rich soil into dirt. Please note that this tiny ad is not a rototiller:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
reply
    Bookmark Topic Watch Topic
  • New Topic