×

Static keyword in C++ vs Java

Both in C++ and Java, the static keyword is employed for essentially the same function. But there are some variations. The static keyword's similarities and differences between C++ and Java are discussed in this article.

What do we mean by the keyword Static ?

In the C++ programming language, static is used to help an element with some strict characteristics. Static elements are permitted to be given the storing location only in the static storage region once during the program's entire lifetime. And they're justifiable as long as the program is being executed.

In Java, memory management is the main application for the static keyword. Blocks, nested classes, variables, methods, and blocks can all be utilised using the static keyword. Instead of referring to a class instance, the static keyword is connected to the class.

Java and C++ Share Similarities for Static Keyword :

  • Both languages allow for the definition of static data members.
  • In both the programming languages, static member methods can be defined.
  • Without constructing any objects, it is simple to access static members.

C++ and Java's differences for static keywords :

C++ :

  • Static blocks are not supported by C++.
  • Declaring Static Local Variables is possible.

Java :

  • Java allows for static blocks (also known as static clause). It is often in use for static initialization of a class.
  • The use of static local variables is not permitted.

Below, the details of the aforementioned points are discussed :

1.Static Data Members:

Static data members in Java, just like they are in the C++ programming language, are shared among all the objects and are class members. For instance, the static variable count is often used to tally the number of objects produced in the Java programme below.

Example :

class Testing {
	static int counting = 0;


	Testing() { counting++; }
	public static void main(String arr[])
	{
		Testing T1 = new Testing();
		Testing T2 = new Testing();
		Testing T3 = new Testing();
		Testing T4 = new Testing();
		Testing T5 = new Testing();
		System.out.println("In Total " + counting
						+ " objects are created");
	}
}

Output :

In Total 5 objects are created

2. Static Member Methods :

Static member methods can be expressed in the C++ as well as Java programming languages. The following limitations apply to methods that are class members and are specified as static :

A) They are limited to calling static methods. As an illustration, the compilation of the programme mentioned below fails. funct() is not static and is used in the static main() function.

Example :

class Main {
	public static void main(String argmnts[])
	{
		System.out.println(fun());
	}
	int funct() { return 123; }
}

B) Only static data should be accessed.

C) They are unable to access this or super. As an illustration, the compilation of the following software fails.

Example :

class BaseClass {
	static int a = 0;
}


class DerivedClass extends BaseClass {
	public static void funct()
	{
		System.out.println(super.a);
	}
}

Output :

Compiler Error: non-static variable can’t be referenced from a static context

D) Static methods and data members can be accessible without first generating an object, much like in C++. The class names can be used to get to them. As an illustration, the static function funct() and the static data member counting are accessible without the use of an object in the following programme.

Example :

class Testing {
	static int counting = 0;
	public static void funct()
	{
		System.out.println("\nStatic funct() is called");
	}
}


class Main {
	public static void main(String ar[])
	{
		System.out.println("Testing.counting = " + Testing.counting);
		Testing.funct();
	}
}

Output :

Testing.counting = 0
Static funct() is called

3. Static Block :

With exception of C++, Java allows a specific type of block known as a static block (sometimes known as a static clause), which is used for a class' static initialization. The static block's code is only invoked once.

4. Static Local Variables :

C++ allows the use of static local variables, in contrast to Java. For instance, the compilation of the following Java application fails :

Example :

class Testing {
	public static void main(String argmnts[])
	{
		System.out.println(funct());
	}
	static int funct()
	{
		static int a = 97;
		return a--;
	}
}

Output :

Compiler Error: Static local variables are not allowed

Related Topics

Data Hiding in C++

C++ : High-performance apps can be made using the cross-platform language C++. Bjarne Stroustrup created C++ as an addition to the C language. Programmers have extensive control over memory and system...

3 minutes read.

Approach in C++

Object oriented programming languages like Java or C++ use a bottom-up approach that identifies each object first.  In the bottom-up approach, we create a small problem first, and try to...

6 minutes read.

Initialize Vector in C++

Initialize Vector in C++  The following comparison operators are defined for vector and those are given below. ==, <, <=, !=, >,>=  This allows you to access the element of a vector using...

3 minutes read.

C++ Math Functions

C++ Math Functions: Like other programming languages, C++ offers plenty of mathematical functions needed for various purposes. These functions are defined mainly in the math library in C++. Let us...

4 minutes read.

Diamond Pattern using While-loop in C++

What is while Loop? A while loop or while statement repeats all code of its body as long as a specific condition is satisfied. The loop ends if or when the...

5 minutes read.

Unary Operators in C++

Unary operators in C++ Unary operator: is operations that function to produce a new value on a single operand. a) unary minus: A minus operator modifies the argument's symbol. A positive number...

3 minutes read.

Pure Virtual Function in C++ With Example Program

What is a Virtual Function? A virtual function is created inside a class with the keyword virtual. A virtual function does not have any value to be returned. Once a virtual...

3 minutes read.

Division in C++

C++ Division Arithmetic Operation In C++ the arithmetic operator / is used for division. This operator takes two operands and returns the result of dividing the left operand by the right...

3 minutes read.

How to call a void function in C++

Generally, any function has two types: 1. Void function: It doesn't return any value. 2. Non-void function: It returns some value. Program to call a void function in C++ #include <iostream> using namespace std;  void check() {  ...

2 minutes read.

Sizeof() Operators in C++

sizeof() Operators in C++ The sizeof() operator in C++ defines the size of variables, constants, or data types. It is a unique operator that manipulates other operators and returns the size...

4 minutes read.

Tensorflow in C++

With cppflow, you can execute TensorFlow models in C++ without Bazel, TensorFlow installation, or TensorFlow compilation. Tensor manipulation, eager execution, and running stored models straight from C++ are all possible. Knowing...

7 minutes read.

Binary Operator Overloading in C++

The Binary Operator Overloading in the C++ programming language will be covered in this part. An operator which comprises two operands to execute a mathematical operation is termed the Binary...

6 minutes read.

How to create a directory or folder in C/C++?

A directory is to lists all files and subdirectories in a directory, set of the files will be kept in the directory, which is a location. A subdirectory is a...

5 minutes read.

C++ array to function

Arrays in C++ : Instead of defining distinct variables for each item, arrays are used to hold numerous values in a single variable. An array can be declared by specifying the variable...

4 minutes read.

Features and Use of Pointers in C/C++

What is a pointer? A pointer is mainly used to store the address of another variable. The * operator creates a pointer variable, which points to a data type (like an...

7 minutes read.

External merge sort in C++

External merge sort in C++ External sorting is a concept for a group of sorting algorithms capable of handling large data volumes. External sorting is needed if the information getting sorted...

9 minutes read.

Const Keyword in C++

The const programming language keyword will be covered in this section. The constant value that cannot change during program execution is defined using the const keywords. It implies that once...

9 minutes read.

C++ Encapsulation

The following two essential components are present in all C++ programmes: Functions are the parts of a programme that perform actions, and they are termed programme statements (code).Program data is the...

4 minutes read.

Leap Year Program in C++

What is a Leap Year? A solar year is the length of time that it takes for Earth to orbit the Sun - approximately 365.25 days. In a calendar year, we...

4 minutes read.

Auto keyword in C++

The primary function of auto keyword is to assign and detect the value of the data type automatically in C++. The compiler knows the data type of the variable by...

2 minutes read.