Java Basics
Java Basics
each statement ends with a semicolon. Forget the semicolon and your Java program won’t
compile.
Types of variables
Java has three types of variables
Instance variables- are used to define attributes or the state for a particular object
Class variables- are similar to instance variables, except their values apply to all that class’s
instances (and to the class itself) rather than having different values for each object.
local variables.- are declared and used inside method definitions, for example, for index counters
in loops, as temporary variables, or to hold values that you need only inside the method
definition itself. They can also be used inside blocks ({}).
Declaring Variables
To use any variable in a Java program, you must first declare it. Variable declarations consist of
a type and a variable name:
int myAge;
String myName;
boolean isTired;
Example
Compute area of a circle
1 public class ComputeArea {
2 public static void main(String[] args) {
3 double radius; // Declare radius
4 double area; // Declare area
5
6 // Assign a radius
7 radius = 20; // radius is now 20
8
9 // Compute area
10 area = radius * radius * 3.14159;
11
12 // Display results
13 System.out.println("The area for the circle of radius " +
14 radius + " is " + area);
15 }
16 }
Variables such as radius and area correspond to memory locations. Every variable has a name, a
type, a size, and a value. Line 3 declares that radius can store a double value. The value is not
defined until you assign a value. Line 7 assigns 20 into variable radius. Similarly, line 4 declares
variable area, and line 10 assigns a value into area.
The plus sign (+) has two meanings: one for addition and the other for concatenating
(combining) strings. The plus sign (+) in lines 13–14 is called a string concatenation operator. It
combines two strings into one. If a string is combined with a number, the number is converted
into a string and concatenated with the other string. Therefore, the plus signs (+) in lines 13–14
concatenate strings into a longer string, which is then displayed in the output.