Skip to content

There is wrong output for the code snippet (***VERY CRUCIAL***) #24

@Gohankr45444

Description

@Gohankr45444

The below link is the place where is wrong output is shown for the code.

Link to the section of readme

Example

	jshell> Integer integer1 = new Integer(5);
	integer1 ==> 5
	jshell> Integer integer2 = new Integer(5);
	integer2 ==> 5
	jshell> Integer integer3 = Integer.valueOf(5);
	integer3 ==> 5
	jshell> Integer integer4 = Integer.valueOf(5);
	integer4 ==> 5
	jshell> integer1 == integer2
	$1 ==> true                   <--------------------------------------- wrong output
	jshell> integer3 == integer4
	$2 ==> true
	jshell>

  new Wrapper(int) Always creates a new instance. So, output can't be true because memory locations are not same.

Correct Example

public class WrapperExample {
    public static void main(String[] args) {
        // Using 'new' - Always creates different objects
        Integer newObj1 = new Integer(100);
        Integer newObj2 = new Integer(100);
        
        System.out.println(newObj1 == newObj2);      // Output: false (Different memory locations)

        // Using 'valueOf' - Reuses cached objects for small values
        Integer valOf1 = Integer.valueOf(100);
        Integer valOf2 = Integer.valueOf(100);
        
        System.out.println(valOf1 == valOf2);        // Output: true (Same cached object)

        // Using 'valueOf' - Outside the typical cache range (-128 to 127)
        Integer largeVal1 = Integer.valueOf(500);
        Integer largeVal2 = Integer.valueOf(500);
        
        System.out.println(largeVal1 == largeVal2);  // Output: false (Not in cache, new objects created)
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions