Monday, 26 September 2016

Converting float to int - Java program

If you have a float number and you have a requirement to show number at some places without decimal points then one of the option is to convert that float type to int and display the value, that’s what this post is about – Converting float to int.

Main point of concern here are -

  • Range; as range of float is much more than int so if you have a float value which will be out of range if converted to int what should happen?
  • How rounding will happen for a float with decimal value when converted to integer.

So let’s see the options available and how these concerns will be addressed.

Using Float.intValue() method

  • intValue()- Returns the value of this Float as an int after a narrowing primitive conversion.
public class FloatToInt {

 public static void main(String[] args) {
  Float f = new Float(567.678);
  int val = f.intValue();
  System.out.println("int value " + val);
 }
}

Output

int value 567

Here you can see that rounding doesn’t happen while converting digits after the decimal points are removed. You will get the same result if you use typecasting instead.

Using typecasting

public class FloatToInt {

 public static void main(String[] args) {
  
  float fVal = 567.678f;
  // type casting
  int val1 = (int)fVal;
  System.out.println("int value " + val1);
  
 }

}

Output

int value 567

Here again you can see by type casting digits after the decimal are removed and there is no rounding. The only difference between using Float.intValue() and explicit casting is you need Float object for using intValue() where as typecasting can be done with a primitive float data type.

Using Math.round() method

As you have seen above methods of converting float to int are just giving the whole part of the number but mostly you will also like to do rounding. For that you can use Math.round method which takes float as argument and returns the value of the argument rounded to the nearest int value.

There are also some special cases –

  • If the argument is NaN, the result is 0.
  • If the argument is negative infinity or any value less than or equal to the value of Integer.MIN_VALUE, the result is equal to the value of Integer.MIN_VALUE.
  • If the argument is positive infinity or any value greater than or equal to the value of Integer.MAX_VALUE, the result is equal to the value of Integer.MAX_VALUE.

Example code

If we take the same float value as used above

public class FloatToInt {

 public static void main(String[] args) {
  
  float fVal = 567.678f;
  int rVal = Math.round(fVal);
  System.out.println("int value " + rVal);
 }
}

Output

int value 568

Here you can see that the value is rounded to the nearest int value.

Example with Some more values -

public class FloatToInt {

 public static void main(String[] args) {
  float f1 = -10.78f;
  float f2 = 4.4999f;
  float f3 = 105.12f;
  int i1 = Math.round(f1);
  int i2 = Math.round(f2);
  int i3 = Math.round(f3);
  System.out.println("float value: " + f1 + "int value: " + i1);
  System.out.println("float value: " + f2 + "int value: " + i2);
  System.out.println("float value: " + f3 + "int value: " + i3);
 }
}

Output

float value: -10.78int value: -11
float value: 4.4999int value: 4
float value: 105.12int value: 105

If float value out of range

If you have seen the special cases mentioned above.

  • If the argument is negative infinity or any value less than or equal to the value of Integer.MIN_VALUE, the result is equal to the value of Integer.MIN_VALUE.
  • If the argument is positive infinity or any value greater than or equal to the value of Integer.MAX_VALUE, the result is equal to the value of Integer.MAX_VALUE.
public class FloatToInt {

 public static void main(String[] args) {
  Float f = new Float(567678865544.678);
  int val = f.intValue();
  System.out.println("int value " + val);
  
  float fVal = 567678865544.678f;
  int val1 = (int)fVal;
  System.out.println("int value " + val1);
  
 }

}

Output

int value 2147483647
int value 2147483647

Here it can be seen that integer value is equal to Integer.MAX_VALUE as float value is greater than Integer.MAX_VALUE

Same way you can check for minimum value.

That's all for this topic Converting float to int - Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Converting string to int - Java Program
  2. Converting double to string - Java Program
  3. Armstrong number
  4. Factorial program in Java
  5. Displaying prime numbers - Java program

You may also like -

>>>Go to Java Programs page

Friday, 23 September 2016

Converting double to string - Java Program

