简体   繁体   中英

Java being strongly typed

I came across this section in some class notes:

在此处输入图像描述

Java programs are what is known as statically and strongly typed.

I'm familiar with the concept of static or dynamic types, but haven't come across strong/weak types, and in looking them up there is always some wishy-washy definition.

In the above, what would be an example of how Java is strongly typed? Does it just mean that you cannot cast one type to another (but what about casting an int to a long or something of the same conceptual type)? How does the concept of strong/weak types relate to Java?

In a Weakly Typed language conversion between unrelated data types is implicit.

For eg JavaScript is a Weakly Typed language:

var x = 22;
var y = x + "example";
console.log(y);  # prints 22example as an instance of String object
# Here the value of x got converted to string without any explicit conversion by the programmer.

A Strongly Typed language is exact opposite. You can do type conversion in Strongly Typed languages, but they are not implicit. You have to do them explicitly.

For eg Java is a Strongly Typed language:

int x = 2;
Long y = x; # Will throw compilation error
# However you can do something like below example
Long y = new Long(x);
# There are other ways to do type conversion in java for different data types, but they are not implicit, you gotta do them explicitly.

I hope this answers your question.

Strongly typed means, variable's data type has to be defined in program. This data type will be fixed at compile time. Unlike in loosely typed, where don't declare data type for variable in program. Data types are assigned in these cases at runtime.

Javascript is a loosely and dynamically typed language. Here we declare like: var age="old"; var income= 4000000; Here, age will be made string type and income will numbers type at runtime in JS.

Hope this contrast between Java and JavaScript helps in understanding this concept.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM