1 1 Chapter 1 Introduction To Java Programming

Download as pdf or txt
Download as pdf or txt
You are on page 1of 21

CHAPTER 1

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

There are basically four editions of java.

• Java Standard Edition (SE) – it is used to develop client-side standalone applications


or applets. It defines everything from the basic types and objects of the Java
programming language to high-level classes that are used for networking, security,
database access, graphical user interface (GUI) development, and XML parsing. Consists
of a virtual machine, development tools, deployment technologies, and other class
libraries and toolkits commonly used in Java technology applications.

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.

• Platform Independent – Unlike many other programming languages including C and


C++, when Java is compiled, it is not compiled into platform specific machine, rather
into platform-independent byte code. This byte code;
o is distributed over the web
o interpreted by the Virtual Machine (JVM) on whichever platform it is being run on.

Platform-independence is a program’s capability of moving easily from one computer


system to another. A platform is the hardware or software environment in which a
program runs. There are two types of platforms:

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.

• Secure – With Java’s secure feature it enables to develop virus-free, tamper-free


systems (tamper means any interference to the system which causes damage or any
unauthorised access). Authentication techniques are based on public-key encryption.
Java is secured because:
o No explicit pointer
o Java Programs run inside a virtual machine sandbox

• 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.

• Architecture-neutral – Java compiler generates an architecture-neutral object file


format, which makes the compiled code executable on many processors, with the
presence of Java runtime system and the size of primitive types is fixed. In C
programming, int data type occupies 2 bytes of memory for 32-bit architecture and 4
bytes of memory for 64-bit architecture. However, it occupies 4 bytes of memory for
both 32 and 64-bit architectures in Java.

• Portable – Being architecture-neutral and having no implementation dependent aspects


of the specification makes Java portable. The compiler in Java is written in ANSI C with
a clean portability boundary, which is a POSIX (Portable Operating System Interface for
Unix) subset.

• Robust – Java makes an effort to eliminate error-prone situations by emphasizing


mainly on compile time error checking and runtime checking. Robust simply means
strong.
Java is robust because:

• It uses strong memory management (memory management is the process of


allocation and de-allocation of objects - Java does memory management
automatically).
• There is a lack of pointers that avoids security problems.
• There is automatic garbage collection in java which runs on the Java Virtual
Machine to get rid of objects which are not being used by a Java application
anymore.
• There are exception handling and the type checking mechanism in Java. All these
points make Java robust.

• Multithreaded – With Java’s multithreaded feature it is possible to write programs that


can perform many tasks simultaneously. This design feature allows the developers to
construct interactive applications that can run smoothly.

o A thread is like a separate program, executing concurrently. We can write Java


programs that deal with many tasks at once by defining multiple threads. It shares
a common memory area.

• 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.

Distributed applications are programs running on different machines connected


together over a network. Using distributed applications, different or same functions of a
single application can be performed at different locations. Distributed applications work
on the principles of Distributed Systems. Here is an illustration to understand the working
of distributed applications.

• Dynamic – Java is considered to be more dynamic than C or C++ since it is designed


to adapt to an evolving environment. Java programs can carry an extensive amount of
run-time information that can be used to verify and resolve accesses to objects at run-
time. It supports dynamic loading of classes. It means classes are loaded on demand. It
also supports functions from its native languages, i.e., C and C++.

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.

• Integrated Development Environment (IDE) – it provides tools that support the


software development process, including editors for writing and editing programs and
debuggers for locating logic errors (errors that cause programs to execute incorrectly).
Popular IDEs include Eclipse (www.eclipse.org) and NetBeans (www.netbeans.org).
6
• Application Programming Interface (API) – contains predefined classes and
interfaces for developing Java programs.

• 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.

• Java Virtual Machine (JVM) – is an abstract machine. It is called a virtual machine


because it doesn’t physically exist. It is a specification that provides a runtime
environment in which Java bytecode can be executed. It can also run those programs
which are written in other languages and compiled to Java bytecode. JVMs are available
for many hardware and software platforms.

JVM, JRE, and JDK are platform dependent because the configuration of each OS is
different from each other. However, Java is platform independent.

The JVM performs the following main tasks:


▪ Loads code
▪ Verifies code
▪ Executes code
▪ Provides runtime environment

Key Points in java


Development Environment
The place where software is being developed. Example: Software Company. The required tools
to develop a software are
▪ Compiler (javac), debugger (jdb), Java Virtual Machine or Interpreter (java), packaging
tool (.jar), running Applet (appletviewer), etc.
• JDK
o It contains the software development tools listed above.
o JDK = JRE + Development tools
▪ IDE
• It is all the JDK tool integrated and accessible from a single window.
• Example: NetBeans, Eclipse, etc.
Production Environment:
▪ It is a place where a software is being used at real-environment (client environment).
• JRE = JVM + Java libraries

7
Preparing Java Environment

Getting the required software

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.

For a high-level programming language, these usually include;

▪ 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

Letting Your OS Know Where to Find 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.

Assuming you have installed Java in c:\Program Files\java\jdk directory:


• Right-click on ‘My Computer’ and select ‘Properties’.
• Click the ‘Environment variables’ button under the ‘Advanced’ tab
• Now, alter the ‘Path’ variable so that it also contains the path to the Java executable.

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’.

Setting Java in MS Windows OS

11
Java programs normally go through five phases:
Edit → Compile → Load → Verify → Execute

Phase 1: Creating a Program


It consists of editing a file with an editor program, normally known simply as an editor
(Notepad, EditPlus (www.editplus.com), TextPad (www.textpad.com) and jEdit
(www.jedit.org). You type a Java program (source code) using the editor, make any necessary
corrections and save the program on a secondary storage device, such as your hard drive. A
file name ending with the .java extension indicates that the file contains Java source code.

Phase 2: Compiling a Java Program into Bytecodes


In this phase, you use the command javac (the Java compiler) to compile a program. For
example, to compile a program called Welcome.java, you’d type

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

Phase 3: Loading a Program into Memory


In this phase, the JVM places the program in memory to execute it – this is known as loading.
The JVM’s class loader takes the .class files containing the program’s bytecodes and transfers
them to primary memory. The class loader also loads any of the .class files provided by Java
that your program uses. The .class files can be loaded from a disk on your system or over a
network (e.g., your local university or company network, or the Internet).

Phase 4: Bytecode Verification


In this, as the classes are loaded, the bytecode verifier examines their bytecodes to ensure
that they’re valid and do not violate Java’s security restrictions. Java enforces strong security
to make sure that Java programs arriving over the network do not damage your files or your
system (as computer viruses and worms might).

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.

Thus, Java programs actually go through two compilation phases:

▪ 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.

Problems That May Occur at Execution Time

Java virtual machine (JVM)

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.)

Platform Independent Architecute of Java Language

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.

Starting Java Application

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.

Summary of a Java Program with its Phases

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.

The Java program-development process consists of repeatedly creating/modifying source code,


compiling, and executing programs.

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.

.class bytecode file:


If there are no syntax errors, the compiler generates a bytecode file with a .class extension.
So, the preceding command generates a file named Welcome.class, see figure (a) below. The
Java language is a high-level language while Java bytecode is a low-level language. The
bytecode is similar to machine instructions but is architecture neutral and can run on any
platform that has a Java Virtual Machine (JVM), see figure (b) below. Rather than a physical
machine, the virtual machine is a program that interprets Java bytecode. This is one of Java’s
primary advantages: Java bytecode can run on a variety of hardware platforms and operating
systems.

19
Typical Programming Cycle
During the implementation of a program, programmers always run into a typical cycle.

Typical Cyle in Java Programming

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

You might also like