Java Basics Notes
Java Basics Notes
Java Basics Notes
Java Basics
Topics in this section include:
• Comments
• Declarations
• Expressions
• Statements
• Garbage collection
• Java Semantics
Portability
Java programs are portable across operating systems and hardware environments.
Portability is to your advantage because:
• You need only one version of your software to serve a broad market.
1. The language. The Java language is completely specified; all data-type sizes and
formats are defined as part of the language. By contrast, C/C++ leaves these
"details" up to the compiler implementor, and many C/C++ programs therefore
2. The library. The Java class library is available on any machine with a Java
runtime system, because a portable program is of no use if you cannot use the
same class library on every platform. Window-manager function calls in a Mac
application written in C/C++, for example, do not port well to a PC.
3. The byte code. The Java runtime system does not compile your source code
directly into machine language, an inflexible and nonportable representation of
your program. Instead, Java programs are translated into machine-independent
byte code. The byte code is easily interpreted and therefore can be executed on
any platform having a Java runtime system. (The latest versions of the Netscape
Navigator browser, for example, can run applets on virtually any platform).
Security
The Java language is secure in that it is very difficult to write incorrect code or
viruses that can corrupt/steal your data, or harm hardware such as hard disks.
There are two main lines of defense:
• Interpreter level:
• No pointer arithmetic
• Garbage collection
Robustness
The Java language is robust. It has several features designed to avoid crashes
during program execution, including:
• No pointer arithmetic
• Applets are not allowed to use file I/O and sockets (other than to the host
platform). Applications do not have these restrictions.
• An applet must be a subclass of the Java Applet class. Aplications do not need to
subclass any particular class.
There is no link phase for Java programs; all linking is done dynamically at
runtime.
The following diagram shows an example of the Java compilation and execution
sequence for a source file named A.java containing public class A and non-public
class B:
Java programs are, in effect, distributed applications. You may think of them as a
collection of DLLs (dynamically loadable libraries) that are linked on demand at
runtime. When you write your own Java applications, you will often integrate
your program with already-existing portions of code that reside on other
machines.
A Simple Application
Consider the following trivial application that prints "hi there" to standard
output:
The command java TrivialApplication tells the Java runtime system to begin
with the class file TrivialApplication.class and to look in that file for a
method with the signature:
The main() method will always reside in one of your class files. The Java
language does not allow methods outside of class definitions. The class, in effect,
creates scoped symbol StartingClassName.main for your main() method.
Applet Execution
An applet is a Java program that runs within a Java-compatible WWW browser or
in an appletviewer. To execute your applet, the browser:
• init(). This method takes the place of the Applet constructor and is only called
once during applet creation. Instance variables should be initialized in this method.
GUI components such as buttons and scrollbars should be added to the GUI in
this method.
• start(). This method is called once after init() and whenever your applet is
revisited by your browser, or when you deiconify your browser. This method
should be used to start animations and other threads.
• paint(Graphics g). This method is called when the applet drawing area needs
to be redrawn. Anything not drawn by contained components must be drawn in
this method. Bitmaps, for example, are drawn here, but buttons are not because
they handle their own painting.
• stop(). This method is called when you leave an applet or when you iconify
your browser. The method should be used to suspend animations and other
• destroy(). This method is called when an applet terminates, for example, when
quitting the browser. Final clean-up operations such as freeing up system
resources with dispose() should be done here. The dispose() method of Frame
removes the menu bar. Therefore, do not forget to call super.dispose() if you
override the default behavior.
The basic structure of an applet that uses each of these predefined methods is:
import java.applet.Applet;
// include all AWT class definitions
import java.awt.*;
All you have to do is fill in the appropriate methods to bring your applet to life. If
you don't need to use one or more of these predefined methods, simply leave them
out of your applet. The applet will ignore messages from the browser attempting
to invoke any of these methods that you don't use.
A Simple Applet
The following complete applet displays "Hello, World Wide Web!" in your
browser window:
import java.applet.Applet;
import java.awt.Graphics;
HTML/Applet Interface
The HTML applet tag is similar to the HTML img tag, and has the form:
where the optional parameters are a list of parameter definitions of the form:
The code, width, and height parameters are mandatory. The parameters
codebase, alt, archives, align, vspace, and hspace are optional within the
<applet> tag itself. Your applet can access any of these parameters by calling:
Applet.getParameter("p")
which returns the String value of the parameter. For example, the applet:
import java.applet.Applet;
width is 300
p1 is 34
p2 is test
Comments
Java comments are the same as C++ comments, i.e.,
where all text between the opening /* and closing */ is ignored, and
where all text from the opening // to the end of the line is ignored.
Note that these two comments can make a very useful combination. C-style
comments (/* ... */) cannot be nested, but can contain C++ style comments.
This leads to the interesting observation that if you always use C++-style
comments (// ...), you can easily comment out a section of code by surrounding
it with C-style comments. So try to use C++ style comments for your "normal"
code commentary, and reserve C-style comments for commenting out sections of
code.
Declarations
A Java variable may refer to an object, an array, or an item of primitive type.
Variables are defined using the following simple syntax:
TypeName variableName;
For example,
Primitive Types
The Java language has the following primitive types:
Primitive Types
boolean true/false
byte 8 bits
short 16 bits
int 32 bits
long 64 bits
Java int types may not be used as boolean types and are always signed.
Objects
A simple C++ object or C struct definition such as "Button b;" allocates
memory on the stack for a Button object and makes b refer to it. By contrast, you
must specifically instantiate Java objects with the new operator. For example,
// Java code
void foo() {
// define a reference to a Button; init to null
Button b;
// allocate space for a Button, b points to it
b = new Button("OK");
int i = 2;
}
As the accompanying figure shows, this code places a reference b to the Button
object on the stack and allocates memory for the new object on the heap.
The equivalent C++ and C statements that would allocate memory on the heap
would be:
// C++ code
Button *b = NULL; // declare a new Button pointer
b = new Button("OK"); // point it to a new Button
/* C code */
Button *b = NULL; /* declare a new Button pointer */
b = calloc(1, sizeof(Button)); /* allocate space for a Button */
init(b, "OK"); /* something like this to init b */
All Java objects reside on the heap; there are no objects stored on the stack.
Storing objects on the heap does not cause potential memory leakage problems
because of garbage collection.
Each Java primitive type has an equivalent object type, e.g., Integer, Byte,
Float, Double. These primitive types are provided in addition to object types
purely for efficiency. An int is much more efficient than an Integer.
Strings
Java string literals look the same as those in C/C++, but Java strings are real
objects, not pointers to memory. Java strings may or may not be null-terminated.
Every string literal such as
Java strings are constant in length and content. For variable-length strings, use
StringBuffer objects.
You may concatenate any object to a string. You use the toString() method to
convert objects to a String, and primitive types are converted by the compiler.
For example,
The length of a string may be obtained with String method length(); e.g.,
"abc".length() has the value 3.
String s = String.valueOf(4);
int a = Integer.parseInt("4");
Array Objects
In C and C++, arrays are pointers to data in memory. Java arrays are objects that
know the number and type of their elements. The first element is index 0, as in
C/C++.
# elements
element type
element 0
element 1
...
element n-1
TypeName[] variableName;
This declaration defines the array object--it does not allocate memory for the array
object nor does it allocate the elements of the array In addition, you may not
specify a size within the square brackets.
int
or
new Button[5]
Button
null pointer
null pointer
null pointer
null pointer
null pointer
setTitle(a[3], "QUIT");
Accessing a defined array element that has not yet been assigned to an object
results in a runtime NullPointerException.
Initializers
• Primitive types
int i = 3;
boolean g = true;
• Objects
Button b = null;
Employee e = new Employee();
• Arrays
or in Java 1.1
int[] i;
i = new int[] {1, 2, 3, 4};
Constants
Expressions
Most Java expressions are similar to those in C/C++.
Constant Expressions
id i, nameList
Integer.MAX_VALUE, obj.member,
qualified-id npackage.class, package.obj
int constant 4
General Expressions
id i, nameList
( expr ) (3+4)*7
Operators
The Java language has added the >>> zero-extend right-shift operator to the set of
C++ operators. (C++ operators include instanceof and new, which are not
present in C. Note that sizeof has been removed, as memory allocation is
handled for you.) The operators, in order of highest to lowest priority, are:
• new
• .
• -- ++ + - ~ ! (TypeName)
• * / %
• + -
• << >> >>>
• < > <= >= instanceof
• == !=
• &
• ^
• |
• &&
• ||
• ?:
• = *= /= %= += -= <<= >>= >>>= &= ^= |=
Note that the precedence of the new operator and the '.' operator bind
// Java code
new T().method();
// C++ code
(new T)->method();
Statements
Java statements are similar to those in C/C++ as the following table shows.
Statement Examples
if (boolean-expr) stat1
if
if (boolean-expr) stat1 else stat2
switch (int-expr) {
case int-const-expr : stat1
switch case int-const-expr : stat2
default : stat3
}
The Java break and continue statements may have labels. These labels refer to
the specific loop that the break or continue apply to. (Each loop can be
preceded by a label.)
Java Semantics
We say that the Java language has "reference semantics" and C/C++ have "copy
semantics." This means that Java objects are passed to methods by reference in
Java, while objects are passed by value in C/C++.
Java primitive types, however, are not treated in the same way as Java objects.
Primitive types are assigned, compared, and passed as arguments using copy
semantics, just as in C/C++. For example, i = j for two int variables i and j
performs a 32-bit integer copy.
Assignment of Objects
Assignment makes two variables refer to the same object. For example,
class Data {
public int data = 0;
public Data(int d) { data = d; }
}
...
Note: The above class definition requires exception handling code. We, however,
have not yet discussed exception handling. For now, pretend that it is not
necessary.
// C++ code
or, in C
/* C code */
// Java code
Equality
Two Java primitive types are equal (using the == operator) when they have the
same value (e.g., "3 == 3"). However, two object variables are equal if and only if
they refer to the same instantiated object--a "shallow" comparison. For example,
void test() {
Data a = new Data(1);
Data b = new Data(2);
Data c = new Data(1);
// a == b is FALSE
// a == c is FALSE (in C++, this'd be TRUE)
Data d = a;
Data e = a;
// d == e is TRUE,
// d,e are referring to same object
}
class Data {
public int data = 0;
public Data(int d) { data = d; }
boolean equals(Data d) {
return data == d.data;
}
}
...
No Pointers!
The Java language does not have pointer types nor address arithmetic. Java
variables are either primitive types or references to objects. To illustrate the
difference between C/C++ and Java semantics, consider the following equivalent
code fragments.
// Java code
Garbage Collection
An automatic garbage collector deallocates memory for objects that are no longer
needed by your program, thereby relieving you from the tedious and error-prone
To illustrate the effect of a garbage collector, consider the following C++ function
that allocates 1000 objects on the heap via the new operator (a similar C function
would allocate memory using calloc/malloc):
// C++ code
void f() {
T *t;
for (int i = 1; i <= 1000; i++) {
t = new T; // ack!!!!!
}
}
Every time the loop body is executed, a new instance of class T is instantiated, and
t is pointed to it. But what happens to the instance that t used to point to? It's
still allocated, but nothing points to it and therefore it's inaccessible. Memory in
this state is referred to as "leaked" memory.
In the Java language, memory leaks are not an issue. The following Java method
causes no ill effects:
// Java code
void f() {
T t;
for (int i = 1; i <= 1000; i++) {
t = new T();
}
}
In Java, each time t is assigned a new reference, the old reference is now available
for garbage collection. Note that it isn't immediately freed; it remains allocated
until the garbage collector thread is next executed and notices that it can be freed.