Download Java Programming: An Object-Oriented Language with GUI and Internet Support and more Study notes Computer Science in PDF only on Docsity!
Introduction to Java Programming
Java is a powerful object-oriented programming language introduced by Sun Microsystems in
1995, which has built-in support to create programs with a graphical user interface (GUI),
utilize the Internet, create client-server solutions, and much more. Programs written in Java
can run, without change, on any of the common computer operating systems Windows
95/NT, Macintosh, and Unix. A variant of Java programs called applets can be embedded
inside a web page and execute on the computer that is viewing the page, automatically and
in a secure environment.
As a language, Java is closely related to C++, which is also object-oriented but retains a lot
of idiosyncrasies inherited from its predecessor language C. Java has removed the
inconsistent elements from C++, is exclusively object-oriented, and can be considered a
modern version of C++.^1 Because of its logical structure Java has quickly become a popular
choice as a teaching language,^2 and because of its extensive Internet support and the
promise of writing programs once and using them on every operating system Java is
becoming more and more accepted in industry.
Basic Java Programming Guidelines
Every Java program must follow these guidelines:
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 l i c c l a s s N a m e
p u b l i c s t a t i c v o i d m a i n ( S t r i n g a r g s [ ] ) p r o g r a m c o d e
In other words, to create a Java program you first create a text file containing the lines
public class Name { public static void main(String args[])
1 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.
... more lines ... } }
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 l i c c l a s s N a m e p u b l i c s t a t i c v o i d m a i n ( S t r i n g a r g s [ ] ) p r o g r a m c o d e s a v e a s
Figure: Saving a Java source code file
Here is an example of a Java source code file. We will later explain what the various lines
mean; for now it is simply a text file that looks as shown.
Example: The first source code file
Create a source code file containing the necessary Java code to get the computer to write "Hi – this
is my first program" on the screen.
Our first Java program looks as follows:
public class Test { public static void main(String args[]) { System.out.println("Hi – this is my first program"); } }
This program, or class, is called Test and must be saved under the file name Test.java.
Compiling a Java Program or Class
A source code file, which is more or less readable in plain English, needs to be transformed
into another format before the computer can act upon it. That translation process is called
compiling and 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
Most IDE’s 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 l i c c l a s s N a m e p u b l i c s t a t i c v o i d m a i n ( S t r i n g a r g s [ ] ) p r o g r a m c o d e s a v e a s j a v a c j a v a
Figure: Executing a class file
A good question at this point is which line in a Java program executes first.
Default Program Entry Point The default program entry point is that part of a class (or program) where execution begins. For every Java class (or program), the standard program entry point consists of the line: public static void main(String args[]) 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.
Java Virtual Machine (JVM) The Java Virtual Machine (JVM) is a platform-independent engine used to run Java applets and applications. The JVM knows nothing of the Java programming language, but it does understand the particular file format of the platform and implementation independent class file produced by a Java compiler. Therefore, class files produced by a Java compiler on one system can execute without change on any system that can invoke a Java Virtual Machine.^3 When invoked with a particular class file, the JVM loads the file, goes through a verification process to ensure system security, and executes the instructions in that class file.
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
3 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.
4 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.
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.
j a v a c (^) j a v a c j a v a c j a v a j a v a J a v a S o u r c e C o d e J a v a B y t e C o d e J a v a V i r t u a l M a c h i n e O p e r a t i n g - s y s t e m d e p e n d e n t t o o l s O p e r a t i n g - s y s t e m i n d e p e n d e n t j a v a U n i x W i n M a c U n i x W i n M a c U n i x W i n M a c
Figure 1.09: Illustrating the machine dependent/independent parts of Java programs
Because the JVM is in effect its own computer, it can shield the actual computer it is running
on from potentially harmful effects of a Java program. This is especially important because
Java programs known as applets can automatically start executing on your machine when
you are surfing the web if the appropriate feature of your web browser is enabled. If these
programs were allowed to meddle with your system, you could accidentally execute a
program that would proceed to erase your entire disk. That, of course, would prompt people
to disable Java on their web browser, which in turn would be bad news for anyone who
supports the Java concept.
Basic Data Types: Primitive Java Data Types Java supports the following primitive, or basic, data types: int , long, or short to represent integer numbers double or float to represent decimal numbers char to represent character values boolean to represent logical values void to represent "no type" Each numeric type has a largest and smallest possible value, as indicated in table 1.10.^6
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.
6 Java also supports a basic type byte, which we do not need currently, and another very useful type String,
introduced later
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:
Valid Names for Variables A variable name must start with a letter, a dollar sign '$', or the underscore character '', followed by any character or number. It can not contain spaces. The reserved keywords listed in the table below can not be used for variable names. Variable names are case-sensitive._
Java Reserved Keywords
Abstract boolean break byte case catch Char Class const continue default do Double Else extends false final finally Float For goto if implements import instanceof Int interface long native new null Package private protected public return short Static super switch synchronized this throw Throws transient true try void volatile While Table 1.12: Reserved keywords in Java
Example: Declaring variables
Declare one variable each of type int, double, char, and two variables of type boolean.
This is an easy example. We declare our variables as follows:
int anInteger; double aDouble; char aChar; boolean aBoolean, anotherBoolean; Assigning a Value to a Variable To assign a value to a declared variable, the assignment operator "=" is used: varName = [varName2 = ... ] expression;
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 2 x 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 Compatible Variable Type
double double
int int, double
char char, int, double
boolean boolean Table 1.13: Value types compatible to variable types
Example: Declaring variables and assigning values
Declare an int, three double, one char, and one boolean variable. Assign to them some suitable
values.
There are two possible solutions. Variables can be declared first and a value can be assigned
to them at a later time:
int anInteger; double number1, number2, number3; anInteger = 10; number1 = number2 = 20.0; number3 = 30; char cc; cc = 'B'; boolean okay; okay = true;
Alternatively, variables can be declared and initialized in one statement:
int anInteger = 10; double number1 = 20.0, number2 = 20.0, number3 = 30; char cc = 'B'; boolean okay = true;
Table: Resulting types of the basic arithmetic operations
Example: A Temperature Conversion Program
Create a complete program that converts a temperature from degrees Fahrenheit in degrees Celsius.
Use comments to explain your code.
public class Converter { public static void main(String args[]) { // Printing out a welcoming message System.out.println("Welcome to my Temperature Converter."); System.out.println("\nProgram to convert Fahrenheit to Celcius.\n"); // Defining the temperature value in Fahrenheit double temp = 212.0; // Applying conversion formula and storing answer in another variable double convertedTemp = 5.0 / 9.0 * (temp - 32.0); // Printing out the complete answer System.out.println(temp + " Fahrenheit = " + convertedTemp + " Celcius."); } }