I have been wondering how local values are creating and destroyed in JavaScript for example
function multiple(value){return value*2;}
when I called this function will a local variable be created value and then would it be destroyed?
Or would it affect garbage collection and become something to be removed?
And would that also apply to Java?
Please don't say premature optimization is the root of all evil, I know that already.
if this is a bad question please dont -rep me, just say so and I'll delete it
In javascript, value is an argument to the function and it will be created at the time the function is called. Another variable is then created as the result of the value*2 expression and that result is then returned from the function.
There are no local variables in the normal sense of that word since none are declared in that function. Arguments to the function work kind of like local variables (same scope, same default lifetime), but people don't normally call them local variables.
If the return value from that function is assigned to something as in:
var result = multiple(3);
Then, the return value will live on in the result variable. If the return value is not assigned and not used (which would be odd in this case), then it will have no references to it and will be freed by the the garbage collector.
Related
Why must local variables, including primitives, always be initialized in Java? Why is the same not applicable in the case of instance variables?
Basically, requiring a variable to be assigned a value before you read it is a Good Thing. It means you won't accidentally read something you didn't intend to. Yes, variables could have default values - but isn't it better for the compiler to be able to catch your bug instead, if it can prove that you're trying to read something which might not have been assigned yet? If you want to give a local variable a default value, you can always assign that explicitly.
Now that's fine for local variables - but for instance and static variables, the compiler has no way of knowing the order in which methods will be called. Will a property "setter" be called before the "getter"? It has no way of knowing, so it has no way of alerting you to the danger. That's why default values are used for instance/static variables - at least then you'll get a known value (0, false, null etc) instead of just "whatever happened to be in memory at the time." (It also removes the potential security issue of reading sensitive data which hadn't been explicitly wiped.)
There was a question about this very recently for C#... - read the answers there as well, as it's basically the same thing. You might also find Eric Lippert's recent blog post interesting; it's at least around the same area, even though it has a somewhat different thrust.
In Java, class and instance variables assume a default value (null, 0, false) if they are not initialized manually. However, local variables don't have a default value. Unless a local variable has been assigned a value, the compiler will refuse to compile the code that reads it. IMHO, this leads to the conclusion, that initializing a local variable with some default value (like null, which might lead to a NullPointerException later) when it is declared is actually a bad thing. Consider the following example:
Object o;
if (<some boolean condition>)
o = <some value>;
else
o = <some other value>;
System.out.println(o);
An initialization of o with null is completely unnecessary, since the Java compiler checks at compile time, that any code-path initializes o (with either null or some non-null value) before the variable is read. That means, that the compiler will refuse to compile the line System.out.println(o); if you would comment out any of the two initializations of the variable o in the code snippet above.
This holds for Java, and maybe for Java only. I don't know about language like C#. In good old C (and maybe C++) however, it is still recommended to always initialize variables when declaring them, AFAIK. Such "old-school" programming languages might be the reason, that the recommendation to always initialize variables pops up in books and discussions about modern languages like Java, where the compiler keeps track of whether a variable has been initialized or not.
Not totally true. Local variables only need to be initialized if being reference. A local variable can be left uninitialized if never referenced. For example:
int x; // Valid
int y;
println("y=" + y); // Not valid since y's value has never been assigned
Well, in case of local variable it's clear what it means 'before' since the program flow between declaration (in method) and reference is sequential. In case of fields declared outside of the method compiler never knows which code is going to be used when so it cannot generate an error as possibly some other method is going to initialize the field before it is used.
Local variables and primitives should be initialized before use because you would know what to expect from the values. Historically, when a new variable was created it would contain random values from the memory [and one could not predict the value]. Java also requires this because it prevents the presence of orphaned variables.
In practice all variables need to be initialized before using them.
I can't think of a time you'd want to use a variable before setting its value (unless you're comparing it against null).
It is necessary to initialize local variables (only when we use them) because they don't get any default value like instance variables.
And as basic rule, we should always initialize any variable before using it. Otherwise it may result in an error like nullPointer, etc
Now, why don't local variables get default value? The reason is that local variables reside on stack and is visible only in local method context, unlike instance variables which resides on heap and has scope throughout the program.
So when the stack will end local method's value will also get destroyed therefore:
1] They are supposed to be initialized explicitly (when we use them)
2] They should not be initialized implicitly (by null,0 or false) like instance variables
Going by the definition of local variable which state, a local variable is declared within a function or is passed as an argument in a function. If you do not initialized a local variable you will encounter exception handling problem because, the compiler will not be able to understand what value the variable holds
Why must local variables, including primitives, always be initialized in Java? Why is the same not applicable in the case of instance variables?
Basically, requiring a variable to be assigned a value before you read it is a Good Thing. It means you won't accidentally read something you didn't intend to. Yes, variables could have default values - but isn't it better for the compiler to be able to catch your bug instead, if it can prove that you're trying to read something which might not have been assigned yet? If you want to give a local variable a default value, you can always assign that explicitly.
Now that's fine for local variables - but for instance and static variables, the compiler has no way of knowing the order in which methods will be called. Will a property "setter" be called before the "getter"? It has no way of knowing, so it has no way of alerting you to the danger. That's why default values are used for instance/static variables - at least then you'll get a known value (0, false, null etc) instead of just "whatever happened to be in memory at the time." (It also removes the potential security issue of reading sensitive data which hadn't been explicitly wiped.)
There was a question about this very recently for C#... - read the answers there as well, as it's basically the same thing. You might also find Eric Lippert's recent blog post interesting; it's at least around the same area, even though it has a somewhat different thrust.
In Java, class and instance variables assume a default value (null, 0, false) if they are not initialized manually. However, local variables don't have a default value. Unless a local variable has been assigned a value, the compiler will refuse to compile the code that reads it. IMHO, this leads to the conclusion, that initializing a local variable with some default value (like null, which might lead to a NullPointerException later) when it is declared is actually a bad thing. Consider the following example:
Object o;
if (<some boolean condition>)
o = <some value>;
else
o = <some other value>;
System.out.println(o);
An initialization of o with null is completely unnecessary, since the Java compiler checks at compile time, that any code-path initializes o (with either null or some non-null value) before the variable is read. That means, that the compiler will refuse to compile the line System.out.println(o); if you would comment out any of the two initializations of the variable o in the code snippet above.
This holds for Java, and maybe for Java only. I don't know about language like C#. In good old C (and maybe C++) however, it is still recommended to always initialize variables when declaring them, AFAIK. Such "old-school" programming languages might be the reason, that the recommendation to always initialize variables pops up in books and discussions about modern languages like Java, where the compiler keeps track of whether a variable has been initialized or not.
Not totally true. Local variables only need to be initialized if being reference. A local variable can be left uninitialized if never referenced. For example:
int x; // Valid
int y;
println("y=" + y); // Not valid since y's value has never been assigned
Well, in case of local variable it's clear what it means 'before' since the program flow between declaration (in method) and reference is sequential. In case of fields declared outside of the method compiler never knows which code is going to be used when so it cannot generate an error as possibly some other method is going to initialize the field before it is used.
Local variables and primitives should be initialized before use because you would know what to expect from the values. Historically, when a new variable was created it would contain random values from the memory [and one could not predict the value]. Java also requires this because it prevents the presence of orphaned variables.
In practice all variables need to be initialized before using them.
I can't think of a time you'd want to use a variable before setting its value (unless you're comparing it against null).
It is necessary to initialize local variables (only when we use them) because they don't get any default value like instance variables.
And as basic rule, we should always initialize any variable before using it. Otherwise it may result in an error like nullPointer, etc
Now, why don't local variables get default value? The reason is that local variables reside on stack and is visible only in local method context, unlike instance variables which resides on heap and has scope throughout the program.
So when the stack will end local method's value will also get destroyed therefore:
1] They are supposed to be initialized explicitly (when we use them)
2] They should not be initialized implicitly (by null,0 or false) like instance variables
Going by the definition of local variable which state, a local variable is declared within a function or is passed as an argument in a function. If you do not initialized a local variable you will encounter exception handling problem because, the compiler will not be able to understand what value the variable holds
I have a lambda function that is sent to another function, i want to change a variable that is declared outside of the lambda scope, in the lambda.
WebElement textArea ;
BrowserToucher.clickOnWebElement(() -> {
WebElement convPopupOrCard = findElementBy(driver,
conversationCardOrPopup);
return textArea = findSubElementBy(driver, convPopupOrCard,
CardAndPopupTextArea);
}, driver);
BrowserToucher.sendKeys(textArea, driver, text);
I need to change the 'textArea' var in the labmda, so i can use its value in the last line.
The only solution i've found is to make 'textArea' an array in size of 1.
But I don't really understand why it works.
Would love if anyone can explain that to me please.
Thank you!!
The only solution i've found is to make 'textArea' an array in size of 1 But I don't really understand why it works.
It works because the captured array itself is either final or effectively final (any variable whose value does not change).
As long as the captured variable is final or effectively final changing the contents of the array is completely fine & permissible.
Of course, code like this is not threadsafe. So, ideally, you should think twice before using this trick.
If I understand your problem correctly, the solution is not that hard if you remember that lambdas are just function but without the names, so you can pass any argument in the brackets there as you do with 'regular' java methods.
The only solution i've found is to make 'textArea' an array in size of
1. But I don't really understand why it works.
This is already very well described in one of stack overflow topics regarding java reference. Please get familiar with it, and you will understand it for good, and maby came up with another solution for your problem :)
Is Java "pass-by-reference" or "pass-by-value"?
Variables inside a lambda, or any anonymous inner class, need to be final or effectively final.
This is because those variables are copied to the lambda scope. If they were referenced instead of copied, a problem would arise when the variable goes out of scope of its declaration zone, while the lambda scope is still executing (think threads).
By defining an array, you are working around that problem: you're forcibly referencing the value, with an effectively final array (you initialize the array once, and never change it).
Final and effectively final variables can safely be copied, knowing that their value is not going to change.
When array goes out of scope, no problem, the GC still holds a pointer to you value from inside the lambda scope and it's not going to be garbage-collected until both lambda and the declaring zone are out of scope.
You could do the same with list, or any other collection. It'd also work with a wrapper class.
Why must local variables, including primitives, always be initialized in Java? Why is the same not applicable in the case of instance variables?
Basically, requiring a variable to be assigned a value before you read it is a Good Thing. It means you won't accidentally read something you didn't intend to. Yes, variables could have default values - but isn't it better for the compiler to be able to catch your bug instead, if it can prove that you're trying to read something which might not have been assigned yet? If you want to give a local variable a default value, you can always assign that explicitly.
Now that's fine for local variables - but for instance and static variables, the compiler has no way of knowing the order in which methods will be called. Will a property "setter" be called before the "getter"? It has no way of knowing, so it has no way of alerting you to the danger. That's why default values are used for instance/static variables - at least then you'll get a known value (0, false, null etc) instead of just "whatever happened to be in memory at the time." (It also removes the potential security issue of reading sensitive data which hadn't been explicitly wiped.)
There was a question about this very recently for C#... - read the answers there as well, as it's basically the same thing. You might also find Eric Lippert's recent blog post interesting; it's at least around the same area, even though it has a somewhat different thrust.
In Java, class and instance variables assume a default value (null, 0, false) if they are not initialized manually. However, local variables don't have a default value. Unless a local variable has been assigned a value, the compiler will refuse to compile the code that reads it. IMHO, this leads to the conclusion, that initializing a local variable with some default value (like null, which might lead to a NullPointerException later) when it is declared is actually a bad thing. Consider the following example:
Object o;
if (<some boolean condition>)
o = <some value>;
else
o = <some other value>;
System.out.println(o);
An initialization of o with null is completely unnecessary, since the Java compiler checks at compile time, that any code-path initializes o (with either null or some non-null value) before the variable is read. That means, that the compiler will refuse to compile the line System.out.println(o); if you would comment out any of the two initializations of the variable o in the code snippet above.
This holds for Java, and maybe for Java only. I don't know about language like C#. In good old C (and maybe C++) however, it is still recommended to always initialize variables when declaring them, AFAIK. Such "old-school" programming languages might be the reason, that the recommendation to always initialize variables pops up in books and discussions about modern languages like Java, where the compiler keeps track of whether a variable has been initialized or not.
Not totally true. Local variables only need to be initialized if being reference. A local variable can be left uninitialized if never referenced. For example:
int x; // Valid
int y;
println("y=" + y); // Not valid since y's value has never been assigned
Well, in case of local variable it's clear what it means 'before' since the program flow between declaration (in method) and reference is sequential. In case of fields declared outside of the method compiler never knows which code is going to be used when so it cannot generate an error as possibly some other method is going to initialize the field before it is used.
Local variables and primitives should be initialized before use because you would know what to expect from the values. Historically, when a new variable was created it would contain random values from the memory [and one could not predict the value]. Java also requires this because it prevents the presence of orphaned variables.
In practice all variables need to be initialized before using them.
I can't think of a time you'd want to use a variable before setting its value (unless you're comparing it against null).
It is necessary to initialize local variables (only when we use them) because they don't get any default value like instance variables.
And as basic rule, we should always initialize any variable before using it. Otherwise it may result in an error like nullPointer, etc
Now, why don't local variables get default value? The reason is that local variables reside on stack and is visible only in local method context, unlike instance variables which resides on heap and has scope throughout the program.
So when the stack will end local method's value will also get destroyed therefore:
1] They are supposed to be initialized explicitly (when we use them)
2] They should not be initialized implicitly (by null,0 or false) like instance variables
Going by the definition of local variable which state, a local variable is declared within a function or is passed as an argument in a function. If you do not initialized a local variable you will encounter exception handling problem because, the compiler will not be able to understand what value the variable holds
while(condition){
int n=1;
}
Will the variable n be destroyed (the memory being represented by the variable is set to a "null" state) when the loop starts over or will n be declared a second time taking up more memory and they won't be destroyed until the loop exits?
At the end of each loop iteration, the variable goes out of scope and ceases to exist. That doesn't mean assigning a special value (such as null) to it; it just means that the memory is available to be used by other things. In any sane JVM implementation, the next iteration of the loop will reuse the same location in memory (and reinitialize its value to 1), so you're using a constant amount of memory no matter how many iterations the loop runs. Note that even though the memory is (probably) reused, it's technically a different variable each time.
Beyond the end of the loop, the variable is permanently out of scope. The memory that it occupies is typically part of the "stack frame" that the JVM creates for all the variables used within the method, so those four bytes are still in-use by the method until it returns, but they can be reused to store another variable that's created later in the same method (if there is one).
Note that an int variable is a primitive type, not an object reference: you can't assign null to it.
A few other answers have mentioned garbage collection. I'd like to clarify that that's actually not relevant here. Objects are garbage-collected, but variables — including those that refer to objects — are not.
A variable is always part of something else: it might be a field in an object, or a static field in a class, or a local variable within a method. Fields within objects have their memory freed when the containing object is garbage-collected, and static fields in classes are released when the class is unloaded (though that usually doesn't happen until the whole program ends). But local variables within a method are stored in the method's stack frame, which is allocated when the method is called, and released when the method returns.
In short: garbage collection is used to find objects that are no longer needed, but there's no need for garbage collection on stack frames because the JVM knows exactly when they're no longer needed: when the method returns.