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

Java Method and Constructors

Uploaded by

Roo Anu
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Java Method and Constructors

Uploaded by

Roo Anu
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

Java main () method

The main() is the starting point for JVM to start execution of a Java program. Without the
main() method, JVM will not execute the program. The syntax of the main() method is:

public: It is an access specifier. We should use a public keyword before the main() method so
that JVM can identify the execution point of the program. If we use private, protected, and
default before the main() method, it will not be visible to JVM.
static: You can make a method static by using the keyword static. We should call the main()
method without creating an object. Static methods are the method which invokes without
creating the objects, so we do not need any object to call the main () method.
void: In Java, every method has the return type. Void keyword acknowledges the compiler
that main () method does not return any value.
main(): It is a default signature which is predefined in the JVM. It is called by JVM to execute
a program line by line and end the execution after completion of this method. We can also
overload the main () method.
String args[]: The main() method also accepts some data from the user. It accepts a group of
strings, which is called a string array. It is used to hold the command line arguments in the
form of string values.
1. main(String args[])
Here, agrs[] is the array name, and it is of String type. It means that it can store a group of
string. Remember, this array can also store a group of numbers but in the form of string
only. Values passed to the main() method is called arguments. These arguments are stored
into args[] array, so the name args[] is generally used for it.
What happens if the main() method is written without String args[]?
The program will compile, but not run, because JVM will not recognize the main() method.
Remember JVM always looks for the main() method with a string type array as a parameter.
Method in Java
In general, a method is a way to perform some task. Similarly, the method in Java is a collection
of instructions that performs a specific task. It provides the reusability of code. We can also
easily modify code using methods.
What is a method in Java?
A method is a block of code or collection of statements or a set of code grouped together to
perform a certain task or operation. It is used to achieve the reusability of code. We write a
method once and use it many times. We do not require to write code again and again. It also
provides the easy modification and readability of code, just by adding or removing a chunk of
code. The method is executed only when we call or invoke it.The most important method in
Java is the main() method.
Method Declaration
The method declaration provides information about method attributes, such as visibility,
return-type, name, and arguments. It has six components that are known as method header, as
we have shown in the following figure.

Method Signature: Every method has a method signature. It is a part of the method
declaration. It includes the method name and parameter list.
Access Specifier: Access specifier or modifier is the access type of the method. It specifies the
visibility of the method. Java provides four types of access specifier:
o Public: The method is accessible by all classes when we use public specifier in our
application.
o Private: When we use a private access specifier, the method is accessible only in the
classes in which it is defined.
o Protected: When we use protected access specifier, the method is accessible within the
same package or subclasses in a different package.
o Default: When we do not use any access specifier in the method declaration, Java uses
default access specifier by default. It is visible only from the same package only.
Return Type: Return type is a data type that the method returns. It may have a primitive data
type, object, collection, void, etc. If the method does not return anything, we use void keyword.
Method Name: It is a unique name that is used to define the name of a method. It must be
corresponding to the functionality of the method. Suppose, if we are creating a method for
subtraction of two numbers, the method name must be subtraction (). A method is invoked by
its name.
Parameter List: It is the list of parameters separated by a comma and enclosed in the pair of
parentheses. It contains the data type and variable name. If the method has no parameter, left
the parentheses blank.
Method Body: It is a part of the method declaration. It contains all the actions to be performed.
It is enclosed within the pair of curly braces.

Naming a Method
While defining a method, remember that the method name must be a verb and start with
a lowercase letter. If the method name has more than two words, the first name must be a
verb followed by adjective or noun. In the multi-word method name, the first letter of each
word must be in uppercase except the first word. For example:
Single-word method name: sum(), area()
Multi-word method name: areaOfCircle(), stringComparision()
It is also possible that a method has the same name as another method name in the same class,
it is known as method overloading.
Types of Method
There are two types of methods in Java:
o Predefined Method
o User-defined Method
Predefined Method
In Java, predefined methods are the method that is already defined in the Java class libraries is
known as predefined methods. It is also known as the standard library method or built-in
method. We can directly use these methods just by calling them in the program at any point.
Some pre-defined methods are length(), equals(), compareTo(), sqrt(), etc. When we call any of
the predefined methods in our program, a series of codes related to the corresponding method
runs in the background that is already stored in the library.
Each and every predefined method is defined inside a class. Such as print() method is defined in
the java.io.PrintStream class. It prints the statement that we write inside the method. For
example, print("Java"), it prints Java on the console.
Let's see an example of the predefined method.
1. public class Demo
2. {
3. public static void main(String[] args)
4. {
5. // using the max() method of Math class
6. System.out.print("The maximum number is: " + Math.max(9,7));
7. }
8. }
Output:
The maximum number is: 9
In the above example, we have used three predefined methods main(), print(), and max(). We
have used these methods directly without declaration because they are predefined. The print()
method is a method of PrintStream class that prints the result on the console. The max()
method is a method of the Math class that returns the greater of two numbers.

In the above method signature, we see that the method signature has access specifier public,
non-access modifier static, return type int, method name max(), parameter list (int a, int b). In
the above example, instead of defining the method, we have just invoked the method. This is
the advantage of a predefined method. It makes programming less complicated.
Similarly, we can also see the method signature of the print() method.
User-defined Method
The method written by the user or programmer is known as a user-defined method. These
methods are modified according to the requirement.
How to Create a User-defined Method
Let's create a user defined method that checks the number is even or odd. First, we will define
the method.
1. //user defined method
2. public static void findEvenOdd(int num)
3. {
4. //method body
5. if(num%2==0)
6. System.out.println(num+" is even");
7. else
8. System.out.println(num+" is odd");
9. }
We have defined the above method named findevenodd(). It has a parameter num of type int.
The method does not return any value that's why we have used void. The method body
contains the steps to check the number is even or odd. If the number is even, it prints the
number is even, else prints the number is odd.

