Rationale behind methods that convert values [closed] - java

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
What is the purpose of having methods converting one value into another value of a different type. For example a method that converts a string of digits into an int and another method converting an int into a string of digits? What exactly would be the advantages to doing one over the other? Is it there is no advantage and the methods for conversion exist only to provide compatible values for the arguments of the constructors of different classes?

Simply, it's because those different types exhibit different behaviors:
String str = "42";
System.out.println(str + 1);
System.out.println(Integer.parseInt(str) + 1);
421
43
You need to have methods like Integer.parseInt() if you want to perform normal addition as opposed to string concatenation, for example.
A tangible example of this can come up when you read a number as input from a user; more often than not you will want to treat this number as a number (double, int, etc.) as opposed to a string.

The different forms serve different purposes beyond providing compatible values for methods and constructors.
For the int type, mathematical operations are most easily performed on this type (and similar primitive types). User input is usually given in the form of a String, so to perform a mathematical operation on user input, one must convert it into an int (or a double, long, float, byte, or short as appropriate).
For converting to a String: This is how numerical output is displayed. We may code System.out.println(myInt);, but behind the scenes, Java is converting the number to a String for display purposes.

Since you used the "Java" tag, I'll answer you regarding java.
It is because, Java was written this way . There are languages that do not need types (lisp for example) and you can read a string (from Std. In) and raise it to a power (for example) if it is a number. But Java needs types. The compiler wants to know it ahead.
One useful advantage of being able to convert numbers to string is that you are able to use very large numbers, storing them as strings, instead of integers. However you cannot work with strings when you use the regular operators (+,-,*,/).
Another advantage: when you have a TextField and you read user input, it is given as a string. So you need to get a number out of it to work with it.

Related

Casting primitive types [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed last month.
Improve this question
I investigated a lot about this but I didn't find an answer that convinces me; for that reason I decided to ask it here.
When you do casting, what occurs internally with the compiler? For example:
double b= 5.67
a = (int) b
Does java convert the type of the variable or converts the internal value of?
Normally, the Java compiler will prevent you from assigning primitives that might result in a loss of data. You don't make it clear, but I am assuming that a is an int. Assigning a double to an int can result in information being lost, so the compiler objects.
If you add a cast the compiler ignores the issue and adds code to do whatever is necessary to convert the value from one type to the value of the other (in this case, assuming a is an int, simply truncating the double in many cases) and ignores any data loss. The type of the variables remains unchanged. Only the value changes.
There is a bit more to it than that for certain values. For example, if the double has the special value NaN (not a number) it is converted to int 0. See in the Java Specification 5.1.3. Narrowing Primitive Conversion.

Are classes with identical values .equals()? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I'm using Point3D.
I have a list full of Point3Ds. I need to create a NEW Point3D at some point, and check if the list contains it.
Will this list ever contain it as it is technically a different reference/object BUT has identical values?
I understand this is a lack of fundamental knowledge in my Java.
A List doesn't care what you put in it - put ten things in, get ten things out.
A Set however will generally only have unique values in it (using .equals() and hashCode() and in some sets other things - e.g. Comparator).
Normally I'd say "to the javadoc" however in this case it has a case of cut/paste'ism from Point3D JavaDoc
equals
public boolean equals(Object obj)
Returns a hash code value for the point.
Overrides:
equals in class Object
Returns:
a hash code value for the point.
So assuming it does what most people expect if you have two points generated with identically valued doubles then yes it'll be as you expect.
HOWEVER, floating point numbers you can easily be "very very close" when you expect to be identical (due to the representation of the value as FP), and remember there are 3 doubles in a Point3D [so 3 potential lots of small error] - so to be safe typically you might decide things are the same within some small distance see javadoc for distance rather than relying on exact matching.

What does it mean when there is a -- before an in value in java? Also what is a StringBuilder [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I am trying to finish an assignment in my intro to Java course, and I have some questions. First off, what does it mean when there is a -- in FRONT of an int value? Also what is a String Builder? I had some help but want to understand what it is I'm using in the code. Thanks.
The -- in front of a value simply means subtract 1 from it. Similarly, ++ in front of a value means add 1 to it.
If you write ++
before the number it is called prefix operator and if after then its post fix
preFix: ++a will increase the value before using it, will first increase and then use it.
postFix a++ will first use it and then use it, for later use you will get the incremented value.
-- is a predecrement
Java StringBuilder class is used to create mutable (modifiable) string.
A String is immutable i.e string cannot be changed once created and everytime a value is change it create new string.
But in case of StringBuilder which is mutable string can change.
My experience is mostly with C# not Java, but in C# strings cannot be changed, when you concatenate two strings like "hello" + "world" you do not change either string, you create a new one and the old two still exist. If you need to do this many times (dozens or hundreds) it can use a lot of memory. A StringBuilder allows you to conserve memory by appending characters to the same block of memory while you are building your string, and then you can turn the result into a normal string for passing around to other functions.

Why we don't see much use of BigInteger? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
I'm a beginner in java and our professor avoided discussing BinInteger and BigDecimal classes from java.math package.I wonder why.Are they not that useful?When exactly we must need to use BigInteger?
You don't need them particularly often, but when you do need them you really need them. You really only need them when you need to actually store arbitrary precision integers or real numbers. long goes up to 263-1, which is a pretty big number.
Always use the primitives when possible because:
They have operators rather than methods, so code is easier to read/write.
They are a lot more efficient.
long, the largest primitive integer type, has a maximum value of 9,223,372,036,854,775,807, or 2^63 - 1, and a minimum value of -2^63.
double, the most precise primitive floating point type, has 64 bits of precision, which is a lot.
However, if you really need an arbitrarily large/small integer or arbitrarily precise decimal number, the BigInteger and BigDecimal types are appropriate. Such scenarios aren't that common, however, which is probably why your professor didn't discuss these types.
Decimal data types are essential when dealing with currencies
The primitive types of int and long have a limited range of values they can represent. The same is true for the floating point primitives float and double. There however you also face the issue of a limited precision. For many cases this does not pose any problem however when larger numbers or exact precision is required (e.g. in a banking application you will want to be as precise as possible) you will use BigInteger and BigDecimal however.
BIGINT is always the product of two Ints.
Example 99X99 = 10000 upto twice as big.
Both of the libraries you mentioned has their uses, if they didn't they wouldn't exist. However, your teacher probably elected not to discuss them as you probably wont be using them in your specific course. (He has to put a limit somewhere, you cannot cover the entirety of Java libs in one course.)

What data type should i use? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
hi i have a java programming assignment wich include 3 exercice i have done 2 already but in the third one i am dont know wich data type i should use
here is the question :
Write a java program that reads from the user the course code, section and the scores of a student for three exams representing two midterms and a final. The percentage of each of the three exams is of fixed value 30, 30 and 40 percent respectively. Your program computes the final average grade and displays it along with the course code and the section.
Remark: All data, except for the average, must be whole numbers and you should use the most efficient data type that is suitable for this specific exercise.
Sample Run:
Enter your course code: CSCI250
Enter your section: E
Enter the scores of the tests and the final: 97 83 77
CSCI250 E 84.8 (result)
so what i want to know is what is the preferable data type to use for course code ? and char is the one that i should use for section right ?
If you're capturing user input, use a String for everything.
Reason? You may request a number, but the user can type anything. Your code needs to handle bad input.
I think you can use String as data type for Course Code. You can write both numbers and letters by using it. And for section, yes, char will be suitable for it.
Use a String for arbitrary text.
If the section code is always present1 and is never more than character than a char can be used.
However, I would still use a String for consistency, flexibility, and easy of use. The teacher may prefer this based on the "efficient"cy they are going for.
1The is a soft "always": while char cannot represent null a sentinel (eg. '\0' or ' ') can be used to indicate 'no section specified'. Using such a sentinel to supplement null can also (but does not always) lead to more logic work - in particular when the record is displayed.
In any case, it is probably best to not switch to Character just for the null as this is most likely outside of the scope of current course work.

Categories

Resources