0% found this document useful (0 votes)
14 views

Java Variables Types

This document discusses Java variables and data types. It covers the following key points: 1. Variables are used to store and manipulate data in memory. They must be declared with a specific data type like int, double, boolean, etc. and can be assigned new values. 2. The syntax for declaring a variable is the data type followed by the variable name. Multiple variables can be declared on one line separated by commas. 3. Variable names must follow identifier rules - they can include letters, numbers, and underscores but must start with a letter. Descriptive, meaningful names are best. 4. The primitive data types in Java include integer types like int and long, floating-point types like

Uploaded by

Ley Manalo
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Java Variables Types

This document discusses Java variables and data types. It covers the following key points: 1. Variables are used to store and manipulate data in memory. They must be declared with a specific data type like int, double, boolean, etc. and can be assigned new values. 2. The syntax for declaring a variable is the data type followed by the variable name. Multiple variables can be declared on one line separated by commas. 3. Variable names must follow identifier rules - they can include letters, numbers, and underscores but must start with a letter. Descriptive, meaningful names are best. 4. The primitive data types in Java include integer types like int and long, floating-point types like

Uploaded by

Ley Manalo
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 32

Java Identifiers and Data

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

Floating-Point Types: Avoid this lowercase L. It looks


doubleTwo allowable forms: too much like the digit ‘1’
Decimal notation: 3.14159 -234.421 0.0042 -43.0
Scientific notation: (use E or e for base 10 exponent)
3.145E5 = 3.145 x 105 = 314500.0
1834.23e-6 = 1834.23 x 10-6 = 0.00183423
float Same as double, but followed by ‘f’ or ‘F’: 3.14159F -43.2f

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.

• int num1, num2; // num1 and num2 are integer variables


• double num3; // num3 is a double variable
• String word; // word is a string variable
• boolean val; // val is a boolean variable
• char symbol; // symbol is a character variable

• num1 = 7; // legal (assigns the value 7 to num1)


• val = true; // legal (assigns the value true to val)
• symbol = ‘#’; // legal (assigns character # to symbol)
• word = “cat” + “bert”; // legal (assigns the value “catbert” to word)
• num3 = num1 – 3; // legal (assigns the integer value 7 – 3 = 4 to double num3)

• val = 5; // illegal! (cannot assign int to boolean)


• num2 = num1 + val; // illegal! (cannot add int and boolean)
• symbol = num1; // illegal! (cannot assign int to char)
LESSON CHECK
10 - Responsibility
10 - Leadership

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[]){

String month; //1.______

int name = “Pedro”; //2.______

boolean isMarried = “false”; //3.______

float spendings/week; //4.______

float Annual Income; //5.______

int 1stQuarter; //6.______

int SecondQuarter; //7.______

char age = 45; //8.______

} 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[]){

float spendings/week; //1.______

float Annual Income; //2.______

int 1stQuarter; //3.______

int SecondQuarter; //4.______

char age = 45; //5.______

String month; //6.______

int name = “Pedro”; //7.______

boolean isMarried = “false”; //8.______

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

(8*4) + “degrees” → “32degrees” (1 + 2) + “5” → “35”


Arithmetic expressions
0 An expression is a set of symbols that represents a
value
0 An arithmetic expression represents a numeric value
0 Simple expressions are single values; examples:
18
-4
1.245e3
0 Previously-declared and initialized variables or
constants can also be simple expressions
Arithmetic operators in Java
Operation Symbol
0Compound
expressions are Addition +
formed by
Subtraction -
combining simple
expressions using Multiplication *
arithmetic
Division /
operators
Modulus %
Arithmetic operations in Java
0 As in algebra, multiplication and division (and
modulus, which we’ll look at momentarily) take
precedence over addition and subtraction
0 We can form larger expressions by adding more
operators and more operands
0 Parentheses are used to group expressions, using the
same rule as in algebra: evaluate the innermost
parenthesized expression first, and work your way out
through the levels of nesting
0 The one complication with this is we have only
parentheses to group with; you can’t use curly or square
brackets, as they have other specific meanings in Java
Examples
int num1 = 4, num2 = 9, num3;

num3 = num1 + num2 * 2; // result is 22

num3 = (num1 + num2) * 2; // result is 26

num2 = num2 – 1; // result is 8


Integer division
0 When one real number is divided by another, the
result is a real number; for example:
double num1 = 5.2, num2 = 2.0, num3;
num3 = num1 / num2; // result is 2.6

0 When dividing integers, we get an integer result


0 For example:
int num1 = 4, num2 = 9, num3;
num3 = num1 / 2; // result is 2
num3 = num2 / num1; // result is 2, again
num3 = num1 / num2; // result is 0
Integer division
0There are two ways to divide integers
0 using the / operator, produces the quotient of the
two operands
0 using the % operator, produces the remainder
when the operands are divided. This is called
modular division, or modulus (often abbreviated
mod). For example:
int num1 = 4, num2 = 9, result;
result = num1 % 2; // result is 0
result = num2 % num1; // result is 1
result = num1 % num2; // result is 4
Assignment conversion
0 Another kind of implicit conversion can take place
when an expression of one type is assigned to a
variable of another type
0 For example, an integer can be assigned to a real-
number type variable; in this case, an implicit
promotion of the integer value occurs
Compound arithmetic/
assignment operators
0 Previous examples in the notes have included the following
statements:
num = num + 1;
num = num / 3;
0 In each case, the current value of the variable is used to
evaluate the expression, and the resulting value is assigned
to the variable (erasing the previously-stored value)
0 This type of operation is extremely common; so much so,
that Java (like C++ and C before it) provides a set of
shorthand operators to perform this type of operation. The
table on the next slide illustrates the use and meaning of
these operators
Compound arithmetic/
assignment operators
Operator Use Meaning

+= num += 1; num = num + 1;

-= num -= 1; num = num – 1;

*= num *= 5; num = num * 5;

/= num /= 2; num = num / 2;

%= num %= 10; num = num % 10;


Introducing Programming with
an Example
Listing 2.1 Computing the Area of a
Circle
This program computes the area of
the circle.

ComputeArea IMPORTANT NOTE: To run the program from the


Run button, (1) set c:\Program
Run Files\java\jdk1.5.0\bin for path, and (2) install
slides from the Instructor Resource Website to a
directory (e.g., c:\LiangIR) .
animation
Trace a Program Execution
allocate
public class ComputeArea {
memory for
/** Main method */
radius
public static void main(String[] args) {
double radius; radius no value
double area;

// 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);
}
}

You might also like