-6

It might be trivial, but I am a beginner in Java so any help will be much appreciated! The error I get if I run the program

public class Main {
    public static void main(String args[]) {
        if(1)
           System.out.println("Hello World!");
    }
}

is

Main.java:3: error: incompatible types: int cannot be converted to boolean if(1) ^

but the following code in C++ works

#include <iostream>
using namespace std;
int main() {
    if(1)
        cout<<"Hello World!";
}

Does Java not consider 0 as false and any number other than 0 true, like in C++?

François Andrieux
  • 28,148
  • 6
  • 56
  • 87
  • 16
    Different languages. Difference rules. – Eran Dec 18 '19 at 14:50
  • 7
    Java and C++ are completly different languages. Do not expect what works in one will work in the other. They have different styles of coding and you should forget you even know C++ and just learn Java like you would if it is your first language. That will help you to get into the Java frame of mind. – NathanOliver Dec 18 '19 at 14:50
  • 4
    I disagree with the close reason being "_This question is opinion-based._" How is this question opinion-based? This question is about different rules, of different languages. Those rules are defined, and not a subject to an opinion. – Algirdas Preidžius Dec 18 '19 at 14:55
  • 1
    @NathanOliver-ReinstateMonica Yes, I would agree, that closing it as a dupe, with the target, you linked to, would be much more accurate, than this question being "opinion-based". – Algirdas Preidžius Dec 18 '19 at 15:00
  • @AlgirdasPreidžius Alright, now it is a duplicate. – NathanOliver Dec 18 '19 at 15:02

1 Answers1

3

The reason for that is simple - in java every condition must be resolved as a boolean value (true of false) while in c / c++ false is 0 while true is anything else...

Yonatan Karp-Rudin
  • 1,056
  • 8
  • 24