Java - Write code to Truncate the String by removing characters from the right side of the String so it is length characters long.

Requirements

Write code to Truncate the String by removing characters from the right side of the String so it is length characters long.

Demo

//package com.book2s;

public class Main {
    public static void main(String[] argv) {
        String string = "book2s.com";
        int length = 42;
        System.out.println(trunc(string, length));
    }/*from   w w w  .jav a 2s.c  o m*/

    public static String trunc(String string, int length) {

        int absLength = Math.abs(length);

        if ((string == null) || (string.length() <= absLength)) {
            return string;
        }

        if (length < 0) {
            int sLength = string.length();
            return string.substring(sLength - absLength, sLength);
        }

        return string.substring(0, length);
    }
}