Win a copy of Microservices Testing (Live Project) 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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • Ron McLeod
  • Jeanne Boyarsky
  • Paul Clapham
Sheriffs:
  • Liutauras Vilda
  • Henry Wong
  • Devaka Cooray
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Al Hobbs
  • Carey Brown
Bartenders:
  • Piet Souris
  • Mikalai Zaikin
  • Himai Minh

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);
}

}
reply
    Bookmark Topic Watch Topic
  • New Topic