OCA Exam Preparation: Java Data Types - Review
OCA Exam Preparation: Java Data Types - Review
OCA Exam Preparation: Java Data Types - Review
4
DECLARING / INITING / OBJECT REFS / CASTING
Declaring a variable is done by stating the data type and giving the variable a valid identifier.
The exam uses identifiers that contain only [a-zA-Z$_]. Identifiers are not limited in their length.
Identifiers may not begin with a digit. As for the underscore _ and the dollar sign $, they are
allowed in the starting place.
Java keywords such as switch and so on, may not be used as identifiers.
A literal is a fixed value that doesn’t need further calculations to be assigned to any variable
provided the variable is of a compatible type.
Numeric literals, which are used to represent numeric values, may contain underscores between
digits and begin with 1–9, 0, 0x, 0X, 0b, or 0B (where 0 stands for zero).
When several variables share a type, they can be declared and initialized in the same statement.
Non-final non-local variables do not require explicit initialization.
5
DECL / INITING / OBJ REFS / CASTING, cont’d
EXTRA: Methods in a final class are effectively final since it’s obviously impossible to override or
hide them; as for fields, they aren’t implicitly final:
Local variables (including loop vars) must be explicitly initialized before use.
The basic building blocks of Java types are the so-called primitive types, which are predefined
by the language. Java doesn’t allow user-defined primitive types.
The language defines eight primitive data types – byte, short, int, long, float, double,
char, and boolean – which can be classified as follows:
numeric:
o integral types
o floating-point types
boolean 6
DECL / INITING / OBJ REFS / CASTING, cont’d
Numeric types:
Numeric types can store either integer or floating-point values.
byte, short, int, and long can be used to store integers.
byte, short, int, and long allocate 8, 16, 32, and 64 bits, respectively, to store
their values.
float and double can be used to store floating-point values.
float and double allocate 32 and 64 bits, respectively, to store their values.
The default data type for integral literals is int.
To designate an integer as long, we append L or l to the literal value.
Numeric values can be stored in binary, octal, decimal, and hexadecimal formats.
Decimal literals use digits from 0 to 9. Octal literals use digits from 0 to 7 (a total of 8
digits). Hexadecimal literals use digits from 0 to 9 and letters from A to F. Binary
literals use digits 0 and 1.
7
DECL / INITING / OBJ REFS / CASTING, cont’d
Octal literals must be prefixed with 0 (zero), hex with 0x or 0X, and binary with 0b or 0B.
The default data type for floating-point values is double.
To designate an integral or floating-point value as float, add the suffix F or f.
The suffixes D and d can be used to mark a literal as a double value.
The char data type is stored as an unsigned positive integer.
char can store a single 16-bit Unicode character, from '\u0000' (or 0) to a maximum of
'\uffff' (or 65,535) inclusive.
When a symbol gets assigned to a char, Java stores its integer equivalent value. It is
therefore allowed to assign a positive integer value to a char instead of a symbol (for
example, char ch = 97 to store the letter ‛a’).
To assign a symbol to a char variable, we use single quotes: char ch = 'a';
The data type boolean:
boolean can store only two possible values, true and false, which are also literals.
Java does not recognize the numeric literals 1 and 0 as valid boolean values.
8
DECL / INITING / OBJ REFS / CASTING, cont’d
Casting:
Casting forcefully makes a variable behave as a variable of another type. Casting applies
to both primitive and reference variables, and can be implicit or explicit.
Automatic casting is done by the compiler (implicitly); narrower datatype wider type.
The casting done by the programmer is called explicit casting. Explicit casting is
mandatory to convert a wider data type to a narrower data type.
Converting a narrower data type into a wider data type is called widening while converting
a wider data type into a narrower type is called narrowing. Widening is safe so the Java
compiler does not flag any error even if the programmer did not use the cast operator (T).
Narrowing is intrinsically unsafe must explicitly use the cast operator in narrowing.
Reference types:
Primitive types, which represent single values, can be assembled into reference types,
which represent a group of values.
Apart from this, reference types can also have methods.
Unlike primitive types, reference types can be null.
Default values for numeric primitives are their corresponding ‛zeroes’ (i.e., 0 or 0.0)
Default value for boolean is false.
Reference types default to null. 9
DECL / INITING / OBJ REFS / CASTING, cont’d
• floats with floating-point literals should have f/F appended → be attentive to the
cases when they are passed to methods that expect floats.
10
DECL / INITING / OBJ REFS / CASTING, cont’d
Using exponent:
The exponent is used with the floating-point literals only (e or E for decimals, p or P for hexes):
Octal notation:
A floating-point number ccanot be written in octal (it gets interpreted as decimal, instead):
11
DECL / INITING / OBJ REFS / CASTING, cont’d
Combat Rule:
No VARIABLE other than char can be assigned to a char without an explicit cast
whereas a CONSTANT can be assigned to a char only if the value fits into char.
EXTRAS:
int or long to float or long to double can lead to loss of precision.
char behaves almost as an unsigned short, e.g.:
sout('a' +1) // prints 98
The floating-point suffixes f, F, d, and D are applicable only to decimal notation.
null can be cast to any reference type:
"Hello".equals((String)null); // perfectly VALID
Known trap on the exam Casts act on the nearest right-side neighbor only.
13
2.3
OBJECT FIELDS
14
READING AND WRITING TO OBJECT FIELDS
15
2.4
OBJECT’S LIFECYCLE
16
OBJECT’S LIFECYCLE
It begins when the object is initialized and ends when the object goes out of scope
or is no longer referenced;
A live object can be referenced by a var to make available its methods and fields to
other objects;
Simply declaring a reference var does not imply that a new object will be created.
Out of several practical ways to create a new object in Java only two are needed for
the 1Z0-808 exam:
– by using the keyword new ← universal method
– by using double quotes ← this shorthand is available only for String.
An object becomes eligible for GC when it can no longer be accessed.
An object becomes inaccessible when no refvar points to it any longer because:
– the reference variable was re-assigned to another object,
– the refvar was set to null, or
– went out of scope 17
OBJECT’S LIFECYCLE, cont’d
The inaccessible objects are removed from memory by the so-called garbage
collection mechanism. The purpose of garbage collection is to identify and remove
the objects that are no longer needed by a program so that their resources can be
reclaimed and reused.
EXTRA: OutOfMemoryError is thrown by the JVM when it’s unable to create objects
on the heap and the garbage collector cannot free more memory for the JVM.
EXTRA: The programmer can attempt to call the garbage collector by calling the
method System.gc() or Runtime.getRuntime().gc() but the fact is the garbage
collector is invoked fully automatically and it is not guaranteed that the GC process
will ever run during a program’s lifecycle. All we can be sure about is whether objects
are eligible for being garbage collected.
18
2.5
USING WRAPPERS
19
USING SELECTED WRAPPER CLASSES
EXTRA:
All wrapper ctors EXCEPT Character (which has only one ctor, i.e. Character(char value))
accept null treating it as a null String but they throw an NFE (or NPE in case of Float and
Double ) EXCEPT the Boolean(null) ctor, which returns FALSE (and not the primitive false).
None of the primitive wrapper classes has a no-arg constructor.
All wrappers (except Character) accept a String and all (no exceptions) accept their underlying
primitives;
Most popular methods on the exam:
valueOf(): static returns a Wrapper object; accepts both String and primitive;
static Integer valueOf(int i) returns an Integer instance representing the specified int value;
static Integer valueOf(String s) returns an Integer obj holding the value of the specified String;
primValue(): non-static returns an underlying primitive; is a no-arg instance method;
int intValue() returns the value of this Integer as an int;
parsePrim(): static 1) accepts String by definition + 2) returns a primitive that
represents the passed-in String;
static int parseInt(String s) parses the String argument as a signed decimal integer.
Boolean.FALSE is an Object (same for Boolean.TRUE).
21
USING SELECTED WRAPPER CLASSES, cont’d