SlideShare ist ein Scribd-Unternehmen logo
1 von 70
Downloaden Sie, um offline zu lesen
BASICS OF JAVA PROGRAMMING
Mugabe N. Gabriel

1
1. INTRODUCTION




Since the invention of
the computer, many
programming approaches have been tried.
These
include techniques such modular programming, topdown programming, bottom-up programming and
structured programming. The primary motivation in
each case has been the concern to handle the
increasing complexity of programs that are reliable and
maintainable.
With the advent of languages such C, structured
programming became very popular and was the
paradigm of the 1980s. Structured programming proved
to be a powerful tool that enable programmers to write
moderately complex programs fairly easily. However, as
programs grew larger, even the structured approach
failed to show the desired results in terms of bug-free,
easy-to-maintain and reusable programs.
2
INTRODUCTION CONT‟D


Object Oriented programming (OOP) is an approach
to program organization
and development which
attempts to eliminate some of the pitfalls of conventional
programming methods by incorporating the best of
structured programming features with several new
concepts. It is a new way of organizing and developing
programs and has nothing to do with any particular
language. However, not all languages are suitable to
implement the OOP concepts easily. Languages that
support OOP features include Smaltalk, Objective C,
C++ and Object Pascal. JAVA a pure OO language, is
one of the recent languages added to the list, the latest
one being C#.

3
INTRODUCTION CONT‟D
Object-Oriented Paradigm
 The major objective of object-oriented approach is
to eliminate some of the flaws encountered in the
procedural approach. OOP treats data as a critical
element in the program development ad does not
allow it to flow freely around the system. It ties data
more closely to the functions that operate on it and
protects it from unintentional modification by other
functions. OOP allows us to decompose a problem
into a number of entities called Objects and then
build data and functions (known as methods in
Java) around these entities. The combination of
data and methods make up an object.


4
INTRODUCTION CONT‟D


Object= Data+Methods

Method

Method

DATA
Method

Method

5
INTRODUCTION CONT‟D


Features of OO paradigm are:









Emphasis on data rather than procedure;
Programs are divided into Objects
Data structures are designed to characterize the objects
Methods operating on the data of an object are tied
together in the data structure
Data is hidden and cannot be accessed by external
functions
Objects may communicate through methods
New data and methods can be easily added when
necessary
Bottom-up approach in program design

6
INTRODUCTION CONT‟D


OO Programming 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 for
creating copies of such modules on demand.

7
INTRODUCTION CONT‟D



Basic Concepts of Object-Oriented Programming:
Objects and Classes:
Objects are the basic runtime 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 may handle. They
may represent also user- defined data types such as vectors
and lists. Objects should be chosen such that they match
closely with real world objects.
 When a program is executed, the objects interact by sending
messages to one another. For instance, „customer‟ and
„account‟ are two objects in banking program, then the customer
object may send a message to the account object requesting for
the balance. Each object contains data and code to manipulate
data. Objects can interact without having to know the details of
each other‟s data or code. The figure below shows a notation
that is popularly used to represent an object in object-oriented
analysis and design:


8
INTRODUCTION CONT‟D
Object

Person
Name

Data

Basic Pay
Salary()

Methods

Tax()

This is representation of an Object

9
INTRODUCTION CONT‟D



Basic Concepts of Object-Oriented Programming:
Objects and Classes:


The entire set of data and code of an abject can be made a
user-defined data type using the concept of a class. A class
may be thought of as a “data type” and an objet as a “variable”
of that data type. Once a class has been defined, someone can
create any number of objects belonging to that class. Each
object is associated with the data of type class with which they
are created. A class is thus a collection of objects of similar
type. For example, mango, apple and orange are members of
the class fruit. Classes are user-defined data types and behave
like the built-in types of a programming language. If fruit has
been defined as a class, then the statement fruit mango will
create an object mango belonging to the class fruit.
10
INTRODUCTION CONT‟D


Data Abstraction and Encapsulation:


The wrapping up of data and methods into a single
unit(called class) is known as encapsulation. Data
encapsulation is the most striking feature of a class. The
data is not accessible to the outside world and only those
methods, which are wrapped in the class, can access it.
These methods provide the interface between the object‟s
data and the program. This insulation of the data from
direct access by the program is called data hiding.
Encapsulation makes it possible for objects to be treated
like “black boxes” each performing a specific task without
any concern for internal implementation. See the figure
below:
11
INTRODUCTION CONT‟D

Information “in”

Data
and
Method

Information “out”

Encapsulation– Objects as “black boxes”

12
INTRODUCTION CONT‟D




Abstraction refers to the act of representing essential features
without including the background details or explanation. Classes
use the concept of abstraction and are defined as a list of abstract
attributes such as size, weight and cost, and methods that 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. Inheritance supports the
concept of hierarchical classification. For instance, the bird robin is a
part of the class flying bird, which is again a part of the class bird. In
the figure below, the principle behind this sort of division is that each
derived class shares common characteristics with the class from
which it is derived.
13
INTRODUCTION CONT‟D
Bird
Inheritance

Attributes:
Feathers
Lay eggs
Non flying
Bird

Flying Bird

Attributes:
-------------------------------

Attributes:
-----------------------------

Robin
Attributes:
-----------------------------

Swallow

Penguin

Attributes:
-----------------------------

Attributes:
-----------------------------

Kiwi
Attributes:
-----------------------------

14
INTRODUCTION CONT‟D


Polymorphism:


Polymorphism is another important OOP concept. It
means the ability to take more than one form. For
example, an operation may exhibit different behaviour in
different instances, The behaviour depends upon the
types of data used in he operation. For instance,
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 is something similar to a
particular word having several different meanings
depending on the context.
15
INTRODUCTION CONT‟D
Shape

Draw ( )

Circle Object

Box Object

Triangle Object

Draw (circle)

Draw (box)

Draw (triangle)

Polymorphism

16
INTRODUCTION CONT‟D


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 the call at
runtime. It is associated with polymorphism and
inheritance

17
INTRODUCTION CONT‟D


Benefits of OOP:











Through inheritance, it is possible to eliminate redundant code and
extend the use of existing classes;
Possibility of building programs from the standard working modules that
communicate with one another,
The principle of data hiding helps the programmer to build secure
programs that cannot be invaded by code in other parts of the program
It is possible to have multiple objects to coexist without any interference
It is possible to map objects in the problem domain to those objects in the
program
It is easy to partition he work in a project based on objects
The data-centered design approach enables us to capture more details of
model in an implementable
OO systems can be easily upgraded from small to large systems
Message passing techniques for communication between objects make
the interface descriptions with external systems much simpler
Software complexity can be easily managed

18
INTRODUCTION CONT‟D
Application of OOP:
 The promising areas for application of OOp
includes:













Real-time systems
Simulation and modeling
OO databases
Hypertext, hypermedia and expertext
AI and expert systems
Neural networks and parallel programming
Decision support and office automation systems
CIM/CAD/CAD system
19
INTRODUCTION CONT‟D


JAVA Features:














Compiled and Interpreted
Platform-independent and portable
Object Oriented
Robust and secure
Distributed
Simple, small and familiar
Multithreaded and interactive
High performance
Dynamic and extensible
Ease of development
Scalability and performance
Monitoring and manageability
Desktop client
20
OVERVIEW OF JAVA LANGUAGE


Java is a general-purpose, object-oriented
programming language. There are two types of java
programs:
Stand-alone applications
 Web applets


Stand-alone applications are program written in
Java to carry out certain tasks on a stand-alone
local computer. Java can be used to develop
programs for all kinds of applications, which earlier,
were developed using languages like C and C++
 Applets are small Java program developed


21
OVERVIEW OF JAVA LANGUAGE
Constants, Variables and Data Types
 Constants are fixed values that do not change
during the execution of the program. Java support
s several types of constants as shown in the figure
below:


22
OVERVIEW OF JAVA LANGUAGE
JAVA Constants

Numeric Constants

Integer
Constants

Real
Constants

JAVA Constants

Character Constants

Character
Constants

String
Constants

23
OVERVIEW OF JAVA LANGUAGE
Integer Constants: refer to a sequence of digits. There exist
decimal integer, octal integer and hexadecimal integer.
 Real Constants : Integer numbers are inadequate to
represent quantities that vary continuously such as distance,
heights, temperature, prices, etc. These quantities are
represented by numbers containing fractional parts like
17.548. Such numbers are called real (or floating point)
constant. 0.0083 -0.75 435.36
 Single Character constant: A single character constant
