Skip to main content

Unit 3 Java


Java Methods

A method in Java is a block of code that performs a specific task and executes only when it is called (invoked).
It helps in reusing code by defining a logic once and calling it multiple times whenever required.

Methods are also known as functions in other programming languages such as C or C++.

 

Purpose of Methods

The main goals of using methods in Java are:

Perform specific tasks: Each method handles one defined operation, like calculation or displaying data.

Avoid code repetition: The same logic can be reused by calling the method instead of rewriting it.

Make programs modular and readable: Dividing a program into smaller methods makes it easier to understand and debug.

Improve code reusability: Once defined, a method can be used in different parts of the program or other classes.

 

Types of Methods in Java

There are two main types of methods:

1.      Predefined Methods (Built-in Methods)

2.      User-defined Methods

3.       

1. Predefined Methods

These are methods already defined and available in Java libraries.
Programmers can use them directly without creating them manually.

Examples:

·         System.out.println() — prints text on the console.

·         Math.sqrt(16) — returns the square root of a number.

·         length() — returns the length of a string or array.

Example Code:

public class Example1 {
  public static void main(String[] args) {
    System.out.println("Hello, this is a predefined method!");
    double result = Math.sqrt(25);
    System.out.println("Square root of 25 is: " + result);
  }
}

Output:

Hello, this is a predefined method!
Square root of 25 is: 5.0

 

2. User-defined Methods

These are methods that the programmer creates to perform specific actions.
They can accept inputs (parameters) and may or may not return a value.

 

General Syntax of a Method

returnType methodName(parameters) {
    // body of the method
    // statements to execute
}

Explanation of Each Part:

Part

Description

returnType

Specifies what type of value the method returns (e.g., int, double, String, void if no return).

methodName

The name of the method (should follow Java naming conventions).

parameters

The list of input values (optional). They are declared within parentheses.

method body

The block of code that performs the task when the method is called.

:

Basic method and Calling a Method

To call or execute a method, use its name followed by parentheses () and a semicolon.

Example:

public class Main {
  static void myMethod() {
    System.out.println("Hello! Method is running.");
  }
  public static void main(String[] args) {
    myMethod();  // calling the method
  }
}

Output:

Hello! Method is running.

 

·         myMethod() → The name of the method.

·         static → It belongs to the class and can be called without creating an object.

·         void → It does not return any value.

·         The code inside {} runs when the method is called.

 

Examples of User-defined Methods

 

Example 1: Method Without Arguments and Without Return Type

This type of method does not take any input and does not return any value.

public class Main {
  static void Method1() {
    int l = 20, b = 40;
    int area = l * b;
    System.out.println("Area: " + area);
  }
  public static void main(String[] args) {
    Method1();  // calling the method
  }
}

Output:

Area: 800

Example 2: Calling a Method Multiple Times

You can call a method as many times as needed.

public class Main {
  static void myMethod() {
    System.out.println("I just got executed!");
  }
  public static void main(String[] args) {
    myMethod();
    myMethod();
    myMethod();
  }
}

Output:

I just got executed!
I just got executed!
I just got executed! 

Example 3: Method With Arguments (Parameters)

This type of method takes input values but does not return anything.

public class Main {
  static void Method1(int l, int b) {
    int area = l * b;
    System.out.println("Area: " + area);
  }
  public static void main(String[] args) {
    int l = 20, b = 40;
    Method1(l, b); // passing arguments
  }
}

Output:

Area: 800

Example 4: Method With Return Type

A method can return a value to the place where it is called.

public class Main {
  static int square(int x) {
    return x * x;  // returns the square of the number
  }
  public static void main(String[] args) {
    int result = square(5);
    System.out.println("Square of 5 is: " + result);
  }
}

Output:

Square of 5 is: 25



Constructor

A constructor in Java is a special block of code that:

  • Has the same name as the class.
  • Is automatically called when an object is created.
  • Is used to initialize objects (assign initialvalues to variables).
  • Does not have any return type, not even void.
  • A constructor is called when you create an object using new keyword.
  • Student s1 = new Student(); // constructor is called here
  • If no constructor is defined, Java automatically provides a default constructor.
  • It is called constructor because it "constructs" the object’s data during creation.


 Rules for Creating a Constructor

  1. The constructor name must match the class name.
  2. A constructor cannot have a return type.
  3. A constructor cannot be abstract, static, final or synchronized.
  4. Access modifiers (public, private, protected, defaul can control where the constructor is accessible.

Types of Java constructors

There are two types of constructors in Java:

  1. Default constructor (no-arg constructor)
  2. Parameterized constructor

Java Default Constructor

A constructor is called "Default Constructor" when it doesn't have any parameter.

Syntax of default constructor:

<class_name>(){}  

Example of default constructor

In this example, we are creating the no-arg constructor in the Bike class. 

It will be invoked at the time of object creation. 

//Java Program to create and call a default constructor  

class Bike1{  

//creating a default constructor  

Bike1()

{

System.out.println("Bike is created");

}  

//main method  

public static void main(String args[]){  

//calling a default constructor  

Bike1 b=new Bike1();  

}  

}  

Output:

Bike is created

Rule: If there is no constructor in a class, compiler automatically creates a default constructor.


In this example, we are creating the no-arg constructor in the Bike class. 

It will be invoked at the time of object creation. 

//Java Program to create and call a default constructor  

class Bike1{  

//creating a default constructor  

Bike1()

{

System.out.println("Bike is created");

}  

//main method  

public static void main(String args[]){  

//calling a default constructor  

Bike1 b=new Bike1();  

}  

}  

Output:

Bike is created

Rule: If there is no constructor in a class, compiler automatically creates a default constructor.

 

Java Parameterized Constructor

parameterized constructor is a constructor that includes one or more parameters.
It is used to initialize objects with specific values during their creation.
By using parameterized constructors, we can assign different values to different objects — although

 the same values can also be used if desired.

Key Points:

·         The constructor has parameters that accept values when creating an object.

·         It allows initialization of object properties at the time of object creation.

·         You can create multiple objects with different data using the same constructor.

·         The constructor name must be same as the class name.

Example: Java Program to Demonstrate Parameterized Constructor

// Java Program to demonstrate the use of parameterized constructor
class Student4
    int id;  
    String name;  
 
    // Creating a parameterized constructor  
    Student4(int i, String n) {  
        id = i;  
        name = n;  
    }  
 
    // Method to display the values  
    void display()
        System.out.println(id + " " + name);  
    }  
 
    public static void main(String args[])
        // Creating objects and passing values  
        Student4 s1 = new Student4(1, "Aakirti");  
        Student4 s2 = new Student4(2, "Ayusha");  
 
        // Calling method to display the values of objects  
        s1.display();  
        s2.display();  
    }  
}

 Output:

1 Aakirti
2 Ayusha

Difference between constructor and method 

Java Constructor

Java Method

A constructor is used to initialize the state of an object.

A method is used to expose the behavior of an object.

A constructor must not have a return type.

A method must have a return type.

The constructor is invoked implicitly.

The method is invoked explicitly.

The Java compiler provides a default constructor if We don't have any constructor in a class.

The method is not provided by the compiler in any case.

The constructor name must be same as the class name.

The method name may or may not be same as the class name.

 

Comments

Popular posts from this blog

Function of OS 1. Process Management The operating system helps in running many programs at the same time. It keeps track of each running program (called a process), decides which one should run next, and stops or starts them as needed. It makes sure that all the programs get a fair chance to use the CPU.   2. Memory Management The OS manages the computer's memory (RAM). It decides which program will use how much memory and keeps track of it. When a program is closed, it frees up the memory so that other programs can use it. This helps the computer run smoothly without crashing.   3. File System Management The operating system helps us to create, save, open, and delete files. It organizes files in folders and keeps them safe. It also controls who can open or edit a file to protect our data.   4. Device Management The OS controls all the input and output devices like the keyboard, mouse, printer, and monitor. It tells the devices what to do and makes su...

UNIT 3 Array in C#

  Array in C# An array is a collection of variables of the same data type , stored in contiguous memory locations , and accessed using a common name and index . Each item in an array is called an element , and the index of arrays in C# starts from 0 .     Key Points About Arrays in C#: 1.       Elements are stored in contiguous memory locations. 2.       Index starts from 0. So, for an array of size 5, valid indexes are 0 to 4. 3.       Arrays are reference types and are allocated on the heap. 4.       C# array is an object of base type System.Array . 5.       Array elements can be of any type , including another array (array of arrays). 6.       Jagged array (array of arrays) elements are reference types and are initialized to null . 7.       Arrays can be single-dimensi...

Unit 2 Java

Data Types A data type defines the kind of data a variable can store, the operations that can be performed on it, and the amount of memory allocated. Java Primitive Data Types Data Type Size Range (Approx.) Example Byte 1 byte -128 to 127 byte a = 100; short 2 bytes -32,768 to 32,767 short s = 1000; Int 4 bytes -2,147,483,648 to 2,147,483,647 int num = 50000; Long 8 bytes -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 long l = 100000L; float 4 bytes ~6–7 decimal digits float f = 5.75f; double 8 bytes ~15 decimal digits double d = 19.99; Char 2 bytes Single Unicode character char c = 'A'; boolean 1 bit* tru...