• 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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Doubt in Declarations

 
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi, Please have a look at the code below


This is one of the Q from Dan's mock exams,,Answer is 1212013
How is it that i of the first for statement doesn't give an error of not being declared and if it shadows the class variable,then why not i of second for statement give an error of i being already declared.I'am confused,
Please Explain..


Thanks
 
Ranch Hand
Posts: 226
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi
Go through the comment that i was placed in code

package sample;

class StaticTest
{

static int i;

public static void main(String args[])
{
//This is the Class Level Variable you can use this Class varible since it is staitc
//if you remove the word static then it is not working .
for (i = 1; i < 3; i++)
{
System.out.print(i);
}
//here varibale is declared inside the llop and scope of the varible is only for this loop
for (int i = 1; i < 3; i++)
{
System.out.print(i);
}
//Declaration is for the main method
int i;

for (i = 0; i < 2; i++)
{
System.out.print(i);
}
//This will print the 3 because in first loop we incremeted the value of i up to 3 and printed upto 2
System.out.print(StaticTest.i);
}

}
 
Did you just should on me? You should read this tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic