Data and Expressions in Java
Data Types and Variables
Primitive data types in Java include the following:
integers | byte, short, int, long |
floating-point numbers | float, double |
boolean | boolean |
character | char |
Other than primitive data types, one can define composite data types (object types) using classes. For example, String
is a class defined in the standard Java library; it is used to represent a sequence of characters.
A variable is a name for a memory location holding a data value. We can declare a variable by specifying its type and name, and assign values to variables.
int count; count = 0; count = count + 1; int a, b = 10; String title = "Theory"; double pi = 3.14159;
Arithmetic Expressions
An arithmetic expression combines arithmetic operators with numeric operands and produces a numeric result. Arithmetic operators include: addition +, subtraction -, multiplication *, division /, and remainder %.
The following are examples of using arithmetic expressions.
int a = 10, b = 3, c, d; c = a / b; // c is 3 d = a % b; // d is 1
Note that, integer division will discard any fractional part of the result; for example, the result of 10/3
is an integer 3
. To get floating-point numbers we have to use explicit conversion: 10/3.0
or 10/((double) 3)
.
Expressions are evaluated according to the operator precedence.
- *, /, % have the same precedence
- +, – have the same precedence
- *, /, % have higher precedence than +, –
- Operators with the same precedence are evaluated from left to right
- Parentheses force precedence
The increment operator (++) adds one to the numeric variable. The decrement operator (–) subtracts one.
int count; count++; // count = count + 1; count--; // count = count - 1;
Assignment operators combine an arithmetic operator with assignment (+=, -=, *=, /=, %=).
int count; count += 5; // count = count + 5; count -= 5; // count = count - 5; count /= 5; // count = count / 5; count %= 5; // count = count % 5;
Type Conversion
Java is a strongly typed language. Every data value in Java is associated with a data type. Type conversions sometimes are necessary, especially between integers and float point numbers.
Assignment conversion occurs when we assign a value of one type to a variable of another type. For example,
int a = 20; double d = a; // d will be 20.0
Certain operators may automatically convert its operands to maintain the consistency of the types of operands.
int a = 20; double b = 3.0; double d = a / b; // left operand is first converted to 20.0
Conversion can be explicitly done using a cast. A cast is specified by a type name within parentheses.
int a = 20; int b = 3; double c = (double) a; // c will be 20.0 double d = (double) a / b; // same as: ((double) a) / b, and // b will be converted to 3.0 before the division
Note that the casting operation has higher precedence than arithmetic operations.