/*
Here is another short example.
Call this file "Example2.java".
*/
class Example2 {
public static void main(String args []) {
int num; // this declares a variable called num
num = 100; // this assigns num the value 100
System.out.println("This is num: " + num);
num = num * 2;
System.out.print("The value of num * 2 is ");
System.out.println(num);
}
}
When you run this program you will see like this output;
This is num: 100
The value of num * 2 is 200
Let's take a close look at why this output is generated.
The first new line in this program ,
int num; // this declares a variable called num
This line declares an integer variable called num. Java requires that variables be declared before they are used. The declaration form is,
type var-name;
Here, type specifies the type of variable being declared, and var-name is the name of the variable.
The next line is;
num = 100; // this assigns num the value 100
Assigns to num the value 100. In Java, the assignment operator is a single equal sign.
The next line in the program,
System.out.println("This is num: " + num);
In this statement, the plus sign causes the value of num to be appended to the string that
precedes it, and then the resulting string is output. (Actually, num is first converted from an integer into its string equivalent and then concatenated with the string that precedes it).
Using the + operator, you can join together as many items as you want within a single
println( ) statement.
The next line of code assigns num the value of num times 2.
num = num * 2;
Java uses the * operator to indicate multiplication.
Here are the next two lines in this program;
System.out.print("The value of num * 2 is ");
System.out.println(num);
The print( ) method is just like println( ), except that it does not output a newline character after each call. So, the built-in method print( ) is used to display the string "The value of num*2 is". This string is not followed by a newline. This means that when the next output is generated, it will start on the same line.
Wednesday, February 25, 2015
Subscribe to:
Post Comments (Atom)
0 comments:
Post a Comment