ads

Saturday, February 13, 2016

Java program to bubble sort

Java program to bubble sort: This code sorts numbers inputted by user using Bubble sort algorithm.

Java programming code

import java.util.Scanner;
 
class BubbleSort {
public static void main(String []args) {
int n, c, d, swap;
Scanner in = new Scanner(System.in);
 
System.out.println("Input number of integers to sort");
n = in.nextInt();
 
int array[] = new int[n];
 
System.out.println("Enter " + n + " integers");
 
for (c = 0; c < n; c++)
array[c] = in.nextInt();
 
for (c = 0; c < ( n - 1 ); c++) {
for (d = 0; d < n - c - 1; d++) {
if (array[d] > array[d+1]) /* For descending order use < */
{
swap = array[d];
array[d] = array[d+1];
array[d+1] = swap;
}
}
}
 
System.out.println("Sorted list of numbers");
 
for (c = 0; c < n; c++)
System.out.println(array[c]);
}
}
Complexity of bubble sort is O(n2) which makes it a less frequent option for arranging in sorted order when quantity of numbers is high.
Download Bubble sort Java program.
Output of program:
Bubble sort Java program output
You can also use sort method of Arrays class to sort integers in ascending order but remember that sort method uses a variation of Quick sort algorithm.
import java.util.Arrays;
 
class Sort
{
public static void main(String args[])
{
int data[] = { 4, -5, 2, 6, 1 };
 
Arrays.sort(data);
 
for (int c: data)
{
System.out.println(c);
}
}
}

Java program to open Notepad

How to open Notepad through java program: Notepad is a text editor which comes with Windows operating system, It is used for creating and editing text files. You may be developing java programs in it but you can also open it using your java code.

How to open notepad using Java program

import java.util.*;
import java.io.*;
 
class Notepad {
public static void main(String[] args) {
Runtime rs = Runtime.getRuntime();
 
try {
rs.exec("notepad");
}
catch (IOException e) {
System.out.println(e);
}
}
}
Download Notepad program.
Explanation of code: getRunTime method is used to get reference of current RunTime object, exec method can be used to execute commands. You can also specify a file while opening notepad such as exec("notepad programming.txt") where 'programming.txt' is the file you wish to open, if the file doesn't exist in current working directory then a dialog box will be displayed to create file. You can launch other applications using exec method, for example exec("calc") will launch calculator application. If an application is present in a directory which is not set in environment variable PATH then you can specify complete path of application. If you are still using Notepad for Java development it is recommended to switch to some advanced text editor like Notepad++or use a development IDE.

Java program to transpose matrix

This java program find transpose of a matrix of any order.

Java programming source code

import java.util.Scanner;
 
class TransposeAMatrix
{
public static void main(String args[])
{
int m, n, c, d;
 
Scanner in = new Scanner(System.in);
System.out.println("Enter the number of rows and columns of matrix");
m = in.nextInt();
n = in.nextInt();
 
int matrix[][] = new int[m][n];
 
System.out.println("Enter the elements of matrix");
 
for ( c = 0 ; c < m ; c++ )
for ( d = 0 ; d < n ; d++ )
matrix[c][d] = in.nextInt();
 
int transpose[][] = new int[n][m];
 
for ( c = 0 ; c < m ; c++ )
{
for ( d = 0 ; d < n ; d++ )
transpose[d][c] = matrix[c][d];
}
 
System.out.println("Transpose of entered matrix:-");
 
for ( c = 0 ; c < n ; c++ )
{
for ( d = 0 ; d < m ; d++ )
System.out.print(transpose[c][d]+"\t");
 
System.out.print("\n");
}
}
}
Download Transpose matrix program class file.
Output of program:
transpose matrix
This code can be used to check if a matrix symmetric or not, just compare the matrix with it's transpose if they are same then it's symmetric otherwise non symmetric, also it's useful for calculating orthogonality of a matrix.

Java program to multiply two matrices

This java program multiply two matrices. Before multiplication matrices are checked whether they can be multiplied or not.

Java programming code

import java.util.Scanner;
 
class MatrixMultiplication
{
public static void main(String args[])
{
int m, n, p, q, sum = 0, c, d, k;
 
Scanner in = new Scanner(System.in);
System.out.println("Enter the number of rows and columns of first matrix");
m = in.nextInt();
n = in.nextInt();
 
int first[][] = new int[m][n];
 
System.out.println("Enter the elements of first matrix");
 
for ( c = 0 ; c < m ; c++ )
for ( d = 0 ; d < n ; d++ )
first[c][d] = in.nextInt();
 
System.out.println("Enter the number of rows and columns of second matrix");
p = in.nextInt();
q = in.nextInt();
 
if ( n != p )
System.out.println("Matrices with entered orders can't be multiplied with each other.");
else
{
int second[][] = new int[p][q];
int multiply[][] = new int[m][q];
 
System.out.println("Enter the elements of second matrix");
 
for ( c = 0 ; c < p ; c++ )
for ( d = 0 ; d < q ; d++ )
second[c][d] = in.nextInt();
 
for ( c = 0 ; c < m ; c++ )
{
for ( d = 0 ; d < q ; d++ )
{
for ( k = 0 ; k < p ; k++ )
{
sum = sum + first[c][k]*second[k][d];
}
 
multiply[c][d] = sum;
sum = 0;
}
}
 
System.out.println("Product of entered matrices:-");
 
for ( c = 0 ; c < m ; c++ )
{
for ( d = 0 ; d < q ; d++ )
System.out.print(multiply[c][d]+"\t");
 
System.out.print("\n");
}
}
}
}
Download Matrix multiplication program class file.
Output of program:
matrix multiply
This is a basic method of multiplication, there are more efficient algorithms available. Also this approach is not recommended for sparse matrices which contains a large number of elements as zero.

Java program to reverse number

This program prints reverse of a number i.e. if the input is 951 then output will be 159.

Java programming source code

import java.util.Scanner;
 
class ReverseNumber
{
public static void main(String args[])
{
int n, reverse = 0;
 
System.out.println("Enter the number to reverse");
Scanner in = new Scanner(System.in);
n = in.nextInt();
 
while( n != 0 )
{
reverse = reverse * 10;
reverse = reverse + n%10;
n = n/10;
}
 
System.out.println("Reverse of entered number is "+reverse);
}
}
Download Reverse number program class file.
Output of program:
reverse number
You can also reverse or invert a number using recursion. You can use this code to check if a number is palindrome or not, if the reverse of an integer is equal to integer then it's a palindrome number else not.

Java program to add two matrices

This java program add two matrices. You can add matrices of any order.

Java programming source code

import java.util.Scanner;
 
class AddTwoMatrix
{
public static void main(String args[])
{
int m, n, c, d;
Scanner in = new Scanner(System.in);
 
System.out.println("Enter the number of rows and columns of matrix");
m = in.nextInt();
n = in.nextInt();
 
int first[][] = new int[m][n];
int second[][] = new int[m][n];
int sum[][] = new int[m][n];
 
System.out.println("Enter the elements of first matrix");
 
for ( c = 0 ; c < m ; c++ )
for ( d = 0 ; d < n ; d++ )
first[c][d] = in.nextInt();
 
System.out.println("Enter the elements of second matrix");
 
for ( c = 0 ; c < m ; c++ )
for ( d = 0 ; d < n ; d++ )
second[c][d] = in.nextInt();
 
for ( c = 0 ; c < m ; c++ )
for ( d = 0 ; d < n ; d++ )
sum[c][d] = first[c][d] + second[c][d]; //replace '+' with '-' to subtract matrices
 
System.out.println("Sum of entered matrices:-");
 
for ( c = 0 ; c < m ; c++ )
{
for ( d = 0 ; d < n ; d++ )
System.out.print(sum[c][d]+"\t");
 
System.out.println();
}
}
}
Download Add matrix program class file.
Output of program:
add matrix
This code adds two matrix, you can modify it to add any number of matrices. You can create a Matrix class and create it's objects and then create an add method which sum the objects, then you can add any number of matrices by repeatedly calling the method using a loop.

Java program to generate random numbers

Java program to generate random numbers: This code generates random numbers in range 0 to 100 (both inclusive).

Java programming code

import java.util.*;
 
class RandomNumbers {
public static void main(String[] args) {
int c;
Random t = new Random();
 
// random integers in [0, 100]
 
for (c = 1; c <= 10; c++) {
System.out.println(t.nextInt(100));
}
}
}
Download Random Numbers program class file.
Output of program:
Java random numbers program output
nextInt(c) method returns next integer in 0 to c (both inclusive), c must be positive. To generate random float's use nextFloat which returns float between 0.0 to 1.0.

Java program to perform garbage collection

This program performs garbage collection. Free memory in java virtual machine is printed and then garbage collection is done using gc method of RunTime class, freeMemory method returns amount of free memory in jvm, getRunTime method is used to get reference of current RunTime object.

Java programming source code

import java.util.*;
 
class GarbageCollection
{
public static void main(String s[]) throws Exception
{
Runtime rs = Runtime.getRuntime();
System.out.println("Free memory in JVM before Garbage Collection = "+rs.freeMemory());
rs.gc();
System.out.println("Free memory in JVM after Garbage Collection = "+rs.freeMemory());
}
}
Download Garbage collection program class file.
Output of program:
garbage collection
Obviously the amount of available after garbage collection will be different on your computer. Numbers are not important, what is important is that amount of memory available is more than before. You can use this code in your program or projects which uses large amount of memory or where frequently new objects are created but are required for a short span of time.

Java program to get ip address

This program prints IP or internet protocol address of your computer system. InetAddress class of java.net package is used, getLocalHost method returns InetAddress object which represents local host.

Java programming source code

import java.net.InetAddress;
 
class IPAddress
{
public static void main(String args[]) throws Exception
{
System.out.println(InetAddress.getLocalHost());
}
}
Download IP address program class file.
Output of program:
IP address
Output of code prints computer name/ IP address of computer. Java has a very vast Networking API and can be used to develop network applications.

