Recent Posts

Pages: 1 ... 8 9 [10]
91
Java / Java program to bubble sort
« Last post by candy on November 17, 2013, 09:25:10 PM »
Java program to bubble sort: This code sorts numbers inputted by user using Bubble sort algorithm.

Java programming code
Code: [Select]
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]);
  }
}


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.

Code: [Select]
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);
    }
  }
}

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.
92
Java / Java program to multiply two matrices
« Last post by candy on November 17, 2013, 09:24:22 PM »
This java program multiply two matrices. Before multiplication matrices are checked whether they can be multiplied or not.

Java programming code
Code: [Select]
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");
         }
      }
   }
}


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.
93
Java / Java program to transpose matrix
« Last post by candy on November 17, 2013, 09:23:43 PM »
This java program find transpose of a matrix of any order.

Java programming source code
Code: [Select]
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");
      }
   }
}


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.
94
Java / Java program to add two matrices
« Last post by candy on November 17, 2013, 09:22:53 PM »
This java program add two matrices. You can add matrices of any order.

Java programming source code
Code: [Select]
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();
      }
   }
}



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.
95
Java / Java program to reverse number
« Last post by candy on November 17, 2013, 09:22:14 PM »
This program prints reverse of a number i.e. if the input is 951 then output will be 159.

Java programming source code
Code: [Select]
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);
   }
}


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.
96
Java / Java program to get ip address
« Last post by candy on November 17, 2013, 09:21:31 PM »
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
Code: [Select]
import java.net.InetAddress;
 
class IPAddress
{
   public static void main(String args[]) throws Exception
   {
      System.out.println(InetAddress.getLocalHost());
   }
}


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.
97
Java / Java program to perform garbage collection
« Last post by candy on November 17, 2013, 09:20:50 PM »
his 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
Code: [Select]
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());
   }
}


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.
98
Java / Java program to generate random numbers
« Last post by candy on November 17, 2013, 09:19:58 PM »
ava program to generate random numbers: This code generates random numbers in range 0 to 100 (both inclusive).

Java programming code
Code: [Select]
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));
    }
  }
}


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.

99
Java / Java program to display date and time, print date and time using java program
« Last post by candy on November 12, 2013, 04:53:12 PM »
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
Code: [Select]
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);
   }
}


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.
100
Java / Java program to find all substrings of a string
« Last post by candy on November 12, 2013, 04:52:30 PM »
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
Code: [Select]
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);
         }
      }
   }
}


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.
Pages: 1 ... 8 9 [10]