Java Variables Types
Java Variables Types
Types
ICT Grade 10
Variables
• What is a variable?
• The name of some location of memory used to hold a data value
• Different types of data require different amounts of memory. The compiler’s job
is to reserve sufficient memory
• Variables need to be declared once
• Variables are assigned values, and these values may be changed later
• Each variable has a type, and operations can only be performed between
compatible types
3 width
• Example 4 height
12 area
int width = 3;
int height = 4;
int area = width * height;
width = 6;
area = width * height;
6 3 width
4 height
24 12 area
Data declaration syntax
◇ The syntax for the declaration of a variable is:
◇ Data type identifier;
◇ “data type” may be the name of a class, as we have seen,
or may be one of the simple types, which we’ll see in a
moment
◇ “identifier” is a legal Java identifier; the rules for simple
variable identifiers are the same as those for object
identifiers
Variable declaration: examples
◇ For example:
int age; // int means integer
double cashAmount; // double is a real #
◇ We can also declare multiple variables of the same type
using a single instruction; for example:
int num1, num2, num3; // or
int num1,
num2,
num3;
◇ The second way is preferable, because it’s easier to
document the purpose of each variable this way.
Identifiers
◇ An identifier is a sequence of characters that consist of
letters, digits, underscores (_), and dollar signs ($).
◇ An identifier must start with a letter, an underscore (_),
or a dollar sign ($). It cannot start with a digit.
◇ An identifier cannot be a reserved word. (See Appendix A,
“Java Keywords,” for a list of reserved words).
◇ An identifier cannot be true, false, or
null.
◇ An identifier can be of any length.
Variable Names
• Valid Variable Names: These rules apply to all Java names, or
identifiers, including methods and class names
• Starts with: a letter (a-z or A-Z), dollar sign ($), or underscore (_)
• Followed by: zero or more letters, dollar signs, underscores, or
digits (0-9).
• Uppercase and lowercase are different (total ≠ Total ≠ TOTAL)
• Cannot be any of the reserved names. These are special names
(keywords) reserved for the compiler. Examples:
class, float, int, if, then, else, do, public, private, void, …
Good Variable Names
• Choosing Good Names Not all valid variable names are good variable names
• Some guidelines:
• Do not use `$’ (it is reserved for special system names.)
• Avoid names that are identical other than differences in case (total, Total, and
TOTAL).
• Use meaningful names, but avoid excessive length
• crItm Too short
• theCurrentItemBeingProcessed Too long
• currentItem Just right
• Camel case capitalization style
• In Java we use camel case
• Variables and methods start with lower case
• dataList2 myFavoriteMartian showMeTheMoney
• Classes start with uppercase
• String JOptionPane MyFavoriteClass
Valid/Invalid Identifiers
Valid:
$$_ Valid but not recommended. Not a descriptive variable
R2D2 Valid but not recommended. Not a descriptive variable
INT okay. “int” is reserved, but case is different here
_dogma_95_
riteOnThru
SchultzieVonWienerschnitzelIII Valid but too long
Invalid:
30DayAbs starts with a digit
2 starts with a digit
pork&beans `&’ is illegal
private reserved name
C-3PO `-’ is illegal
JAVA KEYWORDS
9
Primitive Data Types
• Java’s basic data types:
• Integer Types:
• byte 1 byte Range: -128 to +127
• short 2 bytes Range: roughly -32 thousand to +32 thousand
• int 4 bytes Range: roughly -2 billion to +2 billion
• long 8 bytes Range: Huge!
• Floating-Point Types (for real numbers)
• float 4 bytes Roughly 7 digits of precision
• double 8 bytes Roughly 15 digits of precision
• Other types:
• boolean 1 byte {true, false} (Used in logic expressions and conditions)
• char 2 bytes A single (Unicode) character
• String is not a primitive data type (they are objects)
Numeric Constants (Literals)
• Specifying constants: (also called literals) for primitive data types.
Integer Types:
byte
short optional sign and digits (0-9): 12 -1 +234 0 1234567
int
long Same as above, but followed by ‘L’ or ‘l’: -1394382953L
Note: By default, integer constants are int, unless ‘L’/‘l’ is used to indicate
they are long. Floating constants are double, unless ‘F’/‘f’ is used to
indicate they are float.
Character and String Constants
• char constants: Single character enclosed in single quotes (‘…’) including:
• letters and digits: ‘A’, ‘B’, ‘C’, …, ‘a’, ‘b’, ‘c’, …, ‘0’, ‘1’, …, ‘9’
• punctuation symbols: ‘*’, ‘#’, ‘@’, ‘$’ (except single quote and backslash ‘\’)
• escape sequences: (see below)
• String constants: Zero or more characters enclosed in double quotes (“…”)
• (same as above, but may not include a double quote or backslash)
• Escape sequences: Allows us to include single/double quotes and other special
characters:
\” double quote \n new-line character (start a new line)
\’ single quote \t tab character
\\ backslash
• Examples: char x = ’\’’ → (x contains a single quote)
”\”Hi there!\”” → ”Hi there!”
”C:\\WINDOWS” → C:\WINDOWS
System.out.println( ”Line 1\nLine 2” ) prints
Line 1
Line 2
Data Types and Variables
Study how Java checks the compatibility of the data types in the
expressions.
14
10-Responsibility
Below is a code fragment of a class’s main method with lines that contain
variable declarations. Write “OK” if there is no error in the variable
declaration, otherwise, write “Not OK”. If the declaration is wrong, write
the reason/s. (2 points each).
public static void main(String args[]){
} Go to slide 17
10-Leadership
Below is a code fragment of a class’s main method with lines that contain
variable declarations. Write “OK” if there is no error in the variable
declaration, otherwise, write “Not OK”. If the declaration is wrong, write
the reason/s. (2 points each).
public static void main(String args[]){
Go to slide 17
}
Common String Operators
• String Concatenation: The ‘+’ operator concatenates (joins) two strings.
• “von” + “Wienerschnitzel” → “vonWienerschnitzel”
Note: Concatenation does
not add any space
• When a string is concatenated with another type, the other type is first
evaluated and converted into its string representation
// Assign a radius
radius = 20;
// Compute area
area = radius * radius * 3.14159;
// Display results
System.out.println("The area for the circle of radius "
+
radius + " is " + area);
}
}
animation
Trace a Program Execution
public class ComputeArea {
memory
/** Main method */
public static void main(String[] args) {
radius no value
double radius;
double area; area no value
// Assign a radius
radius = 20;
allocate
// Compute area memory for
area = radius * radius * 3.14159; area
// Display results
System.out.println("The area for the circle of radius "
+
radius + " is " + area);
}
}
animation
Trace a Program Execution
assign 20 to radius
public class ComputeArea {
/** Main method */
public static void main(String[] args) {
radius 20
double radius;
double area; area no value
// Assign a radius
radius = 20;
// Compute area
area = radius * radius * 3.14159;
// Display results
System.out.println("The area for the circle of radius "
+
radius + " is " + area);
}
}
animation
Trace a Program Execution
public class ComputeArea {
memory
/** Main method */
public static void main(String[] args) {
double radius;
radius 20
double area; area 1256.636
// Assign a radius
radius = 20;
compute area and
// Compute area
assign it to variable
area = radius * radius * 3.14159;
area
// Display results
System.out.println("The area for the circle of radius "
+
radius + " is " + area);
}
}
animation
Trace a Program Execution
public class ComputeArea {
memory
/** Main method */
public static void main(String[] args) {
radius 20
double radius;
double area; area 1256.636
// Assign a radius
radius = 20;
// Compute area
area = radius * radius * 3.14159; print a message to the
console
// Display results
System.out.println("The area for the circle of radius "
+
radius + " is " + area);
}
}