File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes chapter 3 self test, question 8 Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "chapter 3 self test, question 8" Watch "chapter 3 self test, question 8" New topic
Author

chapter 3 self test, question 8

Rachel Glenn
Ranch Hand

Joined: Oct 24, 2012
Posts: 95
The function...

void go(int ouch)
{
ouch++;
for (int ouch = 0; ouch < 5; ouch++)
{}
}

So this will compile in C++, but not Java?? Why doesn't JAVA accept this,but C++ does?
Abhilash Sharma
Ranch Hand

Joined: Dec 05, 2010
Posts: 67

R Gle wrote:The function...

void go(int ouch)//1
{
ouch++;
for (int ouch = 0; ouch < 5; ouch++)//2
{}
}

So this will compile in C++, but not Java?? Why doesn't JAVA accept this,but C++ does?


In case of java, once ouch is declared at 1 it can't be declared again at 2 because ouch is considered local to function block/scope and for loop come under that scope. So, you can't declare same variable two times in the same block/scope.

In case of c++, I think for loop may be considered as different scope to the compiler. So, may be redeclaration is not a problem.


OCPJP 6 | OCEJWCD 6
Rahul mir
Ranch Hand

Joined: Oct 31, 2012
Posts: 38

Variables and functions are accessed using scoping rules, not visbility rules, in C++, int ouch is decleared as function parameter and again in side the for loop,
the scope of the variable is fixed inside the braces, it is allow in C++ but not in java.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: chapter 3 self test, question 8