Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

doubt in primitive assignment...

 
Ganeshkumar cheekati
Ranch Hand
Posts: 362
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


my doubt is that:
1)eventhough i declare d as final why compilation error is coming in line1.

2)why it is giving compilation error in line 3.
 
Ankit Garg
Sheriff
Posts: 9521
22
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
1) it is giving error as you are assigning byte to char. Although char has a larger size than byte, but it cannot store negative values while byte can. So if byte has a negative value, then assigning it to char will result in a loss of the original value.

2) it is giving compilation error because when you multiply any data type below integer, the result is always an int.

eg

 
Ganeshkumar cheekati
Ranch Hand
Posts: 362
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i agree with your explanation about second doubt.
in case of first doubt:
i declared byte variable as final so i think it is a compile time constant so no casting is required in line1.

correct me if i am wrong...
 
Ankit Garg
Sheriff
Posts: 9521
22
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
but my dear the compile time constant has a negative value. So the statement will look like this to the compiler

char ch = -12; //not allowed

as you can see that you are trying to assign a negative value to a char data type which is not allowed...
 
subhasish nag
Ranch Hand
Posts: 101
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I suppose it will not give compiler error with the range of (0 to 127).
 
Ganeshkumar cheekati
Ranch Hand
Posts: 362
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
yes ankit you are right.
if i am giving positive values in the range 0 to 127 it is compiling fine.

thanks a lot..
 
Vaes Bart
Greenhorn
Posts: 13
Netbeans IDE Opera Suse
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Explicit casting will force it to compile, like this:


Trying to print it will give (on my machine) a "~".
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic