Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 70

Java Fundamentals

CHAPTER 4
STORING AND MANAGING LOCAL
DATA

Hîrjeu Anna
Software Developer
CHAPTER 4. STORING AND MANAGING
LOCAL DATA
 Introducing variables

 Primitive data types

 Manipulating data (operators)

 Working with String variables


Introducing variables
Variables
• Each variable holds a specific type of data.

• The term variable refers to something that can change.


◦ Variables can be initiated with a value.

◦ The value can be changed.

• A variable is simply a storage location in memory that holds a specific value.


That value can be changed by copying (or “assigning”) a different value to that variable.
Variable Types
•Some of the types of values a variable can hold:
– String (example: "Hello")
– int (examples: -10, 0, 2, 10000)
– double (examples: 2.00, 99.99, -2042.09)
– boolean (true or false)

• If uninitialized, variables have a default value:


– String: null
– int: 0
– double: 0.0
– boolean: false
Defining and assigning a primitive variable

[Data type] [Variable name(identifier)] = [variable value or default];

boolean isThisCorrect = true;


Constants
•Variable (can change): •If someone attempts to change the value of a
• double salesTax = 6.25; constant after it has already been assigned a
value, the compiler gives an error message.
• Constant (cannot change):
•If you modify your code to provide a
• final int NUMBER_OF_MONTHS = 12;
different value for the constant, you need to
recompile your program.
•You should name constants so that they can
The final keyword
causes a variable to be be easily identified.
read only.
•Generally, constants should be capitalized,
with words separated by an underscore (_).
Primitive data types
• Primitive data types, as the name suggests, are the simplest data types in a programming language.

• In the Java language, they’re predefined.

• The names of the primitive types are quite descriptive of the values that they can store.

• Java defines the following eight primitive data types:


— char
— byte
— short
— int
— long
— float
— double
— boolean
Match a value with its corresponding type
Answer

Character values Integer values Decimal values Boolean


a 100 7.3 true
4573
Java Primitive Types

Source Why the 8 Java primitive data types are not objects (theserverside.com)
char
• The char data type can store a single 16-bit Unicode character;

• It can operate virtually all existing languages, including Japanese, Korean, Chinese, French,
German, and Spanish.

• When the desired character is missing from the keyboard, it is possible to represent it using the
Unicode format using a value in the range \ u0000 - \ uffff (0 - 65.535) inclusive.

char c1 = 'D’;
char c12 = 68; // ASCII code
char c2 = '\u00c7'; // Ç
Numeral systems
• Binary number system – A base-2 system, which uses only 2 digits, 0 and 1.
• Octal number system – A base-8 system, which uses digits 0 through 7 (a total of 8 digits).
• Decimal number system – A base-10 number system that you use every day. It’s based on 10
digits, from 0 through 9 (a total of 10 digits).
• Hexadecimal number system – A base-16 system, which uses digits 0 through 9 and letters A
through F(a total of 16 digits and letters).
Literals
A literal is a fixed value that doesn’t need further calculations in order for it to be assigned to
any variable.

Examples:
➔ 5
➔ true
➔ 55
➔ “String”
➔ ‘a’
byte, short, int, long
byte num = 100;
short sum = 1240;
int total = 48764;
long population = 214748368;
long days = 2147483685674567567L;

Integer numeric values are implicitly of type int!

Note that the value of the variable days has the suffix L, because the value of any integer in Java is
treated as an int, and since the int range is too small for 2147483685674567567, we must explicitly specify
that we are working with a long by suffixing the value with L or l
(lowercase l will be accepted by the compiler, but it is not recommended to be used because it can be
confused with the number 1 when a person would analyze the code).
Which statements will be compiled?
➔ long friends = 1559;
➔ long starsInUniverse = 15595695669986589;
➔ short days = 1000;
➔ short weeks = 152589
float, double
These 2 types of data allow working with floating point numbers, both positive and negative.
float average = 20.129F;
float orbit = 1765.65f;
double inclination = 120.1762;

The default type of a decimal literal is double, and by suffixing a value with F or f, it tells the compiler that
the value of the literal should be treated as a float and not as a double.
Which statements will be compiled?
➔ float salary = 1559.68;
➔ float weight = 85.3;
➔ float salary = 1559.68F;
Why:

float weight = 85.3; // doesn’t compile

long friends = 10000; // compiles

short days = 1000; //compiles

long i=10;

float f=i; // compiles

?
Why:
float weight = 85.3; // doesn’t compile
?
long friends = 10000; // compiles
short days = 1000; //compiles
?
long i=10;
float f=i; // compiles
?

Rule: float has less accuracy than double, respectively float cannot correctly represent double numbers even
if it seems that they are in the correct limit.
Default type of numeric constants:
Widening
The process of conversion of a lower data type to a higher data type is
known as Widening Typecasting.

Java automatically performs this type of casting without any explicit code
writing, which is why this type of casting is also known as Automatic typecasting.

byte to short, int, long, float, or double

short to int, long, float, or double

char to int, long, float, or double

int to long, float, or double

long to float or double

float to double
Widening
byte b = 2; int i = 32;
short s = b; (byte to short) long l = i; (int to long)
int i = b; (byte to int) float f = i; (int to float)
long l = b; (byte to long) double d = i;  (int to double)
float f = b; (byte to float)
double d = b; (byte to double) long l = 78;
float f = l; (long to float)
double d = l; (long to double)
short s = 3;
int i = s; (short to int) float decNum = 23.45f ;
long l = s; (short to long) double d = decNum; (float to double)
float f = s; (short to float)
double d = s; (short to double)

char c = ‘d’;
int i = c; (char to int)
long l = c; (char to long)
float f = c; (char to float)
double d = c; (char to double)
boolean
A boolean variable can store one of two possible values literal true or false.
It is used in cases when operating with truth values.

boolean voucherPurchased = true;


boolean examPrepStarted = false;

A literal is a fixed value that doesn’t need further calculations in order for it to be assigned to any
variable.
Manipulating data (operators)
Operators
In Java there are 4 categories of operators that can be used to manipulate variable values.
Operator
Operators Purpose
type

Assignment =, +=, -=, *=, /= Assign value to a variable

Arithmetic +, -, *, /, %, ++, -- Add, subtract, multiply, divide, and modulus primitives

Relation <, <=, >, >=, ==, != Compare primitives

Logical !, &&, || Apply NOT, AND, and OR logic to primitives


Assignment operators =, +=, -=, *=, /=
= - simple assignment operator, the most frequently used operator. It’s used to initialize
variables with values and to reassign new values to them.

Valid lines of code


Invalid lines of
code
+=, -=, *=, and /= operators are short forms of addition, subtraction, multiplication,
and division with assignment.
+= operator can be read as “first add and then assign”;
-= can be read as “first subtract and then assign”;
*= can be read as “first multiply and then assign”;
/= can be read as “first divide and then assign”;
%= can be read as “first modulus and then assign”.
a -= b is equal to a = a – b

a += b is equal to a = a + b

a *= b is equal to a = a * b

a /= b is equal to a = a / b

a %= b is equal to a = a % b
Valid lines of code
You can also assign multiple values on the same line using the assignment operator.
Practice(Examine the following code initializations and select the incorrect answers)
public class FirstApp {
public static void main(String[] args) {
boolean b1, b2, b3, b4, b5, b6; // line 1
b1 = b2 = b3 = true; // line 2
b4 = 0; // line 3
b5 = 'false'; // line 4
b6 = yes; // line 5

} a) The code on line 1 will fail to compile.


}
b) Can’t initialize multiple variables like the code on line 2.
c) The code on line 3 is correct.
d) Can’t assign 'false' to a boolean variable.
e) The code on line 5 is correct.
Arithmetic operators + - * / % ++
--
When you apply the addition operator to char values, their corresponding ASCII values
are added and subtracted.
You can use all arithmetic operators with the char primitive data
type, including unary increment and decrement operators.
IMPLICIT WIDENING OF DATA TYPES IN AN
ARITHMETIC OPERATION
All byte, short, and char values are automatically widened to int when used as operands for arithmetic operations.

If a long value is involved somewhere, then everything, including int values, is widened to long.

If an arithmetic operation includes a data type of float or double, all operand values are widened to double.
++ AND -- (Unary increment and decrement operators)
The operators ++ and -- are unary operators; they work with a single operand. They’re used to
increment or decrement the value of a variable by 1.
Unary operators can also be used in prefix and postfix notation.
In prefix notation, the operator appears before its operand:

In postfix notation, the operator appears after its operand:


++ AND --

When these operators aren’t part of an expression, the postfix and prefix notations behave in
exactly the same manner:
++ AND --

When a unary operator is used in an expression, its placement with respect to its operand decides whether its value
will increment or decrement before the evaluation of the expression or after the evaluation of the expression.

The expression a - ++b uses the increment operator (++) in prefix notation. Therefore, the value of variable b increments
to 11 before it’s subtracted from 20, assigning the result 9 to the variable c.
++ AND --

When ++ is used in postfix notation with an operand, its value increments after it’s been used in
the expression.
What do you think the output of the following code will be?
What do you think the output of the following code will be?

a = 10 + 11 + 11 - 10 + 10;
Practice
int a = 25; int a = 25;
a = ++a + a + --a - --a + a++; a = a++ + a + a-- - a-- + ++a;
System.out.println (a); System.out.println (a);
Practice
int a = 25; int a = 25;
a = ++a + a + --a - --a + a++; a = a++ + a + a-- - a-- + ++a;
System.out.println (a); System.out.println (a);

a = 26 + 26 + 25 - 24 + 24 = 77; a = 25 + 26 + 26 - 25 + 25 = 77;
Relation operators <, <=, >, >=, ==, !=
Relational operators are used to check one condition. You can use these operators to
determine whether a primitive value is equal to another value or whether it is less than or
greater than the other value.

Comparing greater values(>, >=)


Comparing lesser values (<, <=)
Comparing values for equality (==)
Comparing values for inequality (!=)
Relation operators
The operators <, <=, >, and >= work with all types of numbers, both integers (including char) and
floating point, that can be added and subtracted.

!!! You can’t compare incomparable values. For example, you can’t compare a boolean with an int, a char, or
a floating-point number. If you try to do so, your code will not compile.
COMPARING PRIMITIVES FOR EQUALITY (USING == AND !=)

•The operators == (equal to) and != (not equal to) can be used to compare all types of
primitives: char, byte, short, int, long, float, double, and boolean.

• == returns the boolean value true if the primitive values that you’re comparing are equal,
and false otherwise.

•!= returns true if the primitive values that you’re comparing are not equal, and false
otherwise.

•if == returns true, != will return false.


!!!! The result of the relational operation is always a boolean value.
You can’t assign the result of a relational operation to a variable of type char, int, byte, short, long, float, or
double.
COMPARING PRIMITIVES USING THE ASSIGNMENT OPERATOR (=)

It’s a very common mistake to use the assignment operator, =, in place of the equality operator, ==, to
compare primitive values.

B isn’t comparing the variables a and b. It’s assigning the value of the variable b to a and then printing out
the value of the variable a, which is 20. Similarly, c isn’t comparing the variable b1 with the boolean literal
true. It’s assigning the boolean literal true to variable b1 and printing out the value of the variable b1.
You can’t compare primitive values by using the assignment operator, =.
Logical operators !, &&, ||
Logical operators are used to evaluate one or more expressions. These expressions should return a
boolean value. You can use the logical operators AND, OR, and NOT to check multiple conditions and
proceed accordingly.

Real examples
■ Case 1 (for managers)—Request promotion if customer is extremely happy with
the delivered project AND you think you deserve to be in your boss’s seat!
■ Case 2 (for students)—Accept job proposal if handsome pay and perks OR awesome
work profile.
■ Case 3 (for entry-level Java programmers)—If NOT happy with current job, change it.
■ Logical AND (&&)—Evaluates to true if all operands are true; false otherwise.
■ Logical OR (||)—Evaluates to true if any or all the operands are true.
■ Logical negation (!)—Negates the boolean value. Evaluates to true for false and vice versa.
&& AND || ARE SHORT-CIRCUIT OPERATORS
• operators && and || is that they’re also called short-circuit;

• && operator returns true only if both the operands are true. If the first operand to this
operator evaluates to false, the result can never be true. Therefore, && does not evaluate the
second operand;

• the || operator does not evaluate the second operator if the first operand evaluates to true.
Practice
As you know, the short-circuit operators && and || may not evaluate both their operands if they can determine
the result of the expression by evaluating just the first operand. Examine the following code and choose the
expressions that you think will evaluate.
Operator precedence
Examples
Use parentheses to override the default operator precedence

You can use parentheses to override the default operator precedence.


If your expression defines multiple operators and you’re unsure how your expression will be evaluated, use
parentheses to evaluate in your preferred order.
The inner parentheses are evaluated prior to the outer ones, following the same rules of classic algebra.
Working with String variables
String Concatenation
The String class represents character strings. All string literals in Java programs, such as "abc", are implemented as instances of this class.

String variables can be combined using the '+' operator.


– stringVariable1 + stringVariable2
– stringVariable1 + "String literal"
– stringVariable1 + "String literal" + stringVariable2
String Concatenation
• Combining multiple Strings is called “concatenation.”

• You can concatenate a String variable to another String variable.

• You can also concatenate a String literal to a String variable.

• You can concatenate any number of String variables and String literals.

• You can also concatenate a number into a String variable. The compiler converts the numeric
value to its equivalent String value.
Scanner class
Java User Input (Scanner class)
• The Scanner class is used to get user input, and it is found in the java.util package.

• To use the Scanner class, create an object of the class and use any of the available methods found in
the Scanner class documentation.
Scanner. Input Types

Method Description
nextBoolean() Reads a boolean value from the user
nextByte() Reads a byte value from the user
nextDouble() Reads a double value from the user
nextFloat() Reads a float value from the user
nextInt() Reads a int value from the user
nextLine() Reads a String value from the user
nextLong() Reads a long value from the user
nextShort() Reads a short value from the user
Scanner.
Scanner.

Note: If you enter wrong input (e.g. text in a numerical input), you will get an
exception/error message (like "InputMismatchException").

You might also like