Search code examples
javapythonstringstring-concatenationstrong-typing

is Java weak typed as this example demonstrates when compared with python?


I familiar with what strong and weak types are. I also know that Java is strongly typed. now I learn python and it is a strong typed language. But now I see python is "more" strongly typed than Java. example to illustrate

public class StringConcat {

  public static void main(String[] args) {
      String s="hello ";
      s+=4;
    System.out.println(s);
}
}

No error and prints hello 4

in python

>>> x="hello"
>>> x+=4
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: cannot concatenate 'str' and 'int' objects

so this example demonstrates that python is strongly typed. unless Java under the hood, does some manipulation to convert int to String and do String concat.


Solution

  • Java is still strongly typed, despite your example. The code is equivalent to

    String s = "hello ";
    s = s + 4;
    

    and Java will convert the 4 into a string, then perform the string concatenation. This is a language feature.

    In Python, however, you cannot use + to concatenate 4 to your string, because the language will not take the liberty of converting it to a str. As you point out, Java does this for you under the hood.