Can I use a char to do calculation in Java - java

Is it possible for me to do something like the following below in order to save time from doing if else statement?
int x = 1;
int y = 2;
char z = '+';
System.out.println(x + z + y); //e.g. 1 + 2 i.e. 3
Please advise.

You can't. In your expression, the '+' char is converted to its int value. (The result of that expression would be 46: 1 + 43 + 2).
You'd have to use an if (or switch) statement:
int x = 1;
int y = 2;
char z = '+';
if (z == '+') System.out.println(x + y);
else if (z == '-') System.out.println(x - y);
// else if (z == '*') ... and so on
If you are only interested in the result, you can evaluate the String directly using Java's JavaScript ScriptEngine:
import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;
public class Eval {
public static void main(String[] args) throws Exception {
ScriptEngineManager s = new ScriptEngineManager();
ScriptEngine engine = s.getEngineByName("JavaScript");
int x = 1;
int y = 2;
char z = '+';
String exp = "" + x + z + y;
System.out.println(engine.eval(exp));
}
}
Output:
3.0
Note: there can be some issues with the use of ScriptEngine. So do not allow the user to enter the expression to be evaluated directly. Using with variables (x, y and z like you do) takes care of this problem, though.

No, that wouldn't work as expected. (it will compile and run, but since the unicode value of + is 0x2B, or 43, and a char is treated like a number in this case, your expression x + z + y evaluates to 1 + 43 + 2, so it prints 46) You can use if/else or switch statements to evaluate what operation to do, which would work for simple inputs, or you can look at a more general expression parsing library, e.g. exp4j or jexel.

That will compile but not run in the way you expect.
z will be converted to an int, which will be that character's value in the default charset (most likely ASCII).
As an example, on my computer that results in "46"

The output should be 1 + 2 + 43 = 46
For char, it will take the Ascii value of '+'

Related

Double variable with 16+ digits gives error: Integer Number too Large

The following code is designed to factorize a number typed into the variable x.
public class testMod{
public static void main(String[]args){
double x = 11868681080091051216000;
StringBuilder output = new StringBuilder("1 * ");
for(double y = 2; y <= x; y++){
while (x % y == 0) {
System.out.print("Calculating... \n");
String printNumber = y + " * ";
x = x / y;
output.append(printNumber);
System.out.print(output.substring(0, output.length() - 2) + "\n");
}
}
}
}
The problem is that the compiler treats 11868681080091051216000 as an int, regardless of the attempt to assign it to a double. As such, it's out of range.
To specify a double literal, you can simply append D to the end – but do note that you'll lose precision this way:
double x = 11868681080091051216000D;
System.out.println(x); // prints 186868108009105E22
If you need the full precision, you can use a BigInteger instead, but you'll still need to specify that number in expressions that Java can handle, such as a product of its factors.

What does the “+” operator do in Java?

Please someone explain the ("x = " + x) part of the code.
public class While-With-Nested-If {
public static void main(String [] args) {
int x = 1;
while(x < 100) {
System.out.println("x = " + x);
if(x % 2 == 0) {
x++;
} else {
x *= 2;
}
}
}
}
In this case the operator is used to concatenate a string with the string representation of x.
It depends on the operand type.
For String type operands it creates a new String instance (String objects are immutable) and assigns to it the concatenation of two operands.
For numeric types it works as addition operator.
In this case, it concatenates a String with the string representation of x. For example: x = 42;
The "+" operator acts as syntactic sugar for the concatenation operator in regards to String operations.
It is used to concatenate the two strings in your case.
When you write
String a = b + c + d;
then it gets converted into:
String a = new StringBuilder(b).append(c).append(d).toString();
You may refer Oracle docs for more details
In this code block while loop will iterate till x is less than 100 in order to print all the values of x during "while" loop executes the System.out.println("x = " + x); is used.
Here java will send each value of x to output console by appending it to the "x = " string(text) so on each iteration of while loop you will get output on console like
x = 1
x = 2
x = 3
and so on...
x = 99
The + operator concatenates if the operands' type is string, and it performs summing if the operands are ints, floats or doubles.
Here is the out put:
X = 1, X = 2, X = 3, X = 6, X = 7, X = 14, X = 15, X = 30, X = 31, X = 62, X = 63...

Java, how to pass by reference

