Although
hello.java is simple, but it displays important basic structure of
JAVA program.
After
the first 2 classes, I assume you already knew that
1. A program needs a class definition , like class className.
2. A main method in a class is the start point for program.
3. File should be save as className.java.
4. Statement should be ended with ;.
Variables
Let's us count how many cars you and your little
brothers have. Then calculate how many cars in total.
class car_count
{
public static void main(String[] args)
{
int His_Cars=30;
int My_Cars=40;
int TotallCars=His_Cars+My_Cars;
System.out.println("Total books we have="+TotallCars);
}
}
Look at the above code for a while. You may notice
something new: int
I use variables to store information. They are called variables because
the information stored there might change during program execution. His_Cars and My_Cars are
variables.
Just imagine I have a lot of pockets(variables)
for you to use. First you should name a pocket (Computer
guru says: define a variable) and then you put a something
into that pocket(Computer guru says: assign
value to variable).
Just like pockets may have different shapes, variables have different
kinds too. In this tutorial, we are gonna learn 4 different variables: int ,double,
boolean and String.
When you want to use variables, please remember the following rules:
1. First character of variable must be a letter,
an underscore(_) or a dollar sign($).
2. You cannot use a word reserved by JAVA (for example, you can
not have a variable named main or
one named System).
| Variables |
Description |
Example |
| int |
represent whole, non-decimal,
numbers. Such as 100,-15,2 |
int myAge;
myAge=10;
int NoOfToys=20; |
| double |
store numbers with decimal points. |
double priceOfToy;
priceofToy=25.51; |
| boolean |
have one of two values: true or
false. |
boolean isRainingNow;
isRainingNow=false; |
| String |
store a group of letters |
String myName;
myName="JAVA boy"; |
Compile the above code, how many cars in total? |