java program structure,java Tokens, keywords,
java program structure
Java program may contain many classes of which only one class define a main method. Class contain data members and methods that operate on the data members of the class.
Documentation Section
In Java, comments are used to annotate code and are ignored by the compiler. Java supports two types of comments: single-line and multi-line comments.
1.Single-Line Comments
Syntax: Single-line comments start with `//` and continue to the end of the line.
Use Case: Ideal for brief explanations or notes that occupy only one line.
Example:
class MyClass
{
public static void main(String[] args)
{
int number = 10; // This is a single-line comment
System.out.println(number); // Output the number
}
}
2. Multi-Line Comments
Syntax: Multi-line comments start with `/*` and end with `*/`. They can span multiple lines.
Use Case: Useful for longer explanations, notes, or temporarily commenting out blocks of code.
Example:
class MyClass {
public static void main(String[] args) {
/*
* This is a multi-line comment.
* It can span multiple lines.
* Useful for detailed explanations.
*/
int number = 10;
System.out.println(number);
}
}
In this example, the multi-line comment provides a more detailed explanation, which might be too long for a single line.
When to Use Which Type
Single-line comments
best for short notes, like clarifying a single statement or marking something that needs attention.
Multi-line comments
better for providing detailed descriptions, such as explaining a complex section of code, or when you need to comment out a block of code for debugging purposes.
Package Declaration (Optional)
If your class belongs to a package, you declare it at the top of your Java file.
Syntax:
package packageName;
Example:
package com.example.myapp;
Import Statements (Optional)
Used to import other Java classes or packages that you need in your program.
Syntax:
import java.test.*;
Example:
import java.util.Scanner;
Interface Statements
In Java, an interface is a reference type, similar to a class, that can contain only constants, method signatures, default methods, static methods, and nested types. Interfaces cannot contain instance fields, and their methods do not have a body (except for default and static methods). Interfaces are used to specify what a class must do, but not how it does it.
Class Declaration
class is the fundamental building block of a Java program. Every Java program must have at least one class.
// Class body
}
main
method in Java is a special method that serves as the entry point for any standalone Java application. When you run a Java program, the Java Virtual Machine (JVM) looks for this method to start the execution of the program.Types of Tokens in Java
1. Keywords
1. Keywords
Definition : Keywords are reserved words in Java that have a predefined meaning in the language. These cannot be used as identifiers (names for variables, classes, methods, etc.).
Examples :
- `int`
- `class`
- `if`
- `else`
- `public`
- `return`
- `static`
Usage :
public static void main(String[ ] args)
int number = 10; // 'int' and 'public' are keywords
}
2. Identifiers
Examples :
Variable names: `myVariable`, `age`
Class names: `MyClass`, `Student`
Method names: `calculateSum`, `getName`
Rules :
Cannot start with a digit.
Cannot be a keyword.
Case-sensitive: `myVariable` and `MyVariable` are different identifiers.
Usage :
int myVariable = 10;
String myName = "Java";
}
3. Literals
Integer Literals: Whole numbers, e.g., `10`, `0`, `-15`
Floating-point Literals: Decimal numbers, e.g., `3.14`, `0.5`, `-2.7`
Character Literals: Single characters, e.g., `'a'`, `'Z'`, `'1'`
String Literals: Sequences of characters, e.g., `"Hello"`, `"Java"`
Boolean Literals: `true` or `false`
Null Literal: `null`
Examples :
String greeting = "Hello"; // String literal
boolean isJavaFun = true; // Boolean literal
Object obj = null; // Null literal
4. Operators
Definition : Operators are symbols that perform operations on variables and values. Java supports several types of operators:
- Arithmetic Operators : `+`, `-`, `*`, `/`, `%`
- Relational Operators : `==`, `!=`, `<`, `>`, `<=`, `>=`
- Logical Operators : `&&`, `||`, `!`
- Bit-wise Operators : `&`, `|`, `^`, `~`, `<<`, `>>`
- Assignment Operators : `=`, `+=`, `-=`, `*=`, `/=`
- Increment/Decrement Operators: `++`, `--`
- Conditional Operator (Ternary Operator): `? :`
Examples :
5. Separators
Definition : Separators are symbols used to separate code elements in Java. These include:
- Parentheses : `( )`
- Braces : `{ }`
- Brackets : `[ ]`
- Semicolon : `;`
- Comma : `,`
- Period : `.`
Usage:
System.out.println(array[0]); // Parentheses '( )', brackets '[]', and period '.' as separators
}
}
6. Comments :
Single-line comments: Start with `//` and go to the end of the line.
Multi-line comments: Start with `/*` and end with `*/`.
Examples:
System.out.println("Hello, World!"); /* This is a multi-line comment */
}
### List of Java Keywords
Java has a total of 52 reserved keywords (as of Java 17), which are divided into several categories based on their usage:
1. **Data Type Keywords**
2. **Control Flow Keywords**
3. **Access Modifiers**
4. **Class, Method, and Variable Keywords**
5. **Exception Handling Keywords**
6. **Package and Import Keywords**
7. **Concurrency Keywords**
8. **Other Keywords**
### 1. Data Type Keywords
These keywords are used to define data types in Java.
- **`byte`**: Defines an 8-bit integer.
- **`short`**: Defines a 16-bit integer.
- **`int`**: Defines a 32-bit integer.
- **`long`**: Defines a 64-bit integer.
- **`float`**: Defines a 32-bit floating-point number.
- **`double`**: Defines a 64-bit floating-point number.
- **`char`**: Defines a 16-bit Unicode character.
- **`boolean`**: Defines a boolean value (`true` or `false`).
- **`void`**: Specifies that a method does not return any value.
### 2. Control Flow Keywords
These keywords control the flow of execution within a program.
- **`if`**: Starts a conditional statement.
- **`else`**: Provides an alternative block of code if the `if` condition is false.
- **`switch`**: Allows variable values to be compared against a set of constants.
- **`case`**: Defines a branch in a `switch` statement.
- **`default`**: Specifies the default branch in a `switch` statement.
- **`while`**: Starts a loop that continues while a condition is true.
- **`do`**: Used with `while` to create a loop that executes at least once.
- **`for`**: Starts a loop that iterates a fixed number of times.
- **`break`**: Exits a loop or `switch` statement.
- **`continue`**: Skips the current iteration of a loop and continues with the next iteration.
- **`return`**: Exits from the current method and optionally returns a value.
### 3. Access Modifiers
These keywords define the access level for classes, methods, and variables.
- **`public`**: The member is accessible from any other class.
- **`protected`**: The member is accessible within its own package and by subclasses.
- **`private`**: The member is accessible only within its own class.
- **`default`** (no modifier): The member is accessible only within its own package.
4. Class, Method, and Variable Keywords
These keywords are used to define classes, methods, and variables.
`class`: Declares a class.
`interface`: Declares an interface.
`enum`: Declares an enumerated type.
`extends`: Indicates that a class is inheriting from a superclass.
`implements`: Indicates that a class is implementing an interface.
`static`: Defines a class-level method or variable (shared among all instances).
`final`: Defines constants, prevents method overriding, or inheritance.
`abstract`: Defines an abstract class or method.
`synchronized`: Used for threads to ensure that only one thread accesses the resource at a time.
`volatile`: Indicates that a variable may be changed unexpectedly, and ensures visibility of changes across threads.
`transient`: Prevents serialization of a field.
`native`: Specifies that a method is implemented in native code using JNI (Java Native Interface).
`strictfp`: Ensures floating-point calculations adhere to IEEE 754 standards.
5. Exception Handling Keywords
These keywords handle exceptions and errors in Java.
`try`: Defines a block of code that might throw an exception.
`catch`: Handles the exception thrown by the `try` block.
`finally`: Defines a block of code that executes after the `try` block, regardless of whether an exception was thrown.
`throw`: Used to explicitly throw an exception.
`throws`: Declares exceptions that a method can throw.
6. Package and Import Keywords
These keywords manage the organization and access of classes.
`package`: Declares a package, which is a namespace for organizing classes and interfaces.
`import`: Imports other Java classes or entire packages so they can be used in the current class.
7. Concurrency Keywords
These keywords are used in the context of multithreading and concurrency.
`synchronized`: Ensures that only one thread can execute a block of code at a time.
`volatile`: Indicates that a variable's value will be modified by different threads.
8. Other Keywords
These keywords serve various special purposes in Java.
`this`: Refers to the current object instance.
`super`: Refers to the superclass of the current object.
`instanceof`: Tests whether an object is an instance of a specific class or subclass.
`new`: Creates new objects.
`return`: Exits from a method and optionally returns a value.
`null`: Represents the null reference (no object).
`assert`: Used for debugging purposes to make assertions.
`goto`: Reserved but not used in Java.
`const`: Reserved but not used in Java.
Keywords Introduced in Later Java Versions
var (Java 10): Used for local variable type inference, where the compiler automatically determines the type of the variable.
yield (Java 13): Used in switch expressions to return a value.
record (Java 14): Used to define a new type of class that holds immutable data.
sealed , permits (Java 17): Used to restrict which classes can extend or implement a class or interface.
Special Note
const and goto : These are reserved words but are not used in Java. They were reserved for future use but remain unused.
Comments
Post a Comment