Syntax of Writing Java Code
Syntax of Writing Java Code
Class Declaration:
A Java program starts with the declaration of a class. A class is a blueprint for creating objects. The class
declaration includes the class name, access modifier, and body.
java
Copy code
2 // class body
3}
2. Main Method:
The main method is the entry point of a Java program. It must be declared with
the public and static modifiers, and it must return void.
java
Copy code
2 // code to be executed
3}
3. Variables:
Variables are used to store data in a Java program. They can be declared using a data type followed by a
variable name.
java
Copy code
4. Data Types:
Primitive types: byte, short, int, long, float, double, char, boolean
5. Operators:
Arithmetic operators: +, -, *, /, %
Relational operators: <, >, <=, >=, ==, !=
Assignment operators: =, +=, -=, *=, /=, %=, <<=, >>=, &=, ^=, |=
6. Control Structures:
7. Methods:
Methods are used to perform specific tasks in a Java program. They can be declared with a name, return
type, and parameters.
java
Copy code
2 return a + b;
3}
Objects are instances of a class. They can be created using the new keyword.
java
Copy code
9. Inheritance:
Java supports inheritance, which allows a class to inherit the properties and methods of another class.
java
Copy code
2 // class body
3}
10. Interfaces:
Interfaces are used to define a contract for a class. They can be implemented using
the implements keyword.
java
Copy code
2 // class body
3}
11. Exceptions:
Java supports exception handling, which allows a program to handle errors and exceptions.
java
Copy code
1try {
3} catch (Exception e) {
5} finally {
7}
12. Packages:
Packages are used to organize related classes and interfaces into a single unit.
java
Copy code
1package mypackage;
Import statements are used to include classes and interfaces from other packages.
java
Copy code
1import java.util.ArrayList;
14. Comments:
java
Copy code
2/* multi-line
3comment */