Using Blocks of Code
By: aathishankaran Printer Friendly Format
Using Blocks of Code
Java allows two or more statements to be grouped into bocks of code, also called code blocks. Enclosing the statements between opening and closing curly braces does this. Once a block of code has been created, it becomes a logical unit that can be used any place that a single statement can. For example, a block can be target for java’s if and for statements. Consider this if statement:
if( x < y ){
x = y;
y = 0;
}
Here, if x is less than y, then both statements inside the block will be executed. Thus, the two statements inside the block form a logical unit, and statement cannot execute without the other also executing. The key point here is that whenever you need to logically link two or more statements, you do so by creating a block.
Let’s look at another example. The following program uses a block of code as the target of a for loop.
/*
Demonstrate a block of code.
Call this file “BlockTest.javaâ€
*/
class BlockTest {
public
static void main (String args[]) {
int x,
y;
y=20;
for (
x= 0; x<10; x++) {
System.out.println(“This
is x: “ + x);
System.out.println(“This
is y: “ + y);
Y =
y-2;
}
}
}
The output generated by this program is shown here:
This is x: 0
This is y: 20
This is x: 1
This is y: 18
This is x: 2
This is y: 16
This is x: 3
This is y: 14
This is x: 4
This is y: 12
This is x: 5
This is y: 10
This is x: 6
This is y: 8
This is x: 7
This is y: 6
This is x: 8
This is y: 4
This is x: 9
This is y: 2
In this case, the target of the for loop is a block of code and not just a single statement. Thus, each time the loop iterates, the three statements inside the block will be executed. This fact is, of course, evidenced by the output generated by the program
As you will see later in this book, blocks of code have additional
properties and uses. However, the main reason for their existence is to create
logically inseparable units of code.
Comment on this tutorial
- Data Science
- Android
- AJAX
- ASP.net
- C
- C++
- C#
- Cocoa
- Cloud Computing
- HTML5
- Java
- Javascript
- JSF
- JSP
- J2ME
- Java Beans
- EJB
- JDBC
- Linux
- Mac OS X
- iPhone
- MySQL
- Office 365
- Perl
- PHP
- Python
- Ruby
- VB.net
- Hibernate
- Struts
- SAP
- Trends
- Tech Reviews
- WebServices
- XML
- Certification
- Interview
categories
Subscribe to Tutorials
Related Tutorials
Program using concept of byte long short and int in java
Update contents of a file within a jar file
Tomcat and httpd configured in port 8080 and 80
Count number of vowels, consonants and digits in a String in Java
Student marks calculation program in Java
Calculate gross salary in Java
Calculate average sale of the week in Java
Vector in Java - Sample Program
MultiLevel Inheritance sample in Java