×

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

Default arguments in C++

Arguments in a function are defined as the values supplied when the function is called. The source is the values supplied, and the destination is the receiving function. Let us...

3 minutes read.

C++ Output Iterators

Iterators : Iterators serve as a link between algorithms and STL containers, allowing the data inside the container to be modified. They let you to iterate through the container, access and...

4 minutes read.

Swap numbers in C++

Swap numbers Swapping refers to interchanging values between two variables. Swapping is important and easy to understand programming logic in the world of coding. Though it is used in the programming...

4 minutes read.

rand() and srand() in C / C++

In this tutorial, we'll explore the syntax, usage, and examples of the C++ STL functions rand() and srand(). What exactly is rand()? The C++ STL's built-in rand() function is defined in the...

3 minutes read.

Function overloading in C++

Function overloading in C++ As we know that C++ works on the OOP Concepts, that are abstraction, encapsulation, and data hiding, it also uses the other important feature of OOP, which...

8 minutes read.

Name Mangling and extern in C++

Name Mangling and Function Overloading: Function overloading is a feature offered by C++. As long as each function accepts various parameters, we can use this to write many functions with the...

4 minutes read.

getline() Function and Character Array in C++

In this article, we will explore about some concepts on getline() function and character array in the most useful language C++. The getline() method in C++ is simply a standard library...

6 minutes read.

Pointers in C++

Pointers are a powerful feature in the C++ programming language, allowing developers to directly manipulate memory addresses and create more efficient and dynamic programs. However, pointers can also source various...

3 minutes read.

Program to arrange an array in alternate positive and negative numbers

Let’s say, there is given an array arr, arrange the array in such a way that every positive number is followed by a negative number. If there are extra positive...

4 minutes read.

C++ Fork

A new process known as a "child process" is created with the fork system function and runs concurrently with the process that invoked fork() (parent process). Both processes will carry...

4 minutes read.

Abstract class in C++

In this article, you will get exposure to an abstract class in C++. We will discuss this topic using some practical examples too. To understand the abstract classes, you should...

6 minutes read.

C++ Program to Implement Merge Sort

C++ Program to Implement Merge Sort The technique of merge sort is based on the strategy of divide and conquer. We divide the set of while data into smaller bits, arranged...

3 minutes read.

C++ Enumeration

C++ Enumeration In C++, Enum is a special data type that contains some fixed sets of components that have various applications in the programming. Enum works fine with fixed constant sets...

3 minutes read.

Templates in C++ vs Generics in Java

As the title suggests, there is no rivalry or there is no cut comparison between generics and templates in Java and C++, respectively. The main aim of this article is...

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

Snake Code in C++

Snake is a popular game that can be played on almost any device and runs on any operating system. In this game, snakes can move in any direction, including left,...

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

C++ Signal Handling

Signals are interruptions sent by the operating system to a process to cause it to cease doing its current job and focus on the task for which the interrupt was...

4 minutes read.

Initialize Array of objects with parameterized constructors in C++

Initialize Array of objects with parameterized constructors in C++ When a class is defined, only the specification for the object is specified; no memory or capacity is allocated. You need to...

3 minutes read.

C++ Deque

Definition: Deque or the Doubly ended queue is a data structure or operation performed under queue where insertion and deletion are allowed at both ends. A deque is an ordered collection of...

5 minutes read.