Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversWeek Three ViewingAmazon USTune the living room for the next slate of gamesHDMI adapters, wireless headsets, and compact speakers for clearer football-weekend viewing at home.See PicksClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run Scan×
Skip to content
THEGEEKSCLUB

How to Use ‘Static’ in Java

Static in java
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Normally a class member must be accessed in conjunction with an object of its class. There will be times when you will want to define the class member which can be accessed without instantiating that class. This can be accomplished by ‘static’. To create such a member, precede its declaration with the keyword ‘static’.

Advantages of Static

When a member is declared static, it can be accessed before any objects of its class are created or without reference to any object.

Why do we declare main() as Static?

main() is the entry point of  a class. In java everything thing is written in a class. Now when you run java filename on command prompt, loader will load the class and JVM will search the main method to enter into the class. So making the main() as static, will make JVM access it directly through classname.main()

That’s why the program name must be same as the class name, where we wrote the main function.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Shopping ad
Sale
FYY Electronic Organizer, Travel Tech Pouch Bag, Cable Organizer Black
  • Dimensions: 7.5" x 4.3" x 2.2". Compact size and lightweight make it easy to carry and put into your backpack, handbags or laptop bag without taking much space. Suitable for family use and daily organization. Note: Small mesh pockets are ideal for charging cords no longer than 3ft; longer cables (over 3ft) fit better in the larger compartments
  • Quality Material: This electronic organizer travel case made of high quality durable waterproof oxford and soft sponge inside to secure your gadgets in place and deliver a quick access whenever you want. Water-resistant fabric protects your gear from unexpected splashes, keeping all your electronic essentials safe and secure
  • Double Layers Design: This tech pouch features a double-layer interior design with 8 compartments, including multiple see-through mesh pockets and ample space to store your cords, cables, USB drives, cellphone, charger, mouse, flash drive and more, keeping all accessories neatly organized and tangle-free
  • Practical and Convenient: Comes with a comfortable hand strap for easy carrying; You may carry it in your hand when heading out. Durable and smooth zipper closure keeps your favorite device securely, convenient for you to have quick access to the items inside the case
  • Portable and Lightweight: The small size and lightweight design durable cable organizer pouch is a perfect choice when going on holiday, business trip, travel, office. Enjoy hassle-free travel without wasting time on tangled accessories. Great gift for yourself also a nice share with families and friends. (No include cords, electronic accessories)

Important Points to Remember 

  1. Instance Variables declared as static are essentially global variables. When you create objects of its class, no copy of a static variable is made. Even all objects share the same static variable.
  2. static variables or member functions will load during class. That means before creating any instances (objects), the main function is the first runnable function of any program which we run manually.
  3. If you want to get something executed/initialization of static variables before actual loading of the class, then put all those in static block.

E.g.

    static{

       System.out.println(“Static block initialized…”);

    }

It gets executed even before main() method during loading of the class.

Shopping ad
Sale
Ordilend Keyboard Cleaner & Laptop Cleaning Kit, All-in-1 for Computer PC
  • 【UPGRADED LAPTOP CLEANING KIT 】 The macbook cleaning kit computer screen cleaner comes with a number of accessories including a retractable large brush, polishing cleaning cloth X 2, keycap puller, metal pen tip, flocking sponge, thin soft brush, soft plastic lens cleaning pen, 5 replacing cloth, large cleaning microfiber cloth. You deserve the comprehensive computer cleaning kit keyboard vacuum at a low cost
  • 【PROFESSIONAL KEYBOARD CLEANING KIT】 The laptop screen cleaner keyboard cleaner can pull out the keycaps of gaming keyboards and mechanical keyboards. A retractable keyboard brush works on laptops and keyboards, while the mini high-density brush is great for deep cleaning between keys for cleaning between flatter keys on a laptop, the metal pin tip gently removes any stains. This electronic cleaning kit macbook cleaner totally meets professional cleaning needs
  • 【OFFICE DESK ACCESSORIES】This keyboard cleaner kit is easy to use and can clean your keyboard and electronic screen with just one swipe. Wiping with the 2mm thicken widen polishing cleaning cloth designed at a right angle for better fitting screen corners of computers with our recyclable cleaning spray, The laptop cleaner kit for macbook effectively absorbs stubborn stains, leaves no discoloration, no streaks, and no fiber shedding on the screens
  • 【MULTIFUNCTIONAL TOOLS 】Mini soft brush and soft plastic lens cleaning pen are specially designed for DSLR camera screen, lens, and other delicate surfaces. 5 more cleaning cloths of it supplied for replacement. The flocking sponge is an excellent tool for cleaning earbuds charging cases, And the earbud cleaning kit is ideal. This electronics for college students is equivalent to 10 other electronic cleaning kit
  • 【PORTABLE DESIGN & CLEANER TOOL】 The office supplies is compact in design, easy to carry, and you can easily take it anywhere. It's convenient to keep one in a drawer, one in your car, or in your bag and dorm. It is easy to use and can clean your keyboard and electronic screen with just one swipe. Is the college essentials cleaning tool for your friends, family, colleagues and students

