topics content@scaler.com
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Versions and GitHub Sync Note Insights Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       owned this note    owned this note      
    Published Linked with GitHub
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    --- title: Structure of Java Program - Scaler Topics description: Learn about the structure of Java program and Java syntax by Scaler Topics. To get well-versed in any language, you must know its syntax and code structure. author: Sakhi Bhagwat category: Java --- :::section{.main} Java, initially named Oak, was created by James Gosling for Sun Microsystems in 1991 and later acquired by Oracle. Renamed Java symbolizes James Gosling, Arthur Van Hoff, and Andy Bechtolsheim. Java follows the "Write Once, Run Anywhere" principle as an object-oriented, platform-independent language, compiling code into bytecode. JVM translates bytecode into machine code for execution, enabling Java programs to operate seamlessly across diverse systems. It is essential to understand the structure of java program. With a defined syntax, Java ensures portability, security, and ease of debugging, embodying high-level language principles. [IMAGE {1} {} START SAMPLE] https://static.javatpoint.com/core/images/structure-of-java-program.png [IMAGE {1} FINISH SAMPLE] A Java program typically consists of the following components: 1. Documentation Section 1. Package Declaration 1. Import Statements 1. Interface Section 1. Class Definition 1. Class Variables and Variables 1. Main Method Class 1. Methods and Behaviors ::: :::section{.main} ## Documentation Section The documentation section in the structure of a Java program serves as a vital but optional part of a Java program, providing essential details about the program. This includes the author's name, creation date, version, program name, company name, and a brief description. While these details enhance the program's readability, the Java compiler ignores them during program execution. To include these details, programmers typically use comments. Comments are ``non-executable`` parts of a program. A compiler does not execute a comment. It is used to improve the ``readability`` of the code. Writing comments is a good practice as it improves the documentation of the code. There are three different types of comments- single-line, multi-line and documentation comments. * ``Single line comment``- It is a comment that starts with ``//`` and is only used for a single line. ``` java //Single-line comment ``` * ``Multi line comment``- It is a comment that starts with `` /* `` and ends with ``*/ `` and is used when more than one line has to be enclosed as comments. ```java /* Multiline comment in Java */ ``` * ``Documentation comment``- It is a comment that starts with /** and ends with */ ```java /** Documentation comment */ ``` ::: :::section{.main} ## Package Declaration Declaring the package in the structure of Java is optional. It comes right after the documentation section. You mention the package name where the class belongs. Only one package statement is allowed in a Java program and must come before any class or interface declaration. This declaration helps organize classes into different directories based on the modules they're used in. You use the keyword package followed by the package name. For instance: ```java package scaler; //scaler is the package name package com.scaler; //com is the root directory, and scaler is the subdirectory ``` In Java, we have to save the program file name with the ``same name`` as the name of ``public class`` in that file. The above is a good practice as it tells JVM which class to load and where to look for the entry point (main method). The extension should be ``java``. Java programs are run using the following two commands: ```java javac fileName.java // To compile the Java program into byte-code java fileName // To run the program ``` ::: :::section{.main} ## Import Statements Import statements are used to ``import classes``, interfaces or enums that are stored in packages or the entire package. A package contains many ``predefined`` classes and interfaces. We need to mention which package we are using at the beginning of the program. We do it by using the ``import`` keyword. We either import the entire package or a specific class from that package. The following is the description of how we can write the import statement. ![Import Statement Structure of Java Program](https://scaler.com/topics/images/import-statement-structure-of-java-program.webp) ```java import java.util.*; //imports all the classes in util package import java.util.StringTokenizer; // imports only the StringTokenizer class from util package ``` **Explanation-** We have imported *java.util* package in the first and second lines we have imported only the `StringTokenizer` class from java.util package. ::: :::section{.main} ## Interface Section This is an ``optional`` section. The keyword ``interface`` is used to create an interface. An interface comprises a set of cohesive methods that lack implementation details., i.e. method declaration and constants. ```java interface Code { void write(); void debug(); } ``` **Explanation-** In the above code, we have defined an interface named `Code`, which contains two method declarations, namely `write()` and `debug()`, with no method body. The body of abstract methods is implemented in those classes that implement the interface `Code`. ::: :::section{.main} ## Class Definition This is a ``mandatory section`` in structure of java program. Each Java program has to be written ``inside`` a class as it is one of the main principles of Object-oriented programming that Java strictly follows, i.e., its Encapsulation for data security. There can be ``multiple`` classes in a program. Some conventions need to be followed to name a class. They should begin with an uppercase letter. ``` java class Program{ // class definition } ``` ::: :::section{.main} ## Class Variables and Variables Identifiers are used to name ``classes, methods and variables``. It can be a sequence of uppercase and lowercase characters. It can also contain '_' (underscore) and '$' (dollar) signs. It should not start with a digit(0-9) and not contain any special characters. Variables are also known as ``identifiers`` in Java. It is a ``named memory location`` which contains a value. In a single statement, we're able to declare multiple variables of the same type. **Syntax:** ```java <Data-Type> <Variable Name> or <Data-Type> <Variable Name> = value; ``` **Example:** ```java int var=100; int g; char c,d; // declaring more than one variable in a statement ``` ### Rules for Naming a Variable- * A variable may contain characters, digits and underscores. * The underscore can be used in between the characters. * Variable names should be meaningful and depict the program's logic. * Variable names should not start with a digit or a special character. ::: :::section{.main} ## Main Method Class This is a ``compulsory part`` of the structure of java program. This is the **entry point** of the compiler where the execution starts. It is called/invoked by the Java Virtual Machine or JVM. The `main()` method should be defined inside a class. We can call other functions and create objects using this method. The following is the syntax that is used to define. **Syntax** ```java public static void main(String[] args) { // Method logic } ``` ::: :::section{.main} ## Methods and Behaviors A method is a ``collection`` of statements that perform a ``specific task``.Method names typically begin with a lowercase letter. It provides the ``reusability`` of code as we write a method once and use it many times by invoking the method. The most important method is Java's ``main()`` method. The following are the important components of the method declaration. ``Modifier``- Defines access type, i.e., the method's scope. ``The return data type``-It is the data type returned by the method or void if does not return any value. ``Method Name``- The method names should start with a lowercase letter (convention) and not be a keyword. ``Parameter list``- It is the list of the input parameters preceded by their data type within the enclosed parenthesis. If there are no parameters, you must put empty parentheses (). ``Exception list``- The exceptions that a method might throw is specified. ``Method body``- It is enclosed between braces {}. The code to be executed is encapsulated within them. ``Method signature``-It contains the method name and a parameter list (number, type and order of the parameters). The return data type and exceptions are not a part of it. **Example:** ```java public void add(int a, int b){ int c = a + b; System.out.println(c); } ``` **Explanation-** In the above method, we added two numbers passed as parameters and printed the result after adding them. This is only executed when the method is called. The resulting structure typically resembles the following format when incorporating the components above into a Java program. ```java import java.io.*; public class Main{ public static void main(String[] args) throws Exception { System.out.println("Hello, Java!"); } } ``` **Output-** ```java Hello, Java! ``` **Explanation-** In the above program, we printed a line on the console using `System.out.println()`, which gets displayed after the code gets executed. ::: :::section{.summary} ## Conclusion * Java is an **OOP language** which is case-sensitive, platform-independent, and uses both [compiler and interpreter](https://www.scaler.com/topics/c/difference-between-compiler-and-interpreter/). * java program structure consists of compulsory classes to be written. * The main() method is the **entry point** of the compiler from where it starts the execution. * **Variables and identifiers** are used for naming variables and classes. * Keywords are **reserved words** which are predefined and have a meaning. * **Access modifiers** serve to specify the visibility and accessibility of classes, methods, constructors, or data members within a program. * Java file should be saved with the name of the public class and should have the extension .java after the file name. :::

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully