Search This Blog

Java Program to Find Sum of First N Terms of Geometric Progression

In this post we will see a java program to calculate sum of first n terms of a geometric progression. Geometric progression is also called GP (short for Geometric progression). The equation to find sum of first n terms of a geometric progression is as follows:

sum= a*(1-r^n)/(1-r)
sum of geometric progression, sum of gp, gp sum
sum of first n terms of geometric progression

Now, we will see a java program to find sum of first n terms of a GP. There is a case in which the above equation fails. When r (common ratio) is 1, the above equation won't work. Then every term in the GP will be same as first term. Therefore, in that case, the sum is a*n. The program is as follows:



import java.util.Scanner;

public class SumGP {
public static void main(String[] arg)
    {
    Scanner sc=new Scanner(System.in);
    System.out.println("Enter first term, common ratio and n (number of terms)");
    int a=sc.nextInt(),r=sc.nextInt(),n=sc.nextInt();
        System.out.println((r==1)?"Sum is:"+a*n:"Sum is:"+(float)a*(1-Math.pow(r,n))/(1-r));
    }
}

Java Program to Check Whether It Is Possible to Draw a Triangle with Given Sides

For existence of a triangle there is a condition. The condition is that the sum of the lengths of any two sides of a triangle must be greater than or equal to the length of the third side. If the sum of the lengths of any two sides of a triangle is equal to the length of the third side, it forms a triangle with zero area. The vertices are collinear in that case. Still we can say that the triangle exists. So, here we will see a java program to check whether a triangle exists or not with given sides. The program is as follows:

import java.util.Scanner;

public class TriangleSide {
public static void main(String[] arg)
    {
    
    Scanner sc=new Scanner(System.in);
    System.out.println("Enter the sides of triangle");
    int a=sc.nextInt(),b=sc.nextInt(),c=sc.nextInt();
    if(a+b>=c&&b+c>=a&&c+a>=b)
        System.out.println("possible");
    else
        System.out.println("impossible");
    }
}

Body Mass Index Calculator Using Java - Java Application Code

Body Mass Index Calculation is based on your weight and height. Body Mass Index (BMI) = weight/(height*height) where weight is in kilograms and height in meters. The following Java program takes weight and height as input and displays BMI and grades into underweight,Normal, Overweight or obesity.


import java.util.Scanner;

public class BMI {

public static void main(String[] arg)
    {
    Scanner sc=new Scanner(System.in);
    System.out.println("Enter weight in kgs and height in meters");
    float bmi=sc.nextFloat()/(float)Math.pow(sc.nextFloat(),2);
    String s=(bmi<18.5)?"Underweight":(bmi<25)?"Normal weight":(bmi<30)?"Overweight":"Obesity";
    System.out.println("bmi: "+bmi+"   "+s);
    }
}

Calculate your BMI here

Weight (in kg):
Height (in meters):

Four Different Java Programs to Swap Two Numbers Without a Third Variable

Swapping two numbers are done using a third variable. But it is often asked for programming interviews to swap two numbers without using a third variable. We will see four different programs in java to swap two variables without using a third variable. This type of questions are often asked in technical interviews.

Trick 1

In the first java program to swap two numbers without a third variable, we swap the values of the two variables in 3 steps which are simple addition and subtractions.

import java.lang.*;
 
class Swapping
{
public static void main (String[] args) throws java.lang.Exception
    {
    int a=5,b=10;
    a=b+a; //now a =15
    b=a-b; //now b= 5
    a=a-b; // now a=10 (done)
    System.out.println("a = "+a+"  b= "+b);
    }
}


Trick 2

In the second java program to swap two numbers without a third variable, we swap them in a single statement. The statement contains an assignment, addition and subtraction.

import java.lang.*;

class Swapping
{

public static void main (String[] args) throws java.lang.Exception
    {
    int a=10,b=30;
    a=a+b-(b=a);
    //10+30-(10)  a becomes 30
    // b is assigned with 10 in the same line of code
    System.out.println("a= "+a+"  b= "+b);
    }
}

Trick 3

In the third java code, we swap the numbers using bitwise XOR operation. The bitwise operator 
is used in the program. The binary representation of the numbers, the bitwise xor operation on them and the result are shown in the c program as comments. For simplicity and convenience, we are representing numbers using only 5 bits. The real size of an integer in java is much larger. We show only the rightmost 5 bits. It is enough to illustrate the examples with small integers. The program is as follows:


