The Wayback Machine - https://web.archive.org/web/20240930192825/https://www.geeksforgeeks.org/static-keyword-in-java/
Open In App

Comparison of static keyword in C++ and Java

Last Updated : 05 Sep, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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.



Similar Reads

Output of Java Programs | Set 48 (Static keyword)
Prerequisite : Static keyword in Java Question 1. what is the output of this question? class Test1 { public static void main(String[] args) { int x = 20; System.out.println(x); } static { int x = 10; System.out.print(x + " "); } } Option A) 10 20 B) 20 10 C) 10 10 D) 20 20 Output: A Explanation : Static block is executed before main metho
2 min read
static Keyword in Java
The static keyword in Java is mainly used for memory management. The static keyword in Java is used to share the same variable or method of a given class. The users can apply static keywords with variables, methods, blocks, and nested classes. The static keyword belongs to the class rather than an instance of the class. The static keyword is used f
9 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 any static method and static variable, without cr
6 min read
Difference between static and non-static variables in Java
There are three types of variables in Java: Local VariablesInstance VariablesStatic Variables The Local variables and Instance variables are together called Non-Static variables. Hence it can also be said that the Java variables can be divided into 2 categories: Static Variables: When a variable is declared as static, then a single copy of the vari
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/variable gets initialized. Static BlockStatic Vari
3 min read
Difference Between Static and Non Static Nested Class in Java
Nested classes are divided into two categories namely static and non-static. Nested classes that are declared static are called static nested classes. Non-static nested classes are called inner classes. A class can either be static or non-static in java. So there is a lot of difference between making a class static or non-static. There are two kind
4 min read
Static and non static blank final variables in Java
A variable provides us with named storage that our programs can manipulate. There are two types of data variables in a class: Instance variables : Instance variables are declared in a class, but outside a method, constructor or any block. When a space is allocated for an object in the heap, a slot for each instance variable value is created. Instan
5 min read
Understanding storage of static methods and static variables in Java
In every programming language, memory is a vital resource and is also scarce. Hence the memory must be managed thoroughly without any leaks. Allocation and deallocation of memory is a critical task and requires a lot of care and consideration. In this article, we will understand the storage of static methods and static variables in Java. Java Virtu
6 min read
Understanding "static" in "public static void main" in Java
Following points explain what is "static" in the main() method: main() method: The main() method, in Java, is the entry point for the JVM(Java Virtual Machine) into the java program. JVM launches the java program by invoking the main() method. Static is a keyword. The role of adding static before any entity is to make that entity a class entity. It
3 min read
Why non-static variable cannot be referenced from a static method in Java
Java is one of the most popular and widely used programming language and platform. Java is Object Oriented. However, it is not considered as a pure object-oriented as it provides support for primitive data types (like int, char, etc). In java, methods can be declared as either static or non-static. In this article, let's discuss why non-static vari
4 min read
C++ | Static Keyword | Question 1
Predict the output of following C++ program. #include <iostream> using namespace std; class Test { static int x; public: Test() { x++; } static int getX() {return x;} }; int Test::x = 0; int main() { cout << Test::getX() << " "; Test t[5]; cout << Test::getX(); } (A) 0 0 (B) 5 5 (C) 0 5 (D) Compiler Error Answer: (
1 min read
C++ | Static Keyword | Question 2
#include <iostream> using namespace std; class Player { private: int id; static int next_id; public: int getID() { return id; } Player() { id = next_id++; } }; int Player::next_id = 1; int main() { Player p1; Player p2; Player p3; cout << p1.getID() << " "; cout << p2.getID() << " "; cout << p
1 min read
C++ | Static Keyword | Question 3
Which of the following is true? (A) Static methods cannot be overloaded. (B) Static data members can only be accessed by static methods. (C) Non-static data members can be accessed by static methods. (D) Static methods can only access static members (data and methods) Answer: (D) Explanation: A static function is a special type of function which is
1 min read
C++ | Static Keyword | Question 4
Predict the output of following C++ program. #include <iostream> using namespace std; class A { private: int x; public: A(int _x) { x = _x; } int get() { return x; } }; class B { static A a; public: static int get() { return a.get(); } }; int main(void) { B b; cout << b.get(); return 0; } (A) 0 (B) Linker Error: Undefined reference B::a
1 min read
C++ | Static Keyword | Question 5
#include<iostream> using namespace std; class Test { private: static int count; public: Test& fun(); }; int Test::count = 0; Test& Test::fun() { Test::count++; cout << Test::count << " "; return *this; } int main() { Test t; t.fun().fun().fun().fun(); return 0; } (A) Compiler Error (B) 4 4 4 4 (C) 1 1 1 1 (D) 1 2
1 min read
C++ | Static Keyword | Question 6
Output of following C++ program? #include <iostream> class Test { public: void fun(); }; static void Test::fun() { std::cout<<"fun() is static\n"; } int main() { Test::fun(); return 0; } Contributed by Pravasi Meet (A) fun() is static (B) Empty Screen (C) Compiler Error Answer: (C) Explanation: The above program fails in compi
1 min read
Static Keyword in C++
Prerequisite: Static variables in C The static keyword has different meanings when used with different types. We can use static keywords with: Static Variables: Variables in a function, Variables in a classStatic Members of Class: Class objects and Functions in a class. Let us now look at each one of these uses of static in detail.Static VariablesS
5 min read
Internal static variable vs. External static variable with Examples in C
The static variable may be internal or external depending on the place of declaration. Both kinds of static variables are stored in initialized data segments. Internal Static Variables Internal Static variables are defined as those having static variables which are declared inside a function and extend up to the end of the particular function. Synt
2 min read
Comparison of Exception Handling in C++ and Java
Both languages use to try, catch and throw keywords for exception handling, and their meaning is also the same in both languages. Following are the differences between Java and C++ exception handling: Java C++ Only throwable objects can be thrown as exceptions.All types can be thrown as exceptions.We can catch Exception objects to catch all kinds o
4 min read
Comparison of double and float primitive types in Java
Consider the following two codes in Java: Java Code // This program prints true class Geeksforgeeks { public static void main(String args[]) { float f = 5.25f; double d = 5.25 System.out.println(f == d); } } Output true Java Code // But this program prints false. class Geeksforgeeks { public static void main(String args[]) { float f = 5.1f; double
2 min read
Java 11 - Features and Comparison
Every 6 months, Oracle releases new Java versions. The September Java 11 version is already making a lot of buzz in the computer science world even before it was released by declaring that from now on Java is gonna be paid for commercial use. The following articles will show important features, enhancements, and deprecated features about JDK 11. Im
5 min read
Comparison of Inheritance in C++ and Java
The purpose of inheritance is the same in C++ and Java. Inheritance is used in both languages for reusing code and/or creating an ‘is-a’ relationship. The following examples will demonstrate the differences between Java and C++ that provide support for inheritance. 1) In Java, all classes inherit from the Object class directly or indirectly. Theref
4 min read
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, but it surely is a tricky one as there are certain differences in its usage in both Java and C++, which if not taken care, can result in an error. The differenc
5 min read
Comparison of Java with other programming languages
Java is one of the most popular and widely used programming language and platform. A platform is an environment that helps to develop and run programs written in any programming language. Java is fast, reliable and secure. From desktop to web applications, scientific supercomputers to gaming consoles, cell phones to the Internet, Java is used in ev
4 min read
Brief Overview & Comparison of Object-Oriented Programming from C to Java
In this article, you will get the ability to think how really OOP works in Java through C. Through C, you will understand the concept of Polymorphism, Inheritance, Encapsulation, Class, Objects, etc. As you also know C language don't support OOP, but we can understand the concept behind it by defining a fine structure as a Class and Creating its Id
3 min read
Comparison of Autoboxed Integer objects in Java
When we assign an integer value to an Integer object, the value is autoboxed into an Integer object. For example the statement "Integer x = 10" creates an object 'x' with value 10. Following are some interesting output questions based on comparison of Autoboxed Integer objects. Predict the output of following Java Program // file name: Main.java pu
2 min read
Image Processing in Java - Comparison of Two Images
Prerequisites: Image Processing in Java - Read and WriteImage Processing In Java - Get and Set PixelsImage Processing in Java - Colored Image to Grayscale Image ConversionImage Processing in Java - Colored Image to Negative Image ConversionImage Processing in Java - Colored to Red Green Blue Image ConversionImage Processing in Java - Colored Image
4 min read
Usage of Enum and Switch Keyword in Java
An Enum is a unique type of data type in java which is generally a collection (set) of constants. More specifically, a Java Enum type is a unique kind of Java class. An Enum can hold constants, methods, etc. An Enum keyword can be used with if statement, switch statement, iteration, etc. enum constants are public, static, and final by default.enum
4 min read
Using the super Keyword to Call a Base Class Constructor in Java
We prefer inheritance to reuse the code available in existing classes. In Java, Inheritance is the concept in which one class inherits the properties of another class. In the below example there are two classes Programming and DP while Programming is Parent class and DP is child class. From the main class, we have created an object of DP i.e. child
5 min read
super keyword for Method Overloading in Java
We use Method overloading to use a similar method for more than one time. This can be achieved by using different parameters in the signature. In the below example a class GFG with three similar methods is available, though the three methods are overloaded they are provided with different parameters. The object of the class GFG calls a method with
4 min read
Practice Tags :