-3

Possible Duplicate:
Resources for Java coding style?

So I picked java as my first language to learn and in the book I am reading they defined a variable like so

int  apples; 

apples  =  20; 

Then I went off on my own to try the example and wrote it like below and it still compiled without any errors and i didn't notice the difference until now.What I want to know is why the way i wrote it worked and which is the better way to write it so I don't start developing any bad habits. TY in advance =D

int Var=3;
4
  • google.com/… Commented Feb 4, 2013 at 17:37
  • 1
    don't concentrate on style until you've learnt what programming really is. Style will come naturally - plenty of good books to help you with that. :-) concentrate on programming first, style next. Commented Feb 4, 2013 at 17:40
  • Despite the title, it would appear the real focus of the question concerns combining the two statements into one. Is that the real intent? Commented Feb 4, 2013 at 17:45
  • 1
    dude first learn about what are keywords,identifiers and valid variable names.Conventions come later.You should at least know why your code worked. Commented Feb 4, 2013 at 17:45

3 Answers 3

1

Check out the code conventions for java.

Basically, camel case everything. Lower case starts off variables, methods and packages, upper case starts off classes.

Your two examples are both valid. The second form that declares and instantiates in one statement is a shortcut for the two separate lines in the first form.

Sign up to request clarification or add additional context in comments.

Comments

0

There is no useful difference between

int a;
a = 2;

and

int a = 2;

But the second is a preferred style over the first. From the official Java coding conventions:

Try to initialize local variables where they're declared. The only reason not to initialize a variable where it's declared is if the initial value depends on some computation occurring first.

Comments

0

Usually variables are lowercase "var" and types (classes,objects) are uppercase "Var"

Your example would be

int var = 3;

If Var were an object, it would be

Var var = new Var();

http://www.oracle.com/technetwork/java/javase/documentation/codeconvtoc-136057.html

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.