can we write a java method that swaps two integers

Carvia Tech | December 04, 2019 | 1 min read | 95 views

The answer is No.

For knowing the exact answer you must be knowing how Parameter Passing works in Java.

Incase of primitive int

Parameters to the method are passed by value in Java. In case of primitive data types, a copy of the value is passed to the method, so any changes in the method will not reflect in the calling code.

Incase of Integer Wrapper Class

For objects, the reference to the Object are copied by value to the calling method. If we reassign these reference copies then the changes will not be reflected to the method calling this swap(x,y).

Swap method: will never work as intended
public void swap(Integer x, Integer y) {
       Integer tmp =x;

Top articles in this category:
  1. Can two threads call two different synchronized instance methods of an Object?
  2. Given a collection of 1 million integers, All ranging between 1 to 9, how would you sort them in Big O(n) time
  3. How will you increment each element of an Integer array, using parallel operation
  4. Diamond Problem of Inheritance in Java 8
  5. What is volatile keyword in Java
  6. What do you understand by Java Memory Model?
  7. What is AtomicInteger class and how it works internally

Find more on this topic:
Core Java image
Core Java

Core Java - OOP Concepts, Garbage Collection, Multi-threading, Collections Framework, Java 8 Features, Lambda Functions, Streams.

Last updated 1 week ago

Recommended books for interview preparation:

This website uses cookies to ensure you get the best experience on our website. more info