Monday, June 5, 2017

Java 8 Date and Time API: How to Convert Date to Java 8 Date and Time


In this tutorial, you will learn:
  • How to convert Date to Instant
  • How to convert Date to LocalDate
  • How to convert Date to LocalTime
  • How to convert Date to LocalDateTime
  • How to convert Date to ZonedDateTime
Example
package com.melody.datetime;

import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Date;

public class ConvertDateToJava8Date {

 public static void main(String[] args) {
  // Date has no timezone
  Date date = new Date();

  // I did not use toString() because it will automatically
  // format the date with the system default timezone
  System.out.println("Date: " + date.toGMTString());

  // Convert Date to Instant.
  // Instant is the equivalent of Date in Java 8 Date API.
  Instant instant = date.toInstant();
  System.out.println("Instant: " + instant);

  ZoneId defaultTimeZone = ZoneId.systemDefault();

  // Convert Instant to LocalDate (using the system default timezone)
  LocalDate localDate = instant.atZone(defaultTimeZone).toLocalDate();
  System.out.println("LocalDate: " + localDate);

  // Convert Instant to LocalTime (using the system default timezone)
  LocalTime localTime = instant.atZone(defaultTimeZone).toLocalTime();
  System.out.println("LocalTime: " + localTime);

  // Convert Instant to LocalDateTime (using the system default timezone)
  LocalDateTime localDateTime = instant.atZone(defaultTimeZone).toLocalDateTime();
  System.out.println("LocalDateTime: " + localDateTime);

  // Convert Instant to ZonedDateTime (using the system default timezone)
  ZonedDateTime zonedDateTime = instant.atZone(defaultTimeZone);
  System.out.println("ZonedDateTime: " + zonedDateTime);
 }
}
Output

Date: 5 Jun 2017 09:01:52 GMT
Instant: 2017-06-05T09:01:52.527Z
LocalDate: 2017-06-05
LocalTime: 17:01:52.527
LocalDateTime: 2017-06-05T17:01:52.527
ZonedDateTime: 2017-06-05T17:01:52.527+08:00[Asia/Shanghai]


Java 8 Date and Time API: How to Compare Date and Time


In this tutorial, you will learn:
  • How to compare two given LocalDate (e.g. determine if two LocalDate are equal)
  • How to compare two given LocalTime (e.g. determine if two LocalTime are equal)
  • How to find the difference between two LocalDate(e.g. number of days in between)
  • How to find the difference between two LocalTime (e.g. number of minutes in between)
Example
package com.melody.datetime;

import java.time.LocalDate;
import java.time.LocalTime;
import java.time.temporal.ChronoUnit;

public class CompareDateTimeDemo {

 public static void main(String[] args) {
  // Compare LocalDate and calculate differences between two LocalDate
  LocalDate localDate1 = LocalDate.now();
  LocalDate localDate2 = localDate1.plusDays(30);

  System.out.println("Date 1: " + localDate1);
  System.out.println("Date 2: " + localDate2);
  System.out.println("Date 1 is after Date 2? " + localDate1.isAfter(localDate2));
  System.out.println("Date 1 is before Date 2? " + localDate1.isBefore(localDate2));
  System.out.println("Date 1 is equal to Date 2? " + localDate1.isEqual(localDate2));
  System.out.println("No. of days between Date 1 and Date 2: " + ChronoUnit.DAYS.between(localDate1, localDate2));

  // Compare LocalTime calculate differences between two LocalTime
  LocalTime localTime1 = LocalTime.now();
  LocalTime localTime2 = localTime1.minusHours(3);

  System.out.println("\nTime 1: " + localTime1);
  System.out.println("Time 2: " + localTime2);
  System.out.println("Time 1 is after Time 2? " + localTime1.isAfter(localTime2));
  System.out.println("Time 1 is before Time 2? " + localTime1.isBefore(localTime2));
  System.out.println("No. of hours between Time 1 and Time 2: " + ChronoUnit.HOURS.between(localTime2, localTime1));
 }
}
Output

Date 1: 2017-06-05
Date 2: 2017-07-05
Date 1 is after Date 2? false
Date 1 is before Date 2? true
Date 1 is equal to Date 2? false
No. of days between Date 1 and Date 2: 30

