October 8, 2012

Difference Between Variable Declared Inside For Loop and Outside Loop

Question by sagar

How does the jvm manage the memory for i and j? What is the difference between i and j other than their scope?

int i;
for(i=0;i<5;i++)
{
    System.out.println(i)
}
for(int j=0;j<5;j++)
{
    System.out.println(j)
}

Answer by Starx

Its basically the same thing. The only difference is the declaration happens before the loop in the first case and and in the second case it happens before the execution of the loop.

About JVM’s memory management, it is basically managed in the same way.

September 12, 2012

Access String variable from one if statement in another

Question by user185812

I am new to java coming from C#.

If I have a string that gets set in an “if-statement” is there a way to carry that string’s value to other if statements?

E.g. I set the String hi to carry the text “hello” in an if statement, but now have a completely separate if statement, and would like to use the value set to the String hi in the previous if statement.

My issue is that the veriable can’t be set until certain things in the if statement happen.

if(add.equals(temp)) {
    System.out.println ("What is the first number?");
    numberone = listen.nextDouble ();
    System.out.println ("What is the second number?");
    numbertwo = listen.nextDouble ();
    numberthree = numberone + numbertwo;
    previousproblem = numberthree;
    System.out.println ("The answer is " + numberthree);
}

So later on, in another if statement I, need to reference previousproblem, but it can’t be set until this if statement, as numberthree isn’t set until this statement.

Answer by dasblinkenlight

Java is identical to C# in this respect, all you need to do is declaring the variable outside both if statements, and set its initial value:

String s = null;
if (someCondition) {
    s = "hello";
}
if (anotherCondition) {
    System.out.println("s is "+s);
}

Answer by Starx

Define the string, before you start you if and else sequence.

String str1,str2;
if(true) {
   // ... true part
   str1 = "hello";
} else { 
   // ... false part
}

Now in another If

if(true) {
    str2 = str1; //assign the value of str1 to str2 demonstrating the use str1 in another if
}
...

Please fill the form - I will response as fast as I can!