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

2.3k views Asked by At

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.

3

There are 3 answers

0
Prashant Kumar On BEST ANSWER

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.

4
rgettman On

This example doesn't prove Java isn't strongly typed. There's just an implicit string conversion (JLS, Section 5.1.11) going on behind the scenes.

First, conversion to a reference type occurs to create an Integer from the int literal (new Integer(4)), then toString() is called to convert it to a String for concatenation.

0
Simone Gianni On

If you want another funny example, you can find in many places the ugly

intNumber+""

to convert a number to string. Programmers are lazy and don't want to write

Integer.toString(intNumber)

And this causes a string conversion AND a useless string concatenation at runtime.

This does not mean Java is not strong typed, simply all Objects need to have a toString() method, and all primitives can be automatically boxed and unboxed to their non-primitive counterparts (int -> Integer, long -> Long etc..) which implement toString(), and "+" in java acts as string concatenation.