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.




Java - How to mix two strings and generate another?

1. Overview

In this tutorial, We'll learn how to mix and concatenate the two or more strings in java.

Strings are used to store the sequence of characters in the order in the memory and they are considered as objects.

Strings are located in java.lang package

If you are new to Strings, please go through the below string methods.



String creation can be done in two ways using new keyword and literals as below.
String s1 = new String("JavaProgramTo.com");
String s2 = "welcome, Java developer";
In the next sections, you will see examples of adding strings using different techniques.

Java - How to mix two strings and generate another?

HttpClient 4 – Get the Status Code Example

1. Introduction


In this very quick tutorial, I will show how to get and validate the StatusCode of the HTTP Response using HttpClient 4.

2. Maven Dependencies


The following jars are required to run this HttiClient application.

commons-logging is internally is being used by other jars. Please do not forget to add these jars else you will get compile-time and runtime errors.

<dependency>
    <groupId>commons-logging</groupId>
    <artifactId>commons-logging</artifactId>
    <version>1.2</version>
</dependency>

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.12</version>
</dependency>

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpcore</artifactId>
    <version>4.4.13</version>
</dependency>

Java Print HashMap - Displaying Values

1. Overview

In this article, we'll learn how to print the values of HashMap in different ways in java and jdk 8. 
Java Print HashMap - Displaying Values

Friday, November 19, 2021

Java Set Add - Set.add() Adding values

1. Overview

In this tutorial, We'll learn how to add values to set in java. Set implementations are HashSet and LinkedHashSet and TreeSet.

In the next sections, how add() method is used from set class.
Java Set Add - Set.add() Adding values


Uninstall Java on mac os with commands [Fixed]

1. Overview

In this tutorial, we'll learn how to uninstall java version from mac os.

To remove java from mac machine, you can use simple commands.

A) How to remove all versions of java installed on mac
B) How to remove java 11 from mac os.

The second option will work for any java version of mac. It can be either java 7, 8, 10, 11, 1, 13, 0r 14.

Note: you need the administration privileges to mac machine.

Uninstall Java from mac os with commands [Fixed]