public static void main(String [] args){
		ArrayList<String> list1 = new ArrayList<String>();
		ArrayList<String> list2 = method(list1);
	private static ArrayList<String> method(ArrayList<String> list) {
		ArrayList<String> result = list;
		return result;

Could anyone explain this code to me? why it gives me the same result in list1 & list2..

thank you,

The secret of understanding this is to remember that list1, list2, list, and result are references (llike pointers) to an Object of type ArrayList<String>. The only way an actual ArrayList<String> object can be created is with the new keyword (line 3). If you follow the code 1 step at a time you will discover that there is only one ArrayList is this program, and that all those variables are just copies of the variable list1, so they all refer to the same object.
It's not easy to grasp 1st time round. Grab a sheet of paper with boxes for the variables and fill in the boxes as you step through the code. Remember the variables are references (pointers) they are not ArrayLists.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.