- Blocks and Methods in Java
- Blocks in Java
- Static Block
- Non-static Block
- Methods in Java
- Predefined Methods
- User-defined methods
- How to Define a Code Block in Java
- How to Define a Code Block in Java?
- Example 1: Defining a Code Block in Java With a Single Statement
- Example 2: Defining a Code Block With Multiple Statements Comprising Multiple Data Types in Java
- Example 3: Defining a “Static” Code Block in Java
- Example 4: Defining a “Nested” Code Block in Java
- Example 5: Defining a “Function(Code Block)” and Invoking it in the “main()(Code Block)” in Java
- Conclusion
- About the author
- Umar Hassan
- Walking Techie
- Categories
- Wednesday, October 24, 2018
- Block of code in Java
- Recommended Posts:
Blocks and Methods in Java
After learning about the data types in Java, this article is all about blocks and methods in Java. We will discuss the types of blocks and see how methods work in Java. By the end of this article, you will be able to write and call a method.
Blocks in Java
Block refers to a set of statements inside 2 curly braces (one opening ‘ and one closing “>” ). Java supports 2 types of blocks. They are:
Static Block
-
- If the block of code is declared with the static keyword, it is called Static Block in Java.
- We know that the main method is the point where JVM starts program execution. But the static block is always executed before the main method.
- A static block only executes for a single time for the life cycle of the program.
Non-static Block
-
- If you declare a block without any static keyword, then it is a Non-Static Block.
- Non-static blocks are executed before the constructor is called by the user.
- A non-static may execute n number of times as it depends upon the user.
package test; public class JavaBlocks < //a static block static < System.out.println("This is a static block"); >//constructor JavaBlocks() < System.out.println("This is the constructor of JavaBlocks"); >//non static block < System.out.println("This is a non static block"); >public static void main(String[] args) < System.out.println("This is the main method 1"); JavaBlocks obj1=new JavaBlocks(); //creation of object of the class to instantiate the constructor JavaBlocks obj2=new JavaBlocks(); >>
In the above output, you can see that a static block is executed only once and before the main() method. But non-static block can be executed many numbers of times depending upon object creation.
Methods in Java
- A method in Java is a set of instructions that perform a specific task.
- It is a special type of block that has a name and a set of arguments.
- A method may or may not have a return type. Some methods return a value whereas some do not return any value.
- There are 2 types of methods in Java:
- Predefined methods
- User-defined methods
Predefined Methods
- Predefined methods are already present in Java and readily available for use. The best examples are the main method and the print method.
public static void main(String[] args) <>
- There are several predefined methods available for the String class, Math class, Array class, Integer class, etc.
User-defined methods
- The programmer can create and define methods as per his needs.
- Java provides this facility to support user-defined methods for an easier and better approach.
- The syntax to declare a user defined method in Java:
- access_modifier : It describes the scope of the method.
- return_type : This is the data type of the return value of the method. If the method does not return any value, then the return type must be void.
- method_name : This is the name of the method.
- list_of_arguements : This is the list of parameters define what type of variables the method will operate on. The type, order, and the number of parameters of a method differentiate.
Refer to the below program to have a clear understanding of user-defined methods.
package test; public class JavaMethods < //method returns a value of type int public int addition(int a, int b) < return (a+b); >//method returning no values- (void) datatype public void display() < System.out.println("This method does not return any value."); >public static void main(String[] args) < JavaMethods obj1 = new JavaMethods(); /* the method addition is called and the return value is assigned to a variable of type int *which is same as the return type of the method. */ int add=obj1.addition(10, 30); System.out.println("The output of addition method is "+ add); /*The void method display is called. This does not return any value. So it cannot be assigned to any variable */ obj1.display(); >>
In this article, we saw how to define write and call methods and how to use blocks for performing various tasks in Java. The main significance of using methods is “reusing the methods”. You can write a method once and reuse it every single time you want to execute that functionality.
In my next article, I will give a detailed description of the packages in Java. We will learn about the different types of packages available. And what the packages hold within them.
How to Define a Code Block in Java
Defining a code block in Java is essential to implement the desired functionalities and refrain from code limitations. These code blocks can be “nested” and “static” as well to reduce the overall code complexity and streamline the access of the accumulated code blocks, respectively at the programmer’s end. Also, these code blocks assist in differentiating the maintaining the scope of the contained functionalities.
This article will elaborate on defining a “code block” in Java.
How to Define a Code Block in Java?
A code block is defined with the help of the “curly braces ” and contains a section of code in it. This code can comprise one or multiple statements.
Example 1: Defining a Code Block in Java With a Single Statement
In this example, a code block can be defined with a single accumulated statement:
In this code, simply define a code block via curly braces, i.e., “ ” and contain a single statement indicating the initialization of an integer.
Note: This code block cannot yield any outcome since the value is initialized but not printed.
Example 2: Defining a Code Block With Multiple Statements Comprising Multiple Data Types in Java
This example can be utilized to define a code block having multiple statements of various data types:
public class definingcode {
public static void main ( String args [ ] ) {
int value1 = 5 ;
double value2 = 2.3 ;
char value3 = ‘a’ ;
String value4 = «John» ;
System . out . println ( «The integer value is: » + value1 ) ;
System . out . println ( «The double value is: » + value2 ) ;
System . out . println ( «The character value is: » + value3 ) ;
System . out . println ( «The string value is: » + value4 ) ;
} }According to this code snippet, likewise, define a code block and initialize the values comprising “integer”, “double”, “char”, and “String” data types, respectively, and print them individually.
In this output, it can be analyzed that the initialized values are displayed accordingly.
Example 3: Defining a “Static” Code Block in Java
In this particular example, a “static” code block can be defined within the class.
Note: The static blocks can be invoked with the help of the “class” directly regardless of the created class object.
Now, let’s move on to the below-provided example:
class staticClass {
static int a ;
static {
a = 10 ;
} }
public class definingcode2 {
public static void main ( String args [ ] ) {
System . out . println ( staticClass. a ) ;
} }In the above code block, perform the below-provided steps:
- Define a class named “staticClass”.
- In its definition, specify the static integer variable.
- Now, define a “static” code block initializing the value of the specified variable.
- Lastly, in the “main()” method, invoke the defined integer via the “class” directly.
In this outcome, it can be seen that the defined value is invoked appropriately.
Example 4: Defining a “Nested” Code Block in Java
In this particular example, a nested code block can be defined within a code block:
public class definingcode3 {
public static void main ( String args [ ] ) {
int value1 = 2 ;
int value2 = 3 ;
{
System . out . println ( «The multiplication of the values is: » + ( value1 * value2 ) ) ;
}
} }In the above lines of code, similarly, define a code block. Within this block, initialize the stated two integer values. After that, return the multiplication of the initialized values in another “nested” code block.
As observed, the nested code block functions properly.
Example 5: Defining a “Function(Code Block)” and Invoking it in the “main()(Code Block)” in Java
Here, a function can be defined in a code block and invoked in a separate code block in the “main()” method:
public class definingcode4 {
public static void displayMultiplication ( int a, int b ) {
int c = a * b ;
System . out . println ( «The multiplication becomes: » + c ) ;
}
public static void main ( String args [ ] ) {
displayMultiplication ( 3 , 2 ) ;
} }In the above code snippet:
- Define a code block and declare a function named “displayMultiplication()”.
- In its parameters, specify the variables that need to be multiplied.
- In the function definition, multiply the passed numbers and store the resultant multiplication in a separate variable, i.e., “c”.
- Finally, in the “main()” method, define a code block, invoke the defined function, and pass the stated integers, as its argument.
This outcome signifies that the multiplication is returned appropriately.
Conclusion
A code block in Java is defined with the help of “curly braces ” and contains a section of code in it. This code can contain one or multiple statements. Also, a nested code block and separate code blocks for function and the “main()” method can be defined. This blog demonstrated to define a code block in Java.
About the author
Umar Hassan
I am a Front-End Web Developer. Being a technical author, I try to learn new things and adapt with them every day. I am passionate to write about evolving software tools and technologies and make it understandable for the end-user.
Walking Techie
Blog about Java programming, Design Pattern, and Data Structure.
Categories
Wednesday, October 24, 2018
Block of code in Java
Java allows two or more statements to be grouped into blocks of code, also called code blocks. This is done by enclosing the statements between the open and closed curly braces.
- Every block of code in Java start with open curly brace < and ends with close curly brace >.
- There is no limit of statement inside the block of code.
- There is no restriction on the number of blocks inside a block and level of nesting the block, means blocks can be nested and can be included inside any other block.
- Block of code in Java is commonly used in if statement, for loop, and while loop.
- All classes and methods contents are inside the blocks.
- Indent Java code inside the block of code, so it will help in resolving the compile time errors faster and make the code more readable.
For example, a block can be java’s if and for statements.
Consider the block of if statement:
Here, if x is less than y then statements inside the curly braces (block of code) will be executed. Mostly in real time application, you will write block of code. It creates logical unit, and one statement can’t execute without the other statement also executing.
Consider the block of for loop:
Here, x, and y are loop control variable in initialisation portion of for loop. You can declare and initialise multiple loop control variables by comma-separated.
/* Demonstrate the block of code. Call this file as BlockOfCodeDemo.java compile: javac BlockOfCodeDemo.java Run: java BlockOfCodeDemo */ public class BlockOfCodeDemo < public static void main(String[] args) < int x, y; x = 10; y = 20; // block of if statement: // swap the value of x and y if (x < y) < int temp = x; x = y; y = temp; >System.out.println("Value of x:: " + x); System.out.println("Value of y:: " + y); // block of for statement: // Value of x is increased by 1 and value of y is decreased by 2 // in every loop iteration for (x = 10, y = 20; x < y; x++) < System.out.println("Value of x in for loop:: " + x); System.out.println("Value of y in for loop:: " + y); y = y - 2; >> >
When you run this program. output of this program shown below.
Value of x:: 20 Value of y:: 10 Value of x in for loop:: 10 Value of y in for loop:: 20 Value of x in for loop:: 11 Value of y in for loop:: 18 Value of x in for loop:: 12 Value of y in for loop:: 16 Value of x in for loop:: 13 Value of y in for loop:: 14
Recommended Posts: