AllExperts > Java 
Search      
Java
Volunteer
Answers to thousands of questions
 Home · More Java Questions · Answer Library  · Encyclopedia ·
More Java Answers
Question Library

Ask a question about Java
Volunteer
Experts of the Month
Expert Login

Awards

About Us
Tell friends
Link to Us
Disclaimer

 
 
 
 
About Brian Ngure
Expertise
Strong in Java. Will be able to answer both in areas of designing and coding. Some knowledge in servlets

Experience
5 years of Java experience, Sun Certified Java Associate and Sun Certified Java Programmer, JDK 1.4

 
   

You are here:  Experts > Computing/Technology > Focus on Java > Java > swap 2 numbers

Java - swap 2 numbers


Expert: Brian Ngure - 9/3/2009

Question
QUESTION: Hi,
I wanna simple java code to swap 2 numbers without using 3rd variable and these 2 numbers should be taken from the user.i.e., user gv an input of 2 numbers, those 2 numbers should be swaped.




ANSWER: Hi,

You could just reverse the order of the output in the code.

i.e. Instead of writing print(num1 + " " + num2); write print(num2 + " " + num1);

Brian

---------- FOLLOW-UP ----------

QUESTION: public class SwapTwoNumbers

{    
  public static void main(String[] args)

   {         
      int a=1;         
      int b=2;
      System.out.println("Before swap: a="+a+"b="+b);
      a=a+b;         
      b=a-b;  
      a=a-b;     
      System.out.println(" After swap: a="+a+"b="+b);
    }
}

Here is the code for swaping 2 numbers without using third variable. But here 'a' and 'b' value are already set in code. Here 'a' and 'b' value should be taken by user.

can you please tell me. how to do this ?

Answer
Hi,

Here is a simple example of how to get keyboard input:

import java.io.*;

public class TestReadLine {
  public static void main (String args[]) {
     String aLine = "";
     BufferedReader input = new BufferedReader(new InputStreamReader(System.in));

     try {
        aLine = input.readLine();
     } catch (Exception e) {
        e.printStackTrace();
     }

     System.out.println(aLine);
  }
}

Brian

Add to this Answer   Ask a Question


 
User Agreement | Privacy Policy | Kids' Privacy Policy | Help
Copyright  © 2008 About, Inc. AllExperts, AllExperts.com, and About.com are registered trademarks of About, Inc. All rights reserved.