OCA Exam Preparation: Java Data Types - Review

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 22

OCA Exam Preparation

JAVA DATA TYPES –


REVIEW
ABBREVIATIONS & ACRONYMS

actype – actual object’s type at run time AIOOBE – ArrayIndexOutOfBoundsException


assop – assignment operator CCE – ClassCastException
castype – data type specified inside the parens for an explicit cast ChE – checked exception
comperr – compilation error CSR – the Catch-or-Specify Requirement
ctor – constructor DTPE – DateTimeParseException
dim – dimension E – an exception (regardless of the type)
initer – initializer IAE – IllegalArgumentException
op – operator IOE – IOException
paramlist – list of formal parameters in a lambda expression IOOBE – IndexOutOfBoundsException
preditype – data type specified inside the angle brackets LDT – any of the new date/time classes in Java 8
reftype – reference type LOC – line of code
refvar – reference variable NFE – NumberFormatException
sout – any printing statement such as System.out.println(), etc. NPE – NullPointerException
stat – statement RTE – RuntimeException
ternop – ternary operator SIOOBE – StringIndexOutOfBoundsException
var – variable TCF – try-catch-finally construct

Igor Soudakevitch  2019 2


[email protected]
EXAM OBJECTIVE’S STRUCTURE

The 1Z0-808 topics within this group:


1. Declare and initialize variables (including casting of primitive data types);
2. Differentiate between object reference variables and primitive variables;
3. Know how to read or write to object fields;
4. Explain an object’s lifecycle (creation, "dereference by reassignment" and garbage
collection);
5. Develop code that uses wrapper classes such as Boolean, Double, and Integer.

Source: Oracle Univ. 3


2.1 & 2.2
DECLARING AND INITING VARS
OBJECT REFS vs PRIMITIVES
CASTING OF PRIMITIVES

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.

final vars mandate explicit initing  Exam Objective 6.3,


Create and overload ctors, incl.impact on default ctors

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

Extra Practical Rules:


• Both f/F and d/D can be used not only on floating-point literals, so float f = 10F is
VALID.
• ANY integral literal (binary, hex or octal notation) is assignable to long w/o l/L.
• ATTN: char literals (such as ‛a’, etc.) are assignable to long BUT w/o l/L ONLY.
• The underscores in numerical values can appear ONLY between digits or be
chained like
1____2__3 (same as 123). They can be used in the floating point literals, too:
double d = 0_1234.567; // 1234.567

• 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

Casting to char anditback:


What boils down to, char is unsigned whereas
byte, short, etc. can be negative, so
char = short and so on won’t compile.
Also, char can hold up to 65535 while short
maxes out at 32767, so
short = char won’t compile, either.
Implicit narrowing occurs only for byte, char,
short, and int → it does not occur for long, float, or double. So, these
won’t compile:
int i = 129L; // INVALID
char ch = 30L; // INVALID even
though 30 is representable in char
However:
final int s = 10; 12
char c = s; // OK as s is a
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

 An object field is another name for an instance or static variable defined in a


class.
 Access modifiers determine if the object fields can be read and written to directly by
using instance variables.
 Accessing object fields:
 Reading:
o by directly accessing the field (its access modifier permitting), or
o by using a method that returns the field’s value.
 Writing:
o by directly accessing the field (its access modifier permitting), or
o by using constructors or methods that assign a value to the field.

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

 What are wrapper classes?


Java provides specialized classes corresponding to each of the primitive data types:
byte ↔ Byte, short ↔ Short, int ↔ Integer, long ↔ Long,
float ↔ Float, double ↔ Double,
char ↔ Character,
boolean ↔ Boolean
These are called wrapper classes.
 Why do we need wrapper classes?
Sometimes it becomes easier to handle primitives if they were objects.
Typical examples are data structures such as ArrayList, etc. Also, utility classes contain
handy methods that expect objects as their argumens (e.g., Collections.sort() and so on.)
 What is autoboxing?
Conversion of primitive types into objects (instances of the corresponding wrappers)
automatically by the compiler.
 What is unboxing?
Converting an object into its underlying primitive data type is called unboxing.
20
USING SELECTED WRAPPER CLASSES, cont’d

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

 primitive == wrapper works; the RHS gets unboxed.


 A primitive passed to a List<Wrapper> will autobox.
However – TRAP! – the compiler will perform only a single-step conversion on its own!
Can’t add, say, a byte or short to List<Integer>):
byte b = 10;
short s = 20;
List<Integer> l = new ArrayList<>();
// l.add(b); // won’t compile
// l.add(s); // won’t compile, either
l.add( (int)b ); // VALID
 Parsers of the wrapper classes accept only Strings (or String, radix).
 Boolean.valueOf(String) and its overloaded Boolean.valueOf(boolean) version return a
reference to either Boolean.TRUE or Boolean.FALSE wrapper obj, and do NOT create a new
Boolean obj; they simply return the static constants TRUE or FALSE defined in Boolean class.
 EXTRA: All wrapper classes are immutable.
 Although the wrappers extend Number, there’s no IS-A relation between any two of the wrapper
classes  (Long) Integer won’t work. Byte == Short, etc. throws a comperr, too.
 Byte, Short, Integer and Long use the same numerical pool (similar to String case) up to
byte’s boundaries (-128 ... 127), hence == evaluates to true.
22

You might also like