Wednesday, August 28, 2013

JAVA & JavaScript String, Integer, etc.. what does "=" operator?

So today I got a very interesting problem in a JSP project, a discussion about it is here:
http://www.coderanch.com/t/618736/JSP/java/Object-scope-page-including-JSP

So Idecided to make some very simple but enlightetning examples in JAVA and JavaScript:
JAVA:
import java.util.*;

public class Adam {
 public static void main(String[] args){
  String adam = "adam";
  Integer notPrimitiveInteger = 10;
  int primitiveInteger = 20;
  ArrayList arrList = new ArrayList();
  arrList.add(1);
  arrList.add(2);
  doSomething(adam,notPrimitiveInteger,primitiveInteger,arrList);
  System.out.println(adam);
  System.out.println(notPrimitiveInteger);
  System.out.println(primitiveInteger);
  System.out.println(arrList.size());
 }
 private static void doSomething(String adam,Integer notPrimitiveInteger,int primitiveInteger,ArrayList arrList){
  adam = "notAdam";
  notPrimitiveInteger = 500;
  primitiveInteger = 7000;
  arrList.add(3);
 }
}
//Ignore this line :)
And the output is:
adam
10
20
3
 So what is happening?
Basically every time you are making expression's like this:
blabla = "blabla";

every time it's like a  new object is created (in fact not!, but broadly that's the case, learn more here). So it's like you are using the new String(".."); expression, but it's not showed. So when you're about to pass a String or an Integer object to a function , you could get the value of it, but if you want to change it, it will be not changed, because the "=" expression is like making a new object. Again: not making new object, but it behaves like it is.
And what about the ArrayList?
The ArrayList's add(..) function does not make a new ArrayList object! It's like you're working with it's reference, so the original ArrayList object will be changed!
JavaScript:
 var adam = new String("adam");
 var integ = 10;
 var arr = new Array();
 arr.push(1);
 arr.push(2);
 arr.push(3);
 var obj = new Object();
 obj.adam = "oldValue";
 console.log(arr);
 doSomething(adam,integ,arr,obj);
 function doSomething(adam,inte,arr,obj){
  adam="notadam";
  inte="500";
  arr.pop();
  obj.adam="newValue";
 }
 console.log(adam);
 console.log(integ);
 console.log(arr);
 console.log(obj);
And the output is:
The solution is the same as JAVA's.

No comments:

Post a Comment