Java - Write code to reverse a string using for loop

Requirements

Write code to reverse a string using for loop

Demo

//package com.book2s;

public class Main {
    public static void main(String[] argv) {
        String string = "book2s.com";
        System.out.println(reverse(string));
    }/*from  ww  w  .j  a  v  a  2s  .  com*/

    public static String reverse(String string) {
        if (string == null || string.isEmpty())
            return string;

        if (string.length() == 1)
            return string;

        char[] characters = string.toCharArray();
        for (int start = 0, end = string.length() - 1; start < end; start++, end--) {
            char temp = string.charAt(start);
            characters[start] = characters[end];
            characters[end] = temp;
        }

        return String.valueOf(characters);
    }
}

Related Example