In depth understanding :Java is a type safe language while C++ is a non type safe language
- 2020-04-02 01:11:14
- OfStack
Anyone with experience with C++ will find that we can use 0 as false and non-zero as true. A function of type bool can return an int and automatically convert 0 to false and non-zero to true. The code example is as follows:
However, in Java, we can't use this way, Java can't do int to bool type, such as the following code:
Execution of the above code will report the following error:
The above error indicates that an int type cannot be automatically converted to a bool type in Java. That's what type safety means.
#include<iostream>
#include<stdlib.h>
using namespace std;
bool fun()//The function return type is bool, but we can return an int in the function.
{
return 1;
}
void main()
{
int a=1;
if(a)//A is of type int, but can be used as a bool.
{
cout<<"C++ Non-type safe. "<<endl;
}
system("pause");
}
However, in Java, we can't use this way, Java can't do int to bool type, such as the following code:
public class TypeSafeTest {
public static void main(String[] args) {
int i=1;
if(i)
{
System.out.println("java Is a type safe language ");
}
}
}
Execution of the above code will report the following error:
Exception in thread "main" java.lang.Error: Unresolved compilation problem: Type mismatch: cannot convert from int to boolean
at TypeSafeTest.main(TypeSafeTest.java:4)
The above error indicates that an int type cannot be automatically converted to a bool type in Java. That's what type safety means.