Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
73 views

Methods in Java

Methods allow programmers to organize code into reusable blocks. There are two types of methods: user-defined methods created by the programmer, and pre-defined methods that are part of the Java library. Methods can return values or not return values. They are defined with a name, parameters, and body. Methods make code reusable and help manage complexity in large programs. Compile-time errors occur during compilation and prevent execution, while runtime errors occur during execution and are unpredictable.

Uploaded by

siddhant kudesia
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
73 views

Methods in Java

Methods allow programmers to organize code into reusable blocks. There are two types of methods: user-defined methods created by the programmer, and pre-defined methods that are part of the Java library. Methods can return values or not return values. They are defined with a name, parameters, and body. Methods make code reusable and help manage complexity in large programs. Compile-time errors occur during compilation and prevent execution, while runtime errors occur during execution and are unpredictable.

Uploaded by

siddhant kudesia
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 14

Methods (Java)

What is Method?
A method is a set of code which is referred to by name and can be called
(invoked) at any point in a program simply by utilizing the method's name. 
Why Method?
When program becomes more and more complex i.e. .When they gain in size. So one
of the most powerful techniques to cope with complexity in computer programs is
affectionately known as “Divide and Conquer” - that is to take a complex task and
divide it into smaller tasks and they are implemented by Methods

1. To cope with complexity:


When programs become more and more complex that is, when they gain in size, they
become chaotic to handle.

One of the most powerful techniques to reduce this complexity is “Divide and
Conquer” which is to take a complex task and divide it into smaller and easily
understandable tasks. In Java, we accomplish this technique with the help of methods .

2. To hide low-level details:


Another essential use of methods is to create “black boxes”. At the level of
using a method, we need not concern ourselves with how the method’s task is
performed. We are actually treating a method as a black box because we
accept the result without concern for its details.

3.To Reuse code:


Once a task is packaged in a method, that method is available for accessing
anywhere from the program. The method can be reused that is we can call it
more than once in a program and also from other programs.

The practice of reusing is sometimes called “Write once, use many”.


Types of Methods
1. User defined
2. Pre-defined or inbuilt

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.

Method signatures
The line where the methods parameters and return type are defined is known as the method
signature.
 public void calculate()
 public double calculate()
 public void calculate (double number1, double number2)
 public double calculate(double number1, double number2)
Creating Method:

public static int methodName (int a, int b)


{
// Method body
}

 public static : modifier.(Static is non access


modifier
 int: return type
 methodName: name of the method
 a, b: formal parameters
 int a, int b: list of parameters
Syntax of method

modifier returnType methodName (Parameter List)


{
// method body
}
The syntax shown above includes:
modifier: It defines the access type of the method and it is optional to use.

static - If you use static keyword in a method then it becomes a static


method. Static methods can be called without creating an instance of a
class.
returnType: Method may return a value.

nameOfMethod: This is the method name. The method signature consists


of the method name and the parameter list.

Parameter List: The list of parameters, it is the type, order, and number of
parameters of a method. These are optional, method may contain zero
parameters.

Method body: The method body defines what the method does with
statements.
Example:
Here is the source code:

Method with Return type

public static int areaSquare(int a)


{
int area = a*a;
return area;
}

Without Return Type

public static void areaOfRectangle(int length, int breadth)


{
int area = length * breadth;

}
Method Calling:
For using a method, it should be called.

There are two ways in which a method is called i.e.

method returns a value


or
returning nothing no return value.

The process of method calling is simple.


When a program invokes a method, the program control gets transferred to the called method.

This called method then returns control to the caller in two conditions, when:

return statement is executed.


reaches the method ending closing brace.

The methods returning void is considered as call to a statement. Let’s consider an example:
System .out.println("This is tutorialspoint.com !");

The method returning value can be understood by the following example:

int result = sum (6, 9);


Method without return type

public class FirstMethod


{

public static void areaR(int length,int breadth)


{
int area = length*breadth;
System.out.println(area);
}

public static void main(String args[])


{
int y=4;
int x=5;
areaR(x,y); // calling function
}

}
Method with return Type

public class SecondMethod


{

public static double areaC(int radius) // method with return type


{
double pie = 3.142;
double area = 2*pie*radius;
return area;

public static void main(String args[])


{
int r=4;

double result = areaC(r); // calling method


System.out.println("area of circle "+result);
}

}
static and non-static method in Java
A static method is a method that belongs to a class, but it does not belong to
an instance of that class and this method can be called without the instance or
object of that class. 

Every method in java defaults to a non-static method without static keyword


preceding it. 

Non-static methods can access any static method and static variable, without


creating an instance of the object. Let us clarify the differences Below are the
various important differences among these pointers as follows:

Example of static vs non-static method


JavaTester.java

public class JavaTester {


   public static void main(String args[]) {
      Tiger.roar();
      Tiger tiger = new Tiger();
      tiger.eat();
   }
}
class Tiger {
   public void eat(){
      System.out.println("Tiger eats");
   }
   public static void roar(){
      System.out.println("Tiger roars");
   }
}

Following are the important differences between static and non-static method.

Sr. Key Static Non-Static


No.

Access A static method can access A non-static method can access both static as
only static members and well as non-static members.
1
cannot access non-static
members.

Binding Static method uses compile Non-static method uses run time binding or
2 time binding or early dynamic binding.
binding.

Overriding A static method cannot be A non-static method can be overridden being


3 overridden being compile dynamic binding.
time binding.

Memory Static method occupies less A non-static method may occupy more space.
allocation space and memory Memory allocation happens when method is
4
allocation happens once. invoked and memory is deallocated once
method is executed completely.

Keyword A static method is declared A normal method is not required to have any
5
using static keyword. special keyword.
Compile time vs Runtime
Compile-time and Runtime are the two programming terms used in the software
development. Compile-time is the time at which the source code is converted into an
executable code while the run time is the time at which the executable code is started
running. Both the compile-time and runtime refer to different types of error.

Compile-time errors
Compile-time errors are the errors that occurred when we write the wrong syntax. If we
write the wrong syntax or semantics of any programming language, then the compile-
time errors will be thrown by the compiler. The compiler will not allow to run the
program until all the errors are removed from the program. When all the errors are
removed from the program, then the compiler will generate the executable file.

The compile-time errors can be:

o Syntax errors
o Semantic errors

Syntax errors

When the programmer does not follow the syntax of any programming language, then
the compiler will throw the syntax error.

For example,

int a, b:

The above declaration generates the compile-time error as in Java, every statement
ends with the semicolon, but we put a colon (:) at the end of the statement.

Semantic errors

The semantic errors exist when the statements are not meaningful to the compiler.

For example,

a+b=c;
The above statement throws a compile-time errors. In the above statement, we are
assigning the value of 'c' to the summation of 'a' and 'b' which is not possible in C
programming language as it can contain only one variable on the left of the assignment
operator while right of the assignment operator can contain more than one variable.

The above statement can be re-written as:

c=a+b;

Runtime errors
The runtime errors are the errors that occur during the execution and after compilation.
The examples of runtime errors are division by zero, etc. These errors are not easy to
detect as the compiler does not point to these errors.

Let's look at the differences between compile-time and runtime:

Compile-time Runtime

The compile-time errors are the errors The runtime errors are the errors which are not
which are produced at the compile-time, generated by the compiler and produce an
and they are detected by the compiler. unpredictable result at the execution time.

In this case, the compiler prevents the In this case, the compiler does not detect the
code from execution if it detects an error error, so it cannot prevent the code from the
in the program. execution.

It contains the syntax and semantic errors It contains the errors such as division by zero,
such as missing semicolon at the end of determining the square root of a negative
the statement. number.
Good programmers write in a modular fashion which allows for several programmers
to work independently on separate concepts which can be assembled at a later date to
create the entire project.  The use of methods will be our first step in the direction of
modular programming.

Methods are time savers, in that they allow for the repetition of sections of code
without retyping the code.  In addition, methods can be saved and utilized again and
again in newly developed programs.

You are using methods when you use


 System.out.print( ) and System.out.println( ).

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

You might also like