Categories
Interview java matrix

adding two matrix in java with example

In this post, we will learn about adding two matrix in java with example

In below example,We are using two dimensional array for this operations.

Here we are declaring two matrix named as a,b and one more variable sum to store the addition of a&b matrix

The first for loop is used to add two matrix and the second for loop used to print the addition value

Example
public class AddingMatrix {

	public static void main(String[] args) {
		try {

			int a[][] = { { 54, 67 }, { 45, 56 } };
			int b[][] = { { 25, 56 }, { 85, 96 } };

			// Declaring the sum matrix
			int[][] sum = new int[a.length][b.length];

			// Adding two matrix
			for (int i = 0; i < a.length; i++) {

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

			// Printing the sum matrix
			for (int i = 0; i < sum.length; i++) {
				for (int j = 0; j < sum[i].length; j++) {
					System.out.print(sum[i][j] + " ");
				}
				System.out.println();
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}
Output
79 123 
130 152 
Github

https://github.com/rkumar9090/BeginnersBug/blob/master/BegineersBug/src/com/geeks/example/AddingMatrix.java

Related Articles

create 2×2 matrix using java

Categories
java matrix

create 2×2 matrix using java

In this post, we will learn to create 2×2 matrix using java

We all know that In mathematics Matrix is a two dimensional array with rows and column as like above image. Here we are going to create that matrix using java

Java have a feature to create two dimensional array as like below

Two dimensional array Syntax
			int a[][] = { { 1, 2 }, { 2, 4 } };

The above array will convert as like below image

Example
public class CreateMatrixExample {
	public static void main(String[] args) {
		try {

			// Creating 2x2 matrix
			int a[][] = { { 1, 2 }, { 2, 4 } };

			// printing above 2d array in matrix format
			for (int i = 0; i < a.length; i++) {
				for (int j = 0; j < a[i].length; j++) {
					System.out.print(a[i][j] + " ");
				}
				System.out.println();
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
Output
1 2 
2 4 
Github

https://github.com/rkumar9090/BeginnersBug/blob/master/BegineersBug/src/com/geeks/example/CreateMatrixExample.java

Categories
file java

delete a file from java code

In this post, we will learn to delete a file from java code.

When you are delete a file from java. It will delete the file permanently. It will not moved to Trash or Recycle bin

Before executing this code, please make sure you have delete permission for that file from java.
Else you will get Permission denied Exception

Syntax
boolean isDeleted = file.delete();
Example
import java.io.File;

public class DeleteFileExample {

	public static void main(String[] args) {
		try {
			File file = new File("C:\\sample.txt");
			// Below if condition will check that file exists or not
			if (file.exists()) {
				boolean isDeleted = file.delete();
				if (isDeleted == true) {
					System.out.println("File deleted Successfully");
				} else {
					System.out.println("Not able to delete the file");
				}
			} else {
				System.err.println("File path is not correct");
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
Output
File deleted Successfully
File delete using nio pacakage

In Above example, we can customize our exceptions like file not found, file delete staus.

Below example is quick way of deleting file, But we cannot customize out exception

Syntax
	Files.deleteIfExists(Paths.get("C://temp//sample.txt"));
Example
import java.nio.file.Files;
import java.nio.file.Paths;

public class DeleteFileExample {

	public static void main(String[] args) {
		try {
			// Below line will delete if the file exist
			Files.deleteIfExists(Paths.get("C://temp//sample.txt"));
			System.out.println("File deleted successfully");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
Output
File deleted successfully
Github

https://github.com/rkumar9090/BeginnersBug/blob/master/BegineersBug/src/com/geeks/example/files/DeleteFileExample.java

Related Articles

how to list all files inside a folder using java

how to read a file from java with example

Categories
java Linux

ssh to linux box using Kerberos from Java

In this post, we will learn about ssh to linux box using Kerberos from Java

If you want to login to VM without using password from Java we can use this Kerberos for this.

Prerequisites
  • JSch.jar
  • Kerberos Configuration file
  • Jaas file
  • Remote Host information
  • Keytab file location
  • Principle Name

In the code we need to set the below system property

  • System.setProperty(“java.security.krb5.conf”, “/etc/krb5.config”);
  • System.setProperty(“java.security.auth.login.config”, “jass.config”); — Jass file

java.security.krb5.conf – you can see the krb5.config file on /etc directory
java.security.auth.login.config- jass.config will look like below

com.sun.security.jgss.krb5.accept {
        com.sun.security.auth.module.Krb5LoginModule required
        useKeyTab=true
        storeKey=true
        doNotPrompt=true
        principal="[email protected]"
		keyTab="location of keytab"
		
    };
Example

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Properties;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;

public class SSHKerberosExample {

	public static void main() {

		// Remote host that we are going to connect
		String host = "10.118.224.56";
		// Remote host user
		String user = "aws-test-user";
		// Command that we are going to execute on remote host
		String command = "mkdir /home/kerberosexample";

		JSch jsch = new JSch();
		// Kerberos config file
		System.setProperty("java.security.krb5.conf", "/etc/krb5.config");
		// Jass file location
		System.setProperty("java.security.auth.login.config", "/home/jaas.config");
		System.setProperty("javax.security.auth.useSubjectCredsOnly", "false");
		System.setProperty("sun.security.krb5.debug", "true");

		try {

			Session session = jsch.getSession(user, host, 22);
			Properties config = new java.util.Properties();
			config.put("StrictHostKeyChecking", "no");
			config.put("PreferredAuthentications", "gssapi-with-mic");

			session.setConfig(config);
			session.connect(20000);

			Channel channel = session.openChannel("exec");

			// Creating BufferReader to read input from host
			BufferedReader bufferReader = new BufferedReader(new InputStreamReader(channel.getInputStream()));

			((ChannelExec) channel).setCommand(command);
			channel.connect();

			StringBuilder stringBuilder = new StringBuilder();
			for (String string = bufferReader.readLine(); string != null; string = bufferReader.readLine()) {
				stringBuilder.append(string);
			}

			System.out.println(stringBuilder.toString());

			channel.disconnect();
			session.disconnect();
			System.out.println("created folder using kerberos authentication");

		} catch (JSchException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
Output
created folder using kerberos authentication

In case if you didn’t configured the properties correctly you will face auth exception

Github

https://github.com/rkumar9090/BeginnersBug/blob/master/BegineersBug/src/com/geeks/example/SSHKerberosExample.java

Categories
java

Base64 Encoding using Java

In Below example we will learn how to use Base64 Encoding using Java

Finally Java8 incorporated Base64 Encoding. Base64 is one of the common Encoding mechanism.

Syntax
Base64.getEncoder().encodeToString(textForEncoding.getBytes());
Example

import java.util.Base64;

public class Base64Encodng {

	public static void main(String[] args) {
		try {
			String textForEncoding = "QWERTY TEXT";
			String encodedString = Base64.getEncoder().encodeToString(textForEncoding.getBytes());
			System.out.println(encodedString);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
Output
UVdFUlRZIFRFWFQ=

The length of output encoded String must be a multiple of 3. else the output will be padded with additional pad characters (`=`).
But we have option to encode without padding also

Syntax
Base64.getEncoder().withoutPadding().encodeToString(textForEncoding.getBytes());
Example without Padding

import java.util.Base64;

public class Base64Encodng {

	public static void main(String[] args) {
		try {
			String textForEncoding = "QWERTY TEXT";
			String encodedString = Base64.getEncoder().withoutPadding().encodeToString(textForEncoding.getBytes());
			System.out.println(encodedString);		

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
Output
UVdFUlRZIFRFWFQ
Decoding Syntax
Base64.getDecoder().decode(encodedString.getBytes());
Example

import java.util.Base64;

public class Base64Encodng {

	public static void main(String[] args) {
		try {
			String textForEncoding = "QWERTY TEXT";
			String encodedString = Base64.getEncoder().withoutPadding().encodeToString(textForEncoding.getBytes());
			System.out.println(encodedString);
			
			byte[] decodeByte = Base64.getDecoder().decode(encodedString.getBytes());
			String decodedValue=new String(decodeByte);
			System.out.println(decodedValue);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
Output
UVdFUlRZIFRFWFQ
QWERTY TEXT
Github

https://github.com/rkumar9090/BeginnersBug/blob/master/BegineersBug/src/com/geeks/example/Base64Encodng.java

Categories
file java

how to list all files inside a folder using java

In this post, we will how to list all files inside a folder using java. Here we will use File.java for these operations

In below example we are going to use .list method to list all files and directories without trans versing into sub directories.

The file path I am going to use is F:\Java which having file like below image 

Example
import java.io.File;

public class ListAllFilesExample {

	public static void main(String[] args) {
		try {

			File file = new File("F:\\Java");
			String[] list = file.list();
			for (String fileName : list) {
				System.out.println(fileName);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}

Output

access.txt
apache-tomcat-8.5.35
eclipse
Maven
sample.txt
sts-bundle
Transverse into sub folders using Java 8

Using java8 we can easily transverse into all sub folders in side the folder. In below Example we are using Files.walk to get all the files and folders by trans versing inside the folders

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Stream;

public class ListAllFilesUsingJava8 {

	public static void main(String[] args) {
		try {
			Path path = Paths.get("F:/Java");
			Stream<Path> walk = Files.walk(path);
			walk.forEach(x -> System.out.println(x.getFileName()));

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}
Output
org.eclipse.datatools.enablement.hsqldb.ui_1.2.1.201712071719.jar
org.eclipse.datatools.enablement.hsqldb_1.2.1.201712071719.jar
org.eclipse.datatools.enablement.ibm.db2.iseries.dbdefinition_1.2.1.201712071719.jar
Github

https://github.com/rkumar9090/BeginnersBug/blob/master/BegineersBug/src/com/geeks/example/files/ListAllFilesExample.java

https://github.com/rkumar9090/BeginnersBug/blob/master/BegineersBug/src/com/geeks/example/files/ListAllFilesUsingJava8.java

Related Articles

how to read a file from java with example

create text file from java with example

Categories
file java

how to read a file from java with example

In this post, we will learn about how to read a file from java with example

This will called as IO operations

There are many ways to read a file from java. BufferedReader, Scanner, Streams

BufferReader

BufferReader is one of the common way to read a file from java. It will read the file line by line

It is synchronized, so the operations will be thread safe

Once the read operation is done we need to close the BufferReader

we are getting chance of IOException in this code, so we should surround the code by try catch

Example

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;

public class ReadFileExample {

	public static void main(String[] args) {
		try {
			
			File file = new File("C://temp/sample.txt");
			FileInputStream fileInputStream = new FileInputStream(file);
			InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
			
			// Converting input stream to buffer reader
			BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
			String temp = "";
			StringBuffer textFileContent = new StringBuffer();
			while ((temp = bufferedReader.readLine()) != null) {
				textFileContent.append(temp);
			}
			
			System.out.println(textFileContent);
			// In below line we are closing the bufferReader
			bufferedReader.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}
Output
sdfdsfdsfsdfsHelloworld
Scanner

In this example we will do the same operation using Scanner. Here are also we used while loop to iterate the content of file as like bufferedReader

Once we done with the operation we nee to close the scanner as like BufferReader

Scanner Example

import java.io.File;
import java.util.Scanner;

public class ReadFileScannerExample {

	public static void main(String[] args) {
		try {
			File file = new File("C:\\temp\\sample.txt");
			
			Scanner scanner = new Scanner(file);
			StringBuffer textFileContent = new StringBuffer();
			while (scanner.hasNextLine()) {
				textFileContent.append(scanner.nextLine());
			}
			System.out.println(textFileContent);
			scanner.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
Output
sdfdsfdsfsdfsHelloworld
Using NIO pacakge

Using NIO package we have Files.ReadAllBytes method. Using this we can read file as byte array. Then we can convert this into a string as like below example

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;

public class Sample {

	public static void main(String[] args) throws IOException {
		byte[] encoded = Files.readAllBytes(Paths.get("D:\\workspace\\sample.txt"));
		String s = new String(encoded, StandardCharsets.US_ASCII);
		System.out.println(s);
	}
}
java.io.FileNotFoundException

If java not able to find the file it will throw the below exception

java.io.FileNotFoundException: C:\temp\sample.txt1 (The system cannot find the file specified)
	at java.io.FileInputStream.open0(Native Method)
	at java.io.FileInputStream.open(FileInputStream.java:195)
	at java.io.FileInputStream.<init>(FileInputStream.java:138)
	at java.util.Scanner.<init>(Scanner.java:611)
	at com.geeks.example.ReadFileScannerExample.main(ReadFileScannerExample.java:12)
Github

https://github.com/rkumar9090/BeginnersBug/blob/master/BegineersBug/src/com/geeks/example/files/ReadFileExample.java

https://github.com/rkumar9090/BeginnersBug/blob/master/BegineersBug/src/com/geeks/example/files/ReadFileScannerExample.java

Related Articles

create text file from java with example

Categories
file java

create text file from java with example

In this post, we are going to learn create text file from java with example

In this example, we are going to use File.java to create file

please make sure your code is under try catch block. Because there is chance to getting IOException

Prerequisites
  • Java installed
  • your program should have access to create file on the path
Syntax
	file.createNewFile();
Example
import java.io.File;

public class CreateFileExample {

	public static void main(String[] args) {
		try {
			File file = new File("C://temp//sample.txt");
			// .exists Method check if file already exists on the path
			if (!file.exists()) {
				// Below line will create file sample.txt on C://temp// folder
				file.createNewFile();
				System.out.println("File created succesfully !!");
			} else {

				System.err.println("File already exists");
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
Output
File created succesfully !!

if file already exists in the C://temp folder we will get below output

File already exists
Access denied

Make sure you have access from java to create file on the folder else you will get access denied exception like below

java.io.IOException: Access is denied
	at java.io.WinNTFileSystem.createFileExclusively(Native Method)
	at java.io.File.createNewFile(File.java:1012)
	at com.geeks.example.CreateFileEaxmple.main(CreateFileEaxmple.java:11)
Github

https://github.com/rkumar9090/BeginnersBug/blob/master/BegineersBug/src/com/geeks/example/files/CreateFileExample.java

Related Articles

how to read a file from java with example

Categories
date java

calculate number days between two dates using java

In this tutorial, we will learn about calculate number days between two dates using java

There are lot of ways to calculate number of days between two dates in java

Using Java 8

In below example, we are going to use ChronoUnit to calculate days between two days

Syntax
ChronoUnit.DAYS.between(startDate, endDate);
Example

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

public class CalculateDaysBetweenDatesJava8 {

	public static void main(String[] args) {
		try {
			// Start date is 2020-03-01 (YYYY-MM-dd)
			LocalDate startDate = LocalDate.of(2020, Month.MARCH, 1);

			// end date is 2020-03--03 (YYYY-MM-dd)
			LocalDate endDate = LocalDate.of(2020, Month.MARCH, 3);

			long numberOfDays = ChronoUnit.DAYS.between(startDate, endDate);

			System.out.println("Number of days " + numberOfDays);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
Output
Number of days 2

Above example is easiest way to calculate days between two dates

Int the below example we are going to use traditional way to calculate days between two days

Below Java 8

In below example we are going to use GregorianCalendar to calculate number of days between two dates

Example

import java.util.Calendar;
import java.util.GregorianCalendar;

public class CalculateDaysUsingCalender {

	public static void main(String[] args) {
		try {
			Calendar startDate = new GregorianCalendar();
			Calendar endDate = new GregorianCalendar();

			// Start date is 2020-03-01 (YYYY-MM-dd)
			startDate.set(2020, 03, 1);

			// end date is 2020-03--03 (YYYY-MM-dd)
			endDate.set(2020, 03, 3);

			// subtract emdTime-StartTime and divide by (1000 * 60 * 60 * 24)
			int i = (int) ((endDate.getTime().getTime() - startDate.getTime().getTime()) / (1000 * 60 * 60 * 24));
			System.out.println("Number of days " + i);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
Output
Number of days 2
Github

https://github.com/rkumar9090/BeginnersBug/blob/master/BegineersBug/src/com/geeks/example/CalculateDaysUsingCalender.java

https://github.com/rkumar9090/BeginnersBug/blob/master/BegineersBug/src/com/geeks/example/CalculateDaysBetweenDatesJava8.java

Related Articles

convert String to date in java with example

compare two dates in java example

Categories
java String

How to compare two strings in java

In this post, We will learn How to compare two strings in java

It might sounds easy. But we need to take care of few things while comparing two Strings

Avoid ==

If you are newbie to java, This might surprise you

while you use == to compare string it will not check the value of two strings

Instead of that it will check the reference of two Strings

"BeginnersBug" == new String("BeginnersBug") 
// Above check will return false 

In the above snippet even though both the String are equal it will return false because both are not same object

.equals() method

.equlas method will compare two strings with the value irrespective of its object

Even though if it is two different object it will compare the value of two string

"BeginnersBug".equals(new String("BeginnersBug")) 
// Above check will return true

In the above code snippet it will compare two string value and it will return true for the condition

. equalsIgnoreCase() method

equalsIgnoreCase() method will ignore the case while checking the value of two Strings

If you want to check two Strings irrespective of case sensitive you can use this method

"beginnersbug".equalsIgnoreCase(new String("BeginnersBug")) 
// Above method will return true

In the above code snippet equalsIgnoreCase method will ignore the case sensitive. So it is returning true for the statement

Example

public class CompareStringExample {
	public static void main(String[] args) {
		try {
			// Example 1 == Below check will failS
			if ("BeginnersBug" == new String("BeginnersBug")) {
				System.out.println("Example 1 : Both the strings are equal");
			} else {
				System.out.println("Example 1 : Both the strings are not equal");
			}

			// Example 2 .equals()
			if ("BeginnersBug".equals(new String("BeginnersBug"))) {
				System.out.println("Example 2 : Both the strings are equal");
			} else {
				System.out.println("Example 2 : Both the strings are not equal");
			}

			// Example 3 .equalsIgnoreCase()
			if ("beginnersbug".equalsIgnoreCase(new String("BeginnersBug"))) {
				System.out.println("Example 3 : Both the strings are equal");
			} else {
				System.out.println("Example 3 : Both the strings are not equal");
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
Output
Example 1 : Both the strings are not equal
Example 2 : Both the strings are equal
Example 3 : Both the strings are equal
Reference

https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#equalsIgnoreCase(java.lang.String)

Related Articles

Convert String to lowercase using java

Print a String in java with example