Core Java Programs

♠ Posted by Java Tutorials at 2:37 AM

                             Page      1|2|3|4


27.    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.
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());
   }
}
Output of program:

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.

28.    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.
import java.net.InetAddress;

class IPAddress
{
   public static void main(String args[]) throws Exception
   {
      System.out.println(InetAddress.getLocalHost());
   }
}
Output of program:


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.

29.    Java program to reverse number

This program prints reverse of a number i.e. if the input is 951 then output will be 159.
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);
   }
}
Output of program:


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.

30.    Java program to add two matrices

This java program add two matrices. You can add matrices of any order.
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();
      }
   }
}
Output of program:


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.

31.    Java program to transpose matrix

This java program find transpose of a matrix of any order.
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");
      }
   }
}
Output of program:


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.

32.    Java program to multiply two matrices

This java program multiply two matrices. Before multiplication matrices are checked whether they can be multiplied or not.
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");
         }
      }
   }
}
Output of program:


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.

33.    Java program to bubble sort

Java program to bubble sort: This code sorts numbers inputted by user using Bubble sort algorithm.
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.
Output of program:


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);
    }
  }
}
·          

34.    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.
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);
    }  
  }
}
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.

                 

                            Page      1|2|3|4

0 comments :

Post a Comment