Unexplained parenthesise in Java - java

What do parenthesis do in Java other than type casting.
I've seen them used in a number of confusing situations, here's one from the Java Tutorials:
//convert strings to numbers
float a = (Float.valueOf(args[0]) ).floatValue();
float b = (Float.valueOf(args[1]) ).floatValue();
I only know only two uses for parenthesis, calls, and grouping expressions. I have searched the web but I can't find any more information.
In the example above I know Float.valueOF(arg) returns an object. What effect does parenthesize-ing the object have?

Absolutely nothing. In this case they are not necessary and can be removed. They are most likely there to make it more clear that floatValue() is called after Float.valueOf().
So this is a case of parenthesis used to group expressions. Here it's grouping a single expression (which does obviously nothing).
It can be shortened to:
float a = Float.valueOf(args[0]).floatValue();
float b = Float.valueOf(args[1]).floatValue();
which can then be logically shortened to
float a = Float.parseFloat(args[0]);
float b = Float.parseFloat(args[1]);

I dont believe they serve any purpose here. Maybe left over after some refactoring

None other than to confuse you. It's as good as saying
float a = Float.valueOf(args[0]).floatValue();
directly.

I suspect the programmer just found it more readable. I don't agree with him in this particular case, but often use parentheses to make it clearer. For example, I find
int i = 3 + (2 * 4);
clearer than
int i = 3 + 2 * 4;

The extra parentheses in your code sample do not add anything.
//Your example:
float a = (Float.valueOf(args[0]) ).floatValue();
// equivalent:
float a = Float.valueOf(args[0]).floatValue();
It could be that the original programmer had done something more elaborate within the parentheses and so had them for grouping, and neglected to remove them when simplifying the code. But trying to read intent into old source is an exercise in futility.
The extra space in args[0]) ) is pretty odd looking, too, as it is unmatched in the opening paren.

Here they are used for grouping. What's inside one of those expression if of type Float, so you can apply the method floatValue() to the whole content of the parenthesis.
They could be removed here as there is no ambiguity. They would have been mandatory with an expression using another operator of higher preseance order. But according to the docs, there is no such operator, the dot/projector has highest priority. So they are really useless here.
Regards,
Stéphane

Related

Unexpected Identifier Expected Error [duplicate]

Why in java (I dont know any other programming languages) can an identifier not start with a number and why are the following declarations also not allowed?
int :b;
int -d;
int e#;
int .f;
int 7g;
Generally you put that kind of limitation in for two reasons:
It's a pain to parse electronically.
It's a pain for humans to parse.
Consider the following code snippet:
int d, -d;
d = 3;
-d = 2;
d = -d;
If -d is a legal identifier, then which value does d have at the end? -3 or 2? It's ambiguous.
Also consider:
int 2e10f, f;
2e10f = 20;
f = 2e10f;
What value does f have at the end? This is also ambiguous.
Also, it's a pain to read either way. If someone declares 2ex10, is that a typo for two million or a variable name?
Making sure that identifiers start with letters means that the only language items they can conflict with are reserved keywords.
That's because section 3.8 of the Java Language Specification says so.
An identifier is an unlimited-length
sequence of Java letters and Java
digits, the first of which must be a
Java letter. An identifier cannot have
the same spelling (Unicode character
sequence) as a keyword (§3.9), boolean
literal (§3.10.3), or the null literal
(§3.10.7).
As for why this decision was made: probably because this simplifies parsing, avoids ambiguous grammar, allows introduction of special syntax in a later version of the language and/or for historical reasons (i.e. because most other languages have the same restrictionsimilar restrictions). Note that your examples example with -d is especially clear:
int -d = 7;
System.out.println("Some number: " + (8 + -d));
Is the minus the first part of an identifier, or the unary minus?
Furthermore, if you had both -d and d as variables, it would be completely ambiguous:
int -d = 7;
int d = 2;
System.out.println("Some number: " + (8 + -d));
Is the result 15 or 6?
I don't know exactly but i think that's because numbers are used to represent literal values, so when the compiler find a token that starts with a number, it knows it is dealing with a literal. if an identifier could start with a number, the compiler would need to use a look ahead to find the next character in the token to find out if it is an identifier or a literal.
Such things aren't allowed in just about any language (I can't think of one right now), mostly to prevent confusion.
Your example -d is an excellent example. How does the compiler know if you meant "the variable named -d" or "the negative of the number in the variable d"? Since it can't tell (or worse yet, it could so you couldn't be sure what would happened when you typed that without reading the rest of the file), it's not allowed.
The example 7g is the same thing. You can specify numbers as certain bases or types by adding letters to the end. The number 8357 is an int in Java, where as 8357L is a long (since there is an 'L' on the end). If variables could start with numbers, there would be cases where you couldn't tell if it was supposed to be a variable name or just a literal.
I would assume the others you listed have similar reasons behind them, some of which may be historical (i.e. C couldn't do it for reason X, and Java is designed to look like C so they kept the rule).
In practice, they are almost never a problem. It's very rare you find a situation where such things are annoying. The one you'll run into the most is variables starting with numbers, but you can always just spell them out (i.e. oneThing, twoThing, threeThing, etc.).
Languages could allow some of these things, but this simplifying assumption makes it easier on the compiler writer, and on you, the programmer, to read the program.
Parsers are (usually) written to break the source text into "tokens" first. An identifier that starts with a number looks like a number. Besides 5e3, is a valid number (5000.0) in some languages.
Meanwhile : and . are tokenized as operators. In some contexts an identifier that starts with one of these would lead to ambiguous code. And so forth.
Every language needs to define what is a valid character for an identifier and what is not. Part of the consideration is going to be ease of parsing, part is going to be to avoid ambiguity (in other words even a perfect parsing algorithm couldn't be sure all the time), part is going to be the preference of the language design (in Java's case similarity with C, C++) and some is just going to be arbitrary.
The point is it has to be something, so this is what it is.
For example, are there not numerous times we wish to have objects with these names?
2ndInning
3rdBase
4thDim
7thDay
But imagine when someone might try to have a variable with the name 666:
int 666 = 777;
float 666F = 777F;
char 0xFF = 0xFF;
int a = 666; // is it 666 the variable or the literal value?
float b = 666F // is it 666F the variable or the literal value?
Perhaps, one way we might think is that variables that begin with a numeral must end with an alphabet - so long as
it does not start with 0x and end with a letter used as a hexadeciamal digit, or
it does not end with characters such as L or F,
etc, etc.
But such rules would make it really difficult for programmers as Yogi Berra had quipped about - how could you think and hit at the same time? You are trying to write a computer programme as quickly and error free as possible and then you would have to bother with all these little bits and pieces of rules. I would rather, as a programmer, have a simple rule on how variables should be named.
In my efforts using lexers and regexp to parse data logs and data streams for insertion into databases, I have not found having a keyword or variable beginning with a numeral would make it anymore difficult to parse - so long there are as short a path as possible to remove ambiguity.
Therefore, it is not so much as making it easier for the compiler but for the programmer.

Parsing of math expression gives wrong tree

So the code is rather complicated so ill try to do some neat pseudo code that covers the most important issues. I'm trying to parse a math expression. For example: 1-5*(-2)+3 = 14
The syntax that im using is:
expression = term OR term+expression OR term-expression
term = factor OR factor*term OR factor/term
factor = number OR -factor OR (expression)
I have written a piece of code which checks if an expression follows this syntax and it works well for checking the expressions but not for calculating it.
The pseudo code goes something like:
double readExpression()
number = readTerm()
if token == +
number2 = readExpression()
return number + number2
else if token == -
number2 = readExpression()
return number - number2
else
return number
...
(The code for readTerm() is identical to readExpression() in structure)
...
double readFactor()
if token == number
return number
else if token == -
number = readFactor()
return (-1)*number
else if token == (
number = readExpression()
return number
else raise exception
If I do the above calculation with this code it will give me a tree that looks like this:
So anyway, as you matematicians have figured out byt now, the expression should give 14 and not 8 as the tree suggests. I have noticed the that the problem arises when there are minus-signs in front of expressions since affect the whole right term i this problem whilst they should only affect the middle-term.
Ive been thinking like crazy for weeks and thought about solutions for this and looked at other codes and so on. Please dont toss a bunch of links on me if they are not really really simple and good since ive been browsing alot myself on tree traversals and other relevant topics.
What could i do at this stage? As I said, my program can tell if its right or wrong. So now I only need to parse a correct expression. Should I write another class for the parsing of the correct expression? Is it easier? Anyway I dont see how that code would look different than this.
Yes I would parse the equation, it just looks like you miss a key part of the order of operations/parsing. You need to include an additional check for double negatives.
The key factor here is that: In a situation with two identical operators then the left most operation is always carried out first.
First lets narrow down the issue.
This 1-5*(-2)+3 is equal to 1--10+3.
Now for our purposes lets assign a positive to the first operator because it helps illustrate a point:
1--10+3 is the same as +1--10+3
Now if we where to run +1--10+3 through a correct parser we would know that this -- is equal to + but only when used in the following situation:
+X--Y = X+Y
So now our parser has turned the original expression of 1--10+3 into 1+10+3 and we know that is equal to 14.
So all up: Yes you need a parser, but pay special attention to how +X--Y and X+Y work.
Also take a look at this answer: https://stackoverflow.com/a/26227947/1270000

I am running JAVA. When I try to create this method i get errors. The IDE told me to use an array I did and it still didnt work

I created the method below but it has red lines under it in netBeans. the IDE told me to use an array and that still didnt work so i went back to this.
private double getPaymentAmount(double loanValue, double paymentAmount, double numOfPayments, double periodInterestRate){
paymentAmount = loanValue [periodInterestRate(1+periodInterestRate)^numOfPayments]/[(1+periodInterestRate)^numOfPayments-1];
return paymentAmount;
You're confusing Java syntax with mathematical notation. While you might try to multiply variables as someVar(someVar2+someVar3) that's actually a method call. Additionally, square brackets have special meaning, and ^ is XOR and not power (use Math.pow instead).
loanValue *
(periodInterestRate * Math.pow(1+periodInterestRate, numOfPayments)) /
(Math.pow(1+periodInterestRate, numOfPayments)-1);
The code above has been revised to be syntactically valid. I've also taken the liberty of splitting it over multiple lines to make it more readable. However, because your original code was extremely unclear, it is possible that the mathematical meaning of my expression is different from your intention. I'm assuming that you intended to write the following:
Also, you declare paymentAmount as a parameter, although it is not a parameter, but rather a return value.
private double getPaymentAmount(double loanValue, double numOfPayments, double periodInterestRate) {
double paymentAmount = loanValue *
(periodInterestRate * Math.pow(1+periodInterestRate, numOfPayments)) /
(Math.pow(1+periodInterestRate, numOfPayments)-1);
return paymentAmount;
}
What is this syntax with loanValue [calculation1]/[calculation2]?:
paymentAmount = loanValue[periodInterestRate(1+periodInterestRate)^numOfPayments]/[(1+periodInterestRate)^numOfPayments-1];
This does not look like correct use of [] and if loanValue is a function maybe it should be more like:
paymentAmount = loanValue(periodInterestRate((1+periodInterestRate)^numOfPayments)/((1+periodInterestRate)^numOfPayments-1));
Or if loanValue is an array then maybe:
paymentAmount = loanValue[periodInterestRate(1+periodInterestRate)^numOfPayments]/((1+periodInterestRate)^numOfPayments-1);
But it is hard to believe that
periodInterestRate(1+periodInterestRate)
would match an array index or even a hash key.
Then maybe loanValue is just a number, as some others have suggested.
Please clarify: What is the type of loanValue?
Thanks
Square brackets don't mean the same thing as they do in math.Nethier does the caret. Caret is XOR. I think this is what you want:
loanValue * (Math.pow(periodInterestRate(1+periodInterestRate), numOfPayments)) / (Math.pow(1+periodInterestRate, numOfPayments-1))

Convert a string into mathematical equation?

I'm a beginner. I want to convert a string into a mathematical equation in order to be the input of my graphic calculator
for example:
cos(x+1)+ ln(x)
so we will convert it to
double x = -10;
for (int i=0; i<100; i++) {
double y=Math.cos(x+1)+Math.log(x)
x=x+0.5
}
so I want to know a method of converting y
Thank You
There is no "out-of-the-box" solution in java for this.
However:
Obligatory answer: google -> "convert string to mathematical expression java" first few answers are pretty good (like: What's a good library for parsing mathematical expressions in java? )
Obligatory answer 2: There are quite a few libraries on the net for converting strings into math expressions, naming them would be off-topic according to the rules, so I suggest "Obligatory answer" first few hits.
Also most likely you are better off by choosing a Format you will receive, and write your own parser for that format.
You need to write a parser first, building a tree of your input expression. You can then use that to generate your code.
But, "I'm a beginner" doesn't go well with writing parsers :)
You need to have a small formal grammar describing the syntax of your expression, then you need to convert your input string expression to an AST representation.
http://en.wikipedia.org/wiki/Abstract_syntax_tree
Finally you need to have a procedure to evaluate the AST for certain values of the parameters.
This is not a simple thing to do in pure Java. There are a lot of other similar questions with good answers here. Most of the solutions have to do with evaluating the expression in an interpreter or parsing the expression (there are some libraries available for this), or even shelling out. I don't know what is available in Android specifically to do this but there are tons of good answers for this in SO. Here is a good one to start with: Evaluating a math expression given in string form
I did that exact thing using NCalc. I passed in the user's string expression, replaced the variables with the values I am evaluating at, then using the Evaluate method and parsing to a double.
private double Function(double t, double y)
{
NCalc.Expression expression = new NCalc.Expression(this.Expression);
expression.Parameters["t"] = t;
expression.Parameters["y"] = y;
double value;
double.TryParse(expression.Evaluate().ToString(), out value);
return value;
}
For example, given the inputs t = .5 and y = 1 and the expression "4*y + Tan(2*t)", we would evaluate the string "4*1 + Tan(2*.5)" using NCalc.
It is not perfect, NCalc throws an exception if it cannot parse the user's string or it the datatypes of functions are different. I am working on polishing it.
I also asked the same question here.

Java typecasting for retrieving integer part of a double as double

I sometimes tend to use (double)(long)(a*b/c) to store the integer part of the result as double. This works well for negative numbers too.
Is there any better way to achieve the same thing as I believe typecasting is a costly operation.
Please note I'm looking for Integer part of the number and not the rounded value.
For eg :
MyObj.setDouble((double)(long)(522.99))
MyObj.getDouble() returns 522.0 and not 523.0
Thanks.
Try Math.rint(double) or Math.round(double). Regardless of performance differences it's at least more clear and concise.
[Edit]
In response to your clarified question - "how do I get the integer part of a double without casting" (despite your title asking about rounding), try this:
public static double integerPart(double d) {
return (d <= 0) ? Math.ceil(d) : Math.floor(d);
}
integerPart(522.99); // => 522d
integerPart(-3.19); // => -3d
Of course, this form is likely no faster than casting since it's using a comparison and a method call.
Performance is not an issue here. But code (double)(long)(a*b/c) is ugly. You actually do not need casting at all if you assign the result to `double variable:
double d = a*b/c; exactly the same as double d = (double)(long)a*b/c;
You actually never need to perform casting when moving from lower to upper types. It is correct for primitives (e.g. int -> double) and for classes (e.g. ArrayList -> List).
What about Math.floor(double) I cant see the difference between integer part and rouding it down.

Categories

Resources