w3resource

Java Static Members - Exercises, Practice, Solution

Java Static Members Exercises [8 exercises with solution]

[An editor is available at the bottom of the page to write and execute the scripts.  Go to the editor]

1. Static Variables:
Write a Java program to create a class called "Counter" with a static variable count. Implement a constructor that increments count every time an object is created. Print the value of count after creating several objects.

Click me to see the solution

2. Static Methods:
Write a Java program to create a class called "MathUtility" with a static method add that takes two integers and returns their sum. Demonstrate the usage of this static method in the main method without creating an instance of "MathUtility".

Click me to see the solution

3. Static Block
Write a Java program to create a class called "Initializer" with a static block that initializes a static variable 'initialValue' to 1000. Print the value of 'initialValue' before and after creating an instance of "Initializer".

Click me to see the solution

4. Static Final Variables
Write a Java program to create a class called Constants with a static final variable 'PI' initialized to 3.14159. Create a method to calculate the area of a circle given its radius, using the 'PI' constant. Demonstrate the method in the main method.

Click me to see the solution

5. Static Block for Initialization
Write a Java program to create a class called Configuration with a static block that initializes a static variable 'configValue' from a configuration file (simulated with a default value). Print the value of 'configValue' in the main method.

Click me to see the solution

6. Static Method with Static Variable
Write a Java program to create a class called "IDGenerator" with a static variable 'nextID' and a static method "generateID()" that returns the next ID and increments 'nextID'. Demonstrate the usage of generateID in the main method.

Click me to see the solution

7. Static Block for Complex Initialization
Write a Java program to create a class called "ComplexInitializer" with a static block that initializes multiple static variables (x, y, z) using complex logic. Print the values of these variables in the main method.

Click me to see the solution

8. Static Members in Different Contexts
Write a Java program to create a class called "BankAccount" with instance variables 'accountNumber' and balance, and static variables 'bankName' and 'interestRate'. Provide static methods to get and set the static variables. Create several 'BankAccount' objects and print their details along with the static variables.

Click me to see the solution

More to Come !

* To run the code mouse over on Result panel and click on 'RERUN' button.*

Java Code Editor


Do not submit any solution of the above exercises at here, if you want to contribute go to the appropriate exercise page.



Become a Patron!

Follow us on Facebook and Twitter for latest update.