Time 1: 16:53:59.403
Time 2: 13:53:59.403
Time 1 is after Time 2? true
Time 1 is before Time 2? false
No. of hours between Time 1 and Time 2: 3


Java 8 Date and Time API: How to Convert a Time Zone between Countries


In this tutorial, you will learn:
  • How to convert a time zone between different countries using the new Java 8 Date and Time API
Example
package com.melody.datetime;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;

public class ConvertTimezoneDemo {

 public static void main(String[] args) {
  DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy hh:mm:ss a");

  String dateAsString = "05/13/2017 07:30:45 AM";

  // Instantiate a LocalDateTime (without timezone)
  LocalDateTime localDateTime = LocalDateTime.parse(dateAsString, formatter);
  System.out.println("Local date & time without timezone: " + localDateTime.format(formatter));

  // Convert LocalDateTime to ZonedDateTime (timezone = Shanghai)
  ZoneId shanghaiZoneId = ZoneId.of("Asia/Shanghai");
  ZonedDateTime shanghaiZonedDateTime = localDateTime.atZone(shanghaiZoneId);
  System.out.println("Date & time in Shanghai: " + shanghaiZonedDateTime.format(formatter)
     + " " + shanghaiZonedDateTime.getZone());

  // Convert ZonedDateTime to another timezone
  ZoneId newYorkZoneId = ZoneId.of("America/New_York");
  ZonedDateTime newYorkZonedDateTime = shanghaiZonedDateTime.withZoneSameInstant(newYorkZoneId);
  System.out.println("Date & time in New York: " + newYorkZonedDateTime.format(formatter)
    + " " + newYorkZonedDateTime.getZone());
 }
}
Output

Local date & time without timezone: 05/13/2017 07:30:45 AM
Date & time in Shanghai: 05/13/2017 07:30:45 AM Asia/Shanghai
Date & time in New York: 05/12/2017 07:30:45 PM America/New_York


Wednesday, May 17, 2017

Java 8 Date and Time API: DateTimeFormatter


In this tutorial, you will learn:

  • How to format LocalDateTime (date to text)
  • How to parse (convert) String to LocalDateTime (text to date)
Example
package com.melody.datetime;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class DateTimeFormatterDemo {

 public static void main(String[] args) {
  DateTimeFormatter formatter1 = DateTimeFormatter.ofPattern("MM-dd-yyyy hh:mm:ss a");
  DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("MM/dd/yyyy HH:mm:ss");

  // Format LocalDateTime (date to text)
  LocalDateTime currentDateTime = LocalDateTime.now();
  System.out.println("Default date & time format: " + currentDateTime);


  String formattedDateTime = currentDateTime.format(formatter1);
  System.out.println("Format LocalDateTime (date to text): " + formattedDateTime);

  // Parse (convert) String to LocalDateTime (text to date)
  String dateAsString = "05/13/2017 14:30:45";
  System.out.println("Date string to parse: " + dateAsString);

  LocalDateTime parsedDateTime = LocalDateTime.parse(dateAsString, formatter2);
  System.out.println("Parse string to LocalDateTime (text to date): " + parsedDateTime);
 }
}
Output

Default date & time format: 2017-05-17T20:41:33.205
Format LocalDateTime (date to text): 05-17-2017 08:41:33 PM
Date string to parse: 05/13/2017 14:30:45
Parse string to LocalDateTime (text to date): 2017-05-13T14:30:45



Java 8 Date and Time API: ZonedDateTime


Java 8 date and time API introduces a new class ZonedDateTime under java.time package which represents a local date and time with a timezone. ZonedDateTime instances are immutable (cannot be changed) so any operations performed on ZonedDateTime will always return a new instance.

In this tutorial, you will learn:
  • How to create a ZonedDateTime instance representing the current date and time with a timezone
  • How to create a ZonedDateTime instance from a given LocalDate,  LocalTime and timezone
  • How to access the ZonedDateTime properties (e.g. month, year, day of week, etc.)
  • How to perform plus and minus operations on ZonedDateTime
  • How to create instance of ZoneId using offset and timezone location
Example
package com.melody.datetime;

import java.time.LocalDate;
import java.time.LocalTime;
import java.time.Period;
import java.time.ZoneId;
import java.time.ZonedDateTime;

