• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

char

 
Kunal Choudhary
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
public class testoperator
{

public static void main(String args[])
{

int y=3;
char x='a';

x=x+1;
y=y+1;

System.out.println("Value of x is " + x);
System.out.println("Value of y is " + y);


}


}
why does it give an error and how to solve it???
 
Vikas Kapoor
Ranch Hand
Posts: 1374
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What compiler complains about? That's sufficient to understand the problem and to solve too.
 
Vikas Kapoor
Ranch Hand
Posts: 1374
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please make sure you enclose your any code with CODE tag. That gives ease in reading a post.
 
fred rosenberger
lowercase baba
Bartender
Posts: 12143
30
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Kunal,

If you compile and run this, and it give you a compiler error, it GREATLY helps people figure out the problem if you post the EXACT text of that error message. It tells you all kinds of things, including where it thinks the error is (although it is sometimes wrong).

Without that, people have to really study the code, or copy it into their environment and compile it themselves. Even then they can't be sure, because it could be a problem with your environment.

so help us help you - tell us what the error is.
 
Rob Spoor
Sheriff
Pie
Posts: 20546
56
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Kunal Choudhary wrote:char x='a';

x=x+1;

The result of any mathematical operation where both operands are byte, char, short or int is always of type int.
In this case:
x: char
1: int
x + 1: int

There are three ways to solve this:

The first explicitly casts the int result back to a char, whereas the increment operators have an implicit casting internally.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic