For this code:
public class Solution{
public static void main(String[] args){
short x = 10;
x = x * 5;
System.out.print(x);
}
}
This will give compile error - “Lossy conversion from int to short”
Why? Short has a maximum value of 32,767, 10 * 5 = 50, so why am I getting this error?
When you do calculations with short, byte or char Java automatically converts them to int and return int result so you should has to use casting. x = (short) (x*5)
I'm getting exponential value in the result of expression where I'm adding double with long.
package com.testing;
import java.util.Date;
public class TypeCasting {
public static void main(String[] args) {
long varA = 100000;
long varB = 3000000;
double logVarA = Math.log10(varA); // 5.0
double logVarB = Math.log10(varB); // 6.477121254719663
long timeStampInSec = new Date().getTime() / 1000;
System.out.println(timeStampInSec); // 1552543503
double totalValue = logVarA + logVarB + timeStampInSec;
System.out.println(totalValue); // 1.5525435144771214E9
double finalScoreDampingFactor = 1000;
double finalScore = totalValue / finalScoreDampingFactor;
System.out.println(finalScore); // 1552543.5144771214
}
}
In totalValue variable why I'm getting 1.5525435144771214E9 value and when I'm deviding it with 1000, getting 1552543.5144771214.
Can any body please explain ?
A number has the same value, regardless of how it's represented. What you see printed as a String is just a representation of the number.
The JVM has decided, for whichever reason, that the number should be printed in exponential form. If you want to force it to print it differently, you can use printf.
double totalValue = logVarA + logVarB + timeStampInSec;
System.out.printf("%f%n", totalValue); // 1552547672.477121
The notation EX means "times 10 to the power of X".
So the original number was 1552543514.4771214.
1.5525435144771214E9
is 1552543514.... divided by 1000 is 1552543....
Is it possible that you misinterpreted the 1.5525435144771214E9 ?
I have a formula to evaluate
((x+y-1)*(x+y-2))/2 + x
and get the string representation of it.
So in Java 1.7 I write
public static void main(String[] args)
{
int x = 99999;
int y = 99999;
int answer = ((x+y-1)*(x+y-2))/2 + x;
String s = Integer.toString(answer);
System.out.println(s);
}
and in Python 2.7
def answer(x, y):
z = ((x+y-1)*(x+y-2))/2 + x
return str(z);
print(answer(99999,99999))
Java gave me the out put of 672047173 while Python gave me 19999400005 and seems the value from Python is correct. What is the reason behind this difference.
19999400005 is a too large value for int variables, so the Java calculations would overflow.
Use long variables instead:
public static void main(String[] args)
{
long x = 99999;
long y = 99999;
long answer = ((x+y-1)*(x+y-2))/2 + x;
String s = Long.toString(answer);
System.out.println(s);
}
Output is:
19999400005
Also note that you can print answer directly and don't have to convert it to String explicitly:
System.out.println(answer);
Because integer range in java is minimum -2,147,483,648 and a maximum value of 2,147,483,647.
int answer = ((x+y-1)*(x+y-2))/2 + x;
In this line you are assigning higher range value to integer. It causes integer overflow on the arithmetic operation. So that is why you are getting incorrect value to get correct value you have to use Long data type.
public static void main(String[] args)
{
int x = 99999;
int y = 99999;
long answer = (((x+y-1)*1l)*((x+y-2)*1l))/2 + x;
String s = Long.toString(answer);
System.out.println(s);
}
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");
}
Say I have the following three constants:
final static int MY_INT1 = 25;
final static int MY_INT2 = -10;
final static double MY_DOUBLE1 = 15.5;
I want to take the three of them and use Math.max() to find the max of the three but if I pass in more then two values then it gives me an error. For instance:
// this gives me an error
double maxOfNums = Math.max(MY_INT1, MY_INT2, MY_DOUBLE2);
Please let me know what I'm doing wrong.
Math.max only takes two arguments. If you want the maximum of three, use Math.max(MY_INT1, Math.max(MY_INT2, MY_DOUBLE2)).
you can use this:
Collections.max(Arrays.asList(1,2,3,4));
or create a function
public static int max(Integer... vals) {
return Collections.max(Arrays.asList(vals));
}
If possible, use NumberUtils in Apache Commons Lang - plenty of great utilities there.
https://commons.apache.org/proper/commons-lang/javadocs/api-3.1/org/apache/commons/lang3/math/NumberUtils.html#max(int[])
NumberUtils.max(int[])
Math.max only takes two arguments, no more and no less.
Another different solution to the already posted answers would be using DoubleStream.of:
double max = DoubleStream.of(firstValue, secondValue, thirdValue)
.max()
.getAsDouble();
Without using third party libraries, calling the same method more than once or creating an array, you can find the maximum of an arbitrary number of doubles like so
public static double max(double... n) {
int i = 0;
double max = n[i];
while (++i < n.length)
if (n[i] > max)
max = n[i];
return max;
}
In your example, max could be used like this
final static int MY_INT1 = 25;
final static int MY_INT2 = -10;
final static double MY_DOUBLE1 = 15.5;
public static void main(String[] args) {
double maxOfNums = max(MY_INT1, MY_INT2, MY_DOUBLE1);
}
Java 8 way. Works for multiple parameters:
Stream.of(first, second, third).max(Integer::compareTo).get()
I have a very simple idea:
int smallest = Math.min(a, Math.min(b, Math.min(c, d)));
Of course, if you have 1000 numbers, it's unusable, but if you have 3 or 4 numbers, its easy and fast.
Regards,
Norbert
Like mentioned before, Math.max() only takes two arguments. It's not exactly compatible with your current syntax but you could try Collections.max().
If you don't like that you can always create your own method for it...
public class test {
final static int MY_INT1 = 25;
final static int MY_INT2 = -10;
final static double MY_DOUBLE1 = 15.5;
public static void main(String args[]) {
double maxOfNums = multiMax(MY_INT1, MY_INT2, MY_DOUBLE1);
}
public static Object multiMax(Object... values) {
Object returnValue = null;
for (Object value : values)
returnValue = (returnValue != null) ? ((((value instanceof Integer) ? (Integer) value
: (value instanceof Double) ? (Double) value
: (Float) value) > ((returnValue instanceof Integer) ? (Integer) returnValue
: (returnValue instanceof Double) ? (Double) returnValue
: (Float) returnValue)) ? value : returnValue)
: value;
return returnValue;
}
}
This will take any number of mixed numeric arguments (Integer, Double and Float) but the return value is an Object so you would have to cast it to Integer, Double or Float.
It might also be throwing an error since there is no such thing as "MY_DOUBLE2".
int first = 3;
int mid = 4;
int last = 6;
//checks for the largest number using the Math.max(a,b) method
//for the second argument (b) you just use the same method to check which //value is greater between the second and the third
int largest = Math.max(first, Math.max(last, mid));
You can do like this:
public static void main(String[] args) {
int x=2 , y=7, z=14;
int max1= Math.max(x,y);
System.out.println("Max value is: "+ Math.max(max1, z));
}
if you want to do a simple, it will be like this
// Fig. 6.3: MaximumFinder.java
// Programmer-declared method maximum with three double parameters.
import java.util.Scanner;
public class MaximumFinder
{
// obtain three floating-point values and locate the maximum value
public static void main(String[] args)
{
// create Scanner for input from command window
Scanner input = new Scanner(System.in);
// prompt for and input three floating-point values
System.out.print(
"Enter three floating-point values separated by spaces: ");
double number1 = input.nextDouble(); // read first double
double number2 = input.nextDouble(); // read second double
double number3 = input.nextDouble(); // read third double
// determine the maximum value
double result = maximum(number1, number2, number3);
// display maximum value
System.out.println("Maximum is: " + result);
}
// returns the maximum of its three double parameters
public static double maximum(double x, double y, double z)
{
double maximumValue = x; // assume x is the largest to start
// determine whether y is greater than maximumValue
if (y > maximumValue)
maximumValue = y;
// determine whether z is greater than maximumValue
if (z > maximumValue)
maximumValue = z;
return maximumValue;
}
} // end class MaximumFinder
and the output will be something like this
Enter three floating-point values separated by spaces: 9.35 2.74 5.1
Maximum is: 9.35
References Java™ How To Program (Early Objects), Tenth Edition
Simple way without methods
int x = 1, y = 2, z = 3;
int biggest = x;
if (y > biggest) {
biggest = y;
}
if (z > biggest) {
biggest = z;
}
System.out.println(biggest);
// System.out.println(Math.max(Math.max(x,y),z));