Trending ▼   ResFinder  

ICSE Notes 2016 based on functions : Computer Applications (Christ Academy ICSE School, Bangalore)

8 pages, 0 questions, 0 questions with responses, 0 total responses,    0    0
Machha
Christ Academy ICSE School, Bangalore
+Fave Message
 Home > anagha_charly >   F Also featured on: School Page

Formatting page ...

Function/Method & Function Overloading A function is a named portion of code within a larger program which performs a specific task. It is a sequence of some declaration statements and executable statements. Functions are also known as methods, procedure, subprograms or subroutines. Classification Of Functions Based On Availability Predifined functions - Functions which are available within Java package and can be used by importing the required package. Example: Math class provides predefined functions like pow(),sqrt() etc. Userdefined functions - Functions defined by the programmer within the program used for particular tasks. Following is the syntax to define a function/method: <Access Specifier><Return Type><function name>(list of parameters) { Body of the function return statement } where, Access Specifiers can be public, private or protected. Depending upon the nature of the function any one is used. Return type specifies the type of data retuned by the function. Return type is int if the function returns an int value, float if the function returns a floating point value and so on. Function name specifies the name of the function which is related to the process being done in it. Parameter lists are the variables receiving the values passed from the arguments. It is a sequence of type and identifier pairs separated by commas. Though this is the common method of writing a function, a function definition need not contain arguments always. Similarly, all functions need not return a value. If a function does not return a value, its return type is void. Classification of functions based on return type and arguments: 1.Function which does not have an argument or 2.Function which has an argument but no a return type: While defining ,such a function return type: The function may have single or multiple arguments and return type is void. does not have an argument and the return type is Example: void as the function only performs activities like void add2(int a,int b) computation and printing. { Example: int c=a+b; void add1() { int a=10; int b=20; int c=a+b; System.out.println( Sum = +c); } 3.Function with a return type but no argument: The function which returns a value using the return keyword. The return type of the function while defining the function depends on the type of data the function is returning. It can be int, short, System.out.print(c); } 4.Functions which have both argument and return type: Example: int add2(int a,intb) { int c=a+b; return c; 1 byte etc. } Example: int add3() { return 5; } Note: here, the function definition has two arguments of int types and the function returns int value after addition. Function prototype/ signature: A function prototype is the first line of the function definition that tells the program about the type of the value returned by the function and the number and the type of arguments. Access specifiers: public - public classes, methods and fields can be accessed from everywhere. protected - protected methods and fields can only be accessed within the same class , within its subclasses, and within classes of the same package, but not from anywhere else. private - private methods and fields can only be accessed within the same class. private methods and fields are not visible within subclasses and are not inherited by subclasses. default If there is no access specifier mentioned, it is taken as default access. Methods with default access can be accessed by classes or subclasses which exist in the same package and from nowhere else. Advantages of using functions Functions reduce the complexity of programs. Functions reduce duplication of code, enable reuse of code across multiple programs Functions improve readability and maintainability of code. Functions hide implementation details. Functions make debugging easy: it becomes easier to find and rectify an error in a small module of the program rather than the entire complex program. Invoking a function: The process of using a method in a program is called calling a method or invoking the method. Invoking a method is illustrated below: public class Sum { public static int add(int p,int q) { int r=p+q; return r; } public static void main(String[] args) throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.println( Enter two numbers ); int a=Integer.parseInt(br.readLine()); int b=Integer.parseInt(br.readLine()); int res=add(a,b);//invoking add(int,int) function System.out.println( The sum of two numbers is : +res); } } working: In the main, when the function call statement is executed, the values of variables a and b are copied to variables p and q. The function is executed. The value of r is calculated and returned from the function. While returning from the function, the control comes back to the point where the function was called and the value returned from the function is assigned the variable res. Let us assume that a = 2 and b = 3. Then, the function call statement would look like this: int res=add(2, 3); 2 The value 2 is copied into variable p and 3 into q. int r=p+q; r=2+3=5 return r return 5 Control comes back to the point from where the function was called int res=add(2,3) res=5 Here, a and b are the actual parameters. They are used in the function call statement. p and q are called the formal parameters. They are used in the function definition. The values of actual parameters are copied to them and the function works with those copies. The above example is also an example of call by value/ Pass by value method of calling a function. Here, since the method add( ) is static, we need not create an object of the class to call it from static main( ). When the function is non-static, the function call would look like below: class Xyz { void add(int x,int y) { System.out.println(x+y); } } Here,the function add() while defining makes use of two parameters int x,int y so they are formal parameters. class P29 { public static void main() { int p=3,q=4; Xyz obj=new Xyz(); obj.add(p,q); } } Here, p and q are the actual parameters Actual vs. Formal parameters: Actual parameters The parameters of the method when the method is called are called actual parameters. Formal parameters The parameters of the method when the method is actually defined are called formal parameters. They are not preceded by datatype. They are preceded by datatype Call by Value vs. Call by Reference: Call by Value / Pass by Value Call by Reference / Pass by Reference In this method, Formal parameter receives copy of In call by reference, The actual parameters for the data from the actual parameter. function i.e. the objects of given class type are passed as parameters. The working is done on the formal parameter. Any Formal parameter just refers to the actual parameter change in the formal parameter does not effect or i.e. the memory location of the actual change the actual parameter s value parameter. Any change in formal parameter affects the state of the object passed as actual parameter. Normally used when you don t want any change to Normally used when you want to change the state of be made in the original data. Changes made in the object formal parameter do not affect the actual parameter. The actual parameters passed are of primitive type. The actual parameters are of non-primitive type(eg: objects, arrays, String object). Example Example public class pbyval { public void change (int b) { b=b*b; } public static void main() { public class pbyref { public void change (int x[]) { for(int i=0; i<4; i++) x[i]=x[i]*x[i]; } public static void main() 3 int a=10; change(a); system.out.print(a); } } Output: 10 { int a[]={2,3,4,5}; change(a); for (int i=0; i<4; i++) system.out.print(a[i]); } } Output: 4, 9, 16, 25 Return from a Function/Method: A function/method returns to the code that invoked it when it completes all the statements in the method or reaches a return statement, or throws an exception. Even if several return statements are used in a programme, only one will be executed. You declare a function s/method's return type in its function/method declaration. Within the body of the method, you use the return statement to return the value. Any method declared void doesn't return a value. It does not need to contain a return statement, but it may do so. In such a case, a return statement can be used to branch out of a control flow block and exit the method and is simply used like this: return; If you try to return a value from a method that is declared void, you will get a compiler error. Any method that is not declared void must contain a return statement with a corresponding return value, like this: return returnValue; . The data type of the return value must match the method's declared return type; you can't return an integer value from a method declared to return a boolean. main() function main( ) function is a special function which is defined by user and is invoked by default when the program is executed ie. it is the place where execution of any application starts. Therefore, main( ) function is called driver function. Any standalone application must contain a main( ) in order to make it executable. The object creation and invoking of member methods happen inside the main( ) function. Types of functions Pure function Impure function Pure function: Functions that do not change the state of their parameters are known as pure functions For example: class operate { int sqr(int x) { return (x*x) } } Impure function: Functions that modify the state of their parameters are known as impure functions. For example: class abc { int a,b,c; abc(int m) { a=m;b=0;c=0; } void seta() { b+=a; } 4 void setc() { c+=a; System.out.println( value of c +c); } } Setter/Mutator Method: In a Java class, in order to implement data abstraction, the data members should be of private access and member functions should be of public access. The private data members cannot be accessed from anywhere else other than the class containing it. Then, if you want to modify the value of the data member from another class, it is done using setter method. A setter method is a method that sets/ changes the value of a data member of a class. Mostly, setter methods are provided for private members as they are not accessible from other classes. They have the return type void. Example: A setter method for instance variable marks can be written as: public void setMarks(double newMarks){ marks=newMarks; //sets/changes the value of marks } Getter/Accessor method: An accessor or getter method is a method that returns the value of a data member of the class. Mostly, accessor methods are provided for private members. Example: A getter method for instance variable marks can be written as: public double getMarks(){ return(marks); //returns the value of marks } Recursive function: A function which calls itself from its body is known as recursive method. E.g., public int fact(int n) { if (n==0) return (1); else return(n*fact(n-1)); } Function overloading: Function overloading is a process of defining a number of functions with the same function name but with difference in its signature, i.e., difference in types or number of parameters. E.g., public int add(int a, int b) { ----------------} public int add(int a, int b, int c) { ----------------} public float add(float a, float b) { ----------------} In Java, Methood Overloading is not possible by changing only the return type of the method. Need for function overloading: If we have to perform only one operation, having same name of the methods increases the readability of the program. 5 Suppose you have to perform addition of the given numbers, if you write the method such as a(int,int) for adding two numbers, and b(int,int,int) for adding three numbers then, it may be difficult for you as well as other programmers to understand the behaviour of the method because its name differs. Instead, if we name both the functions as add(int, int) and add(int, int, int) it is easier to understand that both functions perform addition of numbers. Advantage of function overloading: Function overloading increases the readability of the program. Constructor function: Constructor is a special method of a class with the same name as that of the class. It is used to initialize each instance of a class. It does not have any return type (not even void). During object creation, the constructor of the class is invoked. Constructors can be overloaded; you can have multiple constructor functions, each with different numbers and/or types of arguments. Default constructor/no-argument constructor: This is a simple constructor which does not have any arguments. This can be written by the programmer. But, if the programmer doesn't write any constructor in a class also, default (no-argument) constructor (that doesn't do anything) will be automatically supplied by Java. class Abc { int a; Abc( )//default constructor-user defined { a=0;//initializing data members to default values } } Parameterized constructor: It is a constructor that takes one or more arguments. It initializes data members to specific values. class Abc { int a; Abc( )//default constructor { a=0;//initializing data members to default values } Abc(int val )//parameterized constructor { a=val;//initializing data members to specific values } } Note: If you don't initialize a field (i.e., either you don't write any constructor function, or your constructor function just doesn't assign a value to that field), the field will be given a default value, depending on its type. class Abc { int a; } In the above example, though the user has not given any constructor, java automatically provides it with a default constructor and initializes the data member with default value ie.,0. Instance variable and Static variables/Methods: In Java, each object created will have its own copy of the data members/instance variables. But, if a field(data member) is declared static, there exists only one copy of that member, which will be shared by all the instances of the class. For eg, let us assume a class declaration as below: 6 class A{ int a; static int count = 0; } Let s assume that 10 instances of the above class have been created. Let the names be obj1, obj2..obj10. Each of these objects have their own copies of data member a which can be accessed using the syntax: object_name.instance_variable_name ie. obj1 s copy of a can be accessed by obj1.a. Similarly, for other objects. Here, the data member a is called an instance variable as there are copies of it instance wise. Whereas, the other field count is declared static. Irrespective of the number of instances of the class, there exists only one copy of count which will be shared by all instances. A public static field or method can be accessed from outside the class using the notation: using the class name instead of the name of the class object: class-name.static_field-or-method-name as in A.count. though, the following notation is also not wrong: class-object.static_field-or-method-name But, the preferred way to access a static field or a static method is using the class name (not using a class object). Because, memory for static members is created before the object is created. A method should be made static when it does not access any of the non-static fields of the class, and does not call any non-static methods. (In fact, a static method can access non-static fields or call non-static methods only with the help of object.) Instance variable VS Static variable: Instance variable Each object of the class has its own copy of the instance variable. Any change made in the value reflects only in that particular object for which the variable belongs to. memory for instance variables are created when the object is created Accessed using the format: object_name.instance_variable_name Static variable There exists only one copy of the static member which is shared by all instances of the class. Any change made in the value reflects in all objects. memory for static members is created before the object is created Accessed using the format: class-name.field-or-method-name this keyword: It may sometimes be required that a function refers to the object that invoked it. For this, Java defines the this keyword. this can be used inside any method to refer to the current object. public Box(double w, double h) { this.width=w; this.height=h; } 7 Another context where this keyword is used is when local variable hides the instance variables. For example, class Box{ double width; double height; public Box(double width, double height) { this.width=w; this.height=h; } } 8

Formatting page ...

Related ResPapers
ICSE Notes 2018
by manumansi 
ICSE Notes of all important string programs 2018 : Computer Applications (St. Francis School (SFS), Madhurawada, Visakhapatnam)
by alladee3 
ICSE Class X 2014 : Computer Applications : ICSE 2014 board provided solutions
by akarshjain 
ICSE Class X Notes 2020 : Computer Applications (Java Notes)
by ayush_7781 

Formatting page ...

Formatting page ...

Formatting page ...

Formatting page ...

Formatting page ...

Formatting page ...

 

  Print intermediate debugging step

Show debugging info


 

 


© 2010 - 2025 ResPaper. Terms of ServiceContact Us Advertise with us

 

anagha_charly chat