Question

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.

Was it helpful?

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.

OTHER TIPS

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.

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top