Thursday, 28 July 2016

Class X - Methods

Its not ROCKET  SCIENCE.....

Its just COMPUTER SCIENCE .....



METHODS
When our program is too complicated, the best approach is to divide it into smaller sections, so that it is easy to write the code and also easy to debug.
If we want to use  a set of statements in more than one place, instead of writing the same code  again and again,we can write it once and call it wherever we need it.
For instance
*******************************************************
WELCOME TO MY BLOG
*******************************************************
Class X Notes.

*******************************************************
class example1
{
    public static void main( )
       {
          System.out.println("******************************");
          System.out.println("WELCOME TO MY BLOG");
          System.out.println("******************************");
          System.out.println("Class X Notes");
              System.out.println("****************************");
      }
}
In the above program the highlighted lines are repeated 3 times. We can reduce the code by writing once and calling it 3 times.
class example1
{
    public static void main( )
       {           
                    star( );
                    System.out.println("WELCOME TO MY BLOG");
                    star( );
                    star( );
                 }
public static void star ( )
     {
                Sytem.out.println("****************************");
      }
}
Method Header
access_specifier  modifier  return data_type method name( )e.g :
 public static void main() 
 

NOTE
  • The other name for method is FUNCTION
  • A method can be easily identified .A method name is always followed by the opening and closing parentheses ( ).
  • A method name must begin with a letter or an underscore, it also can contain letters, numbers and underscore.
  • Access specifier and modifier are optional.
  • main( )  method can be written anywhere in the program.
Function header or prototype
The first line of the method with the name of the method,data type of the return value, number and the type of arguments is called the header or prototype.
Function Signature
It is the number and types of arguments.
1. Example
Write a program to add two numbers .
class addition{
public static void main( )
  {
     int a=10,b=45; --------------------------------------------1
     int s= add(a,b); -------------------------------------2,6     System.out .print("Sum = "+s);-----------------------7
}
 int add(int a,int b)----------------------------------------3
  {      int c;
       c=a+b;-----------------------------------------------4
       return  c; --------------------------------------------5  
  }
}
In the above program , the numbers are the order in which the program will be executed. In the step 2, add( ) is the method name,this is the function call.the control will go to the function in step 3.The method statements will be executed.And the answer will be sent to the step which called the function, that is step 2.The answer is stored in variable s.The data type of the answer is int that is why the return data type is int in function header. Step 2 is also called calling a funtion or invoking a function.
Tha above program can be written like this:

class addition
{
public static void main( )
  {
     int a=10,b=45; --------------------------------------------1
      add(a,b); -------------------------------------2    
}
 void add(int a,int b)----------------------------------------3
  {      int c;
       c=a+b;-----------------------------------------------4
       System.out.print(c); -----------------------------------5  
  }
}
There is a change in step 2, the answer is not stored in any variable .The answer is displayed in the method add itself, thats why there is no return statement and also the datatype is void in function header.  a and b in step 2 are called actual parameters ,a and b in step 3 is called formal parameters.
2. Example 
 Write a program to find the factorial of a number .
class factorial
{
public static void main( )
  {
     int n=5; --------------------------------------------1
     int x= fact(n); -------------------------------------2,8
     System.out .print("Factorial = "+x);------------9
}
 int fact(int n)----------------------------------------3
{
     int i,f=1; ------------------------------------------4
    for(i=1;i<=n;i++)---------------------------------5
     f=f*i; ----------------------------------------------6
  return f; --------------------------------------------7
}
}
After the  step 2 the control will go to the function fact.It will complete all the statements there and send the answer back to main function. The answer will be an integer value ,thats why the return data type is int.
3. Example
Write a program to display the sum of the series

13+23+33+….n3
using the function cube()
class sum

{
public static void main(int n)---------1
{
int i,s=0;
for (i=1;i<=n;i++)
s=s+cube(i);
System.out.print("Sum="+s);
}
public static int cube(int a)
  {
    int c=a*a*a;
    return c;
   }
}
In step 1 you should accept the value of ' n ' from the user. In the above question we should find the cube of each number.We write the code for this once, but call it again and again.

Let me introduce the scope of variables here......

