Professional Documents
Culture Documents
Prepared by:
Advantages of OOP:
Through inheritance, we can eliminate redundant code and extend the use of
existing.
Information hiding and data abstraction increase reliability and helps the
programmer to build secure programs that cannot be invaded by code in other
parts of the program.
Dynamic binding increases flexibility by permitting the addition of a new class
of objects without having to modify the existing code.
Inheritance coupled with dynamic binding enhances the reusability of a code
thus increasing the productivity of a programmer.
Many OO languages provide a standard class library that can be extended by
the users thus saving a lot of coding and debugging effort.
If is possible to have multiple instances of an object to co-exist without any
interference.
It is easy to partition the work in a project based on objects.
DISADVANTAGES:
It is not suitable for small programs where functions can give more accurate and
quick results
It requires complicated spadework before OOP becomes fully operative
Creation of object libraries and its maintenance is a tough job.
Requires the master over the software engineering and programming
methodologies.
Benefits only in long run while managing large software projects.
Procedure Oriented Programming
Object Oriented Programming
Emphasis is on doing things
Emphasis is on data rather than procedures
Programs are divided into small things Programs are divided into what are known as
known as functions
Objects
Data move openly around the system from Data is hidden and cannot be accessed by
function to function
external functions
Debugging Process is very difficult
Debugging Process is very easy
Follows top-down approach in program Follows bottom-up approach in program
design
design
Most of the functions share global data
The data of an object can be accessed only by
the functions that are associated with it
Prepared by:
Objects
Classes
Data abstraction and encapsulation
Inheritance
Polymorphism
Dynamic binding
Message passing
Object: 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 td handle. Objects take up space in the memory and have an associated
address like a record in Pascal or a structure in c.
Classes: Classes are user-defined data types and behave like the built-in types of a
programming language. The entire set of data and code of an object can be made a
user-defined data type with the help of a class. In fact, objects are variables of the
type class. Each object is associated with the data of type class with which they are
created. A class is a collection of objects of similar type. For example mango, apple
and orange are members of the class fruit.
Fruit mango;
Will create an object mango belonging to the class fruit.
Data Abstraction and Encapsulation: The wrapping up of data and functions into a
single unit is known as encapsulation. Data abstraction is done using the classes. 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 or information hiding.
Abstraction refers to the act of representing essential features without including
the background details or explanations. Classes use the concept of abstraction and are
defined as a list of attributes and functions to operate on these attributes. They
encapsulate all the essential properties of the objects that are to be created.
Inheritance: Inheritance is the process by which objects of one class acquire the
properties of objects of another class. It supports the concept of hierarchical
classification. For example the bird robin is a part of the class flying bird which is again a
part of the class bird. The idea behind this sort of division is that each derived class shares
common characteristics with the class form which it is derived. Inheritance provides the idea
of reusability.
There are Five types of Inheritance
a) Single
b) Multiple
c) Multilevel
d) Hierarchical
e) Hybrid
Prepared by:
Single inheritance: Derivation of a class from only one base class is called single
inheritance.
Multiple inheritance: Derivation of a class from two or more classes is called multiple
inheritances.
Hierarchical inheritance: Derivation of several classes from a single base class i.e. the traits
of one class may be inherited by more than one class is called hierarchical inheritance.
Multilevel inheritance: Derivation of a class from another derived class is called multilevel
inheritance.
Hybrid inheritance: Derivation of a class involving more than one form of inheritance is
known as hybrid inheritance.
Multipath inheritance: Derivation of a class from other derived classes, which are derived
from the same base class, is called multipath inheritance.
A
B
SingleInheritance
MultipleInheritance
Hierarchical
Inheritance
A
A
C
Multilevel Inheritance
D
Hybrid Inheritance
Polymorphism: Polymorphism, a Greek term, means the ability to take more than one form.
The following are the different ways of achieving Polymorphism in Java.
Prepared by:
polymorphism
Compile-time polymorphism
Or
static/early binding
Run-time polymorphism
Or
Dynamic/Late binding
Prepared by:
JAVA FUNDAMENTALS
JAVA EVOLUTION:
Java was developed by a team of computer professionals under the guidance of James
Gosling at sun Microsystems in 1991. Java was designed for the development of software for
consumer electronic devices.
JAVA FEATURES
Compiled and Interpreted
Java combines both these approaches thus making java a two-stage system. First, Java
compiler translates source code into what is known as bytecode instructions. Bytecode 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.
Platform-Independent and Portable
Java is compiled to an intermediate form called Java Byte-Code or simply byte code. A Java
program never really executes immediately after compilation on the host machine. Rather,
this special program called the Java Interpreter or Java Virtual Machine reads the bytecode,
translates into the corresponding host machine instructions and then executes the machine
instruction. A java program can run on any computer system for which a JVM and some
library routines are installed. Because of Platform Independence Java programs can be
portable from a mini computer up to a super computer irrespective of H/W requirements and
OS Base.
Object-Oriented
Java is one of the Pure Object Oriented Programming Language where every construction of
the program should be written under the implementation of class which is the basic part of
OOPS.
Robust and Secure
Robustness is measured with the help of 2 concepts 1) Memory Management 2) Exception
Handling
In traditional applications, the programmer is responsible for both allocations and
deallocation of memory. In Java, Memory allocation is controlled by JVM where object
creation is done by the user deallocation is taken by Garbage Collector
In C,C++ error handling is done manually even before running the program. If any run-time
error comes the program is in inconsistent state which leads to memory leak. Java supports
pure exception handling which guards the program from abnormal situations.
Java is intended to work in networked and distributed environments by providing security.
Security becomes an important issue for a language that is used for programming on Internet.
Java Systems not only verify all memory access but also ensures that no viruses are
Prepared by:
communicated with an applet. The absence of pointers in Java ensures that programs cannot
gain access to memory locations without proper authorization.
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
on Internet as easily as they can do in a local system. This enables multiple programmers at
multiple remote locations to collaborate and work together on a single project.
Familiar, Simple and Small
By using Java different range of applications can be developed by keeping the common
structure which is understood by JVM. Java uses many constructs of C and C++ and
therefore, Java code looks like a C++ code.
Multithreaded and Interactive
Multithreaded means handling multiple tasks simultaneously. It is one of the important
features of Java that provides multi-tasking where 2 parts of a program can be runnable
concurrently by sharing the common block of resources. This feature greatly improves the
interactive performance of graphical applications.
High performance
Java performance is impressive for an interpreted language, mainly due to the use of
intermediate bytecode. Java architecture is also designed to reduce overheads during runtime.
Dynamic and Extensible
Java is capable of dynamically linking in new class libraries, methods and objects. In Java
classes that were unknown to a program when it was compiled can still be loaded into it at
runtime. Java programs support functions written in other languages such as C and C++.
Java Weaknesses:
Java is that it doesnt directly support true decimal data.
Ex:
Double x = 5.02;
Double y = 0.01;
Double z = X + Y;
System.out.println(z);
Output:
5.029999999999999
But result is 5.03
Prepared by:
Prepared by:
:
:
:
:
:
JAVA ENVIRONMENT
It is a product from sun microsystem which is a collection of n number of tools and
utilities which are used together to develop dynamic applications using java. The
development tools are part of the system known as Java Development Kit (JDK) and the
classes and methods are part of the Java Standard Library (JSL), also known as the
Application Programming Interface (API).
Tools of Java Development Kit (JDK)
1. Javac (Java Compiler) :
Usage: javac <filename.java>
It stands for Java Compiler which takes the source code and translates into byte code.
Prepared by:
Prepared by:
10
AWT Package:
The Abstract Window Tool Kit package contains classes that implements platform
independent graphical user interface.
Applet Package:
This includes a set of classes that allows us to create Java applets.
OVERVIEW OF JAVA LANGUAGE
SIMPLE JAVA PROGRAM
Class Example
{
public static void main(String args[])
{
System.out.println(Welcome to Java);
}
}
Save this file as Example.java same as class name
Class Example
It defines a class named Example using a keyword class. After that, class definition is
specified within curly braces.
Prepared by:
11
12
This statement instructs the interpreter to load the methods contained in the package java.io.
Interface Statement
This is an optional section and is used only when we wish to implement the multiple
inheritance feature in the program.
Class Definition
A java program may contain multiple class definitions, which contains business logic
methods.
Main Method Class
Since every Java program requires a main method as its starting point, this class is the
essential part of a java program.
JAVA TOKENS
Smallest individual units in a program are known as Tokens. The complier recognized them
for building up expressions and statements. Java languages include 5 types of Tokens. They
are:
Reserved Keywords
Identifiers
Literals
Operators
Separators
Keywords:
A keyword is a word that has special meaning defined by the Java programming language.
The program shown earlier in Listing 1-1 uses four keywords:public, class, static, and void.
In all, Java has 51 keywords. Theyre listed in alphabetical order in Table 1-1. abstract do if
package synchronized boolean double implements private this break else import protected
throw byte extends instanceof public throws case false int return transient catch final
interface short true char finally long static try class float native strictfp void
Prepared by:
13
Identifiers:
An identifier is a word that you make up to refer to a Java programming element by
name. Although you can assign identifiers to many different types of Java elements, theyre
most commonly used for the following elements:
Classes, such as the HelloApp class in Listing 1-1
Methods, such as the main method in Listing 1-1
Variables and fields, which hold data used by your program
Parameters, which pass data values to methods
Comments:
A comment is a bit of text that provides explanations of your code. Comments are completely
ignored by the compiler, so you can place any text you wish in a comment. Using plenty of
comments in your programs is a good idea to explain what your program does and how it
works.
Java has three basic types of comments:
end-of-line comments
traditional comment
Multi comments
JavaDoc comments.
End-of-line comments (single Line comments):
An end-of-line comment begins with the sequence // and ends at the end of the line. You can
place an end-of-line comment at the end of any line.
Everything you type after the // is ignored by the compiler. For example:
total = total * discountPercent; // calculate the discounted total
If you want, you can also place end-of-line comments on separate lines,
like this:
// calculate the discounted total
total = total * discountPercent;
You can place end-of-line comments in the middle of statements that span
two or more lines. For example:
total = (total * discountPercent) // apply the discount first
+ salesTax; // then add the sales tax
Traditional comments (Multi Line comments):
A traditional comment begins with the sequence /* and ends with the sequence */ and can
span multiple lines. For example:
/* HelloApp sample program.
This program demonstrates the basic structure
that all Java programs must follow. */
A traditional comment can begin and end anywhere on a line. If you want, you can even
sandwich a comment between other Java programming elements, like this:
x = (y + /* a strange place for a comment */ 5) / z;
Usually, traditional comments appear on separate lines. One common use for traditional
comments is to place a block of comment lines at the beginning of a class to indicate
information about the class such as what the class does, who wrote it, and so on. However,
that type of comment is usually better coded as a JavaDoc comment, as described in the next
section.
Prepared by:
14
15
Java Interpreter
For windows 98
Byte Code
Java Compiler
Java Program
Byte Code
Byte Code
Java Interpreter
For macintosh
Java
Interpreter
Java Interpreter
For Linux
Prepared by:
16
DATA TYPES
A Data type is the type of data that can be stored into the variable. A description on a variable
that determines what kind of information you can enter in the variable.
There are seven primitive data types, which are supported by Java language programming. A
primitive data type is a data type, which is predefined in Java. Following are the eight
The term Data Type refers to the type of data that can be stored in a variable.
Java is sometimes called a strongly typed language.
Prepared by:
17
Type
int
short
long
byte
float
double
char
boolean
18
char
The char data type is a single 16-bit, unsigned Unicode character. It ranges from 0 to 65,535.
They are not same as ints, shorts etc.
/* Program on Datatypes */
class datatypes
{
public static void main(String []args)
{
int a=457647657;
byte b=12;
short c=435;
long d=345;
float g=3.5f;
double f=345.6;
char k='a';
boolean h=false;
System.out.println("Integer="+a);
System.out.println("Byte="+b);
System.out.println("Short="+c);
System.out.println("Long="+d);
System.out.println("Float="+g);
System.out.println("Double="+f);
System.out.println("Character="+k);
if(h==true)
System.out.println("Boolean value is true");
else
System.out.println("Boolean value is false");
}
}
Output:
E:\sysvol>javac datatypes.java
E:\sysvol>java datatypes
Integer=457647657
Byte=12
Short=435
Long=345
Float=3.5
Double=345.6
Character=a
Boolean value is false
Reference data types :
Reference types are types that are defined by the language java API rather than by the
language itself.
Prepared by:
19
The memory location associated with a reference tpes variable contains an address
(called pointer) that indicates the memory location of the actual object.
VARIABLES
A variable is a basic unit of storage, which represents memory location in which value can be
stored.
Rules for variables:
1. They must not begin with a digit
2. It should not be a keyword
3. White space is not allowed
4. Variable names can be of any length
DECLARATION OF VARIABLES
Before using any variable, it must first be declared. A variable declaration specifies the
datatype, the variable name, and optionally the default value for the variable.
Syntax: datatype identifier {=default value}
Ex:
byte b;
int age, enrolno
boolean male
GIVING VALUES TO VARIABLES
Once you have declared the type of a variable, you can initialize it with some value.
Syntax: variable name=some value
Ex:
int year=20;
SCOPE OF VARIABLES
Java actually has three kinds of variables
Instance variables
Class variables
Local variables
Instance variables are created when the objects are instantiated and therefore they are
associated with the objects. They take different values for each object. Class variables are
similar to instance variables, except their values apply to all the instances of a class rather
than having different values for each object. Local variables are declared and used inside
methods.
Variables :
Variables are also the key to creating programs that can perform calculations.
Type of Variables :
1. class variable
2. Instance variable
3. Local variable
Prepared by:
20
4. Final variable
5. shadowing variable
Class Variable :
A class variable is a variable that any method in a class can access, including static
methods such as main.
When declaring a class variable you have two basic rules to follow:
1. You must place the declarations within the body of the class, but not within any of
the class method.
2. You must include the word static in the declaration. The word static comes before the
variable type.
E.g.: public class helloapp {
static string hellomessage;
public static void main(String[] args) {
hellomessage = Helloworld!;
System.out.println(hellomessage);
}
}
Instance variable :
An instance variable is similar to a class variable, but doesnt specify The word static in its
declaration.
Instance variables are associated with instances of classes.
E.g.:
public class helloapp {
string hellomessage;
public static void main(String[] args) {
hellomessage = Helloworld!;
System.out.println(hellomessage);
}
}
Error :
Cannot make a static reference to the non-static field hellomessage
Local variable :
A local variable is a variable thats declared within the body of a method.
You dont specify static on a declaration for a local variable.
local variables are not given initial default values. The compiler checks to make sure
that you have assigned a value before you use a local variable.
Final variable (Constants) :
Prepared by:
21
22
int i=123456789;
long l=1234567654321L;
float f1=3.142F;
float f2=1.2e-5F;
double d2=0.000000987;
System.out.println(" c="+c);
System.out.println(" b ="+b);
System.out.println(" s= "+s);
System.out.println(" i="+i);
System.out.println(" l="+l);
System.out.println(" f1= "+f1);
System.out.println(" f2="+f2);
System.out.println("d2 ="+d2);
System.out.println(" ");
System.out.println(" Types converted");
short s1=(short)b;
short s2=(short)i;
float n1=(float)l;
int m1=(int)f1;
System.out.println(" (short)b ="+s1);
System.out.println(" (short)i ="+s2);
System.out.println(" (float)l= "+n1);
System.out.println(" (int)f1= - "+m1);
}
}
Note : floating point constants have a default type of double
For example when we want to declare a float variable and initializing it to constant
float x=7.56;
This will give incompatible type for declaration. Explicit cast needed to convert double to
float.
This should be written as
float x=7.56F
Prepared by:
23