Swapping pairs of characters in a String Question: Write a program to swap pairs of characters of a String. In
  case of odd number of characters last character should remain
  unchanged. 
  
  Examples: 
  
  Input: HI
  
  Output: IH
  
  Input: hello there
  
  Output: ehll ohtree


My Code: 

import java.util.*; 
class SwappedPairs
{
    static String swapPairs(String str)
    {
        int len = str.length(); 
        int n; //array's length
        if(len%2 == 0)
        {
            n = len;
        }
        else
        {
            n=len-1;
        }
        char []arr = new char[n];
        for(int i = 0; i&lt; n; i++)
        {
            arr[i] = str.charAt(i); 
        }
        StringBuffer str1 = new StringBuffer(n); 
        for(int i = 0; i&lt;=n-2; i= i+2)
        {
            char temp = arr[i]; 
            arr[i] = arr[i+1];
            arr[i+1] = temp; 
            str1 = str1.append(arr[i]).append(arr[i+1]);
        }

        if(len%2 != 0)
        {
             str1 .append(str.charAt(len-1));
        }
        str = str1.toString();
        return str;
    }

    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter a string: ");
        String str = sc.nextLine(); 
        System.out.println(swapPairs(str));
    }
}


Any suggestion on how to improve it? (It gives the desired output)
Using a StringBuffer for building the new string is good,
but the variable name str1 is non-descriptive.

The computation of the required array length can be shortened 
with the conditional operator:

int n = len % 2 == 0 ? len : len - 1;


Instead of swapping the array elements you can append them to the
string buffer in opposite order:

for (int i = 0; i &lt;= n - 2; i = i + 2) {
    str1 = str1.append(arr[i+1]).append(arr[i]);
}


(and the re-assignment to str1 is not necessary).

And now one sees that the intermediate array is not needed at all: 
You can append the swapped characters directly from the original string:

static String swapPairs(String str) {
    int len = str.length(); 
    StringBuffer swapped = new StringBuffer(len);
    for (int i = 0; i &lt; len - 1 ; i += 2) {
        swapped.append(str.charAt(i + 1));
        swapped.append(str.charAt(i));
    }
    if (len % 2 != 0) {
        swapped.append(str.charAt(len - 1));
    }
    return swapped.toString();
}