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)
The code below that I have written in Java returns the reverse of a number. My question is what is the name for the math process whereby the formula for obtaining the value for my variable reverseNumber is
a =0; (a*10) + b = a;
I remember seeing this in one of my calc or statistic classes before, I just do not remember what it is called. Thanks.
public static int reverse(int number) {
int reverseNumber = 0;
while(number !=0){
lastDigit = number % 10;
number /= 10;
reverseNumber = (reverseNumber * 10) + lastDigit;
}
return reverseNumber;
}
If you are looking for a function to reverse an integer, there is no direct function but you can achieve it using a combination of functions shown below:
public class Main {
public static void main(String[] args) {
int x = 135246;
int y = Integer.parseInt(new StringBuilder(String.valueOf(x)).reverse().toString());
System.out.println("Reverse of " + x + " = " + y);
}
}
Output:
Reverse of 135246 = 642531
Check Integer and StringBuilder classes to learn more about these functions.
This question already has answers here:
Float and double datatype in Java
(9 answers)
Closed 6 years ago.
Can someone show me an example of example how I could use Double in the following code?
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
int myFirstNumber = (5+10) + (6*8);//Declaring an integer myFirstNumber
int mySecondNumber = 10;
int myThirdNumber = 3;
int myTotal = myFirstNumber + mySecondNumber + myThirdNumber;
System.out.println(myFirstNumber);//prints variable myFirstNumber
System.out.println("myFirstNumber ");//
System.out.println(myTotal);
}
}
Use either float or double (or their boxed counterparts, Float and Double) when you need to deal with non-integer values. The code you posted has no apparent need for that, so it's hard to answer your question. But one possibility would be if you wanted to compute, say, the average of the three numbers:
public class HelloWorld { public static void main(String[] args) {
System.out.println("Hello, World!");
int myFirstNumber = (5+10) + (6*8);//Declaring an integer myFirstNumber
int mySecondNumber = 10;
int myThirdNumber = 3;
int myTotal = myFirstNumber + mySecondNumber + myThirdNumber;
float average = myTotal / 3.0f;
System.out.println(myFirstNumber);//prints variable myFirstNumber
System.out.println("myFirstNumber ");//
System.out.println(myTotal);
System.out.println(average);
}
As to when to use float vs. double (the title of your question), use double when you can tolerate less rounding error than you get with float.
class LongDiv{
public static void main(String [] args){
final long x = 24*60*60*1000*1000;
final long y = 24*60*60*1000;
System.out.println(x/y);
}
}
although the expected answer is 1000, but the javac gives it as 5. Reason?
The long x you are creating isn't the value you expected. It is in the integer range. To create longs, use:
final long x = 24L*60L*60L*1000L*1000L;
final long y = 24L*60L*60L*1000L;
System.out.println(x/y);
The x you computed, in the integer range, was 500654080. This divided by the y ( = 86400000), results in 5.794607407407407.... Java truncates the decimal part which causes the 5.
By adding an L after the number literal, you tell the compiler to compile it as a long instead of an int. The value for x you expected is 86400000000. But is was compiled as an int.
We can reproduce the wrong value for x (500654080) by truncating it to an int:
// First correct
long x = 24L*60L*60L*1000L*1000L;
/* x = `86400000000`; */
// Now truncate
x &= 0xFFFFFFFFL; // again: don't forget the L suffix
/* x = `500654080` */
The expressions 24*60*60*1000*1000 is an int type not a long What you want is 24L*60*60*1000*1000 which is long
This is what you have.
final long x = (24*60*60*1000*1000) & 0xFFFFFFFF;
final long y = (24*60*60*1000) & 0xFFFFFFFF;
System.out.println(x/y);
what you want is
final long x = 24L*60*60*1000*1000;
final long y = 24L*60*60*1000;
System.out.println(x/y);
casting (forcing) to long works in case of literal values for the right operand; but the problem persists in case of assigning one long variable to another, as in the below given example:
package utils;
public class Utils {
public static void main(String ... clps){
Utils.longDivision();
Utils.doubleDivision();
}
private static void doubleDivision(){
double x=new Long("54321").doubleValue();
double y=new Long("12345").doubleValue();
double difference=x - y;
double percentage=(difference/x)*100.00;
System.out.println("\nDouble Division ==> X : "+x+" ; Y : "+y+" ; Difference : "+difference+" ; percentage : "+percentage+"\n");
}
private static void longDivision(){
long x=new Long("54321").longValue();
long y=new Long("12345").longValue();
long difference=x - y;
long percentage=(difference/x)*100L;
System.out.println("\nLong Division ==> X : "+x+" ; Y : "+y+" ; Difference : "+difference+" ; percentage : "+percentage+"\n");
}
}
The only way i could get proper answer is by converting the division of longs into division of doubles. It is very strange why division of longs behaves in such mysterious manner.
longDivision gives the answer as zero whereas the doubleDivision gives the correct answer.
I hope this helps others who encountered similar issues...
24*60*60*1000*1000 is too large to fit into an int and overflows.
Tricky one!
The issue is that 24, 60, and 1000 are Java literal ints. Before the values are assigned to x and y, they are truncated to fit in int values. Try
System.out.print(x + ", " + y);
to see exactly what I mean. The quick fix is to make your literals into long values like so:
public class LongDiv{
public static void main(String [] args){
final long x = 24l*60l*60l*1000l*1000l;
final long y = 24l*60l*60l*1000l;
System.out.println(x/y);
}
}
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));