• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Couple of basic syntax questions

 
Aaron Betts
Greenhorn
Posts: 1
Chrome Eclipse IDE Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi!
Just diving into Java and am working through the exercises in Head First Java.

Couple of basic questions:
1. methods can be nested right?
2. I've learned that statements always have to end with a semi-colon, but this piece of code doesn't. Why? while (x < 5) {

Here is the source code (for context) with my questions in the comments.

 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 64721
86
IntelliJ IDE Java jQuery Mac Mac OS X
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
1. No.

2. (a) because the while statement (it's a statement, not a method) doesn't end until line 12, and (b) blocks do not need to be terminated with a semicolon.

If you used better indentation, the structure might be more apparent. Give it a try.
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15219
36
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

This is not a "nested method".

You can have a block of code enclosed in { and }. The while statement needs a block of code, the body of the loop.
 
Campbell Ritchie
Sheriff
Posts: 48652
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch

As you have already been told, you have only written the first part of the while loop; it must be followed by a single statement but you can susbtitute a block for that single statement. It is all in the Java Language Specification (JLS); here is the definition for Statement:You can see that while (line 10) is a kind of statement, and most but not all kinds of statement finish with semicolons. Block does not require a terminal semicolon, which would actually count as a new Statement. The JLS is by no means easy to understand, I am afraid.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic