How to swap two numbers in java

i have an idea in c but i don't know in java..somenoe like to share their idea i appreciate a lot...
here is a sample code in c...hope u can help me in java.....thanks a lot ....
#include<stdio.h>
void swap(int x, int y)
int temp;
temp=x;
x=y;
y=temp;
  void main(void)
    int x=10,y=20;
      clrscr();
printf("Before swap:x=%d,y-%d", x,y);
    swap(x,y);
printf("\n After swap:x=%d,y=%d",x,y);
   getch();
#include<stdio.h>
void swap(int* x, int* y)
int temp;
temp=*x;
*x=*y;
*y=temp;
void main(void)
int x=10,y=20;
clrscr();
printf("Before swap:x=%d,y-%d", x,y);
swap(&x,&y);
printf("\n After swap:x=%d,y=%d",x,y);
getch();
}My aim of this program is to make one java file and 2 class files in java and display the output . The first output would be the number before swapping and the number after swapping.....

There are several ways to achieve the results. You can use an array or a custom "Swaper" class to swap two values. Here is an example using generics for better code reuse.
public class Swapper<T> {
   private T first;
   private T second;
   public Swapper(T first, T second) {
      this.first = first;
      this.second = second;
   public void swap() {
      T temp = first;
      first = second;
      second = temp;
   public <T> Swapper<T> swap(T first, T second) {
      return new Swapper<T>(second, first);
   public T getFirst() {return first;}
   public T getSecond() {return second;}
   private static void swap(int[] num) {
      if (num.length != 2) {
         throw new IllegalArgumentException("num array must be of length 2");
      int temp = num[0];
      num[0] = num[1];
      num[1] = temp;
   public static void main(String[] args) {
      // method 1: use array
      int[] num = {1, 2};
      System.out.printf("Before swap:first=%d,second=%d\n", num[0], num[1]);
      Swapper.swap(num);
      System.out.printf("After swap:first=%d,second=%d\n", num[0], num[1]);
      // method 2: use a custom "Swapper" class
      Swapper<Integer> swapper = new Swapper<Integer>(3, 4);
      System.out.printf("Before swap:first=%d,second=%d\n", swapper.getFirst(), swapper.getSecond());
      swapper.swap();
      System.out.printf("After swap:first=%d,second=%d\n", swapper.getFirst(), swapper.getSecond());
      // method 2: using another data type
      Swapper<String> stringSwapper = new Swapper<String>("C#", "Java");
      System.out.printf("Before swap:first=%s,second=%s\n", stringSwapper.getFirst(), stringSwapper.getSecond());
      stringSwapper.swap();
      System.out.printf("After swap:first=%s,second=%s\n", stringSwapper.getFirst(), stringSwapper.getSecond());
      /*    --- OUTPUT ---
       * Before swap:first=1,second=2
       * After swap:first=2,second=1
       * Before swap:first=3,second=4
       * After swap:first=4,second=3
       * Before swap:first=C#,second=Java
       * After swap:first=Java,second=C#
}

Similar Messages

  • How to compare two files in java & uncommon text should print in text file.

    Hi,
    Can any one help me to write Core java program for this.
    How to compare two files in java & uncommon text should print in other text file.
    thanks
    Sam

    Hi All,
    i m comparing two HTML file.. thats why i am getting problem..
    import java.io.BufferedReader;
    import java.io.FileReader;
    public class textmatch{
    public static void main(String[] argv)
    throws Exception{
    BufferedReader fh =new BufferedReader(new FileReader("internal.html"),1024);
    BufferedReader sh = new BufferedReader(new FileReader("external.html"),1024);
    String s;
    String y;
    while ((s=fh.readLine())!=null)
    if ( s.equals(y=sh.readLine()) ){    
    System.out.println(s + " " + y); //REMOVE THIS PRINTLN STATEMENT IF YOU JUST WANT TO SHOW THE SIMILARITIES
    sh.close();
    fh.close(); }
    thanks
    Sam

  • How to compare two files in Java & uncommon text should print in Diff text

    Hi All,
    can any one help me to write a java program..
    How to compare two files in Java & uncommon text should print in Diff text file..
    Thanks
    Sam

    Hi All,
    i m comparing two HTML file.. thats why i am getting problem..
    import java.io.BufferedReader;
    import java.io.FileReader;
    public class textmatch{
    public static void main(String[] argv)
    throws Exception{
    BufferedReader fh =new BufferedReader(new FileReader("internal.html"),1024);
    BufferedReader sh = new BufferedReader(new FileReader("external.html"),1024);
    String s;
    String y;
    while ((s=fh.readLine())!=null)
    if ( s.equals(y=sh.readLine()) ){    
    System.out.println(s + " " + y); //REMOVE THIS PRINTLN STATEMENT IF YOU JUST WANT TO SHOW THE SIMILARITIES
    sh.close();
    fh.close(); }
    thanks
    Sam

  • How to swap two string variables without using a 3rd variable?

    How to swap two string variables without using a 3rd variable?
    ex.
    A = "aa"
    B = "bb"
    Result required
    A = "bb"
    B = "aa"
    Thanks

    How to swap two string variables without using a 3rd
    variable?
    Something like this.
    Append A with B (so A equals "aabb")
    Set B equal to a substring of A starting with the first character and ending at A's length minus B's length. (So B equals "aa")
    Set A equal to a substring of A starting from B's length and ending at the end of A. (So A equals "bb")

  • How to swap two primitive dataelements using swap function??

    How to write a swap function that can swap two integer..??

    Now we are getting somewhere. Next time you post code, use the code tags!! See Formatting Tips or just select the code and click the Code button.
    you cant swap i,j using the above code...You're right. You can't do that.
    so how to do that??The ints must be within some object, like I showed you
    You cannot swap the values of two arguments to a method and expect the caller's variables be swapped because Java passes arguments by value not reference. There is no such thing as a pointer to a variable in Java as there is in C/C++.

  • How to Add two numbers using RFC in WD abap

    Dear Experts,
    I have to add the two numbers using RFC.
    I have created the RFC and by using create -> service call i have include that RFC in my WD abap Program.. After that i don't know how to link the input view and to display the result in another view...
    Please help me..
    Thank you.

    This is the third thread that you have posted on this same question.  This is also your second warning that such activity is not allowed in the SCN forums.  Please return to your original thread if you wish to post a follow up question. 
    Beacause this is a duplicate thread it will be locked.

  • How to generate Serial numbers using JAVA SCRIPT

    how to generate serial numbers(incrementing by 1) using JAVA SCRIPT
    thanking you,
    pola pradeep

    i am afraid that whether ur looking for this. bcoz its a simple for loop
    <script language="JavaScript">
    //count = limit value for u
    for(i=0;i<count;++i){
         alert(i);
    </script>
    or if ur looking for something else, pls mention ur requrment precisely
    aleena

  • How to Compare two Dates in java

    How to Compare two Date Field after getting the values from jTextField1.getText() and jTextField2.getText().

    Date d1=DateFormat.getDateInstance().parse(yourstring1);
    same for d2
    d1.compareTo(d2);
    could be that i misrememberd the exact naems of some functions or mixed up something in the equence of d1=

  • How to compare two Timestamps in java ??

    Hi , I have a class CurrentAddress, which is supposed to compare two TimeStamps of two address and store the current address
    I am not able to compare it using the < operator .How am I supposed to compare them ?
    Here is my code . Please reply
    public class CurrentAddress {
         private int EmpID;
         String CurrentEmpAddress;
         Timestamp CurrentTimeStamp;
         boolean TimeIsStampAlreadySet;
         public boolean compareTimeStamps(EmployeeAddress e)
               if(TimeIsStampAlreadySet)
                    Timestamp EmployeesTimeStamp=e.getTimeStamp();
                    if(EmployeesTimeStamp<this.CurrentTimeStamp)--------Compiler flags me here
    }I dont know what method will compare them .Is there anybody who can answer my question?
    Thanks a bunch
    Kavita Rivera

    Hi , Thank you , I will try that .
    I appreciate you writing back .
    Kavita Rivera .

  • How to communicate two objects in java

    pls reply to this mail

    >>
    http://saloon.javaranch.com/cgi-bin/ubb/ultimatebb.cgi
    ?ubb=get_topic&f=1&t=012041
    Communicate between forum.java.sun and Java Ranch?Communicate with the heathens at Java Ranch?

  • Swapping two columns

    How to swap two columns of a table.
    can any body give sample query.

    update table
    set col1 = col2, col2 = col1;As per Ask Tom...

  • How to add two different page numbers in a single page

    How to add two different page numbers in a single page? One is for page number of the whole article, the other one is for page number for each chapter in the article.

    It's quite complicated, see
    Two Page Numbering Schemes in the Same Document.
    Regards, Hans Vogelaar (http://www.eileenslounge.com)

  • I have two numbers listed in my messages tab under settings.  One number is checked(mine) and the other is not(my sons).  However when someone sends me a text it goes to both mine and my sons iphones.  How do i delete his number from my phone.

    I have two numbers listed in my messages tab under settings.  One number is checked(mine) and other is not(my sons).  However when someone sends me a test it goes to both numbers.  Mine and my sons.  How do I delete his number so that he no longer received texts intended for me.

    The best way is to not share Apple IDs but also make sure under Settings & Messages on both devices that only one phone number is checked.

  • I have two numbers on one skype account - how do I...

    My skype account has two numbers and I want to add one more, how do I allow answering of them separately?

    Hi, DHPE.Staff, and welcome to the Community,
    Unfortunately, Skype does not provide a facility to do this.  While a Skype account's incoming calls, whether to the Skype account itself or a Skype Number, can be forwarded to multiple mobile or land line numbers, each Skype Number purchased for an account is considered affiliated with that account and cannot be forwarded separately.
    The work-around people use is to create a new account for each Skype Number needed; that way call forwarding and caller ID can be differentiated between the numbers.
    The thing to be mindful of in doing this, however, is to use different payment methods, otherwise the payment methods and accounts may be trapped inadvertently by Skype's anti-fraud filters.  More details about this here:
    https://support.skype.com/en/faq/FA4081/can-i-use-my-credit-card-to-fund-more-than-one-skype-account
    Regards,
    Elaine
    Was your question answered? Please click on the Accept as a Solution link so everyone can quickly find what works! Like a post or want to say, "Thank You" - ?? Click on the Kudos button!
    Trustworthy information: Brian Krebs: 3 Basic Rules for Online Safety and Consumer Reports: Guide to Internet Security Online Safety Tip: Change your passwords often!

  • How to call two RFC in a single JAVA method.

    Dear all,
    I just want to know that how to call two RFC in a single java method which is defined in CRM implementation file. I'm using NWDS as the customization IDE & working on ISA 7.0.

    Hi Sunil,
    In the Backend Implementation class, in any method you can call multiple RFCs.
    It will be the same way as you do for the single RFC call.
    Following syntax is for your reference.
    Get the JCO connection
    JCoConnection  connection = getDefaultJCoConnection();
    JCO.Function func = connection.getJCoFunction("ZXXXXXXX");
    set the import parameters
    Execute it.
    connection.execute(func);
    get the data from export / table parameters
    Now call the second RFC
    func = connection.getJCoFunction("ZYYYYYYYYYY");
    set the import parameters
    Execute it.
    get the data from export / table parameters
    close the connection
    Hope this will help you.
    -Chandra.
    Edited by: Chandra Sekhar Seeli on Jan 13, 2011 2:04 PM

Maybe you are looking for