Static Keyword in C++ and JAVA
In C++, the keyword static is used to give element unique properties. Static elements are only allocated storage in the static storage area once during the program's lifetime. And they are valid for the duration of the programme. The following are examples of static keywords:
The static keyword in Java is primarily used for memory management. The static keyword can be used with variables, methods, blocks, and nested classes. The static keyword is associated with the class rather than an instance of the class.
The static can be as follows:
In both C++ and Java, the static keyword serves nearly the same function. However, there are some distinctions. This post compares and contrasts the static keyword in C++ and Java.
Static Keyword Similarities between C++ and Java:
Differences in Static Keywords between C++ and Java:
The following points are discussed in detail below:
1) Static Data Members: Static data members in Java, like in C++, are class members that are shared by all objects. In the following Java programme, for example, the static variable count is used to count the number of objects created.
Total 2 objects created
2) Static Member Methods: Static member functions can be defined in C++ and Java. Static methods are class members with the following restrictions:
a. can only use static methods. For example, the compilation of the following programme fails. fun() is a non-static function that is called in static main ().
b. They are only permitted to access static data.
c. They do not have access to this or super. For example, the compilation of the following programme fails.
d. Just like in C++, static data members and static methods can be accessed without the need to create an object. They are accessible via the class names. In the following programme, for example, static data member count and static method fun() are accessed without the use of an object.
Test.count = 0 Static fun() called
3) Static Block: Unlike C++, Java has a special block called static block (also known as static clause) that can be used for static class initialization. This code within the static block is only executed once. For more information, see Static blocks in Java.
4) Static Local Variables: Unlike Java, static local variables are supported in C++. For example, the compilation of the following Java programme fails.
Next TopicException Handling in C++ and JAVA