The scope of the variable is nothing but where all you can use a particular variable in a program.
  • Local variable - Variable which is declared inside any function.You can use the variable only in that function not throughout the program .
  • Global variable - variable declared ouside all functions. i.e. just after class.This can be used anywhere in the program.
Example 4
Define a class salary describesd as below:
Data members : Name,Address,Subject,Salary,Income tax
Member methods :
  1.   accept the details of the teacher
  2. display the details
  3. compute the income tax as 5% of the annual salary above Rs.1,75,000.
Write a main method to create an object .
import java.util.*;
class salary
{
String name,address,subject;-----------1
double sal,it;--------------------------2
void get(String n,String add,String sub,double s1)------3
{
  name=n;
  address=add;
  subject=sub;
  sal=s1;
}
void compute()
{   
   int a=sal*12 ;
  if(a > 175000)
          it=0.05* a;
  else
          it=0;
}
void display( )
{
  System.out.println("Name="+name);
  System.out.println("Address="+address);
  System.out.println("Subject="+subject);
  System.out.println("Salary="+sal);
  System.out.println("tax="+it);
}
public static void main()
{
   salary ob=new salary();---------------------------4
   Scanner s=new Scanner(System.in);
    System.out.println("Enter the name");
    name=s.next();
    System.out.println("Enter the address");
    address=s.next();
    System.out.println("Enter the subject");
    subject=s.next();
    System.out.println("Enter the  Monthly salary");
   salary=s.nextDouble();
   ob.get(name,address,subject);
   ob.compute();
   ob.display( );
}
}

Steps 1 and 2 are the global variables.You can use them anywhere in the program. In step 3, the values received from the main method . and in   get ()  the values are stored in global variable for the same reason mentioned above.compute() and display() are according to the question.In step 4, we create an object. salary is the calss name,donot use anything else, ob is the object name,you can give any name. new is the keyword, it allocates memory for the object.
Remember to write the global variable on the left hand side and local variable on the right hand side in void get().Donot mix it up
Methods can be divided into
  • Pure method or accessors - methods donot change the state of an object.
  • Impure mentod or mutators - methods the change  the state of the object.
Method Overlaoding or Function OverloadingThere can be more than one method with the same name.But the problem is how the control will go to the method it is supposed to go.Thats why there should be  some difference in the methods.So method overloading will have more than one method with same name but differ in the number or types of arguments or both.   
Write a program using a function called area( ) to do the following :
  1. Area of a circle
  2. Area of a square
  3. Area of a rectangle

import java.util.*;
class menu
{
public void area(int r)
{
System.out.println("Area of circle="+(3.14*r*r));
}
public void area(int l,int b)
{
System.out.println("Area of rectangle="+(l*b));
}
public void area(float side)
{
System.out.println("Area of square="+(side*side));
}
public  void main( )
{
   Scanner s =new Scanner(System.in);
   System.out.println("Enter radius");
   int r=s.nextInt();
   System.out.println("Enter length and breadth");
    int l=s.nextInt();
    int b=s.nextInt();
   System.out.println("Enter side:");
   float side=s.nextFloat();
area(r);-------------------1
area(l,b);-----------------2
area(side);---------------3
}
}

In step 1 and step 3 have same number of arguments but different data type values and all the 3 functions have same name and differ in something or the other so it represents function overloading.
I give a similar program, try it.If you want your program to be checked, mail it to me.
Write a program using a class to calculate the volume,surface area and the diagonal of cuboid with the following specifications:
class name  : Cuboid
Data members : int l,int b,int h
Member funcions :
void input() : Accept length,breadth and height of cuboid
void calculate() : find volume,surface area and diagonal
void dispaly(): Print the result
Volume of cuboid : lxbxh
Surface Area : 2(lb+bh+lh)
Diagonal :  square root of   l2+b2+h2

Java provides two ways in which a value can be called.
  • Pass or call by value : Its simple,just pass the value in calling function and receive the value in receiving function like in the above examples.
  • Pass or call by reference : Reference is the memory address. The memory address of the variable is passed , so if there is a change in the receiving function, then it will refelect in the calling function also.e.g passing arrays.

No comments:

Post a Comment