0 ratings0% found this document useful (0 votes) 27 views28 pagesJava Part 1
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here.
Available Formats
Download as PDF or read online on Scribd
Object Oriented Programming
OOP treats data as an important element in the program development and does not allow it to flow
freely around the system. It ties data more closely to the function that operate on it, and protects it
from accidental modification from outside function, OOP allows decomposition ofa problem into a
umber of entities called objects and then builds data and function around these objects.
‘The organization of data and function in object-oriented programs is shown in the following figure
Organization of data and fimetion in OOP
Object A Object B
DATA pata
ommunication
¥ F »| +
FUNCTION FUNCTION
DATA|
z
FUNCTION
Features of object oriented programming are:
+ Emphasis is on data rather than procedure,
+ Programs are divided into what are known as objects.
+ Data structures are designed such that they characterize the objects
+ Functions that operate on the data of an object are tied together in the data structure.
+ Data is hidden and cannot be accessed by external funtion,
+ Objects may communicate with each other through function.
+ New data and functions can be easily added whenever necessary,
+ Follows bottom up approach in program design.
Basic Concepts of Object Oriented Programming
+ Objects
+ Classes:
+ Inheritance
+ Polymorphism
+ Abstraction+ Encapsulation
+ Dynamic binding
+ Message passing
1. Objects
Object is an instance of a class. Objects are the basic run time entities in an object-oriented system
‘They may represent a person, a place, a bank account, a table of data or any item that the program has
to handle. They may also represent user-defined data such as vectors, time and lists. Objects take up
space in the memory and have an associated address like a record in Pascal, ora structure ine.
2. Classes
+ Collection of objects is called a class. It isa logical entity
+ class ean also be defined as a blueprint from which you ean create an individual object
Class doesn't consume any space.
+ Acclass is thus a collection of objects of similar types. For examples, Mango, Apple and orange
‘members of class fruit. Classes are user-defined that types and behave like the built-in types of
a programming language.
+ Lffiuit has been defined as a class, then the statement
Fruit Mango; Will create an object mango belonging to the class fruit.
3. Inheritance: Inheritance is the process by which objects of one class acquire the properties of
objects of another classes. It supports the concept of hierarchical classification
For example, the bird, ‘robin’ isa part of class “flying bird’ which is again a part of the class “bird”.
Each derived class shares common characteristics with the class ftom which it is derived. In OOP, the
concept of inheritance provides the idea of reusability. This means that we can add additional features
to an existing class without modifying it.
4. Polymorphism : Polymorphism is another important OOP concept. Polymorphism means the
ability to take more than on form. An operation may exhibit different behavior in different instances,
For example, consider the operation of addition. For two numbers, the operation will generate a sum.
If the operands are strings, then the operation would produce a third string by concatenation. This
process is known as operator overloading.
5. Abstraction : Abstraction refers to the act of representing essential features without including the
‘background details or explanation. Classes use the concept of abstraction. They encapsulate all the
essential properties of the object that are to be created
The attributes are some time called data members because they hold information. The functions
that operate on these data are sometimes called methods or member function
6. Encapsulation : The wrapping up of data and function into a single unit (called class) is known as
encapsulation. The data is not accessible to the outside world, and only those functions which are‘wrapped in the class can access it. This insulation of the data from direct access by the program is
called data hiding o information hiding.
7. Dynamic Binding ; In dynamic binding, the method call is bonded to the method body at run time,
Dynamic binding means that the code associated with a given procedure call is not known until the
time of the call at run time, Its associated with polymorphism and inheritance.
Consider the previous fig, Every object will have “draw”. ts algorithm is, however, unique to
each object and so the draw procedure will be redefined in each class that defines the object. At
run-time, the code matching the object under current reference will be called.
Dynamic binding is also known as late binding
8. Message Passing
An object-oriented program consists of a set of objects that communicate with each otber. The
process of programming in an object-oriented language, involves the following basic steps
1. Creating classes that define object and their behavior,
2. Creating objects from class definitions, and
3. Establishing communication among objects.
A Message for an object is a request for execution of a procedure, and therefore will invoke a
function (procedure) in the receiving object that generates the desired results. Message passing
involves specifying the name of object, the name of the function (message) and the information to be
sent.
Example:
+ Employee. Salary (name);
Introduction to Java
+ Java is a programming language and a platform. Java is a high level, robust, object
oriented and secure programming language.
+ Java was developed at Sun Microsystems (which is now the subsidiary of Oracle) by
James Gosling in the year 1991, James Gosling is known as the father of Java. Before
Java, its name was Oak, Since Oak was already a registered company, so James Gosling
‘and his team changed the Oak name to Jav:
+ Java programming is very useful for Internet Programming, Today, it is used not only
for Web Programming, but also for developing standalone applications across platforms
on servers, desktops and mobile devices.
Classification of Java Programs
programs are classified into two types:
1. Application Programs2. Applet Programs
1.An application program is run on the computer under the operating system of the
computer. This is similar to the other programming languages.
2.An applet is designed to be transmitted over the internet and executed by a Java
‘compatible web browser. Applets can be run from a web browser. Applets use a modern
graphical user interface with buttons, text fields, text areas, radio buttons and so on, to
interact with users on the web and process their request. Applets make the web
responsive, interactive and fun to use. Applets are not full-featured application
programs. They are usually written to accomplish a small task or a component of task.
Differences between Application Program and Applet
Applets are smalll Java programs that
are designed to be included with the
HTML web document. They require a
Java-enabled web browser for
execution.
Applet does not require a main
function for its execution,
Applets don’t have local disk and
network access.
Applets can only access the browser
specific services. They don’t haye
access to the local system.
Applets cannot execute programs
from the local machine, It is
downloaded from remote machines.
‘An applet program is needed to.
perform smal tasks or the part of it.Features of Java
Compiled and Interpreted
Platform Independent and Portable
Object-Oriented
Robust and Secure
Distributed
Simple, Small and Familiar
Multithreaded and Interactive
Dynamic and Extensible
High Performance
Explanation of the Features of Java
1, Compiled and Interpreted
Usually a computer language is either compiled o
approach, thus making Java a two-stage system.
terpreted. Java combines both this
First, Java compiler translates source code into what is known as byte code instructions.
Byte codes are not machine instructions and therefore, in the second stage, Java
interpreter generates machine code that can be directly executed by the machine that is,
running the Java program. We can thus say that Java is both a compiled and
interpreted.
Ex: filename,java
‘Compiling > javae filename java
After successful compilation, filename.class is made which is a byte code.
Interpreting > Now, filename.class can be executed anywhere by:
java filename
2. Platform Independent and Portable
Java is a platform independent language. Once we created the program in one operating
system, it can work on any other operating system under any environment.
Java programs can be easily moved from one computer system to another, anywhere
and anytime. Changes and upgrades in operating systems, processors and system
resources will not force any changes in Java programs.
Java ensures portability in two way:Java compiler generates byte code instructions that can be implemented on any
machine.
i. The size of the primitive data types are macl
same
1¢ — independen
.. sizes remain the
3. Object-Oriented
Java is a true object oriented language. Almost everything in Java is an object. All the
program code and data reside within objects and classes. Java comes with an extensive set
of classes, arranged in packages, that we can use in our programs by inheritance. The object
oriented model in Java is simple and easy to understand.
4, Robust and Secure
+ Java is a robust language. It provides many safeguards to ensure reliable code. It has
strict compile time and runtime checking for data types. It is designed as a garbage —
collected language relieving the programmers virtually all memory management
problems.
Java also incorporates the concept of exception handling which captures serious errors
and eliminates any risk of crashing the system. Security becomes an important issue for
a language that can be used for programming on internet. Java systems not only verify
all memory access but also ensure that no viruses ean communicate with an applet. The
absence of pointer in Java ensures that programs cannot gain access to memory
locations without proper authorization,
5. Distributed
Java is designed as a distributed language for creating applications on networks. It has
the ability to share both data and programs. Java applications can open and access
remote objects or internet as easily as they can do in a local system. This enables
multiple programmers at multiple remote locations (o collaborate and work together on
a single object.
6, Simple, Small and Familiar
+ Java is a small and simple language. Many features of C and C++ that are either
redundant or sources of unreliable code are not part of Java, For example, Java does not
use pointers, pre-processor header files, goto statement and many others,
+ To make the language look familiar to the existing programmers, it was modelled on C
and C+ languages, Java uses many constructs of C and C+ and therefore, Java code
“look like a C+#” code.
7. Multithreaded and Interactive
‘Multithreaded means handling multiple tasks simultancously. In Java, we need not to
wait for the application to finish one task before beginning another. For example, we can
listen to an audio clip while scrolling a page and at the same time download an applet
from a distant computer. This feature greatly improves the interactive performance of
graphical applications.8. Dynamic and Extensible
Java is a dynamic language. Java is capable of dynamically linking the new class
libraries methods and objects. Java supports functions written in other languages such
as C and C++. These functions are known as native methods. Native methods are linked
dynamically at runtime.
9. High Performance
Java performance is impressive for an interpreted language, mainly due to the use of
intermediate byte code Java and architecture is designed to reduce overheads during
runtime. Furthermore, multithreading enhance the overall execution speed of Java
programs.
Java Environment
Phase 1 = }_.fSa |
Phase 2 — |_,!
Phase 3 ‘Stas Loader
Phase 4
Phase 5
Phase 1: Java program is typed in a text editor (ex. Notepad). The programmer specifies
that the fire in the editor should be saved. The program is stored on a secondary storage
device such as disk. Java program files are stored with .java extension filename.
Ex:- C:\jdk1.S\bin\filename.jaya
+ Phase 2: The programmer gives the command javac filename,java to compile the
program. At this stage, the Java compiler translates the Java program into byte codetha
correcth
that will be interpreted d
s the language understood by the Java interpreter. If the program compiles
a file called filename.class is produced. This is the file containing byte codes
ig the execution phase.
+ Phase 3: This phase is called loading. The program must be placed in memory before it
can be executed. This is done by the class loader, which takes the .class file cont
byte code and translates it into the memory.
+ Phase 4: Byte code verifier confirms that all byte codes are valid and do not violate Java
security instructions.
+ Phase 5: Java interpreter reads byte code and translate them into a language that the
computer can understand and then exeeutes the code.
Java Program Structure
1, Documentation: Comprises a set of comment ing the name of the program, the
author and other details,
a ae *yforms the compiler that the classes defined here
belong to this package.
ex: package abes
3. Import Statements: \elude statement in C
import abe.test
‘This statement instructs the interpreter to load the test ¢
abe.
ss contained in the package
4, Interface Statements:
implement multiple inhe
is like a class but includes a group of method declarations used to
ance.
5. Class Definitions: Classes are the prime and essential elements used to map the objects.
6. Main Method Class :Every Java standalone program requires a man method as its
starting point.
Tokens in Java+ Reserved Keywords :
Keywords have specific meaning in Java. We cannot use them as names for variables,
classes, methods and so on.
Ex: class, double, event, new, public, try, while ete.
About 50 reserved keywords currently in Java.
+ Identifiers :
‘These are used for naming classes, methods, variables, objects, labels, packages and
interfaces. Ex: sum, length, average etc.
© Literals
Integral Literals in Java t 146, -98
Floating-Point Literals : 101.23, 78.987
Char Literals in Jaya :
‘a. Single Quote : char ch = ‘a's
b, Escape Sequence : char ch = \n's
String Literals : String s = "Hello"
Boolean Literals : boolean b = true;
‘* Constants: Constants are also like normal variables. But, the only difference is, their
values can not be modified by the program once they are defined. Constants refer to
fixed values. They are also called as literals.
Syntax:
final int a= 16;
+ Separators: Parentheses(), braces {}, brackets[], semicolon; comma , dot . (used to
separate package name from sub package and classes)A simple Java Program
class Example
{
publie static void main (String args[])
System.out.printin(“Hello”)
1
}
- Class Declaration : The first
oriented construct.
ine i.e. class Example declares a class, which is an object
2. Opening Braces : Every class definition in Java begins with an opening brace “{* and
ends with a closing brace *}”
3. The Main Line
The third line
public static void main(String args[])
This defines a method main whi
the execution of the program.
is the starting point for the interpreter to begin
Contains public, static, void and string args|]
4. public: it declares the main method as unprotected and therefore making it
accessible (o all the other classes,
5. static: Declares this method as one that belongs to the entire class and not a part of
any object of the class. It_ allows main( ) method to be called without having to
instantiate a particular instance of the class. The interpreter uses this method before any
objects are created.
6. void: main( ) method does not return any value.
4. String args] ] : Declares a parameter named args, which is am array of instances of
the class string. args receives any command line arguments present when the program is
executed.
4, The Output
‘System.out.printin(“Java is better than CH);
It is similar to pringf(). Since Java is a true object oriented language, every method
must be a part of an object, which is a static data member of the System class.Data Types
Data Type
Primitive Non-Primi
Boolean Numeric
Character integral
Integer Floating-point
ae ee
boolean char byte short int long float double
Primitive Data TypesJava Statements
Expression Statements
Expression statements are valid Java expressions that are terminated by a semicolon. In
Java, there are four kinds of expression statements:
+ assignment expressions such as ¢ = ab; a4=53 z=x;
‘+ prefix and postfix increment and decrement such as ++a3 --b; ¢~
+ method invocations, whether or not they return a value
If and If-Else Statements
‘The simplest control flow construct in Java is the if statement, which can have an
optional else clause, Here is the format without the else clause:
if (oolean-expression)
statement
‘The statement can be a simple statement terminated by a semicolon or a block enclosed in
curly braces. Alternatively, we can add an els
if (boolean-expression)
statement!
else
statement?
Else-If Ladder
if(conditiont)
statement-1;