How to convert float to int in Java?

You can convert a float to an int in Java by using the round method Math.round(float):

The method rounds the float to the closest int value.

Other methods that you can use to convert a float to int are:

  • (int) Math.ceil(float) – returns the smallest int which is greater than or equal to the method parameter. As the Math.ceil() method returns the double value by default, it needs to be cast to an int
  • (int) Math.floor(float) – returns the largest int which is less than or equal to the method parameter. As the Math.floor() method returns the double value by default, it needs to be cast to an int
  • (int) float – casting a float to an int removes the decimal fraction of the float

Let me explain you these methods in this blog post.

Math.round(float)

The method to convert a float to an int which is the best in most of the cases is the Math.round(float) method. The method rounds the float to the closest integer value. You can find the description of the method in the table below.

Method header public static int round(float f)
Parameters float f – parameter to be rounded to the closest integer
Returns int – parameter of the method rounded to the closest int
Math.round(float) example

Let me show you an example how you can use the Math.round(float) method.

The output of the code is:

Let me demonstrate what kind of results the method Math.round(float) produces for different method parameters.

f Math.round(f)
-10.93f -11
-10.5f -10
-10.13f -10
10.13f 10
10.5f 11
10.93f 11
Float.NaN 0
<= Integer.MIN_VALUE Integer.MIN_VALUE
>= Integer.MAX_VALUE Integer.MAX_VALUE

 

(int) Math.ceil(float)

To convert a float to an int you can use as well the (int) Math.ceil(float) method. The method will return the smallest int which is greater than or equal to the float parameter. We need to cast the value returned by the method to an int as the method Math.ceil() returns a double value.

(int) Math.ceil(float) example

Let me show you the example, how we can use this method.

The output of the code is:

Below you find the results that the method will produce for different parameters.

f (int) Math.ceil(f)
-10.93f -10
-10.5f -10
-10.13f -10
10.13f 11
10.5f 11
10.93f 11
Float.NaN 0

Note: In the Java documentation you can find that by default the Math.ceil(double) method takes a double as a parameter. Designers of the Math class didn’t decide to create another method to handle float parameters. The reason for that is that all the float parameters will produce the correct results when passed to the Math.ceil(double) method.

 

(int) Math.floor(float)

Another technique you can use to convert a float to an int is to use (int) Math.floor(float). The method returns the largest int which is smaller than or equal to the method argument. Note that we need to use casting to an int as the method Math.floor() returns the double value.

(int) Math.floor(float) example
The output is:
To find out what is the result of the result of using the method for different parameters, check the table below.

f (int) Math.floor(f)
-10.93f -11
-10.5f -11
-10.13f -11
10.13f 10
10.5f 10
10.93f 10
Float.NaN 0

 

Cast float to int

Another method to convert a float to an int is to cast it. The method will just remove the decimal fraction of the float.

Cast float to int example

Let me show you the code example how you can cast a float to an int.

The output of executing the method is:

Below you can find a detailed results, what kind of results cast a float to an int gives.

f (int) f
-10.93f -10
-10.5f -10
-10.13f -10
10.13f 10
10.5f 10
10.93f 10
Float.NaN 0

 

Summary

As you can see there are many methods to convert a float to an int. There is no universal method which will be the best in all the cases. You need to decide what kind of conversion you want to have and pick the method which suits your needs the best.

Initialize String[] in Java

To initialize String[] you can do:
More details are given below.

Declaration vs Initialization

Let’s consider the array strings:
The above line of code is just a declaration of an array. There is no memory allocated for the elements of strings. If you would try to assign some value to the first element of the array, eg. by executing the code:
You would get an error like “Error:(6,9) java: variable strings might not have been initialized”.
We need to initialize it then. You can do that like this:
The new operator allocated memory for the array and now we can use without problems. You can combine declaration and initialization in one statement:
You can also declare, initialize and add elements to an array in one statement:
which is equivalent to

Java Sorting Map by key

To have a sorted map by key in Java you can use the TreeMap. It guarantees the natural order. You can use it like this:
For more details read the following paragraphs.

TreeMap with the natural order

This type of a Map stores the elements in the natural order. If you just want to sort a variable map, you can use the constructor of the TreeMap: new TreeMap(mapas in the following example:

The result of executing this code is:

 

Complex classes as a key

If the key of a map is a complex class, to sort a map using TreeMap you need to implement in the class the Comparable interface. Let’s assume that we have a class Person containing the firstName (String), lastName (String) and age (Integer). If you want objects of this class to be sorted by age, the class may look like this one:
To test if this works correctly, we may execute the code below

After executing the code, the result is:

As you can see, people were sorted correctly by age.

How to convert String to Character array in Java

October 16, 2017

Using ArrayUtils

If you are familiar with Apache Commons you can try this code:
The toCharArray() method will converts the String to char array. The ArrayUtils.toObject(String) method to converts the array of chars to the array of Character objects.

Own method

If for some reason you don’t want to use the Apache solution, you can write your own method.

How to get file extension in Java?

August 31, 2017

Simple Java parser

If you want to get a file extension from the file path you can try this code:
The fileName is a variable which contains the name of your file. lastIndexOf() will give you the index of the last dot in a file name. The if statement guarantees that you will get a substring from dot to the end of a string (which usually is the file extension). Although, this solution is not perfect. It will work only with simple Windows-like file names. When it comes to the Unix ones like archive.tar.gz, it won’t work.

Apache Commons IO

If you are familiar with Apache Commons, you can use its FilenemUtils class. This contains the proper method named getExtension() which deal with the problems listed in the previous solution. Here’s how to use that:
 

How to set proxy for JVM

August 28, 2017
Java applications connect to the Internet very often. If you want to use the proxy server to connect to the Internet, you need to set your JVM to use the proxy. To do this, you can set:
http.proxyHost and http.proxyPort. These are JVM flags. We will explain how to set them correctly.

JVM flags

You can set them when starting your JVM on the command line. In Windows, you can use a bat file. In Unix a shell script:
The situation is slightly different when you are using containers (such as WebLogic). Then you need to edit the startup scripts which your container provides.

nonProxyHost property

When you don’t want to use the proxy to resolve some local hosts you can use http.nonProxyHosts property. The usage:

org.apache.maven.plugin.PluginResolutionException: Plugin or one of its dependencies could not be resolved

August 23, 2017
If you are struggling with the error:
You should check the maven repository server is up firstly. It can be the root of the problem. Of course, sometimes the server is up, and you still get the error. That’s why there are more ways to deal with it in paragraphs below.

Set up the Proxy

This is the second step you should take to find the problem. You should be sure that maven settings.xml contains the proxy settings:

Check the Cache

If Maven still doesn’t work, you should check if it’s not the cache fault. Delete all files in your local repository in:
The path can be different in your system. The path above is the default one. If you have removed the files, you need to rerun the maven command.

IDE Issue

It is time to check if its IDE fault at this point. We will show you the steps for the Eclipse. At command line level outside of Eclipse ran ‘mvn compile’. If the command doesn’t work, go to the next paragraph. If it runs and you’ve still got the same issue, read further. It happens when Eclipse doesn’t use the maven plugin. You should go here:
Window -> Preferences -> Maven -> User Settings and check if you got the path to the settings.xml there. If not, you should create the file yourself in your project. This is a sample of how it should look like:

Automatically download and install missing plugin

You can do that by declaring the missing plugin in the POM file. Maven will automatically retrieve the required plugin. POM file contains all the plugins which your project uses. You should put in the <plugins> section the one you need and wait until Maven download and synchronize himself. In the <plugin> section you should have something similar to:

Manually install needed plugin

If you are reading this paragraph, it means that none of the above ones helped. The last thing you can do is to manually download the plugin from the maven repository website. After doing that just copy it into the folder where Maven holds all the plugins. In the end, just reran the ‘mvn compile’ command.

How to create an InputStream from a String in Java?

August 22, 2017

This short post will present how to convert String to InputStream in Java.

1. The String.getBytes() method with ByteArrayInputStream constructor

At the beginning, we declared a String and used the String.getBytes() method to convert it to the bytes array. We created a new InputStream object by using the constructor of the ByteArrayInputStream class, passing the bytes array as a method constructor parameter.

2. Apache Commons

If you are familiar with Apache libraries, you can make use of IOUtils class:

The output will be the same as before.

 

 

How to round a double to n decimal places in Java

To round a double to n decimal places, we need to use the BigDecimal.doubleValue() method.

1. Creating a proper method

We can easily reach the rounding by creating the round method, like in the example below.

As you can see, this code allows us to round to a specific number of places. In the above example, we’ve rounded the number 47.432643 to 2 decimal places. Let’s talk a little bit about this code.

2. Analysis

The round method takes two arguments: val which is the value to round and places which is a number of places we want to round to. Next, if the places are given wrong the method throws an exception.

Then we must convert val to BigDecimal because it gives us complete control over rounding behavior. Further, we use the setScale method to reach our goal – rounding to specified places. RoundingMode gives us the opportunity to decide how we can round the number. Here, when we got the half of number it is rounded up but we can change it to down or to an even number.

In the end, the method returns the converted value to the previous type which is double.

As the result, in the main method, we can test our fresh method. The code prints:

How to run a jar file in command prompt

In this very short post, we will show how to run a jar file in command prompt.

1. -jar command

To run a jar file you need use this command:

2. -cp command

Although, if you don’t have a manifest in your jar invoking java -jar command will not work. In that case, you should use -cp command:

 

1 2 3 4
Page 1 of 4

Privacy Preference Center

Necessary

Advertising

Analytics

Other