0% found this document useful (0 votes)
18 views53 pages

Functions n Methodes in Java

Uploaded by

anshj9797
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
18 views53 pages

Functions n Methodes in Java

Uploaded by

anshj9797
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 53

Methods in Java Programming Language

 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.
 The use of methods will be our first step in the
direction of modular programming.
 Method definitions have four basic parts:
 The name of the method
 The type of object or base type this method returns
 A list of parameters
 The body of the method
 The syntax for defining a method is:
 Method definition consists of a method header and
a method body.The same is shown in the following
syntax
 modifier returnValueType methodName(list of
parameters) { // Method body; }
 public static int methodName(int a, int b)
 { // body }
 method header
 The method header specifies the modifiers, return
value type, method name, andparameters of the
method.
 modifier − It defines the access type of the method and it is
optional to use.
 return type − Method may return a value. It can be any data
type.
 name of method − This is the method name. The method
signature consists of the method name and the parameter list.
 Parameter List − Parameter list may two type 1. formal
parameter 2. actual parameter. The list of parameters, it is the
type, order, and a number of parameters of a method. These are
optional, the method may contain zero parameters.
 formal parameter - The variables defined in the method
header are known as formal parameters or simply parameters. A
parameter is like a placeholder.
 actual parameter - When a method is invoked, you pass a
value to the parameter. This value is referred to as an actual
parameter or argument.
 method body − The method body defines what the method does
with the statements.

 method body
 The method body contains a collection of statements
that implement the method. The method body of the
max method uses an if statement to determine which
number is larger (numA or numB) and return the
value of that number. In order for a value-returning
method to return a result, a return statement using
the keyword return is required. The method
terminates when a return statement is executed.
 Method Calling
 In a method definition, you define what the method
is to do. To execute the method, you have to call or
invoke it.There are two ways in which a method is
called depending on whether the method returns a
value or not.
 method returns a value
 If a method returns a value, a call to the method is
usually treated as a value. and this value will store in
a variable For example,
 int largestNumber = max(15, 8);
 calls max(15, 8) and assigns the result of the method
to the variable largestNumber.
 method returs but not in a variable
 The methods returning nothing or void is
considered as call to a statement. Lets consider an
example ?
 System.out.println(max(15, 8));This is also a
example of method calling
 which prints the return value of the method
call max(15, 8)
 Void Method
 This section shows how to define and invoke a void
method. The void keyword allows us to create
methods which do not return a value.
 public class VoidMethodExample {
 public static void main(String[] args) { System.out.print("You
are ");
 printAge(78);
 System.out.print("You are ");
 printAge(15); }
 public static void printAge(double age) {
 if (age >= 90.0) {
 System.out.println("lagend Old"); }
 else if (age >= 60.0) {
 System.out.println("old"); }
 else if (age >= 40.0) {
 System.out.println("adult"); }
 else if (age >= 20.0) {
 System.out.println("young"); }
 else {
 System.out.println("boy"); } } }
 Passing Parameters by Value
 The power of a method is its ability to work with
parameters. You can use println to print any string
and max(4,7) to find the maximum of any two int values.

When you invoke a method with an argument, the value
of the argument is passed to the parameter. This is
referred to as pass-by-value. When calling a method, you
need to provide arguments, which must be given in the
same order as their respective parameters in the method
signature. This is known as parameter order association
 public class SwappingExample
 { public static void main(String[] args)
 { int a = 3; int b = 4;
 System.out.println("Before swapping, a = " + a + " and
b = " + b); // Invoke the swap method swapFunction(a,
b);
 System.out.println("\n Now, Before and After
swapping values will be same here :");
System.out.println("After swapping, a = " + a + " and b
is " + b); }
 public static void swapFunction(int a, int b) {
System.out.println("Before swapping(Inside), a = " + a
+ " b = " + b); // Swap a with b
 int c = a; a = b; b = c;
 System.out.println("After swapping(Inside), a = " + a
+ " b = " + b); } }
 What is Method Overloading
 In Java it is possible to define two or more
methods within the same class that share the same
name, as long as their parameter declarations are
different. When this is the case, the methods are
said to be overloaded, and the process is referred to
as method overloading.
 If a class has multiple methods having same name
but different in parameters, it is known as Method
Overloading.

Method overloading is one of the ways that Java
supports polymorphism.
 Advantage of method overloading
 The main advantage of this is cleanliness of code.
 Method overloading increases the readability of the
program.
 Flexibility
 Overloaded methods give programmers the
flexibility to call a similar method for different types
of data.
 Different ways to overload the method
 There are two ways to overload the method in java
 By changing number of arguments
 By changing the data type
Pure function vs. impure function

 Pure Functions: This function always returns the


same output as given the same input parameters.
Pure functions only depend on their input
parameters and don’t affect the state of the
application or other parts of the code.
 Characteristics:
 Functions do not modify any state or have any side
effects.
 Functions only depend on their input parameters.
 These are predictable and have a deterministic
behavior and are easier to test, debug, and maintain.
Impure Functions:

 Impure functions are functions that can modify the


state of the application or have side effects. In other
words, impure functions can have unpredictable
behavior and do affect other parts of the application.
Characteristics:

 Functions can modify the state of the application or


have side effects.
 Functions depend on other parts of the code.
 These are unpredictable and can have a non-
deterministic behavior and are harder to test, and
maintain.
 Constructor
 A constructor is a special kind of method that
determines how an object is initialized when it’s
created.
 Rules for creating Java constructor
 There are basically three rules defined for the
constructor.
 Constructor name must be same as its class name
 Constructor must have no explicit return type. i.e
Constructors do not have a return type — not even
void
 Constructors are invoked using the new operator
when an object is created. Constructors play the role
of initializing objects.
 Types of Java constructors
 There are two types of constructors:
 Default constructor (no-arg constructor)
 Parameterized constructor
 Java Default Constructor
 A constructor that have no parameter is known as
default constructor.
 Syntax of default constructor:
 ClassName() { }
 Example of Default Constructor
 In this example, we are creating the no-arg
constructor in the Sample class. It will be invoked at
the time of object creation.
 class Sample{
 Sample(){
 // constructor
 System.out.println("this is inside constructor"); }
public static void main(String args[]){
 Sample b=new Sample(); } }
 What is the purpose of default constructor?
 Default constructor provides the default values to the object
like 0, null etc. depending on the type.
 Example of default constructor that displays the
default values
 class Student{
 String name;
 int rollNo;
 void display(){
 System.out.println(rollNo+" "+name); }
 public static void main(String args[]){
 Student s1=new Student();
 Student s2=new Student();
 s1.display();
 s2.display(); } }
 In the above class,you are not creating any constructor so
compiler provides you a default constructor.Here 0 and null
values are provided by default constructor.
 class Demo{
 int value1;
 int value2;
 Demo(){
 // this is constructor
 value1 = 10;
 value2 = 20;
 System.out.println("Inside Constructor"); }
 public void display(){
 System.out.println("Value1 === "+value1);
System.out.println("Value2 === "+value2); } public
static void main(String args[]){
 Demo d1 = new Demo();
 d1.display(); } }
 Java parameterized constructor
 A constructor that have parameters is known as
parameterized constructor.
 Why we use parameterized constructor?
 Parameterized constructor is used to provide
different values to the distinct objects.
 class Student{ String name; int rollNo;
Student(String n, int i){ name = n; rollNo = i; }
void display(){ System.out.println(rollNo+"
"+name); } public static void main(String
args[]){ Student s1=new Student("Dhinchak
Pooja", 1); Student s2=new Student("Hero
Alom",2); s1.display(); s2.display(); } }
 Constructor overloading
 The constructor has exactly the same name as its
defining class. Like regular methods, constructors
can be overloaded (i.e., multiple constructors can
have the same name but different signatures),
making it easy to construct objects with different
initial data values.
 When do we need Constructor Overloading?
 Sometimes there is a need of initializing an
object in different ways. This can be done using
constructor overloading. For example, Thread
class has 6 types of constructors. If we do not
want to specify anything about a thread then we
can simply use default constructor of Thread
class,
 Thread t= new Thread (); however if we need to
specify thread name, then we may call the
parameterized constructor of Thread class with a
String args like this:
 Thread t= new Thread ("Thread1");
 class StudentClass{ String name; int rollNo; int
year; StudentClass(String n,int i){ name = n;
rollNo = i; } StudentClass(String n,int i,int y){
name = n; rollNo = i; year=y; } void display(){
System.out.println("Roll NO: "+rollNo+" Name:
"+name+" Year: "+year); } public static void
main(String args[]){ StudentClass s1 = new
StudentClass("Dhinchak Pooja",25); StudentClass
s2 = new StudentClass("Hero Alom",22,2);
s1.display(); s2.display(); } }
 A static method is a method that belongs to
a class rather than an instance of a class. This means
you can call a static method without creating an
object of the class. Static methods are sometimes
called class methods.
 Features of static method:
 A static method in Java is a method that is part of a
class rather than an instance of that class.
 Every instance of a class has access to the method.
 Static methods have access to class variables (static
variables) without using the class’s object (instance).
 Only static data may be accessed by a static method.
It is unable to access data that is not static (instance
variables).
 In both static and non-static methods, static
methods can be accessed directly.
 Syntax to declare the static method:
 Access_modifier static void methodName() { //
Method body. }
Scope of Variables in Java

 In programming, scope of variable defines how a


specific variable is accessible within the program or
across classes.
 In programming, a variable can be declared and
defined inside a class, method, or block. It defines
the scope of the variable i.e. the visibility or
accessibility of a variable. Variable declared inside a
block or method are not visible to outside. If we try
to do so, we will get a compilation error.
 We can declare variables anywhere in the program
but it has limited scope.
 A variable can be a parameter of a method or
constructor.
 A variable can be defined and declared inside the
body of a method and constructor.
 It can also be defined inside blocks and loops.
 Variable declared inside main() function cannot be
accessed outside the main() function
Member Variables (Class Level Scope)

 These are the variables that are declared inside the


class but outside any function have class-level scope.
 We can access these variables anywhere inside the
class.
 Note that the access specifier of a member variable
does not affect the scope within the class.
 Java allows us to access member variables outside
the class with the following rules:
 Loop Variables (Block Scope)
A variable declared inside pair of brackets “{” and “}”
in a method has scope within the brackets only.

You might also like