java programming

70
BASICS OF JAVA PROGRAMMING Mugabe N. Gabriel 1

Upload: niyitegekabilly

Post on 12-May-2015

369 views

Category:

Technology


5 download

TRANSCRIPT

Page 1: JAVA PROGRAMMING

1

BASICS OF JAVA PROGRAMMING

Mugabe N. Gabriel

Page 2: JAVA PROGRAMMING

2

1. INTRODUCTION

Since the invention of the computer, many programming approaches have been tried. These include techniques such modular programming, top-down 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.

Page 3: JAVA PROGRAMMING

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#.

Page 4: JAVA PROGRAMMING

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.

Page 5: JAVA PROGRAMMING

5

INTRODUCTION CONT’D

Object= Data+Methods

DATA

Method Method

Method Method

Page 6: JAVA PROGRAMMING

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

Page 7: JAVA PROGRAMMING

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.

Page 8: JAVA PROGRAMMING

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:

Page 9: JAVA PROGRAMMING

9

INTRODUCTION CONT’D

Person

Name

Basic Pay

Salary()

Tax()

ObjectData

Methods

This is representation of an Object

Page 10: JAVA PROGRAMMING

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.

Page 11: JAVA PROGRAMMING

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:

Page 12: JAVA PROGRAMMING

12

INTRODUCTION CONT’D

Information “in” Information “out”

Data and

Method

Encapsulation– Objects as “black boxes”

Page 13: JAVA PROGRAMMING

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.

Page 14: JAVA PROGRAMMING

14

INTRODUCTION CONT’D

Bird

Attributes:FeathersLay eggs

Flying Bird

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

Non flying Bird

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

Robin

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

Swallow

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

Penguin

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

Kiwi

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

Inheritance

Page 15: JAVA PROGRAMMING

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.

Page 16: JAVA PROGRAMMING

16

INTRODUCTION CONT’D

Shape

Draw ( )

Circle Object

Draw (circle)

Triangle Object

Draw (triangle)

Box Object

Draw (box)

Polymorphism

Page 17: JAVA PROGRAMMING

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

Page 18: JAVA PROGRAMMING

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

Page 19: JAVA PROGRAMMING

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

Page 20: JAVA PROGRAMMING

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

Page 21: JAVA PROGRAMMING

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

Page 22: JAVA PROGRAMMING

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:

Page 23: JAVA PROGRAMMING

23

OVERVIEW OF JAVA LANGUAGE

JAVA Constants

Numeric Constants Character Constants

Integer Constants

Real Constants

Character Constants

StringConstants

JAVA Constants

Page 24: JAVA PROGRAMMING

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”

Page 25: JAVA PROGRAMMING

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

Page 26: JAVA PROGRAMMING

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:

Page 27: JAVA PROGRAMMING

27

OVERVIEW OF JAVA LANGUAGEDATA TYPES IN JAVA

Primitive (intrinsic) Non Primitive (Derived)

Numeric ArraysNon Numeric Classes

Integer Floating point

Character Boolean Interface

Page 28: JAVA PROGRAMMING

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

Page 29: JAVA PROGRAMMING

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

Page 30: JAVA PROGRAMMING

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

Page 31: JAVA PROGRAMMING

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;

Page 32: JAVA PROGRAMMING

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: “;

Page 33: JAVA PROGRAMMING

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);}}

Page 34: JAVA PROGRAMMING

34

OVERVIEW OF JAVA LANGUAGE

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

Page 35: JAVA PROGRAMMING

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:

Page 36: JAVA PROGRAMMING

36

OPERATORS AND EXPRESSIONSOperators Meaning

+ Addition or unary plus

- Substraction or unary minus

* Multiplication

/ Division

% Module division

Page 37: JAVA PROGRAMMING

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

Page 38: JAVA PROGRAMMING

38

OPERATORS AND EXPRESSIONS

3.Logical operators:

Operators Meaning

&& Logical AND

II Logical OR

! Logical NOT

Page 39: JAVA PROGRAMMING

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

Page 40: JAVA PROGRAMMING

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: +

Page 41: JAVA PROGRAMMING

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 (;)

Page 42: JAVA PROGRAMMING

42

OPERATORS AND EXPRESSIONSStatement Description

Empty Statement 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 Combination of operators, constant of variablesSelection Statement 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 multi-threading

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

Page 43: JAVA PROGRAMMING

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;]}

Page 44: JAVA PROGRAMMING

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;}

Page 45: JAVA PROGRAMMING

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; }

Page 46: JAVA PROGRAMMING

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

Page 47: JAVA PROGRAMMING

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:

Page 48: JAVA PROGRAMMING

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

Page 49: JAVA PROGRAMMING

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];

Page 50: JAVA PROGRAMMING

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;

Page 51: JAVA PROGRAMMING

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

Page 52: JAVA PROGRAMMING

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;

Page 53: JAVA PROGRAMMING

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.

Page 54: JAVA PROGRAMMING

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}};

Page 55: JAVA PROGRAMMING

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.

Page 56: JAVA PROGRAMMING

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

Page 57: JAVA PROGRAMMING

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 semi-colon at the end of the statement. Every statement in Java ends with a semi-colon.

Page 58: JAVA PROGRAMMING

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);}}

Page 59: JAVA PROGRAMMING

59

RUNNING PROGRAMS 2.Displaying numbers as a triangleclass 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");

}}

Page 60: JAVA PROGRAMMING

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{

Page 61: JAVA PROGRAMMING

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);

}}

Page 62: JAVA PROGRAMMING

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))

Page 63: JAVA PROGRAMMING

63

RUNNING PROGRAMSgrade='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);

}}

Page 64: JAVA PROGRAMMING

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();

}}

Page 65: JAVA PROGRAMMING

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”);elseSystem.out.println(“C is the gretest”);elseIf(b>c)System.out.println(“ B is the Greatest”);elseSystem.out.println(“ C is the Greatest”);}}

Page 66: JAVA PROGRAMMING

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!"); } }}

Page 67: JAVA PROGRAMMING

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)

Page 68: JAVA PROGRAMMING

68

EXCEPTION HANDLINGEXCEPTION 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

Page 69: JAVA PROGRAMMING

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

Page 70: JAVA PROGRAMMING

70

RUNNING PROGRAMS

7. Exception handlingclass 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 ");}

}}