In the post converting String to double we have already seen ways to do that conversion. This post is about doing just the reverse; convert double values to string.

Concatenating with an empty String

Easiest way to convert double to a string is to concatenate double with an empty string. That will give you a string value, conversion is handled for you.

public class DoubleToString {

 public static void main(String[] args) {
  double num = 78.111167d;
  String str = "" + num;
  System.out.println("Value " + str);
 }
}

Output

Value 78.111167

Here note that with double value you can use d or D (even f or F, for single float). If you use f instead of d value may be a little different.

Using valueOf() method of String class

String class has valueOf() method which is overloaded and those variants take int, float, double, long data types as parameters. Using valueOf(double d) method will return string representation of the double argument.

public class DoubleToString {
 public static void main(String[] args) {
  double num = -67.16789;
  String str = String.valueOf(num);
  System.out.println("Value " + str);

 }
}

Output

Value -67.16789

toString() method of the wrapper classes

Each of the Number subclass (Integer, Float, Double etc.) includes a class method, toString(), that will convert its primitive type to a string. Thus, using Double.toString(double d) returns a String object representing the specified float value.

public class DoubleToString {

 public static void main(String[] args) {
  double num = 124686.9698694d;
  String str = String.valueOf(num);
  System.out.println("Value " + str);

 }
}

Output

Value 124686.9698694

Using String.format method

  • String format(String format, Object... args) - Returns a formatted string using the specified format string and arguments.
Here as a format you can use 'f' which means floating point and the result is formatted as a decimal number.

Example code

public class DoubleToString {

 public static void main(String[] args) {
  double num = 124686.9698694d;
  String str = String.format("%.2f", num);
  System.out.println("Value " + str);
 }
}

Output

Value 124686.97

Here note that .2f is used as format so there will be 2 decimal places. In the syntax you can see that second argument is a vararg which is of type Object. Still you can pass double primitive data type because of autoboxing.

That's all for this topic Converting double to string - Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Converting float to string - Java Program
  2. Displaying prime numbers - Java program
  3. How to format date in Java using SimpleDateFormat
  4. How to find the longest palindrome in the given String
  5. Java String interview questions

You may also like -

>>>Go to Java Programs page

Thursday, 22 September 2016

Converting string to double - Java Program

There are several instances when you want to convert a string to double data type so in this post we’ll see what different ways do we have for this conversion.

In Java, Double class provides two methods for converting string to float -

  • parseDouble(String s) - Returns a new double initialized to the value represented by the specified String. Throws NumberFormatException if the string does not contain a parsable double.
  • valueOf(String s) - Returns a Double object holding the double value represented by the argument string s. Throws NumberFormatException if the string does not contain a parsable number. If s is null, then a NullPointerException is thrown.

Here Few things to note are -

  1. Both of the methods are static so you can use them directly with the class i.e. Double.parseDouble(String s) and Double.valueOf(String s).
  2. If you have noticed parseDouble method returns double (primitive data type) where as valueOf() method returns Double class object.
  3. String passed should have digits only except that the first character may be an ASCII minus sign '-' ('\u002D') to indicate a negative value or an ASCII plus sign '+' ('\u002B') to indicate a positive value.
  4. You can use “d” or “D” (even f or F which denotes float) with the value so having string as “43.67d” will not throw NumberFormatException while converting where as “43.67e” will throw exception.

Note that Double class also has a constructor that takes String as argument so that is also one way to convert string to float.

Double(String s) - Constructs a newly allocated Double object that represents the floating-point value of type double represented by the string.

Double.parseDouble example

public class StringToDouble {

 public static void main(String[] args) {
  String num = "45.78678968d";
  try{
   double value = Double.parseDouble(num);
   System.out.println("value " + value);
  }catch(NumberFormatException neExp){
   System.out.println("Error while conversion " + 
      neExp.getMessage());
  }
 }
}

Output

value 45.78678968

Since double has double precision and occupies 8 bytes so you will get better precision than float.

Double.valueOf() example

public class StringToDouble {
 public static void main(String[] args) {
  String num = "-45.0784";
  try{
   Double value = Double.valueOf(num);
   System.out.println("value " + value);
  }catch(NumberFormatException neExp){
   System.out.println("Error while conversion " + 
      neExp.getMessage());
  }
 }
}
Output
value -45.0784

Note here that if the sign is negative, the first character of the result is '-' , if the sign is positive, no sign character appears in the result.

NumberFormatException

If conversion fails then NumberFormatExcpetion is thrown. So, it is better to enclose your conversion code with in a try-catch block.

public class StringToDouble {

 public static void main(String[] args) {
  String num = "45.0784e";
  try{
   Double value = Double.valueOf(num);
   System.out.println("value " + value);
  }catch(NumberFormatException neExp){
   System.out.println("Error while conversion " + 
      neExp.getMessage());
  }

 }

}

Output

Error while conversion For input string: "45.0784e"

Note here that String has alphabet e also along with the digits. Which results in NumberFormatException.

That's all for this topic Converting string to double - Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Converting float to string - Java Program
  2. Converting int to string - Java Program
  3. Searching within a String using indexOf(), lastIndexOf() and contains() methods
  4. Converting string to bytearray - Java Program
  5. How to add double quotes to a String

You may also like -

>>>Go to Java Programs page

Tuesday, 20 September 2016

Converting float to string - Java Program

In the post converting String to float we have already seen ways to do that conversion. This post is about doing just the reverse; convert float values to string.

Concatenating with an empty String

Easiest way to convert float to a string is to concatenate float with an empty string. That will give you a string value, conversion is handled for you.

public class FloatToString {

 public static void main(String[] args) {
  float num = 7.345f;
  String value = "" + num;
  System.out.println("Value is " + value);
 }
}

Output

Value is 7.345

Using valueOf() method of String class

String class has valueOf() method which is overloaded and those variants take int, float, double, long data types as parameters. Using valueOf(float f) method will return string representation of the float argument.

public class FloatToString {

 public static void main(String[] args) {
  float num = -97.345f;
  String value = String.valueOf(num);
  System.out.println("Value is " + value);

 }

}

Output

Value is -97.345

toString() method of the wrapper classes

Each of the Number subclass (Integer, Float, Double etc.) includes a class method, toString(), that will convert its primitive type to a string. Thus, using Float.toString(float f) returns a String object representing the specified float value.

public class FloatToString {

 public static void main(String[] args) {
  float num = 78.34576865959f;
  String value = Float.toString(num);
  System.out.println("Value is " + value);
 }
}

Output

Value is 78.34577

Here note that vale has been rounded off. That is one thing to be considered while converting float values that those are not precise.

That's all for this topic Converting float to string - Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Converting int to string - Java Program
  2. Converting string to bytearray - Java Program
  3. Check whether a given String/Number is a palindrome or not
  4. How to find all the permutations of the given String
  5. Java String interview questions

You may also like -

>>>Go to Java Programs page

Monday, 19 September 2016

Converting string to float - Java Program

There are several instances when you want to convert a string to float data type so in this post we’ll see what different ways do we have for this conversion.

In Java, Float class provides two methods for converting string to float -

  • parseFloat(String s) - Returns a new float initialized to the value represented by the specified String. Throws NumberFormatException if the string does not contain a parsable number.
  • valueOf(String s) - Returns a Float object holding the float value represented by the argument string s. Throws NumberFormatException if the string does not contain a parsable number.

Here Few things to note are -

  1. Both of the methods are static so you can use them directly with the class i.e. Float.parseFloat(String s) and Float.valueOf(String s).
  2. If you have noticed parseFloat method returns float (primitive data type) where as valueOf() method returns Float class object.
  3. String passed should have digits only except that the first character may be an ASCII minus sign '-' ('\u002D') to indicate a negative value or an ASCII plus sign '+' ('\u002B') to indicate a positive value.
  4. You can use “f” or “F” (even d or D which denotes double) with the float value so having string as “56.78f” will not throw NumberFormatException while converting where as “56.78a” will throw exception.

Note that Float class also has a constructor that takes String as argument so that is also one way to convert string to float.

  • Float(String s) - Constructs a newly allocated Float object that represents the floating-point value of type float represented by the string.

Float.parseFloat example

public class StringToFloat {

 public static void main(String[] args) {
  String num = "-67.789788F";
  try{
   float value = Float.parseFloat(num);
   System.out.println("value " + value);
  }catch(NumberFormatException neExp){
   System.out.println("Error while conversion " + 
      neExp.getMessage());
  }
 }
}

Output

value -67.78979

Here you can see that while converting to float number has been rounded off. So be informed that some precision may be lost while converting as float as float is single precision represented by 32 bits (4 bytes) if you want more precision then you may use Double or even better BigDecimal.

Float.valueOf() example

public class StringToFloat {

 public static void main(String[] args) {
  String num = "45.78";
  try{
   Float value = Float.valueOf(num);
   System.out.println("value " + value);
  }catch(NumberFormatException neExp){
   System.out.println("Error while conversion " + 
      neExp.getMessage());
  }
 }
}

Output

value 45.78

Note that here value is a Float class object.

NumberFormatExcpetion

If conversion fails then NumberFormatExcpetion is thrown. So, it is better to enclose your conversion code with in a try-catch block.

Example code

public class StringToFloat {

 public static void main(String[] args) {
  String num = "45.78e";
  try{
   Float value = Float.valueOf(num);
   System.out.println("value " + value);
   System.out.println("value " + value.floatValue());
  }catch(NumberFormatException neExp){
   System.out.println("Error while conversion " + 
      neExp.getMessage());
  }
 }
}

Output

Error while conversion For input string: "45.78e"

That's all for this topic Converting string to float - Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Converting string to int - Java Program
  2. Converting string to bytearray - Java Program
  3. Count number of words in a String
  4. String join() method in Java 8
  5. Searching within a String using indexOf(), lastIndexOf() and contains() methods

You may also like -

>>>Go to Java Programs page

Wednesday, 14 September 2016

forEach statement in Java 8

Undoubtedly, the most important addition in Java 8 are lambda expressions and stream. Along with these features came the new forEach method to loop the collections like List and Set. Of course you can also use it with Map but with a little difference as Map doesn’t implement either the Iterable or the Collection interface.

Using forEach()

  1. Iterable interface provides forEach method as an interface default method
    default void forEach(Consumer<? super T> action)
    

    Where Consumer is the functional interface which implements the action to be performed on each iteration. If you see the default implementation of forEach in Iterable interface it is like-

    for (T t : this) {
     action.accept(t);
    }
    

    Collections like list and set implement Iterable interface so they can use forEach() directly. As example if there is a list called numList and you want to iterate it using forEach() method it can be done like -

    numList.forEach(System.out::println);
    

    Here note that method reference is used to call println method.

  2. Another way to use forEach is to get it through stream. Stream interface also has forEach method. Collection interface provides the default implementation for getting the stream instance. As example of if there is a list called numList you can convert it to stream and then call forEach method like this -

    numList.stream().forEach(System.out::println);
    

    Ofcourse you can call many other methods on the stream like filter and then at the last you can call a terminal operation like forEach to get what all elements are left after filtering.

    As example

    List<Integer> numList = Arrays.asList(1, 2, 3, 4, 5);
    numList.stream().filter(l -> l>3).forEach(System.out::println);
    

    Output

    4
    5
    

Iterating List and Set using Iterable’s forEach

public class ForEachDemo {
    public static void main(String args[]){
        List<Integer> numList = Arrays.asList(1, 2, 3, 4, 5);
        System.out.println("Iterating list  ");
        numList.forEach(System.out::println);
        
        Set<Integer> numSet = new HashSet<Integer>();
        numSet.add(1);
        numSet.add(2);
        System.out.println("Iterating set  ");
        numSet.forEach(System.out::println);
    }
}

Output

Iterating list  
1
2
3
4
5
Iterating set  
1
2