Restrictions While using Static

  1. static method can access only static variables.
  2. static method can invoke static method only.
  3. static method can’t refer to this and super in any way.

Program

class Addition{
  static int num1;
  static int num2;
  int a;
  int b;
  Addition(){
    num1 = -1;
    num2 = -1;
    a = -1;
    b = -1;
  }
  Addition(int num1,int num2,int a,int b){
    this.num1 = num1;
    this.num2 = num2;
    this.a = a;
    this.b = b;
  }
  static void sum(){
    //System.out.println("Sum of 4 numbers is: "+(num1+num2+a+b));  /*static method can’t access static vars */
    System.out.println("Sum of 'num1' and 'num2' is: "+(num1+num2));
    System.out.println();
  }
  void add(){
    System.out.println("Addition of 4 numbers is: "+(num1+num2+a+b));
    System.out.println();
  }
}

class AditionDemo1{
  public static void main(String args[]){
    System.out.println();
    System.out.println("Static method sum() called without creating any object");
    System.out.println("------------------------------------------------------");
    Addition.sum();

    Addition ad1 = new Addition();

    System.out.println("Static Method sum() is invoked second time");
    System.out.println("-----------------------------------------------");
    Addition.sum();

    System.out.println("Non-Static Method add() is invoked using Object ad1");
    System.out.println("-----------------------------------------------");
    ad1.add();

    Addition ad2 = new Addition(10,20,30,40);

    System.out.println("Static Method sum() is invoked second time");
    System.out.println("-----------------------------------------------");
    Addition.sum();

    System.out.println("Non-Static Method add() is invoked using Object ad2");
    System.out.println("-----------------------------------------------");
    ad2.add();

    System.out.println("Static Method sum() is invoked third time");
    System.out.println("-----------------------------------------------");
    Addition.sum();

    System.out.println("Static Method sum() is invoked using Object");
    System.out.println("-------------------------------------------");
    ad1.sum();
    ad2.sum();
  }
}

Output

 Static in java

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Explanation of the Java Code & Output

If you see the code carefully, then you will find we have taken two static variables and two non static variables which are initialized by two constructors viz. one is parameterized and another one is default. We have defined one static method and one non static method.

In main(), first we have invoked static method sum() without creating any object of Addition Class.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Shopping ad
Sale
BAGSMART Large Electronic Organizer Travel Case for Tech Accessories, Black
  • Compatible Space: This electronics organizer bag features 2 zippered mesh pockets fits phones, standard power banks, 4 elastic loop pouches for small items, 2 elastic loop pouches for wireless headphones and small chargers. Elastic loops for phone charging cable. And specific slots for SD cards. Please check the size to ensure it meets your needs
  • Lightweight Travel Accessories: The size of the electronic organizer travel case is 10.6" L x 7.5" W x 1.2" H, Compact but substantial size fits your intended bag or space. Suitable for traveling use and daily organization
  • Keep Everything Organized: This compact travel organizer features dedicated compartments for your phone charger, cables, and tech accessories, keeping them tangle-free and ready to go. You can find travel accessories quickly, no chasing cords in your pack anymore
  • Durable Travel Essentials: Features double zippers for easy access, elastic loops with non-slip grips for daily protection. Organizer for office use and traveling, (Not including cords, electronic accessories). It can serve as a travel checklist. Before you leave a place, just open the case and check if everything is there, preventing you from leaving things behind
  • Versatile Use: Its practicality and convenience make it a travel essential bag. It is suitable for a weekend trip, business trip, and travel. This organizer pouch is suitable for office, business, daily use and can be given as a gift for friends, family, or men, for birthdays, Valentine's Day, Christmas Day, Father's Day

