Search This Blog

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.

Java Program to Implement Broadcasting System Between a Server and Many Clients

Multicast and Broadcast using java program. java source code sample program for broadcasting or multicasting
Screenshot of broadcast server and clients using java
In this post we will see a java program which implements a broadcasting system. A Server can send a message as a multicast message into a multicast group. Any client can receive the multicasted packets after joining the group. The program make use of MulticastSocket class which is a subclass (derived class) of DatagramSocket class. Multicasting is almost same as UDP messaging. Datagram packets are used by MulticastSocket class. MulticastSocket class has two methods joinGroup() and leaveGroup(), each receive a InetAddress object as parameter which should be representing a multicast IP address. The datagrams sent using the MulticastSocket object should be addressed to a multicast group with IP between 224.0.0.0 and 239.255.255.255. These are IP addresses reserved for multicasting. The following java program to implement broadcasting using Multicast will tell you more.

How to Load a Webpage in a Java App

Do you wonder how to load a webpage in your java application? It is simple. You can load a web document whether it is a web document in internet or a web document from a file in the localhost. I know three methods to do it. You can use JTextPane in java swing (javax.swing), JEditorPane in java swing (javax.swing) or WebView in javaFX (javafx.scene.web.WebView). We will discuss each method to display a webpage in a java application.

The three methods we are going to discuss are:
  • Using JTextPane
  • Using JEditorPane
  • Using WebView in JavaFX

Java FileNotFoundException While File is Existing There

Sometimes you my encounter a FileNotFoundException in java while you can see that the specified file is there. This can happen for several reasons.The java code may throw a  FileNotFoundException even when the file exists. This can be for different reasons.

Reason 1

The file does not exist really. Although you can see the file, the path you may have entered may be incorrect. For example, the following code may throw exception in some operating systems:

File f=new File("D:\myfile.txt");

This is because the file separator character is '\' in windows os. since \ is used to display non graphical characters like '\n' you should use its corresponding escape sequence. So "D:\\myfile.txt" would work on windows. If your java application is a cross platform program, you should consider using File.separator instead of '\\' because not all operating systems use '\\' as file separator character. So, the best approach is ;

File f=new File("D:"+File.separator+"myfile.txt");

File.separator is the system-dependent default name-separator character, represented as a string for convenience. This string contains a single character, namely File.separatorChar. If you want to get this character as a Character itself, you can use File.separatorChar. There can be other mistakes in the path.

Reason 2

The name you entered as a file may be actually a directory. So an exception can be thrown in java when you try to read from or write to such File object.

Reason 3

You cannot open it for reading or writing for some other reasons. You can check the status of file by calling the methods like f.exists(), f.canRead(), f.canWrite(), f.isFile() and f.isDirectory(). All these methods return a boolean. I hope these java method names describe well what they are intended for.