简体   繁体   中英

logic of java in-built method

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.. eg 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

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.

在此处输入图片说明

在此处输入图片说明

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.

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.

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 .

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM