Win a copy of Spring in Action (5th edition) this week in the Spring 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
  • Bear Bibeault
  • Devaka Cooray
  • Liutauras Vilda
  • Jeanne Boyarsky
Sheriffs:
  • Knute Snortum
  • Junilu Lacar
  • paul wheaton
Saloon Keepers:
  • Ganesh Patekar
  • Frits Walraven
  • Tim Moores
  • Ron McLeod
  • Carey Brown
Bartenders:
  • Stephan van Hulst
  • salvin francis
  • Tim Holloway

ints and arrays........  RSS feed

 
Ranch Hand
Posts: 435
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What will be the result of attempting to compile and run the following class?

Options:
1)The code will print i=1 iArr[0]=1;
2)The code will print i=1 iArr[0]=2;
3)The code will print i=2 iArr[0]=1
4)The code will print i=2 iArr[0]=2
5)The code will not compile
Answer :
2)The code will print i=1 iArr[0]=2
In this case, iArr[0] =2 (Agreed), but why is the value of i still 1, rather it should be incremented to 2??
Sonir
 
Ranch Hand
Posts: 178
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
because i is passed by value not by reference
 
Ranch Hand
Posts: 479
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i is passed by value and your array is passed by reference.
So once you get out of the incr method(), value of i is 1.
 
Younes Essouabni
Ranch Hand
Posts: 479
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

What if you do this???


 
Rajinder Yadav
Ranch Hand
Posts: 178
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Essouabni, the variable i is not defined in the scope of method void incr(int n), it is local to main()
You will get a compile error in your case.

Originally posted by Essouabni Younes:

<hr></blockquote>[/QB]

 
Younes Essouabni
Ranch Hand
Posts: 479
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Right, I just wanted to see if you were aware of it.
Sorry, I didn't pay attention
[ January 25, 2002: Message edited by: Essouabni Younes ]
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!