Saturday, October 31, 2020

Optimized Java Program to Find the Largest Among Three Numbers

1. Overview

In this tutorial, you'll learn how to find the biggest number from any given three numbers in java.

This is a very basic program for freshers but still we optimize the code using minimal if conditions.

Let us explore the different ways to find the largest value in 3 numbers and finally the best optimized way to achieve this.

To understand clearly this example, if you have knowledge on the below topics, that is added advantage in understanding easily.


Read the article till end, shown the best way in the last section.

Example:

Input: 10 20 30
Output: 30

Input: 56 100 30
Output: 100

Input: 100 -1 200
Output: 200

Optimized Java Program to Find the Largest Among Three Numbers

Friday, October 30, 2020

Java Program To Find First Non-Repeated Character In String

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, October 29, 2020

Java Program to Multiply Two Floating Point Numbers

1. Overview

In this article, you'll learn how to get the multiplication of two floating numbers in java

To understand this, you need to have the knowledge on the following areas.

Simple Hello World Example

Variables in java

This is as same as the multiplication of two numbers with * operator.

In the previous article shown how to multiply two integer numbers.

Java Program to Multiply Two Floating Point Numbers

Java Program to Find ASCII Value of a Character Or String

1. Introduction


In this article, you will learn how to convert a value or character to ASCII its value.

This can be done by using type casting and variable assignment.

Let us see how to convert String or Char into ASCII values.

This is part of Java Programming Series.

Java Program to Find Quotient and Remainder

1. Overview

In this tutorial, you'll learn how to find the quotient and remainder when one number is divided by another one.

This is a simple and easy but many students does not get digested easily.

let us understand clearly with the examples.

Hello World example in java

Understand public static void main(String[] args) method


Java Program to Find Quotient and Remainder



Tuesday, October 27, 2020

Java Program to Find Transpose of a Matrix

1. Overview

In this article, you'll learn how to find the transpose of a given matrix using a simple for loop.

You can go thorough the previous articles on addition and multiplication of two matrices using arrays.

Transpose is nothing but a swapping the rows with columns and also order will be swapped. Finally, it produces the new matrix.

Matrix M :    [A11, A12 

	      A21, A22

	      A31, A32]


Transpose of Matrix M: [ A11, A21, A31

			 A12, A22, A32]
 

Order of Transpose Matrix:

Matrix M order: 3 X 2 

Transpose of Matrix M order: 2 X 3

Java Program to Find Transpose of a Matrix

Monday, October 26, 2020

Java Program to Multiply two Matrices by Passing Matrix to a Function

1. Overview

In this tutorial, you'll learn how to write the function for matrix multiplication. Let us pass the input and result matrices to this method and will run the core logic to multiply. Finally, the output is stored in the result array.

In the previous article, shown how to multiply two matrices without using function.

Example:

Matrix 1 order: 2 X 3 

Matrix 2 order: 3 X 2

Result matrix order: 2 X 2

key note in the matrix multiplication is always matrix 1 columns size and matrix two row size must be equal. Otherwise matrix multiplication is not possible.

Java Program to Multiply two Matrices by Passing Matrix to a Function

Sunday, October 25, 2020

Java Program to Multiply two Matrix Using Multi-dimensional Arrays

1. Overview

In this tutorial, you'll learn how to multiply two matrix in java using multi dimensional arrays.

To understand this example program, it is better to know the following concepts.

Arrays - How to Initialize Arrays

For Loops Examples

Java Program to Multiply two Matrix Using Multi-dimensional Arrays


One condition must be satisfied for matrix multiplication as below.

First matrix order: R1 X C1

Second matrix order: R2 X C2

Always C1 and R2 must be same number that means number of columns in matrix 1 should be equal to the number of rows in the second matrix.

If this condition is not satisfied then matrix multiplication is not possible.

And also output matrix order will be R1 X C2.

Friday, October 23, 2020

Java Program to Add Two Matrix Using Multi-dimensional Arrays

1. Overview

In this tutorial, You'll learn how to add two matrix in java using arrays. You should know the basic mathematic problem solving which you learnt in the schooling level for Matrix Addition.

This can be implemented using two for loops easily in java programming.

In the previous article, we have shown how to multiply two matrices in java using threads.

Java Program to Add Two Matrix Using Multi-dimensional Arrays


2. Example Program To Add Two Matrices

Let us write a simple java program that takes two arrays as input and executes the core logic for addition. Finally, output array is printed onto the console.

Key note here is the order of two matrices should be same otherwise can not be computed the output.

package com.javaprogramto.programs.arrays.matrix;

public class MatrixAddition {

	public static void main(String[] args) {
		// creating the first matric using arrays
		int[][] matrix1 = { { 1, 2, 3 }, { 4, 5, 6 } };

		// creating the second matrix using two dimension array
		int[][] matrix2 = { { 1, 2, 3 }, { 4, 5, 6 } };

		// output array for storing the addition result
		int[][] output = new int[matrix1.length][matrix2[1].length];

		// matrix addition core logic
		for (int i = 0; i < matrix1.length; i++) {
			for (int j = 0; j < matrix2[1].length; j++) {
				output[i][j] = matrix1[i][j] + matrix2[i][j];
			}
		}

		// printing the result
		for (int i = 0; i < output.length; i++) {
			for (int j = 0; j < output[1].length; j++) {
				System.out.print(output[i][j]+ " ");
			}
			System.out.println();
		}

	}

}

 

Output:

2 4 6 
8 10 12 

 

Here, First created two 2 dimensions arrays for storing the matrix1 and matrix2.  Next, need to find the rows and columns using matrix1 and matrix 2. 

We initialized the new array with the rows and columns size. This is used to store the result of addition.

Core logic is loop through the two matrices and add the values at the same index from both arrays.

At last, printed the output array using simple for loop.


3. Conclusion

In this article, you've seen how to find the addition of two matrices in java using arrays.

As usual, example shown is over GitHub.

Ref How to initialize the array in java

Java Program to Find Largest Element of an Array(+Java 8 Approach)

1. Overview

In this article, you'll learn how to find the largest value from an array. You should know the basic understanding of java Arrays, for-each loopand java 8 lambdas.

Finding the biggest value can be done in different ways.

Let us explore 3 different ways using for each loop, sort() method,  java 8 streams.

Note: Array is not sorted. if is sorted in ascending already then take the value from the array the last index-1 which gives the biggest value. If sorted descending, take zero index value.

Java Program to Find Largest Element of an Array(+Java 8 Approach)

Wednesday, October 14, 2020

Java Program to Calculate Average Using Arrays

1. Overview

In this article, you'll learn how to calculate the average of numbers using arrays

You should know the basic concepts of a java programming language such as Arrays and forEach loops.

We'll see the two programs on this. The first one is to iterate the arrays using for each loop and find the average.

In the second approach, you will read array values from the user.

Let us jump into the example programs.

Java Program to Calculate Average Using Arrays


2. Example 1 to calculate the average using arrays

First, create an array with values and run. the for loop to find the sum of all the elements of the array.

Finally, divide the sum with the length of the array to get the average of numbers.

package com.javaprogramto.programs.arrays.average;

public class ArrayAverage {

	public static void main(String[] args) {

		// create an array
		int[] array = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };

		// getting array length
		int length = array.length;

		// default sium value.
		int sum = 0;

		// sum of all values in array using for loop
		for (int i = 0; i < array.length; i++) {
			sum += array[i];
		}

		double average = sum / length;
		
		System.out.println("Average of array : "+average);

	}

}

Output:

Average of array : 6.0

3. Example 2 to find the average from user inputted numbers

Next, let us read the input array numbers from the user using the Scanner class.

Scanner Example to add two numbers

import java.util.Scanner;

public class ArrayAverageUserInput {

	public static void main(String[] args) {

		// reading the array size.
		Scanner s = new Scanner(System.in);

		System.out.println("Enter array size: ");
		int size = s.nextInt();
		// create an array
		int[] array = new int[size];

		// reading values from user keyboard
		System.out.println("Enter array values :  ");
		for (int i = 0; i < size; i++) {
			int value = s.nextInt();
			array[i] = value;

		}

		// getting array length
		int length = array.length;

		// default sium value.
		int sum = 0;

		// sum of all values in array using for loop
		for (int i = 0; i < array.length; i++) {
			sum += array[i];
		}

		double average = sum / length;

		System.out.println("Average of array : " + average);

	}

}

Output:

Enter array size: 
5
Enter array values :  
12
23
34
45
56
Average of array : 34.0

4. Conclusion

In this article, you've seen how to calculate the average number in an array.

All examples shown are in GitHub.

Average

Monday, October 12, 2020

Java Program to Check if An Array Contains a Given Value or Not (+Java 8)

1. Overview

In this article, you'll learn how to check an array contains the given value in it or not.

It is not mandatory to have complete knowledge of the arrays but you should know the following.

how to create and initialize an array in java.

How to declare the variables in java?

Java Program to Check if An Array Contains a Given Value or Not (+Java 8)


2. Example 1 To check the given number in the array using the native approach

This is a simple approach to search the given value in an array and this is called a linear search algorithm.

package com.javaprogramto.programs.arrays.search;

public class FIndValue {

	public static void main(String[] args) {

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

		int findValueOf = 6;

		boolean isFound = false;
		for (int i = 0; i < array.length; i++) {

			if (array[i] == findValueOf) {
				isFound = true;
				break;
			}

		}

		if (isFound) {
			System.out.println("Number " + findValueOf + " is found in the  array");
		} else {
			System.out.println("Number " + findValueOf + " is not found in the  array");
		}
	}

}

Output:

Number 6 is found in the  array

In the above example for loop is used to iterate over the array values and compare each value with the findValueOf variable value.

3. Example 2 To find the number using Java 8 Streams for primitive values

Next, let us use the Java 8 Stream API to check the given value in an array or not.

Now, we are checking with primitives values so you should use the IntStream.

First, convert an array to int stream using IntStream.of() method and call anyMatch() method to check value.

import java.util.stream.IntStream;

public class IntStreamFindValue {

	public static void main(String[] args) {

		int[] array = { 10, 30, 20, 90, 40, 60 };

		int findValueOf = 90;

		boolean isFound = false;

		isFound = IntStream.of(array).anyMatch(condition -> condition == findValueOf);

		if (isFound) {
			System.out.println("Number " + findValueOf + " is found in the array in java 8");
		} else {
			System.out.println("Number " + findValueOf + " is not found in the  array in java 8");
		}
	}

}

Output:

Number 90 is found in the array in java 8

If a number is found in the array then anyMatch() returns true else false.

4. Example 3 To find the number using Java 8 Streams for non-primitive values

In the above section, you've seen for primitive arrays but how can you find in the string array.

Interestingly, the same anyMatch() method works for any type of array.

import java.util.Arrays;

public class IntStreamFindStringValue {

	public static void main(String[] args) {

		String[] stringArray = new String[] { "hello", "how", "life", "is", "going" };

		String findString = "java";

		boolean isFound = false;

		isFound = Arrays.stream(stringArray).anyMatch(value  -> value.equals(findString));

		if (isFound) {
			System.out.println("String " + findString + " is found in the array in java 8");
		} else {
			System.out.println("String " + findString + " is not found in the  array in java 8");
		}
	}

}

Output:

String java is not found in the  array in java 8

5. Conclusion

In this article, you've seen the different ways to check if an array contains a given value or not and also examples using java 8 api.

As usual, all examples are over GitHub.

Arrays

Stream.anyMatch()

How To Initialize An Array In Java In Different Ways

1. Overview

In this article, You'll learn how to initialize the array in java. Array creation can be done in different ways.

Typically, Arrays are a collection of the value of that of the same type. You can not store the different types of values inside the array.

This is the underlying structure that is widely used in the Collection API and problem solving interview questions.

All the values stored inside the array are called as elements and each element is stored at a unique index. Array index starts from ZERO.

How To Initialize An Array In Java In Different Ways


But, Collection api is preferred over arrays if you are doing insertions in middle or resizing the array.

2. How To Declare An Array?

Declaring array is pretty straight forward. Look at the below syntax.

DataType[] arrayName ;

All the below three segments are mandatory in the array declaration.

Data Type: Data type defines the type of objects or values are stored inside array such as int, boolean, char, float, etc.
[] : Square brackets indicates as an array.
arrayName: Variable name is to access the array values from memory.
package com.javaprogramto.arrays.initialize;

public class ArrayDeclaration {

    public static void main(String[] args) {
        
        // int array declaration
        int[] intArray;

        // boolean array declaration
        boolean[] statusArray;

        // float array declaration
        float[] salaryArray;
    }
}

3. Initializing An Array


In the above section, you understood how to declare an array. Now, let us understand some basic rules about the array initialization.

Declaring an array means that does not array is initialized. To store the values inside an array, You must have to initialize the array first.

Below is the syntax to initialize the array.
DataType[] arrayname = new DataType[size];
new keyword and size must be specified to create an array.

Array initialization can be done in different ways. Let us explore all the possible ways to create and store the values in an array.

4. Initializing An Array Without Assigning Values


Java allows initializing the values at all indexes at the time of its creation.

In the below example program, We are creating an array with its default values
package com.javaprogramto.arrays.initialize;

public class ArrayInitializationDefaultValues {

    public static void main(String[] args) {

        // int array initialization
        int[] intArray = new int[9];

        System.out.println("Printing array values : ");
        for(int i = 0; i < intArray.length ; i++){
            System.out.println(intArray[i]);
        }

    }
}
Output:
Printing array values : 
0
0
0
0
0
0
0
0
0

Created and initialized an array with size 9 and did not assign any values in the program. When we run the for loop on intArray then it printed 0 for all indexes.

Note: Array length can be accessed through a special variable name called "length". This length is available on all array variables.

5. Initializing An Array After Declaration


If you observe in the above program, the Array is declared and initialized in a single line. But there is a way to declare the array first and next initialize an array with values.
package com.javaprogramto.arrays.initialize;

public class ArrayInitializationAfterDeclaration {

    public static void main(String[] args) {

        // Example 1
        // int array declaration
        int[] intArray;

        // Array initialization
        intArray = new int[]{10, 20, 30, 40, 50};

        System.out.println("Printing array values : ");
        for (int i = 0; i < intArray.length; i++) {
            System.out.println(intArray[i]);
        }

        // Example 2

        // Boolean array declaration
        boolean[] booleanArray ;

        // boolean array initialization
        booleanArray = new boolean[]{true, false, true};

        System.out.println("Printing boolean array : ");
        for(int index = 0;index < booleanArray.length; index++){
            System.out.println(booleanArray[index]);
        }
    }
}

Output:
Printing array values : 
10
20
30
40
50
Printing boolean array : 
true
false
true

In this example, Created two arrays, intArray stores int values, booleanArray stores boolean values.
These two arrays are first declared and in the next line initialized with its values.

Note: When an array is initialized with values in the next line than that array creation must use a "new" keyword. Otherwise, You will get the compile-time error saying "Array initialization is not allowed here"

6. Initializing An Array And Assigning Values Without Using new Keyword


Still, there is a way to initialize the array without using the new keyword. But, this is allowed only at the time of array declaration. If you try to do the same in the next line will give the compile-time error.

Let us see the examples.

int[] intArray = {2, 4, 6, 8, 20};

boolean[] booleanArray = {true, false, true};

double[] salaryArray = {15000, 35000, 50000};

Here, a new keyword is not used and size is calculated based on the values added to the array at declaration.

Full example program
package com.javaprogramto.arrays.initialize;

public class ArrayInitializationWithoutNewKeyword {

    public static void main(String[] args) {

        // Example 1
        // int array declaration and intialization without new keyword
        int[] intArray = {2, 4, 6, 8, 20};

        System.out.println("Printing array values : ");
        for (int i = 0; i < intArray.length; i++) {
            System.out.println(intArray[i]);
        }

        // Example 2

        // Boolean array declaration and intialization without new keyword
        boolean[] booleanArray = {true, false, true};

        System.out.println("Printing boolean array : ");
        for (int index = 0; index < booleanArray.length; index++) {
            System.out.println(booleanArray[index]);
        }

        // Example 3

        // Double array declaration and intialization without new keyword
        double[] salaryArray = {15000, 35000, 50000};

        System.out.println("Printing salary double array : ");
        for (int index = 0; index < salaryArray.length; index++) {
            System.out.println(salaryArray[index]);
        }
    }
}

7. Initializing the Wrapper Arrays and Employee Array


As of now, you've seen how to create and initialize an array for primitive types. But, the same can be applied to the Wrapper classes, String, and also for user-defined classes.

Observe the below examples and all are valid.
package com.javaprogramto.arrays.initialize;

import com.javaprogramto.models.Employee;

public class ArrayInitializationForNonPrimitives {

    public static void main(String[] args) {

        // Array initialization without the "new" keyword
        String[] stringArray = {"hello", "welcome"};

        // String Array initialization with "new" keyword
        String[] newStringArray = new String[]{"hello", "welcome"};

        Employee e1 = new Employee(100, "Jhon", 30);
        Employee e2 = new Employee(101, "Amal", 25);
        Employee e3 = new Employee(102, "Paul", 35);

        // Employee Array initialization without "new" keyword
        Employee[] empArrayWithoutNewKeyword = {e1, e2, e3};

// Employee Array initialization without "new" keyword Employee[] empArrayWithNewKeyword = new Employee[]{e1, e2, e3}; } }

8. Create and Initialize An Array With Size Zero(0)


Many developers who started learning java will get the common question is it possible to create an array with size 0?

The answer is yes it is possible and array has zero values in it and here are the few examples.
 		// Array initialization without the "new" keyword with size 0
        String[] stringArray = {};

        // String Array initialization with "new" keyword with size 0
        String[] newStringArray = new String[0];

        // Employee Array initialization without "new" keyword with size 0
        Employee[] empArrayWithoutNewKeyword = {};

        // Employee Array initialization with "new" keyword with size 0
        Employee[] empArrayWithNewKeyword = new Employee[0];
        

9. Conclusion


In this article, You've seen how to create and initialize an array in java in different ways.

Array related interesting articles others reading


All examples are shown are over GitHub.


Friday, October 9, 2020

Java Program To Remove Duplicates From Array (Without Using Set)

1. Overview

In this article, you'll learn how to remove the duplicate values from array in different ways using java programming.

Let us learn how to work with the sorted and unsorted array for this scenario.

In the previous article, we've explained the different ways to remove duplicates from List in Java 8?

Java Program To Remove Duplicates From Array (Without Using Set)


Wednesday, October 7, 2020

Java Program To Get Intersection Of Two Arrays

1. Overview

In this tutorial, you'll learn how to get the intersection of two arrays in java.  An Intersection Set is a common values among all collections. 

In our case, you need to get the values that are common in both arrays.

For example, Look at the below two arrays.

Array 1: { 1, 2, 3, 4, 5}

Array 2: {2,  4,  6,  8}

In these two arrays, 2 and 4 are the common values so these 2,4 set is an intersection of Array 1 and Array 2.

Java Program To Get Intersection Of Two Arrays


We are going to write the java program using HashSet and retainAll() method.

retainAll() Example to get unique and duplicate values from the list

We've seen in the previous article, how to get a union of two arrays of integers or string values.

Monday, October 5, 2020

Java Program To Get Union Of Two Arrays

1. Overview

In this article, you'll learn how to get the union of two arrays in java.  A union set is all the values of two sets or from all collection.

We can do the union function in java using HashSet with arrays. Use the addAll() method to add all the values of each array into HashSet.

This is a simple solution. As well as this solution will work with both numbers and string values.

Java Program To Get Union Of Two Arrays


2. Union of two Integer arrays with numbers

Let us write the java program to print the union of two integer arrays.

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

public class UnionTwoArraysNumbers {

	public static void main(String[] args) {

		// Integer array 1
		Integer[] array1 = { 1, 2, 3, 4, 5, 6, 7, 8 };
		System.out.println("Array 1 : " + Arrays.toString(array1));

		// Integer array 2
		Integer[] array2 = { 2, 4, 6, 8, 10, 12, 14 };
		System.out.println("Array 2 : " + Arrays.toString(array2));

		// creating a new Set
		Set<Integer> unionOfArrays = new HashSet<>();

		// adding the first array to set
		unionOfArrays.addAll(Arrays.asList(array1));

		// adding the second array to set
		unionOfArrays.addAll(Arrays.asList(array2));

		// converting set to array.
		Integer[] unionArray = {};
		unionArray = unionOfArrays.toArray(unionArray);

		// printing the union of two arrays.
		System.out.println("Union of two arrays: " + Arrays.toString(unionArray));

	}

}

Output:

Array 1 : [1, 2, 3, 4, 5, 6, 7, 8]
Array 2 : [2, 4, 6, 8, 10, 12, 14]
Union of two arrays: [1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14]

3. Union of two String arrays

Let us write the java program to print the union of two String arrays.


public class UnionTwoArraysStrings {

	public static void main(String[] args) {

		// Integer array 1
		String[] array1 = { "A", "B", "C", "D" };
		System.out.println("String Array 1 : " + Arrays.toString(array1));

		// Integer array 2
		String[] array2 = { "C", "D", "E", "F" };
		System.out.println("String  Array 2 : " + Arrays.toString(array2));

		// creating a new Set
		Set<String> unionOfArrays = new HashSet<>();

		// adding the first array to set
		unionOfArrays.addAll(Arrays.asList(array1));

		// adding the second array to set
		unionOfArrays.addAll(Arrays.asList(array2));

		// converting set to array.
		String[] unionArray = {};
		unionArray = unionOfArrays.toArray(unionArray);

		// printing the union of two arrays.
		System.out.println("Union of two String arrays: " + Arrays.toString(unionArray));

	}

}

Output:

String Array 1 : [A, B, C, D]
String  Array 2 : [C, D, E, F]
Union of two String arrays: [A, B, C, D, E, F]

4. Conclusion

In this article, we've seen how to find the union of two arrays in java using HashSet.

As usual, all examples. are over Github.

How to compare two strings?

How to add integers to ArrayList?

HashSet

String API Methods

Integer API

Saturday, October 3, 2020

Java String to String Array Conversion Examples

1. Overview

In this article, you'll learn how to convert String to String Array in java with example programs.

Let us learn the different ways to do the conversion into a string array. from a string value.

Java String to String Array Conversion Examples