import java.lang.*;

class Swapping
{

public static void main (String[] args) throws java.lang.Exception
    {
    int a=8,b=12;
    
   /* a: 8 : 01000
      b:12 : 01100
    */
   
    a=a^b; 
   
    /*  a:  01000 ^
        b:  01100
        a=  00100 (4)
    */

    b=a^b;

    /*a:    00100 ^
      b:    01100
      b=    01000 (8)
    */

    a=b^a;

    /* b:   01000 ^
       a:   00100 
       a=   01100 (12)
    */

    System.out.println("a= "+a+"  b= "+b);
    }
}

Trick 4

In the fourth java program to swap two numbers without a temporary variable, we swap the numbers using a combination of addition, subtraction and bitwise NOT (inversion) operation. The bitwise operator is used in the program. The binary representation of the numbers, the bitwise NOT operation on them and the result are shown in the java program as comments. The program is as follows:


import java.lang.*;

class Swapping
{

public static void main (String[] args) throws java.lang.Exception
     {
     int a=14,b=4;
    
   /* a: 14 : 1110
      b:  4 : 0100
     ~a:   :  0001  
     ~b:   :  1011  
   */
   a=b-~a-1;
    /* b:   0100 -
      ~a:   0001
            0011 -
       1:   0001
            0010
     now a= 0010 
    */
    b=a+~b+1;
    /* a:   0010 +
      ~b:   1011
       1:   0001
    now b:  1110  (14)
       ~b:  0001
    */
    a=a+~b+1;
   /*  a:   0010 +
      ~b:   0001
       1:   0001
    now a:  0100 (4)
   */

   System.out.println("a= "+a+"  b= "+b);
   }
}

Java Program For Spiral Matrix - Java Programming Interview Question

A spiral matrix is a matrix (two dimensional array) in which the elements are stored in a spiral fashion. Actually it is a normal NxN two dimensional array. But instead of accessing elements in row-wise or column-wise order, we access them in spiral order. i.e, in a 3x3 matrix the order of retrieval of elements is spiral order is as follows:

(0,0)  (0,1)   (0,2)  (1,2)   (2,2)   (2,1)   (2,0)   (1,0)   (1,1)

The following picture shows a 4x4 spiral matrix:
4x4 spiral matrix using two dimensional array - Java Program for spiral matrix
A 4x4 Spiral matrix

An question asked by zoho corporation during interview was to write a program to read a matrix spirally. In this post, we will answer this zoho interview question. Remember that the memory implementation is purely same as a normal matrix. The only difference here is the order in which we store elements to matrix or access elements in matrix. The following is the java program to read a spiral matrix. In thi s java program for spiral matrix, we just read the elements to the matrix. The elements entered by the user are entered into the matrix spirally. And the program finally displays the full matrix just as all normal matrices are displayed. Then you can see that the elements are not stored in the order as they were entered. You can see the spiral order in the matrix.

import java.io.*;
public class Spiral
{

public static void main(String args[])
{
int a[][]=new int[10][10];
int o,cellcount,cc=0,c=0,i=0,j=0,g=1;
try{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the order of spiral matrix");
o=Integer.parseInt(br.readLine());
cellcount=o;
System.out.println("\nEnter the elements:\n");
while(c<o*o)
    {
    cc=0;
    for(;cc<cellcount;j=j+g,cc++)
	a[i][j]=Integer.parseInt(br.readLine());
    j=j-g;
    c+=cc;
    cc=0;
    i=i+g;
    cellcount--;
    if(c>=o*o)
	break;
    for(;cc<cellcount;i=i+g,cc++)
	a[i][j]=Integer.parseInt(br.readLine());
    c+=cc;
    i=i-g;
    j=j-g;
    g*=-1;
    }
System.out.println("\nThe spiral matrix is:");
for(i=0;i<o;i++)
    {
    System.out.print("\n");
    for(j=0;j<o;j++)
	System.out.print(Integer.toString(a[i][j])+"\t");
    }
}catch(Exception ex){ex.printStackTrace();}
}

}

UnitCon - Universal Unit Converter and Currency Converter for Computers in Java

