Difference between operator += and =+ - java

Can you clearly explain the difference between the operator += and the operator =+ ?
Obviously, both are shortcuts for a sum, but I don't get the meaning of "=+"
a += b is equivalent to a = a + b. But what is the equivalence of a =+ b ???
Here is the practical example:
public class SumOfSquares {
private int[] inputArray;
private Integer result;
public SumOfSquares(int[] inputArray) {
this.inputArray=inputArray;
result = new Integer(0);
}
public Integer getResult () {
for (int counter=0; counter<inputArray.length; counter++) {
int currentNumber = inputArray[counter];
result += currentNumber*currentNumber;
}
return result;
}
}
inputArray={1,2,3,4,5}. Expected result=55 (1^2+2^2+3^2+4^2+5^2 = 1+4+9+16+25 = 55)
If I replace result += currentNumber*currentNumber; by result =+ currentNumber*currentNumber;, I get a result of 25 instead of 55. I would like to understand why.

=+ is not an operator. You might be confusing it with the combination of the assignment = and the unary + operator, which will take the value as positive (doesn't change its sign, + (-3) is still -3) and can be perfectly ommitted for integer values.
int a = 5;
int b = 3;
a = (+b); // a = 3
a = (-b); // a = -3
&plus; Unary plus operator; indicates positive value (numbers are positive without this, however)

a=+b is the same as a=0+b, in other words, a=b
=+ is not an operator. it is the assignment operator =, followed by a positive sign +. The + is applied to the variable to the right, so you can read it as a= (+b).

a -= b is equivalent to a = a - b, and
a =- b is equivalent to a = - b

No, both are not shortcuts for a sum. Have you tried =+ to see what it does?
Hint, try with =- to see what that does.

Related

Attempting to return a fraction (as a float) in Java

In this function:
public float cgRatio(String dna) {
//initialize count to be 0
int count = 0;
//for each character in the string
//if character == 'C' or 'G' increment count
for (int i = 0; i < dna.length(); i++) {
char c = dna.charAt(i);
if (c == 'C' || c == 'G') {
count++;
}
}
//return the ratio of C & G in DNA strand
return count/dna.length();
}
with my test function:
public void testFindGene() {
String[] dnaStrands = new String[6];
dnaStrands[0] = "AGCATGGTAACCAATAAGCGTTAAGCCAT";
dnaStrands[1] = "AATAATGGCATGGCCAATGAATGCGTAACCGATTAA";
dnaStrands[2] = "ATAATGCGGAATTGACATGGTA";
dnaStrands[3] = "AGCATGGTAACCAATTAGCGTTAAGCCAT";
dnaStrands[4] = "AATAATGGCATGGCCAATGAATTGACGTAACCGATTAA";
dnaStrands[5] = "ATAATGCGGAATCTAGACATGGTA";
for (int i = 0; i < dnaStrands.length - 1; i++) {
String gene = findGene(dnaStrands[i], 0);
System.out.println("The DNA strand is: \"" + dnaStrands[i] + "\"");
System.out.println("Gene: " + gene);
System.out.println("CG ratio of gene sequence is: " + String.format("%.02f", cgRatio(gene)));
}
}
My cgRatio return value is always 0.00. If I return just the count, I get accurate results in the form of a float. So that means my cgRatio function fails on this line:
//return the ratio of C & G in DNA strand
return count/dna.length();
Can you not return a fraction in Java? If you can, how can I fix this? If you cannot, why and what is an alternative solution?
try doing as ,
return (float)count/dna.length();
count and length both are int that is why you are getting like that.
Declaring count as a float would also solve the issue. Integer division yield an integer and omits fractions.
float count = 0;
For more clarification as to what is actually happening, the code
return count/dna.length();
is doing integer math then casting the result as a float.
For example if count is 5 and dna.length() returns 7,
5 / 7 = 0.714 which equals 0 when doing integer math (it rounds down to the nearest integer value).
So your code is essentially doing float(0) which gets your result of 0.00.
Cast your variables before dividing return (double)count/(double)dna.length(); Java is making it integer division because both are ints.

Converting String binary to integer

How can I do this without using multiplication, division or mod?
I come with the solution but it needs multiplication.
public StringBToInt(String b) {
int value = 0;
for(int z = 0; z < b.length(); z++) {
value = value * 2 + (int)b.charAt(i) - 48;
}
}
EDIT: SORRY! Only 3 java API are allowed. length(), charAt(), and equals()
Without multiplication, use bitwise shift operator:
public StringBToInt(String b) {
int value = 0;
for(int z = 0; z < b.length(); z++) {
if(b.charAt(z) == '1'){
shift = b.length()-z-1;
value += (1 << shift);
}
}
}
Use the Integer.valueOf(String, int) method:
Integer.valueOf('10101',2)
Try to use Integer.parseInt(..) like this:
int value = Integer.parseInt(b, 2);
Ofcourse b is a binary String.
You can use the method Integer.parseInt to do this.
String binary = "101010"
int value = Integer.parseInt(binary, 2);
The '2' in Integer.parseInt means to parse the String in base 2.

Ternary Operator in Java

I'm trying to learn Java using my knowledge I have gained from programming in C. In C, I loved the ternary operation. I'm trying to apply this in Java but I'm not sure if I'm doing it correctly. For the following recursive method that sums the from 1 to n, I have the following:
public static void main(String[] args){
int n = 6;
System.out.printf("sum of %d is %d ", n, new learn().sum(n));
}
public int sum(int num){
int result;
result = (num == 1) ? result = 1 : result = num + sum(num - 1);
}
which is giving me an error by stating that + is undefined. If someone could point out where my mistake is at, that would be much appreciated!
Your sum method currently has a return type of void. It therefore cannot return anything. In that case, you cannot be using the method invocation expression as a value, as you do in
num + sum(..)
// or in
System.out.printf("sum of %d is %d ", n, new learn().sum(n));
Change it to
public int sum(int num) {
return (num == 1) ? 1 : num + sum(num - 1);
}
to get the behavior you want.
Assigning result within the ternary expression when you are assigning to it outside of the ternary expression is completely pointless since you can't use the intermediary assignment.
That wouldn't be correct in C, either. The ternary operator evaluates to the selected expression, so don't assign inside it (just assign the result), and you clearly intend your method to return an int. Change the return type and return result (or eliminate the variable entirely and just return the value of the ternary expression).
Change:
result = (num == 1) ? result = 1 : result = num + sum(num - 1);
To:
result = (num == 1) ? 1 : num + sum(num - 1);
What is inside the operators ?: are the possible values of "result".

How can I tell that an integer is only 2 digits long?

I need to write a Java program that prompts the user to enter an integer consisting of exactly 2 digits; then displays on the screen the sum of its individual digits.
I am stuck here. What am I doing wrong?
import java.util.Scanner ;
public class ss {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int x;
System.out.println("Please Enter a number consists of 2 digits only : ");
x = input.nextInt();
x.length() == 2;
}
}
and the last line contains an error!
Assuming that x is positive, a simple way to check if it has exactly two digits would be:
if (x >= 10 && x <= 99) {
// x contains exactly two digits
}
The variable x is of type int, so you can't call a method on it. You need to either read the input as a String or convert the int to a String then call length(), or just test that the int is between 10 and 99, inclusive.
In a programming langauge, there are things called L-values and R-values. In an assignment operation, a L-value can accept a R-value as input. This comes from the typical layout which has L-values on the left of the assignment operator and R-values on the right side of the assignment operator.
x = 5;
x is the L-value and 5 is the R-value. It is possible to assign five to x.
However, a function returns a R-value. Therefore, it is possible to do this
x = a.length();
but is is not possible to do
a.length() = x;
because you can not assign a value to the return of a function.
Fundamentally, L-values are names which represent a value, but R-values are values or items which when analyzed result in the return of values.
Now, if you used the equals comparison operator, both values must be R-values, because no assignment is being performed
a.length == x
is just fine, because it is not the assignment operator = but rather one of the comparison operators ==.
Your error comes because x is a primitive, not an object. Only objects have methods like length(). A quick an easy way to determine the length of an integer is by using Math.log().
public int length(int n){
if (n == 0) return 1; // because Math.log(0) is undefined
if (n < 0) n = -n; // because Math.log() doesn't work for negative numbers
return (int)(Math.log10(n)) + 1; //+1 because Math.log10 returns one less
//than wanted. Math.log10(10) == 1.
}
This method uses the fact that the base b logarithm of an integer a is related to the length of the integer a.
Or, if you don't know how to use methods, you could do this (assuming n is the integer to check):
int length = (n == 0)? 1: ((n > 0)? (int) (Math.log(n)) + 1: (int) (Math.log(-n)) + 1);
Or, if you don't use the ternary operator, you could expand it:
int length = -1; //placeholder; might not need it.
if (n == 0) length = 1;
else if (n > 0) length = (int) (Math.log(n)) + 1;
else length = (int) (Math.log(-n)) + 1;
You can't find the length of an int by calling a method on it, but you can find the length of a String.
Try converting the int to a String and finding the length of that:
boolean isTwoDigits = x.toString().length() == 2;
You cannot call length on integer just write
if(x>=10 && x<=99)
{
//write your code here
}

Will a double equal to an integer always cast to that integer?

Will a double equal to an integer always cast to that integer (assuming the double is not one that causes an overflow). Example: Math.ceil() will return a double that is equal to an integer. Assuming no overflow, will it always cast to the same integer that it is supposedly equal to?
If not, how can I round up a double to an int or long?
Since Java types are fixed and Java doubles have a 52 bit mantissa, they can (with ease) represent a 32-bit Java int without rounding.
Yes, it will convert exactly. This is described in Section 5.1.3 of the JLS, which mentions
Otherwise, if the floating-point number is not an infinity, the
floating-point value is rounded to an integer value V, rounding toward
zero using IEEE 754 round-toward-zero mode...
Since your double exactly equals the int, the "rounded" value is just the exact same value, but you can read the spec for details.
All possible int values can be represented by a double without error. The simplest way to round up is to use Math.ceil() e.g.
double d =
long l = (long) Math.ceil(d); // note: could overflow.
Empirically, the answer seems to be yes - note that it also works with i2 = (int) d;.
public static void main(String[] args) {
for (int i = Integer.MIN_VALUE + 1; i < Integer.MAX_VALUE; i++) {
double d = i;
int i2 = (int) Math.ceil(d);
if (i != i2) {
System.out.println("i=" + i + " and i2=" + i2); //Never executed
}
}
}
I believe so, but you might test it yourself:
public static void main(String... args) throws Exception {
int interactions = Integer.MAX_VALUE;
int i = Integer.MIN_VALUE;
double d = Integer.MIN_VALUE;
long init = System.currentTimeMillis();
for (; i < interactions; i++, d++)
if (!(i == (int) Math.ceil(d)))
throw new Exception("something went wrong with i=" + i + " and d=" + d + ", Math.ceil(d)="+Math.ceil(d));
System.out.println("Finished in: "+(System.currentTimeMillis() - init)+"ms");
}

Categories

Resources