Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

semicolon in java

 a Semicolon (;) is used to separate statements in a program. Each Statement in a Java program must end with a semicolon, just like in many other programming languages.

Here's an example of  semicolon in a Java program:

int x = 5; // Declare a variable and assign a value

System.out.println(x); // Print the value of the variable

x++; // Increment the value of the variable

System.out.println(x); // Print the new value of the variable

In this example, there are three statements: one for declaring a variable and assigning a value, one for printing the value of the variable, and one for incrementing the value of the variable. Each statement ends with a semicolon, which separates them from each other.

It's worth noting that, in Java, a semicolon is not always necessary. For example, if you are defining a class or method, you don't need to use a semicolon at the end of the definition. Also, you don't need to use a semicolon after a block statement (statements enclosed in curly braces {}) that is part of a control statement such as if-else, while, for, etc. The end of the block statement is represented by the closing curly brace.

In the case of a single-line if statement or a single-line loop, you can also omit the curly braces {} and write the statement directly after the if or while keyword, respectively.

if(x==5) System.out.println("x is 5");

while(x

In summary, a semicolon is used in Java to separate statements and mark the end of a statement. However, it's not always required and depends on the context of the statement or block.

It's worth noting that in Java, a semicolon is also used in certain control statements such as the "for" loop and the "enhanced for" (or "for-each") loop.

In a "for" loop, the initialization, condition, and increment/decrement statements are separated by semicolons. 


In this example, the initialization statement "int i = 0" is executed once before the loop starts, the condition "i

In the case of the "enhanced for" loop, the semicolon is used to separate the loop variable and the array or collection that is being iterated over.



This post first appeared on Java Tutorial - InstanceOfJava, please read the originial post: here

Share the post

semicolon in java

×

Subscribe to Java Tutorial - Instanceofjava

Get updates delivered right to your inbox!

Thank you for your subscription

×