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

4 Variables

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

4 Variables

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

Variables

• Variables are used to store values in


programming
• For example:
class Variables {

public static void main(String[] args) {


int radius = 10;
}
}
Identifier Rule
• There is some rules for naming identifiers:
• An identifier consists of letters, digits,
underscores, and dollar signs
• An identifier cannot start with a digit
• An identifier cannot be a reserved word
• An identifier can be of any length
Variable Declarations
• Before we can use a variable, we need to
declare it first
• Declaring a variable means reserving an
address in the memory for that variable
Variable Declarations
• Declaring a variable is done by writing the
variable’s data type followed by its name
class VariableDeclarations {

public static void main(String[] args) {


int radius;
}
}
Variable Declarations
• Using a variable without declaring it will
result in a compile error:
class VariableDeclarations {

public static void main(String[] args) {


radius = 10;
}
}
Variable Declarations
• After declaring a variable, we can change
its value with values of the same data type
class VariableDeclarations {

public static void main(String[] args) {


int radius = 10;
radius = 20;
}
}
Variable Declarations
• Changing a variable’s value to another type
will result in a compile error:
class VariableDeclarations {

public static void main(String[] args) {


int radius = 10;
radius = “Twenty”;
}
}
Variable Declarations
• Once declared, we cannot “undeclare” a
variable; it will exist until our program
terminates
Variable Declarations
• You can have multiple declarations on a
single line:
class VariableDeclarations {

public static void main(String[] args) {


int radius, perimeter;
}
}
Variable Declarations
• Variable names are case-sensitive!
• For example, these variables are three
separate variables:
class VariableDeclarations {

public static void main(String[] args) {


int radius, Radius, RADIUS;
}
}
Java-reserved Keywords
• Java-reserved keywords cannot be used as
variable names
abstract continue for new switch
assert default goto package synchronized
boolean do if private this
break double implements protected throw
byte else import public throws
case enum instanceof return transient
catch extends int short try
char final interface static void
class finally long strictfp volatile
const float native super while
Variable Declarations
• You can both declare and initialize a
variable in the same line
• For example:
class VariableDeclarations {

public static void main(String[] args) {


int radius = 10;
}
}
Variable Declarations
• The above code is equivalent to:
class VariableDeclarations {

public static void main(String[] args) {


int radius;
radius = 10;
}
}
Initialization

int radius = 10;


Declaration
Variable Declarations
• You cannot declare a variable twice in a
program
• For example:
class VariableDeclarations {

public static void main(String[] args) {


int radius = 10;
int radius = 200;
}
}
Variable Declarations
• A variable must have a value before it can
be used
• The following results in a compile error:
class VariableDeclarations {

public static void main(String[] args) {


int radius;

System.out.println(radius);
}
}
Variable Type Inference
• Java has been critizied for being too
verbose and explicit
• When a variable is declared and initialized
in one statement, the type of the variable
can be inferred from the literal type
• In Java 10, the var keyword is introduced
int radius = 10;
This can be inferred Integer literal
from the literal
Since Java 10!

var radius = 10;


This is inferred Integer literal
from the literal
Variable Type Inference
• However we cannot do this:
class VariableTypeInference {

public static void main(String[] args) {


var radius;
}
}
Variable Type Inference
• Or this:
class VariableTypeInference {

public static void main(String[] args) {


var a = 10, b = 20;
}
}
Variable Type Inference
• Keep in mind that the type is still fixed:
class VariableTypeInference {

public static void main(String[] args) {


var radius = 10;
radius = “20”; // error
}
}
Data Types
• There are eight primitive (simple) data
types in Java
• Four of them are integer types; two are
floating-point number types; one is
character type; and one is boolean type
Integer Types
class IntegerTypes {

public static void main(String[] args) {


byte index = 127;
short length = 200;
int radius = 20;
long volume = 1000;
}
}
Integer Types
• The integer types are signed
• The int type is the most commonly used
integer types
• The byte and short types, because of their
smaller sizes, are useful for saving memory
in large arrays
Floating-Point Types
• The floating-point types denote numbers
with fractional parts
• Floating-point types in Java implement IEEE
754 standard
Floating-Point Types
class FloatingPointTypes {

public static void main(String[] args) {


float f = 127f;
double d = 3.14;
}
}
Character Types
• The char type is used to describe
individual characters
• Characters are written in single quotes
• For example:
class CharacterTypes {

public static void main(String[] args) {


char grade = ‘A’;
}
}
Character Types
• Unicode code units can be expressed as
hexadecimal values that run from \u0000
to \uFFFF
• For example, \u2122 is the trademark
symbol (™) and \u03C0 is the Greek letter
pi (π)
Character Types
• There are several escape characters for
special characters
Escape
Character Unicode Value
Character
\b Backspace \u0008
\t Tab \u0009
\n Linefeed \u000a
\r Carriage return \u000d
\’ Single quote \u0027
\” Double quote \u0022
\\ Backslash \u005c
Boolean Types
• The boolean type has two values: true and
false
• For example:
class BooleanTypes {

public static void main(String[] args) {


boolean valid = true;
boolean pass = false;
}
}
Literals
• A literal is a directly-written value
• For example: 100, 3.14, “Hello”, ‘x’, true
• A literal can be assigned to a variable, as
usual:
int value = 100;
double pi = 3.14;
String greeting = "Hello";
boolean valid = true;
Initialization

Variable Literal

int radius = 10;


Declaration

Statement
Integer Literals
• A literal has its own data type
• A number is of type integer
• For example, the following statement
prints an integer:
System.out.println(1000);
Integer Literals
• You can write a number literal which is
within the integer range:
System.out.println(-2147483648);
System.out.println(2147483647);
• But you cannot write the following
because the literals are out of the integer
range:
System.out.println(-2147483649);
System.out.println(2147483648);
Integer Literals
• You have to make the number a long type
literal by appending an L:
System.out.println(-2147483649L);
System.out.println(2147483648L);
• It is recommended to use uppercase L
instead of lowercase l because it can be
confused with 1
Integer Literals
• In Java 7 and later, you can insert
underscores which will be ignored by the
compiler:
System.out.println(-2_147_483_649L);
System.out.println(2_147_483_648L);
Integer Literals
• An integer literal can be assigned to an
integer variable as long as the literal can fit
into the variable
• For example, the following lines result in a
compile error because the literal is out of
the variable range:
byte b = 128;
short s = 32768;
Floating-Point Literals
• Numbers written with a decimal point are
treated as double, not float
• For example:
System.out.println(3.14); // as double
• To write a float literal, append an f or F:
System.out.println(3.14f); // as float
Floating-Point Literals
• You can also write a double literal by
appending an d or D or a decimal point (.):
System.out.println(100d);
System.out.println(100D);
System.out.println(100.);
System.out.println(100.0);
Scientific Notation
• Floating-point literals can be written in
scientific notation in the form of a x 10b
• For example, the scientific notation for
123.456 is 1.23456 x 102
• In Java, it can be written like so:
double value1 = 1.23456e2;
double value2 = 1.23456E2;
double value3 = 1.23456E+2;
double value4 = 1.23456e+2;
Assignments
• In programming languages, the equal sign
(=) is used to assign (store) values
• This is the syntax of assignment
statements:
variable = expression;
• An expression can be a variable, a literal,
or a operation result
Assignments
class IntegerTypes {

public static void main(String[] args) {


int a = 10;
int b = 20;

a = b; // variable
a = 10; // literal
a = a + b; // operation
a = b + 10; // operation
a = 10 + 20; // operation
}
}
Initialization

Expression

Variable Literal Literal

int radius = 10 + 20;


Declaration

Statement
Assignments
• In assignments, a value is not moved; rather,
it is copied
X =Y

X
Y

X Y
Assignments

Step Statement X Y

1. (Initial condition) (Empty) “Tea”

2. X =Y “Tea” “Tea”
Tea and Coffee Problem

Coffee Coffee

X Tea X Tea

Coffee Coffee

X Tea X Tea
Tea and Coffee Problem
String tea = “Tea”; x = tea;
String coffee = “Coffee”; tea = coffee;
String x = “”; coffee = x;

System.out.println(tea); System.out.println(tea);
System.out.println(coffee); System.out.println(coffee);
System.out.println(x); System.out.println(x);
Assignments
• Multiple assignments of a value to several
variables can be done in one line
• For example:
class Assignments {

public static void main(String[] args) {


int a, b;

a = b = 10;
}
}
Assignments
• The above code is equivalent to:
class Assignments {

public static void main(String[] args) {


int a, b;

a = 10;
b = 10;
}
}
Casting
• You can assign a value to a numeric
variable which size is larger than the value
• For example:
class Casting {

public static void main(String[] args) {


int i = 10;
long l = i;
}
}
Casting
• But if you try to assign a value to a
numeric variable which size is smaller,
compile error will occur
• For example:
class Casting {

public static void main(String[] args) {


int i = 10;
byte b = i; // error
}
}
Casting
• You need to cast the variable to do that
• Casting is converting a value to another
data type
• For example:
class Casting {

public static void main(String[] args) {


int i = 10;
byte b = (byte) i;
}
}
Casting
• Casting a value to a larger data type is
called widening a type
• The opposite is called narrowing a type
Casting
• Java automatically widens a type when you
do such assignment
• For example:
class Casting {

public static void main(String[] args) {


int i = 10;
long l = i;
}
}
Casting
• But you need to explicitly cast to narrow a
type
• For example:
class Casting {

public static void main(String[] args) {


int i = 10;
byte b = (byte) i;
}
}
Casting
• However, be careful when casting; loss of
information might lead to inaccurate
results
Constants
• Variables can be converted into constants
by adding the final keyword
• For example:
final String TEA = “Tea”;
TEA = “Coffee”; // error
• By convention, constant names should be
in UPPERCASE and words are
SEPARATED_BY_AN_UNDERSCORE

You might also like