Have a look at this code
Integer x = 5;
Integer y = 2;
Integer xy = x+y;
System.out.println("xy = " + xy); // outputs: 7
System.out.println("xy2 = " + xy2); // outputs: 7
x++;
System.out.println("xy = " + xy); // outputs: 7
System.out.println("xy2 = " + xy2); // outputs: 7
How can I get the code to output 8 without using a method that calculates it for you?
An Integer in Java is immutable. You can not change its value. In addition, it's a special autoboxing type to provide an Object wrapper for the int primitive.
In your code, for example, x++ does not modify the Integer object x is referencing. It un-autoboxes it to a primitive int, post-increments it, re-autoboxes it returning a new Integer object and assigns that Integer to x.
Edit to add for completeness: Autoboxing is one of those special things in Java that can cause confusion. There's even more going on behind the scenes when talking about memory / objects. The Integer type also implements the flyweight pattern when autoboxing. Values from -128 to 127 are cached. You should always use the .equals() method when comparing Integer objects.
Integer x = 5;
Integer y = 5;
if (x == y) // == compares the *reference (pointer) value* not the contained int value
{
System.out.println("They point to the same object");
}
x = 500;
y = 500;
if (x != y)
{
System.out.println("They don't point to the same object");
if (x.equals(y)) // Compares the contained int value
{
System.out.println("But they have the same value!");
}
}
See: Why aren't Integers cached in Java? for more info (and of course the JLS)
You need to update xy after modifying x. So:
x++;
xy = x + y;
xy2 = x + y;
In Java you'll need to update a variable yourself if you want the value to change. It's not like other languages where you express a relationship between two variables and this relationship is maintained whenever a variable changes.
The expression:
xy = x + y
doesn't mean that now xy is depends on the values of x and y (if they changed, xy is changed too). You can see it as follows: the value of the expression x + y is inserted into xy.
Therefore, you must increase the value of x (by x++), before your set the value of xy.
I'm new to java, and I'm not really sure of the context for this question, but if all you want to do is output 8, you can just make it xy++ instead of x++.
Integer x = 5;
Integer y = 2;
Integer xy = x+y;
int xy2 = x+y; // just testing to see if it makes a difference
System.out.println("xy = " + xy); // outputs: 7
System.out.println("xy2 = " + xy2); // outputs: 7
**xy++;**
System.out.println("xy = " + xy); // **outputs: 8**
System.out.println("xy2 = " + xy2); // outputs: 7

Reason for error: var might not have been initiazed

The user should enter the values to x and y, and if x is greater than 5 and and when y= 0 , then z should be equivalent to x+y. However, when I compile it gives me an error saying that z might not have been initialized.
import java.util.Scanner;
public class add {
public static void main(String[] args ){
Scanner input = new Scanner (System.in);
System.out.print("Enter a value for x");
int x = input.nextInt();
System.out.print("\nEnter a value for y ");
int y = input.nextInt();
int z;
if (x > 5){
if (y == 0)
z = x + y;
System.out.println("The answer is " + z);
}
else
System.out.println("The answer is only" + x);
}
}
There is an execution path where z doesn't get initialized, but you attempt to print it. If x is greater than 5, but y isn't 0, then z is not initialized, but you refer to z when printing it.
Use braces to create an inner block for your inner if statement, so z is only referenced if it's initialized:
if (x > 5){
if (y == 0) {
z = x + y;
System.out.println("The answer is " + z);
}
}
Also, proper indenting helps to identify visually what's part of a block and what's not.
Your 'if' statement is misleading:
if (y == 0)
z = x + y;
What if y != 0? In that case, z is not initialized.
The next line
System.out.println("The answer is " + z);
doesn't apply to the y==0 statement, as you don't have braces {}.
You probably meant to write something like:
if (x > 5) {
if (y == 0) {
z = x + y;
System.out.println("The answer is " + z);
}
}
Note the "{" after the if statement.
As you are not using braces for if condition, your z will not initialized.
To solve such kind problems always keep in mind that if you are calculating something with integer variable do initialize them with some value (here, 0 is the best).
Then you can access that variable anywhere in the code without any initialization error.
To rid of this problem, you have two ways
One way:
just simply initialize your z variable like:
int z=0;
Second way:
Try to put braces for if condition like:
if (y == 0){
z = x + y;
System.out.println("The answer is " + z);
}
You need to assure the compiler that z will get a value no matter what.
You may want to assign it a default value when declaring it.
Something along these lines:
int z = 0; // just an example
int z has no value, try the code at the bottom then give it a 0 or input.nextInt();
int z = 0;
or
int z = input.nextInt();

Increment X Mod N in One Line

I have several small programs that require infinitely looping over the integer set Z sub n. I often write the code in this manor:
int x = 0;
int n = 13; //or some other prime
while(1) {
//do stuff dependent on x
++x;
x %= n;
}
I write code mostly in C/C++ & Java so I was wondering:
Is there a way to increment x mod n in one line rather then two in either language?
Have you considered:
x = (x + 1 == n ? 0: x + 1);
The chances are the x + 1 will optimise to one instruction and at least you are guaranteed to never use division (which a bad optimiser might use when % is involved).
x = (x + 1) % n;
Not terribly surprising.
Another alternative is this
x = ++x % n; // Java
if (++x == n) x = 0;
Using x = (x + 1 == n ? 0 : x + 1); requires two additions: one for the comparison and another when the value of x is set to x + 1.

Categories