public class ZonedDateTimeDemo {

 public static void main(String[] args) {
  ZonedDateTime currentZonedDateTime = ZonedDateTime.now();
  System.out.println("Current date and time with timezone: "
    + currentZonedDateTime);

  // Create a ZonedDateTime instance from a given date,
  // time and timezone
  ZoneId zoneId = ZoneId.systemDefault();
  LocalDate localDate = LocalDate.of(2017, 11, 14);
  LocalTime localTime = LocalTime.of(13, 30, 44);
  ZonedDateTime zonedDateTime = ZonedDateTime.of(localDate, localTime, zoneId);
  System.out.println("ZonedDateTime instance from date and time using system timezone: "
    + zonedDateTime);

  // Access the ZonedDateTime properties
  System.out.println("Get date: " + zonedDateTime.toLocalDate());
  System.out.println("Get time: " + zonedDateTime.toLocalTime());
  System.out.println("Get timezone: " + zonedDateTime.getZone());
  System.out.println("Get year: " + zonedDateTime.getYear());
  System.out.println("Get month (enum): " + zonedDateTime.getMonth());
  System.out.println("Get month: " + zonedDateTime.getMonthValue());
  System.out.println("Get day of month: " + zonedDateTime.getDayOfMonth());
  System.out.println("Get hour: " + zonedDateTime.getHour());
  System.out.println("Get minute: " + zonedDateTime.getMinute());
  System.out.println("Get second: " + zonedDateTime.getSecond());

  // Add and minus operations on ZonedDateTime
  // using Period instead of plusXX or minusXX because it can
  // give more accurate calculation when daylight saving changes
  // are involved.
  System.out.println("Add 1 yr to 2017-11-14: " + zonedDateTime.plus(Period.ofYears(1)));
  System.out.println("Minus 1 yr, 1 month & 1 day from 2017-11-14: " + zonedDateTime.minus(Period.of(1, 1, 1)));

  // Create instance of ZoneId using offset
  ZoneId zoneId1 = ZoneId.of("UTC+8");
  System.out.println("Zone Id using offset UTC+8: " + zoneId1);

  // Create instance of ZoneId using timezone location (continent/city)
  ZoneId zoneId2 = ZoneId.of("Asia/Shanghai");
  System.out.println("Zone Id using timezone location Asia/Shanghai: " + zoneId2);
 }
}

Output

Current date and time with timezone: 2017-05-17T20:34:02.561+08:00[Asia/Shanghai]
ZonedDateTime instance from date and time using system timezone: 2017-11-14T13:30:44+08:00[Asia/Shanghai]
Get date: 2017-11-14
Get time: 13:30:44
Get timezone: Asia/Shanghai
Get year: 2017
Get month (enum): NOVEMBER
Get month: 11
Get day of month: 14
Get hour: 13
Get minute: 30
Get second: 44
Add 1 yr to 2017-11-14: 2018-11-14T13:30:44+08:00[Asia/Shanghai]
Minus 1 yr, 1 month & 1 day from 2017-11-14: 2016-10-13T13:30:44+08:00[Asia/Shanghai]
Zone Id using offset UTC+8: UTC+08:00
Zone Id using timezone location Asia/Shanghai: Asia/Shanghai



Java 8 Date and Time API: LocalDateTime


Java 8 date and time API introduces a new class LocalDateTime under java.time package which represents a local date and time without a timezone. LocalDateTime instances are immutable (cannot be changed) so any operations performed on LocalDateTime will always return a new instance.

In this tutorial, you will learn:
  • How to create a LocalDateTime instance representing the current date and time
  • How to create a LocalDateTime instance from a given year, month, day, hour, minute and second
  • How to create a LocalDateTime instance from a given LocalDate and LocalTime
  • How to access the LocalDateTime properties (e.g. month, year, day of week, etc.)
  • How to perform plus and minus operations on LocalDateTime
  • How to convert LocalDateTime to ZonedDateTime (date and time with timezone)
Example
package com.melody.datetime;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.temporal.TemporalAdjusters;

public class LocalDateTimeDemo {

