Motombo
Motombo

Reputation: 1787

Using {} brackets after statement in Java, will this cause problems ever?

I just started learning java ( I come from Javascript and PHP) about two days ago and I am reading my textbook, and noticed that my textbook always has a class of the form say

public class BankAccount
{
    private double balance;
    public BankAccount()
    {
        balance = 0;
    }
    // some other code here...
}

I.E notice how the brackets are on different lines.

Now lets take a look at something in javascript

function getPerson(){
    return
            {
                firstname: 'Tony'
            }

}

console.log(getPerson());

Here the Javascript engine says "Hey, since we put those brackets on another line after return I'm just gonna automatically insert a semicolon after return". As a result some of the books ive read on js say to just put the squiggly brackets on the same line to ever avoiding this. Thus logging undefined

My Question

Does something like this ever happen in Java? I'm wondering since my book so far just puts the squiggly on different lines, if this automatic semi colon thing could mess me up.

;

Upvotes: 0

Views: 80

Answers (3)

Olivier
Olivier

Reputation: 873

Java is not like Javascript. In Java, semi-colons at the end of statement are compulsory. Moreover, Java will never add semi-colon automatically for whatever reasons.

Writing:

public class BankAccount
{
}

or

public class BankAccount {
}

is just a matter of convention. Both are strictly the same from the parser's point of view. Do what whatever your programming convention tells you to do. Just be consistent within a project.

Same goes for function declaration.

Upvotes: 2

m_callens
m_callens

Reputation: 6360

If you're asking if you need to put a semicolon after method declarations in Java then no, you do not. I cannot think of a case in Java where you do put semicolon after a pair of {}.

Upvotes: 0

Magnus
Magnus

Reputation: 8300

Java does not have semicolon insertion like JavaScript does. You can split a statement over as many lines as you like, but it must eventually be terminated with a semicolon.

Upvotes: 0

Related Questions