0% found this document useful (0 votes)
2 views14 pages

2. Java Methods

Java methods are code blocks that perform specific tasks, promoting code reusability, modularity, readability, and maintainability. They can be categorized into instance, static, final, built-in, and user-defined methods, with each type serving different purposes in programming. The document also explains method syntax, signatures, and how to call different types of methods in Java.

Uploaded by

gokuthecrackhead
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views14 pages

2. Java Methods

Java methods are code blocks that perform specific tasks, promoting code reusability, modularity, readability, and maintainability. They can be categorized into instance, static, final, built-in, and user-defined methods, with each type serving different purposes in programming. The document also explains method syntax, signatures, and how to call different types of methods in Java.

Uploaded by

gokuthecrackhead
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Java Methods

Java Methods are blocks of code that perform a specific task. A method allows us to reuse code, improving both efficiency and organization. All methods in Java
must belong to a class. Methods are similar to functions and expose the behavior of objects.

Why Use Methods?


 Code Reusability: Write once, use multiple times without repeating code so that code reusability increase.
 Modularity: Dividing a program into separate methods allows each method to handle a specific task, making the code more organized and easier to manage.
 Readability: Smaller, named methods make the code easier to read and understand.
 Maintainability: It is easier to fix bugs or update code when it is organized into methods.

Example:

Output

Explanation:

Page 1 of 14
 Here, first we create a method which prints Hello, Java Students!
 printMessage() is a simple method that prints the message.
 It has no parameters and does not return anything.
Syntax of a Method

Key Components of a Method


Method consists of a modifier (Define access level), return type (what value returned or void), name (Define the name of method follows camelCase),
parameters (optional inputs), and a body (Write your logic here).

Note: In Java, every method must have a return type. If it is not specified, a compile-time error occurs. The only exception is constructors, which do not have
a return type.

Types of methods in Java


 Instance = belongs to object
 Static = belongs to class
 Final = cannot change
 Built-in = already given by Java
 User-defined = we write it

Page 2 of 14
Example 1 : basic

Output:

Explanation: in the above code Methods


 User-defined method → show()
Variables
 Static method → displayCount()
 Static variable → count (shared by all objects)
 Final method → message()
 Instance variable → id (different for each object)
 Built-in method → length()
 Final variable → PI (cannot be changed)

Page 3 of 14
Example 2: using abstract class

Output:

Page 4 of 14
Recall
We cannot create an object of an abstract class directly. Then why does it have a constructor?
The constructor is used to initialize common data members when a subclass object is created.

Do constructors of an abstract class get inherited? Explain with example.

No, constructors are not inherited.


However, they are automatically called during object creation through constructor chaining.

Example showing that

 Constructor is not inherited


 But it is called during object creation (constructor chaining)

Output

Page 5 of 14
Example 3: using interface

Output

Page 6 of 14
Types of methods in Java based on

1. who defines it
 Built-in methods → already provided in java libraries (e.g., length(), sqrt())
 User-defined methods → written by programmer

2. object/class
 Instance method → belongs to object
 Static method → belongs to class

3. implementation
 Concrete method → has body (normal method)
 Abstract method → no body (only declaration)

4. special behavior
 Final method → cannot be overridden
 Default method → (in interface) has body // In a Java interface, if you do not specify any access modifier, the method is public by default
 Static method (in interface) → belongs to interface

Standard definitions
o Predefined ( Library or Built-in) Method
Predefined methods are the method that is already defined in the Java class libraries. It is also known as the standard library method or built-in method.
For example, random() method which is present in the Math class and we can call it using the [Link]() as
[Link]() //returns random value

o User-defined Method
The method written by the user or programmer is known as a user-defined method. Example:
printMessage() // created in the first example of this doc

o Instance Method: Access using the object name. Declared inside a class.
Example:

Page 7 of 14
o Static Method: Access using class name. Declared inside class with static keyword.
Example:

...
Method Signature
It consists of the method name and a parameter list.

 Number of parameters
 Type of the parameters
 Order of the parameters

Note: The return type and exceptions are not considered as part of it.

Example of method Signature:

max(int x, int y) Number of parameters is 2, Type of parameter is int.

Naming a Method
In Java language method name is typically a single word that should be a verb in lowercase or a multi-word, that begins with a verb in lowercase followed by
an adjective, noun. After the first word, the first letter of each word should be capitalized (camelCase format).

Calling Different Types of Methods in Java

 Calling User-Defined method

Page 8 of 14
To execute a user-defined method, we first create an object of the class (if the method is non-static) and then call the method using that object.

Example:

Output:
Explanation: In the above code a class MethodLearn with a method hello() that displays a message. In the main() method, we create an object of the class and
use it to call the hello() method.

 Calling Predefined (built-in) method

Output:
Explanation:
 length() is a built-in Java method (already written by Java).
 It counts how many characters are in a string.

Page 9 of 14
 We just use it. No need to create it.

Note: length() does not require any import.

- length() belongs to the String class


- The String class is part of [Link] package
- And [Link] is imported automatically in every Java program

 Calling an Abstract method


Abstract methods have no body and must be overridden in a subclass. They are called using an object of the subclass.
Example:

Output:
Explanation: In the above code an abstract class Animal with an abstract method makeSOund(), which is implemented in the subclass Dog. In the main()
method, an object of Test is created to call the implemented makeSound() method.

 Calling a Static Method


Page 10 of 14
Static methods belong to the class, not the object. They can be called without creating an object.

Output:
Explanation: we call a static method hello() from the TestStatic class without creating an instance of the class. The method prints "Hello" when invoked from
the main method.

Instance methods in Java

An instance method belongs to an object of a class and requires an instance to be called.


 Can access and modify instance variables (object state).
 Can accept parameters and return a value.
 Can call other instance methods or static methods.
 Supports encapsulation and object-oriented design.

Example: Instance method without parameter

Explanation:
 greet() is an instance method.
 It prints the name of the object.
 Called using an object p of the Person class.

Output

Page 11 of 14
Example: Instance method with parameter

Output:

Explanation:
 GFG class has an instance method add() that accepts two integers.
 The method adds the numbers and prints their sum.
 We create an object and call add() with parameters 2 and 3.

Page 12 of 14
Static Methods in Java
In Java, the static keyword is used to create methods that belongs to the class rather than any specific instance of the class. Any method that uses
the static keyword is referred to as a static method.

Features of Static Methods

 A static method in Java is associated with the class, not with any object or instance.
 It can be accessed by all instances of the class, but it does not rely on any specific instance.
 Static methods can access static variables directly without the need for an object.
 They cannot access non-static variables (instance) or methods directly.
 Static methods can be accessed directly in both static and non-static contexts.

The JVM executes the static method first, even before creating class objects. So, static methods cannot access instance variables, as no object exists at
that point.

Restrictions on Static Methods

 Static method cannot access instance variables.


 Non-static data members or non-static methods cannot be used by static methods, and static methods cannot call non-static methods directly.
 In a static environment, this and super are not allowed to be used.

Why is the main method static in Java?


The main method must be static because the JVM does not create an object of the class before invoking it. If it were a non-static method, JVM would first build
an object before calling the main() method, resulting in an extra memory allocation difficulty.

Page 13 of 14
Difference between the Static Method and Instance Method

Instance Methods Static Methods


It requires an object of the class. It does not require an object of the class.

It can access all attributes of a class. It can access only the static attribute of a class.

The methods can be accessed only using object reference. The method is only accessed by class name.

Syntax: [Link]() Syntax: [Link]()

Common types to recall:

For Variables

1. Instance variable
2. Static variable
3. Final variable

For Methods

1. Instance method
2. Static method
3. Abstract method
4. Final method
5. Built-in method
6. User-defined method

Page 14 of 14

You might also like