• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Strings

 
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Is the following valid:
String s = "Hello";
char c = s[2];
I don't think so.
 
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Frank,
The current statements are not valid.
>> String s = "Hello";
>> char c = s[2];
First you create a String object and you initialize it with the value "Hello", and this is correct.
But then then you create a variable of the primitive type char and you initialize with something invalid with Java. The java compiler while evaluate the expression "s[2]" like this: "s is an array of object and I need to take the third element of this array but... hey wait a second... s is a String object, not an array!"
The way Java manage char and String is totally different than C. Basically because a String is an object, not a type. There`s some methods in the String object to do what you're looking for. Here, take a look at this piece of code :
...
String s = "Hello!";
char c1 = s.charAt(2);
char c2 = s.toCharArray()[2];
...
This is two way of doing what you wanted, but the first one is more efficient.
Have fun with Java!
J-C
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic