Click here to load reader

Lecture # 5 Methods and Classes. What is a Method 2 A method is a set of code which is referred to by name and can be called (invoked) at any point in

Embed Size (px)

Citation preview

Introduction

Continue4Each method has its own name. When that name is encountered in a program, the execution of the program branches to the body of that method. When the method is finished, execution returns to the area of the program code from which it was called, and the program continues on to the next line of code.

Methods6There are two basic types of methods: Built-in: Build-in methods are part of the compiler package, such as System.out.println( ) and System.exit(0).

User-defined: User-defined methods are created by you, the programmer. These methods take-on names that you assign to them and perform tasks that you create.

Built-in Methods7Java Provides some Method for common mathematical calculations e.g.Calculate the square root of 900.0:Math.sqrt( 900.0 )Method sqrt belongs to class MathDot (.) allows access to method sqrtThe argument 900.0 is located inside parenthesesClassMethod which belongs to class MathThis always performs actions. Parameters or data passed to method to perform an actionAdvantageBreak large programs into a series of smaller modulesHelps manage complexityMakes it easier to build large programsMakes it easier to debug programsMost of the time, you need to know what a function does, but not how it actually does it.You use other peoples code without knowing how it does its job.

8

Some Built-in Math Functions Method Declarations (cont.)9General format of method declaration:

modifiers return-value-type method-name( parameter1, , parameterN ){ declarations and statements}Method can also return values:Methods Declarations10Parameters or argumentsValues that is to be passed into the Method, or the value on which the function will operate. It may be a int, float, char or String.Returned ValueThe value which is returned by the Method after applying the code on it. It may be a int, float, char or String.Local variablesDeclared and used in method declaration (its scope is the method only)

ProgramImport Java.util.Scanner;Class Square{public static void main(String arg[]){Scanner input = new Scanner(System.in);int val;val=input.nextInt();int res;res= findSqr(val);System.out.println(Square = + res);}public static int findSqr( int x){return x*x;}} ProgramImport Java.util.ScannerClass Square{public static void main(String arg[]){Scanner input = new Scanner(System.in);int val;val=input.nextInt();int res;res= findSqr(val);System.out.println(Square = + res);}public static int findSqr( int x){return x*x;}} Function NameReturn typeParameters13Classes and Objects in JavaBasics of Classes in Java14IntroductionJava is a true OO language and therefore the underlying structure of all Java programs is classes.Anything we wish to represent in Java must be encapsulated in a class that defines the state and behaviour of the basic program components known as objects.Classes create objects and objects use methods to communicate between them. They provide a convenient method for packaging a group of logically related data items and functions that work on them.15ClassesA class is a collection of fields (data) and methods (procedure or function) that operate on that data. Circlecentreradius

circumference()area()

16ClassesA class is a collection of fields (data) and methods (procedure or function) that operate on that data.The basic syntax for a class definition:

Bare bone class no fields, no methods

public class Circle { // my circle class}class ClassName [extends SuperClassName]{ [fields declaration] [methods declaration]}17Adding Fields: Class Circle with fieldsAdd fields

The fields (data) are also called the instance varaibles.

public class Circle { public double x, y; // centre coordinate public double r; // radius of the circle

}18Adding MethodsA class with only data fields has no life. Objects created by such a class cannot respond to any messages.Methods are declared inside the body of the class but immediately after the declaration of data fields.The general form of a method declaration is:type MethodName (parameter-list){Method-body;}19Adding Methods to Class Circlepublic class Circle {

public double x, y; // centre of the circle public double r; // radius of circle

//Methods to return circumference and area public double circumference() { return 2*3.14*r; } public double area() { return 3.14 * r * r; }}Method Body20Object DeclarationObjects are the existence of class in memory, members of class is accessed through the object of a class.

Can define variables (objects) of that type:

Circle aCircle;Circle bCircle;21Class of Circle cont.aCircle, bCircle simply refers to a Circle object, not an object itself. aCirclePoints to nothing (Null Reference)bCirclePoints to nothing (Null Reference)nullnull22Creating objects of a classObjects are created dynamically using the new keyword.aCircle and bCircle refer to Circle objects

bCircle = new Circle() ;aCircle = new Circle() ;23Creating objects of a classaCircle = new Circle();bCircle = new Circle() ;

bCircle = aCircle;24Creating objects of a classaCircle = new Circle();bCircle = new Circle() ;

bCircle = aCircle;PaCircleQbCircleBefore AssignmentPaCircleQbCircleBefore Assignment25Automatic garbage collectionThe object does not have a reference and cannot be used in future.

The object becomes a candidate for automatic garbage collection.

Java automatically collects garbage periodically and releases the memory used to be used in the future.

Q26Accessing Object/Circle DataSimilar to C syntax for accessing data defined in a structure.

Circle aCircle = new Circle();

aCircle.x = 2.0 // initialize center and radiusaCircle.y = 2.0aCircle.r = 1.0ObjectName.VariableNameObjectName.MethodName(parameter-list)

27Executing Methods in Object/CircleUsing Object Methods:Circle aCircle = new Circle();

double area; aCircle.r = 1.0;area = aCircle.area();sent message to aCircle28Using Circle Class// Circle.java: Contains both Circle class and its user class//Add Circle class code hereclass MyMain{ public static void main(String args[]) { Circle aCircle; // creating reference aCircle = new Circle(); // creating object aCircle.x = 10; // assigning value to data field aCircle.y = 20; aCircle.r = 5; double area = aCircle.area(); // invoking method double circumf = aCircle.circumference(); System.out.println("Radius="+aCircle.r+" Area="+area); System.out.println("Radius="+aCircle.r+" Circumference ="+circumf); }}[raj@mundroo]%: java MyMain Radius=5.0 Area=78.5Radius=5.0 Circumference =31.400000000000002MethodDescriptionExample

abs( x )absolute value of x (this method also has float, int and long versions)abs( 23.7 ) is 23.7

abs( 0.0 ) is 0.0

abs( -23.7 ) is 23.7

ceil( x )rounds x to the smallest integer not lessthan xceil( 9.2 ) is 10.0

ceil( -9.8 ) is -9.0

cos( x )trigonometric cosine of x (x is in radians)cos( 0.0 ) is 1.0

exp( x )exponential method exexp( 1.0 ) is 2.71828

exp( 2.0 ) is 7.38906

floor( x )rounds x to the largest integer not greater than xfloor( 9.2 ) is 9.0

floor( -9.8 ) is -10.0

log( x )natural logarithm of x (base e)log( Math.E ) is 1.0

log( Math.E * Math.E ) is 2.0

max( x, y )larger value of x and y (this method also has float, int and long versions)max( 2.3, 12.7 ) is 12.7

max( -2.3, -12.7 ) is -2.3

min( x, y )smaller value of x and y (this method also has float, int and long versions)min( 2.3, 12.7 ) is 2.3

min( -2.3, -12.7 ) is -12.7

pow( x, y )x raised to the power y (xy)pow( 2.0, 7.0 ) is 128.0

pow( 9.0, 0.5 ) is 3.0

sin( x )trigonometric sine of x (x is in radians)sin( 0.0 ) is 0.0

sqrt( x )square root of xsqrt( 900.0 ) is 30.0

sqrt( 9.0 ) is 3.0

tan( x ) trigonometric tangent of x (x is in radians)tan( 0.0 ) is 0.0

Math-class methods.