aspose file tools*
The moose likes Beginning Java and the fly likes TYPE CASTING Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of JavaScript Promises Essentials this week in the JavaScript forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "TYPE CASTING" Watch "TYPE CASTING" New topic
Author

TYPE CASTING

Sadashiv Borkar
Ranch Hand

Joined: Jun 07, 2000
Posts: 49
class Chartype{
public static void main(String argv[] )
{
Conv c=new Conv();
String s=new String("ello");
c.amethod(s);
}
public void amethod(String s)
{
char c='H';
// c = c + s;
s = c + s;
System.out.println(s);
}
}
The Above Programe works fine if Compiled and run but the output given is just "H".
But i remove the above comment (c=c+s) then it gives a compilation error.
Please reply Iam confused as according to me should give a type conversion error saying that the primitive datatype cannot be converted to String data type.
Mohan Ramanna
Ranch Hand

Joined: Jun 26, 2000
Posts: 36
class Chartype{
public static void main(String argv[] )
{
Chartype c = new Chartype();
String s = new String("ello");
c.amethod(s);
}
public void amethod(String s)
{
char c='H';
//c = c + s;
s = c + s;
System.out.println(c);
System.out.println(s);
}
}
sudhakar the code if not commented gives the error cannot
convert char to java.lang.string if commented gives output H
and Hello on executed.
Sadashiv Borkar
Ranch Hand

Joined: Jun 07, 2000
Posts: 49
class Chartype{
public static void main(String argv[] )
{
Chartype c = new Chartype();
String s = new String("ello");
c.amethod(s);
}
public void amethod(String s)
{
char c='H';
s = c + s;
System.out.println(s);
}
}
I think you didnot understand the question clearly...
Now see the above code .The above code works fine if Iam compiling it and gives me an output as H.....Ok..If you see above code clearly you will find that there is a char variable declared above. "According to me when Iam adding a char to a string it should give me an error saying that you cannot convert a char to a string"....
Now see the code Below
class Chartype{
public static void main(String argv[] )
{
Chartype c = new Chartype();
String s = new String("ello");
c.amethod(s);
}
public void amethod(String s)
{
char c='H';
c = c + s;
System.out.println(c);
}
}
If you see the above code you will find that now it gives me an
compilation error Of TypeCAsting Now I think you can clarify my doubt...
Thanks in Advance...
chao
Ling Wu
Ranch Hand

Joined: Jul 19, 2000
Posts: 184
Your first set of code should give you a print out of "Hello" and the second set will receive a compile error of "incompatible types"
You can add a char to a String, but you cannot add a String to a char. That's why you don't receive a compile error with the first one. I'm not sure about the reason. Mayby it's because String is an array of chars?
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: TYPE CASTING