Programming technique 1    Cascaded assignment (short hand)

 

public class CascadeAssign
{
   public static void main(String[] args)
   {
       int i, j, k;

       // Single line assignment statements
       k = 1;      // Assigning the same value
       j = 1;
       i = 1;

       // Can be done much quicker like this
       i = j = k = 1;
   }
}
  

DEMO: demo/02-elem-prog/09-prog-tech/CascadeAssign.java

Programming technique 2    swapping values in 2 variables

Write code to exchange the values in the variables a and b:

public class SwapVars
{
   public static void main(String[] args)
   {
       int a = 1, b = 2;

       

       // Code to swap values in a and b


       // End result: a = 2, b = 1
   }
}
  

Programming technique 2    swap value in 2 variables

Analogy to example the swap programming technique:

 

 

Programming technique 2    swapping values in 2 variables

Let's write code using the analogy:

public class SwapVars
{
   public static void main(String[] args)
   {
       int a = 1, b = 2;

       

       // Code to swap values in a and b


       // End result: a = 2, b = 1
   }
}
  

Programming technique 2    swapping values in 2 variables

(1) Define a helper variable (must be of the same data type as the swapping variables)

public class SwapVars
{
   public static void main(String[] args)
   {
       int a = 1, b = 2;

       int help;      // Helper variable to hold a value 

       // Code to swap values in a and b


       // End result: a = 2, b = 1
   }
}
  

Programming technique 2    swapping values in 2 variables

(2) Save the value of a in the helper variable:

public class SwapVars
{
   public static void main(String[] args)
   {
       int a = 1, b = 2;

       int help;      // Helper variable to hold a value 

       // Code to swap values in a and b
       help = a;      // Now a is "free"

       
   }
}
  

Programming technique 2    swapping values in 2 variables

(3) Save the value of b in the variable a:

public class SwapVars
{
   public static void main(String[] args)
   {
       int a = 1, b = 2;

       int help;      // Helper variable to hold a value 

       // Code to swap values in a and b
       help = a;      // Now a is "free"
       a = b;         // Perform first half of the swap
       
   }
}
  

Programming technique 2    swapping values in 2 variables

(4) Save the value in helper variable help in the variable b:

public class SwapVars
{
   public static void main(String[] args)
   {
       int a = 1, b = 2;

       int help;      // Helper variable to hold a value 

       // Code to swap values in a and b
       help = a;      // Now a is "free"
       a = b;         // Perform first half of the swap
       b = help;      // Perform second half of the swap     
   }
}
  

DEMO: demo/02-elem-prog/09-prog-tech/SwapVars.java