In the code you can see that static method can’t access non- static variables. If you try to access then you will get the following error, as we got:

Static in java

Now if you see, static variables are global variables only. Irrespective of the objects it has given the same result whenever static method sum() is invoked by any objects.

Shopping ad
ColorCoral Cleaning Gel Universal Dust Cleaner for PC Keyboard Car Detailing Office Electronics Laptop Dusting Kit Computer Dust Remover, Computer Gaming Car Accessories, Gift for Men Women 160g
  • Universal fit: ColorCoral cleaning gel, simple and convenient cleaning kits for PC/laptop keyboard and other rugged surface, such as the car vent, camera, printer, telephone, calculator, Instrument, speaker, air conditioner, TV and other appliances
  • Safe cleaning gel: The keyboard cleaner gel is made from natural gel, no sticky to hands, smells sweet with lemon fragrance, no stimulation to skin
  • Easy dust cleaning: Make sure your hands are dry and clean, knead the cleaning gel into a ball, press the cleaning gel slowly into the keyboard, car vent and rugged surface till the cleaning gel could touch the bottom and then pull out, the dust would be carried away with the cleaning gel
  • Reusable: The keyboard cleaning gel could be used repeatedly till the color turn to dark or it become sticky, then you have to replace the cleaning gel with a new one. After cleaning, please stock the cleaning gel in cool place. (Note: Don’t wash the gel in water.)
  • In the package: 1 can of universal cleaning gel, we provide the cleaning gel with brand new, if you find the package broken, the cleaning gel dirty, or any other quality issues, please email us through message, we provide you new one soon

Non-static method can access static variables.

Non static method can invoke static methods.

Static methods can be invoked with <classname>.<static method name> and with <objectname>.< static method name > as well.

For non-static variables, each object will have different copies of non-static variables with different values for different objects.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Shopping ad
Sale
HOTO Pocket-Size Laser Measuring Tool, EDC Gadget Birthday Gift for Men Dad
  • Award-Winning Compact Design & EDC-Ready Gift Choice: Weighing only 0.09 lb and sized like a credit card, this compact laser measure is designed for everyday carry. It slips easily into a pocket, tool pouch, or bag, and can attach to a keychain for quick access wherever you go. Its minimalist design, premium tactile finish, and practical one-button measuring make it a useful EDC gadget for DIYers, real estate agents, homeowners, and tech enthusiasts. A thoughtful gift for men on any occasion
  • One-Button Easy Measuring, Simple to Use: Designed with simple one-button operation, this compact laser tape measure makes quick measuring easy without complicated controls. Just press to measure room dimensions, furniture spacing, window height, wall décor placement, and everyday distances around the home. Ideal for users who want a smart, pocket-size measuring tool that fits naturally into an everyday carry (EDC) setup and feels intuitive, modern, and easy to use
  • Fast & Accurate Indoor Measurements with Class 2 Laser: Measure distances from 0.16 ft to 98 ft with up to ±1/16 in / ±2 mm accuracy. With quick measurement response in about 0.2 seconds, HOTO helps you check spaces efficiently for home renovation, furniture layout, moving, decorating, craft projects, and DIY planning. Built with a Class 2 laser for everyday indoor measuring; use as directed and avoid direct eye exposure
  • Low-Power OLED Display & USB-C Rechargeable Convenience: The low-power OLED display provides clear indoor readings while helping reduce battery drain. With USB-C rechargeable design, auto shut-off, and up to 1000 measurements per charge, this digital laser measure is built for repeated daily use without frequent battery replacement. Compact enough to keep in a drawer, toolbox, bag, or pocket
  • Useful for Home, Work & Everyday Projects: From home renovation and furniture measuring to room planning, real estate checks, interior design, and light construction projects, this pocket-size laser distance measure is made for practical everyday use. Compact enough to keep in a drawer, toolbox, bag, or pocket, it is a stylish measuring tool that feels just as giftable as it is useful

Next we will learn about how to use “this” keyword in Java.

Checkout more useful tutorials and definitive guidelines on Java programming here.

MX Player for PC

snaptube pc minecraft download pc Ativador Windows 7

Avatar photo
Written by

Nitin Agarwal

A blogger, tech evangelist, YouTube creator, books lover, traveler, thinker, and believer of minimalist lifestyle.

More from this author ↗
Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.