• 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
  • Tim Cooke
  • Ron McLeod
  • Jeanne Boyarsky
  • Paul Clapham
Sheriffs:
  • Liutauras Vilda
  • Henry Wong
  • Devaka Cooray
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Al Hobbs
  • Carey Brown
Bartenders:
  • Piet Souris
  • Mikalai Zaikin
  • Himai Minh

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: 23923
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
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic