1.2%20Fundamentals%20of%20Java%20Programming.pptx_0
1.2%20Fundamentals%20of%20Java%20Programming.pptx_0
By Almodad Mutinda
|
Course Objectives
At the end of this lecture, each student should:
• Understand Java’s primitive types
• Understand variables in java.
• Understand Data Types in java.
• Understand Operators in java.
• Data type defines the values that a variable can take, for
example if a variable has int data type, it can only take
integer values.
• In java we have two categories of data type:
1) Primitive data types
2) Non-primitive data types – Arrays and Strings are
non- primitive data types,
• Java is a statically typed language.
• A language is statically typed, if the data type of a variable
is known at compile time. This means that you must specify
the type of the variable (Declare the variable) before you
can use it.
• If the expression results true then the first value before the
colon (:) is assigned to the variable num1 else the second
value is assigned to the num1.
Rules of precedence:
1.Operators within a pair of parentheses
2.Increment and decrement operators
3.Multiplication and division operators,
evaluated from left to right
4.Addition and subtraction operators,
evaluated from left to right
– Type casting lowers the range of a value, quite literally chopping it down
to a smaller size, by changing the type of the value (for example, by
converting a long value to an int value).
– You do this so that you can use methods that accept only certain types
as arguments, so that you can assign values to a variable of a smaller
data type, or so that you can save memory.
– Put the target_type (the type that the value is being type cast to) in
parentheses in front of the item that you are type casting. The syntax for
type casting a value is:
» identifier = (target_type) value
– where:
• identifier is the name you assign to the variable
• value is the value you want to assign to the identifier
• (target_type) is the type to which you want to type cast the value.
Notice that the target_type must be in parentheses.
• Syntax:
identifier = (target_type) value
• Example of potential issue:
int num1 = 53; // 32 bits of memory to hold the value
int num2 = 47; // 32 bits of memory to hold the value
byte num3; // 8 bits of memory reserved
num3 = (num1 + num2); // causes compiler error
• Example of potential solution:
int num1 = 53; // 32 bits of memory to hold the value
int num2 = 47; // 32 bits of memory to hold the value
byte num3; // 8 bits of memory reserved
num3 = (byte)(num1 + num2); // no data loss
Examples:
int myInt;
long myLong = 99L;
myInt = (int) (myLong); // No data loss, only zeroes.
// A much larger number would
// result in data loss.
int myInt;
long myLong = 123987654321L;
myInt = (int) (myLong); // Number is "chopped"