Basics
Data Types
Primitive Types:
Non-Primitive Types:
String
Array
Class
Interface
Identifier Rules
Names can contain letters, digits, underscores, and dollar signs.
Names must begin with a letter, underscore or dollar sign.
Names should start with a lowercase letter (Camel Case).
Reserved words (e.g. keywords, such as
intorboolean) cannot be used as names
Literals
To improve the readability of program, we can use underscores in the literals.
Operators
Arithmetic operators
Relational operators
Logical operators
Bitwise operators
Assignment operators
In Java, we can use % operator, even on floating point numbers.
Code: Sum of two numbers
Type Conversion
Widening Conversion (Implicit)
Widening conversion takes place when two data types are automatically converted.
This happens when:
The two data types are compatible.
When we assign a value of a smaller data type to a bigger data type.
For Example, in java, the numeric data types are compatible with each other
but no automatic conversion is supported from numeric type to char or boolean.
Also, char and boolean are not compatible with each other.
Byte-> Short-> Int-> Long-> Float-> Double
Where it happens:
Assignments
Expressions
Method arguments
Type Promotion
While evaluating expressions, the intermediate value may exceed the range of operands and hence the expression value will be promoted.
Some conditions for type promotion are:
Java automatically promotes each
byte,short, orcharoperand tointwhen evaluating an expression.If one operand is
long,floatordoublethe whole expression is promoted tolong,float, ordoublerespectively.
Important detail:
This is invalid because b * 2 is an expression, so its value will be promoted to int type, and cannot be assigned to byte type directly.
Narrowing Conversion (Explicit)
If we want to assign a value of a larger data type to a smaller data type we perform explicit type casting or narrowing.
This is useful for incompatible data types where automatic conversion cannot be done.
The decimal part of the variable price is lost (the variable is converted to integer).