• Post Reply Bookmark Topic Watch Topic
  • New Topic

Retrieving a character from String  RSS feed

 
Niki Kulkarni
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Everyone,

String charAt() method returns a particular Character at the specified index in the String.

How is this function implemented internally?. How a particular character can be retrieved from String?.

Thanks for your time.
 
Clif Boyd
Greenhorn
Posts: 5
IntelliJ IDE Java
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
My understanding is that Strings are really char arrays, wrapped inside of a class called "String". So charAt() just returns the char, at the index indicated, in the char array hidden in the String object.
 
Paweł Baczyński
Bartender
Posts: 2075
44
Firefox Browser IntelliJ IDE Java Linux Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you look at the source code of String class, you'll see that indeed it holds char[] internally. But it doesn't have to. You don't need this and should't rely on this.
This is what is called encapsulation. You don't need to know how the class is working internally. You know that charAt() returns a char at given index and that's all you need.
They might change internals of String in some future release and you wouldn't even notice. Because charAt() method's behaviour won't change.
 
Niki Kulkarni
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Pawel and Clif
 
Winston Gutkowski
Bartender
Posts: 10575
66
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Niki Kulkarni wrote:String charAt() method returns a particular Character at the specified index in the String.

No it doesn't, it returns the char at the specified index.

'char' is a Java primitive, 'Character' (with a capital 'C') is an object (specifically, a java.lang.Character (←click)).

Sorry if it sounds nitpicky, but case and spelling are very important when you're writing programs, so be aware of them.

HIH

Winston
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!