Basic Java Language: Difference between revisions

wikademia>Crossbow9
No edit summary
wikademia>Crossbow9
Line 41: Line 41:
==Declaring Variables==
==Declaring Variables==
In a nutshell, declaring a variable has this syntax:
In a nutshell, declaring a variable has this syntax:
<pre> [variable type] [identifier]</pre>
<pre> [variable type] [identifier];</pre>
This works for both reference variables and primitive variables. [variable type] is the type of variable, like '''int''' or '''char'''. [identifier] is the name for the variable you wish to create, for example, ''password'' or ''number_of_fish''. If you wanted to create a '''int''' variable called ''age'', you would type this:
This works for both reference variables and primitive variables. [variable type] is the type of variable, like '''int''' or '''char'''. [identifier] is the name for the variable you wish to create, for example, ''password'' or ''number_of_fish''. If you wanted to create a '''int''' variable called ''age'', you would type this:
<pre>int age</pre>
<pre>int age;</pre>
Notice the semicolon at the end of the statement. All statements in Java must end in this, otherwise you will get a compiler error.


You can set the values of variables while declaring them, like this:
<pre>int age = 100;</pre>
===Identifiers===
There are several rules for the naming of your variables. Identifiers can be named using all the letters from A through Z (capital or lowercase, you choose), numbers 0-9 and underscore _ and the dollar sign $. The first character of the identifier cannot be a number, but it can be a letter, _ or $.
You can't create two variables with the same identifier, all identifiers must be unique. You also can't use an identifier that is a Java keyword. Here is a list of all the [http://en.wikipedia.org/wiki/Java_keywords Java Keywords]
===Statements===
A statement in Java is generally a line of code that does something. Statements are ended by a semicolon ;. An example of a statement is the declarationg of a variable like we saw before. Another example you will recall from the "Hello World" program we made in Lesson 1.
<pre>System.out.println("Hello World");</pre>
This line of code prints ''Hello World'' onto the console.




[[Topic:Java|Back to Java Main Page]]
[[Topic:Java|Back to Java Main Page]]