UnitCon Unit and Currency converter is a free unit converter software for computer. It allows you to
freeware free download unit conversion software currency conversion software free currency converter
UnitCon Free Unit Conversion Software and Currency converter
convert between units of about 20 different physical quantities. It also has a currency converter functionality which allows conversion between currencies of almost all countries. The unit conversion functionality is completely offline. But for currency conversion, internet connection is required.

The different physical quantities for which unit conversion is available are:


  1. Acceleration
  2. Angle
  3. Angular Acceleration
  4. Angular Velocity
  5. Area
  6. Capacitance
  7. Density
  8. Digital Storage
  9. Distance
  10. Electric charge
  11. Energy
  12. Force
  13. Frequency
  14. Luminous Intensity
  15. Mass
  16. Power
  17. Solid Angle
  18. Speed or Velocity
  19. Temperature
  20. Time
  21. Torque
  22. freeware free download unit conversion software currency conversion software free currency converter
    Free unit converter and currency converter software
  23. Volume

And after all, currency conversion is also available. The software is coded in java. You may require to download and install Java Runtime Environment 1.8 or later if you don't have it installed. The application (below 300KB) is available for free download. The source code of the unit converter is also available for free download.



Remote Method Invocation (RMI) in Java - Example Program to Calculate Power using RMI

Remote Proceure Call (RPC) is a protocol by which a computer can call a function in another computer connected through network. The caller passes arguments through network and the callee executes the function and returns the output to the caller. In object oriented languages we use RMI (Remote Method Invocation) instead of RPC. Let us see a sample java program which uses RMI. .

Here, we call the computer that hosts the method, a server. And those computers which call this method are called clients. More precisely, RMI server and RMI clients. RMI clients call remote methods in RMI servers.

Our example program is answer to the following question:
Write a java program that uses RMI in which RMI clients can calculate powers of numbers by invoking a remote method in RMI server.

Java Program To Send an XML File From Server to Client and Display it as Table

java program send xml file process cml file display as table java code xml parser
XML parsed and displayed as a table
In this post, i am writing a java program which will send an XML file over the network from Server to Client using Socket connection (TCP connection) and the client displays the received file as a table using swing. This program is based on my network lab experiment at college. The problem was:

Write a Program to read an xml file stored in the server. A client connected to the server gets the file and display the contents in a table using swing. The xml file contains details of books with the following fields.

Temperature Converter Program Using Java - Celsius, Kelvin, Fahrenheit, Reaumur and Rankine

free java temperature converter program. java temperature conversion using java program unit converter celsius kelvin fahrenheit and other different temperature scales
Java Temperature Converter Program
A responsive and accurate temperature converter program can be made using java. In this post, we
will see a good temperature converter code. This java temperature conversion application converts temperature between Celsius, Kelvin, Fahrenheit, Reaumur and Rankine scales. The java program for this temperature consists of methods for:
  • Celsius to Fahrenheit Conversion
  • Celsius to Kelvin Conversion
  • Celsius to Reaumur Conversion
  • Celsius to Rankine Conversion
  • Fahrenheit to Celsius Conversion
  • Fahrenheit to Kelvin Conversion
  • Fahrenheit to Reaumur Conversion
  • Fahrenheit to Rankine Conversion
  • Kelvin to Celsius Conversion
  • Kelvin to Fahrenheit Conversion
  • Kelvin to Reaumur Conversion
  • Kelvin to Rankine Conversion
  • Reaumur to Celsius conversion
  • Reaumur to Kelvin conversion
  • Reaumur to Fahrenheit conversion
  • Reaumur to Rankine conversion
  • Rankine to Celsius conversion
  • Rankine to Kelvin conversion
  • Rankine to Fahrenheit conversion
  • Rankine to Reaumur conversion

Java Program to Send a File over a Network after Encryption

Here is a simple java program which can be used to send and receive encrypted files over network. The sender encrypts the file before sending and the receiver decrypts the file and displays it. The program is based on a networking lab experiment at my college. So, although we say 'encryption', characters are simply incremented here. The lab question was as follows:

A client wants a file that is with a server in a secure system. The server encrypts the file in such a way that 'A' will be replaced with 'B', 'B' with 'C'... and 'Z' with 'A' and sends to the client. The client should get file and decrypt it to the original one and display the content. Implement it using TCP/IP.