• Post Reply Bookmark Topic Watch Topic
  • New Topic

Casting Primitives  RSS feed

 
Kaur Manpreet
Ranch Hand
Posts: 30
Java Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,

In the following program if line 1 is uncommented the code throws a compile time error, whereas if line 1 is replaced by Line 2 and Line 3 it works absolutely fine and displays the value of a:5 b:23 c:28


Doubt: If I have understood the concept, is the reason why line 1 doesn't work is because the variable c is not initialized in the main method. And not because the explicit cast is required.

Thanks

added code tags, please read UseCodeTags
 
Henry Wong
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Kaur Manpreet wrote:Hi All,

In the following program if line 1 is uncommented the code throws a compile time error, whereas if line 1 is replaced by Line 2 and Line 3 it works absolutely fine and displays the value of a:5 b:23 c:28

class ExplicitCast
{
public static void main(String[] args)
{
byte a = 5, b=23;
// byte c += a+b; // Line 1
byte c = 0; // Line 2
c+= a + b; // Line 3
System.out.println("a: "+a+" b: "+b+" c: "+c);
}
}

Doubt: If I have understood the concept, is the reason why line 1 doesn't work is because the variable c is not initialized in the main method. And not because the explicit cast is required.

Thanks


It's defined in the specification that way. Declarations do not support compound statements for initialization.

Henry
 
Kaur Manpreet
Ranch Hand
Posts: 30
Java Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Henry
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!