Win a copy of Succeeding with AI this week in the Artificial Intelligence and Machine Learning forum!
  • 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Liutauras Vilda
  • Junilu Lacar
Sheriffs:
  • Tim Cooke
  • Jeanne Boyarsky
  • Knute Snortum
Saloon Keepers:
  • Stephan van Hulst
  • Tim Moores
  • Tim Holloway
  • Carey Brown
  • Piet Souris
Bartenders:
  • salvin francis
  • fred rosenberger
  • Frits Walraven

Casting

 
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
Can anyone please tell me why line 9 gives an error but line 10 doesn't. Isn't C1+=1 the same as C1=C1+1?
The explaination for the answer is:
"We can apply ++ operator on char values it will do increament on its ascii value i.e. it will make A to B.We can also apply += operator as it also do implicit casting.But the statement "c1=c1+1" is not valid as we required casting to store an int value into a variable of type char".
But I don't see why... it is that on line 9 the number 1 is converted to a character and on line 10 C1 is converted to an integer? If the number 1 on line 9 is an interger, is it possible to implicitly convert it to a character, so that it can be stored in C1 which is defined as a char?

1 class Char
2 {
3 public static void main(String arg[])
4 {
5 char c1,c2;
6 c1='A';
7 c1++;
8 c1+=1;
9 c1=c1+1;
10 c2='B';
11 c2--;
12 c2=c2-1;
13 }
14 }
Thanks,
 
Anthea Blake
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
Sorry... the line numbers are 8 and 9 not 9 and 10.
Thanks,
 
Ranch Hand
Posts: 219
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
8 c1+=1;
9 c1=c1+1;
Because of Assignment implicit conversion. The += uses implicit coversion. c1+=1 is equivalant to c1 = (char) (c1+1) So no problem. But when you use + operator both the operands will be converted to int. so c1+1 gives an int result which can not be coverted into char. That is why the error is.
 
Anthea Blake
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for your reply.
So does it mean that in the case.
C1 = (char)(C1+1), is (C1+1) evaluated to and integer and then cast down to a Character.? If this is the case, when is downcasting permitted and when is it not.?
 
Watchya got in that poodle gun? Anything for me? Or this tiny ad?
Two software engineers solve most of the world's problems in one K&R sized book
https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
    Bookmark Topic Watch Topic
  • New Topic