Java Variables
Java Variables
Run Anywhere.”
James Arthur Gosling
Machine code for PC Machine code for Apple Machine code for Linux
Here is an example Java program. It is about as small as a Java program can be. When
it runs, it writes Hello World! On the computer monitor. The details will be explained
later.
class Hello
{
public static void main ( String[] args )
{
System.out.println("Hello World!");
}
}
System.out.println("Hello World!");
System.out.println("Hello Java!");
All data in Java falls into one of two categories: primitive data and objects. There
are only eight primitive data types. However, Java has many types of objects, and
you can invent as many others as you need.
Any data type you invent will be a type of object.
boolea
byte short int long float double char
n
Here is an example of how you declare an integer variable called MyVariable in the
main method:
class Variables
{
public static void main(String[] args)
{
int myVariable;
}
}
If you want to declare more than 1 variable of the same type you must separate the
names with a comma.
class Variables
{
public static void main(String[] args)
{
int myInteger;
myInteger = 5;
String myString = "Hello";
}
}
You can print variables on the screen with System.out.println.
class Variables
{
public static void main(String[] args)
{
int myInteger = 5;
String myString = "Hello";
System.out.println(myInteger);
System.out.println(myString);
}
}
You can join things printed with System.out.println with a +.
class Variables
{
public static void main(String[] args)
{
int myInteger = 5;
System.out.println("The value of myInteger is " + myInteger);
}
}
The if else statement syntax looks like this:
if (condition is true)
{
Statement to execute if condition is true;
}
else
{
Statement to execute if condition is false;
}
The condition can contain any of the comparison operators,
sometimes called relational operators:
x == y // x equals y
x != y // x is not equal to y
int count = 0;
System.out.println( count ) ;
Homework #1
count = count + 1;
System.out.println( count ) ;
Exercise 9. Write a Java Program that calculates and
prints the next equation on the screen:
Homework #2
X2, if x ≥ -5
Y=
- X , in other cases
X=5 Y = 25
X = -10 Y = 10
Input data in the program
import java.util.Scanner;