1

can anyone tell me , where can I find the logic of java in-built String methods like length() , tocharArray(), charAt() , etc... I have tried decompiler on String.class but found no logic their. I want to a code to count the number of characters of a String without using any in-built String class but I am unable to crack the idea of how to break String into set of characters without using String in-built method.. e.g. String str = "hello"; how to convert this String into

'h' ,  'e' ,  'l' , 'l' , 'o' 

and this is not any homework assignment...

please help with regards, himanshu

MrT
  • 594
  • 2
  • 17

5 Answers5

1

Built-in libraries source code is available with JDK.

The JDK folder would contain src.zip which contain the sources for the built-in libraries.

enter image description here

enter image description here

Uma Kanth
  • 5,659
  • 2
  • 20
  • 41
0

I always used http://grepcode.com. It usually has source code of methods/objects I'm looking for. Here is GC for String class String.length()

EDIT: As for your second question, how to calculate String length. I would use String.toCharArray(). I hope you can calculate length of an array.

Sok Pomaranczowy
  • 993
  • 3
  • 12
  • 32
0

Whole string data is kept in a private char array field.

length() is just:

  public int length()
  {
       return this.value.length;
  }

And charAt(int) isn't much more complicated:

public char charAt(int paramInt)
{
    if ((paramInt < 0) || (paramInt >= this.value.length)) {
      throw new StringIndexOutOfBoundsException(paramInt);
    }
    return this.value[paramInt];
}

The method you are looking for separation String chars is toCharArray()

If you want to decomplie .class files try using: http://jd.benow.ca/ It has both GUI application and Eclipse IDE plugin.

itwasntme
  • 1,442
  • 4
  • 21
  • 28
0

You can view OpenJDK source code online. Make sure you're looking at the right version of the code (library version and revision).

For example, here's the code of toCharArray() of jdk8:

public char[] toCharArray() {
    // Cannot use Arrays.copyOf because of class initialization order issues
    char result[] = new char[value.length];
    System.arraycopy(value, 0, result, 0, value.length);
    return result;
}

Here's charAt(int index):

public char charAt(int index) {
    if ((index < 0) || (index >= value.length)) {
        throw new StringIndexOutOfBoundsException(index);
    }
    return value[index];
}

You can find the source code of String class here.

naktinis
  • 3,957
  • 3
  • 36
  • 52
0

You can't work with a String without using - directly or indirectly - its methods. For example, you can iterate over string characters using charAt(int index) or create a StringBuilder(String s) (which calls String.length() internally).

pkalinow
  • 1,619
  • 1
  • 17
  • 43