Java Intro
Java Intro
Java Intro
Java is case sensitive, i.e. the word Program is different from program.
Curly brackets { and } are used to group statements together.
An executable Java program must contain at least the following lines as a framework:
public class Name
{ public static void main(String args[])
{ ... program code ...
}
}
Every statement whose next statement is not a separate group must end in a semicolon.
A Java program containing the above framework must be saved using the filename
Name.java, where Name (including correct upper and lower cases) is the word that follows
the keywords public class and the file extension is .java.
p u b lic c la s s N a m e
public static void main(String args[])
program code
In other words, to create a Java program you first create a text file containing the lines
Java does have disadvantages. For example, programs written in Java are generally slower than those in C++ and it
is difficult to accomplish system-level tasks in Java.
2
Java compilers and tools are available for free, an important consideration for academic and student budgets.
The file containing our code is called the source code file.
Source Code
A Java source code file is a text file that contains programming code written according to the
Java language specifications, resembling a mixture of mathematical language and English. A
computer cannot execute source code, but humans can read and understand it.
Java source code files should be saved as Name.java, where Name is the name that appears in the
first line of the program: public class Name. That Name is referred to as the name of the class,
or program. By convention its first letter is capitalized.
p u b lic c la s s N a m e
public static void main(String args[])
program code
save as
This program, or class, is called Test and must be saved under the file name Test.java.
is accomplished using the Java compiler javac from the Java Developer's Kit (JDK), which could be
invoked by an IDE such as BlueJ.
Compiling
Compiling is the process of transforming the source code file into a format that the computer can
understand and process. The resulting file is called the byte-code, or class, file. The name of the
class file is the same as the name of the program plus the extension .class. The program javac
from the Java Developer's Kit is used to transform a source code file into a class file.
p u b lic c la s s N a m e
public static void main(String args[])
pr ogram code
save as
ja v a c
If a source code contains any errors, they are flagged by the compiler. You need to fix them and recompile until there are no further errors.
Tip: In case of an error, the javac compiler shows the line number and position of where it
thinks the error occurred in your source code.
If the compiler points out an error, then there is an error at or before the indicated position.
If the compiler reports a certain number of errors, than this is the least amount of errors.
If one error is fixed, other errors may automatically disappear or new ones may appear.
Fix your source code a few errors at a time. Recompile often to see if the number of errors and
the error messages change until no errors are reported. If you can not find an error at the
position indicated by the compiler, look at the code before that position.
Under Windows and Unix, execute a program by typing at the command prompt java Name,
where Name is the name of the program (no extension). On a Macintosh, double-click the java
icon and select the appropriate class file.
Most IDEs allow for a convenient way to execute a file. In BlueJ you right-click on a compiled class
and select the main method.
p u b lic c la s s N a m e
public static void main(String args[])
prog ra m code
save as
ja v a c
ja v a
If that line is not present in your source code, the JVM can not execute your program and
displays an error message.
At this point, we need to explain what the Java Virtual Machine is and how it relates to the
operating system and to Java class files.
In general, the Java Virtual Machine is an abstractly specified class file interpreter that can be realized by different
software makers. The JVM that comes with the JDK was created by SUN Microsystems, but any other JVM is also
able to run the same class files. Different JVM's can vary in efficiency, but they all must run the same class files.
The JVM, in other words, forms a layer between the operating system and the Java program that is
trying to execute. That explains how one Java program can run without change on a variety of
systems: it can not! A Java program runs on only one system, namely the Java Virtual Machine. That
virtual system, in turn, runs on a variety of operating systems and is programmed quite differently
for various systems. To the Java programmer, it provides a unified interface to the actual system
calls of the operating system.4
You can include graphics, graphical user interface elements, multimedia, and networking operations
in a Java program and the JVM will negotiate the necessary details between the class file(s) and the
underlying operating system. The JVM produces exactly the same results in theory regardless of
the underlying operating system. In the Basic (or C, or C++) programming language, for example,
you can create code that specifies to multiply two integers 1000 and 2000 and store the result as
another integer. That code works fine on some systems, but can produce negative numbers on others. 5
In Java, this can not happen: either the code fails on all platforms, or it works on all platforms.
Java S ource
C ode
U n ix
ja v a c
W in
ja v a c
U n ix
W in
M ac
ja v a c
M ac
J a v a V ir tu a l
M a c h in e
J a v a B y te
C ode
O p e r a tin g -s y s te m
d e p e n d e n t to o ls
O p e r a tin g -s y s te m
in d e p e n d e n t
U n ix
ja v a
W in
ja v a
M ac
ja v a
This is somewhat similar to old Basic programs: a simple Basic program can run on virtually any system that has a
Basic interpreter installed since the interpreter mediates between the program trying to run and the operating system.
5
Programming languages have a largest possible integer whose value can differ on different systems. A C++
program executing on a machine with a largest integer bigger than 2,000,000 produces the correct result, but on a
system where the largest integer is, say, 32,767 it fails. The JVM has the same largest integer on every platform.
int, long,
double
or short
or float
char
boolean
void
Each numeric type has a largest and smallest possible value, as indicated in table 1.10. 6
Most programs use int for integers and double for decimal numbers, while long, short, and float
are needed only in special situations.
Type
double
Range
largest positive/negative value:
smallest non-zero value:
significant digits:
float
int
largest value
smallest value:
short
largest value
smallest value:
long
largest value
1.7976931348623157E308
4.9E-324
16 digits after decimal point
3.4028235E38
1.4E-45
8 digits after decimal point
2147483647
-2147483648
32767
-32768
9223372036854775807
Literals
Literals are constant values for the basic data types. Java supports the following literals:
int, short:
long:
digits only, with possible leading plus (+) or minus (-) sign
like int literals, but must end with an "L"
Java also supports a basic type byte, which we do not need currently, and another very useful type String,
introduced later
double:
float:
boolean:
digits including possible periodic point or leading plus ( +) or minus (-) sign,
or numbers in scientific notation #.###############E###,7 where each #
represents a digit
like double literals, but must end with an "F"
Single Unicode characters enclosed in single quotes, including the special
control sequences described in table 1.118
true or false
char:
In addition, Java has an object literal called null for object references.
Character literals include the following special characters called control sequences:
Control
Meaning
Sequence
Control
Meaning
Sequence
\n
new line
\t
tab character
\b
backspace
\r
return
\f
form feed
\\
backslash
\'
single quote
\"
double quote
Table: Common character control sequences
The ranges for the numeric types are the same, regardless of the underlying operating system (after
all, programs run under the JVM, not the native operating system). In languages such as C or C++
an integer sometimes has a range similar to a Java short, and sometimes that of a Java int,
depending on the underlying operating system, which can cause different results if the same
program runs on different systems.
To use the basic data types to store information, we must define variables that have one of these
types:
Declaration of Variables
To declare a variable that can store data of a specific type, the syntax:
type varName [, varName2,..., varNameN];
is used, where type is one of the basic data types, varName is the name of the variable, and
varName2, ..., varNameN are optional additional variables of that type. Variables can be
declared virtually anywhere in a Java program.
Variables must have a name and there are a few rules to follow when choosing variable names:
boolean
Class
Else
For
Int
Package
Static
Throws
While
break
const
extends
goto
interface
private
super
transient
byte
continue
false
if
long
protected
switch
true
case
default
final
implements
native
public
synchronized
try
catch
do
finally
import
new
return
this
void
Assignments are made by first evaluating the expression on right, then assigning the resulting
value to the variable on the left. Numeric values of a type with smaller range are compatible with
numeric variables of a type with larger range (compare table 13). Variables can be declared and
assigned a value in one expression using the syntax:
type varName = expression [, varname2 = expression2, ...];
The assignment operator looks like the mathematical equal sign, but it is different. For example, as a
mathematical expression
x 2x 1
is an equation which can be solved for x. As Java code, the same expression
x = 2*x + 1;
means to first evaluate the right side 2*x + 1 by taking the current value of x, multiplying it by 2,
and adding 1. Then the resulting value is stored in x (so that now x has a new value).
Value and variable types must be compatible with each other, as shown in table 1.13.
Value Type
double
int
int, double
char
boolean
double
char, int, double
boolean
Software Engineering Tip: Variables serve a purpose and the name of a variable should
reflect that purpose to improve the readability of your program. Avoid one-letter variable names 9.
Do not reuse a variable whose name does not reflect its purpose.
If a variable serves a minor role in a code segment (such as a counter in a loop) it can be declared using a one-letter
variable name.
Whenever possible, assign an initial value to every variable at the time it is declared. If a
variable is declared without assigning a value to it, all basic types except boolean are
automatically set to 0, boolean is set to false, and all other types are set to null.10
Declare variables as close as possible to the code where they are used. Do not declare all
variables at once at the beginning of a program (or anywhere else).
This code computes the perimeter z of a rectangle with width x and length y and the area w of a
triangle with base x and height y, so the variable names should reflect that. In addition, variables
should be assigned a value when they are declared, so the code segment should be rewritten as
follows:
double
double
double
double
It is immediately clear that the formulas used are correct. Choosing appropriate variable names
clarifies the code significantly and makes it easy to locate potential problems.
10
Left
Right
Argument
Argument
int
int
double
double
int
double
int
double
Result
int
double
double
double
The compiler may display an error message if it encounters variables that are not explicitly initialized.