Tuesday, April 28, 2009

Java Example : How To Swap Integer and String Variables Without Using a Temporary Variable

Hi guys,

Swapping two variable has always been a classic learning example for beginners, well for a change in the example below we would be learning to swap two variables (String or Integer) without using a temporary variable.

/*

  *   @(#)Swap.java       1.1   28/04/09

  *

  *   Copyright   2009   Lazy   Coder.   All   rights   reserved.

  *   To   be   used   only   for   educational   purposes.

  *   Not   to   be   reproduced   and   published

  *   without   seeking   prior   consent.

  */


package   com.lazy.coder.examples;





/**

  *   A   class   that   demonstrates   how   to   swap  

  *   two   strings   or   two   integers   without

  *   using   a   temporary   variable

  *  

  *   @author   lazycoder

  *  

  */


public   class   Swap   {



      

       /**

         *   @param   args

         */


       public   static   void   main(String[]   args)   {

              //Swapping   two   String   without   using   temp   variable.

              String   firstString   =   "Lazy";

              String   secondString   =   "LazyCoder";

              System.out.println("firstString   =   "   +   firstString);

              System.out.println("secondString   =   "   +   secondString);

              System.out.println("Swapping");

              firstString   =   firstString   +   secondString;

              secondString   =   firstString.substring(0,   firstString.length()

                            -   secondString.length());

              firstString   =   firstString.substring(secondString.length());

              System.out.println("firstString   =   "   +   firstString);

              System.out.println("secondString   =   "   +   secondString);

             

              //Swapping   two   Integers   without   using   temp   variable.

              int   firstInt   =   111111111;

              int   secondInt   =   999999999;

              System.out.println("firstInt   =   "   +   firstInt);

              System.out.println("secondInt   =   "   +   secondInt);

              System.out.println("Swapping");

              /*

                *   Using   exclusive-or   (XOR)   to   avoid  

                *   stack   overflow/underflow

                */


              firstInt   =   firstInt   ^   secondInt;

              secondInt   =   firstInt   ^   secondInt;

              firstInt   =   firstInt   ^   secondInt;

              System.out.println("firstInt   =   "   +   firstInt);

              System.out.println("secondInt   =   "   +   secondInt);

       }

}



Thats all for now, check back for more java examples.

Lazy Coder
signing off for now...

Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl

1 comment: