Iii Sem Java Unit-1
Iii Sem Java Unit-1
OOP is an approach that provides a way of modularizing programs by creating partitioned memory area
for both data and functions that can be used as templates.
1. OOP treats data as a critical element in the program development and does not allow it to flow
freely around the system.
2. OOP allows us to divide a problem into a number of entities called objects which consists of data
and methods.
3. Data structures are designed such that they characterize the objects.
4. Data is hidden and cannot be accessed by external functions.
5. Objects may communicate with each other through methods.
6. New data and methods can be easily added whenever required.
7. It follows bottom – up approach in program design.
8. Object C, Object Pascal, C++, Java, etc are the examples
Basic concepts of Object Oriented Programming:
1. Object: Objects are the basic runtime entities in an object oriented system. They may represent a
thing, a person, a place or a back account. It represents data and methods that are used to manipulate
the data. Object must be declared is such a way that they match real world objects.
Ex: Customer and account are two objects in a bank program. The customer object may send a
message to the account object requesting for the balance.
2. Class: Class is a user defined data type. It consists of the entire set of data and methods that are used
to manipulate the data. A class is a collection of similar type of objects. Once a class is create we
create any number of objects belonging to that class.
Ex: Fruit is a class and mango, apple and orange are the objects of class fruit.
1
Object Oriented Programming Using JAVA UNIT-I
3. Data Abstraction: Abstraction refers to the act of representing essential features by hiding the
background details. Class and object uses this concept. Class is defined as a list attributes such as
size, weight and cost and methods to operate these attributes and these are represented by objects.
Since classes use the concept of data abstraction they are called as Abstract Data Types(ADT).
4. Data Encapsulation: The wrapping up of data and methods into a single unit is known as
encapsulation. Class follows this concept. The data is tied to methods and is not accessible to the
outside classes. This is called as data hiding.
5. Inheritance: Inheritance is the process of acquiring the properties of one class to another class. This
concept provides the idea of reusability. This means that we can add new features to an existing class
without modifying it.
6. Polymorphism: The ability to take more than one form is called as polymorphism. For example, an
operation may exhibit different behavior different situations. The behavior depends upon the types
of the data used in the operation. A single method name can be used to handle different types of
arguments and produce different results.
7. Dynamic Binding: Binding refers to the linking of a procedure call to the code to be executed in
response to the call. Dynamic binding means that the code associated with a given procedure call is
not known until the time of execution.
8. Message passing: An object oriented program consists of a set of objects that communicate with
each other. The process of programming in an object oriented language is:
• OOP provides greater programmer productivity, better quality programs and reduce
maintenance cost.
• By using inheritance feature we can reuse program.
• The data hiding feature helps the programmer to built secure programs.
• The polymorphism feature is used to develop efficient programs.
• Message passing techniques for communication between objects make the interface much
simpler.
• Software complexity can be easily managed.
• The data binding feature is used to develop powerful programs.
2
Object Oriented Programming Using JAVA UNIT-I
• OOP is used to solve real world problems effectively.
• It is possible to have multiple instances of an object.
• It is easy to partition the work of a project based on objects.
Applications of OOP:
• OOP is used to develop software for Real-time systems such as cell phones, TVs, VCRs and
other electronic machines.
• OOP is used for simulation and modeling. It is used to design the simulator like chess playing
etc.
• It is used to develop Object Oriented databases such as Oracle and SQL server etc.
• It is used to develop AI models like robotics.
• It is used to design expert system like car theft scanning etc.
• It is used to develop neural networks and parallel programming in network system.
• It is used to develop CAM and CAD software for architecture planning in industries.
• It is used to develop and design some new system software and packages such as operating
systems and new programming languages etc.
• It manage all the textual, graphical and animation by developing the multimedia events.
• It helps in game playing softwares.
• All resource management softwares are designed and developed through object oriented
languages.
• It develops security software for banks and finance oriented organizations.
Difference between C and Java:
C – Language Java
C ++ Java
C++ is a Object Oriented Programming Java is also a Object Oriented Programming
language. language.
Java does not use header files and preprocessor
C++ uses header files like iostream.h.
directives.
C++ uses goto, sizeof and typedef statements. Java does not include goto, sizeof and typedef.
C++ uses type modifier keywords such as auto,
Java does not use such kind of keywords.
extern, register, signed and unsigned.
C++ uses pointers. Java does not use pointers.
Java does not support multiple inheritance. It
C++ supports multiple inheritance.
uses interfaces.
C++ supports operator overloading. Java does not support operator overloading.
C++ uses destructor function. Java uses finalize function.
C++ follows bottom-up approach in program Java also follows bottom-up approach in
design. program design.
History of java:
1) Java is a general-purpose, object-oriented programming language developed by Sun
Microsystems of USA in 1991.
3) it was designed for the development of software for consumer electronic devices like TVs,
VCRs, toasters and electronic machines.
4
Object Oriented Programming Using JAVA UNIT-I
4) Oak was unsuccessful. So in 1995, sun changed the name to java and modified the language
to take the advantage of WWW.
5) The java team wanted to develop a language which is simple, portable and highly realiable.
6) The team modeled the new language java on C & C++, but removed a number of features that
were considered as sources of problems. So it makes java a powerful language.
7) The most striking feature of java is that it is a platform neural and it is the first language that
it is not tied to any particular hardware operating system.
8) The programs developed in java can be executed at anywhere and at any system.
YEAR DEVELOPMENT
1990 Sun Micro Systems decided to develop a special software
1991 OAK was developed
1992 The first project called Green project was developed
1993 WWW appeared on the Internet
1994 Developed a web browser called Hot Java
1995 OAK was renamed as java
1996 Sun releases Java Development Kit(JDK 1.0)
1997 Sun releases Java Development Kit(JDK 1.1)
1998 Sun releases Java2 with Software Development Kit(SDK 1.2)
Sun releases Java2 Standard Edition(J2SE) and Java2 Enterprise
1999
Edition(J2EE)
2000 J2SE with SDK 1.3 was released
2002 J2SE with SDK 1.4 was released
2004 J2SE with JDK 5.0 was released
Features of Java:
The inventors of java wanted the language to be not only reliable, portable and distributed but
also simple, compact and interactive. The following are the features of java:
1. Compiled and Interpreted: Usually a computer language is either compiled of interpreted, but java
combines both these approaches in two stages. In the first stage java compiler translates the source
code into byte code. In the second stage java interpreter generates the byte code that can be directly
executed by the machine.
5
Object Oriented Programming Using JAVA UNIT-I
2. Platform-independent and portable: Java programs can be easily moved from one system to
another. It can be run on any kind of system with any type of operating system. Changes and upgrades
in operating systems, processors and system resources will not force any changes in java programs.
So java has become a popular language for Internet programming.
3. Object Oriented: Java is a true object oriented language. Almost everything in java is an object. The
object model in java is simple and easy to extend.
4. Robust and secure: Java is a robust language. It provides many safeguards to ensure reliable code.
They are:
• It is designed as garbage collected language which solves all memory management problems.
• The exception handling feature helps us to identify and eliminate the errors.
• Java ensures that no viruses are communicated with an applet.
5. Distributed: Java is designed as a distributed language for creating applications on networks. It has
the ability to share both data and programs. This will help multiple programmers at multiple remote
locations to work together on a single project.
6. Simple, Small and Familiar: Java is a small and simple language as many features of C and C++
are eliminated in java. It eliminates pointers, header files and goto etc from C and operator
overloading and multiple inheritance from C++.
7. Multithreaded and interactive: Multithreaded means handling multiple parts of the same program
simultaneously. We need not wait for the application to finish one task before beginning another.
8. High performance: Java performance is impressive mainly due to the ustie of intermediate byte
code. Java is designed to reduce difficulties during the run time. It is efficient and reliable.
9. Dynamic and Extensible: Java is capable linking new class libraries, methods and objects
dynamically at run time.
10. Ease of development: It is very easy to develop java programs as java supports features sucAh as
generics, enhanced for loop, auto boxing, type safe etc.
Applications of java:
Java Environment:
Java environment includes a large number of development tools that are used for hundreds of classes
and methods. They are two categories. They are:
1. Java Development Kit (JDK):
It contains the development tools such as applet viewer, java, javac, etc.
Java Development Tools
Tool Use
Applet viewer It enables us to run java applets.
Text Editor
Java
javadoc HTMLS Files
Source Code
javac
Java
javah Header files
Class File
java jdb
7
output
Object Oriented Programming Using JAVA UNIT-I
It contains the classes and methods such as language support package, utilities package, etc. It is
also known as Application Programming Interface (API). Most commonly used packages are:
• Language Support Package: It is a collection of classes and methods required for implementing
basic features of java.
• Utilities Package: It is a collection of classes that contains utility functions such as date and time
functions.
• Input / Output Package: It is a collection of classes required for input/output manipulations.
• Networking Package: It is a collection of classes for communicating with other computers through
internet.
• AWT Package: The Abstract Window Tool Kit package contains classes that implements graphical
user interface.
• Applet Package: It is a collection of classes that allows us to create java applets.
OVERVIEW OF JAVA LANGUAGE: Java is a general-purpose, object-oriented programming
language. We can develop two types of java programs. They are:
• Stand-alone applications.
• Applets.
Stand-alone applications: They are the programs that are written in java to carry out certain tasks on
stand-alone computer. Stand-alone programs can read and write files and perform certain operations that
applets cannot do. HotJava itself is a Java application program. Executing a stand-alone Java program
involves two steps:
1. Compiling source code into byte code using javac compiler.
2. Executing the byte code program using java interpreter.
Applets: They are small java programs developed for internet applications. An applet located on a
distant computer (server) can be downloaded via Internet and executed on a local computer (client) using
a browser. We can develop applets for doing everything from simple animated graphics to games and
utilities. An applet can only run within a web browser. An applet program can compile the program
using Javac and can run this program using appletviewer.
8
Object Oriented Programming Using JAVA UNIT-I
Implementing a Java Program:
Creating the program: We can create a program using any text editor. We must save the program by
the class name, which contains the main method. This file is called the source file. Java source files
will have the extension (.java).
C:\> EDIT
class Sum
{
public static void main(String args[])
{
int s=0,i;
for(i=1;i<=10;i++)
{
s=s+i;
}
System.out.println(“Sum of 10 natural numbers:”+s);
}
}
• Compiling the program: To compile the program, we must run the java compiler javac, with
the name of the source file on the command line
C:\> javac Sum.java
If every thing is OK, the javac compiler creates a file called Sum.class containing the
byte code of the program.
• Running the program: We need to use the java interpreter to run a stand-alone program. At the
command prompt, type
C:\>java Sum 55 (Output)
• Class declaration: The first line class Sample declares a class, which is an object-oriented
construct. Java is a true object-oriented language and therefore everything must be placed inside
a class. class is a keyword and declares that a new class definition follows. Sample is a java
identifier that specifies the name of the class to be defined.
• Opening Brace: Every class definition in Java begins with an opening brace { and ends with a
matching closing brace } appearing in the last line.
• main(): The third line public static void main (String args[])defines a method named main ().
Every java application program must include the main () method. This is the starting point for
the interpreter to begin the execution of the program. A java application can have any number of
classes but only one of them must include a main method. The java applets will not use the main
method.
• All parameters to a method are declared inside a pair of parentheses. Here String args[] declares
a parameter named args, which contains an array of objects of the class type String.
• The output statement in the program is System.out.println(“Welcome to Java”);
Since Java is a true object oriented language, every method must be part of an object. The
println method is a member of the out object, which is static data member of System class. Every
Java statement must end with a semicolon.
Java Virtual Machine (JVM): It is a program that interprets the intermediate java byte code and
generates the desired output. Java is highly portable because of JVM concept. All language compilers
translate source code into machine code for a specific computer. The java compiler produces an
intermediate code known as byte code for a machine that does not exist. That machine is called as the
JVM and it exists only inside the computer memory.
11
Object Oriented Programming Using JAVA UNIT-I
The virtual machine code is not machine specific. The machine code is generated by the java
interpreter by acting as an mediator between the virtual machine and the real machine.
Java Statements: The statements in Java are like sentence in natural languages. A statement is an
executable combination of tokens ending with a semicolon (;) mark. There are five types of statements
in java. They are:
➢ Expression: Most statements are expression statements. Java has seven types of expression
statements. They are assignment, pre-increment, pre-decrement, post-increment, post-decrement,
method call and allocation expression.
➢ Labeled statement: Labels in java are used as the arguments of jump statements. Such labels
must not be keywords, already declared local variables or previously used labels in this module.
➢ Control statement:
▪ Sequential statement: Statements, Which are in between { and }
▪ Branching statement: selects one of several control flows. There are two types of
selection statements in java:
o Conditional branching: if, switch, conditional operator
o Unconditional branching: break, continue, return
▪ Iteration statement (Loop): Loop is a statement, which executes a group of statements
for a fixed number of times. There are three types of iteration statement:. They are: for,
while and do while
➢ Synchronization statement: These are used for handling issues with multithreading.
➢ Guarding statement: Guarding statements are used for safe handling of code that may cause
exceptions (such as division by zero). These statements use the keywords such as try, catch and
finally.
14
Object Oriented Programming Using JAVA UNIT-I
Constants: Constants in Java refer to fixed values that do not change during the execution of a
program.
Integer constant:
• An integer constant refers to a sequence of digits.
• There are three types of integer namely decimal integer, octal integer and hexadecimal
integer.
• Decimal integers consist of digits 0 through 9, preceded by an optional minus sign. Spaces,
commas and non-digit characters are not permitted between digits.
Example: 127, -131, 65534 etc.,
• An octal integer constant consists of digits from the 0 through 7, with leading O.
Example: O37, O435, o346 etc.
• A sequence of digits preceded by Ox or OX is considered as hexa-decimal integer. They may
also include alphabets A through F or a through f. A letter A through F represents the numbers
10 through 15.
Example: OX2, OX9F, OXbcd etc.,
Real Constants:
• Numbers containing fractional parts like 17.548. Such numbers are called real constants.
• A real number may also be expressed in exponential notation. The general form is
mantissa E exponent
• Mantissa is either a real number or an integer. The exponent is an integer with an optional + or –
sign. The mantissa and the exponent can be written in either lower case or uppercase.
Example: 215.65 may be written as 2.1565e2.
e2 means multiple by 102.
Single character constant:
A single character constant contains a single character enclosed within a pair of single quote
marks.
Examples: ‘5’ ‘x’ ‘;’ ‘’
• Note that the character constant ‘5’ is not the same as the number 5.
String character constant:
A string constant is a sequence of characters enclosed between double quotes. The character
may be alphabets, digits; special characters and blank spaces.
“2009” “Programming with Java” “3+6=9” “X”
15
Object Oriented Programming Using JAVA UNIT-I
Java supports some special backslash character constants that are used in output methods. For
example the symbol ‘\n’ stands for new line character.
List of backslash character constants
Constant Meaning
‘\b’ Back space
‘\f’ Form feed
‘\n’ New line
‘\r’ Carriage return
‘\t’ Horizontal tab
‘\” Single quote
‘\”’ Double quote
‘\\’ backslash
Symbolic constants: Symbolic constants are the variables in which they will be assigned with a
constant that cannot be changed in the program.
Syntax: final type symbolic-name = value;
Ex: final float PI= 3.14159;
Points to be remembered:
1. Symbolic names take the same form as variable names. But, they are written in capitals to distinguish
them from normal variable names.
2. After declaration of symbolic constants, they should not be assigned any other values within the
program.
3. Symbolic constants cannot be declared inside a method. They should be used only as class data
members in the beginning of the class.
//EXAMPLE PROGRAM FOR SYMBOLLIC CONSTANTS
import java.lang.Math;
class Circle
{
final double PI=3.1459f;
int r;
void putdata(int x)
{
r=x;
}
void area()
16
Object Oriented Programming Using JAVA UNIT-I
{
double a=PI*Math.pow(r,2);
System.out.println("the area of circle is ="+a);
}
}
class Carea
{
public static void main(String args[])
{
Circle c=new Circle();
c.putdata(2);
c.area();
}
}
OUTPUT:
D:\java>javac Carea.java
D:\java>java Carea
the area of circle is =12.583600044250488
Data types: Data type is the representation of the kind of data that we use in the program. Every
variable in Java has a data type. Data types specify the size and type of values that can be stored. Java
language is rich in its data types.
1. Integer types: Integer types can hold whole numbers along with the negative numbers. The size of
the values that can be stored depends on the integer data type. Java supports four types of integers.
They are byte, short, int and long. Java doest not support the concept of unsigned types.
Integer
Default
Type Size Minimum Value Maximum Value
value
byte 1 byte 0 -128(-27) 127(27-1)
short 2 bytes 0 -32,768(-215) 32,767(215-1)
int 4 bytes 0 -2,147,483,648(-231) 2,147,483,647(231-1)
17
Object Oriented Programming Using JAVA UNIT-I
long 8 bytes 0L -9,232,372,036,854,775,808(-263) -9,232,372,036,854,775,807(263-1)
2. Floating Point Types: Floating point type can hold numbers containing fractional part such as
22.365 and -89.365. There are two kinds of floating point storage in java.
Floating point
Float Double
Class: Class is a user defined data type. It consists of the entire set of data and methods that are used to
manipulate the data. A class is a collection of similar type of objects. Once a class is created we create
any number of objects belonging to that class.
Ex: Fruit is a class and mango, apple and orange are the objects of class fruit.
Interface: An interface is basically a kind of class. The difference is that interfaces define only
abstract methods and final fields. This means that interfaces do not specify any code to implement
these methods and data fields contain only constants.
Arrays: An array is a variable that can store multiple values of same data type; where as an ordinary
variable can store a single value at a time.
18
Object Oriented Programming Using JAVA UNIT-I
Variable: A variable is a data name that may be used to store a data value. A variable may take
different values at different times during execution. A variable name can be chosen by the programmer
in a meaningful way so as to reflect what it represents in the program.
Rules for a variable:
• They must begin with a letter.
• The upper and lowercase are distinct.
• It should not be a keyword.
• White spaces are not allowed.
• Variable names can be of any length.
Declaration of variables: In Java, variables are the name of storage locations. After designing suitable
variable names, we must declare them to the compiler.
• It tells the name of the variable.
• It specifies the type of data.
• The place of declaration decides the scope of the variable.
Syntax: type variable_1, variable_2, . . . . . variable_n;
Example: int a,b;
Assigning values to variables: A variable must be given value after it has been declared but before it
is used in an expression.
1. By using an assignment statement:
Syntax: variable name=value; Example: x=0;
It is also possible to assign a value to a variable at the time of its declaration.
Syntax: type variable name=value; Example: int y=2;
The process of giving initial values to variable is known as the initialization. If the variable is
not initialized, it is automatically set to zero.
2. By using a Read statement:
import java.io.*;
Class Reading
{
public static void main(String args[])throws Exception
{
InputStreamReader instr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(instr);
int n=0;
float m=0.0f;
System.out.println(“Enter an integer”);
19
Object Oriented Programming Using JAVA UNIT-I
n=Integer.parseInt(br.readLine());
System.out.println(“Enter a float value”);
m=Float.valueOf(br.readline()).floatValue();
System.out.println(“N=”+ n);
System.out.println(“M=”+ m);
}
}
Scope of variables: The area of the program where the variable is accessible is called its scope.
1. Instance variables: Instance and class variable are declared inside a class. Instance variables are
created, when the objects are instantiated and therefore they are associated with the objects. They
take different values for each object.
2. Class variables: Class variable are global to a class and belong to the entire set of objects that
class creates. Only one memory location is created for each class variable.
3. Local variables: Variables declared and used inside methods are called local variable. They are
not available for the outside the method definition. Local variables can also be declared inside
program blocks that are defined between an opening brace and a closing brace.
Type casting: Type casting is a process of converting one data type to another data type.
Syn: type variable_1 = (type) variable_2
Casting into a smaller type may result in a loss of data. The float and double can be cast to any
other type except Boolean. Casting a floating point value to an integer will result in a loss of the
fractional part.
Example: int m=50; byte n = (byte) m;
Automatic type conversion is possible only if the destination type has enough precession to
store the source value. For example, int is large enough to hold a byte value.
Example: byte b=75; int a=b;
From To
Byte short, char, int, long, float, double
Short int, long, float, double
Char int, long, float, double
20
Object Oriented Programming Using JAVA UNIT-I
Int long, float, double
Long float, double
Float Double
• The process of assigning a smaller type to a larger one is known as widening or promotion
• The process of assigning a larger type to a smaller one is known as narrowing.
// EXAMPLE ON TYPECASTING
class Dataconversion
{
public static void main(String args[])
{
byte m=50;
System.out.println("m="+m);
int n=m;
System.out.println("n="+n);
}
}
OUTPUT:
D:\java>javac Dataconversion.java
D:\java>java Dataconversion
m=50
n=50
Operators: An operator is a symbol that tells the computer to perform certain mathematical or logical
operations. Types of Operators:
21
Object Oriented Programming Using JAVA UNIT-I
2. Relational 6. Conditional
4. Assignment 8. Special
% Modulo Division
== Is equal to
!= Is not equal to
22
Object Oriented Programming Using JAVA UNIT-I
3.Logical Operators: An expression, which combines one or more relational expressions, is termed as
|| OR (a>b)||(a>c)
! NOT !(a>b)
4. Assignment Operator (=): Assignment operators are used to assign the value to a variable.
5. Increment and decrement Operators: The operator ++ adds 1 to the operand and the operator - -
subtracts 1 from operand. We use the increment and decrement statements in for and while loops
extensively.
A pre-increment operator first adds 1 to the operand and then the result is assigned to the variable on
left.
m=5; y=++m;
A post-increment operator first assigns the value to the variable on the left and then increment the
operand.
m=5; y=m++;
A pre-decrement operator first subtracts 1 from the operand and then the result is assigned to the variable
on left. Ex:m=5; y = --m;
A post-decrement operator first assigns the value to the variable on the left and then decreases the
operand by 1. Ex: m=5; y=m--;
x = (a > b)? a: b;
In the above example x will be assigned the value of b as the value of a is not greater than the value of
b.
7.Bit wise Operators: These operators are used for testing the bits, or shifting them right or left.
Operator Meaning
| bit wise OR
~ one’s complement
8. Special Operator:
a. Instanceof operator: This operator allows us to find whether the object belongs to a particular class
or not.
b. Dot operator: The dot operator (.) is used to access the instance variable and methods of class objects.
Ex: x.rno, x.name, x.average() It is also used to access classes and sub-packages from a package.
24
Object Oriented Programming Using JAVA UNIT-I
Ex: a=5; b= 6;
a + b = 11
2. Real Arithmetic Expression: It is an expression in which all the operands are real and the result
is real.
Ex: a=2.5; b= 3.5;
a + b = 6.0
3. Mixed Mode Arithmetic Expression: It is an expression in which all the operands are both
integers and real and the result is real.
Ex: a=2.5; b= 6;
a + b = 8.5
Evaluation of expressions: Expressions are evaluated using an assignment statement such as
Variable = expression;
Variable is any valid java variable name. When the statement is encountered the expression
is evaluated first and the result will replaces the previous value of the variable on the left-hand side.
All variables used in the expression must be assigned values before evaluation is attempted.
Operator precedence and associatively: The precedence is used to determine how expression
involving more than one operator is evaluated. The operator at the higher level of precedence is
evaluated first. The operators of the same precedence are evaluated either from left to right or from
right to left, depending on the level. This is known as the associatively property of an operator.
25
Object Oriented Programming Using JAVA UNIT-I
+ Addition
Left to right 4
- Subtraction
<< Left shift
>> Right shift Left to right 5
>>> Right shift zero fill
< Less than
<= Less than or equals to
Left to right 6
> Greater than
>= Greater than or equals to
== Equality
Left to right 7
!= inequality
& Bitwise and 8
^ Bitwise Xor 9
| Bitwise or 10
&& Logical and Left to right 11
|| Logical or 12
?: Conditional operator 13
= Assignment operator 14
26