• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

strings

 
Neha Sawant
Ranch Hand
Posts: 204
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all'
int index=1;
String a[]=new String(5);
String b=a[index];//1
S.o.p(b);
It prints null
but i thought there will be a compiler error at line 1 b is not of the type []
Thanks in advance
Neha
 
Fei Ng
Ranch Hand
Posts: 1245
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Neha Sawant:
Hi all'
int index=1;
String a[]=new String(5);
String b=a[index];//1
S.o.p(b);
It prints null
but i thought there will be a compiler error at line 1 b is not of the type []
Thanks in advance
Neha

Maybe i don't understand your question, buy anyway...
String b=a[index];//1
String assign to a String, nothing wrong with line one //1.
a[index] is a String Object. And b is a String reference.
So, b has null now. I think it works ok.
 
Jane Griscti
Ranch Hand
Posts: 3141
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Neha,
<code>
String a[]=new String(5);
</code>
Here you are declaring a String array a[] and initializing it to hold 5 String objects.
The default value of all objects, including String objects, is null.
So a[0] points to a 'null' object, a[1] points to a 'null' object, etc.
Hope that helps.
------------------
Jane Griscti
Sun Certified Programmer for the Java� 2 Platform
Co-author Mike Meyers' Java 2 Certification Passport
[This message has been edited by Jane Griscti (edited December 02, 2001).]
 
Neha Sawant
Ranch Hand
Posts: 204
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanx Feing and Jane.
I was under the impression that a being of type array[] how it can be assigned to a plain string type.
But after Jane's explanation i realised that it is not the entire [] that is assigned but just a[1] that is assigned to string b.
Thanx once again
Neha.
 
Uma Viswanathan
Ranch Hand
Posts: 126
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A minute one to note:
String a[]=new String(5);
Will give compiler error.
 
Tony Sam
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Uma Viswanathan:
A minute one to note:
String a[]=new String(5);
Will give compiler error.

Of course,it may be String a[]=new String[5],but as you know ,it's not the main point
 
Uma Viswanathan
Ranch Hand
Posts: 126
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey...that's why without touching the main subject, just pointed out...
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic