Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

New to Java  RSS feed

 
Dave Morley
Ranch Hand
Posts: 38
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Good Day.

I have a question that is probably very easy for most of you but I am struggling to understand it. Please try to make the answer user friendly !!!

when declaring variables i have been told to do the following:

public class DonnaApplet extends applet implements Actionlistener{

// declaring variables
String firstName, lastName;
int size,content,delivery,organization,rank;
float totalContent = 0;

my question is this, why do you have to set totalContent to 0. I understand that this will be an answer after the program is run but size , content etc have no initial value but totalContent does.

Thank you in advance.
DM

trying to understand???
 
ankur rathi
Ranch Hand
Posts: 3830
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It is just to make program readable ...

If you will not initialize a instance variable then also they will get initialize automatically at the time of instantiatiating a class ( making a object of a class ) .

hope it will help .
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sometimes the compiler will warn you that a variable may not have been initialized when you use the variable in some method. Putting the 0 makes that warning go away. It's still your job to make sure it was initialized correctly.
 
ankur rathi
Ranch Hand
Posts: 3830
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Stan James:
Sometimes the compiler will warn you that a variable may not have been initialized when you use the variable in some method.


No but I dont think that compiler will give any error at the time when you are not initializing a instance variable . It will only give error if you will try to use local variable without initialize .
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!