1 1 Chapter 1 Introduction To Java Programming
1 1 Chapter 1 Introduction To Java Programming
1 1 Chapter 1 Introduction To Java Programming
INTRODUCTION TO
OBJECT ORIENTED PROGRAMMING
IN JAVA
Overview of Java Programming and Java Types
Java – the world’s most widely used computer programming language. Java is the preferred
language for meeting many organizations’ enterprise programming needs. Java has also
become the language of choice for implementing Internet-based applications and software for
devices that communicate over a network.
Java programming language was originally developed by Sun Microsystems which was
initiated by James Gosling and released in 1995 as core component of Sun Microsystems‘ Java
platform (Java 1.0 [J2SE]). Sun Microsystems in 1991 funded an internal corporate research
project led by James Gosling, which resulted in a C++-based object-oriented programming
language Sun called Java.
With the advancement of Java and its widespread popularity, multiple configurations were built
to suite various types of platforms. Ex: J2EE for Enterprise Applications, J2ME for Mobile
Applications. Sun Microsystems has renamed the new J2 versions as Java SE, Java EE and Java
ME, respectively.
A key goal of Java is to be able to write programs that will run on a great variety of computer
systems and computer-control devices. This is sometimes called “write once, run
anywhere.” Java is guaranteed to be “Write Once, Run Anywhere”.
Java Editions
1
• Java Enterprise Edition (EE) – is geared toward developing large-scale, distributed
networking applications and web-based applications. In the past, most computer
applications ran on “standalone” computers (computers that were not networked
together). Today’s applications can be written with the aim of communicating among the
world’s computers via the Internet and the web.
• Java Mobile Edition (ME) – is geared toward developing applications for small,
memory-constrained devices, such as BlackBerry smartphones. The Java ME platform
provides an API and a small-footprint virtual machine for running Java programming
language applications on small devices, like mobile phones. The API is a subset of the
Java SE API, along with special class libraries useful for small device application
development. Java ME applications are often clients of Java EE platform services.
• JavaFX – it is a platform for creating rich internet applications using a lightweight user-
interface API. JavaFX applications use hardware-accelerated graphics and media engines
to take advantage of higher-performance clients and a modern look-and-feel as well as
high-level APIs for connecting to networked data sources. JavaFX applications may be
clients of Java EE platform services.
Features of Java
Programmers have accepted java very quickly because it provides everything that is needed in
a modern day language including the following features; Java is:
• Object Oriented – In Java, everything is an Object. Java can be easily extended since
it is based on the Object model.
o software-based
o hardware-based.
Java provides a software-based platform. The Java platform differs from most other
platforms in the sense that it is a software-based platform that runs on the top of other
hardware-based platforms.
2
It has two components:
a. Runtime Environment
b. API (Application Programming Interface)
• Simple – Java is designed to be easy to learn and understand, and its syntax is simple.
If you understand the basic concept of OOP Java, it would be easy to master. According
to Sun, Java language is a simple programming language because:
o Java syntax is based on C++.
o Java has removed many complicated and rarely-used features, for example,
explicit pointers, user-defined operator overloading (only + is allowed for
concatenation), etc.
o There is no need to remove unreferenced objects because there is an Automatic
Garbage Collection in Java.
• Class loader – it is part of the Java Runtime Environment (JRE) which is used to load
Java classes into the Java Virtual Machine dynamically. It adds security by separating
the package for the classes of the local file system from those that are imported from
network sources.
o Bytecode Verifier – it checks the code fragments for illegal code that can violate
access right to objects.
3
o Security Manager – it determines what resources a class can access such as
reading and writing to the local disk.
• Interpreted – Java byte code is translated on the fly to native machine instructions and
is not stored anywhere. The development process is more rapid and analytical since the
linking is an incremental and light-weight process.
4
• High Performance – With the use of Just-In-Time compilers (compiling bytecodes into
native machine code at run time), Java enables high performance. Java is faster than
other traditional interpreted programming languages because Java bytecode is “close”
to native code. It is still a little bit slower than a compiled language (e.g., C++). Java
is an interpreted language that is why it is slower than compiled languages, e.g., C,
C++, etc.
• Distributed – Java is designed for the distributed environment of the internet. Java is
distributed because it facilitates users to create distributed applications in Java. This
feature of Java makes us able to access files by calling the methods from any machine
on the internet.
5
Definition of Java Application, Java Applets
• Editor – You can use any text editor or IDE to create and edit a Java source-code file.
• Java Development Toolkit (JDK) – it consists of a set of separate programs, each
invoked from a command line, for developing and testing Java programs. Besides JDK,
you can use a Java development tool (e.g., NetBeans, Eclipse, and TextPad).
The Java Development Kit (JDK) is part of the Java SE Product, there are other parts
as well, but you can treat them as the same thing for development purposes.
It contains a private Java Virtual Machine (JVM) and a few other resources such as an
interpreter/loader (java), a compiler (javac), an archiver (jar), a documentation
generator (Javadoc), etc. to complete the development of a Java Application.
JDK Contains
▪ a private Java Virtual Machine (JVM)
▪ an interpreter/loader (java),
▪ a compiler (javac),
▪ an archiver (jar),
▪ a documentation generator (Javadoc),
▪ etc. to complete the development of a Java Application.
• Java Runtime Environment (JRE) – it is a set of software tools which are used for
developing Java applications. It is used to provide the runtime environment. It is the
implementation of JVM. It physically exists. It contains a set of libraries + other files that
JVM uses at runtime.
JVM, JRE, and JDK are platform dependent because the configuration of each OS is
different from each other. However, Java is platform independent.
7
Preparing Java Environment
A necessary step before ones can write computer programs to help solve some problems is to
prepare the required environment. Once a programmer decides that he or she will use a specific
programming language (or an application development framework) to create computer
programs, certain sets of software needs to be installed.
▪ a text editor, which lets programmers type in the instructions of the programs and save
into a text file,
▪ a software that can change that text file into a file filled with binary representations
that can be understood by the operating systems of the computer, upon which the
programs are aimed to be run.
For Java;
Since the platform-independent nature of Java relies on the fact that the Java Virtual Machine
(JVM) must be there to nullify the differences among different operating systems, there is
another piece of software that must be installed on the machine apart from the two already
mentioned.
▪ Any text editors in the market would work for writing Java programs.
▪ Apart from the text editor which ones can choose according to their preferences,
probably, the easiest way to obtain the rest of the required software is to download and
install the Java Development Kit (JDK) from the official Java website. Due to the
quickly changing nature of computer business, the website’s specific URL might be
changed over years. The trick in finding it is to simply perform a search for “JDK
download” on a search engine.
8
Click Oracle “Java Downloads”.
Go down to “Windows”.
9
Either use “.exe” or “MSI”. Download one of them and install.
The Java platform has many editions offered to be downloaded and installed such as Java SE,
Java Embedded, Java EE, Java ME, and etc. For general purpose Java programs, Java SE (Java
Platform, Standard Edition) would be the most suitable one. The JDK package contains many
things useful for developing a Java program as well as the Java Runtime Environment (JRE)
that is needed for running any Java programs developed by anyone. When JDK is installed on
a machine, it also installs JRE too. Note that for ordinary users that may wish to just run a Java
program, they only need to install JRE.
Starting Java
One way to compile the source code of a Java program and to run the compiled Java bytecode
on JVM is to execute certain programs from the command prompt of the computer’s operating
system.
▪ Java Compiler: The Java compiler is the program file with the name javac.exe,
o can be founded in a subdirectory called bin (short for binaries) of the folder that
JDK is installed,
▪ Java interpreter: is the program to be called when executing any compiled Java
bytecode, is the program file with the name java.exe.
o can be founded in the bin subdirectory of the folder that JRE is installed.
Command Prompt:
How to open the command prompt differs among different operating systems.
▪ In MS Windows, the command prompt can be found from the start menu,
▪ in MacOS as well as other Linux-based operating systems, the command prompt are
basically the Terminal program.
Project Folder
For the purpose of learning and practicing writing Java programs, we usually save our source
codes and run the corresponding programs in directories different from the ones that JDK and
JRE get installed. We generally want to call javac.exe and java.exe directly from the
directories that the source codes are saved, or in other words, the directories in which we are
currently working and avoid providing the full path to both javac.exe and java.exe each and
every time we need to compile and run Java programs.
10
Therefore, in order to do that, we need to let the operating system know where to look for
programs that are called from the command prompt and cannot be found in the current working
directory. Readers should consult manuals of their operating systems of how to set the paths
that they should look inside for unfound programs.
For MS Windows, these paths can be registered by setting the environment variable called
path to include the paths to the bin subdirectories of both the JDK and the JRE folders.
Example, if the path is currently set to ‘C: \WINDOWS\SYSTEM32’, then change your path to
read ‘C: \WINDOWS\SYSTEM32;c:\Program Files\java\jdk\bin’.
11
Java programs normally go through five phases:
Edit → Compile → Load → Verify → Execute
in the command window of your system (i.e., the Command Prompt in Windows). If the
program compiles, the compiler produces a .class file called Welcome.class that contains the
compiled version of the program.
The Java compiler translates Java source code into bytecodes. Bytecodes are executed by the
Java Virtual Machine (JVM) – a part of the JDK and the foundation of the Java platform. A VM
is a software application that simulates a computer but hides the underlying operating system
and hardware from the programs that interact with it. If the same VM is implemented on many
computer platforms, applications that it executes can be used on all those platforms. The JVM
is one of the most widely used virtual machines.
Unlike machine language, which is dependent on specific computer hardware, bytecodes are
platform independent. So, Java’s bytecodes are portable – without recompiling the source
12
code, the same bytecodes can execute on any platform. The JVM is invoked by the java
command. For example, to execute a Java application called Welcome, you’d type the command
13
Phase 5: Execution
In this phase, the JVM executes the program’s bytecodes, thus performing the actions specified
by the program. The JVM analyzes the bytecodes as they’re interpreted, searching for hot spots
– parts of the bytecodes that execute frequently. For these parts, a just-in-time (JIT) compiler
– known as the Java HotSpot compiler – translates the bytecodes into the underlying
computer’s machine language. When the JVM encounters these compiled parts again, the faster
machine-language code executes.
▪ Translation: Source code is translated into bytecodes (for portability across JVMs on
different computer platforms)
▪ Execution: During execution, the bytecodes are translated into machine language for the
actual computer on which the program executes.
Compiling Java source code does not result in a machine language program. Instead, when
Java source code is compiled, we get what is called Java bytecode. Java bytecode is a form
of machine language instructions. However, it is not primitive to the CPU. Java bytecode runs
on a program that mimics itself as a real machine. This program is called the Java Virtual
Machine (JVM) or JavaRun-time Environment (JRE). This architecture makes Java bytecode
runs on any machines that have JVM, independent of the OSs and CPUs. This means the effort
14
in writing java source code for a certain program is spent once and the target program can run
on any platforms. (E.g. Windows, MacOS, UNIX, etc.)
Java code can be run on multiple platforms. Example: Windows, Linux, Sun Solaris,
Mac/OS, etc. It is compiled by the compiler and converted into bytecode. This bytecode is a
platform-independent code because it can be run on multiple platforms, i.e., Write Once and
Run Anywhere (WORA).
Java is platform-independent at both the source and the binary level. At the source level, Java’s
primitive data types have consistent sizes across all development platforms. Java’s foundation
class libraries make it easy to write code that can be moved from platform to platform without
the need to rewrite it to work with that platform. Platform independence doesn’t stop at the
source level. Java binary files are also platform-independent and can run on multiple problems
without the need to recompile the source. How does this work? Java binary files are actually in
a form called bytecodes.
15
Traditional Compiled Programs
Java Programs
Bytecodes are a set of instructions that looks a lot like some machine codes, but that is not
specific to any one processor.
Normally, when you compile a program written in C or in most other languages, the compiler
translates your program into machine codes or processor instructions. Those instructions are
16
specific to the processor your computer is running—so, for example, if you compile your code
on a Pentium system, the resulting program will run only on other Pentium systems. If you
want to use the same program on another system, you have to go back to your original source,
get a compiler for that system, and recompile your code. Things are different when you write
code in Java. The Java development environment has two parts: a Java compiler and a Java
interpreter. The Java compiler takes your Java program and instead of generating machine
codes from your source files, it generates bytecodes.
A Java application is a computer program that executes when you use the java command to
launch the Java Virtual Machine (JVM).
Example:
Let us begin with a simple Java program that displays the message “Welcome to Java!” on
the console. Console refers to text entry and display device of a computer.
Output:
The line numbers are displayed for reference purposes but are not part of the program. So,
don’t type line numbers in your program.
• Line 1 defines a package. It is a way of organizing a program at one place.
• Line 2 defines a class. Every Java program must have at least one class. Each class has
a name. By convention, class names start with an uppercase letter. In this example,
the class name is Welcome.
• Line 3 defines the main method. In order to run a class, the class must contain a
method named main. The program is executed from the main method. A method is a
construct that contains statements. The main method in this program contains
the System.out.println statement. This statement prints a message “Welcome to
Java!” to the console (line 4). Every statement in Java ends with a semicolon (;),
known as the statement terminator.
• A pair of braces in a program forms a block that groups the program’s components. In
Java, each block begins with an opening brace ({) and ends with a closing brace (}).
Every class has a class block that groups the data and methods of the class. Every
17
method has a method block that groups the statements in the method. Blocks can be
nested, meaning that one block can be placed within another, as shown in the following
code.
Note:
Java source programs are case-sensitive. Example: main and Main are different.
You have to create your program and compile it before it can be executed. This process is
repetitive. If your program has compilation errors, you have to modify the program to fix them,
then recompile it. If your program has runtime errors or does not produce the correct result,
you have to modify the program, recompile it, and execute it again.
From the command window, you can use the NotePad to create the Java source code file, as
shown in Figure below.
18
You can create the Java source file using Windows NotePad.
File Name:
The source file must end with the extension .java and must have exactly the same name as
the public class name. For example, the file for the source code above should be
named Welcome.java, since the public class name is Welcome.
Compile:
A Java compiler translates a Java source file into a Java bytecode file. The following command
compiles Welcome.java:
Note:
You must first install and configure JDK before compiling and running programs. How to install
and use JDK has already been explained above.
19
Typical Programming Cycle
During the implementation of a program, programmers always run into a typical cycle.
It normally starts with the coding step, in which the source code is written in any text editors
or integrated programming environment. In Java, source code files are usually saved with .java
extension. Once the Java source code is saved, it is compiled using a java compiler, such as
javac.exe, to obtain the resulting Java bytecode, which is also called a Java class. The actual
Java class file is created with .class extension. Then, the program is executed by running the
command ‘java.exe’ on the class file. If the result appears as expected, the cycle terminates.
Otherwise, the source code has to be edited, then compiled and executed again. The process
of fixing the source code in order to obtain the right result is called ‘debugging’.
(a) Java source code is translated into bytecode. (b) Java bytecode can be executed on any
computer with a Java Virtual Machine.
20
Interpreting bytecode:
To execute a Java program is to run the program’s bytecode. You can execute the bytecode on
any platform with a JVM. Java bytecode is interpreted. Interpreting translates the individual
steps in the bytecode into the target machine-language code one at a time rather than
translating the whole program as a single unit. Each step is executed immediately after it is
translated.
Run:
The following command runs the bytecode:
The figure below shows the javac command for compiling Welcome.java. The compiler
generated the Welcome.class file. This file is executed using the java command.
21