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 No publishing access yet

      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.

      Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Explore these features while you wait
      Complete general settings
      Bookmark and like published notes
      Write a few more notes
      Complete general settings
      Write a few more notes
      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 New
    • Engagement control
    • Make a copy
    • 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 Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy 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 No publishing access yet

    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.

    Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Explore these features while you wait
    Complete general settings
    Bookmark and like published notes
    Write a few more notes
    Complete general settings
    Write a few more notes
    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
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    --- title: Static Method in Java With Examples - Scaler Topics description: The static method in Java and members in Java can be accessed without creating the object of the class. Learn more on Scaler Topics. author: Aayush Saini category: Java --- :::section{.main} The static methods are class methods that don't belong to instances of the class. They are designed to be shared among all instances of the same class and are accessed by the class name of the particular class. In Java, a `static` keyword is used for declaring the static method. The static method in Java cannot be overridden because static methods are linked to the class during the compilation time, and we know very well that method overriding is based on the runtime `polymorphism`. That's why the static methods cannot be overridden. The static methods can be accessed by the outside environment very easily. We have already dicussed the `main()` method example in the above section. The **main() method** is of static type because when the Java runtime starts, no object from the class is present. The main method has to be static so the `JVM` load sthe class into main memory and call it. ### Features of Static Method in Java * In Java, a static method is a part of the class itself rather than an instance of a class. * The method is available to each instance of the class. * The method is available to each class instance. They have access to class variables (static variables) (instance) without requiring the class's object. * A static method has only access of static data. It cannot access dynamic data (instance variables). * Static methods can be accessed directly in non-static and static methods. ### Syntax to Declare the Static Method ```java //static keyword must be used for the static method static return_type methodname(parameter){ //Code to be executed } ``` The return_type of the static method can be int, float, etc, any user-defined datatype. ### Syntax to Call a Static Method We can call the static methods using the class name because they belong to the class itself and have `no relation` with its instances. **Syntax:** ```java ClassName.methodName() ``` The classname is the name of the class followed by the name of the static method. **Let's understand what a static method is called using an example.** ```java class Main { static void print() { System.out.println("This the static method of the Main class"); } public static void main(String[] args) { Main.print(); } } ``` **Output:** ```plaintext This is the static method of the Main class ``` ::: :::section{.main} ## Examples of Static Method in Java After discussing static methods and when you might use them, let's look at real-world examples to understand how they function. ### Example 1: Creating a Utility Class Let's say we want to develop a utility class that includes operations for performing math. To include static methods for addition, subtraction, multiplication, and division, we may make a class called MathUtils. This is how the MathUtils class might appear: ```java public class ArithmeticUtilityClass { public static int add(int a, int b) { return a + b; } public static int subtract(int a, int b) { return a - b; } public static int multiply(int a, int b) { return a * b; } public static int divide(int a, int b) { return a / b; } } ``` We have developed a utility class with four static methods for mathematical operations in the code above. These MathUtils class methods can be called without first constructing an object of that class. For instance: ```java int result = ArithmeticUtilityClass.add(3, 6); // result is 9 result = ArithmeticUtilityClass.subtract(8, 2); // result is 6 result = ArithmeticUtilityClass.multiply(5, 8); // result is 40 result = ArithmeticUtilityClass.divide(20, 4); // result is 5 ``` ### Example 2: Implementing the Singleton Design Pattern Singletons are frequently utilised to manage resources like database connections or thread pools. Suppose our goal is to develop a class that symbolises a database connection. We can use the singleton design pattern to ensure that there can only be one connection to the database at a time. Given below is the Java implementation to demonstrate the above explanation: ```java public class DBConnection { // private constructor to prevent instantiation private DBConnection() {} // static instance of the class private static DBConnection instance = null; // method to get the instance of the class public static DBConnection getInstance() { if (instance == null) { instance = new DBConnection(); } return instance; } // other methods... } ``` The `DBConnection` class's constructor has been designated private in the code above. By doing this, other classes cannot instantiate the `DBConnection` class. Moreover, a static method for obtaining the class instance and a static instance of the class are declared. First, the `getInstance()` method verifies whether a class instance has already been created. If not, it builds one and returns it. If not, it returns the current instance. This guarantees that only one instance of the `DBConnection` class can exist at any one moment. ::: :::section{.main} ## Why Use Static Methods? This question always arises in the mind of the programmer: why use a static method in java programs? Let's understand some `common` uses for static methods so that we can efficiently use them. * If the implementation of the method's code is `not changed` by the instances of the class. In this case, we can make the method a static method. * When we want to access static and other non-object-based static methods, then, we have to use static methods * If we want to define some utility functions, such as the user-defined sorting method in the class, we can define them using static concepts because the utility function can `easily` be shared among all class objects due to the static method's property. ::: :::section{.main} ## Restrictions of Static Method in Java When the methods are declared as static, there are lots of `restrictions` applied to the static method that make it different from the instance methods of the class. **Let's discuss some restrictions on the static method in Java.** * The static method cannot invoke the instance member and class methods. Static methods are accessed without the class's object reference, but we cannot access the instance variables and methods without an object reference. If we try to access the instance variable or methods inside the static method, this will cause an' error'. **Let's try to understand this using an example.** ```java class Main { void hello() { System.out.print("This is the non static method"); } static void print() { // Calling the non-static method from the static method // This will cause an error hello(); } public static void main(String[] args) { // Accessing the static method of the class. Main.print(); } } ``` **Output:** ```plaintext java: non-static method hello() cannot be referenced from a static context ``` In the above program, we are trying to access the `nonstatic method` from the class's static method, which will cause an `error`. Use this [Free Online Compiler](https://www.scaler.com/topics/java/online-java-compiler/) to compile your Java code. * The static methods can only access other static members and methods. Because static members and methods are `linked` to the class during compilation, they can access each other without creating an instance of the class. * We cannot use `this` and `super keyword` in the body of the static method because the `this` keyword is the reference of the current object, but without creating an object, we can access the static method. This will cause an error, and in the case of the super keyword, we know super is the reference of the `parent class` very well, but we cannot use a reference in the body of the static method. We have already discussed the reason behind this. ::: :::section{.main} ## main Method in Java Static Java's `main()` method is static since an object doesn't need to call a static method. If the function weren't static, JVM would create an object before executing the `main()` method, making memory allocation more complex. ::: :::section{.main} ## Important Points to Remember about Static Methods * The static methods are the `class` methods and are accessed by the `name` of the class. * The static methods `cannot be overridden` because static methods are resolved at the compilation time of the Java program, and we know very well the method overriding is the runtime `polymorphism`. * The keywords such as super and this cannot be used in the body of the `static method`; we have already discussed the reason behind this in the above section. * The static methods `cannot` access the instance members and methods of the class. * The state of the static methods is `equally` shared among all the class objects. ::: :::section{.main} ## Difference between the Static Method and Instance Method | Static method | Instance method | | --------------------------------------------------------------------- |:-----------------------------------------------------------------:| | Static method can be considered as pass-by-reference programming. | While instance methods are considered as pass-by-value programming. | | The static method doesn't require an object from a class. | Instance methods require an object of a class. | | Its syntax - classname.methodname() | Its syntax - objref.methodname() | | Static method has only access of static attribute.| While Instance method has access to all of the attribute.| |Static method is only accessible by classname.| Instance methods are only accessible by object reference. | ::: :::section{.summary} ## Conclusion * The static members and methods belong to the `class` rather than the `instance` of the class. * They are accessed by the name of the class. * The keywords such as `this` and `super` are not used in the body of the static method. * Modification of the static field value is not allowed. :::

    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
    Sign in via Google Sign in via Facebook Sign in via X(Twitter) Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    By signing in, you agree to our terms of service.

    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