Static keyword is used for almost same purpose in both C++ and Java. There are some differences though. This post covers similarities and differences of static keyword in C++ and Java.
Static Data Members: Like C++, static data members in Java are class members and shared among all objects. For example, in the following Java program, static variable count is used to count the number of objects created.
Total 2 objects created
Static Member Methods: Like C++, methods declared as static are class members and have following restrictions:
1) They can only call other static methods. For example, the following program fails in compilation. fun() is non-static and it is called in static main()
2) They must only access static data.
Like C++, static data members and static methods can be accessed without creating an object. They can be accessed using class name. For example, in the following program, static data member count and static method fun() are accessed without any object.
Static Block: Unlike C++, Java supports a special block, called static block (also called static clause) which can be used for static initialization of a class. This code inside static block is executed only once. See Static blocks in Java for details.
Static Local Variables: Unlike C++, Java doesn’t support static local variables. For example, the following Java program fails in compilation.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important Java and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.
- Static and non static blank final variables in Java
- Difference between static and non-static method in Java
- Difference between static and non-static variables in Java
- Understanding storage of static methods and static variables in Java
- static keyword in java
- Output of Java Programs | Set 48 (Static keyword)
- Understanding "static" in "public static void main" in Java
- Why non-static variable cannot be referenced from a static method in Java
- C++ | Static Keyword | Question 1
- C++ | Static Keyword | Question 2
- C++ | Static Keyword | Question 3
- C++ | Static Keyword | Question 4
- C++ | Static Keyword | Question 5
- C++ | Static Keyword | Question 6
- Static Keyword in C++
- Internal static variable vs. External static variable with Examples in C
- Comparison of Inheritance in C++ and Java
- Comparison of boolean data type in C++ and Java
- Comparison of double and float primitive types in Java
- Comparison of yield(), join() and sleep() in Java