Skip to main content

Posts

Showing posts with the label Java

Best way to convert float to int in Java 8?

Most of the time, Java developers have to do type conversion. In this example, I will cover the conversion of  float datatype to int . There are several ways to achieve this. Solution 1 public class FloatToIntCasting {               public static void main( String[] args ) {                  float value = 0.9f;                  System.out.println( "0.9f converted to int : " +  (int) value );                  value = 1.1f;                  System.out.println( "1.1f converted to int : " + (int) value );              } } Output  0.9 f converted to int : 0 1.1 f converted to  int  : 1 As we can see in the above example, casting a float to int results in downcasting. It simply removes the fraction part and returns the value. Solution 2 public class FloatToIntUsingMathRound {     public static void main( String[] args ) {         float value = 0.9f;                    System.out.println( "0.9f rounded to int  : " + 

Java - slf4j vs log4j

Java developers use these two APIs but most of them will not be aware of the differences between these two. slf4j stands for Simple Logging Facade for Java. It can be considered as a simple  Facade  or abstraction for various Java logging frameworks and not an implementation. It adds the flexibility to switch different logging framework for application and this decision can be taken at runtime without recompiling the code. This prevents the application to be dependent on a specific logging framework and unwanted inclusion of different jar/libraries dependent on that specific logging framework. commons-logging  is a competitor or alternate for slf4j. log4j is the implementation and it provides the logging or tracing ability to the application. It is one of the most widely used logging framework for Java. Manual logging can drastically impact the performance of an application and can slow it down, whereas log4j has been designed for flexibility, simplicity and speed.