Java Progamming Paradigms, OOPS Concept, Introduction to Java, Structure of Java Program, Creating a Simple Java Program
1. Introduction to Java Programming 1.1
Introduction to Object Oriented Programming and Java
1.1 Concept of OOPS
Object-oriented programming (OOP) is a programming paradigm that
represents concepts as "objects" that have data fields (attributes that describe the object)
and associated procedures known as methods. Objects, which are usually instances of
classes, are used to interact with one another to design applications and computer
programs.
Objects
Instance of class
Attribute
+
Methods
Object
An object is basic run time entities in an object oriented system.
Object should be matched closely with the real world objects.
Object is used to invoke data and functions which handle data.
Objects can communicate with each other using messages.
Programming problem is analyzed in terms of object in object oriented system.
Object is the instance of the class.
Object has unique identifier, state and behavior.
They may be a person, a place, a bank account etc…
Student
Name
Roll No
Marks
Result()
Object
Data
Method
Real-world objects share two characteristics: They all have state and behavior.
Dogs have state (name, color, breed and hungry) and behavior (barking, fetching,
wagging tail). Bicycles also have state (current gear, current pedal cadence, and current
speed) and behavior (changing gear, changing pedal cadence, applying brakes).
Identifying the state and behavior for real-world objects is a great way to begin thinking
in terms of object-oriented programming.
For each object that you see, ask yourself two questions: "What possible states
can this object be in?" and "What possible behavior can this object perform?” The real-
2. 1.2 Java Programming Paradigms
world objects vary in complexity; your desktop lamp may have only two possible states
(on and off) and two possible behaviors (turn on, turn off), but your desktop radio might
have additional states (on, off, current volume, current station) and behavior (turn on,
turn off, increase volume, decrease volume, seek, scan, and tune). These real-world
observations all translate into the world of object-oriented programming.
Software objects are conceptually similar to real-world objects: they too consist of
state and related behavior. An object stores its state in fields (variables in some
programming languages) and exposes its behavior through methods (functions in some
programming languages).
Figure 1.1 Software Object.
By attributing state (current speed, current pedal cadence, and current gear) and
providing methods for changing that state, the object remains in control of how the
outside world is allowed to use it. For example, if the bicycle only has 6 gears, a method
to change gears could reject any value that is less than 1 or greater than 6.
Consider a bicycle, for example:
Figure 1.2 A bicycle modeled as a software object.
3. Introduction to Java Programming 1.3
Bundling code into individual software objects provides a number of benefits, including:
1. Modularity: The source code for an object can be written and maintained
independently of the source code for other objects. Once created, an object can be
easily passed around inside the system.
2. Information-hiding: By interacting only with an object's methods, the details of its
internal implementation remain hidden from the outside world
3. Code re-use: If an object already exists (perhaps written by another software
developer), you can use that object in your program. This allows specialists to
implement/test/debug complex, task-specific objects, which you can then trust to
run in your own code.
4. Pluggability and debugging ease: If a particular object turns out to be problematic,
you can simply remove it from your application and plug in a different object as
its replacement. This is analogous to fixing mechanical problems in the real
world. If a bolt breaks, you replace it, not the entire machine.
Classes
Class forms the basis in object oriented system.
Class is a user defined data types to create objects.
Object is the variable of type class.
Class can be considered as a template which defines the structure of the object.
Class is defined as the blueprint for an object.
Class serves as a plan or a template.
Collection of object is called a class.
Object 1
Object 2
Class
Object 3
Data Abstraction
The techniques refer to the act of representing the essential features to the user
without including the background details is known as Data Abstraction.
Both the data and function can be abstracted in class data type.
Classes use the concept of abstraction and defined as a list of abstract and are
4. 1.4 Java Programming Paradigms
defined as a list of abstract attributes such as size, weight and cost and methods the
operate on these attributes.
Example
A well-known example for abstraction is a car. We drive cars without knowing
the internal details about how the engine works and how the car stops on applying brakes.
Here abstraction provided to us like brakes, steering, etc. and we interact with them. As a
driver he can know the essential details but he cannot know the implementation details.
X
Implementation details
Essential details
User
Encapsulation
The process of combining data and functions together into a single entity is called
as Encapsulation
Data
X
Other Functions
Functions
Encapsulation is a technique used for hiding the properties and behaviors of an
object and allowing outside access only as appropriate, this is also known as data hiding.
It prevents other objects from directly altering or accessing the properties or methods of
the encapsulated object.
5. Introduction to Java Programming 1.5
Inheritance
Inheritance is the process of creating a new class from existing class.
A subclass inherits all the properties of a base class, in addition to this; it can add its
own features (properties and behavior).
Transport
Road Transport
Bus
Motor Bike
Air Transport
Water Transport
Aero plane
Boat
The existing classes are called base classes and the inherited (or) newly created classes
are called derived classes.
Example: cars, scooters, planes and ship all have an engine and a speedometer. These are
the characteristics of vehicles. Each subclass has its own characteristics feature, (i.e.)
motorcycles have disk braking system, while planes have hydraulic braking system. A car
can run only on the surface, while a plane can run in air and a ship sails over water.
Advantage of inheritance is code reusability. Because when a class inherits another
class, it has all properties of the base class and it adds some new properties of its own.
Abstract Class
Classes from which objects cannot be instantiated with new operator are called
abstract classes.
Each abstract class contains one or more abstract methods.
In a class if there exit any method with no implementation (i.e. method body) is
known as abstract method.
Polymorphism
Polymorphism means the ability to take more than one form. It can be defined as the
same thing being used in different forms. An operation may exhibit different behavior in
different instances
6. 1.6 Java Programming Paradigms
The behavior depends upon the types of data used in the operation. For example,
consider the operation of addition. For two numbers, the operation will generate a sum. If
the operation is strings, then the operation produce a third string by concatenation.
Shape
Draw
Circle Object
Draw (Circle)
Box Object
Draw (Box)
Triangle Object
Draw (Triangle)
Polymorphism plays an important role in allowing objects having different internal
structures to share the same external interface. This means that a general class of
operations may be accessed in the manner even though specific actions associated with
each operation may differ. Polymorphism is extensively used in implementing
inheritance.
There are two types of polymorphism: compile time and run time polymorphism.
Run time polymorphism is also known as dynamic binding or late binding is used to
determine which method to invoke at runtime. Run time polymorphism is implemented in
overriding.
Compile time polymorphism is implemented by overloading. Overloading have the
same name, but different lists and different definitions.
Message Communication (methods and messages)
Objects in object oriented system can communicate with each other using
messages.
Procedure call
Object 1
Object 2
Arguments
The process of programming in an object oriented language, therefore, involves the
following basic step
1. Creating classes that define objects and their behavior.
7. Introduction to Java Programming 1.7
2. Creating object from definitions.
3. Establishing communication among objects
Object 1
Object 2
Object 5
Object 4
Object 3
Figure 1.3 Network of Objects communicating between them.
Sending
Object
Message
Method()
Receiving
object
Figure 1.4 Message triggers a method
Messages passing between objects are necessary to simulate the real world object.
Message is passed by calling the procedures (methods) of the object with
information (arguments).
Message passing consists of object name, method name with arguments.
1.2 Benefits of OOPS
Through inheritance, we can eliminate redundant code and extend the use of
existing classes.
The principle of data hiding helps the programmer to build secure programs that
cannot be invaded by code in other parts of the programs.
It is possible to map objects in the problem domain to those in the program.
Object-oriented system can be easily upgraded from small to large system.
Message passing techniques for communication between objects makes the
interface descriptions with external systems much simpler.
Software complexity can be easily managed.
8. 1.8 Java Programming Paradigms
1.3 Applications
o Real Time System
o Simulation and modeling
o Object oriented modeling
o Hypertext and hypermedia
o Artificial and Expert System
o Neural networks
o Parallel programming
o CAD/CAM System
o Office automation system
Introduction to Java
1.4 History of Java
In 1991, James Gosling, Mike Sheridan and Patrick Naughton initiated the java
language project. First it was named as Oak. Since this name was registered by some
other company, later it was changed to java.
Java is a general purpose, concurrent, class based, object oriented computer
programming language developed by Sun Microsystem.
Java was designed for the development of software for consumer electronic
devise like TVs, VCRs and other electronic machines.
In 1996, Java Development Kit (JDK) 1.0 was released.
Java was originally developed by James Gosling at Sun Microsystem(which is
now a subsidiary of Oracle Corporation) and released in 1995.
Naming of Java
James Gosling with his team members were consuming a lot of coffee while
developing this language. Good quantity of coffee was supplied from a place called Java
Island. Hence they fixed the name of the language as Java. The symbol for java language
is cup and saucer.
Java version release
JDK Alpha and Beta (1995)
JDK 1.0 (January 23, 1996)
JDK 1.1 (February 19, 1997)
J2SE 1.2 (December 8, 1998)
J2SE 1.3 (May 8, 2000)
J2SE 1.4 (February 6, 2002)
J2SE 5.0 (September 30, 2004)
Java SE 6 (December 11, 2006)
Java 6 updates
Java SE 7 (July 28, 2011)
Java 7 updates
9. Introduction to Java Programming 1.9
1.5 Java Features
i) Simple
Understanding the basic concepts of java is easier, because it inherits the C/C++
syntax and many of the object oriented features of C++, so it is easy to learn and use java.
Java omits many rarely used, poorly understood, confusing features of C++.
ii) Object Oriented
Java is pure object oriented programming language. In object oriented, objects are
characterized by state and behavior. Everything in java is object oriented. All
program code and data are belongs to the particular object and classes.
An extensive class library available in the core language package.
In java, object oriented feature is most popular language because it support code
reusability, mainability etc.,
Oops concept in java includes object, class, data abstract and encapsulation,
inheritance, polymorphism and message passing.
iii) Compiler and Interpreter
1
Source Code
Compiler
Byte Code
2
Machine Code
Interpreter
Figure 1.5 Compiler and interpreter
Usually a computer language is either compiler (or) interpreter. Java has both these
approaches thus making java a two stage system.
First stage the java program (Source code) was compiled and byte code was
created. This byte code was not machine code.
Therefore, second stage, java interpreter generates machine code from byte code
that can be directly executed by the machine that is running the java program.
iv) Platform Independent and Portable
Java is platform independent and portable because after compiling the java source
code, byte code (.class) files are created. This byte code can be executed in any operating
system machine. This is done by JVM.
10. 1.10 Java Programming Paradigms
Java Source Code (.java)
Compiler (javac)
Byte Code(.class)
Linux Interpreter
Mac Interpreter
Machine Code
Machine Code
Machine Code
Windows
Computer
Linux Computer
Windows
Interpreter
Mac Computer
Figure1.6 Java Platform Independent
v) Distributed System
Distributed applications are created in java program by using RMI (Remote Method
Invocation) concept.
Java was designed for use on network.
Java can be transmitted over internet by using HTTP and FTP protocol.
Java applications can open and access remote objects on internet, as they can do in
a local system.
In distributed system, resources are shared.
vi) Multithreading Process
o Java allows multiple-threads to execute concurrently. That is a program can be
divided into several threads and each threads can be executed concurrently or in
parallel with the other threads.
o A thread is a light weight process.
o Multithreading increases CPU efficiency.
o A real world example for multithreading is computer. While we are listening to
music at the same time we can write in a word document and download some files.
vii) Dynamic
◊ Java is more dynamic language than C & C++.
◊ Java programs carry with them substantial amounts of run time type information
that is used to verify and resolve accesses to objects at run time.
11. Introduction to Java Programming 1.11
◊ Libraries can freely add new methods and instance variables without any effect on
their client.
viii) High Performance
Interpretation of byte codes performance was slow in the early versions. But
updated version of java virtual machines uses adaptive and just-in-time compilation
techniques speed up the performance.
ix) Robust and secure
Java provides strict compile time error checking and run time error checking. It
incorpate concept of exception handling which capture series of errors. Eliminate any
risks of crashing the system.
x) Secure
With Java's secure feature it enables to develop virus-free, tamper-free systems.
Authentication techniques are based on public-key encryption.
1.6 Structure of Java Program
A java program may contain many classes of which only one class defines a main
method. Classes contain data member and methods that operate on the data members of
the class. Methods may contain data type declarations and executable statements.
Documentation Section
Package Statement
import Statement
interface Statement
class Definition
Suggested
Optional
Optional
Optional
Atleast
one
class
main Method
{
Only one main
---method
}
Figure 1.7 Structure of a Java Program
Documentation Section
It is a set of comment line giving the name of the program, the author and other
details, which the programmer would like to refer. Comments must explain why and
what of classes and how of algorithms. Comments can be given by the following
// This is one line commands
/**
This is multiple line comments. This is used for generate automatically.
*/
12. 1.12 Java Programming Paradigms
Package
The first statement in java source code file is package statement. This statement
declares a package name and informs the compiler that the classes defined here belongs
to this package.
Ex:package travel;
Inside this package we can declare class, methods and variables. If this package has
public declaration of classes, methods and variable then it can be accessed from
anywhere. Package statement is optional statement.
import statement
Next to package statement is import statement. Two import statements
1) System import (built in)
Example
import java.io.*;
import java.awt.*;
2) User import (package created by the user)
import travelpackage.*;
This statement instructs the interpreter to load the test class contained in the
package travelpackage.
import travelpackage.*;
// *(star) represents it will load all the classes, methods
and variable in the package. Import statement is optional statement.
interface statement
An interface is like a class but include a group of method declaration, and method
definition (coding) will be in the subclass. Multiple inheritances were not supported in
java. So we implement the multiple inheritance using interfaces keyword.
Example of declaring interface
interface interfacename;
class definitions
Java program may contain multiple class definitions, in a single program for
execution any one of the class must contain main() method. These classes are used to
map the objects of real world problems.
Example of class declaration
class classname
{
// coding
}
13. Introduction to Java Programming 1.13
main method
Every program has main method where the execution is started. This is essential
part of a java program. A simple java program may contain only this part. The main
method creates objects of various classes and establishes communications between them.
On reaching the end of the main, the program terminates and the control passes back to
the operating system.
1.7 Creating a Simple Java Program
Write a simple java program in a notepad or in java text editor. Create a class
name SimpleProgram that contains only main method and prints a message “Welcome to
Java Programming Paradigms”.
Simple Java Program
class SimpleProgram
{
public static void main(String[] args)
{
System.out.println(“Welcome to Java Programming Paradigms”);
}
}
Program 1.1 Simple java program
To compile: javac SimpleProgram.java
To run (or) execute: java SimpleProgram
Output
Welcome to Java Programming Paradigms
Let us explain the program line by line and understand the unique features that
contain java program. And how to compile and execute the java program.
Class Declaration
The first line
class SimpleProgram {….}
declares the classname as SimpleProgram in java.
A class code starts with { and ends with a}.
public static void main(String args[])
o public is an access specifier that is visible to all, so other classes can make access
of this class.
o static is a keyword it is used before the main() method, so while executing the
class file, the main() method is called automatically without creating an object.
o void is a keyword, that is not a return type.
o main() the execution starts from the main method. In a java source file there
should be only one main() method.
o String args[] the main method has the parameter names args[] as string array.
14. 1.14 Java Programming Paradigms
System.out.println(“Welcome to Java Programming Paradigms”);
The println statement will print the statement i.e. given in “…” and allow next
print statement to print in new line.
If you use the statement
system.out.print(“Welcome to Java Programming Paradigms”);
The print statement will print the statement i.e. given in “…” and allow next print
statement to print in same line.
SetPath
If the java source file is not in (java bin) location then we need to set path for the
file before compiling and executing a java program.
To set path: set path=“C:Program Filesjavajdk1.6.0_07bin”
This “C:Program Filesjavajdk1.6.0_07bin” may change according to your java
installed location and version based.
Compile
While compiling a java file. It should be compiled with the file name. For
example if the file name is firstprogram.java
Then the compile statement must be javac firstprogram.java
If the class name is declared as public then the class name and the file name
should be same, if the file is compiled successfully we will get a .class file
Executing
If we get a .class file, then we can executing a java file, it should be executed with
the main method classname.
For example if the main method class name is SimpleProgram,
Execution statement is like java SimpleProgram.java
1.8 Java Virtual Machine
Java Virtual Machine (JVM) is the heart of entire Java program execution process.
First of all, the .java program is converted into a .class file consisting of byte code
instructions by the java compiler at the time of compilation. Remember, this java compiler
is outside the JVM. This (.class) file is given to the JVM. The figure 1.2 shows the
architecture of Java Virtual Machine.
In JVM, there is a module (or program) called class loader sub system, which
performs the following instructions:
· First of all, it loads the .class file into memory.
· Then it verifies whether all byte code instructions are proper or not. If it finds any
instruction suspicious, the execution is rejected immediately.
If the byte instructions are proper, then it allocates necessary memory to
15. Introduction to Java Programming 1.15
execute the program. This memory is divided into 5 parts, called run time data areas,
which contain the data and results while running the program. These areas are as
follows:
Method area
Method area is the memory block, which stores the class code, code of the
variables and code of the methods in the Java program.
Heap
This is the area where objects are created. Whenever JVM loads a class,
method and heap areas are immediately created in it.
Java Stacks
Method code is stored on Method area. But while running a method, it
needs some more memory to store the data and results. This memory is allotted on
Java Stacks. So, Java Stacks are memory area where Java methods are
executed. While executing methods, a separate frame will be created in the Java
Stack, where the method is executed. JVM uses a separate thread (or process) to
execute each method.
PC(Program Counter)
Method code is stored on Method area. But while running a method, it needs
some more memory to store the data and results. This memory is allotted on Java
Stacks. So, Java Stacks are memory area where Java methods are executed.
While executing methods, a separate frame will be created in the Java Stack, where
the method is executed. JVM uses a separate thread (or process) to execute each
method.
Native Method Stacks
Java methods are executed on Java Stacks. Similarly, native methods (for
example C/C++ functions) are executed on Native method stacks. To execute the
native methods, generally native method libraries (for example C/C++ header files)
are required. These header files are located and connected to JVM by a program,
called Native method interface.
Execution Engine contains interpreter and JIT compiler which translates
the byte code instructions into machine language which are executed by the
microprocessor. Hot spot (loops/iterations) is the area in .class file i.e. executed by
JIT compiler. JVM will identify the Hot spots in the .class files and it will give it to
JIT compiler where the normal instructions and statements of Java program are
executed by the Java interpreter.
Review Questions
Part- A (2 marks)
1) What is object oriented programming?
2) Define the terms.
16. 1.16 Java Programming Paradigms
i) object
ii) classes
iii) data abstraction
iv) encapsulation
v) inheritance vi) polymorphism
vii) methods and messages.
3) What is java?
4) What are the principal concepts of OOPS?
5) Distinguish between the following terms
i) Objects and Classes
ii) Data abstraction and encapsulation
iii) Inheritance and Polymorphism
6) List the applications of java.
7) What are the advantages of java?
8) List the features of java.
9) Why java is called platform independent language?
10) Give the structure of java.
11) Write a simple program for java.
12) What is java virtual machine?
Part-B
1)
2)
3)
4)
5)
Explain OOPS concept in detail.
List the features of java and explain them in detail.
Explain the structure of java.
Write a simple java program and explain each line in detail.
Explain java virtual machine.