Variables, Datatypes and Typeconversion
Variables, Datatypes and Typeconversion
• Type
• How much memory do a variable need.
• This information is determined by a type.
• Name
• How to differentiate a variable with another variable of the same type.
• Name refers to the memory location assigned to this variable.
• Value
• What is the value?
• The actual value contained by a variable.
Variable - Example
00000000 Location 0
Locations 0 – 3 are collectively 00000000 Location 1
called as ‘temperature’ 00000000 Location 2
00100011 Location 3
Location 4
100011 is the binary equivalent of 35 Location 5
Variable Type
• Whole Numbers
int numPeople = 2;
• Type casting is when you assign a value of one primitive data type to
another type.
Type Casting
int x = 10;
byte y = (byte)x;
12
Widening or Automatic type converion
13
Example
14
Narrowing or Explicit type conversion
• When you are assigning a larger type value to a variable of smaller type,
then you need to perform explicit type casting.
15
Example
16
Type Casting
Introduction to Java
17
Type Casting
• Ans: 9
Introduction to Java
18
Conversions
Introduction to Java
19
The Math class
• To take the square root of a number, use the Math.sqrt; for example,
Math.sqrt(x)
Introduction to Java
20
Example
• In Java
• can be represented as
Introduction to Java
21
Mathematical Methods in Java
Math.pow(x, y) power xy
Math.exp(x) ex
Introduction to Java
22
Type Conversion – Widening Conversion
• Narrow data types are converted into broad data type with out loss of
information
• Both types are compatible.
• Numeric types are not compatible with boolean and char
• Destination type is larger than source type.
• Example
• byte -> int
• int -> long
int myInt = 9;
• Broader data type is converted into narrower data type with loss of
information
• Process is called casting (explicit type conversion)
float x = 3.4f;
• Assignment Statement
• In Mathematics the value x = x + 1 is not possible why?
• In Java x = x +1 is possible because “=” is an assignment operator and not an
equality operator.
• Assignment operator means that the contents of the right hand side is
transferred to the memory location of the left hand side.
• Example:
• X = 5671;
Constants
• 6 + 2 * 3 / 6;
• 7
• 0.5
• 13.0
• 4
Manipulating Values
• Mathematical Operators
• Common mathematical operators are available in Java for manipulating values
e.g. addition(+), subtraction(-), multiplication(*), division(/), and modulus (%)
• Operator Precedence
• Operator precedence controls the order in which operations are performed
• Operator Associativity
• The associativity of an operator specifies the order in which operations of the
same precedence are performed
• So far the variable types that we have studied are primitive data types.
• Primitive data types only have a memory space for storing values.
• However, Object-Oriented Programming is special because OOP has
more variables then just primitive data types.
What Will Happen Here?
Any Questions?