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.

The class name should be the same as the file name (case-sensitive).
 
Syntax:
 
class ClassName
{
    // Class body
}
 
Java Main Method
 
The 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.
 
Syntax :Main Method
 
public static void main(String[] args)

------------------end the Java Program Structure----------------------


Java Tokens
 
In Java, a **token** is the smallest element of a program that is meaningful to the compiler. Tokens are the building blocks of Java code. When you write Java code, the compiler breaks it down into these tokens to understand and process it. Java has several types of tokens:

Types of Tokens in Java

1. Keywords
2. Identifiers
3. Literals
4. Operators
5. Separators
6. Comments

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 :
 
class MyClass 
{
        public static void main(String[ ] args) 
        {
            int number = 10; // 'int' and 'public' are keywords
        }
}


2. Identifiers
 
Definition : Identifiers are names given to various program elements such as variables, classes, methods, and arrays. An identifier must begin with a letter (A-Z or a-z), a currency symbol (`$`), or an underscore (`_`). Subsequent characters can include digits (0-9).

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 :
 
class MyClass 
{
      int myVariable = 10;
      String myName = "Java";
  }


3. Literals
 
Definition : Literals are fixed values that appear directly in the code. Java supports several types of 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 :
 
int number = 100;            // Integer literal
double pi = 3.14;            // Floating-point literal
char letter = 'A';           // Character literal
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:

  1. Arithmetic Operators            :    `+`, `-`, `*`, `/`, `%`
  2. Relational Operators             : `==`, `!=`, `<`, `>`, `<=`, `>=`
  3. Logical Operators                  : `&&`, `||`, `!`
  4. Bit-wise Operators                 : `&`, `|`, `^`, `~`, `<<`, `>>`
  5. Assignment Operators           : `=`, `+=`, `-=`, `*=`, `/=`
  6. Increment/Decrement Operators: `++`, `--`
  7. Conditional Operator (Ternary Operator): `? :`

Examples :
 
int a = 5;
int b = 10;
int sum = a + b;  // '+' is an arithmetic operator
boolean isEqual = (a == b);  // '==' is a relational operator
boolean isTrue = (a < b) && (b > 0);  // '&&' is a logical operator

5. Separators

Definition : Separators are symbols used to separate code elements in Java. These include:
 
  1. Parentheses    : `( )`
  2. Braces             : `{ }`
  3. Brackets         : `[ ]`
  4. Semicolon       : `;`
  5. Comma           : `,`
  6. Period             : `.`

Usage:
 
class MyClass 
{
    public static void main(String[ ] args) 
    {
        int[ ] array = {1, 2, 3};  // Braces '{ }' and semicolon ';' as separators
          System.out.println(array[0]); // Parentheses '( )', brackets '[]', and period '.' as separators
      }
  }


6. Comments :
 
Definition: Comments are used to annotate the code and are ignored by the compiler. Comments can be single-line or multi-line.

Single-line comments: Start with `//` and go to the end of the line.

Multi-line comments: Start with `/*` and end with `*/`.

Examples:
 
class MyClass 
{
    public static void main(String[] args) 
    {
        // This is a single-line comment
        System.out.println("Hello, World!"); /* This is a multi-line comment */
      }
}

Java Keywords

Java keywords are reserved words that have a predefined meaning in the Java language. These keywords are integral to the syntax and structure of Java programs, and they cannot be used as identifiers (names for variables, classes, methods, etc.). Each keyword serves a specific purpose and contributes to the flow and logic of the code.

### 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

Popular posts from this blog

digital marketing ppt-u1

SOFTWARE

cn lab

Computer Operations and Performing - D L Unit-1-1

DBMS Degree Lab Records

DS-Record-mca-04) write a program for evaluating a given postfix expression using stack.

Java unit-1 history , C++ vs Java , java environment

Access the Internet to Browse Infromation & E-Mail Operation- D L Unit-2-1

OAT-Record-01) Visiting card