Question

I'm playing devils advocate here, but if casting is so easy and not able to be disallowed why not just use all string types in Java and just cast to a number right before the math operation.

Casting seems to sort of defeat the purpose of a Strongly typed language.

What advantages/point are there to actually using primitive numeric types?

edit: sorry for calling it casting, I was under the impression that casting was a general term for coverting between types, I see now it's for primitive types and parsing is what happens when converting a string. TIL!!

Was it helpful?

Solution

First let's make sure you understand what parsing and casting is:

Parsing and casting are two entirely different beasts. Parsing is (normally) the process of analyzing a String and checking whether or not it obeys certain grammar rules, e.g. your Java source code is parsed for syntax errors.

Casting primitive types (ints, longs, doubles) is converting one type to another type according to certain rules. Parsing object types is 'viewing' an object as another type, e.g. a String also is an Object and it also implements the interface Comparable. You can view/cast a String to all the other types.

Source: http://www.java-forums.org/new-java/35811-parsing-vs-casting.html

You cannot cast a String to int:

String line = "7";   
int a  = (int)line;// This doesnt work, you'll get an error  

However, you can parse it:

String line = "7";  
int a = Integer.parseInt(line);//This is a perfectly acceptable statement in java  

Source: http://www.coderanch.com/t/439266/java/java/Casting-Parsing

Now, the reason why we don't standardize Strings as our primitive data type is for a a handful of reasons:

  • Inefficient to parse
  • Easier to compile into machine/assembly language if variables are purely primitive data types (double, int, boolean).
  • If we used "0" instead of 0, then the program would have to take an extra step to realize the String is the value zero where as it could easily grab it from the registry.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top