Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

5 ways to use the static keyword in Java

I just had an interview where one of the questions was something like "Describe 5 ways to use the static keyword in Java." I could only think of 2 on the spot, and afterwards I found 2 more. What is the 5th?

  1. Declaring a field belonging to a class as opposed to an instance of the class.
  2. Declaring a method that can be called on a class as opposed to an instance.
  3. Declaring a nested class as static
  4. Defining a static class initializer.
  5. ???
like image 758
Sam Avatar asked Oct 17 '09 00:10

Sam


People also ask

How many ways can you use static keyword in Java?

The static keyword in Java is used to share the same variable or method of a given class. The users can apply static keywords with variables, methods, blocks, and nested classes. The static keyword belongs to the class than an instance of the class.

Why do we use static keyword in Java?

One such frequently used keyword in Java is the “Static” keyword. The most important reason why static keywords are heavily used in Java is to efficiently manage memory. Generally, if you want to access variables or methods inside a class, you first need to create an instance or object of that class.

What are static methods used for?

A static method has two main purposes: For utility or helper methods that don't require any object state. Since there is no need to access instance variables, having static methods eliminates the need for the caller to instantiate the object just to call the method.

Which methods are static in Java?

Static methods are the methods in Java that can be called without creating an object of class. They are referenced by the class name itself or reference to the Object of that class.


1 Answers

static import (since java 1.5):

import static my.package.MyClass.*;

like image 170
ChssPly76 Avatar answered Nov 06 '22 04:11

ChssPly76