Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Why Error Here?

 
Joe Harry
Ranch Hand
Posts: 10124
3
Eclipse IDE Mac PPC Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Ranchers,

Code below,


Why a complie time error?

Regards,
Jothi Shankar Kumar. S
 
William Yan
Ranch Hand
Posts: 69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi, you mean this? or?
 
Joe Harry
Ranch Hand
Posts: 10124
3
Eclipse IDE Mac PPC Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Above,

I mean the other way,
char c = 'H';
String s = "ello";
c = c + s; //why it gives error here?

Regards,
Jothi Shankar Kumar. S
 
Gowher Naik
Ranch Hand
Posts: 643
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

I have made single change in your code.
Try to find out yourself why there is error.
 
William Yan
Ranch Hand
Posts: 69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
char is a primitive with 16-bits, why do you think you could stored so fat a String into a char?
 
srini p.
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Latest exam for SCWCD is Exam cx-310-081(SCWCD using J2EE 1.4)

Best book to pass SCWCD is Head First Servlet & JSP by
Bryan Basham,Kethy Sierra & Bert Bates


Hi Kumar,

public void amethod(String s){
char c='H';
c+=s;
System.out.println(c); }

If U observe the code, you are tiring to concatenate a String to char. U can't use "+" operator on a char data (i.e c).

replace the method with
public void amethod(String s){
char c='H';
s+=c;
System.out.println(s); }
It will work !!

Regards,
Srinivas.
 
Joe Harry
Ranch Hand
Posts: 10124
3
Eclipse IDE Mac PPC Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all Above,

So a char fits into a String but not the other way. Am I right?

Regards,
Jothi Shankar Kumar. S
 
William Yan
Ranch Hand
Posts: 69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, Jothi,
char is a primitive, but a String is 'like' an array of char.
 
Anvi Dixit
Ranch Hand
Posts: 45
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,

yes the below code is compiling fine but why i am getting the exception
saying : Exception in thread "main" java.lang.NoClassDefFound error

public void amethod(String s){
char c='H';
c+=s;
System.out.println(c); }

If U observe the code, you are tiring to concatenate a String to char. U can't use "+" operator on a char data (i.e c).

replace the method with
public void amethod(String s){
char c='H';
s+=c;
System.out.println(s); }

PLease help me out .
Thanks
Anvi
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic