We help IT Professionals succeed at work.

We've partnered with Certified Experts, Carl Webster and Richard Faulkner, to bring you a podcast all about Citrix Workspace, moving to the cloud, and analytics & intelligence. Episode 2 coming soon!Listen Now

x

# Variables

on
Medium Priority
214 Views
I have a method abc() in class XYZ { long a=0,b,c,d;

abc()
{

if(condition A)
{ a=System.currentTimeMillis(); }

if(condition B)
{
b=c-a;  //i am getting a= 0 when i call the method abc() second time...
}

First time when i call method condition A satisfies

when i call second time Condition B gets satisfied

How can i keep value a= what ever i got at the condition A

Thanks
Comment
Watch Question

## View Solutions Only

Commented:

when i call abc method second time value of variable a becomes zero. I want to keep the value of a when this if satisfied

if(condition A)
{ a=System.currentTimeMillis(); }

Commented:
What does abc() return?  void?

you might rewrite a as:

private static boolean firstTime = true;

public void abc()
{
if(conditionA)
{
if(firstTime)
{
firstTime = false;
a=System.currentTimeMillis();
}
}
...................

// now 'a' is only once assigned a value (for this object ONLY!).

;JOOP!

Commented:
Correction: my solution is for ALL objects XYZ.
If you want this to happen PER OBJECT, then drop the word 'static'.

;JOOP!

Not the solution you were looking for? Getting a personalized solution is easy.

Commented:
If you assign the attribute a a value it will not be reset to 0 except you do it.
See the following example:

public class Xyz {
private long a, b, c;

public void abc(boolean condition1, boolean condition2) {
if (condition1) {
a = System.currentTimeMillis();
}
if (condition2) {
b = c-a;
}
}

public long getA() {
return a;
}

public static void main(String[] args) {
Xyz xyz = new Xyz();
xyz.abc(true, false);
System.out.println("a: " + xyz.getA());
xyz.abc(false, true);
System.out.println("a: " + xyz.getA());
xyz.abc(true, true);
System.out.println("a: " + xyz.getA());
}

}
##### Thanks for using Experts Exchange.

• View three pieces of content (articles, solutions, posts, and videos)
• Ask the experts questions (counted toward content limit)
• Customize your dashboard and profile