Escolar Documentos
Profissional Documentos
Cultura Documentos
Expressions II
Outline
Java Data Types
Variables and Assignment
Expressions
Data Conversion
Interactive Programs
variables
A variable is a name for a
location in memory that holds a
value
variable declaration specifies the variable's name and its type of information
variable initialization variable should be given initial value before used else error
int num;
int sum = 0;
int base = 32, max = 149;
total = 55;
Example 1 : variables declaration
//********************************************************************
// PianoKeys.java Author: Lewis/Loftus
//
// Demonstrates the declaration, initialization, and use of an
// integer variable.
//********************************************************************
}
}
Example 3 : variables assignment
//********************************************************************
// Geometry.java Author: Lewis/Loftus
// Demonstrates the use and effect of an assignment statement
//********************************************************************
public class Geometry
{
//-----------------------------------------------------------------
// Prints the number of sides of several geometric shapes.
//-----------------------------------------------------------------
public static void main (String[] args)
{
int sides = 7; // declaration with initialization
System.out.println ("A heptagon has " + sides + " sides.");
sides = 12;
System.out.println ("A dodecagon has " + sides + " sides.");
} Output
}
A heptagon has 7 sides.
A decagon has 10 sides.
a dodecagon has 12 sides.
Identifiers name of a class, variable,
constant and method
private throw
protected throws
public transient
return try
short void
static volatile
super while
native switch
new synchronized
Package this
constant an identifier that holds the same
value during its entire existence –
cannot be reassigned
2.In the program you created in Exercise 1, try leaving the fields
uninitialized and print out their values. Try the same with a local
variable and see what kind of compiler errors you can produce.
Becoming familiar with common compiler errors will make it easier to
recognize bugs in your code.