Java Syntax and Structure with Examples
1. Java Program Structure (Classes and Methods)
Understanding Java Classes
- A class is a blueprint for creating objects in Java. Here’s a simple example of a Java class:
- In this example,
MyFirstClass
is a Java class,number
is a variable, anddisplayNumber
is a method that prints the value ofnumber
.
- A class is a blueprint for creating objects in Java. Here’s a simple example of a Java class:
The Main Method
- The
main
method is the entry point for any Java application. Here’s a simple "Hello, World!" program: - In this code,
public static void main(String[] args)
is the main method, where execution starts.System.out.println("Hello, World!");
prints text to the console.
- The
Creating and Calling Methods
- Methods allow us to break down code into smaller, reusable parts. Here’s an example with method declaration and invocation:
- Here,
add
is a method that takes two parameters (int a
andint b
), adds them, and returns the sum. Themain
method callsadd
, and the result is printed.
- Methods allow us to break down code into smaller, reusable parts. Here’s an example with method declaration and invocation:
2. Comments in Java
- Single-line Comments (
//
) - Multi-line Comments (
/* ... */
) - Documentation Comments (
/** ... */
)- Documentation comments like these are used for creating JavaDocs.
3. Java Statements
- Example of Variable Declaration and Assignment Statements
- Syntax Rules
- Every statement ends with a semicolon (
;
). Code blocks are wrapped in braces ({}
). For example:
- Every statement ends with a semicolon (
4. Java Keywords
Common Keywords Example
- Here,
public
,class
,static
,void
,int
, andfinal
are keywords.
- Here,
Reserved Words in Java
- Words like
new
,if
,else
,switch
, etc., are reserved in Java and cannot be used as variable names. Here’s an example usingif
andelse
:
- Words like