contains a single character enclosed within a pair of single
quote marks. „5‟ „X‟ „;‟ „ „
 String Constant: A string constant is a sequence of
characters enclosed between double quotes. “Hello Java”
“1997” “Well done”


24
OVERVIEW OF JAVA LANGUAGE


Variables: A variable is an identifier that denotes
a storage location to store a data value. Contrary to
the constants, a variable may take different values
at different times during the execution of the
program. A variable name can be chosen by the
programmer in a meaningful way so as to reflect
what it represents in the program. Eg. : average,
height


Variables are subjected to following conditions:
They must not begin with a digit
 Uppercase and lowercase are distinct. The variable Total is not
the same as total or TOTAL
 It should not be a keyword
 White space is not allowed
 Variable name can be of any length


25
OVERVIEW OF JAVA LANGUAGE


Data Types: Every variable in Java has a data
type. Data types specify the size and type of values
that can be stores. There are various categories of
data types in Java as shown in the following figure:

26
OVERVIEW OF JAVA LANGUAGE
DATA TYPES IN JAVA

Primitive (intrinsic)

Numeric

Integer

Non Primitive (Derived)

Non Numeric

Floating
point

Character

Boolean

Arrays

Classe
s

Interface

27
OVERVIEW OF JAVA LANGUAGE


Integer Types: Integer types can hold whole numbers
such as 1323, -96 and 5643. The size of the values that
can be stored depends on the integer data type we
choose. There exist :
Byte = 1 byte
 Short = 2 bytes
 Int = 4 bytes
 Long = 8 bytes




Floating Point Types: Floating point type is used to
hold numbers containing fractional parts such 20.56 and
-1.76. We have:
Float = 4 bytes
 Double = 8 bytes


28
OVERVIEW OF JAVA LANGUAGE
Character Type: Java provides a data type called char
of a size of 2 bytes but it can hold only a single
character.
 Boolean Type: It is used when we want to test a
particular condition during the execution
of the
program. It can take two values: true or false.
 Declaration of variables: Variables should be declared
to the compiler. Declaration does three things:


It tells the compiler what the variable name is
 It specifies what type of data the variable will hold
 The place of declaration decides the scope of the variable


29
OVERVIEW OF JAVA LANGUAGE


Some valid declaration are:
Int count;
 Float x,y;
 Double pi;
 Byte b;
 Char c1,c2,c3;




Giving values to variables: A variable must be
given a value after it has been declared but before
it is used in an expression. This is done in two
ways:
By using an assignment statement
 By using a read statement


30
OVERVIEW OF JAVA LANGUAGE
Assignment Statement:
 variableName = value


Initialvalue = 0;
 finalvalue = 100;
 Yes = „x‟;


It is also possible to assign a value to a variable at the
time of its declaration:
 type variableName = value


int finalValue = 100;
 Double total = 75.36;


31
OVERVIEW OF JAVA LANGUAGE
Using a read statement: values can be given to variables
through keyboard using the readLine() method as
illustrated below:
Import java.io.DataInputStream;
Class Reading
{
public static void main(String args[ ])
DataInputStream in= new DataInputStream(System.In);
int intNumber = 0;
float floatNumber = 0.0f;
Try
{
System.out.println(“Enter an Integre: “;


32
OVERVIEW OF JAVA LANGUAGE
intNumber = Integer.parseInt(in.readLine());
System.out.println(“Enter a float number: “);
floatNumber= Float.Value0f(in.readLine()).floatValue();
}
Catch (Exception e) { }
System.out.println(“ intNumber=“ + intNumber);
System.out.println(“floatNumber =“ + flaotNumber);
}
}

33
OVERVIEW OF JAVA LANGUAGE


Scope of variables: variables are classified into
Instance variables
 Class variables and
 Local variables


34
OPERATORS AND EXPRESSIONS
Operators
 An operator is a symbol that tells the computer to
perform
certain
mathematical
or
logical
manipulations. Java operators can be classified into
a number of related categories as below:




1.Arithmetic operators:

35
OPERATORS AND EXPRESSIONS
Operators

Meaning

+
*
/
%

Addition or unary plus

Substraction or unary minus

Multiplication

Division

Module division

36
OPERATORS AND EXPRESSIONS


2.Relational operators:

Operators

Meaning

<
<=
>
>=
==
!=

Is less than
Is less than or equal
Is greater than
Is greater than or equal to
Is equal to
Is not equal to

37
OPERATORS AND EXPRESSIONS


3.Logical operators:

Operators

Meaning

&&

Logical AND

II

Logical OR

!

Logical NOT
38
OPERATORS AND EXPRESSIONS
4.Assignment Operators: Assignment operators are
used to assign the value of an expression to a variable.
The operator is “=“
 5. Increment and decrement operators: The operator is
++ and –
 The operator ++ adds 1 to the operand while - - substracts
1
 6. Conditional Operator: ? is the ternary operator
available in Java, it is used to construct conditional
expression of the form exp1?exp2:exp3


39
OPERATORS AND EXPRESSIONS


7. Dot operator: (.) is used to access the entrance
variables and methods of class objects

Precedence of arithmetic operators
 A arithmetic expression without any parentheses will
be evaluated from left to right using the rules of
precedence of operators. There are two distinct
priority levels of arithmetic operators in java:


High priority: * / %
 Low priority: +


40
OPERATORS AND EXPRESSIONS
Java Statements
 The statements in java are like sentences in natural
languages
 A statement is an executable combination of
variables, operators, constants ending with semi
colon (;)


41
OPERATORS AND EXPRESSIONS
Statement
Empty Statement

Description
These do nothing and are used during program
development as a place holder

Labeled Statement

Any statement may begin with label. Labels in java
are used as the argument of jump statements

Expression Statement
Selection Statement

Combination of operators, constant of variables
These select one of several control flows. There 3
types of selection statement in Java: if, if-else; and
switch

Iteration Statement

They specify how and when looping will take place.
There are 3 types: while, do and for

Jump Statement

Jump statements pass control to the beginning or
end of the current block, or to a labeled statement.
The types are: break, continue, throw and return

Synchronization statement

These are used to handle issues with multithreading

Guarding statement

Guarding statements are used for safe handling of
code that may cause exception. The statement use
keywords: try, catch, finally

42
CLASS, OBJECT, METHOD DECLARATION


Classes, Objects and Methods:
Classes provide a convenient method for packing
together a group of logical data items and function that
work on them. In Java data items are called fields and
Functions are called Methods.
 Defining a class: the basic form of class declaration is:
 Class<classname>[extends<superclassname>]
{
[variable declaration;]
[methods declaration;]
}


43
CLASS, OBJECT, METHOD DECLARATION
Classes, Objects and Methods:
 Adding variables:


Data is encapsulated in a class by placing data fields
inside the body of the class definition. These variables
are called instance variables because they are created
whenever an object of the class is instantiated. We can
create instance variable as follows:
 Class Rectangle
{
Int length;
Int width;
}


44
CLASS, OBJECT, METHOD DECLARATION



Classes, Objects and Methods:
Adding Methods:
Methods are declared inside the body of the class but
immediately after the declaration of instance variables. The
general form of method declaration is:
 Type methodname (parameter –list)
{
Method body;
}
 Eg: void getdata (int x, int y)
{
length= x;
width= y;
}


45
CLASS, OBJECT, METHOD DECLARATION



Classes, Objects and Methods:
Creating Objects:
Object in Java is essentially a block of memory that contains
space to store all instance variables. Creating an object is
also referred as instantiating an object. Here is an a example
of creating an object of type of rectangle.:
 Rectangle rect1= new Rectangle();
 The new operator creates an object of the specified class and
returns a reference to that object.




Arrays:


An array is a group of contiguous or related data items that
share a common name. For instance, we can define an array
name salary to represent a set of salaries of group of
employees
46
ARRAYS


Arrays:
A particular value is indicated by writing a number called
index number or subscript in brackets after the array
name. For example salary[10] represents the salary of
10th employee. While the complex set of value is
referred to as an array, the individual values are called
elements. Arrays can be any variable type:
 One dimensional array: a list of items can be given one
variable name using only one subscript and such
variable is called a single subscripted variable or a one
dimensional array.
 For instance if we want to represent a set of five
numbers, say (35,40,20,27,19) by an array variable
number, then we can create the variable number as
follows:


