Open In App

Comparison of static keyword in C++ and Java

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

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++

Java

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");
    }
}


Output

Total 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();
    }
}


Output

Test.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;
}


Output

Count 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();
        }
    }
}


Output

Count 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.



Last Updated : 05 Sep, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads