Similarities between Java and C++
Mithlesh Upadhyay
Seeking Generative AI Data Scientist roles | Experienced in Generative AI, LLM, NLP & Python | M.Tech in Artificial Intelligence from DTU
Java and C++ are the two most popular programming languages. Although they have many differences, there are quite a lot of similarities between them.
Let us look into the similarities between Java and C++.
1. Comments
Comments are same in C++ and Java. Single line comments are done by // and multiple line comments are done by/*.....*/ .
Examples have been given below.
2. Main function
In both C++ and Java execution of the program is initiated from the main() function. Example –
In both Java and C++ main() function is there but their syntax is quite different.
public class Java {
// main() function in Java
public static void main(String[] args) {
// Write your code here
}
}
But in C++ it is quite different
// main() function in C++
int main() {
// Write your code here
}
3. Classes And Objects
Java is an object-oriented programming language. C++ also supports classes and objects.
(But C++ is not fully object oriented language, a C++ programs can easily be written without concepts of classes and objects.).Example –
Here we give a simple example of a complex class in C++ and Java.
领英推荐
class Complex{
float re;
float im;
};
//Note that ‘;’ is not given at the end of classes in Java
4. Control Constructs
Major Control Constructs (for , while loops if etc.) in C++ and Java are identical. Example –
In both Java and C++ loops, if-else statements are as follows:
int fact = 1;
for(int i=1;i<=m;i++)
{
//Computes factorial of a given number m
fact=fact*m;
}
5. Primitive Types
Primitive types in Java are almost the same as that of C++.
(Though there are some differences, such as unsigned int data type is present in C++, Java does not support it. In contrast, Java has bigInteger data type that theoretically has no limit but C++ does not support such data types. Example –
In both C++ and Java primitive types are declared as follows:
int a,b=5;
float c=0.7;
Relational And Arithmetic Operators
No significant difference.
Example –
a +=5;
b =5*4;
P.S. -?I have contributed this article here -?Similarities between Java and C++