Comparison of static keyword in C++ and Java
Last Updated :
05 Sep, 2023
Static keyword is used for almost the 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.
Similarities between C++ and Java for Static Keyword
- Static data members can be defined in both languages.
- Static member functions can be defined in both languages.
- Easy access of static members is possible, without creating some objects.
Differences between C++ and Java for Static Keyword
|
C++ doesn't support static blocks. | Java supports static block (also called static clause). It is used for the static initialization of a class. |
Static Local Variables can be declared. | Static Local Variables are not supported. |
The above points are discussed are in detail below:
1. 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, the static variable count is used to count the number of objects created.
Java
class Test {
static int count = 0;
Test() { count++; }
public static void main(String arr[])
{
Test t1 = new Test();
Test t2 = new Test();
System.out.println("Total " + count
+ " objects created");
}
}
OutputTotal 2 objects created
2. Static Member Methods:
In C++ and Java, static member functions can be defined. Methods declared as static are class members and have the following restrictions:
a). They can only call other static methods. For example, the following program fails in the compilation. fun() is non-static and it is called in static main().
Java
class Main {
public static void main(String args[])
{
System.out.println(fun());
}
int fun() { return 20; }
}
b). They must only access static data.
c). They cannot access this or super. For example, the following program fails in the compilation.
Java
class Base {
static int x = 0;
}
class Derived extends Base {
public static void fun()
{
// Compiler Error: non-static variable
// cannot be referenced from a static context
System.out.println(super.x);
}
}
d). Like C++, static data members and static methods can be accessed without creating an object. They can be accessed using the class names. For example, in the following program, static data member count and static method fun() are accessed without any object.
Java
class Test {
static int count = 0;
public static void fun()
{
System.out.println("Static fun() called");
}
}
class Main {
public static void main(String arr[])
{
System.out.println("Test.count = " + Test.count);
Test.fun();
}
}
OutputTest.count = 0
Static fun() called
3. 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 the static block is executed only once. See Static blocks in Java for details.
4. Static Local Variables:
Unlike Java, C++ supports static local variables. For example, the following Java program fails in the compilation.
Java
class Test {
public static void main(String args[])
{
System.out.println(fun());
}
static int fun()
{
// Compiler Error: Static local
// variables are not allowed
static int x = 10;
return x--;
}
}
In C++ and Java, the static keyword has different meanings and uses. Here are some comparisons between the static keyword in C++ and Java:
Static variables:
In C++, a static variable inside a function retains its value even after the function has returned. It is initialized only once, and its value is preserved across function calls. In Java, a static variable inside a class belongs to the class rather than to any instance of the class. All instances of the class share the same value of the static variable.
Static functions:
In C++, a static function is a member function of a class that can be called without an object of that class. It is bound to the class and not to any object. In Java, a static function is also bound to the class and not to any object. It can be called using the class name rather than an object of the class.
Static classes:
In C++, there is no concept of a static class. In Java, a static class is a nested class that is declared with the static keyword. It can be accessed without creating an instance of the outer class.
Advantages of using static keyword:
1. Memory efficiency: Static variables and functions are allocated memory only once, which can save memory in certain cases.
2. Accessing class members without an object: Static functions and variables can be accessed without creating an object of the class, which can make code more concise and easier to read.
3. Global scope: Static variables and functions have a global scope within the file or class in which they are declared.
Disadvantages of using static keyword:
1. Difficulty in testing: Static functions and variables can be difficult to test because they have a global scope and may be affected by other parts of the program.
2. Thread safety: Static variables are shared between threads, which can cause thread-safety issues if they are not properly synchronized.
3. Difficulty in debugging: Because static variables and functions have a global scope, it can be difficult to debug issues related to their use.
Here are some examples of using the static keyword in C++ and Java.
C++ example:
C++
#include <iostream>
void printCount()
{
static int count = 0;
count++;
std::cout << "Count is: " << count << std::endl;
}
int main()
{
for(int i = 0; i < 5; i++)
{
printCount();
}
return 0;
}
OutputCount is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
This C++ program declares a function printCount which uses the static keyword to create a variable count that is only initialized once and retains its value between function calls. The main function calls printCount five times, incrementing the count variable each time and printing its current value to the console.
Java example:
Java
public class StaticExample {
public static int count = 0;
public static void printCount()
{
count++;
System.out.println("Count is: " + count);
}
public static void main(String[] args)
{
for(int i = 0; i < 5; i++)
{
printCount();
}
}
}
OutputCount is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
This Java program declares a class StaticExample with a static variable count and a static function printCount that increments and prints the count variable. The main function calls printCount five times in a loop, producing the same output as the C++ program.
Both of these programs demonstrate the use of static variables to retain state between function or method calls, and static functions or methods to provide behavior that is shared across all instances of a class.
Similar Reads
Comparison of boolean Data Type in C++ and Java The Boolean data type is one of the primitive data types in both C++ and Java. Although it may seem to be the easiest of all the data types, as it can have only two values, true or false. The main difference between them is listed below:In Java, the boolean type can hold false or true.In C++, the bo
4 min read
Static Keyword in C++ The static keyword in C++ has different meanings when used with different types. In this article, we will learn about the static keyword in C++ along with its various uses.In C++, a static keyword can be used in the following context:Table of ContentStatic Variables in a FunctionStatic Member Variab
5 min read
Static method in Interface in Java Static Methods in Interface are those methods, which are defined in the interface with the keyword static. Unlike other methods in Interface, these static methods contain the complete definition of the function and since the definition is complete and the method is static, therefore these methods ca
2 min read
Difference between static and non-static method in Java A static method is a method that belongs to a class, but it does not belong to an instance of that class and this method can be called without the instance or object of that class. Every method in java defaults to a non-static method without static keyword preceding it. Non-static methods can access
6 min read
Static import in Java In Java, static import concept is introduced in 1.5 version. With the help of static import, we can access the static members of a class directly without class name or any object. For Example: we always use sqrt() method of Math class by using Math class i.e. Math.sqrt(), but by using static import
4 min read
Class Loading and Static Blocks Execution Using Static Modifier in Java Static is a keyword which when attached to the method, variable, Block makes it Class method, class variable, and class Block. You can call a static variable/method using ClassName. JVM executes the static block at âCLASS LOADING TIMEâ Execution Order: There is an order in which static block/method/
3 min read