Java - Write code to Get last n chars from a string.

Requirements

Write code to Get last n chars from a string.

Demo

//package com.book2s;

public class Main {
    public static void main(String[] argv) {
        String string = "book2s.com";
        int n = 2;
        System.out.println(lastNChars(string, n));
    }/* w  w w .  ja  v a2s  . c o  m*/
    public static String lastNChars(String string, int n) {
        int length = string.length();
        if (length <= n)
            return string;

        int startIndex = length - n;
        return string.substring(startIndex);
    }
}