47
ARRAYS


Arrays:
Int number[ ]= new int[5]
The values to the array elements can be assigned as
follows:
Number [0]=35;
Number[1]=40;
Number[2]=20;
Number[3]=27;
Number[4]=19;
 Creating an array:
 Creation of an array involves three steps: (1)declare an
array, (2)create memory location, (3) put values into
memory locations


48
ARRAYS


Arrays:










(1)Declaration of array: Arrays in Java may be declared
in two forms:
Form1: type arrayname[ ];
Form2: type[ ] arrayname;
Eg: int number[ ];
float average[ ];
int[ ] number;
float[ ] average;
(2) Creating memory locations: after declaring the array,
we need to create it in the memory as shown below:
Arrayname= new type[size];
49
ARRAYS


Arrays:








Eg : number= new int[5];
avergae=new float[10];
It is also possible to combine the two steps declaration
and creation into one as shown below:
Int number[ ]= new int[5];
(3)Putting values into memory locations: the final step is
to put values into the array created. This process is
known as initialization. This is done as shown below:
arrayname[subscript]=value;
Eg: number[0]=35;
number[1]=40;
number[4]=19;
50
ARRAYS


Arrays:
It is also possible to initialize arrays automatically in the
same way as the ordinary variables when they are
declared as follows:
 Type arrayname [ ]={list of values};
 Eg : int number[ ]={35,40,20,27,19};




Array length:




In Java, all arrays store the allocated size in a variable
named length. We can access the length of the array „a‟
using a.length
Eg. Int a size=a.length

51
ARRAYS


Strings:
Strings represent a sequence of characters, they may
be declared and created as follows:
String stringname;
stringname = new String(“ string”);
 Eg. String firstName;
firstName= new String(“John”)
 These 2 statements can be combined into one as
follows:
 String firstName=new String (“John”)
 Like arrays, it is also possible to get the length of string
using the „length‟ method of the string class.
int m= firstName.Length;


52
ARRAYS


Strings:
String Arrays:
 String itemArray[ ]= new String[3];
The above statement will create an array itemarray of size 3 to
hold the 3 string constants
 Multidimensional Arrays
 The array variables can store a list of values, but there will be
a situation where a table of values will have to be stored. For
that, two dimensional array can be created and used. For
creating two dimensional arrays, we must flow the same steps
as that of simple arrays.
 Eg. Int a[ ] [ ];
a=new int[3][4]; or
int a[ ] [ ]= new int[3][4];
 Theabove array declaration creates a table that can store 12
integer values, four across and three down.


53
ARRAYS


Strings:
Multidimensional Arrays
 Like one dimensional arrays, two dimensional arrays
may be initialized by following their declarations with a
list of initial values enclosed in braces.
 Eg. Int a[2][3]={0,0,0,1,1,1}; or
int a[ ][ ]= {{0,0,0},{1,1,1}};


54
RUNNING PROGRAMS
First Program:
class sample
{
public static void main (String[ ] args)
{
System.out.println("Welcome to JAVA Programming");
}
}
 Class declaration: the first line, class sample, declares a
class. Java is a true OO language, therefore, everything
must be placed into a class. Class is a key word and
declares that a new class definition follows.


55
RUNNING PROGRAMS
Opening brace: every class definition in Java logins with a
brace { and ends with a matching closing brace}
 The main line: the 3rd line, public static void main(String args[
]) defines a method named main. This is the starting point of
the interpreter to login execution of the program. A java
application can have any number of classes but only one of
them must include a main method to initiate the execution.
 Public: the key word public is access specifier that declares
the main method as unprotected and therefore it can be
accessible to all other classes
 Static: this declares the model as one that belongs to the
entire class and not the class. The main menu must always
be declared as static since the interpreter uses this method
before any objects are created


56
RUNNING PROGRAMS
Void: the type modifier void states that the main method
does not return any value. All parameters to a method
are declared inside a prior of parenthesis. Here String
args[ ] declares a parameter named args which contains
an array of objects of the class type string.
 The output line: the only executable statement in the
program is System.out.println(“Welcome to JAVA
Programming”). The println method is a member of out
objet, which is a static data member of System class.
The methods println always appends a new line
character to the end of the string, this is means that any
subsequent output will start on new line. Note the semicolon at the end of the statement. Every statement in
Java ends with a semi-colon.


57
RUNNING PROGRAMS


1.calculating the square root of a number
import java.lang.Math;
class SquareRoot
{
public static void main(String args[ ])
{
double x=5;
double y;
y=Math.sqrt(x);
System.out.println(“y=“+y);
}
}

58
RUNNING PROGRAMS
2.Displaying numbers as a triangle
class displaying
{
public static void main(String[ ] args)
{
System.out.println("Screen Display");
for(int i=1;i<=9;i++)
{
for(int j=1;j<=i;j++)
{
System.out.print(" ");
System.out.print(i);
}
System.out.print("n");
}
System.out.println("Screen Display Done");
}
}


59
RUNNING PROGRAMS


3.Area of a rectangle
class Rectangle
{
int length, width;
void getdata(int x,int y)
{
length=x;
width=y;
}
int rectArea()
{
int area=length*width;
return area;
}
}
class rectArea
{

60
RUNNING PROGRAMS
public static void main (String args[])
{
int area1, area2;
Rectangle rect1=new Rectangle();
Rectangle rect2=new Rectangle();
rect1.getdata(15,10);
area1=rect1.rectArea();
rect2.length=3;
rect2.width=5;
area2=rect2.length*rect2.width;
System.out.println("Area1="+area1);
System.out.println("Area2="+area2);
}
}

61
RUNNING PROGRAMS


4.Displaying marks
class MarkList
{ int studNo;
float Mark1,Mark2,Mark3;
char grade;
float total, average;
MarkList(int SNo,float M1,float M2,float M3)
{
studNo=SNo;
Mark1=M1;
Mark2=M2;
Mark3=M3;
}
void calculate()
{
total=Mark1+Mark2+Mark3;
average=total/3;
if((average>=90)&&(average<=100))
grade='A';
else if ((average>=70)&&(average<=89))

62
RUNNING PROGRAMS
grade='B';
else if((average>=50)&&(average<=69))
grade='C';
else
grade='D';
}
void display()
{
System.out.println("Student number="+studNo);
System.out.println("Subject1 mark="+Mark1);
System.out.println("subject2 mark="+Mark2);
System.out.println("subject3 mark="+Mark3);
System.out.println("Student Total="+total);
System.out.println("Student Average="+average);
System.out.println("Student Grade="+grade);
}
}
63
RUNNING PROGRAMS
class StudentMark
{
public static void main(String args[])
{
MarkList stud1=new MarkList(001,80,90,95);
stud1.calculate();
stud1.display();
MarkList stud2=new MarkList(002,70,50,40);
stud2.calculate();
stud2.display();
}
}
64
RUNNING PROGRAMS


5.Greatest of 3 numbers
class FindGreatest
{
Public static void main(String args[ ])
{
Int a,b,c;
a=12;
b=20;
c=10;
if(a>b)
if(a>c)
System.out.println(“ A is the Greatest”);
else
System.out.println(“C is the gretest”);
else
If(b>c)
System.out.println(“ B is the Greatest”);
else
System.out.println(“ C is the Greatest”);
}
}

65
RUNNING PROGRAMS


6. Inputs from keyboard
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
class Test
{
public static void main(String[ ] args) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter A String:");
String s = br.readLine();
System.out.print("Enter Integer:");
try
{
int i = Integer.parseInt(br.readLine());
}
catch(NumberFormatException nfe)
{
System.err.println("Invalid Format!");
}
}
}

66
EXCEPTION HANDLING


Exception: an exception is a condition that is caused
by a run-time error in the program. The purpose of the
exception handling mechanism is to provide a means
to detect and report on exceptional circumstance so
that appropriate action can be taken. The mechanism
suggests incorporation of a separate error handling
code that performs the following action:
Find the problem(Hit the exception)
 Inform that an error has occurred(Throw the exception)
 Receive the error information(Catch the exception)
 The corrective actions(Handle the exception)


67
EXCEPTION HANDLING
EXCEPTION TYPE

CAUSE OF ECXEPTION

Arithmetic Exception

Caused by math errors such as division by zero

Array index out of bounds exception

Caused by bad array indexes

Array store exception

Caused when a program tries to store the wrong
type of data in array

FileNotFound exception

Caused by an attempt to access or non existing
file

IO exception

Caused by general I/O failures, such inability to
read a file

Nullpointer exception

Caused by referencing a null object

Numberformat exception

Caused when a conversion between a string and
number fails

OutOfMemory exception

Caused when there is not enough memory to
allocate new object

Security exception

Caused when an applet tries to perform an
action not allowed by the browser‟s security
setting

StackOverflow exception

Caused when a system runs out of stack space

StringIndexOutof bounds exception

Caused when a system attempts to access a
non existing characters position in a string

68
EXCEPTION HANDLING
Java uses a keyword try to preface a block of code
that is likely to cause an error condition and “throw”
and exception
 A catch block defined by a keyword catch “catches”
the exception “thrown” by the try block and handles
it appropriately
 The catch block is immediately added after try block


69
RUNNING PROGRAMS


7. Exception handling

class Handling
{
public static void main(String args[ ] )
{
int a=10;
int b=5;
int c=5;
int x,y;
try
{
x=a/(b-c);
}
catch(ArithmeticException e)
{
System.out.println("Division by zero does not exist ");
}
}
}

70

Weitere ähnliche Inhalte

Was ist angesagt?

Core java complete ppt(note)
Core java  complete  ppt(note)Core java  complete  ppt(note)
Core java complete ppt(note)arvind pandey
 
Core java concepts
Core java  conceptsCore java  concepts
Core java conceptsRam132
 
Basics of JAVA programming
Basics of JAVA programmingBasics of JAVA programming
Basics of JAVA programmingElizabeth Thomas
 
Presentation on Core java
Presentation on Core javaPresentation on Core java
Presentation on Core javamahir jain
 
JRE , JDK and platform independent nature of JAVA
JRE , JDK and platform independent nature of JAVAJRE , JDK and platform independent nature of JAVA
JRE , JDK and platform independent nature of JAVAMehak Tawakley
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in javaTech_MX
 
JDBC: java DataBase connectivity
JDBC: java DataBase connectivityJDBC: java DataBase connectivity
JDBC: java DataBase connectivityTanmoy Barman
 
Java Tutorial For Beginners - Step By Step | Java Basics | Java Certification...
Java Tutorial For Beginners - Step By Step | Java Basics | Java Certification...Java Tutorial For Beginners - Step By Step | Java Basics | Java Certification...
Java Tutorial For Beginners - Step By Step | Java Basics | Java Certification...Edureka!
 
What Is Java | Java Tutorial | Java Programming | Learn Java | Edureka
What Is Java | Java Tutorial | Java Programming | Learn Java | EdurekaWhat Is Java | Java Tutorial | Java Programming | Learn Java | Edureka
What Is Java | Java Tutorial | Java Programming | Learn Java | EdurekaEdureka!
 
Data Types & Variables in JAVA
Data Types & Variables in JAVAData Types & Variables in JAVA
Data Types & Variables in JAVAAnkita Totala
 
Oops concepts || Object Oriented Programming Concepts in Java
Oops concepts || Object Oriented Programming Concepts in JavaOops concepts || Object Oriented Programming Concepts in Java
Oops concepts || Object Oriented Programming Concepts in JavaMadishetty Prathibha
 

Was ist angesagt? (20)

Core java complete ppt(note)
Core java  complete  ppt(note)Core java  complete  ppt(note)
Core java complete ppt(note)
 
JVM
JVMJVM
JVM
 
Core java concepts
Core java  conceptsCore java  concepts
Core java concepts
 
Basics of JAVA programming
Basics of JAVA programmingBasics of JAVA programming
Basics of JAVA programming
 
Presentation on Core java
Presentation on Core javaPresentation on Core java
Presentation on Core java
 
JRE , JDK and platform independent nature of JAVA
JRE , JDK and platform independent nature of JAVAJRE , JDK and platform independent nature of JAVA
JRE , JDK and platform independent nature of JAVA
 
Java
JavaJava
Java
 
Java tutorial PPT
Java tutorial PPTJava tutorial PPT
Java tutorial PPT
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to java
 
JDBC: java DataBase connectivity
JDBC: java DataBase connectivityJDBC: java DataBase connectivity
JDBC: java DataBase connectivity
 
Introduction of java
Introduction  of javaIntroduction  of java
Introduction of java
 
Features of java
Features of javaFeatures of java
Features of java
 
JDBC – Java Database Connectivity
JDBC – Java Database ConnectivityJDBC – Java Database Connectivity
JDBC – Java Database Connectivity
 
Java basic
Java basicJava basic
Java basic
 
Java Tutorial For Beginners - Step By Step | Java Basics | Java Certification...
Java Tutorial For Beginners - Step By Step | Java Basics | Java Certification...Java Tutorial For Beginners - Step By Step | Java Basics | Java Certification...
Java Tutorial For Beginners - Step By Step | Java Basics | Java Certification...
 
What Is Java | Java Tutorial | Java Programming | Learn Java | Edureka
What Is Java | Java Tutorial | Java Programming | Learn Java | EdurekaWhat Is Java | Java Tutorial | Java Programming | Learn Java | Edureka
What Is Java | Java Tutorial | Java Programming | Learn Java | Edureka
 
Data Types & Variables in JAVA
Data Types & Variables in JAVAData Types & Variables in JAVA
Data Types & Variables in JAVA
 
Oops concepts || Object Oriented Programming Concepts in Java
Oops concepts || Object Oriented Programming Concepts in JavaOops concepts || Object Oriented Programming Concepts in Java
Oops concepts || Object Oriented Programming Concepts in Java
 
Java interfaces
Java interfacesJava interfaces
Java interfaces
 

Ähnlich wie JAVA PROGRAMMING

Object Oriented Programming Lecture Notes
Object Oriented Programming Lecture NotesObject Oriented Programming Lecture Notes
Object Oriented Programming Lecture NotesFellowBuddy.com
 
1 intro
1 intro1 intro
1 introabha48
 
Introduction to object oriented language
Introduction to object oriented languageIntroduction to object oriented language
Introduction to object oriented languagefarhan amjad
 
Programming In C++
Programming In C++ Programming In C++
Programming In C++ shammi mehra
 
CPP_,module2_1.pptx
CPP_,module2_1.pptxCPP_,module2_1.pptx
CPP_,module2_1.pptxAbhilashTom4
 
Object Oriented Programming using C++.pptx
Object Oriented Programming using C++.pptxObject Oriented Programming using C++.pptx
Object Oriented Programming using C++.pptxparveen837153
 
C++Day-1 Introduction.ppt
C++Day-1 Introduction.pptC++Day-1 Introduction.ppt
C++Day-1 Introduction.pptcitizen15
 
programacion orientado a abjetos poo
programacion orientado a abjetos pooprogramacion orientado a abjetos poo
programacion orientado a abjetos pooRasec De La Cruz
 
Software_Engineering_Presentation (1).pptx
Software_Engineering_Presentation (1).pptxSoftware_Engineering_Presentation (1).pptx
Software_Engineering_Presentation (1).pptxArifaMehreen1
 

Ähnlich wie JAVA PROGRAMMING (20)

Object Oriented Programming Lecture Notes
Object Oriented Programming Lecture NotesObject Oriented Programming Lecture Notes
Object Oriented Programming Lecture Notes
 
OOPS_Unit_1
OOPS_Unit_1OOPS_Unit_1
OOPS_Unit_1
 
1 intro
1 intro1 intro
1 intro
 
chapter-6-oops.pdf
chapter-6-oops.pdfchapter-6-oops.pdf
chapter-6-oops.pdf
 
Introduction to object oriented language
Introduction to object oriented languageIntroduction to object oriented language
Introduction to object oriented language
 
Programming In C++
Programming In C++ Programming In C++
Programming In C++
 
OOP ppt.pdf
OOP ppt.pdfOOP ppt.pdf
OOP ppt.pdf
 
Object oriented concepts
Object oriented conceptsObject oriented concepts
Object oriented concepts
 
CPP_,module2_1.pptx
CPP_,module2_1.pptxCPP_,module2_1.pptx
CPP_,module2_1.pptx
 
Basic concept of OOP's
Basic concept of OOP'sBasic concept of OOP's
Basic concept of OOP's
 
Chapter1
Chapter1Chapter1
Chapter1
 
OOP.pptx
OOP.pptxOOP.pptx
OOP.pptx
 
Unit 1 OOSE
Unit 1 OOSE Unit 1 OOSE
Unit 1 OOSE
 
Unit 5.ppt
Unit 5.pptUnit 5.ppt
Unit 5.ppt
 
Object Oriented Programming using C++.pptx
Object Oriented Programming using C++.pptxObject Oriented Programming using C++.pptx
Object Oriented Programming using C++.pptx
 
C++Day-1 Introduction.ppt
C++Day-1 Introduction.pptC++Day-1 Introduction.ppt
C++Day-1 Introduction.ppt
 
programacion orientado a abjetos poo
programacion orientado a abjetos pooprogramacion orientado a abjetos poo
programacion orientado a abjetos poo
 
OOP-1.pptx
OOP-1.pptxOOP-1.pptx
OOP-1.pptx
 
Software_Engineering_Presentation (1).pptx
Software_Engineering_Presentation (1).pptxSoftware_Engineering_Presentation (1).pptx
Software_Engineering_Presentation (1).pptx
 
C++ & VISUAL C++
C++ & VISUAL C++ C++ & VISUAL C++
C++ & VISUAL C++
 

Mehr von Niyitegekabilly

Mehr von Niyitegekabilly (7)

Introduction to knowledge management
Introduction to knowledge managementIntroduction to knowledge management
Introduction to knowledge management
 
Data mining techniques and dss
Data mining techniques and dssData mining techniques and dss
Data mining techniques and dss
 
Data mining introduction
Data mining introductionData mining introduction
Data mining introduction
 
Data wirehouse
Data wirehouseData wirehouse
Data wirehouse
 
Introduction to knowledge management
Introduction to knowledge managementIntroduction to knowledge management
Introduction to knowledge management
 
JAVA PROGRAMMINGD
JAVA PROGRAMMINGDJAVA PROGRAMMINGD
JAVA PROGRAMMINGD
 
Birasa 1
Birasa 1Birasa 1
Birasa 1
 

Kürzlich hochgeladen

VoIP Service and Marketing using Odoo and Asterisk PBX
VoIP Service and Marketing using Odoo and Asterisk PBXVoIP Service and Marketing using Odoo and Asterisk PBX
VoIP Service and Marketing using Odoo and Asterisk PBXTarek Kalaji
 
Igniting Next Level Productivity with AI-Infused Data Integration Workflows
Igniting Next Level Productivity with AI-Infused Data Integration WorkflowsIgniting Next Level Productivity with AI-Infused Data Integration Workflows
Igniting Next Level Productivity with AI-Infused Data Integration WorkflowsSafe Software
 
Secure your environment with UiPath and CyberArk technologies - Session 1
Secure your environment with UiPath and CyberArk technologies - Session 1Secure your environment with UiPath and CyberArk technologies - Session 1
Secure your environment with UiPath and CyberArk technologies - Session 1DianaGray10
 
Nanopower In Semiconductor Industry.pdf
Nanopower  In Semiconductor Industry.pdfNanopower  In Semiconductor Industry.pdf
Nanopower In Semiconductor Industry.pdfPedro Manuel
 
activity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdf
activity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdf
activity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdfJamie (Taka) Wang
 
Valere | Digital Solutions & AI Transformation Portfolio | 2024
Valere | Digital Solutions & AI Transformation Portfolio | 2024Valere | Digital Solutions & AI Transformation Portfolio | 2024
Valere | Digital Solutions & AI Transformation Portfolio | 2024Alexander Turgeon
 
The Kubernetes Gateway API and its role in Cloud Native API Management
The Kubernetes Gateway API and its role in Cloud Native API ManagementThe Kubernetes Gateway API and its role in Cloud Native API Management
The Kubernetes Gateway API and its role in Cloud Native API ManagementNuwan Dias
 
Computer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and HazardsComputer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and HazardsSeth Reyes
 
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdfUiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdfDianaGray10
 
How Accurate are Carbon Emissions Projections?
How Accurate are Carbon Emissions Projections?How Accurate are Carbon Emissions Projections?
How Accurate are Carbon Emissions Projections?IES VE
 
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...Will Schroeder
 
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...Aggregage
 
Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)Commit University
 
Building Your Own AI Instance (TBLC AI )
Building Your Own AI Instance (TBLC AI )Building Your Own AI Instance (TBLC AI )
Building Your Own AI Instance (TBLC AI )Brian Pichman
 
9 Steps For Building Winning Founding Team
9 Steps For Building Winning Founding Team9 Steps For Building Winning Founding Team
9 Steps For Building Winning Founding TeamAdam Moalla
 
Artificial Intelligence & SEO Trends for 2024
Artificial Intelligence & SEO Trends for 2024Artificial Intelligence & SEO Trends for 2024
Artificial Intelligence & SEO Trends for 2024D Cloud Solutions
 
Cybersecurity Workshop #1.pptx
Cybersecurity Workshop #1.pptxCybersecurity Workshop #1.pptx
Cybersecurity Workshop #1.pptxGDSC PJATK
 
99.99% of Your Traces Are (Probably) Trash (SRECon NA 2024).pdf
99.99% of Your Traces  Are (Probably) Trash (SRECon NA 2024).pdf99.99% of Your Traces  Are (Probably) Trash (SRECon NA 2024).pdf
99.99% of Your Traces Are (Probably) Trash (SRECon NA 2024).pdfPaige Cruz
 
Machine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdfMachine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdfAijun Zhang
 
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPA
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPAAnypoint Code Builder , Google Pub sub connector and MuleSoft RPA
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPAshyamraj55
 

Kürzlich hochgeladen (20)

VoIP Service and Marketing using Odoo and Asterisk PBX
VoIP Service and Marketing using Odoo and Asterisk PBXVoIP Service and Marketing using Odoo and Asterisk PBX
VoIP Service and Marketing using Odoo and Asterisk PBX
 
Igniting Next Level Productivity with AI-Infused Data Integration Workflows
Igniting Next Level Productivity with AI-Infused Data Integration WorkflowsIgniting Next Level Productivity with AI-Infused Data Integration Workflows
Igniting Next Level Productivity with AI-Infused Data Integration Workflows
 
Secure your environment with UiPath and CyberArk technologies - Session 1
Secure your environment with UiPath and CyberArk technologies - Session 1Secure your environment with UiPath and CyberArk technologies - Session 1
Secure your environment with UiPath and CyberArk technologies - Session 1
 
Nanopower In Semiconductor Industry.pdf
Nanopower  In Semiconductor Industry.pdfNanopower  In Semiconductor Industry.pdf
Nanopower In Semiconductor Industry.pdf
 
activity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdf
activity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdf
activity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdf
 
Valere | Digital Solutions & AI Transformation Portfolio | 2024
Valere | Digital Solutions & AI Transformation Portfolio | 2024Valere | Digital Solutions & AI Transformation Portfolio | 2024
Valere | Digital Solutions & AI Transformation Portfolio | 2024
 
The Kubernetes Gateway API and its role in Cloud Native API Management
The Kubernetes Gateway API and its role in Cloud Native API ManagementThe Kubernetes Gateway API and its role in Cloud Native API Management
The Kubernetes Gateway API and its role in Cloud Native API Management
 
Computer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and HazardsComputer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and Hazards
 
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdfUiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
 
How Accurate are Carbon Emissions Projections?
How Accurate are Carbon Emissions Projections?How Accurate are Carbon Emissions Projections?
How Accurate are Carbon Emissions Projections?
 
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
 
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...
 
Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)
 
Building Your Own AI Instance (TBLC AI )
Building Your Own AI Instance (TBLC AI )Building Your Own AI Instance (TBLC AI )
Building Your Own AI Instance (TBLC AI )
 
9 Steps For Building Winning Founding Team
9 Steps For Building Winning Founding Team9 Steps For Building Winning Founding Team
9 Steps For Building Winning Founding Team
 
Artificial Intelligence & SEO Trends for 2024
Artificial Intelligence & SEO Trends for 2024Artificial Intelligence & SEO Trends for 2024
Artificial Intelligence & SEO Trends for 2024
 
Cybersecurity Workshop #1.pptx
Cybersecurity Workshop #1.pptxCybersecurity Workshop #1.pptx
Cybersecurity Workshop #1.pptx
 
99.99% of Your Traces Are (Probably) Trash (SRECon NA 2024).pdf
99.99% of Your Traces  Are (Probably) Trash (SRECon NA 2024).pdf99.99% of Your Traces  Are (Probably) Trash (SRECon NA 2024).pdf
99.99% of Your Traces Are (Probably) Trash (SRECon NA 2024).pdf
 
Machine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdfMachine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdf
 
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPA
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPAAnypoint Code Builder , Google Pub sub connector and MuleSoft RPA
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPA
 

JAVA PROGRAMMING

  • 1. BASICS OF JAVA PROGRAMMING Mugabe N. Gabriel 1
  • 2. 1. INTRODUCTION   Since the invention of the computer, many programming approaches have been tried. These include techniques such modular programming, topdown programming, bottom-up programming and structured programming. The primary motivation in each case has been the concern to handle the increasing complexity of programs that are reliable and maintainable. With the advent of languages such C, structured programming became very popular and was the paradigm of the 1980s. Structured programming proved to be a powerful tool that enable programmers to write moderately complex programs fairly easily. However, as programs grew larger, even the structured approach failed to show the desired results in terms of bug-free, easy-to-maintain and reusable programs. 2
  • 3. INTRODUCTION CONT‟D  Object Oriented programming (OOP) is an approach to program organization and development which attempts to eliminate some of the pitfalls of conventional programming methods by incorporating the best of structured programming features with several new concepts. It is a new way of organizing and developing programs and has nothing to do with any particular language. However, not all languages are suitable to implement the OOP concepts easily. Languages that support OOP features include Smaltalk, Objective C, C++ and Object Pascal. JAVA a pure OO language, is one of the recent languages added to the list, the latest one being C#. 3
  • 4. INTRODUCTION CONT‟D Object-Oriented Paradigm  The major objective of object-oriented approach is to eliminate some of the flaws encountered in the procedural approach. OOP treats data as a critical element in the program development ad does not allow it to flow freely around the system. It ties data more closely to the functions that operate on it and protects it from unintentional modification by other functions. OOP allows us to decompose a problem into a number of entities called Objects and then build data and functions (known as methods in Java) around these entities. The combination of data and methods make up an object.  4
  • 6. INTRODUCTION CONT‟D  Features of OO paradigm are:         Emphasis on data rather than procedure; Programs are divided into Objects Data structures are designed to characterize the objects Methods operating on the data of an object are tied together in the data structure Data is hidden and cannot be accessed by external functions Objects may communicate through methods New data and methods can be easily added when necessary Bottom-up approach in program design 6
  • 7. INTRODUCTION CONT‟D  OO Programming 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 for creating copies of such modules on demand. 7
  • 8. INTRODUCTION CONT‟D   Basic Concepts of Object-Oriented Programming: Objects and Classes: Objects are the basic runtime 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 may handle. They may represent also user- defined data types such as vectors and lists. Objects should be chosen such that they match closely with real world objects.  When a program is executed, the objects interact by sending messages to one another. For instance, „customer‟ and „account‟ are two objects in banking program, then the customer object may send a message to the account object requesting for the balance. Each object contains data and code to manipulate data. Objects can interact without having to know the details of each other‟s data or code. The figure below shows a notation that is popularly used to represent an object in object-oriented analysis and design:  8
  • 10. INTRODUCTION CONT‟D   Basic Concepts of Object-Oriented Programming: Objects and Classes:  The entire set of data and code of an abject can be made a user-defined data type using the concept of a class. A class may be thought of as a “data type” and an objet as a “variable” of that data type. Once a class has been defined, someone can create any number of objects belonging to that class. Each object is associated with the data of type class with which they are created. A class is thus a collection of objects of similar type. For example, mango, apple and orange are members of the class fruit. Classes are user-defined data types and behave like the built-in types of a programming language. If fruit has been defined as a class, then the statement fruit mango will create an object mango belonging to the class fruit. 10
  • 11. INTRODUCTION CONT‟D  Data Abstraction and Encapsulation:  The wrapping up of data and methods into a single unit(called class) is known as encapsulation. Data encapsulation is the most striking feature of a class. The data is not accessible to the outside world and only those methods, which are wrapped in the class, can access it. These methods provide the interface between the object‟s data and the program. This insulation of the data from direct access by the program is called data hiding. Encapsulation makes it possible for objects to be treated like “black boxes” each performing a specific task without any concern for internal implementation. See the figure below: 11
  • 12. INTRODUCTION CONT‟D Information “in” Data and Method Information “out” Encapsulation– Objects as “black boxes” 12
  • 13. INTRODUCTION CONT‟D   Abstraction refers to the act of representing essential features without including the background details or explanation. Classes use the concept of abstraction and are defined as a list of abstract attributes such as size, weight and cost, and methods that 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. Inheritance supports the concept of hierarchical classification. For instance, the bird robin is a part of the class flying bird, which is again a part of the class bird. In the figure below, the principle behind this sort of division is that each derived class shares common characteristics with the class from which it is derived. 13
  • 14. INTRODUCTION CONT‟D Bird Inheritance Attributes: Feathers Lay eggs Non flying Bird Flying Bird Attributes: ------------------------------- Attributes: ----------------------------- Robin Attributes: ----------------------------- Swallow Penguin Attributes: ----------------------------- Attributes: ----------------------------- Kiwi Attributes: ----------------------------- 14
  • 15. INTRODUCTION CONT‟D  Polymorphism:  Polymorphism is another important OOP concept. It means the ability to take more than one form. For example, an operation may exhibit different behaviour in different instances, The behaviour depends upon the types of data used in he operation. For instance, 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 is something similar to a particular word having several different meanings depending on the context. 15
  • 16. INTRODUCTION CONT‟D Shape Draw ( ) Circle Object Box Object Triangle Object Draw (circle) Draw (box) Draw (triangle) Polymorphism 16
  • 17. INTRODUCTION CONT‟D  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 the call at runtime. It is associated with polymorphism and inheritance 17
  • 18. INTRODUCTION CONT‟D  Benefits of OOP:           Through inheritance, it is possible to eliminate redundant code and extend the use of existing classes; Possibility of building programs from the standard working modules that communicate with one another, The principle of data hiding helps the programmer to build secure programs that cannot be invaded by code in other parts of the program It is possible to have multiple objects to coexist without any interference It is possible to map objects in the problem domain to those objects in the program It is easy to partition he work in a project based on objects The data-centered design approach enables us to capture more details of model in an implementable OO systems can be easily upgraded from small to large systems Message passing techniques for communication between objects make the interface descriptions with external systems much simpler Software complexity can be easily managed 18
  • 19. INTRODUCTION CONT‟D Application of OOP:  The promising areas for application of OOp includes:          Real-time systems Simulation and modeling OO databases Hypertext, hypermedia and expertext AI and expert systems Neural networks and parallel programming Decision support and office automation systems CIM/CAD/CAD system 19
  • 20. INTRODUCTION CONT‟D  JAVA Features:              Compiled and Interpreted Platform-independent and portable Object Oriented Robust and secure Distributed Simple, small and familiar Multithreaded and interactive High performance Dynamic and extensible Ease of development Scalability and performance Monitoring and manageability Desktop client 20
  • 21. OVERVIEW OF JAVA LANGUAGE  Java is a general-purpose, object-oriented programming language. There are two types of java programs: Stand-alone applications  Web applets  Stand-alone applications are program written in Java to carry out certain tasks on a stand-alone local computer. Java can be used to develop programs for all kinds of applications, which earlier, were developed using languages like C and C++  Applets are small Java program developed  21
  • 22. OVERVIEW OF JAVA LANGUAGE Constants, Variables and Data Types  Constants are fixed values that do not change during the execution of the program. Java support s several types of constants as shown in the figure below:  22
  • 23. OVERVIEW OF JAVA LANGUAGE JAVA Constants Numeric Constants Integer Constants Real Constants JAVA Constants Character Constants Character Constants String Constants 23
  • 24. OVERVIEW OF JAVA LANGUAGE Integer Constants: refer to a sequence of digits. There exist decimal integer, octal integer and hexadecimal integer.  Real Constants : Integer numbers are inadequate to represent quantities that vary continuously such as distance, heights, temperature, prices, etc. These quantities are represented by numbers containing fractional parts like 17.548. Such numbers are called real (or floating point) constant. 0.0083 -0.75 435.36  Single Character constant: A single character constant contains a single character enclosed within a pair of single quote marks. „5‟ „X‟ „;‟ „ „  String Constant: A string constant is a sequence of characters enclosed between double quotes. “Hello Java” “1997” “Well done”  24
  • 25. OVERVIEW OF JAVA LANGUAGE  Variables: A variable is an identifier that denotes a storage location to store a data value. Contrary to the constants, a variable may take different values at different times during the execution of the program. A variable name can be chosen by the programmer in a meaningful way so as to reflect what it represents in the program. Eg. : average, height  Variables are subjected to following conditions: They must not begin with a digit  Uppercase and lowercase are distinct. The variable Total is not the same as total or TOTAL  It should not be a keyword  White space is not allowed  Variable name can be of any length  25
  • 26. OVERVIEW OF JAVA LANGUAGE  Data Types: Every variable in Java has a data type. Data types specify the size and type of values that can be stores. There are various categories of data types in Java as shown in the following figure: 26
  • 27. OVERVIEW OF JAVA LANGUAGE DATA TYPES IN JAVA Primitive (intrinsic) Numeric Integer Non Primitive (Derived) Non Numeric Floating point Character Boolean Arrays Classe s Interface 27
  • 28. OVERVIEW OF JAVA LANGUAGE  Integer Types: Integer types can hold whole numbers such as 1323, -96 and 5643. The size of the values that can be stored depends on the integer data type we choose. There exist : Byte = 1 byte  Short = 2 bytes  Int = 4 bytes  Long = 8 bytes   Floating Point Types: Floating point type is used to hold numbers containing fractional parts such 20.56 and -1.76. We have: Float = 4 bytes  Double = 8 bytes  28
  • 29. OVERVIEW OF JAVA LANGUAGE Character Type: Java provides a data type called char of a size of 2 bytes but it can hold only a single character.  Boolean Type: It is used when we want to test a particular condition during the execution of the program. It can take two values: true or false.  Declaration of variables: Variables should be declared to the compiler. Declaration does three things:  It tells the compiler what the variable name is  It specifies what type of data the variable will hold  The place of declaration decides the scope of the variable  29
  • 30. OVERVIEW OF JAVA LANGUAGE  Some valid declaration are: Int count;  Float x,y;  Double pi;  Byte b;  Char c1,c2,c3;   Giving values to variables: A variable must be given a value after it has been declared but before it is used in an expression. This is done in two ways: By using an assignment statement  By using a read statement  30
  • 31. OVERVIEW OF JAVA LANGUAGE Assignment Statement:  variableName = value  Initialvalue = 0;  finalvalue = 100;  Yes = „x‟;  It is also possible to assign a value to a variable at the time of its declaration:  type variableName = value  int finalValue = 100;  Double total = 75.36;  31
  • 32. OVERVIEW OF JAVA LANGUAGE Using a read statement: values can be given to variables through keyboard using the readLine() method as illustrated below: Import java.io.DataInputStream; Class Reading { public static void main(String args[ ]) DataInputStream in= new DataInputStream(System.In); int intNumber = 0; float floatNumber = 0.0f; Try { System.out.println(“Enter an Integre: “;  32
  • 33. OVERVIEW OF JAVA LANGUAGE intNumber = Integer.parseInt(in.readLine()); System.out.println(“Enter a float number: “); floatNumber= Float.Value0f(in.readLine()).floatValue(); } Catch (Exception e) { } System.out.println(“ intNumber=“ + intNumber); System.out.println(“floatNumber =“ + flaotNumber); } } 33
  • 34. OVERVIEW OF JAVA LANGUAGE  Scope of variables: variables are classified into Instance variables  Class variables and  Local variables  34
  • 35. OPERATORS AND EXPRESSIONS Operators  An operator is a symbol that tells the computer to perform certain mathematical or logical manipulations. Java operators can be classified into a number of related categories as below:   1.Arithmetic operators: 35
  • 36. OPERATORS AND EXPRESSIONS Operators Meaning + * / % Addition or unary plus Substraction or unary minus Multiplication Division Module division 36
  • 37. OPERATORS AND EXPRESSIONS  2.Relational operators: Operators Meaning < <= > >= == != Is less than Is less than or equal Is greater than Is greater than or equal to Is equal to Is not equal to 37
  • 38. OPERATORS AND EXPRESSIONS  3.Logical operators: Operators Meaning && Logical AND II Logical OR ! Logical NOT 38
  • 39. OPERATORS AND EXPRESSIONS 4.Assignment Operators: Assignment operators are used to assign the value of an expression to a variable. The operator is “=“  5. Increment and decrement operators: The operator is ++ and –  The operator ++ adds 1 to the operand while - - substracts 1  6. Conditional Operator: ? is the ternary operator available in Java, it is used to construct conditional expression of the form exp1?exp2:exp3  39
  • 40. OPERATORS AND EXPRESSIONS  7. Dot operator: (.) is used to access the entrance variables and methods of class objects Precedence of arithmetic operators  A arithmetic expression without any parentheses will be evaluated from left to right using the rules of precedence of operators. There are two distinct priority levels of arithmetic operators in java:  High priority: * / %  Low priority: +  40
  • 41. OPERATORS AND EXPRESSIONS Java Statements  The statements in java are like sentences in natural languages  A statement is an executable combination of variables, operators, constants ending with semi colon (;)  41
  • 42. OPERATORS AND EXPRESSIONS Statement Empty Statement Description These do nothing and are used during program development as a place holder Labeled Statement Any statement may begin with label. Labels in java are used as the argument of jump statements Expression Statement Selection Statement Combination of operators, constant of variables These select one of several control flows. There 3 types of selection statement in Java: if, if-else; and switch Iteration Statement They specify how and when looping will take place. There are 3 types: while, do and for Jump Statement Jump statements pass control to the beginning or end of the current block, or to a labeled statement. The types are: break, continue, throw and return Synchronization statement These are used to handle issues with multithreading Guarding statement Guarding statements are used for safe handling of code that may cause exception. The statement use keywords: try, catch, finally 42
  • 43. CLASS, OBJECT, METHOD DECLARATION  Classes, Objects and Methods: Classes provide a convenient method for packing together a group of logical data items and function that work on them. In Java data items are called fields and Functions are called Methods.  Defining a class: the basic form of class declaration is:  Class<classname>[extends<superclassname>] { [variable declaration;] [methods declaration;] }  43
  • 44. CLASS, OBJECT, METHOD DECLARATION Classes, Objects and Methods:  Adding variables:  Data is encapsulated in a class by placing data fields inside the body of the class definition. These variables are called instance variables because they are created whenever an object of the class is instantiated. We can create instance variable as follows:  Class Rectangle { Int length; Int width; }  44
  • 45. CLASS, OBJECT, METHOD DECLARATION   Classes, Objects and Methods: Adding Methods: Methods are declared inside the body of the class but immediately after the declaration of instance variables. The general form of method declaration is:  Type methodname (parameter –list) { Method body; }  Eg: void getdata (int x, int y) { length= x; width= y; }  45
  • 46. CLASS, OBJECT, METHOD DECLARATION   Classes, Objects and Methods: Creating Objects: Object in Java is essentially a block of memory that contains space to store all instance variables. Creating an object is also referred as instantiating an object. Here is an a example of creating an object of type of rectangle.:  Rectangle rect1= new Rectangle();  The new operator creates an object of the specified class and returns a reference to that object.   Arrays:  An array is a group of contiguous or related data items that share a common name. For instance, we can define an array name salary to represent a set of salaries of group of employees 46
  • 47. ARRAYS  Arrays: A particular value is indicated by writing a number called index number or subscript in brackets after the array name. For example salary[10] represents the salary of 10th employee. While the complex set of value is referred to as an array, the individual values are called elements. Arrays can be any variable type:  One dimensional array: a list of items can be given one variable name using only one subscript and such variable is called a single subscripted variable or a one dimensional array.  For instance if we want to represent a set of five numbers, say (35,40,20,27,19) by an array variable number, then we can create the variable number as follows:  47
  • 48. ARRAYS  Arrays: Int number[ ]= new int[5] The values to the array elements can be assigned as follows: Number [0]=35; Number[1]=40; Number[2]=20; Number[3]=27; Number[4]=19;  Creating an array:  Creation of an array involves three steps: (1)declare an array, (2)create memory location, (3) put values into memory locations  48
  • 49. ARRAYS  Arrays:       (1)Declaration of array: Arrays in Java may be declared in two forms: Form1: type arrayname[ ]; Form2: type[ ] arrayname; Eg: int number[ ]; float average[ ]; int[ ] number; float[ ] average; (2) Creating memory locations: after declaring the array, we need to create it in the memory as shown below: Arrayname= new type[size]; 49
  • 50. ARRAYS  Arrays:      Eg : number= new int[5]; avergae=new float[10]; It is also possible to combine the two steps declaration and creation into one as shown below: Int number[ ]= new int[5]; (3)Putting values into memory locations: the final step is to put values into the array created. This process is known as initialization. This is done as shown below: arrayname[subscript]=value; Eg: number[0]=35; number[1]=40; number[4]=19; 50
  • 51. ARRAYS  Arrays: It is also possible to initialize arrays automatically in the same way as the ordinary variables when they are declared as follows:  Type arrayname [ ]={list of values};  Eg : int number[ ]={35,40,20,27,19};   Array length:   In Java, all arrays store the allocated size in a variable named length. We can access the length of the array „a‟ using a.length Eg. Int a size=a.length 51
  • 52. ARRAYS  Strings: Strings represent a sequence of characters, they may be declared and created as follows: String stringname; stringname = new String(“ string”);  Eg. String firstName; firstName= new String(“John”)  These 2 statements can be combined into one as follows:  String firstName=new String (“John”)  Like arrays, it is also possible to get the length of string using the „length‟ method of the string class. int m= firstName.Length;  52
  • 53. ARRAYS  Strings: String Arrays:  String itemArray[ ]= new String[3]; The above statement will create an array itemarray of size 3 to hold the 3 string constants  Multidimensional Arrays  The array variables can store a list of values, but there will be a situation where a table of values will have to be stored. For that, two dimensional array can be created and used. For creating two dimensional arrays, we must flow the same steps as that of simple arrays.  Eg. Int a[ ] [ ]; a=new int[3][4]; or int a[ ] [ ]= new int[3][4];  Theabove array declaration creates a table that can store 12 integer values, four across and three down.  53
  • 54. ARRAYS  Strings: Multidimensional Arrays  Like one dimensional arrays, two dimensional arrays may be initialized by following their declarations with a list of initial values enclosed in braces.  Eg. Int a[2][3]={0,0,0,1,1,1}; or int a[ ][ ]= {{0,0,0},{1,1,1}};  54
  • 55. RUNNING PROGRAMS First Program: class sample { public static void main (String[ ] args) { System.out.println("Welcome to JAVA Programming"); } }  Class declaration: the first line, class sample, declares a class. Java is a true OO language, therefore, everything must be placed into a class. Class is a key word and declares that a new class definition follows.  55
  • 56. RUNNING PROGRAMS Opening brace: every class definition in Java logins with a brace { and ends with a matching closing brace}  The main line: the 3rd line, public static void main(String args[ ]) defines a method named main. This is the starting point of the interpreter to login execution of the program. A java application can have any number of classes but only one of them must include a main method to initiate the execution.  Public: the key word public is access specifier that declares the main method as unprotected and therefore it can be accessible to all other classes  Static: this declares the model as one that belongs to the entire class and not the class. The main menu must always be declared as static since the interpreter uses this method before any objects are created  56
  • 57. RUNNING PROGRAMS Void: the type modifier void states that the main method does not return any value. All parameters to a method are declared inside a prior of parenthesis. Here String args[ ] declares a parameter named args which contains an array of objects of the class type string.  The output line: the only executable statement in the program is System.out.println(“Welcome to JAVA Programming”). The println method is a member of out objet, which is a static data member of System class. The methods println always appends a new line character to the end of the string, this is means that any subsequent output will start on new line. Note the semicolon at the end of the statement. Every statement in Java ends with a semi-colon.  57
  • 58. RUNNING PROGRAMS  1.calculating the square root of a number import java.lang.Math; class SquareRoot { public static void main(String args[ ]) { double x=5; double y; y=Math.sqrt(x); System.out.println(“y=“+y); } } 58
  • 59. RUNNING PROGRAMS 2.Displaying numbers as a triangle class displaying { public static void main(String[ ] args) { System.out.println("Screen Display"); for(int i=1;i<=9;i++) { for(int j=1;j<=i;j++) { System.out.print(" "); System.out.print(i); } System.out.print("n"); } System.out.println("Screen Display Done"); } }  59
  • 60. RUNNING PROGRAMS  3.Area of a rectangle class Rectangle { int length, width; void getdata(int x,int y) { length=x; width=y; } int rectArea() { int area=length*width; return area; } } class rectArea { 60
  • 61. RUNNING PROGRAMS public static void main (String args[]) { int area1, area2; Rectangle rect1=new Rectangle(); Rectangle rect2=new Rectangle(); rect1.getdata(15,10); area1=rect1.rectArea(); rect2.length=3; rect2.width=5; area2=rect2.length*rect2.width; System.out.println("Area1="+area1); System.out.println("Area2="+area2); } } 61
  • 62. RUNNING PROGRAMS  4.Displaying marks class MarkList { int studNo; float Mark1,Mark2,Mark3; char grade; float total, average; MarkList(int SNo,float M1,float M2,float M3) { studNo=SNo; Mark1=M1; Mark2=M2; Mark3=M3; } void calculate() { total=Mark1+Mark2+Mark3; average=total/3; if((average>=90)&&(average<=100)) grade='A'; else if ((average>=70)&&(average<=89)) 62
  • 63. RUNNING PROGRAMS grade='B'; else if((average>=50)&&(average<=69)) grade='C'; else grade='D'; } void display() { System.out.println("Student number="+studNo); System.out.println("Subject1 mark="+Mark1); System.out.println("subject2 mark="+Mark2); System.out.println("subject3 mark="+Mark3); System.out.println("Student Total="+total); System.out.println("Student Average="+average); System.out.println("Student Grade="+grade); } } 63
  • 64. RUNNING PROGRAMS class StudentMark { public static void main(String args[]) { MarkList stud1=new MarkList(001,80,90,95); stud1.calculate(); stud1.display(); MarkList stud2=new MarkList(002,70,50,40); stud2.calculate(); stud2.display(); } } 64
  • 65. RUNNING PROGRAMS  5.Greatest of 3 numbers class FindGreatest { Public static void main(String args[ ]) { Int a,b,c; a=12; b=20; c=10; if(a>b) if(a>c) System.out.println(“ A is the Greatest”); else System.out.println(“C is the gretest”); else If(b>c) System.out.println(“ B is the Greatest”); else System.out.println(“ C is the Greatest”); } } 65
  • 66. RUNNING PROGRAMS  6. Inputs from keyboard import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; class Test { public static void main(String[ ] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Enter A String:"); String s = br.readLine(); System.out.print("Enter Integer:"); try { int i = Integer.parseInt(br.readLine()); } catch(NumberFormatException nfe) { System.err.println("Invalid Format!"); } } } 66
  • 67. EXCEPTION HANDLING  Exception: an exception is a condition that is caused by a run-time error in the program. The purpose of the exception handling mechanism is to provide a means to detect and report on exceptional circumstance so that appropriate action can be taken. The mechanism suggests incorporation of a separate error handling code that performs the following action: Find the problem(Hit the exception)  Inform that an error has occurred(Throw the exception)  Receive the error information(Catch the exception)  The corrective actions(Handle the exception)  67
  • 68. EXCEPTION HANDLING EXCEPTION TYPE CAUSE OF ECXEPTION Arithmetic Exception Caused by math errors such as division by zero Array index out of bounds exception Caused by bad array indexes Array store exception Caused when a program tries to store the wrong type of data in array FileNotFound exception Caused by an attempt to access or non existing file IO exception Caused by general I/O failures, such inability to read a file Nullpointer exception Caused by referencing a null object Numberformat exception Caused when a conversion between a string and number fails OutOfMemory exception Caused when there is not enough memory to allocate new object Security exception Caused when an applet tries to perform an action not allowed by the browser‟s security setting StackOverflow exception Caused when a system runs out of stack space StringIndexOutof bounds exception Caused when a system attempts to access a non existing characters position in a string 68
  • 69. EXCEPTION HANDLING Java uses a keyword try to preface a block of code that is likely to cause an error condition and “throw” and exception  A catch block defined by a keyword catch “catches” the exception “thrown” by the try block and handles it appropriately  The catch block is immediately added after try block  69
  • 70. RUNNING PROGRAMS  7. Exception handling class Handling { public static void main(String args[ ] ) { int a=10; int b=5; int c=5; int x,y; try { x=a/(b-c); } catch(ArithmeticException e) { System.out.println("Division by zero does not exist "); } } } 70