Developing the Java Application
A Java application is a standalone Java program-- a program
written in the Java language that runs independently of any
browser.
Example:
/**
* The HelloWorldApp class implements an application that
* simply displays "Hello World!" to the standard output.
*/
class HelloWorldApp
{
public static void main(String[] args)
{
System.out.println("Hello World!"); //Display the string.
}
}
To
view, how to write,compile and run the Java Program.
Comments in Java Code
The bold characters in the following listing are comments.
/**
* The HelloWorldApp class
implements an application that
* simply displays "Hello World!"
to the standard output.
*/
class HelloWorldApp
{
public static void main(String[] args)
{
System.out.println("Hello World!");
//Display the string.
}
}
The Java language supports three kinds of comments:
/*
text */
The compiler ignores everything from /* to */.
/**
documentation */
This indicates a documentation comment (doc comment, for
short). The compiler ignores this kind of comment, just like
it ignores comments that use /* and */.
//
text
The compiler ignores everything from // to the end of the
line
Defining a Class
The first bold line in the following listing begins a class
definition block.
/**
* The HelloWorldApp class implements an application that
* simply displays "Hello World!" to the standard output.
*/
class HelloWorldApp
{
public static void main(String[] args)
{
System.out.println("Hello World!"); //Display the string.
}
}
A class--the basic building block of an object-oriented
language such as Java--is a template that describes the data
and behavior associated with instances of that class.
The data associated with a class or object is stored in
variables; the behavior associated with a class or object is
implemented with methods. Methods are similar to the
functions or procedures in procedural languages such as C.
In the Java language, the simplest form of a class
definition is
class name
{
. . .
The main Method
The first bold line in the
following listing begins the definition of a main method.
/**
* The HelloWorldApp class implements an application that
* simply displays "Hello World!" to the standard output.
*/
class HelloWorldApp {
public static void main(String[] args)
{
System.out.println("Hello World!"); //Display the string.
}
}
Every Java application must contain a main method whose
signature looks like this:
public static void
main(String[] args)
The method signature for the main method contains three
modifiers:
• public indicates that the main method can be called by
any object.
• static indicates that the main method is a class method.
• void indicates that the main method doesnt return any
value.
How the main Method Gets
Called
The main method in the Java language is similar to the main
function in C and C++. When the Java interpreter executes an
application (by being invoked upon the applications
controlling class), it starts by calling the classs main
method. The main method then calls all the other methods
required to run your application. If you try to invoke the
Java interpreter on a class that does not have a main
method, the interpreter refuses to compile your program and
displays an error message similar to this: In class NoMain:
void main(String argv[]) is not defined
Using Classes and Objects
The "Hello World" application
is about the simplest Java program one can write that
actually does something. Because it is such a simple
program, it doesnt need to define any classes except for
HelloWorldApp.
The "Hello World" application
does use another class--the System class--that is part of
the API (application programming interface) provided with
the Java environment. The System class provides
system-independent access to system-dependent functionality.
The bold code in the following listing illustrates the use
of a class variable of the System class, and of an
instance method.
/**
* The HelloWorldApp class implements an application that
* simply displays "Hello World!" to the standard output.
*/
class HelloWorldApp
{
public static void main(String[] args)
{
System.out.println("Hello
World!");
//Display the string.
}
}
Using a Class Method or Variable
Lets take a look at the first segment of the statement:
System.out
.println("Hello World!");
The construct
System.out is the full name of the out
variable in the System class
Using Classes and Objects
The "Hello World" application
is about the simplest Java program one can write that
actually does something. Because it is such a simple
program, it doesnt need to define any classes except for
HelloWorldApp.
The "Hello World" application
does use another class--the System class--that is part of
the API (application programming interface) provided with
the Java environment. The System class provides
system-independent access to system-dependent functionality.
The bold code in the following listing illustrates the use
of a class variable of the System class, and of an
instance method.
/**
* The HelloWorldApp class implements an application that
* simply displays "Hello World!" to the standard output.
*/
class HelloWorldApp
{
public static void main(String[] args)
{
System.out.println("Hello
World!");
//Display the string.
}
}
Using a Class Method or Variable
Lets take a look at the first segment of the statement:
System.out
.println("Hello World!");
The construct
System.out is the full name of the out
variable in the System class.
Using
an Instance Method or Variable
Methods and variables that are not class methods or class
variables are known as instance methods and instance
variables.
While Systems out variable is a class variable, it refers to
an instance of the PrintStream class (a class provided with
the Java development environment) that implements the
standard output stream.
When the System class is loaded into the application, it
instantiates PrintStream and assigns the new PrintStream
object to the out class variable.
System.out.println("Hello
World!");
This line of code displays "Hello World!" to the
applications standard output stream
Java Program Structure
A Java program may contain one or more section which is as
follow:
1. Documentation section
(suggested)
The documentation section comprises a set of comment line of
the program, the author
and other details, which the programmer would like to refer
to at a later stage.
2. Package statement
(Optional)
This statement declares a package name and inform the
compiler that the class defined here belong to this package.
Ex:
package student;
3. Import Statement
(Optional)
This statement instructs the interpreter to load the
specific class contained in the package.
Ex:
import student. test;
4. Interface Statement
(Optional)
An interface is like a class but include a group of method
declarations.
5. Class Definitions
(Optional)
Classes are the primary and essential elements of Java
program. These classes are used
to map the object of real world problems.
6. Main Method Class
(Essential)
As every Java stand-alone program
requires a main method as its starting point, this class is
the essential part of the program.
Java
Tokens
The smallest individual units in a program are known as
TOKEN.
A java program is a collection of tokens, comments and white
spaces.
Java language includes five types of tokens
They are:
1) Reserved Keyword
2) Identifiders
3) Literals
4) Operator
5) Separators
Reserved Keyword
Keywords have specific meaning and implement specific
features of the language.
Java language has reserved 60 words as keywords.
Identifiers
Identifiers are programmer-designed tokens. They are used
for naming class,
methods, variables, objects, labels, packages, and interface
in a program.
Literals
Literal is a programming language term that essentially
means that what you type is what you get. Numbers,
characters, and strings are all examples of literals.
Therefore literals
Variables
Variables are locations in memory in which values can be
stored. Each one has a name, a type, and a value.
Before we can use a variable, we have to declare it. After
it is declared, we can then assign values to it.
Java actually has three kinds
of variables:
1. instance variables,
2. class variables,
3. And local variables.
Instance variables,
are used to define the attributes of a particular object.
Class variables are similar to instance variables, except
their values apply to all that classs instances (and to the
class itself) rather than having different values for each
object.
Local variables are declared
and used inside method definitions,
Although all three kinds of variables are declared in much
the same ways, class and instance variables are accessed and
assigned in slightly different ways from local variables.
Java does not have global variables-that is, variables that
are global to all parts of a program. Instance and class
variables can be used to communicate global information
between and among objects.
1) Are constants having no identifier.
2) Have their value specified within the programs source
code.
3) Can only appear on the right side of an assignment
operator (=) or within an expression.
4) Have a data type associated with them.
Declaring Variables
To use any variable in a Java program, we must first declare
it. Variable declarations consist of a type and a variable
name:
int myAge;
String myName;
boolean isTired;
Variable definitions can go anywhere in a method definition
(that is, anywhere a regular Java statement can go),
although they are most commonly declared at the beginning of
the definition before they are used:
public static void main (String args[]) {
int count;
String title;
boolean isAsleep;
...
}
We can string together variable names with the same type on
one line:
int x, y, z;
String firstName, LastName;
We can also give each
variable an initial value when we declare it:
int myAge, mySize, numShoes = 28;
String myName = "SOBM";
boolean isTired = true;
int a = 4, b = 5, c = 6;
If there are multiple variables on the same line with only
one initializer the initial
value applies to only the last variable in a declaration.
We can also group individual variables and initializers on
the same line using
commas, as with the last example.
Rules on Variable Names
Variable names in Java can start with a letter, an
underscore (_), or a dollar sign ($). They cannot start with
a number. After the first character, our variable names can
include any letter or number. Symbols, such as %, *, @, and
so on, are often reserved for operators in Java, so we
should be careful when using symbols in variable names. The
Java language uses the Unicode character set. The Java
language is case sensitive, which means that uppercase
letters are different from lowercase letters. This means
that the variable X is different from the variable x, and a
rose is not a Rose is not a ROSE.
Variable Types
In addition to the variable name, each variable declaration
must have a type, which defines what values that variable
can hold.
The variable type can be one of three things:
• One of the eight primitive data types
• The name of a class or interface
• An array
Primitive Data Types
The eight primitive data types handle common types for
integers, floating-point numbers, characters, and boolean
values (true or false).
Theyre called primitive because theyre built into the system
and are not actual objects, which makes them more efficient
to use.
Integer Type
There are four Java integer types, each with a different
range of values.
All are signed, which means they can hold either positive or
negative numbers.
Table 3.1. Integer types
|
Type |
Size |
Range |
|
byte |
8 bits |
-128 to 127 |
|
short |
16 bits |
-32,768 to 32,767 |
|
int |
32 bits |
-2,147,483,648 to 2,147,483,647 |
|
long |
64 bits |
-9,223,372,036,854,775,808 to
9,223,372,036,854,775,807 |
Floating-point type:
Floating-point numbers are used for numbers with a decimal
part.
There are two floating-point types: float (32 bits, single
precision) and double (64 bits, double precision).
Char type:
The char type is used for individual characters. Because
Java uses the Unicode character set, the char type has 16
bits of precision, unsigned.
Constants
• Are similar to variables but, once initialized, their
contents may NOT be changed?
• Are declared with the keyword final?
• By convention, have all capital letters in their
identifier. This makes them easier to see within the code.
Example 1:
This program defines a number of constants and then displays
some of their values.
public class App
{
public static void main(String[] args)
{
final boolean YES = true;
final char DEPOSIT_CODE = D;
final byte INCHES_PER_FOOT = 12;
final int FEET_PER_MILE = 5280;
final float PI = 3.14F;
final double SALES_TAX_RATE = .06;
final String ADDRESS = "119 South Street";
// Display some of the values
System.out.println(INCHES_PER_FOOT);
System.out.println(ADDRESS);
}
}
Example 2:
This program will not compile because an attempt is made to
change the value of its constant.
public class App1
{
public static void main(String[] args)
{
final double SALES_TAX_RATE = .06;
SALES_TAX_RATE = .04;
// Display the sales tax rate
System.out.println(SALES_TAX_RATE);
}
}
Here the compiler error will occur like this
Expressions
and Operators
Operators enable us to perform an evaluation or computation
on a data object or objects.
Operators applied to variables and literals form
expressions.
An expression can be thought of as a programmatic equation.
Therefore, an expression is a sequence of one or more data
objects (operands) and zero or more operators that produce a
result.
An example of an expression follows:
x =
y / 3;
In this expression, x and y are variables, 3 is a literal,
and = and / are operators.
This expression states that the y variable is divided by 3
using the division
operator (/), and the result is stored in x using the
assignment operator (=).
Here the expression is described from right to left.
Operator Precedence
Java expressions are typically evaluated from left to right,
there still are many times when the result of an expression
would be indeterminate without other rules.
The following expression illustrates the problem:
x = 2 * 6 + 16 / 4
By using the left-to-right evaluation of the expression, the
multiplication operation 2 * 6 is carried out first, which
leaves a result of 12. The addition operation 12 + 16 is
then performed, which gives a result of 28. The division
operation 28 / 4 is then performed, which gives a result of
7. Finally, the assignment operation x = 7 is handled, in
which the number 7 is assigned to the variable x.
But--its wrong! The problem is that using a simple
left-to-right evaluation of expressions can yield
inconsistent results, depending on the order of the
operators.
The solution to this problem lies in operator precedence,
which determines the order in which operators are evaluated.
Every Java operator has an associated precedence.
Following is a list of all the Java operators
from highest to lowest precedence.
In this list of operators, all the operators in a particular
row have equal precedence.
The precedence level of each row decreases from top to
bottom. This means that the [] operator has a higher
precedence than the * operator, but the same precedence as
the () operator.
|
. |
[] |
() |
^ |
|
++ |
- |
! |
~ |
|
* |
/ |
% |
& |
|
+ |
- |
|| |
&& |
|
<< |
>> |
>>> |
= |
|
< |
> |
<= |
>= |
|
= |
!= |
?: |
|
|
|
|
Evaluation of expressions still moves from left to right,
but only when dealing with operators that have the same
precedence.
Otherwise, operators with a higher precedence are evaluated
before operators with a lower precedence.
Knowing this, take another look at the sample equation:
x = 2 * 6 + 16 / 4
Before using the left-to-right evaluation of the expression,
first look to see whether any of the operators have
differing precedence.
Here the multiplication (*) and division (/) operators both
have the highest precedence, followed by the addition
operator (+), and then the assignment operator (=).
Because the multiplication and division operators share the
same precedence, evaluate
them from left to right. Doing this, we first perform the
multiplication operation 2 * 6
with the result of 12. Then we perform the division
operation 16 / 4, which results in 4.
After performing these two operations, the expression looks
like this:
x = 12 + 4;
Because the addition operator has a higher precedence than
the assignment operator, we perform the addition operation
12 + 4 next, resulting in 16. Finally, the assignment
operation x = 16 is processed, resulting in the number 16
being assigned to the variable x.
As we can see, evaluating the expression using operator
precedence yields a completely different result.
Just to get the point across, take a look at another
expression that uses parentheses for grouping purposes:
x = 2 * (11 - 7);
Without the grouping parentheses, we would perform the
multiplication operation first and then the subtraction
operation. However, referring back to the precedence list,
the () operator comes before all other operators. So the
subtraction operation 11 - 7 is performed first, yielding 4
and the following expression:
x = 2 * 4;
The rest of the expression is easily resolved with a
multiplication operation and an assignment operation to
yield a result of 8 in the variable x.