 public static void main(String[] args) {
  LocalDateTime currentLocalDateTime = LocalDateTime.now();
  System.out.println("Current local date and time: " + currentLocalDateTime);

  // Create a LocalDateTime instance from a given year, month,
  // day, hour, minute and second
  LocalDateTime localDateTime = LocalDateTime.of(2017, 11, 14, 13, 45, 30);
  System.out.println("Local date & time from a given year, month, day, hour, minute & second: "
    + localDateTime);

  // Create a LocalDateTime instance from date and time
  LocalDate localDate = LocalDate.of(2017, 11, 14);
  LocalTime localTime = LocalTime.of(13, 30, 44);
  LocalDateTime localDateTime2 = LocalDateTime.of(localDate, localTime);
  System.out.println("LocalDateTime instance from date and time: " + localDateTime2);

  // Access the LocalDateTime properties
  System.out.println("Get date: " + localDateTime.toLocalDate());
  System.out.println("Get time: " + localDateTime.toLocalTime());
  System.out.println("Get year: " + localDateTime.getYear());
  System.out.println("Get month (enum): " + localDateTime.getMonth());
  System.out.println("Get month: " + localDateTime.getMonthValue());
  System.out.println("Get day of month: " + localDateTime.getDayOfMonth());
  System.out.println("Get hour: " + localDateTime.getHour());
  System.out.println("Get minute: " + localDateTime.getMinute());
  System.out.println("Get second: " + localDateTime.getSecond());

  // Add and minus operations on LocalDateTime
  System.out.println("Add 1 yr, 1 month & 1 day to 2017-11-14: " + localDateTime.plusYears(1).plusMonths(1).plusDays(1));
  System.out.println("Minus 1 yr, 1 month & 1 day from 2017-11-14: " + localDateTime.minusYears(1).minusMonths(1).minusDays(1));
  System.out.println("Add 1 hour, 1 minute & 1 second to 13:45:30 = " + localDateTime.plusHours(1).plusMinutes(1).plusSeconds(1));
  System.out.println("Minus 1 hour, 1 minute & 1 second to 13:45:30 = " + localDateTime.minusHours(1).minusMinutes(1).minusSeconds(1));

  // Adjust the LocalDateTime
  System.out.println("Adjust 2017-11-14 into 2019-12-14: " + localDateTime.withYear(2019).withMonth(12));
  System.out.println("Adjust 13:45:30 into 15:30:30 = " + localDateTime.withHour(15).withMinute(30));

  // Adjust the LocalDateTime using TemporalAdjusters
  System.out.println("Adjust 2017-11-14 into first day of the month: " + localDateTime.with(TemporalAdjusters.firstDayOfMonth()));

  // Convert LocalDateTime to ZonedDateTime (date & time with timezone)
  ZonedDateTime zonedDateTime = localDateTime.atZone(ZoneId.of("Asia/Shanghai"));
  System.out.println("Convert LocalDateTime to ZonedDateTime: " + zonedDateTime);
 }
}
Output

Current local date and time: 2017-05-17T20:23:56.230
Local date & time from a given year, month, day, hour, minute & second: 2017-11-14T13:45:30
LocalDateTime instance from date and time: 2017-11-14T13:30:44
Get date: 2017-11-14
Get time: 13:45:30
Get year: 2017
Get month (enum): NOVEMBER
Get month: 11
Get day of month: 14
Get hour: 13
Get minute: 45
Get second: 30
Add 1 yr, 1 month & 1 day to 2017-11-14: 2018-12-15T13:45:30
Minus 1 yr, 1 month & 1 day from 2017-11-14: 2016-10-13T13:45:30
Add 1 hour, 1 minute & 1 second to 13:45:30 = 2017-11-14T14:46:31
Minus 1 hour, 1 minute & 1 second to 13:45:30 = 2017-11-14T12:44:29
Adjust 2017-11-14 into 2019-12-14: 2019-12-14T13:45:30
Adjust 13:45:30 into 15:30:30 = 2017-11-14T15:30:30
Adjust 2017-11-14 into first day of the month: 2017-11-01T13:45:30
Convert LocalDateTime to ZonedDateTime: 2017-11-14T13:45:30+08:00[Asia/Shanghai]



Tuesday, May 9, 2017

Java 8 Date and Time API: LocalTime


Java 8 date and time API introduces a new class LocalTime under java.time package which represents a local time without a timezone. LocalTime instances are immutable (cannot be changed) so any operations performed on LocalTime will always return a new instance.

In this tutorial, you will learn:

  • How to create a LocalTime instance representing the current time
  • How to create a LocalTime instance from a given hour, minute and second
  • How to create a LocalTime instance from a given String
  • How to access the LocalTime properties (e.g. hour, minute, second)
  • How to perform plus and minus operations on LocalTime
  • How to remove time unit (e.g. seconds) from a LocalTime
Example

package com.melody.datetime;

import java.time.LocalTime;
import java.time.temporal.ChronoUnit;

public class LocalTimeDemo {

 public static void main(String[] args) {
  LocalTime currentLocalTime = LocalTime.now();
  System.out.println("Current local time: " + currentLocalTime);

  // Create a LocalTime instance from a given hour, minute and second
  LocalTime localTime = LocalTime.of(13, 30, 44);
  System.out.println("Local time from a given hour, minute & second: " + localTime);

  // Create a LocalTime instance from a given String
  LocalTime localTimeFromStr = LocalTime.parse("08:25:16");
  System.out.println("Local time from a given string: " + localTimeFromStr);

  // Access the LocalTime properties
  System.out.println("Get hour: " + localTime.getHour());
  System.out.println("Get minute: " + localTime.getMinute());
  System.out.println("Get second: " + localTime.getSecond());

  // Add and minus operations on LocalTime
  System.out.println("Add 1 hour, 1 minute & 1 second to 13:30:44 = " + localTime.plusHours(1).plusMinutes(1).plusSeconds(1));
  System.out.println("Minus 1 hour, 1 minute & 1 second to 13:30:44 = " + localTime.minusHours(1).minusMinutes(1).minusSeconds(1));

  // Adjust the LocalTime
  System.out.println("Adjust 13:30:44 into 15:45:44 = " + localTime.withHour(15).withMinute(45));

  // Remove the seconds unit from LocalTime
  System.out.println("Remove seconds from 13:30:44 = " + localTime.truncatedTo(ChronoUnit.MINUTES));
 }
}
Output

Current local time: 21:21:35.371
Local time from a given hour, minute & second: 13:30:44
Local time from a given string: 08:25:16
Get hour: 13
Get minute: 30
Get second: 44
Add 1 hour, 1 minute & 1 second to 13:30:44 = 14:31:45
Minus 1 hour, 1 minute & 1 second to 13:30:44 = 12:29:43
Adjust 13:30:44 into 15:45:44 = 15:45:44
Remove seconds from 13:30:44 = 13:30

Java 8 Date and Time API: LocalDate


Java 8 date and time API introduces a new class LocalDate under java.time package which represents a local date without a timezone. LocalDate instances are immutable (cannot be changed) so any operations performed on LocalDate will always return a new instance.

In this tutorial, you will learn:
  • How to create a LocalDate instance representing the current date
  • How to create a LocalDate instance from a given year, month and day
  • How to access the LocalDate properties (e.g. month, year, day of week, etc.)
  • How to perform plus and minus operations on LocalDate
  • How to use TemporalAdjusters to adjust LocalDate
Example

package com.melody.datetime;

import java.time.LocalDate;
import java.time.Month;
import java.time.temporal.TemporalAdjusters;

public class LocalDateDemo {

