• 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
  • Tim Cooke
  • paul wheaton
  • Ron McLeod
  • Jeanne Boyarsky
Sheriffs:
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
Bartenders:

Char and Ints

 
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Can any one explain
public class chchar
{
public static void main(String str)
{
char c='a';
int i =2;
c=c+i;
System.out.println(c);
}
}
gives you an error but
public class chchar
{
public static void main(String str)
{
char c='a';
int i =2;
c+=i;
System.out.println(c);
}
}
Works fine.
What is the diffrence?
 
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
For c = c + i,
it is doing as c = (int) c + i;
assigning an int to a char is not allowed without explicit cast unless the int is a final
For c += i,
it is doing as c = (char) c + i;
so it is alright.
 
Ranch Hand
Posts: 39
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The diff is simple
c+=i;
is treated as:
c = (char)(c+i);
Since the result of c+i is an int it requires an explicit cast. In the first code u havent provided this cast so compiler complains. But as u see above in the second case the cast is implied implicitly.
Remember this point. It is very imp for SCJP exam
-Aj
 
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Its the way the two assignments work:
When you use c += b, behind the scenes, this is what is actually happening (char)(c+b).
So the casting is taken care by JVM for you.
However in the first case, you are adding a char and a byte. This will return an int which who are assigning to a char variable. causing it to complain.
Trust this helps.
 
I'm THIS CLOSE to ruling the world! Right after reading this tiny ad:
Clean our rivers and oceans from home
https://www.kickstarter.com/projects/paulwheaton/willow-feeders
reply
    Bookmark Topic Watch Topic
  • New Topic