Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / June 2008

Tip: Looking for answers? Try searching our database.

compiler question

Thread view: 
ankur - 29 Jun 2008 19:25 GMT
This code snippet will compile and run as given below:

public class TooSmartClass {
   public static void main(String[] args) {
    int weight = 10, thePrice;                         // Local
variables
      // int weight = 10, thePrice = 0;                     // Local
variables

       if (weight <  10) thePrice = 1000;
       if (weight >  50) thePrice = 5000;
       if (weight >= 10) thePrice = weight*10;            // Always
executed.
      // System.out.println("The price is: " + thePrice);   // (1)
   }
}

But will not compile as given below:

public class TooSmartClass {
   public static void main(String[] args) {
    int weight = 10, thePrice;                         // Local
variables
      // int weight = 10, thePrice = 0;                     // Local
variables

       if (weight <  10) thePrice = 1000;
       if (weight >  50) thePrice = 5000;
       if (weight >= 10) thePrice = weight*10;            // Always
executed.
         System.out.println("The price is: " + thePrice);   // (1)
   }
}

Error : C:\Java Files>javac TooSmartClass.java
TooSmartClass.java:10: variable thePrice might not have been
initialized
       System.out.println("The price is: " + thePrice);   // (1)
                                             ^
1 error

Why so ?? Because thePrice is not initialized in both the scenarios !

Thanks,
Ankur
Manish Pandit - 29 Jun 2008 20:36 GMT
> This code snippet will compile and run as given below:
>
[quoted text clipped - 43 lines]
> Thanks,
> Ankur

That is because a local variable is not defaulted like the class
variables (boolean is false, int is zero...etc.). You are assigning
values to thePrice based on the weight, but since there is no default
value for that variable, java complains when you try to *access* it.
It is not just the System.out.println, even if you do something like

int xyz = thePrice+20;

it will throw the same compile error.

-cheers,
Manish
Roedy Green - 29 Jun 2008 20:45 GMT
Sun, 29 Jun 2008 11:25:56 -0700 (PDT), ankur
<ankur.a.agarwal@gmail.com> wrote, quoted or indirectly quoted someone
who said :

>    if (weight <  10) thePrice = 1000;
>        if (weight >  50) thePrice = 5000;
>        if (weight >= 10) thePrice = weight*10;            // Always
>executed.
>          System.out.println("The price is: " + thePrice);   // (1)

You are presuming greater intelligence of the compiler than it has.

Is sees this blurrily something ilke

 if ( somethingoroother ) assign price
if ( somethingelse ) assign price
if (yetanothingh thing) assign price

Had you written this as:

 if (weight <  10)
  {
  thePrice = 1000;
  }
else   if (weight >  50)  
  {  
  thePrice = 5000;
  }
else
 {
  thePrice = weight*10;
  }

Then it could be absolutely sure thePrice will be assigned. It does
not have to analyse the conditional expressions to know this.

Signature

Roedy Green Canadian Mind Products
The Java Glossary
http://mindprod.com

Maarten Bodewes - 30 Jun 2008 00:19 GMT
>  Sun, 29 Jun 2008 11:25:56 -0700 (PDT), ankur
> <ankur.a.agarwal@gmail.com> wrote, quoted or indirectly quoted someone
[quoted text clipped - 31 lines]
> Then it could be absolutely sure thePrice will be assigned. It does
> not have to analyse the conditional expressions to know this.

Yup, and to be sure that your variable will only be assigned precisely
once, create it using the final keyword.

final int thePrice;
if(..) thePrice = 1;
else thePrice = 2;

This will throw a compiler error whenever thePrice is not assigned, or
when thePrice is assigned a second time. Much more secure.

Note that I would not use two assignments in one line, it's less
readable and harder to work with in the debugger.

Regards,
Maarten
Arne Vajhøj - 30 Jun 2008 00:32 GMT
>>  Sun, 29 Jun 2008 11:25:56 -0700 (PDT), ankur
>> <ankur.a.agarwal@gmail.com> wrote, quoted or indirectly quoted someone
[quoted text clipped - 41 lines]
> Note that I would not use two assignments in one line, it's less
> readable and harder to work with in the debugger.

When it comes to style I would recommend Java Coding Convention
from SUN.

The above is not compliant.

Arne
Maarten Bodewes - 30 Jun 2008 20:05 GMT
>>>  Sun, 29 Jun 2008 11:25:56 -0700 (PDT), ankur
>>> <ankur.a.agarwal@gmail.com> wrote, quoted or indirectly quoted someone
[quoted text clipped - 46 lines]
>
> The above is not compliant.

Absolutely! My only possible way of explaining myself is not having the
Eclipse checkstyle plugin working on my Thunderbird client :)

Maarten
John B. Matthews - 30 Jun 2008 04:00 GMT
[...]
> Yup, and to be sure that your variable will only be assigned precisely
> once, create it using the final keyword.
[quoted text clipped - 5 lines]
> This will throw a compiler error whenever thePrice is not assigned, or
> when thePrice is assigned a second time. Much more secure.

Aha, I had seen this in Roedy's and others' code without fully
understanding its import. I'm a fan of letting the compiler do the
work:-) Thanks!

[...]
Signature

John B. Matthews
trashgod at gmail dot com
home dot woh dot rr dot com slash jbmatthews

Roedy Green - 30 Jun 2008 23:31 GMT
On Sun, 29 Jun 2008 23:00:31 -0400, "John B. Matthews"
<nospam@nospam.com> wrote, quoted or indirectly quoted someone who
said :

>Aha, I had seen this in Roedy's and others' code without fully
>understanding its import. I'm a fan of letting the compiler do the
>work:-) Thanks!

I am a great fan of final. See http://mindprod.com/jgloss/final.html
for why.
Signature


Roedy Green Canadian Mind Products
The Java Glossary
http://mindprod.com



Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.