15

Object-Oriented Programming with Java

LEARNING OBJECTIVES

At the end of the chapter, you should be able to understand

  • Downloading and installing JDK required to run your programs.

  • Setting environment variables.

  • Understanding what processes are involved in running a Java program.

  • Running a Java stand-alone program.

  • Running a Java applet with Java swing components.

  • Using Industry standard Eclipse Development Tool.

15.1 Introduction

Java has been specially designed for the Internet. There are many features of Java that are ideally suited for calling it as language for the network. C and C++ are proven structured and objective-oriented languages but they are not built for network and the Internet. Java is a pure objective-oriented language and we can program in Java without using objects.

In this chapter, we will introduce you to the World Wide Web and discuss aspects of Java that make the language best suited language for networking applications. The objective-oriented features of Java are discussed in brief and portability and platform-independent features are discussed in detail. Care has also been taken to provide examples of methods and programs to make you comfortable with the programming environment of Java.

15.2 Internet and the World Wide Web

Java has been specially created as a network language. There are two terms closely connected with Java programming. They are Internet and the World Wide Web (www). They are NOT synonymous and are NOT the same.

Firstly, network is a collection of computers either homogenous or heterogeneous.

Internet is a collection or grouping together of networks. We can say that the Internet is a network of networks, comprising of millions of computers. These computers communicate with each other using Internet protocols.

Protocol is set of rules for communicating computers. One such popular protocol is HTTP (Hyper Text Transfer Protocol) which is widely used. FTP (File Transfer Protocol) is also another widely used protocol.

World Wide Web (WWW) is a way of accessing information on the Internet. It uses HTTP to exchange data amongst communicating computers. The services provided by www uses Internet browsers such as Internet Explorer (IE), FireFox, and Google Chrome, etc. The information is exchanged using HTTP and web pages. Web page is a place where required information is stored. Web pages are linked through hyperlinks.

Who is the boss – Internet or www? It is Internet who is the boss. www is a method of Internet to exchange data over the Internet. Can you guess other ways to exchange data on the Internet. Yes, email is another popular method. It uses SMTP (Simple Mail Transfer Protocol).

15.3 C and C++ are Around – Then Why Java?

C is a structured and procedure-oriented and powerful language designed for systems programming such as operating systems, compilers, data base programs, etc. C was originally designed as a language for UNIX operating system. C++ was developed as an object-oriented programming language with very well-developed reusability features such as inheritance, etc. However, both these languages are NOT designed to work with the Internet. Both C and C++ are machine dependent. This means that programs will work only on computers that have the same hardware and OS as that on which programs have been originally written. In other words, C and C++ programs lack wider portability.

On the other hand, Java has been specially designed to work with the Internet. The Internet has heterogeneous computers interconnected through www. Hence, Java is designed to be platform independent. This means that it is hardware and OS independent. There is a popular saying about Java language: Write here and execute it anywhere! Sun Micro Systems indeed used “Write Once, Run Anywhere (WORA)” as its catchword.

15.4 Java Story

James Gosling and Patric Naughton, inventors of Java language, were originally looking for designing a universal remote that would work with any set top box. They wanted it to be a “virtual machine” that would truly be machine (set top box) independent. Later, they added advanced features and called it as “oak”. It was also known for some time as “Green” and ultimately settled as “Java”. The idea by Gosling was to build a virtual machine and a language that would work truly as a machine-independent language with features of already popular C++ language notation. The design goals envisaged by inventors of Java are:

  • It should be simple, object oriented, and familiar.
  • It should be robust and secure.
  • It should be architecture neutral and portable.
  • It should execute with high performance.
  • It should be interpreted, threaded, and dynamic.

Sun Micro first released Java 1.0 in 1995. All major web browsers incorporated and supported Java 1.0. With rich platform-independent and easy to program features, Java soon became very popular. J2SE 1.2 was released in 1998–1999 to cater to different platforms. J2EE catered to Enterprise Edition and J2ME catered to mobile computing requirements. Since 2006, Java is known by three names based on the segments they provide service, namely Java SE (Standard Edition), JavaEE, and JavaME.

15.5 Java Features

15.5.1 Portability or Platform Independent

Machine-dependent languages, such as C and C++, use compilers that produce object codes that are highly machine/hardware and OS dependent, whereas programs written in Java run without any modifications on any other hardware or operating system. To achieve this feature, Java uses “byte code” and a virtual machine.

Byte code is interpreted by virtual machine (VM) for the host hardware. Users need to install JRE (Java Run-Time Environment) along with JDK for running Java applications. JRE is also available in web browsers for executing Java applets. What is the cost involved in getting all important machine independence and portability? It is speed. Interpretation is slow compared to the compilation process. To increase the speed, Just in time Compilers (JIT compilers) were introduced that convert byte code into machine code. JDK shipped by Sun Micro Systems is a superset of Java compiler, Javadoc, and a debugger.

15.5.2 Automatic Garbage Collection

Unlike C++ where in program had to keep track of dispersal of objects after use, Java resorts to automatic memory release for objects no more needed. Java uses automatic garbage collector to manage memory. So what is automatic garbage collector? Garbage collector is a software program that runs in the background and picks up and clears memory space occupied by the dead objects. It follows a predetermined algorithm to decide which objects have no remaining reference, i.e. they are no longer referred and frees the memory automatically. This process will happen when the program is idle or when there is insufficient free memory on the heap to be freed.

15.5.3 Object-oriented Features

For detailed treatment on objective-oriented features, we would strongly advise the reader to visit Chapters 1, 2, and 3. The succeeding sections give a brief overview of the concepts involved.

15.5.3.1 Classes and Objects

Object-oriented programming is a methodology in which we create cooperating objects that communicate with each other and accomplish the desired task. Java is a pure object-oriented language. You cannot write a Java program without a class. In fact program resides in a class. Java program uses objects and classes. So when we refer to object called Student we refer to both attributes(state) and behaviour. Attributes are also called state of an object.

Class: A collection of objects. We can also define as an array of instances objects. But class can have member functions and member data. Here unlike array, a class can have different data types as its elements. Class defines abstract, i.e. hidden characteristics of an object including attributes and behaviour. A class called Student can be viewed as a factory producing instances of Object Student that have different attributes (i.e. individual data) and a common functionality (i.e. common functions) Attributes and functions provided by the class are called member data and member functions. In Java, member functions are called methods. A class allows us to encapsulate member functions and member data into a single entity called object. Figure 15.1 shows objects of students class.

 

Student objects

 

Figure 15.1 | Student objects

Objects – Encapsulation: In object-oriented programming like Java is a data primacy language, i.e. data is important and functions are not important. As per memory mapping, data is stored in data areas such as stack, free space, functions are stored in code area and there is a need to maintain strict control over the accessing of data by functions. Java achieves this control by using encapsulation feature. Encapsulation is binding member data and calling function together with security classification, so that no unauthorized access to data takes place. Java depends heavily on access specifiers to maintain data integrity. The security access specifiers are public, private, protected, and default specifier package.

Public: Member functions and data if any declared as public can be accessed outside the class member functions.

Private: Member data declared as private can only be accessed within the class member functions and data is hidden from outside.

Protected: Member data and member functions declared as protected are private to outsiders and public to descendants of the class in inheritance relationship. You will learn more about this in the chapter on Inheritance under C++ and the Java chapter that follows.

Package (default): You can access it from any other class in the same directory. Encapsulation can now be defined as “Binding together the member functions and member data with access specifiers like private, public, and protected, package, etc. into object by the class.”

15.5.3.2 Method

In Java, class member functions are called Methods. A method is nothing but a code written to achieve a result. The syntax is:

 

image

 

Arguments: Number and type of parameters are called arguments. Parameters are also called formal parameters.

Signature: Name and arguments together are called the signature of the method. A method will have a return type which is outside the signature. The variables declared inside a method are called local variables and are never available anywhere outside the method. A method can be executed by sending a message to the object. Message comprises: a reference to the object, a dot (.), method name, and actual parameters (arguments). Values of actual parameters are copied to formal parameters, a method gets executed and return value replaces the message. The local values are all lost.

15.5.3.3 Polymorphism

Polymorphism means one method performing many different tasks depending on the users’ requirements. This is one of the most powerful features of object orientation. There are two kinds of polymorphisms. Overloading and Overriding. Overloading means the same name but different signatures (number and type of parameters). When a message is sent, signatures are compared and best fit methods get loaded. This happens at run-time.

Overriding is a phenomenon which take place in inheritance. Overriding is commonly used to make methods more specific. Suppose both base class and class derived from base class have declared the same method with common signatures; then when a message is sent to an object, the method of derived class is loaded.

15.5.3.4 Extending/Deriving New Classes

We can derive a new class based on the existing class. This is possible through the inheritance and containment property afforded by Java. Inheritance provides access to member data and member functions declared as protected to the descendant class.

15.5.3.5 Inner Class

Class within a Class – Inner Class. Inner class is one of the techniques provided by Java to achieve reusability of the code. Inner class means a class containing another class or more than one class. Inner classes cannot be declared as static.

15.5.3.6 Inheritance and Class Hierarchy

Reusability of code is one of the strong promises that are made by designers of Java and inheritance is the tool selected by Java to fulfill the promise of reusability. The concept of inheritance is not new to us. We inherit property, goodwill and name from our parents. Similarly, our descendants will derive these qualities from us. Study the inheritance class hierarchy shown in Figure 15.2. Human and Animal derive qualities from living beings. Professionals, students and Athletes are derived from Human. We say these three categories have inherited from Human. Class Human is called base class and Student and Athlete are called derived class. What can be inherited? Both member functions and member data can be inherited.

 

Inheritance hierarchy

 

Figure 15.2 Inheritance hierarchy

 

Have you noticed the direction of the arrow to indicate the inheritance relation? It is pointed upwards as per modelling language specifications.

Inheritance specifies is type of relation. Observe that a Student is a Human. Similarly Mammal is Animal. Human is a superclass and Student is a derived class. Derivation from base class is the technique to implement is type of relation. A superclass can have more than one derived class.

When do we use Inheritance? You inherit so that you can derive all the functionality and member data from base class and derived class can add its own specialized or individualistic functionality. For example, Athlete derives all functionality and attributes of Human and in addition adds sports and Athletic functionality and attributes on its own.

Inheritance is a powerful tool in the hand of a programmer to define a new class from existing classes.

15.5.3.7 Class as Abstract Data Type (ADT)

A class can also be called Abstract Data Type (ADT). Refer to Figure 15.3.

 

Hierarchical inheritance

 

Figure 15.3 Hierarchical inheritance

 

We will declare a base class (ADT) called Shape. You will appreciate Shape has no definite shape, no definite area or perimeter or specific draw routine. Shape will hence declare methods with only names and no implementation details. In Java, these types of classes are called interfaces and methods are called abstract method. An abstract method is a method that is declared but not defined. It is declared with the keyword abstract, and has a header like any other method, but ends with a semicolon instead of a method body.

An abstract class is one that contains one or more abstract methods; it must itself be declared with the abstract keyword. A class may be declared abstract even if it does not contain any abstract methods. A non-abstract class is sometimes called a concrete class. An abstract class cannot be instantiated because it has no solid methods. We will derive classes like Circle and Square and provide the solid implementation of the methods declared in the interface. Solid means that all methods will be implemented in each of the derived classes.

Interface is declared with the keyword interface instead of the usual keyword class. Interface can only contain abstract methods. However, using the keyword abstract for these methods is optional. A class can extend to only one class but can implement several interfaces.

15.5.3.8 Generic Programming in Java

Generic programming is a facility provided by Java to achieve reusability of code. Generics can be applied to classes and methods. Class templates are very useful in achieving the reusability of code for different data types. No wonder then that Java relies heavily on Generic programming. Generic programming is very useful to abstract over types. For example, Java's Container types present Java's Collection hierarchy, are very useful in implementing data structures often used in programming, such as Linked List, Queue, Stack, Searching and Sorting, etc. In a nutshell, Generic Programming improves productivity of the programmer.

15.5.4 Easy to Learn and Excellent Documentation

Since Java has done away with pointers, operator overloading, multiple inheritances etc., it is relatively easy to learn for a programmer. It follows C & C++ syntax which are already popular with programmers and widely used in the Industry. In addition, Java provides excellent inline documentation called APIs in .html format for providing instant help to the programmer. For this, Java provides three types of comment statements. Comments are included to enhance the readability of the program. Java allows both single-line comment statements and also multiline comment statements like C & C++

  • Single line comment. These comment lines start with double slash : //

    Ex :// HelloWorld.java , a Java program to print a line of text

  • Multi Line Comment: These comment lines are used when comments extend beyond a single line. They start with /* and end with */

    Ex: /* Inheritance.java :The program introduces concepts of Inheritance and other related reusability features of Java */

  • Java API Documentation Comments: These comments are used to describe features of Java program. Java documentation feature depends on .html file format and produce .html file we need to use these documentation comments. They start with /** and end with */.

    Ex: /** Class definition to show extend feature*//** Method to compute student grades */

These .html files are called APIs (Application Program Interfaces). To produce these APIs we need to use Javadoc compiler. In Section 15.5.4, Example 15.1, we have shown the procedure for producing API document for a Java source program.

15.5.5 Byte Code

Byte code is an instruction set of one byte (8 bits). Byte code may often be either directly executed on a virtual machine (i.e. interpreter), or it may be further compiled into machine code for better performance. These are employed because they reduce the dependence on hardware and operating systems. Byte codes are compact numeric codes and references (normally numeric addresses) which encode the result of parsing and semantic analysis and hence offer much better performance than by direct reading of source code. A byte code program can be parsed directly executing instructions one at a time by byte code Interpreter. These are portable codes. After parsing and semantic analysis, part code that requires repeated execution, etc., are handed over to Just in time compiler (JIT Compiler) to translate byte code into machine code at run-time. Thus, JVM is not portable but byte code is fully portable. Because of its performance advantage, Java language implementations execute a program in two phases, first compiling the source code into byte codes, and then passing the byte codes to the virtual machine. Therefore, there are virtual machines for Java.

15.5.6 Java Virtual Machine (JVM)

JVM is specific to hardware and Operating System. Each JVM will have the following components:

  • Class Loader Mechanism for loading class files and interfaces.
  • Execution Engine to execute instructions contained in class files.
  • Run-time data areas to store class files, formal and actual parameters, return values, etc.
  • Each instance of the Java virtual machine has one method area and one heap. These run-time data areas are shared by all threads running inside the virtual machine. All objects instantiated are stored on heap area.
  • Java Stack comprises several stack frames. Java allocates separate stack frames to each of the Java threads (for now its just a new task).
  • When a new thread comes into effect, it is allotted a Program Counter (PC) and its own Java Stack area. PC stores the address of the next instruction and Java Stack stores the state of Java Methods invoked. The state of a Java method invocation includes its local variables, the parameters with which it was invoked, its return value, and intermediate calculations. When a thread invokes a method, the Java virtual machine pushes a new frame onto that thread's Java stack. When the method completes, the virtual machine pops and discards the frame for that method.
  • Native Stack area is machine dependent and keeps track of native method invocation.
  • These areas are private to the owning thread. No thread can access the pc register or Java stack of another thread.

Figure 15.4 provides details of Java Development Environment. Figure 15.5 depicts the architecture explained above. Figure 15.6 gives details of run-time shared data areas.

 

A Java Development Environment

 

Figure 15.4 A Java Development Environment

 

Architecture of JVM

 

Figure 15.5 Architecture of JVM

 

Shared and exclusive data areas. MethodArea and heap are shared by all Threads. Java Stack, PC are individual to each thread, which are shown in the shaded box

 

Figure 15.6 Shared and exclusive data areas. MethodArea and heap are shared by all Threads. Java Stack, PC are individual to each thread, which are shown in the shaded box

15.5.7 Comparison with C++

The main differences between C++ and Java are summarized in Table 15.1.

 

Table 15.1 Differences between C++ and Java