Using Stream and forEach

public class ForEachDemo {
    public static void main(String args[]){
        List<Integer> numList = Arrays.asList(1, 2, 3, 4, 5);
        System.out.println("Iterating list  ");
        // numbers greater than 3
        numList.stream().filter(l -> l > 3).forEach(System.out::println);
        
        Set<Integer> numSet = new HashSet<Integer>();
        numSet.add(1);
        numSet.add(2);
        System.out.println("Iterating set  ");
        // Only even numbers
        numSet.stream().filter(s -> s%2 == 0).forEach(System.out::println);
        
    }
}

Output

Iterating list  
4
5
Iterating set  
2

Using with Map

As already mentioned Map doesn’t implement Collection interface so you have to get the Collection view of the map and then use forEach method in case you are using it after converting to stream.
Map interface also provides default implementation of forEach method so it can be used directly also.

Example code

public class ForEachDemo {
    public static void main(String args[]){
        Map<String, String> numMap = new HashMap<String, String>();
        
        numMap.put("1", "1");
        numMap.put("2", "2");
        // Directly using
        numMap.forEach((k, v) -> System.out.println("Key " + k));
        // With stream
        numMap.entrySet().stream().forEach(System.out::println);
    }
}

Output

Key 1
Key 2
1=1
2=2

That's all for this topic forEach statement in Java 8. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. interface static methods in Java 8
  2. Optional class in Java 8
  3. Overview of lambda expressions
  4. effectively final in Java 8
  5. String join() method in Java 8

You may also like -

>>>Go to Java advance topics page

Monday, 12 September 2016

Converting string to bytearray - Java Program

This post shows how String can be converted to byte array and vice versa.

String class has getBytes() method which can be used to convert String to byte array.

getBytes() - Encodes this String into a sequence of bytes using the platform's default charset, storing the result into a new byte array.

There are two other variants of getBytes() method in order to provide an encoding for String.

  • getBytes(Charset charset)
  • getBytes(String charsetName)

Java Program

import java.util.Arrays;

public class StringToByte {

 public static void main(String[] args) {
  String str = "Example String";
  byte[] b = str.getBytes();
  System.out.println("Array " + b);
  System.out.println("Array as String" + Arrays.toString(b));
 }

}

Output

Array [B@2a139a55
Array as String[69, 120, 97, 109, 112, 108, 101, 32, 83, 116, 114, 105, 110, 103]

As you can see here printing the byte array as it is gives the memory address so used Arrays.toString in order to print the array.

Conversion with encoding

Suppose you want to use “UTF-8” encoding then it can be done in 3 ways.

String str = "Example String";
byte[] b;
try {
 b = str.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
}
b = str.getBytes(Charset.forName("UTF-8"));
b = str.getBytes(StandardCharsets.UTF_8);

Using str.getBytes("UTF-8") will require to enclose it in a try-catch block as UnsupportedEncodingException is thrown. To avoid that you can use str.getBytes(Charset.forName("UTF-8")) Java 7 and above you can also use str.getBytes(StandardCharsets.UTF_8);

Converting byte array to String

String class has a constructor which takes byte array as an argument. Using that you can get the String from a byte array.

String(byte[] bytes) - Constructs a new String by decoding the specified array of bytes using the platform's default charset.

If you want to provide a specific encoding then you can use the following constructor -

String(byte[] bytes, Charset charset) - Constructs a new String by decoding the specified array of bytes using the specified charset.

Example code

public class StringToByte {

 public static void main(String[] args) {
  String str = "Example String";
  // converting to byte array
  byte[] b = str.getBytes();
  
  // Getting the string from a byte array
  String s = new String (b);
  System.out.println("String - " + s);
 }
}

Output

String - Example String

That's all for this topic Converting string to bytearray - Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Converting string to int - Java Program
  2. How to find the longest palindrome in the given String
  3. How to find all the permutations of the given String
  4. Check if given strings are anagram or not
  5. How to add double quotes to a String

You may also like -

>>>Go to Java Programs page