 public static void main(String[] args) {
  LocalDate currentLocalDate = LocalDate.now();
  System.out.println("Current local date: " + currentLocalDate);

  // Create a LocalDate instance from a given year, month and day
  LocalDate localDate = LocalDate.of(2017, 11, 14);
  System.out.println("Local date from a given year, month & day: " + localDate);

  // Create a LocalDate instance from a given year, MONTH (enum) and day
  localDate = LocalDate.of(2017, Month.NOVEMBER, 14);
  System.out.println("Local date from a given year, MONTH (enum) & day: " + localDate);

  // Access the LocalDate properties
  System.out.println("Get year: " + localDate.getYear());
  System.out.println("Get month (enum): " + localDate.getMonth());
  System.out.println("Get month: " + localDate.getMonthValue());
  System.out.println("Get day of month: " + localDate.getDayOfMonth());
  System.out.println("Get day of year: " + localDate.getDayOfYear());
  System.out.println("Get day of week: " + localDate.getDayOfWeek());
  System.out.println("Get length of month: " + localDate.lengthOfMonth());
  System.out.println("Get length of year: " + localDate.lengthOfYear());
  System.out.println("Is leap year: " + localDate.isLeapYear());

  // Add and minus operations on LocalDate
  System.out.println("Add 1 yr, 1 month & 1 day to 2017-11-14: " + localDate.plusYears(1).plusMonths(1).plusDays(1));
  System.out.println("Minus 1 yr, 1 month & 1 day from 2017-11-14: " + localDate.minusYears(1).minusMonths(1).minusDays(1));

  // Adjust the LocalDate
  System.out.println("Adjust 2017-11-14 into 2019-12-14: " + localDate.withYear(2019).withMonth(12));

  // Adjust the LocalDate using TemporalAdjusters
  System.out.println("Adjust 2017-11-14 into first day of the month: " + localDate.with(TemporalAdjusters.firstDayOfMonth()));
 }
}

Output

Current local date: 2017-05-09
Local date from a given year, month & day: 2017-11-14
Local date from a given year, MONTH (enum) & day: 2017-11-14
Get year: 2017
Get month (enum): NOVEMBER
Get month: 11
Get day of month: 14
Get day of year: 318
Get day of week: TUESDAY
Get length of month: 30
Get length of year: 365
Is leap year: false
Add 1 yr, 1 month & 1 day to 2017-11-14: 2018-12-15
Minus 1 yr, 1 month & 1 day from 2017-11-14: 2016-10-13
Adjust 2017-11-14 into 2019-12-14: 2019-12-14
Adjust 2017-11-14 into first day of the month: 2017-11-01


Tuesday, February 28, 2017

Java Programming: Different ways to reverse a String


When I was still looking for a job, I noticed that most job programming exams will have at least one or two questions about string manipulation in Java. Reversing a string is one of the most common questions I encountered about string manipulation. You might think, “Oh, it’s just easy! I’ll just use the Java’s built-in API for string reversion”. Unfortunately, you will be asked to reverse a string without using the built-in API, either using iteration or recursive method. I suggest that you get familiar with either of those methods if you want to show your future employer that if there’s no API available, then you can always write your own implementation.

Without further ado, here are the different ways to reverse a string in Java.


public class StringReverseDemo {

     public static void main(String[] args){
         // Original string
         String origStr = "What a wonderful day today";
         System.out.println("Original string: " + origStr);
         
         String reversedStr;
         
         // Reverse a string using StringBuilder
         reversedStr = new StringBuilder(origStr).reverse().toString();
         System.out.println("Reverse a string using StringBuilder: " + reversedStr);
         
         // Reverse a string using iteration method
         reversedStr = reverseUsingIteration(origStr);
         System.out.println("Reverse a string using iteration method: " + reversedStr);
         
         // Reverse a string using recursive method
         reversedStr = reverseStringRecursively(origStr);
         System.out.println("Reverse a string using recursive method: " + reversedStr);
     }
     
     public static String reverseUsingIteration(String str) {
         StringBuilder builder = new StringBuilder();
         char[] strChars = str.toCharArray();
         
         for (int i = strChars.length - 1; i >= 0; i--) {
             builder.append(strChars[i]);
         }
         
         return builder.toString();
     }
     
     public static String reverseStringRecursively(String str) {
         // This condition handles one character string and empty string
         if (str.length() < 2) {
             return str;
         }
         
         return reverseStringRecursively(str.substring(1)) + str.charAt(0);
     }
}

Output

Original string: What a wonderful day today                                                          
Reverse a string using StringBuilder: yadot yad lufrednow a tahW                                     
Reverse a string using iteration method: yadot yad lufrednow a tahW                                  
Reverse a string using recursive method: yadot yad lufrednow a tahW

Monday, February 20, 2017

Java Programming: Generating random numbers using Math.random()


If you’re working on a program or a game that relies on generating random numbers (e.g. throwing dice can have possible values of 1 to 6), then you can use Java’s built-in function Math.random(). This method returns a pseudorandom positive double number greater than or equal to 0.0 and less than 1.0 (inclusive of 0 but exclusive of 1).

The following example will show the different usage of Math.random().

Example
public class MathRandomDemo {

     public static void main(String[] args){
         
         // Generate random double number between 0.0 (inclusive) and 1.0 (exclusive)
         double x = Math.random();
         System.out.println("Random double number between 0.0 (inclusive) and 1.0 (exclusive): " + x);
         
         // Generate random double number between 0.0 (inclusive) and 10.0 (exclusive)
         double y = Math.random() * 10.0;
         System.out.println("Random double number between 0.0 (inclusive) and 10.0 (exclusive): " + y);
         
         // Generate random integer number between 1 (inclusive) and 6 (inclusive)
         int z = (int) (Math.random() * 6) + 1;
         System.out.println("Random integer number between 1 (inclusive) and 6 (inclusive): " + z);
     }
}

Output

Random double number between 0.0 (inclusive) and 1.0 (exclusive): 0.340407647793009
Random double number between 0.0 (inclusive) and 10.0 (exclusive): 9.048673266441012
Random integer number between 1 (inclusive) and 6 (inclusive): 3

In the example above, if you want to generate a double value greater than or equal to 0.0 but less than 10.0, then you just need to multiply the result of Math.random() with 10.0. This will return random numbers from 0.0 to 9.99. If you want to include 10.0 on the results, then you need to multiply Math.random() with 11.0 instead.

Let’s say you want to specify a minimum and maximum range to the generated random number, then all you have to do is to multiply Math.random() with the maximum value and add the minimum value to its result. In the example above, the minimum value is 1 and maximum value is 6, so we simply do (Math.random() * 6) + 1 to generate numbers from 1 to 6.

Since Math.random() returns a double value, you can cast its result to int if you want to return integer values.

Monday, January 30, 2017

MoushTech Privacy Policy


PRIVACY POLICY
(Last updated January 31, 2017)

PLEASE READ THE FOLLOWING PRIVACY POLICY CAREFULLY BEFORE USING THE APPLICATION PROVIDED BY US. BY ACCESSING OR USING OUR APPLICATION, YOU AGREE TO THE TERMS OF THIS PRIVACY POLICY. MoushTech ("we", "our", or "us") is pleased to offer you access to this mobile application (together, the "Application"). Your use of the Application is subject to the terms set forth in this Privacy Policy and any other terms we may provide you.

Collecting User Information

We do not collect any personally identifiable information from users. You are not required to register to use the Application. We do not collect precise information about the location of your mobile device. 

The Application may collect certain non-personal information automatically, including, but not limited to, the type of mobile device you use, your mobile operating system, your network service provider, the IP address of your mobile device and information about the way you use the Application. We do not collect, send or share any of these non-personal information or content created by you.

Sharing of User Information

We use Google Analytics to collect non-personal information in the form of various usage and user metrics when you use the Application. Otherwise, we does not sell, rent, share, or disclose user information to other third parties. Information about our customers may be disclosed as part of, or during negotiations of, any merger, sale of company assets or acquisition.

Use of Collected User Information

We use the collected information solely for the purpose of tracking bugs, improving the Application functionality and enhancing user experience.

Opt-out Option 

You can stop all collection of information by the Application easily by uninstalling the Application. You may use the standard uninstall processes as may be available as part of your mobile device or via the mobile application marketplace or network.

Children

While the Application may be used by children, it is not intended to be used by children, without involvement, supervision, and approval of a parent or legal guardian. MoushTech does not knowingly collect information from children under the age of 13 without parental approval. In the event you become aware that an individual under the age of 13 has used the Application without parental permission, please advise us immediately.

Security

All collected information is stored on our own restricted database servers or on Google Analytics server. We limit access to this information to authorized employees who need to know that information in order to operate, develop or improve our Application. Please be aware that, although we endeavor provide reasonable security for information we process and maintain, no security system can prevent all potential security breaches.

Privacy Policy Changes

This Privacy Policy may be updated from time to time. We will notify you of any changes to our Privacy Policy by posting the new Privacy Policy on this page. You are advised to consult this Privacy Policy regularly for any changes.

Contact Us

If you have any questions regarding privacy while using the Application, or have questions about our practices, please contact us via email at moushtech@gmail.com.