In Java , methods , blocks and constructors serve basic purposes in structuring and executing code within a class .
- Method:
Method is a member of a class which is used for representing the behaviors of an object,any funtionality or operation . It is a collection of statements grouped together to perform a specific operation .
Methods can be invoked explicitly using the dot ( . ) operator on a object or class (for static methods ) .
Syntax:
<Modifiers > <Methodreturn type > <Method Name > ( Method Parameters ) {
Body of the method
}
Classification of Methods :
- Instance Method
- Static Method
- Instance Method : Method declaration without static modifier is known as instance method . Any instance method allocate memory at the time of object creation if it is called .
Example :
class Gift {
void display() {
System.out.println(“Gift is beautiful ” ) ;
}
}
In the above example , Gift class contains method named display () without a static modifier, so this display () method is an instance method .
2. Static Method : Method declaration with static modifier is known as static method . Static method allocates memory at the time of class loading if it is called .
Example :
class Gift{
static void display () {
System.out.println(“Gift is worthy “);
}
}
In the above example , The Gift class contains display () method with static modifier, so display () method is a static method which allocates memory at the time of class loading if it is called .
How to call a Method?
Both instance method and static method can be called in different different ways as explained below :
Example :
class Gift {
//static method
static void lastgift(){
System.out.println(“Last gift is even worthy “);
}
//instance method
void topgift() {
System.out.println(“Top gift is amazing “);
}
}
How to call instance Method?
- By reference variable which contains the actual object .
Gift g1 = new Gift () ;
g1.topgift();
Here , with the help of g1 reference variable which contains Gift class object , we are calling instance method topgift() of Gift class.
2. By using dynamic object :
Gift g2=new Gift ();
new Gift().topgift();
Here, we are calling instance method topgift() with the help of dynamic object new Gift() .
How to call Static Method ?
- By using the class name :
Gift.lastgift();
Here, we are calling static method lastgift() with the help of class name Gift.
2. By the reference variable which contains the actual object:
Gift g1=new Gift();
g1.lastgift();
Here, we are calling static method lastgift() with the help of reference variable g1.
3. By using the null reference variable :
Gift g=null;
g.lastgift();
Here, we are calling the static method lastgift() with the help of null reference variable g .
Members of Method :
1.Method Returntype
2. Method Parameters
- Method Returntype:
case1 : If we are accessing the result within the method itself and no need to call the result from method definition to the caller of the method , then we declare the method return type as void. Void is the default method return type which can’t return any value.
case2 : If inside the method, there are some resultant value after some operation and we need to access the result of the method in the caller of the method , then we need to provide compatible data type as a return type of the method.
Example :
class Add {
//declaring method sum with void as return type
void sum(){
int i1=18;
int i2=28;
int sum=i1+i2;
System.out.println(“Sum is :“+sum);
}
}
class Calculation{
public static void main(String args[] ){
//Creating an object of a Add class
Add a=new Add();
a.sum();
}
}
OUTPUT:
Sum is : 46
In the above example , we are declaring a method name sum with void as return type inside the class Add. As return type is void, this method is not returning any resultant value to the caller of the method . From main class Calculation, we are creating an object of Add class and call the method sum .
Example 2:
class Subtraction{
int subtract(int i1 , int i2){
int sub=i1-i2;
return sub;
}
}
class Calculation {
public static void main(String args[] ) {
Subtraction s= new Subtraction ();
int sub=s.subtract(28,10);
System.out.println(“Resultant value of subtraction is : ” + sub);
}
}
In the above example, we have created a method named subtract with return type as int. In the main class Calculation , we are creating an object of Subtraction class and we are calling the subtract method .
2. Method parameters :
Method parameters are known as method argument which is used for reusing the logic of the method for multiple set of input values while calling the same method many times .
Method parameters are classified into two types :
- Formal parameters
- Actual parameters
The parameters which we are defining while declaring the method is known as Formal parameters .
Example : void sum(int i1 , int i2 ){
}
The input values which we are providing while calling the method are known as actual values .
Example : sum(8,18);
NOTE :
While we are calling any method, there must be matching of formal parameters and actual parameters in terms of data type of the parameters , count of the parameters and order of the parameters .
JAVA BLOCKS:
Java block is a section of code enclosed in curly braces{ } . In Java code blocks are used to group one or more statements .
Java blocks are used for initializing the instance and static variables of a class in the next line .
Types of Blocks in Java:
The following are the types of blocks in Java.
- Static Block
- Instance Block
- Constructor Block
- Method Block
- Loop/Conditional Block
- Synchronized Block
- Static Block:
Static block in Java is a block which is used to initialize the static variables or logic when the class is loaded . This static block executes only once , even before the main() method is executed .
Static blocks are commonly used for setting up static resources , for loading configurations , or registering components . In a java class, multiple static blocks can be present and they execute in the order they appear in the code .
Example :
public class ExampleStaticBlock{
static{
System.out.println(“First static block executed “);
}
static{
System.out.println(“Second static block executed”);
}
public static void main(String args[] ) {
System.out.println(“Main method executed “);
}
}
OUTPUT :
First static block executed
Second static block executed
Main method executed.
2. Instance Initialization Block in Java :
An instance initialization Block is used to initialize instance variables before any constructor is executed . In Java, instance initialization Block runs everytime an object is created and it runs before before the constructor is executed.
public class ExampleInstanceBlock{
//Declaring instance block
{
System.out.println(“Instance block executed “);
}
//Declaring constructor
ExampleInstanceBlock() {
System.out.println(“Constructor executed “);
}
public static void main(String args[] ) {
ExampleInstanceBlock obj1=new ExampleInstanceBlock();
ExampleInstanceBlock obj2=new ExampleInstanceBlock();
}
}
OUTPUT :
Instance block executed
Constructor executed
Instance block executed
Constructor executed
Instance block basically used for sharing code across multiple constructors , in creation of logging object , for runtime validation or setup before object construction .
Constructor Block in Java:
Constructor blocks in java are the bodies of constructor that initializes instance variables or perform setup tasks when an object is created .
Constructor block executes after the instance block .
Example:
public class ExampleConstructorBlock{
//Creating constructor without arguments
ExampleConstructorBlock(){
System.out.println(“Constructor without arguments”);
}
//Creating constructor with arguments
ExampleConstructorBlock(String msg){
System.out.println(“Constructor with message:”+msg);
}
public static void main(String args[] ) {
ExampleConstructorBlock obj1= new ExampleConstructorBlock();
ExampleConstructorBlock obj2= new ExampleConstructorBlock(“Congrats!!you win“);
}
}
OUTPUT:
Constructor without arguments
Constructor with message : Congrats!!you win
Method Block in Java:
Method Block in Java is the body of a method enclosed within { } . Method Block contains logic that is executed when the method is called. Method blocks can contain variables , control statements , loops and calls to other methods .
Method blocks only execute when the method is explicitly called .
Example:
public class ExampleMethodBlock{
void gift(){
System.out.println(“Gift from method block”);
}
public static void main(String args[]){
ExampleMethodBlock obj1=new ExampleMethodBlock();
obj1.gift();
}
}
OUTPUT:
Gift from method block
Loop and Conditional Blocks in Java
Loop blocks (for, while , do-while) and conditional blocks(if,else,switch) use curly braces {} to group statements that execute repeatedly or under certain conditions . These Loop and Conditional Blocks allow for readable and structured control flow in a Java program .Variables declared inside these blocks are limited to the block’s scope , which enhance memory efficiency .
Loop and Conditional Blocks in Java are basically used for Decision-making logic , Iterating over collections or arrays , Validating user input
Example:
public class ExampleLoopConditionalBlocks{
public static void main(String args[]){
int num=3;
if(num%2==0){
System.out.println(“Even number”);
}
else{
System.out.println(“Odd number”);
}
for(int i=0;i<3;i++){
System.out.println(“For loop iteration:”+i);
}
}
}
OUTPUT:
Odd number
For loop iteration :0
For loop iteration:1
For loop iteration:2
Synchronized Block in Java
Synchronized block in java is used in multithreading programming to restrict access to a block of code so that only one thread at a time can execute that code which ensures thread safety when multiple threads try to access shared resources.
Synchronized Block in Java is used to prevent race conditions , to synchronize shared resources , to manage access to critical sections .
Execution Flow of Blocks in Java:
The different types of blocks in java are executed in a specific order during the lifecycle of a class and it’s objects .
The java block execution order, when a java program is executed is as follows:
1.Instance Initialization Block :
This block executes everytime an object is created, before the constructor .
2. Static Block:
Static block executes once when the class is loaded into memory before the execution of main() method .
3. Constructor Block :
This block executes after Instance initialization block during the object creation .
4.Method Block:
This block executes only when it is explicitly called after object creation .
JAVA CONSTRUCTOR:
Java constructor is a special member which is called when an object of the class is created . Constructor is used to initialize objects .
Basic characteristics of a Java Constructor :
- Same name as the class: A constructor must have the same name as the class to which it belongs to.
- Implicitly invoked : Constructor is called automatically when an object is instantiated, you don’t have to call constructor explicitly.
- No return type : Constructor don’t have any return type, not even void .
- Used for Initialization : The primary purpose of constructor is to initialise object , by assigning values to its instance variables .
- Can be overloaded : A class can contain multiple constructors , as long as each constructor have different parameter list which is known as constructor overloading
- Default constructor : If you don’t define any constructor explicitly in a class , the java compiler automatically providea a default , no-argument constructor . This default constructor initializes instance variables with their default values (e.g. , 0 for integers , null for objects ) .