Java program to find all substrings of a string

Java program to find substrings of a string :- This program find all substrings of a string and the prints them. For example substrings of "fun" are :- "f", "fu", "fun", "u", "un" and "n". substring method of String class is used to find substring. Java code to print substrings of a string is given below.

Java programing code

import java.util.Scanner;
 
class SubstringsOfAString
{
public static void main(String args[])
{
String string, sub;
int i, c, length;
 
Scanner in = new Scanner(System.in);
System.out.println("Enter a string to print it's all substrings");
string = in.nextLine();
 
length = string.length();
 
System.out.println("Substrings of \""+string+"\" are :-");
 
for( c = 0 ; c < length ; c++ )
{
for( i = 1 ; i <= length - c ; i++ )
{
sub = string.substring(c, c+i);
System.out.println(sub);
}
}
}
}
Download Substrings of a string program class file.
Output of program:
Substrings of string
For a string of length n there will be (n(n+1))/2 non empty substrings and one more which is empty string. Empty string is considered to be substring of every string also known as NULL string.

Java program to display date and time, print date and time using java program

Java date and time program :- Java code to print or display current system date and time. This program prints current date and time. We are using GregorianCalendar class in our program. Java code to print date and time is given below :-

Java programming code

import java.util.*;
 
class GetCurrentDateAndTime
{
public static void main(String args[])
{
int day, month, year;
int second, minute, hour;
GregorianCalendar date = new GregorianCalendar();
 
day = date.get(Calendar.DAY_OF_MONTH);
month = date.get(Calendar.MONTH);
year = date.get(Calendar.YEAR);
 
second = date.get(Calendar.SECOND);
minute = date.get(Calendar.MINUTE);
hour = date.get(Calendar.HOUR);
 
System.out.println("Current date is "+day+"/"+(month+1)+"/"+year);
System.out.println("Current time is "+hour+" : "+minute+" : "+second);
}
}
Download Date and time program class file.
Output of program:
date time
Don't use Date and Time class of java.util package as their methods are deprecated means they may not be supported in future versions of JDK. As an alternative of GregorianCalendar class you can use Calendar class.

Java program for linear search

Java program for linear search: Linear search is very simple, To check if an element is present in the given list we compare search element with every element in the list. If the number is found then success occurs otherwise the list doesn't contain the element we are searching.

Java programming code

 
import java.util.Scanner;
 
class LinearSearch
{
public static void main(String args[])
{
int c, n, search, array[];
 
Scanner in = new Scanner(System.in);
System.out.println("Enter number of elements");
n = in.nextInt();
array = new int[n];
 
System.out.println("Enter " + n + " integers");
 
for (c = 0; c < n; c++)
array[c] = in.nextInt();
 
System.out.println("Enter value to find");
search = in.nextInt();
 
for (c = 0; c < n; c++)
{
if (array[c] == search) /* Searching element is present */
{
System.out.println(search + " is present at location " + (c + 1) + ".");
break;
}
}
if (c == n) /* Searching element is absent */
System.out.println(search + " is not present in array.");
}
}
Download Linear Search Java program class file.
Output of program:
Linear Search Java program
Above code locate first instance of element to found, you can modify it for multiple occurrence of same element and count how many times it occur in the list. Similarly you can find if an alphabet is present in a string.

Java program for binary search

Java program for binary search: This code implements binary search algorithm. Please note input numbers must be in ascending order.

Java programming code

import java.util.Scanner;
 
class BinarySearch
{
public static void main(String args[])
{
int c, first, last, middle, n, search, array[];
 
Scanner in = new Scanner(System.in);
System.out.println("Enter number of elements");
n = in.nextInt();
array = new int[n];
 
System.out.println("Enter " + n + " integers");
 
 
for (c = 0; c < n; c++)
array[c] = in.nextInt();
 
System.out.println("Enter value to find");
search = in.nextInt();
 
first = 0;
last = n - 1;
middle = (first + last)/2;
 
while( first <= last )
{
if ( array[middle] < search )
first = middle + 1;
else if ( array[middle] == search )
{
System.out.println(search + " found at location " + (middle + 1) + ".");
break;
}
else
last = middle - 1;
 
middle = (first + last)/2;
}
if ( first > last )
System.out.println(search + " is not present in the list.\n");
}
}
Download Binary Search Java program class file.
Output of program:
Binary Search Java program
Other methods of searching are Linear search and Hashing. There is a binarySearch method in Arrays class which can also be used.
import java.util.Arrays;
 
class BS
{
public static void main(String args[])
{
char characters[] = { 'a', 'b', 'c', 'd', 'e' };
 
System.out.println(Arrays.binarySearch(characters, 'a'));
System.out.println(Arrays.binarySearch(characters, 'p'));
}
}
binarySearch method returns the location if a match occurs otherwise -(x+1) where x is the no. of elements in the array, For example in the second case above when p is not present in characters array the returned value will be -6.