Friday, February 5, 2021

What will be the output of given example



public class StringConcating {

	public static void main(String[] args) {
		String str ="Hello";
		String str2 = "Narayan";
		String str3 = "HelloNarayan";
		String str4 = str+str2;
		
		if(str3 == str4) {
			System.out.println("Match");
		}else {
			System.out.println("Not Match");
		}
	}

}


Output:-
Not Match


Now you may wordering bcoz both object have same value still not match
so reason behind of this is when we do any operation over string it
return new object that will store in heap memory so we can say that str4 store
in heap while str3 will store in string constant pool and can't change value
of it since string is immutable

No comments:

Post a Comment

How to find middle node of LinkedList without using extra memory in java

To find the middle node of a LinkedList without using extra memory in Java, you can use the "tortoise and hare" algorithm. This al...