C++ Java
C++ is not pure objective-oriented language. It is possible to write C++ programs without using classes Java is pure object-oriented programming language. Java program is a collection of classes
C++ supports pointers Java does not support C/C++ style pointers
C++ primitive data types are objects Primitive data types are not objects
In C++, the programmer has to free the heap memory occupied by the object when it is no longer required. Freeing of heap memory of objects no longer referred is automatically carried out by Java's garbage collector
C++ supports operator overloading Java does not support operator overloading
C++ supports multiple inheritance Java does not support multiple inheritance
There are constructors and destructors Java supports only constructor. Garbage collector does the job of freeing of objects no longer required
C++ supports two kinds of comments: a single line style marked with two slashes (//), a multiple line style opened with a slash asterisk (/*) and closed with an asterisk slash (*/) There are three different styles of comment: a single line style marked with two slashes (//), a multiple line style opened with a slash asterisk (/*) and closed with an asterisk slash (*/) and the Javadoc commenting style opened with a slash and two asterisks (/**) and closed with an asterisk slash (*/)
Write once compile anywhere (WOCA) Write once run anywhere / everywhere (WORA / WORE)
Allows direct calls to native system libraries Call through the Java Native Interface and recently Java Native Access
Exposes low-level system facilities Runs in a protected virtual machine environment
C++ supports native unsigned arithmetic Java does not support native unsigned arithmetic
Pointers, References, and pass-by value are supported Primitive data types always passed by value. Objects are passed by nullable reference
Supports class, struct, and union and can allocate them on heap or stack Java supports only classes and allocates them to heap memory
No inline documentation is supported by C++ Javadoc is documentation supported by Java
C++ supports function pointers and function objects No function pointers. Java uses interfaces and listeners to achieve the same purpose
C++ supports const keyword Java supports final, a limited version for primitive data type

15.6 Developing First Java Application

15.6.1 Installing and Using Java Development Kit

We will be using JDK1.6.0_20 of Sun Micro Systems for developing and executing our programs. You can freely download the Java Development Kit(JDK1.6.0_20) from java.sun.com/javase/6/download.jsp. Normally when you download JDK from Sun Micros web site, it gets downloaded to C:Program Filesjava unless otherwise chosen by you. After downloading, the JDK directory will look as shown in Figure 15.7. The bin directory contains both the compiler and the launcher. We will be demonstrating all our programs with JDK1.6.0 environment.

 

Directory Structure after installing JDK 15.0_20

 

Figure 15.7 Directory Structure after installing JDK 15.0_20

15.6.2 Setting Path and Classpath

It is very important to set environment for JDK 1.6.0_20 so that compilation and execution take place very smoothly. There are two environment variables to be set. Of course, your programs will run without setting up these variables but every time we have to specify path and classpath which can be very tiring and cumbersome. Hence we recommend setting up these variables on a permanent basis, so that they are available at the time of booting the system.

Let us say that we want to use a folder called “Oopsjava” in C directory and within the folder we have created a separate folder called “examples”. In side folder “examples”, two subfolders, namely bin and src, are created. “bin” folder will house all our compiled code. In Java environment, file holding compiled code is called class file and will have .class as extension. Class file holds “byte code”. “src” folder on the other hand will hold all our source programs. In addition, we would create a separate folder called “TestDriver” to hold all our test programs for class files we have written. These programs are also called driver programs or interfaces. Therefore, the path for storing all class files and source programs developed by us would be

    C:Oopsjavaexamplesin
    C:Oopsjavaexamplessrc
    C:OopsjavaexamplesTestDriver

Eclipse is an Industry popular IDE and can be used for developing Java applications. You can download from www.eclipse.org/downloads/. Usage of Eclipse is optional for you. Eclipse can be loaded into our folder “Oopsjava”.

We also need to link up bin and lib directories of JDK1.6.0-20. Their paths would be

    C:Program FilesJavajdk1.6.0_20in // contains all company supplied programs
    C:Program FilesJavajdk1.6.0_20include; // win32 & header files
    C:Program FilesJavajdk1.6.0_20lib // libraries

We can depict our directory structure pictorially as shown in Figure 15.8. The upper part of the figure depicts the folders you have to create using the Operating system or created automatically when you use an IDE like eclipse. The lower part of the folders is automatically created by Java package statement. We will explain about Java package when we handle our first Java program.

 

Organization structure

 

Figure 15.8 Organization structure

 

We need to set the path variable if we want to run Java executables such as javac.exe, java.exe, javadoc.exe, etc. from any directory without having to type the full path or classpath of the command. If you do not set these variables, you need to specify the full path to the executable every time you run it. By setting path variable, we will have freedom to operate from any directory and calling any module or program without explicitly mentioning the path name.

Variable classpath, on the other hand, is a message from you to the Java environment, where to search for your class files. Remember you have to set classpath only for the class file you have created. You need not bother about class files supplied by Java. While setting these variables, note that dot “ . ” indicates current working directory.

 

Example 15.1:   How to Set Path and Classpath for Windows Platforms

Setting Environment Variables on Windows Platforms “
Path:
C:Javajdk1.6.0_20in;C:Javajdk1.6.0_20lib;c:javajdk1.6.0_220include;c:Oopsjavaexamples;c:Oopsjavaexamplessrc;c:Oopsjavaexamplesin;
c: OopsjavaexamplesTestDriver
Classpath : .;c:OopsJavaexamplesin;c:OopsJavaexamplesTestDriver
Permanent Setting of variable:
   • Go to settings->control panel->system -> advanced-> set environment variable.
   • Select path->edit : copy & paste path -> ok
   • Select classpath ->edit : copy & paste ->ok
   • Reboot the system
Alternately, you can set path and classpath each time you give the command
Path:
   • C:Program FilesJavajdk1.6.0in > javac HelloWorld.java
Classpath:
   • C:OopsJavaexamples>java -classpath c:OopsJava.examplesin> HelloWorl
   To check whether CLASSPATH is set on Microsoft Windows XP, enter & execute
   C:> echo CLASSPATH
   • If CLASSPATH is not set you will get a %CLASSPATH% (MicrosoftXP).

 

Example 15.2:   How to Set Path and Classpath for Linux Platforms

Let us suppose that jdk15.0_20 has been installed in directory /usr/local/
Linux:

      For C shell (csh), edit the startup file (~/.cshrc):
      set path=(/usr/local/jdk1.6.0/bin )
      For bash, edit the startup file (~/.bashrc):
      PATH=/usr/local/jdk1.6.0/bin:
      export PATH
      For ksh, the startup file is named by the environment variable, ENV.
      To set the path:
      PATH=/usr/local/jdk1.6.0/bin:
      export PATH
      For sh, edit the profile file (~/.profile):
      PATH=/usr/local/jdk1.6.0/bin:
      export PATH

Then load the startup file and verify that the path is set by repeating the Java command shown below:

    For C shell (csh):
    % source ~/.cshrc
    % java -version
    For ksh, bash, or sh:
    % . /.profile
    % java -version

Alternately, you can set path each time you give the commands

Path:

    % /usr/local/jdk1.6.0/bin/>javac HelloWorld.java
    To find out if the path is properly set, execute:
    % java -version

This will print the version of the Java tool, if it can find it. If the version is old or you get the error java: Command not found, then the path is not properly set.

Classpath in Linux:

We need to set our classpath to include three directories: current working directory denoted by a dot (.), bin directory and TestDriver.

The class path is the path that the Java run-time environment searches for classes. The class path can be set using either the -classpath option when calling Java tool such as Javac or Javadoc or Java, etc. by setting the CLASSPATH environment variable. The -classpath option is preferred because you can set it individually for each application without affecting other applications and without other applications modifying its value.

    %javac –classpath classpath1:classpath2:classpath
    %javac –classpath .:/usr/local/Oopsjava/examples/bin:
    /usr/local/Oopsjava/examples/TestDriver:

Current working directory by default classpath search directory. Setting the CLASSPATH variable or using the -classpath command-line option overrides that default, hence we have included the current directory “.” in the search path.

    You can also get the same result by executing the following command:
          In csh % setenv CLASSPATH classpath1:classpath2…
          In sh enter; CLASSPATH = path1:path2:… export CLASSPATH
    To clear classpath already set from the previous commands
          In csh: unsetenv CLASSPATH
          In sh : unset CLASSPATH
    To check if classpath is set correctly on Linux, execute the following:
    % echo $CLASSPATH
    If CLASSPATH is not set you will get a
        CLASSPATH: Undefined variable error
Changing Startup Settings:
    If the class path is set at system startup then we should:
    For shells csh , tcsh look for setenv command in .cshrc file
    (~/.cshrc): and enter
    % setenv CLASSPATH classpath1:classpath2…
    For shells sh , ksh look into .profile export command(~/.
    profile):
       CLASSPATH= classpath1:classpath2:
       export classpath

One final word about setting classpath. For .class files in an unnamed package, the class path ends with the directory that contains the .class files. For .class files in a named package, the class path ends with the directory that contains the “root” package (the first package in the full package name). Multiple path entries are separated by colons. We have explained package concept in Section 15.5.5.

So much for environment variables? Yes, understanding the environment variables setting is very important if you do not want to waste weeks in getting your advanced programs compiled and run correctly.

15.6.3 Java Program Structure

Java is a pure object-oriented language. Remember that we cannot write anything outside the class. OOP is a creation of objects and achieves the desired result through communication and interaction amongst them. The sections in a Java program are shown in Figure 15.9.

 

Program Structure

 

Figure 15.9 Program Structure

 

Therefore, all class files which are required are kept in a package. With a statement

     package com.oops.chap1;

Refer to Figure 15.8. Setting classpath will take the control to c:Oopsjavaexmplesin. Our package statement will create the directories comoopschap1.

Next important section is you need to import all the packages either supplied by Java or written and stored by you through the package statement explained above.

Finally, the structure will have a collection of classes. If you are engaged in writing a standalone application, then there will be class with void main () statement. There can be more than one class. A Java program can also be an Applet-based program in which case the class will not have void main() but will have init() function.

15.6.4 Java Documentation Comments

The syntax is: javadoc packagename. Look at the organization chart in Figure 15.8. Our packages are kept in src with package com.oops.chap1. javadoc compiler and its usage in producing API documents are explained in Example 15.3.

 

Example 15.3:   How to Produce Java API Documents with Javadoc Compiler

We want to produce API documents to our package com.oops/chap1. These are situated in our src directory( refer to Figure 15.8). Go to src directory and type

         C:OopsJavaexamplessrc>javadoc com.oops.chap1
Loading source files for package com.oops.chap1…
Constructing Javadoc information…
Standard Doclet version 1.6.0_20
Building tree for all the packages and classes…
Generating com/oops/chap1/ClassX.html… Generating com/oops/chap1/ClassY.html…
Generating com/oops/chap1/HaiWorld.html… Generating com/oops/chap1/HelloWorld.html…
Generating com/oops/chap1/VrHello.html.. Generating com/oops/chap1/VrHelloIndia.html…
Generating com/oops/chap1/package-frame.html..
Generating com/oops/chap1/package-tree.html…
Generating com/oops/chap1/package-summary.html…
Generating constant-values.html… Generating serialized-form.html…
Building index for all the packages and classes… Generating overview-tree.html…
Generating index-all.html… Generating deprecated-list.html…
Building index for all classes… Generating allclasses-frame.html…
Generating allclasses-noframe.html.. Generating index.html…
Generating help-doc.html.. Generating stylesheet.css…
All the above documents with extension .html are produced by Java-doc compiler and stored at C:oopsjavaexamplessrc>.Go ahead and get acquainted with Javadoc API. As a professional programmer you need to know the organization and method of presentation of Java documentation.

15.6.5 Java Development Environment

Before we execute our program there is a need to understand the Java development environment (refer to Figure 15.4).

Step 1: Edit: Edit the source program using any of the editors notepads. For example, our program will have a main class “HelloWorld”. Hence our Java program should also be named HelloWorld.java. Remember that we want to use package com.oops.chap1 as explained in Figure 15.8. Hence move to directory C:Oopsjavaexamplessrccomoopschap1 and create the required source file.

 

cd C:Oopsjavaexamplessrccomoopschap1> edit HelloWorld.java

Step 2: Compile: We need to store all our compiled code in C:Oopsjavaexamplesincomoopschap1. Therefore from the directory C:Oopsjavaexamplessrccomoopschap1. Compile the source file and redirect the class file into C:Oopsjavaexamplesincomoopschap1. For redirecting you have to use –d option and provide the complete path to bin directory as shown below:

 

C:OopsJavaexamplessrccomoopschap1>javac -d

c:Oopsjavaexamplesin HelloWorld.java

Compiler creates byte codes and stores then in a file with name HelloWorld.class at c:Oopsjavaexamplesincomoopschap1.

Step 3: Loader: Class Loader ;Loads the byte codes (Class file) into primary memory

Step 4: Byte code Verifier: It checks if the byte codes are all ok and do not override Java's security restrictions.

Step 5: JVM: (Java Virtual Machine) calls interpreter and Just in time (JIT) compiler and converts the byte codes into object codes that local machines understand. JVM is a combination of interpreter and compiler. JVM as it interprets looks for “hotspots”, i.e. parts of the program that are repeated, for example, a loop executing several times. In such cases, the JIT compiler converts them into machine code and for others, interpreter of JVM simply interprets the byte code.

15.6.6 Our First Java Application

As our first Java application, we want to simply display a message: “HelloWorld, Welcome to Object-oriented Programming in Java”.

 

Example 15.4:   HelloWorld.java: Our First Java Application

  1. // A program HelloWorld.java to print a line
  2. package com.oops.chap1;
  3. public class HelloWorld
  4. {
  5. public static void main(String[] args)
  6. {
  7. System.out.println(“Welcome to Object Oriented Programming in Java “);
  8. }
  9. }

Welcome to Object-oriented Programming in C++ and Java

Line No. 2: package: As a developer, you would like to keep all your work together, so that you can reuse them in future if needed. We would like to keep all our work as a “package”. Suppose you are working in a company called “oops.com”, then it is customary to create package as “com.oops”. Now we are writing programs for Chapter 1. Hence we will name our package as “com.oops.chap1”. More details about package later in Chapter 19 (refer to Figure 15.8). Path variable will link up to c:Oopajavaexamplesrc. It is your package statement which will link to com.oops.chap1.
Line No 3:

Source file must be named after the public classes they contain. Hence we have named our Java source program as HelloWorld.java. The source file can contain only one public class and several non-public classes.

Keyword public means that methods inside a public class can be called outside the class hierarchy. The hierarchy of the class is the name of the directory in which .java file resides.

Keyword static means that the class can be invoked directly without using an instance of the class to invoke the method “main”. This facility is required because normally you can invoke a method only through an instance of the object of the class. If we can invoke method main without instance of object, we can instantiate objects inside main() and achieve the desired result. Static just does this job. Note that main() is not a keyword of Java. Just that main() is called by Java to launch the program and pass control.

Void means that the main method does not return any value. Note also that void is a data type.

String args: The main method accepts an array of Strings objects of variable length as arguments normally through command line. Number of arguments, String objects, is specified by args.

Line No. 7: System class has defined a public static called out, which is an instance of PrintStream class and provides several methods for printing out data to Standard.out, such as println(), etc. The string “Welcome to Object-oriented Programming in Java” is automatically converted toString object by the compiler.

To produce the above output, Type/Edit the source program.

 

C:OopsJavaexamplessrccomoopschap1 edit HelloWorld.java

 

Compile WelcomeWorld.java using the command

 

C:OopsJavaexamplessrccomoopschap1>javac -d

c:Oopsjavaexamplesin HelloWorld.java

Now go to bin directory and type the command to execute Java program giving the full package path.

 

C:OopsJavaexamplesin>java com/oops/chap1/HelloWorld

Welcome to Object Oriented Programming in Java

Note that since it is a simple program, we have executed it from bin directory. For large programs or programs with several classes, we would write a driver program and place the class program in directory TestDriver. Then we need to execute Java command from TestDriver directory.

15.6.7 Application with Swing Components

Java extended package called Javax houses several graphical libraries which would greatly enhance the graphics components. One such facility is a dialog box for obtaining the input from the use and displaying the message. Broad class hierarchy of JComponents is shown in Figure 15.10 for basic understanding. We have shown only the components that we are going to use in the immediate sections. More details can be found in Chapters 22 and 23 on Graphics and Swing Components. Example 15.5 deals Java application that uses dialog boxes of swing components in Java.

 

Class hierarchy of graphics in Java

 

Figure 15.10 Class hierarchy of graphics in Java

 

Example 15.5: HelloWorldDialog.java: Java Application with Dialog Boxes Using Swing

      //HelloWorldDialog.java
      //We will use Dialog box offered in swing components
  1. package com.oops.chap1;
  2. import javax.swing.JOptionPane;
  3. public class HelloWorldDialog {
  4.   public static void main(String[] args) {
  5.   String input = JOptionPane.showInputDialog(“Enter your name?”);
  6.   // create the message
  7.   String message =
  8.   String.format(“Welcome %s to Object oriented programming in
  9. Java”,input);
  10.  // display the message
  11.  JOptionPane.showMessageDialog(null, message);
       }
}

Class JOptionPane in swing package is a predefined class which provides dialog boxes to be readily inserted into your program. JOptionPane.showInputDialog(“Enter your name?”); produces a dialog box for user input.

Line No. 7 & 8: String message = String.format(“Welcome %s to Object oriented programming in Java”, input); embeds input name in to message of String class.Finally Line No. 10 displays output again through Dialog box.

To obtain output Type/Edit the source program.

 

Table 15.2 Escape characters and their functions

Escape characters and their functions

 

C:Oopsjavaexamplessrccomoopschap1 edit

HelloWorldDialog.java

 

Compile WelcomeWorld.java using the command.

 

C:OopsJavaexamplessrccomoopschap1>javac -d

c:Oopsjavaexamplesin HelloWorldDialog.java

 

Now go to bin directory and type the command to execute Java program giving the full package path.

 

C:OopsJavaexamplesin>java

com/oops/chap1/HelloWorldDialoga

 

Dialog Boxes

 

image

 

Caution/Note: We are providing detailed compile and run instructions only in Chapter 1. We expect you to practice these commands well. In the succeeding chapters, we provide example programs only. Now that you have practiced two programs and learnt the edit, compile and load and run in command screen, we will introduce you to Java programming using “eclipse” JDE.

15.6.8 Eclipse-integrated Development Environment

We have loaded eclipse.exe in C:OopsJavaeclipse-jee-galileo-SR2-win32eclipse and execute eclipse.exe

Step 1: File image new imagejavaproject ..> project name : examples2 //enter project name

Execution environment :java SE 1.6 // select from drop list
Create separate folders for source & class files // select the check box
Finish.
At this stage you can see that required folders : examples2 and bin , and
src have been created by eclipse at C:OopsJavaexamples2

Step 2: File image new imageclass

Observe that you have chosen
src folder: examples2/src package : com.oops.chap1
class name as Calculator with java.lang.Object as its Super
Application with public static void main()
Inherit abstract methods
Click : finish

“eclipse” will provide basic program structure. Type in the program shown in Example 15.6. Observe that eclipse would have created your package by creating additional folders in bin and src of your project directory examples2. The package you have asked is “com.oops.chap1. Hence your Calculator.java program will be positioned at c:Oopsjavaexamples2srccomoopschap1 directory. Similarly, class file will be positioned at c:Oopsjavaexamples2incomoopschap1 directory. Run as Java Application or Java applet as the case may be. You have two options: (1) Go through run command or (2) click run on the tool bar.

 

Example 15.6: Calculator.java: Java Applet With Swing

1. package com.oops.chap1;
2. import javax.swing.*;// for JOptionPane
3. public class Calculator
4. {
5. public static void main(String[] args)
6. {
7. String number1,number2,choice; // two numbers from the user from console
8. int num1,num2,result,ch; // we need these data to do internal calculations

 

image

 

9. //input data as strings
10. number1=JOptionPane.showInputDialog(“Enter first number”);
11. number2=JOptionPane.showInputDialog(“Enter second number”);
12. // get the choice of operation to be performed**
13. choice = JOptionPane.showInputDialog(
14. “Enter 1 - Addition :
 2 - Subtraction “);
15. //for doing calculations we need to convert to intrinsic data type say int
16. num1 = Integer.parseInt(number1);
17. num2 = Integer.parseInt(number2);
18. ch = Integer.parseInt(choice);
19. if (ch==1)
20. result=num1+num2;
21. else
22. //subtract
23. result=num1-num2;
24. //display result
25. JOptionPane.showMessageDialog(null,”The result is “+result, ”Answer”,JOptionPane.PLAIN_MESSAGE);
26. // return i.e. exit programme
27. System.exit(0);
28. }
29. } // end Calculator prog

 

Output

 

image

 

Line No. 7: Number1,number2, and choice have been defined as variables of string class of Java. All inputs we will get as String class in Java.
Line Nos. 15, 17, & 18: We will convert String variables into int variable of Java to facilitate internal computations. num1 = Integer.parseInt(number1); will convert String class variable to Integer class variable.
Line Nos. 19–23: If statement will confirm if operation is addition or subtraction.
Line No. 25: Displays the result through message dialog box of JOptionpane. Null in the arguments states that dialog box to appear in the center of the screen, Message type is plain. The other options of type of messages are:
JOptionMessage.ERROR_MESSAGE
JOptionMessage.INFORMATION_MESSAGE
JOptionMessage.WARNING_MESSAGE
JOptionMessage.QUESTION_MESSAGE
Line No. 27: Is System.exit(0) returns control to Java Run-Time(JRE). Argument 0 indicates exit without error. Return 1 implies unusual program termination and return.

15.6.9 Command Line Arguments

In this example, we will revisit our calculator program and execute it through command line arguments. Please observe the void main() method

            public static void main(String[] args) {

Strings [] args means we can pass any number of arguments to main(). These are array of Strings . Accordingly, args[0] args[1] args[2] ….. etc. each argument is separated by a space. There are three arguments: number1 , number2, operation (Add or Subtract)

 

Example 15.7: Calculator2.java: A Calculator Program Command Line Argument

1. package com.oops.chap1;
2. import javax.swing.*;
3. public class Calculator2 {
4. public static void main(String[] args) {
5. int num1 = Integer.parseInt(args[0]);
6. int num2 = Integer.parseInt(args[1]);
7. int ch = Integer.parseInt(args[2]);
8. int result;
9. if (ch==1)
10. result=num1+num2;
11. else
12. //subtract
13. result=num1-num2;
14. //display result
15. JOptionPane.showMessageDialog(null,”The result is “+result, ”Answer”,JOptionPane.PLAIN_MESSAGE);
16. // return i.e exit programme
17. System.exit(0);
18. }
19. } // end Calculator prog

 

image

 

Compile Calculator2.java using the command.

 

C:OopsJavaexamplessrccomoopschap1>javac -d

c:Oopsjavaexamplesin Calculator2.java

 

Now go to bin directory and type the command to execute Java program giving full package path with arguments: 10 10 1

 

C:OopsJavaexamplesin>java com/oops/chap1/Calculator2 10 10

 

A common mistake everybody does at the stage is to forget to give complete package path: java com/oops/chap1/Calculator2. If you forget this, you will encounter “class not found error”.

15.7 Summary

  1. Java is a networking language. The Internet is a collection of cooperating networks. A network is a collection of cooperating computers.
  2. WWW (World Wide Web or simply web) is a way of accessing information from the network. We use HTTP/FTP for retrieval of information from the web. Email (through Simple Mail Protocol, SMP) is another important and widely used method to exchange information on the web.
  3. Java is platform independent, i.e. it is independent of underlying hardware and operating systems that are controlling the hardware resources.
  4. Java was originally named as “OAK” by its inventors James Gosling and Patrik Naughton.
  5. Extending/Deriving new classes from existing classes, containment through inner classes, Extending through Inheritance mechanism.
  6. Single, multi level , and hierarchical inheritance are allowed by Java . Java does not support multiple inheritance.
  7. A class with abstract method is called abstract class with keyword abstract. An abstract class need not necessarily have abstract methods.
  8. Interface is declared with keyword interface instead of usual keyword class. Interface can only contain abstract methods. However, using keyword abstract for these methods is optional.
  9. A class can extend to only one class but can implement several interfaces.
  10. Generic programming is a facility provided by Java to achieve reusability of code. Generics can be applied to classes and methods. Generic programming is very useful to abstract over types.
  11. Java supports single line, multiline, and Java API documentation comments.
  12. Byte code is an instruction set of 1 byte (8 bits). Byte codes are compact numeric codes and references (normally numeric addresses).
  13. JVM is not portable but byte code is fully portable. JVM is specific to hardware and Operating System.
  14. Package is a collection of all class files.
  15. Path command is used to link all resources situated in any directory.
  16. Classpath is used to inform the Java runtime environment where to find class files.
  17. Javadoc is a compiler used to generate API documents for a package.
  18. Java.io.* is an import statement used to import all files related to io. Similarly java.lang.* is a package imported to include Java features. This is default package Java imports automatically by default.
  19. Keyword public means that methods inside a public class can be called outside the class hierarchy.
  20. Keyword static means that the class can be invoked directly without using an instance of the class to invoke the method “main”.
  21. Java extended package called Javax houses several graphical libraries which would greatly enhance the graphics components.

Exercise Questions

Objective Questions

  1. Java has been developed by
    1. Gosling and Patric Naughton
    2. Bjarne Stroustrup
    3. Rambaugh
    4. Grady Booch
  2. Java is
    1. Hardware independent
    2. Software independent
    3. Language independent
    4. Firmware independent
  3. ------------------- command converts Java source code into byte code class file
    1. Java
    2. Javac
    3. Appletviewer
    4. Javadoc
  4. ------------------- command loads and executes a Java class file
    1. Java
    2. Javac
    3. Appletviewer
    4. Javadoc
  5. Javadoc compiler produces a file in format of type
    1. Byte code
    2. HTML format
    3. HTTP
    4. Word
  6. Java virtual machine (JVM)
    1. Converts Source Code to Object Code
    2. Converts Source Code to Byte Code
    3. Converts Byte Code to Object Code
    4. None of the above
  7. JVM uses---------------------- to convert a Java byte code class to produce machine-dependent object code
    1. Interpreter
    2. Compiler
    3. Interpreter and JIT
    4. a, b and c
  8. Inheritance is
    1. Has-type of relation
    2. Is-type relation
    3. As-is-type relation
    4. None of the above
  9. Which of the following statements are true in case of abstract classes?
    1. Must contain at least one abstract method
    2. They can be instantiated
    3. Keyword abstract must be present in the class declaration
    4. Class having abstract methods need to be declared as abstract class
    1. i
    2. ii
    3. i, iii and iv
    4. ii, iii and iv
  10. In command line arguments statement, the arguments are separated by
    1. Commas
    2. Dot (.)
    3. Space
    4. Colon
  11. BufferedReader reads
    1. Char by char
    2. String per line
    3. Word by word
    4. Till “Enter” key

    Short-answer Questions

  12. Explain WWW and internet.
  13. What are the popular protocols supported by the world wide web?
  14. Java is a language for network. Justify.
  15. What are byte codes?
  16. What is Java Virtual Machine?
  17. How do byte code and virtual machine ensure portability?
  18. What is interpreter?
  19. How do interpreter and JIT compiler improve performance of Java?
  20. List out access specifiers of Java.
  21. What are the types of inheritances supported by Java?
  22. What is the difference between a class and an interface in Java?
  23. Explain the terms JDK and API.
  24. What is Java package?

    Long-answer Questions

  25. Discuss how Java can be truly called language designed for networks.
  26. Justify “WORA”, write once and reuse it anywhere, philosophy of Java developers.
  27. Explain the objective-oriented features of Java.
  28. Discuss the similarities and differences between abstract class and interface.
  29. Explain the byte codes and JVM role in Java run-time environment.
  30. Discuss the architecture of JVM.
  31. What are environment variables? Why do we need to set these variables?

    Assignment Questions

  32. Explain how Java is most suited for networking program.
  33. How does main() work in Java environment? Explain the keyword used in void main() statement and their relevance.
  34. What are objective orientation features program of Java?
  35. Explain with a flowchart how a Java program is executed.
  36. What are the differences and similarities between C++ and Java?
  37. Distinguish between abstract class and interface.

Solutions to Objective Questions

  1. a
  2. a
  3. b
  4. a
  5. b
  6. c
  7. c
  8. b
  9. c
  10. c
  11. b
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.226.133.49