0% found this document useful (0 votes)
28 views18 pages

OCA Points

This document provides an overview of Java building blocks and core concepts covered in Chapter 1 of the OCA exam, including: - Defining the structure of Java classes and using classes to create objects - Working with Java data types such as variables, primitive types, and object references - Understanding object lifecycles and garbage collection - Key features of Java like platform independence and object orientation

Uploaded by

Manju Palat
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as RTF, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views18 pages

OCA Points

This document provides an overview of Java building blocks and core concepts covered in Chapter 1 of the OCA exam, including: - Defining the structure of Java classes and using classes to create objects - Working with Java data types such as variables, primitive types, and object references - Understanding object lifecycles and garbage collection - Key features of Java like platform independence and object orientation

Uploaded by

Manju Palat
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as RTF, PDF, TXT or read online on Scribd
You are on page 1/ 18

OCA

Chapter 1

Java Building Blocks


OCA EXAM OBJECTIVES COVERED IN THIS
CHAPTER:
✓ Java Basics

▪ Define the scope of variables


▪ Define the structure of a Java class
▪ Create executable Java applications with a
main method; run a Java program from the
command line; including console output
▪ Import other Java packages to make them
accessible in your code
▪ Compare and contrast the features and
components of Java such as platform
independence, object orientation, encapsu-
lation, etc. ✓ Working with Java Data Types
▪ Declare and initialize variables (including
casting or primitive types)
▪ Differentiate between object reference
variables and primi- tive variables
▪ Know how to read or write to object fields
▪ Explain an Object’s Lifecycle (creation,
“dereference by reassignment” and garbage
collection

Creating Objects
———————————
There are two key points to note about
the constructor:
• the name of the constructor matches the
name of the class,
• and there’s no return type.

When you see a method name beginning with


a capital letter and having a return type, pay
special attention to it. It is not a constructor
since there’s a return type.
The purpose of a constructor is to initialize
fields, although you can put any code in there.
For most classes, you don’t have to code a
constructor—the compiler will supply a “do
nothing” default constructor for you.
Naming conflicts
import java.util.Date;
import java.sql.*;
If you explicitly import a class name, it takes
precedence over any wildcards present.
import java.util.Date; import java.sql.Date;
Java is smart enough to detect that this code is
no good. As a programmer, you’ve claimed to
explicitly want the default to be both the
java.util.Date and java.sql.Date
implementations. Because there can’t be two
defaults, the compiler tells you:
The import java.sql.Date collides with another
import statement

Instance Initializer Blocks


The code between the braces is called a code
block. Sometimes code blocks are inside a
method. These are run when the method is
called. Other times, code blocks appear
outside a method. These are called instance
initializers.
. 3: public static void main(String[] args) {
. 4: { System.out.println("Feathers"); }
. 5: }
. 6: { System.out.println("Snowy"); }

When counting instance initializers, keep in


mind that it does matter whether the braces are
inside a method. There’s only one pair of
braces outside a method. Line 6 is an instance
initializer.

Order of Initialization
• Fields and instance initializer blocks are run in
the order in which they appear in the file.
• The constructor runs after all fields and
instance initializer blocks have run.
The last thing you need to know about
numeric literals is a feature added in Java 7.
You can have underscores in numbers to make
them easier to read:

Local variables—in scope from declaration to


end of blockInstance variables—in scope from
declaration until object garbage collected
Class variables—in scope from declaration
until program ends

Variable type
boolean - falsebyte, short, int, long - 0 (in the
type’s bit-length)float, double - 0.0 (in the
type’s bit-length)char - \u0000' (NUL)All
object references (everything else) - null

Think of the acronym PIC (picture): package,


import, and class. Fields and methods are
easier to remember because they merely have
to be inside of a class.
multiple classes can be defined in the same
file, but only one of them is allowed to be
public. The public class matches the name of
the file. A file is also allowed to have neither
class be public. As long as there isn’t more
than one public class in a file, it is okay.
Java provides a garbage collector to
automatically look for objects that aren’t
needed anymore.
All Java objects are stored in your program
memory’s heap. The heap, which is also
referred to as the free store, represents a large
pool of unused memory allocated to your Java
application. The heap may be quite large,
depending on your environment, but there is
always a limit to its size. If your program
keeps instantiating objects and leaving them
on the heap, eventually it will run out of
memory.
Garbage Collection
Garbage collection refers to the process of
automatically freeing memory on the heap by
deleting objects that are no longer reachable in
your program.
You do need to know that System.gc() is not
guaranteed to run, and you should be able to
recognize when objects become eligible for
garbage collection.
Java provides a method called System.gc().
Now you might think from the name that this
tells Java to run garbage collection. Nope! It
meekly suggests that now might be a good
time for Java to kick off a garbage collection
run.
The more interesting part of garbage
collection is when the memory belonging to an
object can be reclaimed. Java waits patiently
until the code no longer needs that memory.
An object will remain on the heap until it is no
longer reachable. An object is no longer
reachable when one of two situations occurs:■
The object no longer has any references
pointing to it. All references to the object have
gone out of scope.
Do not confuse a reference with the object that
it refers to; they are two different enti- ties.
The reference is a variable that has a name and
can be used to access the contents of an object.
A reference can be assigned to another
reference, passed to a method, or returned
from a method. All references are the same
size, no matter what their type is.
An object sits on the heap and does not have a
name. Therefore, you have no way to access
an object except through a reference. Objects
come in all different shapes and sizes and
consume varying amounts of memory. An
object cannot be assigned to another
object, nor can an object be passed to a
method or returned from a method. It is the
object that gets garbage collected, not its
reference.
finalize()
Java allows objects to implement a method
called finalize() that might get called. This
method gets called if the garbage collector
tries to collect the object. If the garbage
collector doesn’t run, the method doesn’t get
called. If the garbage collector fails to collect
the object and tries to run it again later, the
method doesn’t get called a second time.
protected void finalize()
The lesson is that the finalize() call could run
zero or one time.
Benefits of Java
Object Oriented Java is an object-oriented
language, which means all code is defined in
classes and most of those classes can be
instantiated into objects.
Encapsulation Java supports access modifiers
to protect data from unintended access and
modification.
Platform Independent Java is an interpreted
language because it gets compiled to bytecode.
A key benefit is that Java code gets compiled
once rather than needing to be recompiled for
different operating systems.
This is known as “write once, run
everywhere.”
Robust One of the major advantages of Java
over C++ is that it prevents memory leaks.
Java manages memory on its own and does
garbage collection automatically. Bad memory
management in C++ is a big source of errors
in programs.
Secure Java code runs inside the JVM. This
creates a sandbox that makes it hard for Java
code to do evil things to the computer it is
running on.

Numeric Promotion Rules


1. If two values have different data types, Java
will automatically promote one of the val-
ues to the larger of the two data types.
2. If one of the values is integral and the other
is floating-point, Java will automatically
promote the integral value to the floating-
point value’s data type.
3. Smaller data types, namely byte, short, and
char, are first promoted to int any time they’re
used with a Java binary arithmetic operator,
even if neither of the operands is int.
4. After all promotion has occurred and the
operands have the same data type, the result-
ing value will have the same data type as its
promoted operands.

The logical complement operator, !, flips the


value of a boolean expression.
Likewise, the negation operator, -, reverses
the sign of a numeric expression, as shown in
these statements:
you cannot applya negation operator, -, to a
boolean expression, nor can you apply a
logical complement operator, !, to a numeric
expression.
nt x = !5; // DOES NOT COMPILE boolean y
= -true; // DOES NOT COMPILE boolean z
= !0; // DOES NOT COMPILE ..does not
compile because you cannot take the logical
comple- ment of a numeric value, nor can you
assign an integer to a boolean variable.
Casting primitives is required any time you are
going from a larger numerical data type to a
smaller numerical data typ e
Java will automatically promote from smaller
to larger data types, but it will throw a
compiler exception if it detects you are trying
to convert from larger to smaller data types.
int x = 1.0; // DOES NOT COMPILE trying to
assign a double 1.0 to an integer value Even
though the value is a mathematic integer, by
adding .0, you’re instruct- ing the compiler to
treat it as a double
short y = 1921222; // DOES NOT COMPILE-
the literal value 1921222 is outside the range
of short and the compiler detects this.
int z = 9f; // DOES NOT COMPILE-the f
added to the end of the number that instructs
the compiler to treat the number as floating-
point value.
long t = 192301398193810323; // DOES NOT
COMPILE -the f added to the end of the
number that instructs the compiler to treat the
number as floating-point value.
Casting primitives is required any time you are
going from a larger numerical data type to a
smaller numerical data type, or converting
from a floating-point number to an integral
value.

//TODO Casting Primitive Values Overflow


underflow

Compound operators are useful for more than


just shorthand—they can also save us from
having to explicitly cast a value.
long x = 10;int y = 5;y = y * x; // DOES NOT
COMPILE -the result being promoted to a
long and assigned to an int variable:
This last line could be fixed with an explicit
cast to (int), but there’s a better way using the
compound assignment operator:
long x = 10; int y = 5;y *= x;
The compound operator will first cast x to a
long, apply the multiplication of two long
values, and then cast the result to an int. the
compiler will automatically cast the resulting
value to the data type of the value on the left-
hand side of the compound operator.
long x = 5;long y = (x=3);
System.out.println(x); // Outputs 3
System.out.println(y); // Also, outputs 3
> , >=, <, <= are applied to numeric primitive
data types only. If the two numeric operands
are not of the same data type, the smaller one
is promoted in the manner as previously
discussed.
a instanceof b True if the reference that a
points to is an instance of a class, subclass, or
class that implements a particular
interface, as named in b
logical operators, (&), (|), and (^), may be
applied to both numeric and boolean data
types. When they’re applied to boolean data
types, they’re referred to as logical operators.
Alternatively, when they’re applied to numeric
data types, they’re referred to as bitwise
operators, as they perform bitwise
comparisons of the bits that compose the
number.
x&y x | y
y= true y= false
x= true true false
x= false false false

x^y
y= true y= false
(EXCLUSIV
E OR)
x= true true true
false
x= false true

(AND)
(INCLUSIVE y= true y= false
OR)
x= true false true
x= false true false
■■■
Here are some tips to help remember this
table:AND is only true if both operands are
true.Inclusive OR is only false if both
operands are false.
Exclusive OR is only true if the operands are
different.
we present the conditional operators, &&
and ||, which are often referred to as short-
circuit operators. The short-circuit operators
are nearly identical to the logical opera- tors,
& and |, respectively, except that the right-
hand side of the expression may never be
evaluated if the final result can be determined
by the left-hand side of the expression.
A more common example of where short-circuit operators are used is checking for
null objects before performing an operation, such as this:

if(x != null && x.getValue() < 5) { // Do something

if(x != null & x.getValue() < 5) { // Throws an exception if x is null // Do something

} //ifwe used a logical &, then both sides would always be evaluated and when x was
null this would throw an exception:

Equality Operators
1. Comparing two numeric primitive types. If the numeric values are of different
data types, the values are automatically promoted as previously described. For
example, 5 == 5.00 returns true since the left side is promoted to a double.

2. Comparing two boolean values.


3. Comparing two objects, including null and String values.

The comparisons for equality are limited to these three cases, so you cannot mix and
match types. For example, each of the following would result in a compiler error:
//TODO
boolean x = true == 3; // DOES NOT COMPILEboolean y = false != "Giraffe"; // DOES NOT COMPILE
boolean z = 3 == "Kangaroo"; // DOES NOT COMPILE

For object comparison, the equality operator is applied to the references to the objects,
not the objects they point to. Two references are equal if and only if they point to
the same object, or both point to null.

You might also like