Hardik Vats Hardik Vats - 1 month ago 4x
Java Question

Accessing characters of a String beyond the range of Integer

I have a

sequence that is being repeated infinitesimally... Naturally ,characters will go out of range of Integer and start falling into range of Long, since methods used for accessing characters for both String as well as
class all require an
int "index"
how do I access these characters at say ,
Long long>Intger.MAX_VALUE
. is there a way to override these methods such as
charAt(int index)
so that they start "accepting " long arguments ,if not so , how can I access the characters at this index, considered conversion to character array using
method but then again, array length can only be upto
. Is there a
type that I'm not aware of which accepts long arguments?


You should definitely not construct a string and do measurements on it.

This is a test on how well you are able to abstract things. I will give you some code you may study. You should not copy+paste it for several reasons - including the possibility that I did some mistake.

The idea is, to simply compute the information, which is possible because we have a simple repetition pattern.

class RepeatedString {
    private String s;
    public RepeatedString(String s) {this.s = s;}

    public char charAt(long i) {
      return s.charAt((int)(i % s.length()));

    public long count(char c, long i) {
      long n = 0;
      // how many complete repetitions?
        long r = i / s.length();
        if (r > 0) {
          // count c in s
          for (int j = 0 ; j < s.length() ; j++) n += s.charAt(j) == c ? 1 : 0;
          n *= r;
      // how many c in last repitition
        long l = i % s.length();
        for (int j = 0 ; j < l ; j++) n += s.charAt(j) == c ? 1 : 0;
      return n;

class Kata {

  public static void main(String[] args) {
    RepeatedString s = new RepeatedString("bla");

    System.out.println(s.charAt(1)); // expected 'l'
    System.out.println(s.charAt(6)); // expected 'b'

    System.out.println(s.count('a', 19)); // expected 6
    System.out.println(s.count('a', 21)); // expected 7