BlackThorn
BlackThorn

Reputation: 13

Which type of commands need to end with a semicolon(;)?

I am learning Java and can write a lot of programs but something that I haven't really understood is which type of commands need to end with a semicolon ;.
I enter them mechanically but I want to learn where exactly they are needed.
For example, import java.util.Scanner; needs a semicolon ; at the end but public static void main(String[] args) doesn't, although it is actually where the program starts, right?

Upvotes: 1

Views: 1240

Answers (3)

Sanjeev Sachdev
Sanjeev Sachdev

Reputation: 1321

All the non-block statements must end with a semicolon -- ;

Block statments are enclosed within curly braces -- {}

import java.util.Scanner; is a non-block statement.

public static void main(String[] args){
 System.out.println("Hello World !");
}

is a block statement that contains one non-block statement.

Reading through the topic Expressions, Statements, and Blocks at Oracle's Java tutorial will be helpful in understanding the use of semicolon ; in a Java program.

Upvotes: 0

IFebles
IFebles

Reputation: 338

The semicolon (;) needs to be used at the end of every statement different from a block declaration, e.g:

int variable;
System.out.println("Io");

public static void main(String[] args) is a method with a body ({}), fully declared as such:

public static void main(String[] args)
{

}

Which is a block.

The String[] args part is a declaration, but it's a parameter declaration, which doesn't need the semicolon (;) since its purpuse is to "finish" a statement, and in this case is a method (block).

Upvotes: 1

Azog the Debugger
Azog the Debugger

Reputation: 227

Every command needs a semicolon (';') at the end so the program knows that this is the end of the command, sometimes you need to stretch a command over more than one line so the semicolon comes at the end of the last line of this command.

public static void main(String[] args) is a method. Methods conatin more commands and to differ what commands are in which method you surrond the commands with {and }. If you only worked with main so far you won't notice it as much but methods save you a lot of work. Instead of writing:

public static void main(String[] args)
{
    System.out.println("One");
    System.out.println("Two");
    System.out.println("Three");
    System.out.println("One");
    System.out.println("Two");
    System.out.println("Three");
}  

You can write another method and then call that, like this:

public static void prinNumbers()
{
    System.out.println("One");
    System.out.println("Two");
    System.out.println("Three");
}  

This is a method that you now can call in main. Remember calling the method is a command and needs a semicolon.

public static void main(String[] args)
{
    printNumbers();
    printNumbers();
}

I hope I could help you, you can find some more information about methods right here

Upvotes: 1

Related Questions