• 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
  • Devaka Cooray
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Jeanne Boyarsky
  • Tim Cooke
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Tim Moores
  • Mikalai Zaikin
  • Carey Brown
Bartenders:

Casting Primitives

 
Ranch Hand
Posts: 30
Oracle Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
author
Posts: 23942
142
jQuery Eclipse IDE Firefox Browser VI Editor C++ Chrome Java Linux Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
Oracle Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks Henry
 
I was her plaything! And so was this tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic