Can I declare and define variables with generated names and values? [duplicate] - java

This question already has answers here:
Assigning variables with dynamic names in Java
(7 answers)
Closed 8 years ago.
An example:
int x1 = 1;
int x2 = 2;
int x3 = 3;
...
int xn = n;
As you can see the name and value of the variables are generated - in this case by a counter. Is this possible?How?

I do not know how, but this is probably possible with some crazy Reflection hacking - do not try to do it, as it will produce code that is hard to maintain, hard to understand and vulnerable to hard-to-trace bugs.
Instead use Collections (do not use arrays if not absolutely needed), for example ArrayList.

Yes, it is valid Java code, but in this particular case you would just use the numbers :D

Related

Alternative for deprecated new Double(double) [duplicate]

This question already has answers here:
The constructors Integer(int), Double(double), Long(long) and so on are deprecated
(1 answer)
create a new Integer object that holds the value 1?
(2 answers)
Closed 3 years ago.
I'm following a book by Walter Savitch called Absolute Java. A sample program in it contains the following lines:
Double[] d = new Double[10];
for (int i = 0; i < d.length; i++)
d[i] = new Double(d.length - i);
And I got the following warning message:
warning: [deprecation] Double(double) in Double has been deprecated
I believe that the warning message is telling me to replace the use of constructors since it is already deprecated, so what should I replace it with?
Explanation
You should replace it with:
d[i] = Double.valueOf(d.length - i);
From its Javadoc:
Deprecated.
It is rarely appropriate to use this constructor. The static factory valueOf(double) is generally a better choice, as it is likely to yield significantly better space and time performance.
In general, valueOf is not forced to always return a new instance. It can utilize an internal cache and re-use values created before already, which makes it faster. For example if you create hundreds of 1.0.
Note
Is there a specific reason you are using a Double[] in the first place? If not, go for double[] instead. The primitives are much faster and have less memory overhead, compared to their object wrapper.
Then your code is just:
double[] d = new double[10];
for (int i = 0; i < d.length; i++)
d[i] = d.length - i;
By the way, you should prefer to never omitt the curly braces. Even if your loop is just one line. This is a very common source for bugs that are hard to find.
Also, your variable naming is not very good. What is d? Try to give it a name that reflects what it actually means. Like ages if it stores person ages, for example. If you do not have something specific, maybe use values. That is already better than just d. Especially since it is plural, so it is clear that it is an array of multiple values.
double[] values = new double[10];
for (int i = 0; i < values.length; i++) {
values[i] = values.length - i;
}
From Java 9 constructor(s) method(s) was Deprecated
Deprecated. It is rarely appropriate to use this constructor. The static factory valueOf(double) is generally a better choice, as it is likely to yield significantly better space and time performance.
Constructs a newly allocated Double object that represents the primitive double argument.
So replace with:
Double.valueOf(d.length - i)

How to find sum with forEach and lambda expression in Java? [duplicate]

This question already has answers here:
Variable used in lambda expression should be final or effectively final
(9 answers)
How to sum a list of integers with java streams?
(12 answers)
Closed 4 years ago.
The following snippet does not compile. How to find the sum using forEach as shown below?
private int Sum(ArrayList<Integer> inputs) {
int sum = 0;
inputs.stream().forEach(x -> sum += x);
return sum;
}
This should do the trick:
private int Sum(ArrayList<Integer> inputs) {
return inputs.stream().mapToInt(Integer::intValue).sum();
}
EDIT :
The problem with using for-each is that it is a terminal operation, which means that it doesn't produce another intermediate stream for us to work on. The better approach would be to use mapToInt which produces an IntStream on which we can easily find the sum.
This answer is just to provide a bit more context as to why your code doesn't work and therefore allowing you to decipher the problem if it were to happen in the future.
It seems like you're a .NET user which makes it completely understandable for one to expect the code you've written to work. As in .NET the equivalent would be:
private int Sum(List<int> inputs) {
int sum = 0;
inputs.ForEach(x => sum += x);
return sum;
}
However, in java variables used in a lambda expression must be final or effectively final, for that reason the statement inputs.stream().forEach(x -> sum += x); will not compile.
Nevertheless, simply because one would expect the aforementioned code to work in C# doesn't necessarily mean it should work in Java as there are different rules.
There are solutions available to find the sum of a set of numbers using the forEach method but it's not the idiomatic approach and so should be avoided unless necessary.
The idiomatic approach is as #Nicholas K has shown.
On another note:
even in .NET the idiomatic approach would be return inputs.Sum();
as opposed to using the ForEach extension method to sum the elements of a given list.
whenever you seem to see yourself use inputs.stream().forEach(...); in java you should instead do inputs.forEach(...) as all lists have a forEach method.
method names in Java should be camelCase as opposed to PascalCasing as in C#.

why float and double showing different behaviour in java? [duplicate]

This question already has answers here:
What is float in Java?
(4 answers)
Closed 7 years ago.
case 1
float a=033.0 //shows compilation problem
case 2
double a=033.0 //works fine
Why case 1 is showing error but not case 2 or vice-versa?
By default java uses double type to store floating values. since you are storing double in float (down casting) java will throw an error. it can be resolved by two ways
float a=033.0f
float a= (float)033.0
case 1----float a=033.0 //shows compilation problem
case 2----double a=033.0 //works fine
In Java, decimal number is interpreted as a double ,so converting from double to float cannot be performed automatically ,so you need to give like this :
float a= 033.0f;
Its simply the understanding of Java Syntax.
You can read the Primitive data types of java.
You'll get it anywhere...
Link : https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
Direct to this link, do ctrl+F, & paste this "Floating-Point Literals".
You wont't waste time wandering...
For your own convenience now, you can prefer this.
float fractionNumber = 25.24F;
fractionNumber = 25.24f;
double biggerFractionNum = 56.65555D;
biggerFractionNum = 56.65555;
but generally its like this all over... later you'll get used to it.
float foo = 34.4F;
double doo = 34.4;
IMPLEMENT it right away ! ...experience it, understand it...& you'll never forget it. :)

What is "int..." in Java method's parameter? [duplicate]

This question already has answers here:
What is the ellipsis (...) for in this method signature?
(5 answers)
What do 3 dots next to a parameter type mean in Java?
(9 answers)
Closed 7 years ago.
I came across a method definition:
void doType(int... keyCodes) {
doType(keyCodes, 0, keyCodes.length);
}
void doType(int[] keyCodes, int offset, int length) {
if (length == 0) {
return;
}
robot.keyPress(keyCodes[offset]);
doType(keyCodes, offset + 1, length - 1);
robot.keyRelease(keyCodes[offset]);
}
The "int..." seems to indicate an indeterminate number of integer parameters but the variable is used as an array inside the function. Can someone please explain?
As you already stated correctly this java notation is to make the method accept a variable amount of (in this case) int parameter.
To handle this variable amount of variables you can access it like an array.
This functionality is introduced in java 5.
See also here:
https://docs.oracle.com/javase/1.5.0/docs/guide/language/varargs.html
You are right in deducing that the ellipses indicate that this method is variadic.
When you have a variable number of potential arguments, you need some way to iterate over them - otherwise they aren't very useful in practice. Java and C# happen to have the array indexing syntax. C and C++ happen to have the va_start, va_arg and va_end macros. Different languages may have something else.
The reason why Java has the array syntax specifically is probably because it happens to match the way they are actually implemented: as a simple array parameter replaced at compile time.

variable/parameterized width for printf/format in Java (using * or something else?) [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Java printf using variable field size?
I haven't worked with Java in a while so I was looking for a way to
specify variable width in format/printf when formatting/printing output. My example shows the use with an integer, but of course I'd like this to work for other types too.
E.g., something along the lines of
int val = 8;
int wid = 5;
System.out.printf("%"*d\n", wid, val);
I could use this work-around, which is ugly:
System.out.printf("%"+wid+"d\n", val);
Was the * variable field width specifier removed from Java? This old'ish
page, section 1.3.1,
shows the use (like it would be used in C), but I can't get it to
work, resulting in:
java.util.UnknownFormatConversionException: Conversion = '*'
nor have I been able to find more recent references that this
does work.
Is there an easier way to do this other than my work-around above?
I did look around before posting and came across this about 2-year old SO question Java printf using variable field size? but is that the final word on this?
The general syntax of a format specifier is
%[parameter][flags][width][.precision][length]type
Instead of printf, you can also use
String.format("%"+wid+"d",val);
And yes, these are the only ways in case you are using a Java Formatter.

Categories