In php/perl we can simply say $a=’hi” and then $a=1 without needing to declare its type. But there are type casting errors in java for the same.
Why this difference?
PHP is dynamically typed, while Java and C are statically typed.
With static typing, type checking can be done at compile time and this can catch many errors, so it’s not necessarily a bad thing. This also allows them to be much faster than dynamic languages.
Just because a language is statically typed like the other answers here are saying, it doesn’t mean it needs explicit type declarations. There are many type inference algorithms out there that work extremely well, needing only rare type declarations.
It just happens that in dynamic languages, they tend to (more often than not) not care so much about the type of an object, but rather that it respond to a specific set of behaviour (duck typing), so it doesn’t typically matter for them what the explicit type is.
The type declaration hinting is helpful to the compiler, though not explicitly required for the common case (and depending on inference algorithm, only required in complex cases).
As others mentioned Java, C, C++ are statically typed. PHP, Perl, Ruby, Boo and so on are dynamically typed.
However some statically typed languages such as for instance C#4 supports dynamically typed programming as well.
dynamic x = 3;
Functional languages, C++, C# and others also supports type-inference which means it’s still uses static types but the compiler infers the type.
auto x = 3; // C++0x
var x = 3; // C#
let x = 3 // F#
Why do statically typed languages suffer from type casting errors as well? Because they support inheritance and downcasting from superclasses to subclass. Downcasts can’t in general be verified in compile-time but can be detected in run-time and will generate an exception.
Java uses a so-called static type system. This means that every variable is defined to have a specific type at compile time, and this cannot be changed. Like any features, there are pluses and minuses to this. In general, the compiler can catch many more programming errors if the types are fixed, and generally produce more robust code.
Many (but not all) compiled languages use static typing because it helps the compiler make faster machine (or byte) code. It also helps the compiler find errors in your code.