Lecture 1: Java Compiler, Programs, Applets, Types, Control, I/O,
Variables, Assignments
Java is a programming language created by Sun
Mircosystems. It is a powerful, modern programming language related to C++ that improves
the useful features of C++ and removes the idiosyncrasies of that language. Among the
features that make Java the current language of choice are:
| Platform independent: programs written in Java run without changes on Windows 95,
Windows NT, Macintosh, or Unix systems (and soon Windows 3.1). |
| Object Oriented: Java is completely and entirely object oriented. You can not
simply write a small program. Everything needs to be written as objects with
methods. |
| Multi-threaded: Java easily supports the creation of multi-tasking programs, i.e.
programs where more than one thing happen simultaneously |
| Network support: Java has network support built-in. It is easy to create two
programs that communicate with each other across the internet. |
| Exception handling: Java has a sophisticated method of handling run-time errors.
Every object can throw an exception, i.e. an unexpected error in a program,
and that error can be caught gracefully |
| Supporting Objects: Java has a wealth of objects already defined that can be
utilized to quickly create reasonably complex programs, complete with graphical user
interface |
| Easy and Modern: Java has no pointers and automatically performs garbage
collection. You can, however, still have dynamic structures quite easily. |
- Here is how to create a program using the Java Development Kit provided by Sun free of
charge:
| You use a plain text editor to create the source file, named SomeName.java |
| You call up the Java compiler to compile the file into SomeName.class. This
file is not an object file usually created by other compilers, but what is called a
byte-code file. To compile, use the syntax javac SomeName.java |
| You start the Java Virtual Machine (JVM) which runs the byte-code in an interpreter. In
other words, your programs dont actually run on your computer, but a virtual
computer is created inside your computer, and that virtual computer interprets and
executes the byte-code file. That is why Java can be platform independent: all Java
programs run inside the JVM, which is identical on every platform. The interface of the
JVM to the actual computer is, of course, implemented differently on different platforms,
but that is of no concern to the Java programmer. To create the JVM and execute your
program, there are two distinct possibilities: |
| To create the JVM and execute a standalone program, use: java
SomeName |
| To run a program inside a web browser, the web browser provides the JVM and the
input/output contexts. Such programs are called applets. See the example below for
details. |
In the following, well review some standard constructions that any programming
language has, and well see how the particular Java implementation looks like:
General Information:
| Java is case sensitive and almost all Java statements must be ended with a
semicolon |
| Curly brackets are used to group statements together. An instruction block is either a
single Java statement followed by a semicolon or a group of statements enclosed in curly
brackets. |
| Any text starting the // will be treated as a comment up to the end of that
line. You can comment out large blocks by using /* comments spanning several lines */ |
Basic Data Types:
| Java provides the following basic data types: int, double, char,
and boolean. In addition, there are the types Double, Int, Boolean,
Char, and String. The capitalized versions are actually objects, but for
now the String object should be treated as a basic data type. |
| Character constants are enclosed in single quotes, String constants are enclosed in
double quotes. |
Declaring Variables:
| Variables can be declared (almost) anywhere in the code. They can also be initialized at
the time they are declared. A variable declaration looks like: Type VarName1 =
InitialVal1, VarName2 = InitialVal2, ..., VarNameN = InitialValN; |
| Initializing a variable when declaring it is optional but highly recommended. Variables
remain valid within the block they are defined. |
Assignment:
| Variables are assigned values using the single equal sign. More than one variable can be
assigned a value at one time. Assignments look like:
VarName1 = VarName2 = ... = VarNameN = value; |
| First, the right side of an assignment is evaluated, if necessary, then the final value
is assigned to the variable(s), from right to left. |
Boolean Operations:
| There are the usual boolean operations not, and, or, equal, but they dont look
like it. Instead: and is && or is || not is ! equal is == |
| There are also the usual comparison operators >, <, >=, <=. Boolean
operations should be enclosed in standard parenthesis. |
Basic Arithmetic:
| Java uses the standard symbols +, -, *, / to denote the basic operations. % stands for
modulus. The usual order of operations applies and can be changed by using regular
parentheses. |
| There are a few shortcuts commonly employed in the Java programming language: |
| var++ stands for var = var + 1 |
| var-- stands for var = var - 1 |
| var1+=var2 stands for var1 = var1 + var2 |
| var1*=var2 stands for var1 = var1 * var2 |
| Strings can be concatenated using the "+" symbol, and if data types such as
double or int are added to strings they will be automatically converted to
their string equivalent and concatenated in the appropriate order. |
| All standard math operations such as sin, cos, sqrt, etc. are available but must be
imported from a Java component called java.lang.Math. |
Flow control:
| Basic flow control is done through the if statement, which can be nested.
The forms of the if statement are: |
if (test)
instruction block
|
if (test)
instruction block
else
instruction block
|
if (test)
instruction block
else if (test)
instruction block
else
instruction block
|
if (GPA > 90)
Grade = A;
|
if (GPA > 70)
Grade = P;
else
Grade = F
|
if (GPA >= 90)
Grade = A;
else if (GRPA >= 80)
Grade = B;
else
Grade = C;
|
Loop Control:
| Basic loop control is handled by for and while statements. They have
the following syntax: |
while (test)
instruction block
|
for (initialization; test; modification)
instruction block
|
int i = 0;
while (i < 10)
{
// whatever;
i++;
}
|
for (int i=0; i<10; i++)
{
// whatever
}
|
Basic IO:
Java automatically provides two output sources called System.out and
System.err and one input source, called System.in. Usually the
output sources are the screen and the input source is the keyboard. System.out
is used for standard output, while System.err is used to print error message.
To write to an output source, use System.out.println(Strings) To read the value of a
variable, use System.in.read(charVariable). However, the System.in.read method
is more complicated and will be dealt with later.
Now all we need to get started is the structure of a basic Java program/applet. Here are
two elementary examples:
A Basic Java Program
public class Test
{
public static void main(String[] args)
{
System.out.println("Hello, world.");
}
}
To compile into byte-code:
To run the program
Notice that the file name for a public class must be the same as the name of the
class, including capitalization. In general, it has several advantages if the name of a
class is always the same as the filename.
A Basic Java Applet:
import java.applet.Applet; // importing the Applet object
import java.awt.*; // importing the abstract
window toolkit
public class Test extends Applet
{
public void paint(Graphics g)
{
g.drawString("Hello, world.",10,10);
}
}
To compile into byte-code:
To run inside a web browser you first need to create an HTML file such as this:
<HTML>
<BODY>
<APPLET CODE="Test.class" WIDTH=150 HEIGHT=50>
</APPLET>
</BODY>
</HTML>
This HTML file can have any name (but the Java source file must still have the same name
as the name of the class). Then open this file in a java-enabled web browser or an
appletviewer provided by the JDK.
Now we are ready for some more elaborate examples:
Examples:
Write a Java program that defines a real variable Celsius, initializes it to 75,
converts it to Fahrenheit, and writes the result to the screen.
public class Test1
{
public static void main(String[] args)
{
double Celsius = 75;
double Fahrenheit = 1.8 * Celsius + 32;
System.out.println(Celsius + " deg C = " + Fahrenheit + " deg F");
}
}
Write a Java program that writes out the first 20 numbers together with their squares
and square roots.
import java.lang.Math;
public class Test2
{
public static void main(String[] args)
{
for (int I = 0; I < 20; I++)
{
System.out.println(I + " squared: " + I*I + "square root: " + Math.sqrt(I));
}
}
}
Write a Java program that writes out the first 40 numbers, but only every third,
together with their squares:
public class Test3
{
public static void main(String[] args)
{
for (int I = 0; I < 20; I+=3)
{
System.out.println(I + " squared is " + I*I);
}
}
}
Write a Java program using a while loop to go through the first 20 numbers, printing out
even or odd for the corresponding number.
public class Test4
{
public static void main(String[] args)
{
int I = 0;
while (I < 20)
{
if ( (I % 2) == 0)
System.out.println(I + " is even");
else if ( (I % 2) == 1)
System.out.println(I + " is odd");
else
System.out.println("found a new number !!");
I++;
}
}
}