How to Call or Invoke a User-defined Method


Once we have defined a method, it should be called. The calling of a method in a program is
simple. When we call or invoke a user-defined method, the program control transfer to the
called method.
1. import java.util.Scanner;
2. public class EvenOdd
3. {
4. public static void main (String args[])
5. {
6. //creating Scanner class object
7. Scanner scan=new Scanner(System.in);
8. System.out.print("Enter the number: ");
9. //reading value from the user
10. int num=scan.nextInt();
11. //method calling
12. findEvenOdd(num);
13. }
In the above code snippet, as soon as the compiler reaches at line findEvenOdd(num), the
control transfer to the method and gives the output accordingly.
Constructors in Java

Constructors are used to initialize the object’s state. Like methods, a constructor also
contains collection of statements (i.e. instructions) that are executed at time of Object
creation.
Need of Constructor
Think of a Box. If we talk about a box class then it will have some class variables (say length,
breadth, and height). But when it comes to creating its object(i.e Box will now exist in
computer’s memory), then can a box be there with no value defined for its dimensions. The
answer is no.
So constructors are used to assign values to the class variables at the time of object creation,
either explicitly done by the programmer or by Java itself (default constructor).
When is a Constructor called ?
Each time an object is created using new() keyword at least one constructor (it could be default
constructor) is invoked to assign initial values to the data members of the same class.
A constructor is invoked at the time of object or instance creation.
Box Example :

/* Here, box uses a constructor to initialize the value dimensions of a box.


*/
Class Box {
double width;
double height;
double depth;
// This is the constructor for Box.
Box ( ) {
System.out.println(“Constructing Box”) ;
width= 10;
height =10;
depth = 10;
}
// compute and return volume
double volume ( ) {
return width*height*depth;
}
}
class BoxDemo {
public static void main (String srqs[] )
// declare, allocate, and initialize Box objects
Box mybox1 = new Box ( ) ;
Box mybox2 = new Box ( ) ;
double vol ;
// get volume of first box
vol = mybox1.volume( );
System.out.println(“Volume is” +vol);
}
}
When we run the programme we get the following results
Constructing Box
Constructing Box
Volume is 1000.0
Volume is 1000.0
Types of Constructor
In Java, constructors can be divided into 3 types:
1. No-Arg Constructor
2. Parameterized Constructor
3. Default Constructor

1. Java No-Arg Constructors


Similar to methods, a Java constructor may or may not have any parameters (arguments).
If a constructor does not accept any parameters, it is known as a no-argument constructor. For
example,
private Constructor() {
// body of the constructor
}
Example 2: Java private no-arg constructor
class Main {
int i;
// constructor with no parameter
private Main() {
i = 5;
System.out.println("Constructor is called");
}
public static void main(String[] args) {
// calling the constructor without any parameter
Main obj = new Main();
System.out.println("Value of i: " + obj.i);
}
}
Output:
Constructor is called
Value of i: 5
In the above example, we have created a constructor Main(). Here, the constructor does not
accept any parameters. Hence, it is known as a no-arg constructor.
Notice that we have declared the constructor as private.
Once a constructor is declared private, it cannot be accessed from outside the class. So,
creating objects from outside the class is prohibited using the private constructor.
Here, we are creating the object inside the same class. Hence, the program is able to access the
constructor.
However, if we want to create objects outside the class, then we need to declare the
constructor as public.
Example 3: Java public no-arg constructors
class Company {
String name;
// public constructor
public Company() {
name = "Programiz";
}
}
public class Main {
public static void main(String[] args) {
// object is created in another class
Company obj = new Company();
System.out.println("Company name = " + obj.name);
}
}
Output:
Company name = Programiz
2. Java Parameterized Constructor
A Java constructor can also accept one or more parameters. Such constructors are known as
parameterized constructors (constructor with parameters).
Example 4: Parameterized constructor
class Main {
String languages;
// constructor accepting single value
Main(String lang) {
languages = lang;
System.out.println(languages + " Programming Language");
}

public static void main(String[] args) {


// call constructor by passing a single value
Main obj1 = new Main("Java");
Main obj2 = new Main("Python");
Main obj3 = new Main("C");
}
}
String languages;
// constructor accepting single value
Main(String lang) {
languages = lang;
System.out.println(languages + " Programming Language");
}
public static void main(String[] args) {
// call constructor by passing a single value
Main obj1 = new Main("Java");
Main obj2 = new Main("Python");
Main obj3 = new Main("C");
}
}
Output:
Java Programming Language
Python Programming Language
C Programming Language
In the above example, we have created a constructor named Main(). Here, the constructor
takes a single parameter. Notice the expression,
Main obj1 = new Main("Java");
Here, we are passing the single value to the constructor. Based on the argument passed, the
language variable is initialized inside the constructor.

3. Java Default Constructor


If we do not create any constructor, the Java compiler automatically create a no-arg constructor
during the execution of the program. This constructor is called default constructor.
Example 5: Default Constructor
class Main {

int a;

boolean b;

public static void main(String[] args) {

// A default constructor is called

Main obj = new Main();

System.out.println("Default Value:");

System.out.println("a = " + obj.a);

System.out.println("b = " + obj.b);

Output:

a=0

b = false
Here, we haven't created any constructors. Hence, the Java compiler automatically creates the
default constructor.

There are many differences between constructors and methods. They are given below.

Java Constructor Java Method

A constructor is used to initialize the state A method is used to expose the behavior
of an object. 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 The method is not provided by the
constructor if you don't have any compiler in any case.
constructor in a class.

You might also like