Pages

Showing posts with label Java Programs. Show all posts
Showing posts with label Java Programs. Show all posts

Thursday, September 5, 2024

Java Program To Reverse A String Without Using String Inbuilt Function reverse()

1. Introduction


In this tutorial, You'll learn how to write a java program to reverse a string without using string inbuilt function reverse().
This is a very common interview question that can be asked in many forms as below.

A) java program to reverse a string without using string inbuilt function
B) java program to reverse a string using recursion
C) java program to reverse a string without using the reverse method
C) Try using other classes of Java API (Except String).



The interviewer's main intention is not to use the String class reverse() method.

Friday, January 7, 2022

Java Program To Find First Non-Repeated Character In String (5 ways)

1. Overview


In this article, We will be learning and understanding the various ways to find the first non repeated character in a given string in various ways along with Java 8 Streams. Many programs may face this type of question in programming interviews or face to face round.
Let us start with the simple approach and next discover the partial and single iteration through the string.

Java Program To Find First Non-Repeated Character In String (5 ways)


Thursday, January 6, 2022

Latest 20+ JMS Interview Questions and Answers

1. Introduction


In this tutorial, We'll learn about JMS interview questions that are frequently asked in 2020. As part of the interview, There are chances to ask some of the questions on JMS area if you have 6 years plus. But, even less experience, it is good to have in the profile on JMS experience. The interviewer will check as messaging is a key aspect of enterprise Java development.
JMS is a popular open-source Messaging API and many vendors such as Apache Active MQ, Websphere MQ, Sonic MQ provides an implementation of Java messaging API or JMS.


Usually, Any interview starts with a basic. If all questions are answered properly then we will go onto the JMS experience project-based questions.

Basics mean What is Topic? What is the Queue? What is Publisher? What is Subscriber? What are a Publisher and Subscriber model? How to configure MQ?
Next level means Questions on a project where you have implemented JMS concepts?

Tuesday, December 28, 2021

Java Program to Check Leap Year (With Examples)

1. Overview

In this tutorial, you'll learn how to check the given year is a leap year or not.

Everyone knows that leap year comes for every 4 years and February month with 29 days.

But, when we do the logic in java it is bit different and should know the complete formula to evaluate leap year.


Java Program to Check Whether an Alphabet is Vowel or Consonant

1. Overview

In this tutorial, you'll learn how to check the given alphabet is a vowel or consonant in java.

We are going to solve this question using if else and switch statements.

To understand the programs in this article, you should have knowledge on the following topics.





Wednesday, December 22, 2021

Java Program to Calculate Standard Deviation

1. Overview

In this tutorial, you'll learn how to calculate the standard deviation in java using for loop and its formula.


2. Example to calculate standard deviation

Let us write a simple java program to find the standard deviation for an individual series of numbers.

First create a method with name calculateStandardDeviation(). Create an array with integer values and. pass this array to the calculateStandardDeviation() method. This method has the core logic to get the standard deviation and. returns to main method.

package com.javaprogramto.programs.arrays.calculation;

public class StandardDeviation {

	public static void main(String[] args) {

		int[] array = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

		double standardDeviation = calculateStandardDeviation(array);

		System.out.format("Standard deviation : %.6f", standardDeviation);

	}

	private static double calculateStandardDeviation(int[] array) {

		// finding the sum of array values
		double sum = 0.0;

		for (int i = 0; i < array.length; i++) {
			sum += array[i];
		}

		// getting the mean of array.
		double mean = sum / array.length;

		// calculating the standard deviation
		double standardDeviation = 0.0;
		for (int i = 0; i < array.length; i++) {
			standardDeviation += Math.pow(array[i] - mean, 2);

		}

		return Math.sqrt(standardDeviation/array.length);
	}

}
 

Output:

Standard deviation : 2.581989
 

3.  Conclusion

In this article, you've seen how to find the standard deviation in java.

As usual, the shown example is over GitHub.


Java Program to Find the Biggest of 3 Numbers

1. Overview


In this w3schools java programming series, You'll be learning today how to find the biggest of 3 numbers. This is also a very basic interview question. But the interviewer will look for the optimized and fewer lines code. We will show you all the possible programs and how most of java developers think.

For example, given three numbers 4 67 8. Among these three 67 is bigger. For this, we need to perform a comparison with all numbers.

How to add 3 numbers in java?

Thursday, December 16, 2021

How To Check If int is null in Java

1. Overview

In this tutorial, We'll learn how to check if primitive int is null or not in java.

First, let us write the simple example program and see what is the output if we check int is not null using != operator.

How To Check If int is null in Java


Monday, December 6, 2021

Increasing or Extending an Array Length in 3 ways

1. Overview

In this tutorial, We'll see how many ways an array can be extended in java.

The actual array values are stored in contiguous memory locations. The answer may not be promptly obvious.

if you are new to the Java Array, It is worthful to read the beginner articles.


Increasing or Extending an Array Length in 3 ways

Saturday, December 4, 2021

Java Program to Bitonic Sort

1. Overview


In this article, We'll learn about how to implement Bitonic sort in java.

Bitonic Sort is a classic parallel sorting algorithm. This is called as Bitonic Mergesort. It is also used as a construction method for building a sorting network.

Basically, it is a procedure of Biotonic sequence using bitonic splits.

How to write optimized bubble sort in java?

In java many sorting techniques can be implemented. But we have to choose the better one. This is very rarely used in real applications.


Java Program to Bitonic Sort



The bitonic sequence is said that when there is an index i exists such that either monotonically increasing and monotonically decreasing from index i and vice versa.


Eg. 7, 4, 2, 1, 9, 8, 7, 6, 5


Wednesday, November 24, 2021

Java Convert String To int - Parse Examples

1. Overview

In this tutorial, We'll learn how to convert string to int in java

Let us explore the different ways to convert a string to an integer value using various methods from java built-in API.

This is very common in software life. We need to represent the string that contains numbers into the integer type.

Example:

Input String = "12345";
Output int = 12345;

In Java, we can convert String to int using Integer.parseInt(), Integer.valueOf(), Integer constructor and DecimalFormat.parse(string).intValue() methods and these methods returns integer object.

Java Examples - Convert String To int


2. String to Int: Using Integer.parseInt()


parseInt(String string) method is static method and it is present in Integer class.This method converts the given string into integer number. If the given string contains at least non digit then it will throw the runtime error NumberFormatException.

public class ParseIntExample 
{
    public static void main(String[] args) 
    {
		// Creating a string
        String s = "12345";
		
		// converting string to int using parseInt() method
        int i = Integer.parseInt(s);
		
		// printing the input and output
        System.out.println("string : "+s);
        System.out.println("integer : "+i);
    }
}

Output:

string : 12345
integer : 12345

3. String to Int: Using Integer.valueOf()


Next, use valueOf(String s) method to convert String object to an int value. But this method also works as similar to the parseInt() method.

But the main difference between parseInt() and valueOf() method is parseInt() method returns primitive int and valueOf() method returns wrapper Integer object.

public class ValueOfExample
{
    // Example to string to int
    public static void main(String[] args) 
    {
		// Creating String object with value "1000"
        String s2 = "1000";
		
		// Calling valueOf() method which does string to int conversion
        Integer i2 = Integer.valueOf(s2);
		
		// printing values
        System.out.println("string value: "+s2);
        System.out.println("integer value: "+i2);
    }
}

Output:

string value: 1000
integer value: 1000

4. String to Int: Using Integer Constructor with String Argument


Next, Look at another approach which does use constructor of Integer class with string type as an argument as new Integer("2468");

public class IntegerConstructorExample
{
	// string to int with integer constructor
    public static void main(String[] args) 
    {
		// creating string object 3
        String s3 = "999";
		
		// convert string to integer with Interger constructor
        Integer i3 = new Integer(s3);
		
         // convert Wrapper integer to primitive int using primitive int
        int int3 = i3.intValue();
		
		// printing the values
        System.out.println("String s3 value : " + int3);
        System.out.println("Integer int3 value : " + int3);
    }
}

Output:

String s3 value : 999
Integer int3 value : 999

5. String to Int: Using DecimalFormat class


The final approach is, Use DecimalFormat.parse() method with string as an argument. Pass value "0" to DecimalFormat class constructor so that it treats only the numbers as input.

Next, call parse() and pass the string value to be converted into an int value. parse() method returns Number object and needs to get the int value from intValue() method from Number class.

Example:

import java.text.DecimalFormat;
import java.text.ParseException;

public class DecimalFormatExample 
{
    // DecimalFormat.parse() example to parse string into int value.
    public static void main(String[] args) throws ParseException 
    {
		// Creating a string object with value 123456
        String string = "123456";

        // Passing "0" to the DecimalFormat indicates that it shuould accepts only digits.
        DecimalFormat decimalFormat = new DecimalFormat("0");

        // parsing String to Number
        Number number = decimalFormat.parse(string);
     
        // converting Number to primitive int.
        int i4 = number.intValue();

		// printing values
       System.out.println("string value : " + string);		
       System.out.println("i4 value : " + i4);
    }
}

Output:

string value : 123456
i4 value : 123456

6. String To Int Exception Java


If the input string literal is having the non numeric characters and call Integer class parseInt() or valueOf() or constructor or DecimalFormat class methods will end up in runtime exception "NumberFormatException".

package com.javaprogramto.convert.string.toint;

/**
 * Example to exception in string to integer conversion
 * 
 * @author Javaprogramto.com
 *
 */
public class StringToIntException {

	public static void main(String[] args) {

		// creating string with alphabets
		String s = "hello world";

		// convert string to int using parseInt() method. This will throw exception
		// int number = Integer.parseInt(s);
		// int number = Integer.valueOf(s);
		Integer number = new Integer(s);

		// printing vlaues
		System.out.println("Number : " + number);
	}
}

Output:

Exception in thread "main" java.lang.NumberFormatException: For input string: "hello world"
	at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:68)
	at java.base/java.lang.Integer.parseInt(Integer.java:658)
	at java.base/java.lang.Integer.<init>(Integer.java:1117)
	at com.javaprogramto.convert.string.toint.StringToIntException.main(StringToIntException.java:19)


7. Conclusion


In this article, We've seen how to convert string to integer in different ways in java with example programs.


Monday, November 22, 2021

Java Event Handler - Events and Listeners Examples

1. Overview

In this tutorial, We'll learn how to work with event handlers in java.

How to add events to the actions of users and work with the listeners in java.

When you are working on GUI based projects using AWT or Applets then you might have seen the scenarios where you need to change the state of an object from one form to another.

For example, add action when a button is pressed or when the text is entered then enable another text box.

Java Event Handler - Events and Listeners Examples

Sunday, November 21, 2021

Java - How To Find Transpose Of A Matrix in Java in 4 ways?

1. Overview

In this article, we'll learn how to find the transpose of a matrix in java using for loops.

Look at the below inputs and outputs for the matrix transpose.

Input:

1 2 3
4 5 6
7 8 9

Output:

1 4 7
2 5 8
3 6 9

This is just an interchange of the columns with rows or rows with columns.

Java - How To Find Transpose Of A Matrix in Java in 4 ways?


Saturday, November 20, 2021

Java Scanner.close() - How to Close Scanner in Java?

1. Overview

In this article, We'll learn how to close the scanner in java and what are the best practices to do it.

Java Scanner.close() - How to Close Scanner in Java?


2. Java Scanner.close() 


look at the below syntax.

Syntax:
public void close()

close() method does not take any arguments and returns nothing. It just closes the current scanner instance.


If this scanner has not yet been closed then if its underlying readable also implements the Closeable interface then the readable's close method will be invoked.

Invoking this method will have no effect if the scanner is already closed.

An IllegalStateException will be thrown if you attempt to execute search activities after a scanner has been closed.

3. How to close scanner in java?


Once you perform the operations on Scanner instance then at the end you need to close the scanner properly. Otherwise, scanner will be opened and it is available to pass any info to the application and may cause the data leaks.

It is always recommended to close the resources in the recommended way.

Example 1:

In the below example, we are reading two values from the user and then closing the scanner after completing the actions on it.
package com.javaprogramto.programs.scanner.close;

import java.util.Scanner;

public class ScannerCloseExample1 {

	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);

		System.out.println("Enter your birth year");
		int year = scanner.nextInt();

		System.out.println("Enter your age ");
		int age = scanner.nextInt();

		scanner.close();

		System.out.println("Given age and year are (" + age + "," + year + ")");
	}
}
Output:
Enter your birth year
1990
Enter your age 
31
Given age and year are (31,1990)

4. Read values after Scanner close() invocation


After closing the Scanner with the close() method, then next invoke next() method.
What is your expected output?

Example 2:
package com.javaprogramto.programs.scanner.close;

import java.util.Scanner;

public class ScannerCloseExample2 {

	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);

		System.out.println("Enter your birth year");
		int year = scanner.nextInt();

		System.out.println("Enter your age ");
		int age = scanner.nextInt();

		scanner.close();

		System.out.println("Given age and year are (" + age + "," + year + ")");
		
		System.out.println("Enter your name ");
		String name = scanner.next();
	}
}

Output:
Enter your birth year
2000
Enter your age 
21
Given age and year are (21,2000)
Enter your name 
Exception in thread "main" java.lang.IllegalStateException: Scanner closed
	at java.base/java.util.Scanner.ensureOpen(Scanner.java:1150)
	at java.base/java.util.Scanner.next(Scanner.java:1465)
	at com.javaprogramto.programs.scanner.close.ScannerCloseExample2.main(ScannerCloseExample2.java:21)

Execution is failed at runtime because it is saying IllegalStateException with the reason scanner is closed already. 

Here, we tried to read the name string from the user after closing the connection with scanner.

5. Closing Scanner From Finally Block


It is a better approach to close the finally always from the finally block. If there is an exception then it must be closed before the error.

If you read the data from the file or string with multi-line separators, you must have to close the scanner.

Example 3:

Closing scanner from finally block.
package com.javaprogramto.programs.scanner.close;

import java.util.Scanner;

public class ScannerCloseExample2 {

	public static void main(String[] args) {

		String multiLinesSeparator = "Line 1 \n Line 2 \n Line 3";
		Scanner scanner = new Scanner(multiLinesSeparator);

		try {

			String firstLine = scanner.nextLine();
			String secondLine = scanner.nextLine();
			String thirdLine = scanner.nextLine();

			System.out.println(
					"Info from string via scanner are (" + firstLine + ", " + secondLine + ", " + thirdLine + ")");

			thirdLine.charAt(100);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			scanner.close();
            System.out.println("scanner is closed");
		}

	}
}

Output:
Info from string via scanner are (Line 1 ,  Line 2 ,  Line 3)
java.lang.StringIndexOutOfBoundsException: String index out of range: 100
	at java.base/java.lang.StringLatin1.charAt(StringLatin1.java:48)
	at java.base/java.lang.String.charAt(String.java:711)
	at com.javaprogramto.programs.scanner.close.ScannerCloseExample2.main(ScannerCloseExample2.java:21)
scanner is closed
Scanner is closed even though an exception is thrown.


6. Conclusion


In this article, we've seen how to close scanner in java using Scanner.close() method.
Scanner can be used to read the input from the user, string or file. For all sources, we need to close the scanner always.




Thursday, November 18, 2021

Java Exit Program - How to end program in java?

1. Overview

In this tutorial, We'll learn how many ways to end java program and how to terminate program execution in java.

Stopping the java program can be done in two ways as below.

A) Using System.exit() method
B) Using return statement
How to end program in java?

Saturday, November 13, 2021

Java FizzBuzz - FizzBuzz Solution In Java 8 with examples

1. Overview

In this tutorial, We'll learn how to write a java program to fizzbuzz solution in java language.

This is a fun game mostly played in elementary schools with your friends in schools.

FizzBuzz game rules:

This is a multiplayer game. When your turn comes then you have to say one number. If the number is multiple of 5 then you have to say "Fizz" in the french ascent. If the number is multiple of 7 then say "Buzz". If the number is multiple of 5 and 7 then say "FizzBuzz". If you can not say the right word for your number then you are out of the game. So must have to say the correct fizz buzzword to continue the game otherwise game will be continued without you. Whoever is alone in the game that person is the winner.

Let us implement the Fizz Buzz game in java language with the simple if-else conditions.

2. Java FizzBuzz Solution Using If else

The below logic is implemented using simple while loop and if-else conditions.


package com.javaprogramto.programs.fizzbuzz;

/**
 * Java program to implement fizz buzz solution
 * @author javaprogramto.com
 *
 */
public class FizzBuzzExample {

	public static void main(String[] args) {
		
		// limit the fizz buzz game
		int limit = 100;
		
		// staring number
		int currentNumber = 1;
		
		// running the while loop till it reaches the max limit
		while (currentNumber <= limit) {
			
			// checking for fizzbuzz
			if (currentNumber % 5 == 0 && currentNumber % 7 == 0) {
				System.out.println("FizzBuzz");

				// checking for fizz
			} else if (currentNumber % 5 == 0) {
				System.out.println("Fizz");
				
				// checking for buzz
			} else if (currentNumber % 7 == 0 ) {
				System.out.println("Buzz");
			}  else {
				System.out.println(currentNumber);
			}
			
			// incrementing the number by 1
			currentNumber++;
		}
	}
}
 

Output:

1
2
3
4
Fizz
6
Buzz
8
9
Fizz
11
12
13
Buzz
Fizz
16
17
18
19
Fizz
Buzz
22
23
24
Fizz
26
27
Buzz
29
Fizz
31
32
33
34
FizzBuzz
36
37
38
39
Fizz
41
Buzz
43
44
Fizz
46
47
48
Buzz
Fizz
51
52
53
54
Fizz
Buzz
57
58
59
Fizz
61
62
Buzz
64
Fizz
66
67
68
69
FizzBuzz
71
72
73
74
Fizz
76
Buzz
78
79
Fizz
81
82
83
Buzz
Fizz
86
87
88
89
Fizz
Buzz
92
93
94
Fizz
96
97
Buzz
99
Fizz

 

3. FizzBuzz Solution in Java 8

We can implement the solution for FizzBuzz using java 8 stream API as below.

In the below example, we have used the ternary operator for condition evaluation.

IntStream.range() is to generate the numbers from 1 to 100

mapToObj(): uses the ternary operator and gets the right word.

forEach(): To iterate over the stream and print the values to console.

public class FizzBuzzExampleJava8 {

	public static void main(String[] args) {

		// limit the fizz buzz game
		int limit = 100;

		// staring number
		int currentNumber = 1;

		// IntStream to generate the numbers range from 1 to 100 and mapToObj() to get the right fizz buzz word.
		IntStream.rangeClosed(currentNumber, limit)
				.mapToObj(i -> i % 5 == 0 ? (i % 7 == 0 ? "FizzBuzz" : "Fizz") : (i % 7 == 0 ? "Buzz" : i))
				.forEach(System.out::println);
	}
}
 

This program also produces the same output as in the above section.

4. Conclusion

In this article, we have seen how to implement the solution to the FizzBuzz problem using java before and after java 8 concepts.

GitHub

Ref

IntStream

java 8 forEach

Java Math pow() method Example (Recursive and Loop Iterative)

1. Overview

In this post, You will learn how to calculate the power of a number using the Math pow() method in java

In other words, in Some interviews, these questions are asked as writing a program to find/calculate the power of a number in a java programming language. In this tutorial, you'll learn to calculate the power of a number using a recursive function in Java.


The java.lang.Math. pow() is used to calculate a number raise to the power of some other number. This function takes two parameters and both are double type. This method returns the value of first parameter raised to the second parameter. Also pow() is a static method.
Java Math pow method Example (Recursive and Loop Iterative)



2. Java Math Pow Syntax

public static double pow(double a, double b)


Parameter:

a : this parameter is the base
b : this parameter is the exponent.

Returns :

This method returns a.

Thursday, November 11, 2021

Java Program - How to Print an Array in Java?

1. Introduction


In this tutorial, we'll learn different techniques on how to print the elements of a given array in Java.
                              Java Program - How to Print an Array in Java?

2. Example To Print Array of Numbers using for loop


In the below example for-each loop is used to iterate the array of integer numbers.

for each is also called as enhanced for loop.

[package com.javaprogramto.arrays.print;

public class PrintArray {
public static void main(String[] args) {

int[] array = { 1, 2, 3, 4, 5, 6, 7 };

for (int value : array) {
System.out.println(value);
}

}
}]

Monday, November 8, 2021

Java - Joining Multiple Strings With a Delimiter

1. Overview

In this tutorial, We'll learn how to join the multiple strings with a delimiter in java programming.

Joining strings can be done in several ways with the given separator.

Before java 8, this is solved with the StringBuilder class. But, the same can be solved in 3 ways in java 8 or later.

Let us jump into the example programs on each solution.
Java - Joining Multiple Strings With a Delimiter



2. Java Joining Strings With Delimiter - StringBuilder


StringBuilder is a class that built on the Builder pattern and this is not synchronized.

By using this class, we run the for loop and add the each string and delimiter using append() method.

Look into the below example. Here we are using var-args concept.
package com.javaprogramto.programs.strings.joining;

public class JoiningStringDelimiterExample1 {

	public static void main(String[] args) {

		// input 1
		String output1 = joinStringsWithDelimiter("-", "hello", "world", "welcome", "to", "java", "programs");
		System.out.println("Ouptut 1 : " + output1);

		// input 1
		String output2 = joinStringsWithDelimiter("**", "this", "is", "second", "input");
		System.out.println("Ouptut 2 : " + output2);

	}

	/**
	 * Gets the joined string for the input strings with a given delimiter
	 * 
	 * @param delimiter
	 * @param strings
	 * @return
	 */
	private static String joinStringsWithDelimiter(String delimiter, String... strings) {

		StringBuilder stringBuilder = new StringBuilder();
		int index = 0;
		for (index = 0; index < strings.length - 1; index++) {

			stringBuilder.append(strings[index]).append(delimiter);
		}

		stringBuilder.append(strings[index]);

		return stringBuilder.toString();
	}

}

Output:
Ouptut 1 : hello-world-welcome-to-java-programs
Ouptut 2 : this**is**second**input

Any no of strings and any delimiter can be passed to this program. And also, StringBuffer can be used in-place of StringBuilder but StringBuffer is slow because of thread safe.

3. Java 8 Joining Strings With Delimiter - StringJoiner


One of the ways in java 8 is using StringJoiner class and this is a string utility class.

StringJoiner class can be used to construct the set of strings with the delimiter.

Look at the below example program.
package com.javaprogramto.programs.strings.joining;

import java.util.StringJoiner;

public class JoiningStringDelimiterExample2 {

	public static void main(String[] args) {

		// input 1
		String output1 = stringJoinerWithDelimiter("-", "hello", "world", "welcome", "to", "java", "programs");
		System.out.println("Ouptut 1 : " + output1);

		// input 1
		String output2 = stringJoinerWithDelimiter("**", "this", "is", "second", "input");
		System.out.println("Ouptut 2 : " + output2);

	}

	private static String stringJoinerWithDelimiter(String delimiter, String... strings) {

		StringJoiner stringJoinder = new StringJoiner(delimiter);
		for (String str : strings) {

			stringJoinder.add(str);
		}

		return stringJoinder.toString();
	}

}

This program produces the same output as above section example.

And alos this supports for adding the suffix and prefix. But these are optional functionality.
StringJoiner stringJoinder = new StringJoiner(delimiter, "!!", "!!");
Output:
Ouptut 1 : !!hello-world-welcome-to-java-programs!!
Ouptut 2 : !!this**is**second**input!!

4. Java 8 Joining Strings With Delimiter - String.join()


String class is added with join() method in java 8. This function reduces the lots of boiler plate coding in the applications now.

String.join() method takes the delimiter and a set of strings.

And alos optionally prefix and suffix also can be passed to join() method.
package com.javaprogramto.programs.strings.joining;

public class JoiningStringDelimiterExample3 {

	public static void main(String[] args) {

		// input 1
		String output1 = stringJoinWithDelimiter("-", "hello", "world", "welcome", "to", "java", "programs");
		System.out.println("Ouptut 1 : " + output1);

		// input 1
		String output2 = stringJoinWithDelimiter("**", "this", "is", "second", "input");
		System.out.println("Ouptut 2 : " + output2);

	}

	private static String stringJoinWithDelimiter(String delimiter, String... strings) {

		return String.join(delimiter, strings);
	}
}

This example also generates the same output.

5. Java 8 Joining Strings With Delimiter - Collectors.joining()


Java 8 stream api is added with very useful method Collectors.joining() method.

Collectors.joining() method should be passed to the collect() method. So that String can be retrieved from joining() output.

Look at the below sample code.
import java.util.Arrays;
import java.util.stream.Collectors;

public class JoiningStringDelimiterExample4 {

	public static void main(String[] args) {

		// input 1
		String output1 = stringCollectorsJoiningWithDelimiter("-", "hello", "world", "welcome", "to", "java",
				"programs");
		System.out.println("Ouptut 1 : " + output1);

		// input 1
		String output2 = stringCollectorsJoiningWithDelimiter("**", "this", "is", "second", "input");
		System.out.println("Ouptut 2 : " + output2);

	}

	private static String stringCollectorsJoiningWithDelimiter(String delimiter, String... strings) {

		String output = Arrays.stream(strings).collect(Collectors.joining(delimiter));

		return output;
	}
}
The generated output is same for this example also.

6. Java 8 Joining Strings With Delimiter - Third Party Libraries


Third party api's also provide the support for this functionality from apache commons lang StringUtils.join() and guava Joiner class.
import org.apache.commons.lang3.StringUtils;

public class JoiningStringDelimiterExample5 {

	public static void main(String[] args) {
	// same code as abvoe example
	}

	private static String stringCollectorsJoiningWithDelimiter(String delimiter, String... strings) {

		String output = StringUtils.join(strings, delimiter);

		return output;
	}
}

7. Conclusion


In this article, We've seen how many ways string joining is possible in older java, java 8 and third party apis.

But the String joining strictly discouraged using "+=" operator as below.
String out = "";

for (int i = 0; i < 100000; i++) {
	out += "new value";
}

Because, this code reconstructs many strings with "+=" operation which over kills the memory and prone to performance issues. Finally, this code execution will be much slower than StringBuilder.

Saturday, November 6, 2021

Java Format Double - Double With 2 Decimal Points Examples

1. Overview

In this tutorial, We'll learn how to convert the String into double and display double with 2 decimal points or 2 decimal places in java programming.

In the previous article, we have already discussed about how to convert String to Double value in 3 ways.

Getting the double with 2 decimal points can be done in many ways. we'll learn all the possible ways with example programs.
Java Format Double - Double With 2 Decimal Points Examples



2. Double With 2 Decimal Points Using DecimalFormat Class


First, convert the string into double using Double.parseDouble() method.
Next, create the instance of DecimalFormat class as new DecimalFormat("0.00") and then call the format() method which returns the double value in string with 2 decimal places.

Below is the example program.
package com.javaprogramto.programs.strings.todouble.decimal;

import java.text.DecimalFormat;

public class StringToDoubleDecimalsPlaces1 {

	public static void main(String[] args) {
		
		String decimalValueInString = "9.144678376262";
		
		// convert string to double
		
		double doubleDecimalValue = Double.parseDouble(decimalValueInString);
		
		System.out.println("Double in string : "+decimalValueInString);
		System.out.println("Double value : "+doubleDecimalValue);
		
		// decimalformat class
		DecimalFormat decimalFormat = new DecimalFormat("0.00");
		
		System.out.println("Double with decimal places "+decimalFormat.format(doubleDecimalValue));
	}
}
Output:
Double in string : 9.144678376262
Double value : 9.144678376262
Double with decimal places 9.14

And also this DecimalFormat class provides the additional functionality to rounding up and down the decimal values using setRoundingMode() method as follows.
decimalFormat.setRoundingMode(RoundingMode.UP);
System.out.println("Double with decimal places with rounding up :  "+decimalFormat.format(doubleDecimalValue));

decimalFormat.setRoundingMode(RoundingMode.DOWN);
System.out.println("Double with decimal places with rounding down :  "+decimalFormat.format(doubleDecimalValue));		
Output:
Double with decimal places with rounding up :  9.15
Double with decimal places with rounding down :  9.14	

3. Double With 2 Decimal Points Using String.format()


Next approach is using String.format() method which is simple and does not provide rounding up options as DecimalFormat or BigDecimal classes.

let us write the example program on format() method.
public class StringToDoubleDecimalsPlaces2 {

	public static void main(String[] args) {
		
		String decimalValueInString = "9.144678376262";
		
		// convert string to double
		
		double doubleDecimalValue = Double.parseDouble(decimalValueInString);
		
		System.out.println("Double in string : "+decimalValueInString);
		System.out.println("Double value : "+doubleDecimalValue);
		
		String strDoubleDecimals = String.format("%.2f", doubleDecimalValue);
		
		System.out.println("Double with 2 decimal values : "+strDoubleDecimals);
		
	}
}

Output:
Double in string : 9.144678376262
Double value : 9.144678376262
Double with 2 decimal values : 9.14

4. Double With 2 Decimal Points Using BigDecimal class


Last way is using BigDecimal class. You need to pass the double number to the BigDecimal constructor and then call setScale() method with a number which is how many decimal points are needed and with the rounding mode.

And also setScale() method can take rounding mode also.

Look at the below example to get the more details about the BigDecimal for decimal places.
package com.javaprogramto.programs.strings.todouble.decimal;

import java.math.BigDecimal;

public class StringToDoubleDecimalsPlaces3 {

	public static void main(String[] args) {
		
		String decimalValueInString = "9.144678376262";
		
		// convert string to double
		
		double doubleDecimalValue = Double.parseDouble(decimalValueInString);
		
		System.out.println("Double in string : "+decimalValueInString);
		System.out.println("Double value : "+doubleDecimalValue);
		
		// BigDecimal
		BigDecimal bigDecimal = new BigDecimal(doubleDecimalValue);
		bigDecimal.setScale(2);
		System.out.println(""+bigDecimal.doubleValue());
		
	}
}

Output:
Double in string : 9.144678376262
Double value : 9.144678376262
Exception in thread "main" java.lang.ArithmeticException: Rounding necessary
	at java.base/java.math.BigDecimal.commonNeedIncrement(BigDecimal.java:4628)
	at java.base/java.math.BigDecimal.needIncrement(BigDecimal.java:4835)
	at java.base/java.math.BigDecimal.divideAndRound(BigDecimal.java:4810)
	at java.base/java.math.BigDecimal.setScale(BigDecimal.java:2910)
	at java.base/java.math.BigDecimal.setScale(BigDecimal.java:2952)
	at com.javaprogramto.programs.strings.todouble.decimal.StringToDoubleDecimalsPlaces3.main(StringToDoubleDecimalsPlaces3.java:20)

Program execution is failed because of Rounding mode was not provided to the big decimal object. So, Rounding mode is mandatory to work with the setScale() method.

Added now RoundingMode.DOWN value to the setScale() method.
package com.javaprogramto.programs.strings.todouble.decimal;

import java.math.BigDecimal;
import java.math.RoundingMode;

public class StringToDoubleDecimalsPlaces3 {

	public static void main(String[] args) {
		
		String decimalValueInString = "9.144678376262";
		
		// convert string to double
		
		double doubleDecimalValue = Double.parseDouble(decimalValueInString);
		
		System.out.println("Double in string : "+decimalValueInString);
		System.out.println("Double value : "+doubleDecimalValue);
		
		// BigDecimal
		BigDecimal bigDecimal = new BigDecimal(doubleDecimalValue).setScale(2, RoundingMode.DOWN);
		//bigDecimal.setScale(0, RoundingMode.HALF_UP);
		System.out.println("Two decimals : "+bigDecimal.doubleValue());
		
	}
}
Output:
Double in string : 9.144678376262
Double value : 9.144678376262
Two decimals : 9.14

5. Double With 2 Decimal Points Using Formatter, NumberFormat, printf()


There are many other ways alos. Few of them are shown in the below example.

package com.javaprogramto.programs.strings.todouble.decimal;

import java.text.NumberFormat;
import java.util.Formatter;

public class StringToDoubleDecimalsPlaces4 {

	public static void main(String[] args) {

		double doubleDecimalValue = 9.144678376262;

		System.out.println("Double value : " + doubleDecimalValue);

		// 1. NumberFormat
		NumberFormat nf = NumberFormat.getInstance();
		nf.setMaximumFractionDigits(2);

		System.out.println("Number format : " + nf.format(doubleDecimalValue));

		// 2. Formatter
		Formatter formatter = new Formatter();
		formatter.format("%.2f", doubleDecimalValue);

		System.out.println("Formatter : " + formatter.toString());

		// 3. Printf
		System.out.printf("printf : Double upto 2 decimal places: %.2f", doubleDecimalValue);

	}
}
Output:
Double value : 9.144678376262
Number format : 9.14
Formatter : 9.14
printf : Double upto 2 decimal places: 9.14

6. Conclusion


In this article, we've seen how to display and format the double value to double 2 decimal places using many methods. 

And also we can use the apache commons math api method Precision.round(2, doubleValue).