How does a number differ from a string in java?
2 answers
A string is not a primitive data type in contrast to numbers. A string is an object ( class String extends Object ), an OOP wrapper over an array of primitives of type char . They can be obtained by calling the toCharArray() method:
char[] chars = "chars".toCharArray(); All numbers are primitive data types . They are designed to store various numeric values. There are integers - short (2 bytes), int (4 bytes) and long (8 bytes); there are fractional - float (4 bytes) and double (8 bytes).
short s = 0; int i = 0; long l = 0L; float f = 0.0f; double d = 0.0d; Some lines can be read as numbers using special methods.
Integer.parseInt("123") == 123; Float.parseFloat("123.0") == 123.0; // Нельзя, вызовет исключение //Integer.parseInt("abcdef"); All numbers can be represented in string form by calling the static methods of wrapper classes.
Integer.toString(123) == "123"; Float.toString(123.0) == "123.0"; Even if the lines contain something representable as numbers, they cannot be added as numbers. Instead, a concatenation (union) of strings will occur:
"123" + "456" == "123456"; First you need to convert to numbers.
Integer.parseInt("123") + Integer.parseInt("456") == 579; Important
Strings are objects, so they need to be compared carefully. Just == will not always work as you might expect:
- Um ... The string is not a primitive and the link is also not mentioned in the list of primitives. A string is an object, OOP-wrapper over an array of
charprimitives - YuriySPb ♦ - @Yuriy SPb yes, right) correct? - Nick Volynkin ♦
- Corrected) Plus, in Java, the lines in double quotes are written) Added some useful links. - JuriySPb ♦
- one@ YurySPb thanks! Quotes - I'm used to Python. ) - Nick Volynkin ♦
Well, these are different types of data that are stored in memory.
A string is a text — a data structure, a series of words, letters, or other characters — characters enclosed in quotes.
And the number is the value with which the counting or calculation of mathematical operations begins, there are also categories and subcategories of numbers, digits, sets and much more.