Search This Blog

Java Program For Matrix Multiplication

This is a java program for Matrix Multiplication. To understand how it works, you should first know how matrix multiplication is done mathematically.

import java.util.Scanner;

public class MatrixMult{

public static void main(String[] args)
{
int[][] m1=new int[10][10];
int[][] m2=new int[10][10];
int[][] prod=new int[10][10];
int i,j,k,r1,c1,r2,c2;
Scanner sc=new Scanner(System.in);
System.out.println("Enter number of rows and columns of first matrix:");
r1=sc.nextInt();
c1=sc.nextInt();
System.out.println("Enter number of rows and columns of second matrix:");
r2=sc.nextInt();
c2=sc.nextInt();
if(r2==c1)
    {
    System.out.println("Enter elements of First matrix (row wise):");
    for(i=0;i<r1;i++)
        for(j=0;j<c1;j++)
            m1[i][j]=sc.nextInt();
    System.out.println("Matrix1 is :");
    for(i=0;i<r1;i++)
        {
        for(j=0;j<c1;j++)
            System.out.printf("%d ",m1[i][j]);
        System.out.printf("\n");
        }
    System.out.println("Enter elements of Second matrix (row wise):");
    for(i=0;i<r2;i++)
        for(j=0;j<c2;j++)
            m2[i][j]=sc.nextInt();
    System.out.println("Matrix2 is:");
    for(i=0;i<r2;i++)
        {
        for(j=0;j<c2;j++)
            System.out.printf("%d ",m2[i][j]);
        System.out.printf("\n");
        }
    System.out.println("Product of the Matrices (M1 x M2):");
    for(i=0;i<r1;i++)
        {
        for(j=0;j<c2;j++)
            {
            prod[i][j]=0;
            for(k=0;k<r1;k++)
                prod[i][j]+=m1[i][k]*m2[k][j];
            System.out.printf("%d ",prod[i][j]);
            }
        System.out.print("\n");
        }
    }
else
    {
    System.out.println("Matrices can't be multiplied.");
    System.out.print("No. of columns of first matrix and no of rows of second are different.");
    }
}
}

Output

Enter number of rows and columns of first matrix:
2
2
Enter number of rows and columns of second matrix:
2
2
Enter elements of First matrix (row wise):
5
8
6
4
Matrix1 is :
5 8 
6 4 
Enter elements of Second matrix (row wise):
5
6
8
9
Matrix2 is:
5 6 
8 9 
Product of the Matrices (M1 x M2):
89 102 
62 72 

Java Program to Display Multiplication Tables of Given Number

This is a java program to display multiplication table of given number. For java program to display multiplication table of all numbers from 1 to 10, see this post: Program to display multiplication table of all numbers from 1 to 10

import java.util.Scanner;

public class Multiples{

public static void main(String[] args)
{
    int n, i;
    Scanner sc=new Scanner(System.in);
    System.out.printf("Enter the number:");
    n=sc.nextInt();
    for(i=1; i<=10; ++i)
        System.out.printf("%d * %d = %d \n", i, n, n*i);
}
}

Output:

Enter the number:5
1 * 5 = 5
2 * 5 = 10
3 * 5 = 15
4 * 5 = 20
5 * 5 = 25
6 * 5 = 30
7 * 5 = 35
8 * 5 = 40
9 * 5 = 45
10 * 5 = 50

Java Program to Display Multiplication Tables of All Number from 1 to 10

This is  a java program to display multiplication tables of all number from 1 to 10. To see java program to display multiplication table of given number only, see this program:
Program to Display Multiplication Table of Given Number
public class Multiples{

public static void main(String[] args)
{
int i,j;
for(i=1;i<=10;i++)
    {
    for(j=1;j<=10;j++)
        System.out.printf("%d*%d=%d  ",i,j,i*j);
    System.out.printf("\n");
    }
}

}


Output:

1*1= 1 1*2= 2 1*3= 3 1*4= 4 1*5= 5 1*6= 6 1*7= 7 1*8= 8 1*9= 9 1*10=10
2*1= 2 2*2= 4 2*3= 6 2*4= 8 2*5=10 2*6=12 2*7=14 2*8=16 2*9=18 2*10=20
3*1= 3 3*2= 6 3*3= 9 3*4=12 3*5=15 3*6=18 3*7=21 3*8=24 3*9=27 3*10=30
4*1= 4 4*2= 8 4*3=12 4*4=16 4*5=20 4*6=24 4*7=28 4*8=32 4*9=36 4*10=40
5*1= 5 5*2=10 5*3=15 5*4=20 5*5=25 5*6=30 5*7=35 5*8=40 5*9=45 5*10=50
6*1= 6 6*2=12 6*3=18 6*4=24 6*5=30 6*6=36 6*7=42 6*8=48 6*9=54 6*10=60
7*1= 7 7*2=14 7*3=21 7*4=28 7*5=35 7*6=42 7*7=49 7*8=56 7*9=63 7*10=70
8*1= 8 8*2=16 8*3=24 8*4=32 8*5=40 8*6=48 8*7=56 8*8=64 8*9=72 8*10=80
9*1= 9 9*2=18 9*3=27 9*4=36 9*5=45 9*6=54 9*7=63 9*8=72 9*9=81 9*10=90
10*1=10 10*2=20 10*3=30 10*4=40 10*5=50 10*6=60 10*7=70 10*8=80 10*9=90 10*10=100

Java Program to Rotate Polygon - 2d Transformation Rotation in Java

This is a java program for rotation transformation in computer graphics. Rotation is one of the important 2d transformations in computer graphics. The program will tell you how to rotate points or polygon around a point (the pivot point). This CG lab program in java language reads the number of sides of polygon, co-ordinates of its vertices, the pivot point for rotation, and angle of rotation. It displays the original polygon and translated polygon in different colors in same screen. This program will tell you how to rotate a polygon in java. I override the paintComponent() method of JPanel to draw on a JPanel.


Java Program for Engine Piston Movement Animation

This program simulates the motion of the components of a two stroke engine. It shows the movement of piston, connecting rod and crank by animating them in java. The program override the paint method of a JFrame to simulate the piston movement in two stroke engine. This can be computer graphics lab (CG lab) problem. The program is as given below. The program uses sin and cos functions to simulate the crank. Also it uses the equation to find the distance between to points.

Decimal to BCD Converter in Java

In this post,we will see java program to convert decimal number to BCD representation. Binary-coded decimal (BCD) is a class of binary encodings of decimal numbers where each decimal digit is represented by a fixed number of bits, usually four. Thus the decimal digit 1 corresponds to  0001, 2 corresponds to 0010,....  8 corresponds to 1000 and 9 corresponds to 1001. Therefore, decimal number 194 can be represented in BCD as 0001 1001 0100. It should be noted that 1010, 1011, 1100, 1101,1110 and 1111 are illegal in BCD. The following java program converts any decimal number to BCD. But in this program, for conversion each digit in the decimal, we use Integer.toBinaryString() method. So, i have added another program which does not use this method.

Program 1:


    public static String toBCD(int num)
    {
        String BCD="";
        while(num!=0)
        {
        int t=num%10;
        String tBCD=Integer.toBinaryString(t);
        while(tBCD.length()<4)
            {
            tBCD="0"+tBCD;
            }
        BCD=tBCD+BCD;
        num/=10;
        }
        return BCD;
    }


Program 2:


import java.util.Scanner;
public class DecimalToBCD {

static String digitToBcd(int digit)
{
    String str="";
    for(int i=3;i>=0;i--)
        {
        int d=(int) Math.pow(2,i);
        if(digit/d!=0)
            {
                str+="1";
                digit-=d;
            }
        else
            str+="0";
        }
    return str;
}
    
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        int decimal=sc.nextInt();
        int digit;
        String BCD="";
        while(decimal!=0)
            {
            digit=decimal%10;
            BCD=digitToBcd(digit)+" "+BCD;
            decimal/=10;
            }
        System.out.println("BCD is:"+BCD);
        
    }
}


The second program does not use any built in methods for conversion of decimal to BCD.

Java Program to Simulate Motion of Simple Pendulum

This is a java program to simulate motion of simple pendulum using java graphics. This was a problem given in computer graphics lab, which i was supposed to do using graphics.h header file in C. This is the java version of the same. If you are looking for a C Program, here it is: C Program to Simulate Simple Pendulum Motion - Computer Graphics Lab.

Output is as follows:



import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;


public class JavaApplication1 extends JFrame{

    int pivotx,pivoty;
    double thetamax,theta;;
    double len=260;
    int x,y,ymax,xmax;
    int bobradius=30;
    int xsign=-1,ysign=1;
    double omega;
    
    public JavaApplication1()
    {
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setSize(600,400);
        thetamax=60*Math.PI/180;
        pivotx=getWidth()/2;
        pivoty=40;
        ymax=(int) (pivoty+len*Math.cos(thetamax));
        xmax=(int) (pivotx+len*Math.sin(thetamax));
        x=xmax;
        y=ymax;
        theta=thetamax;
        System.out.println("pivotx:"+pivotx+" pivoty:"+pivoty);
        System.out.println("starting x:"+x+ "y:"+y);
        System.out.println("starting theta="+theta);
        t.start();
    }

    @Override
    public void paint(Graphics g) {
        System.out.println("called");        
        g.setColor(Color.WHITE);
        g.fillRect(0, 0,getWidth(),getHeight());
        g.setColor(Color.red);
        g.fillOval(pivotx-4,pivoty-4,8,8);
        g.drawLine(pivotx,pivoty, x,y);
        g.fillOval(x-bobradius/2,y-bobradius/2,bobradius,bobradius);
        
    }
    
    Thread t=new Thread()
    {
      public void run()
      {
    try {
      while(true)
      {
      if(x>=pivotx+Math.abs(len*Math.sin(thetamax)))
        {
        System.out.println("right extreme");
        xsign=-1;
        ysign*=-1;
        x=xmax-1;
        Thread.sleep(40);
        }
      else if(x<=pivotx-Math.abs(len*Math.sin(thetamax)))
      {
          System.out.println("left extreme");
          ysign*=-1;
          xsign=1;
          x=(int) (pivotx-Math.abs(len*Math.sin(thetamax))+2);
          Thread.sleep(40);
      }
      else if(y>=pivoty+len)
        {
              ysign*=-1;
              System.out.println("mean position");
        }

      omega=y/60*Math.PI/180;
      double decr=xsign*omega;
          System.out.println("decrement:"+decr);
      theta=theta+decr;
      x=(int) (pivotx+len*Math.sin(theta));
      y=(int) (pivoty+len*Math.cos(theta));
          System.out.println("new theta:"+theta);
      repaint();
      Thread.sleep(40);
    
      }
            } catch (InterruptedException ex) {}
      }
    };
    
    
    public static void main(String[] args) {
        new JavaApplication1().setVisible(true);
    }
    
}





Simplest UDP Chat Program to Run on Single Computer in Java

This is a very simple UDP chat program using java with GUI (Graphical User Interface). The program uses DatagramPackets to send messages over network. Remember, this program only to be run on a single computer (for network simulation purpose). If you want a real UDP program that works on any network, see this post: Chat Room Application using UDP in Java
Program explanation is given below the program.


import java.io.*;
import javax.swing.*;
import java.net.*;
import java.awt.event.*;
import java.util.*;

public class UDPChat extends JFrame implements ActionListener
{
DatagramSocket ds;
JTextField txt;
JButton send;
JTextArea msgs;
int myport;
int destport;
DatagramPacket p;
byte[] b=new byte[200];

public UDPChat()
{
try{
try{
ds=new DatagramSocket(9999);
myport=9999;
p=new DatagramPacket(b,200);
ds.receive(p);
destport=p.getPort();
}catch(Exception ex)
{
ds=new DatagramSocket(0);
myport=ds.getLocalPort();
destport=9999;
String msg="hi";
p=new DatagramPacket(msg.getBytes(),msg.length(),InetAddress.getLocalHost(),destport);
ds.send(p);
}
setLayout(null);
txt=new JTextField();
send=new JButton("Send");
msgs=new JTextArea();
setSize(300,600);
add(txt);
txt.setSize(220,25);
txt.setLocation(5,5);
add(send);
send.setSize(70,25);
send.setLocation(230,5);
add(msgs);
msgs.setSize(300,530);
msgs.setLocation(0,70);
send.addActionListener(this);
receive.start();
}catch(Exception ex){ex.printStackTrace();}
}

public void actionPerformed(ActionEvent ae)
{
try{
DatagramPacket pkt=new DatagramPacket(txt.getText().getBytes(),txt.getText().length(),InetAddress.getLocalHost(),destport);
ds.send(pkt);
}catch(Exception e){e.printStackTrace();}
txt.setText("");
}

Thread receive=new Thread()
{
public void run()
{
try{
while(true)
 {
 DatagramPacket dp=new DatagramPacket(b,200);
 ds.receive(dp);
 msgs.setText(msgs.getText()+"\n"+new String(b));
 }
}catch(Exception exx){exx.printStackTrace();}
}
};

public static void main(String[] args)
{
UDPChat s=new UDPChat();
s.setVisible(true);
}

}

This simple program is enough to run as server or client. When the first user runs the application, it opens a DatagramSocket with port number 9999 (see line 22 in code). Since no Exception will be thrown from this line, it sets myport as 9999. Then waits to receive a DatagramPacket from the other user. When the packet is received, it takes destport from the received packet. Then starts adding GUI elements and then starts the thread to receive messages.

But when the second instance (client) of the program is run, line 22 in code throws a SocketException. Thus execution goes to the catch block. There it opens a DatagramSocket at some random port (ephemeral port assigned by OS). Then, sends a packet to port 9999 in the same PC. This time the first instance (server) is still waiting for a packet as said earlier. It receives this DatagramPacket sent by client a gets its destination port. The client's destport is 9999, as it knew it is already occupied by the SocketException.

The sending of message is carried out when send button is clicked. We use an ActionListener for that. The method public void actionPerformed(ActionEvent ae) is invoked whenever the button is clicked.


Audio Recorder Application in Java - Source Code and Executable File

java audio recorder, sound recorder
Here, we will see how to record sound in java. We make a sound recorder application which can record from microphone, Stereo mix, line in, system audio etc. In the program, we use the Java Sound API. The java sound API allows to record audio in different sample rates starting from 8KHz. It also allows to record audio as stereo or mono. It supports audio formats like wave, au, AIFF etc.

In our program, we list all the available mixers in a JComboBox. And auto detects supported audio formats. The user can select from a list of available sample rates, sample bit sizes and audio file formats. I am embedding the code here. To download the executable file (jar) or project source, you can use the following links.

Sound Recorder Application in Java (Project Source code)

Download Audio Recorder Program (executable)

package javaapplication35;
import java.awt.Desktop;
import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.Line;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.Mixer;
import javax.sound.sampled.TargetDataLine;
import javax.swing.JOptionPane;
import javax.swing.WindowConstants;

class AudInputLine
{
    public Mixer mixer;
    public Line.Info lineInfo;
    public String name;
    
    public String toString()
    {
        return name;
    }
}
public class NewJFrame extends javax.swing.JFrame {

    private javax.swing.JButton btn_refresh;
    private javax.swing.JButton btn_start;
    private javax.swing.JButton btn_stop;
    private javax.swing.JComboBox cmb_bits;
    private javax.swing.JComboBox cmb_file_format;
    private javax.swing.JComboBox cmb_monoORStereo;
    private javax.swing.JComboBox cmb_sample;
    private javax.swing.JComboBox cmb_targetdatalines;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea jTextArea1;

    ArrayList<AudInputLine> lines=new ArrayList<>();
    TargetDataLine inputline;
    File audoutput;
    boolean start=false;
    AudioFormat format;
    Mixer.Info[] mixerInfo;
    AudioInputStream ais;
    String filename;
    AudioFileFormat.Type fileformat;
    String[] exts={"wav","au","aiff","aifc","snd"};
    File directory;
    
    public NewJFrame() {
        
        initComponents();
        filename=System.getProperty("user.home")+File.separator+"AudioRecorder";
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        RefreshInputs();
        File fold=new File(filename);
        if(!fold.exists())
            fold.mkdir();
        directory=new File(fold.getPath());
        filename+=File.separator+"rec";
        startRec.start();
    }
    
//__________ Refresh Input sources list_____________
public void RefreshInputs()
{
lines.clear();
mixerInfo = AudioSystem.getMixerInfo();
Line.Info[] targlines;
//getting all TargetLines from all available mixers
for(Mixer.Info m:mixerInfo)
    {
    targlines=AudioSystem.getMixer(m).getTargetLineInfo();
    for(Line.Info ln:targlines)
        {
        AudInputLine tail=new AudInputLine();
        tail.lineInfo=ln;
        tail.mixer=AudioSystem.getMixer(m);
        tail.name=tail.mixer.getMixerInfo().toString();
        lines.add(tail);
        }
    }

//removing TargetLines that do not support any AudioFormat
for(int i=0;i<lines.size();i++)
    {
    try{
        if(((DataLine.Info)lines.get(i).lineInfo).getFormats().length<1)
            {
            lines.remove(i);
            i-=1;
            }
       }catch(Exception exx)
        {
            lines.remove(i);
            i-=1;
        }
    }

cmb_targetdatalines.removeAllItems();
for(AudInputLine dinf:lines)
    cmb_targetdatalines.addItem(dinf);
}

//__________ Refresh audioformats_____________
public void RefreshAudioFormats()
{
int[] bits={24,16,8};
float[] sampling={8000,11025,16000,22050,44100,48000,96000,192000};
AudInputLine taud=((AudInputLine)cmb_targetdatalines.getSelectedItem());

//____populating samplerates combobox___
cmb_sample.removeAllItems();
for(int i=0;i<sampling.length;i++)
    {
    AudioFormat aftemp=new AudioFormat(sampling[i],8,1,false,true);
    if(taud.lineInfo instanceof DataLine.Info&&((DataLine.Info)taud.lineInfo).isFormatSupported(aftemp)==true)
        {
        cmb_sample.addItem(Float.toString(sampling[i]));
        if(sampling[i]==44100||sampling[i]==48000)
            cmb_sample.setSelectedIndex(i);
        }
    }

//___populating sampleBItSize combobox___
cmb_bits.removeAllItems();
for(int i=0;i<bits.length;i++)
    {
    AudioFormat aftemp=new AudioFormat(8000,bits[i],1,!(bits[i]==8),true);
    if(taud.lineInfo instanceof DataLine.Info&&((DataLine.Info)taud.lineInfo).isFormatSupported(aftemp)==true)
        cmb_bits.addItem(Integer.toString(bits[i]));
    }

//___Populating Channels combobox (mono/stereo)_____
AudioFormat aftemp=new AudioFormat(8000,8,2,false,true);
cmb_monoORStereo.removeAllItems();
if(taud.lineInfo instanceof DataLine.Info&&((DataLine.Info)taud.lineInfo).isFormatSupported(aftemp)==true)
    cmb_monoORStereo.addItem("Stereo");
cmb_monoORStereo.addItem("Mono");
}

//______________Record________________
public void record(){
try{
start=false;
inputline.open(format);
inputline.start();
ais=new AudioInputStream(inputline);
AudioSystem.write(ais,fileformat, audoutput);
}catch(Exception ex)
    {   
    JOptionPane.showMessageDialog(this, ex.getMessage());
    buttonsEnable(true);
    }

}

//method to handle enabling and disabling UI element when start/stop button are pressed
public void buttonsEnable(boolean f)
{
cmb_targetdatalines.setEnabled(f);
cmb_bits.setEnabled(f);
cmb_file_format.setEnabled(f);
cmb_monoORStereo.setEnabled(f);
cmb_sample.setEnabled(f);
btn_stop.setEnabled(!f);
btn_start.setEnabled(f);
}

//The recording thread. Set apart from EDT
Thread startRec=new Thread()
{
  public void run()
  {
  while(true)
    {
    while(start==false)
        try {
            Thread.sleep(300);
        } catch (Exception ex) {}
    record();
    }
 }
};

//___GUI initialisation (netbeans generated)_____
private void initComponents() {

        btn_stop = new javax.swing.JButton();
        btn_start = new javax.swing.JButton();
        cmb_targetdatalines = new javax.swing.JComboBox();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
        jLabel6 = new javax.swing.JLabel();
        cmb_file_format = new javax.swing.JComboBox();
        jLabel7 = new javax.swing.JLabel();
        btn_refresh = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        cmb_sample = new javax.swing.JComboBox();
        cmb_bits = new javax.swing.JComboBox();
        cmb_monoORStereo = new javax.swing.JComboBox();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setAlwaysOnTop(true);

        btn_stop.setText("Stop");
        btn_stop.setEnabled(false);
        btn_stop.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_stopActionPerformed(evt);
            }
        });

        btn_start.setText("Start");
        btn_start.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_startActionPerformed(evt);
            }
        });

        cmb_targetdatalines.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmb_targetdatalinesActionPerformed(evt);
            }
        });

        jTextArea1.setEditable(false);
        jTextArea1.setColumns(20);
        jTextArea1.setFont(new java.awt.Font("Monospaced", 0, 11)); // NOI18N
        jTextArea1.setLineWrap(true);
        jTextArea1.setRows(5);
        jTextArea1.setWrapStyleWord(true);
        jScrollPane1.setViewportView(jTextArea1);

        jLabel6.setText("Sample Size in bits");

        cmb_file_format.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "WAVE", "AU", "AIFF", "AIFF-C", "SND" }));

        jLabel7.setText("Select Input Source");

        btn_refresh.setText("Refresh Inputs");
        btn_refresh.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_refreshActionPerformed(evt);
            }
        });

        jLabel2.setText("Sample Rate");

        jLabel1.setText("Mono/Stereo");

        jLabel3.setText("File Format");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(cmb_targetdatalines, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 403, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(btn_refresh, javax.swing.GroupLayout.PREFERRED_SIZE, 109, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(jLabel7)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(cmb_sample, javax.swing.GroupLayout.PREFERRED_SIZE, 124, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(cmb_bits, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 124, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 124, javax.swing.GroupLayout.PREFERRED_SIZE))
                                    .addComponent(btn_start, javax.swing.GroupLayout.PREFERRED_SIZE, 85, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                    .addGroup(layout.createSequentialGroup()
                                        .addGap(10, 10, 10)
                                        .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 124, javax.swing.GroupLayout.PREFERRED_SIZE))
                                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                            .addComponent(btn_stop, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)
                                            .addComponent(cmb_monoORStereo, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, 124, Short.MAX_VALUE)
                                    .addComponent(cmb_file_format, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel7)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(cmb_targetdatalines, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(btn_refresh, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cmb_sample, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(cmb_bits, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(cmb_monoORStereo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(cmb_file_format, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btn_stop, javax.swing.GroupLayout.DEFAULT_SIZE, 39, Short.MAX_VALUE)
                    .addComponent(btn_start, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addGap(6, 6, 6))
        );

        pack();
    }

private void btn_stopActionPerformed(java.awt.event.ActionEvent evt) {
inputline.stop();  
inputline.close();
try {
    Desktop.getDesktop().open(directory);
    } catch (Exception ex) {}
buttonsEnable(true);
    }

private void btn_startActionPerformed(java.awt.event.ActionEvent evt) {
Date no=new Date();
audoutput=new File(filename+no.toString().replaceAll(":","-")+"."+exts[cmb_file_format.getSelectedIndex()]);
switch(cmb_file_format.getSelectedIndex())
    {
    case 0:fileformat=AudioFileFormat.Type.WAVE;break;
    case 1:fileformat=AudioFileFormat.Type.AU;break;
    case 2:fileformat=AudioFileFormat.Type.AIFF;break;
    case 3:fileformat=AudioFileFormat.Type.AIFC;break;
    case 4:fileformat=AudioFileFormat.Type.SND;break;
    }
AudInputLine tau=(AudInputLine)cmb_targetdatalines.getSelectedItem();
format=new AudioFormat(Float.parseFloat((String)cmb_sample.getSelectedItem()),Integer.parseInt((String)cmb_bits.getSelectedItem()),(cmb_monoORStereo.getSelectedIndex()+1)%2+1,!(Integer.parseInt((String)cmb_bits.getSelectedItem())==8),true);
AudInputLine taud=((AudInputLine)cmb_targetdatalines.getSelectedItem());
if(taud.lineInfo instanceof DataLine.Info&&((DataLine.Info)taud.lineInfo).isFormatSupported(format)==false)
    format=new AudioFormat(Float.parseFloat((String)cmb_sample.getSelectedItem()),Integer.parseInt((String)cmb_bits.getSelectedItem()),(cmb_monoORStereo.getSelectedIndex()+1)%2+1,!(Integer.parseInt((String)cmb_bits.getSelectedItem())==8),false);
try {
    inputline=AudioSystem.getTargetDataLine(format,tau.mixer.getMixerInfo());
    } catch (LineUnavailableException ex) {
        JOptionPane.showMessageDialog(this,ex.getMessage());
        }
buttonsEnable(false);
start=true;
}

private void cmb_targetdatalinesActionPerformed(java.awt.event.ActionEvent evt) {
if(cmb_targetdatalines.getItemCount()>0)
{
AudInputLine tau=(AudInputLine)cmb_targetdatalines.getSelectedItem();
jTextArea1.setText(tau.mixer.getMixerInfo().toString()+".\n"+tau.lineInfo.toString());
RefreshAudioFormats();
}
    }

private void btn_refreshActionPerformed(java.awt.event.ActionEvent evt) {
cmb_targetdatalines.removeAllItems();
RefreshInputs();
    }

//main method
public static void main(String args[]) {
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Windows".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (Exception ex) {}
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new NewJFrame().setVisible(true);
            }
        });
    }


}

How to Find Other Computers in Your Network - Java Application Programming

When you are developing some application software, you may have to search other computers or mobiles (android) in the network. Think about chatting application scenario in which the application shows the list of available computers (with the same chatting application). We will see in this post:

  • how to identify other computers in the network (with same application running)
  • how to get the IP address of those computers
  • how to tell other computers in the network, "I am here".

It is simple. We do it this way; (i) Each computer (or mobile) shouts that it is in the network (ii) Others listen to this. We make use of multicasting for this purpose. Multicasing is same as sending UDP datagrams. But still there are some minor differences. In java, we use MulticastSocket instead DatagramSocket. MulticastSocket has additional facilities to join or leave multicast groups. MulticastSocket class helps for sending and receiving IP multicast packets. In multicasting, we send DatagramPackets to one of the multicast addresses. The multicast addresses are class D IP addresses ranging from 224.0.0.0 (exclusive) to 239.255.255.255 (inclusive). A multicast group is determined by a multicast ip address and a port number. Any computer can send packets to a multicast group. But to receive packets in a multicast group, you should join that group. Really, we can't call this a broadcast. Broadcast is the term used to describe communication where packet(s) are sent from one or more devices to all other devices in the network. Multicast means sending packets from one or more devices to a set of other devices determined by a logical group (not all others).

For example, consider a group 239.0.0.73:19360. Suppose, we have chat servers and chat clients. Chat clients search for chat servers to join a chat. So the chat servers should send UDP packets (Datagram Packets) to 239.0.0.73:19360, no matter on which port the server has opened the multicast socket. But, for the receivers (clients in this example), should open multicast sockets with port number 19360 and join multicast group 239.0.0.73 to receive datagrams sent to multicast group 239.0.0.73:19360. In the following java code, we will see how to do this.

Sender

The following is the java code used by the multicast message sender (chat server in this example).

try{
MulticastSocket mcs=new MulticastSocket(); //creating multicast socket
//port number is assigned by the OS
mcs.setTimeToLive(5);
String decl="!!Chatting%%"+System.getProperty("user.name")+"^^";//broadcast message
DatagramPacket pkt=new DatagramPacket(decl.getBytes(),decl.length(),InetAddress.getByName("239.0.0.73"),19360);//multicast packet

        Socket s=null; //TCP socket for chatting
        ServerSocket ss=new ServerSocket(9999);
//TCP Serversocket to accept connection request from client
        ss.setSoTimeout(500);
        boolean connected=false;
        do{
            try{
            mcs.send(pkt);
            System.out.println("sending: "+decl);
            s=ss.accept();
            connected=true;
            System.out.println("connected to"+s);
            }catch(SocketTimeoutException eee){}
          }while(connected==false);
}catch(Exception ex){ex.printStackTrace();}

Program explanation

line 1: The sender creates a MulticastSocket at random port. The port number is assigned by OS. Port number doesn't matter since sender only needs to send packet to the multicast group, and don't want to receive from.

line 3: Sets time to live (TTL) for the multicast packets.It is the maximum number routers the packets can go through. This value is decremented at every router on the route to its destination. If the TTL field reaches zero before the datagram arrives at its destination, the packet will be dropped. If there are 10 routers between the sender and the receiver, the TTL value should be at least 10 for the packet to reach its destination.

line 4: The content of packet. Here we use !!Chatting string determine whether it is our chatting application sending this packet. We also sends the username of the sender.

line 5: Creating the datagram packet with the message. destination ip and port are set to our multicast group's ip and port.

line 7,8: We use the socket and ServerSocket for TCP chat communication later. This depends on your goal.

line 14: Sending the multicast datagram packet.

Receiver

The following is the java code to receive multicast messages (datagram packets).

try{
        MulticastSocket mcs=new MulticastSocket(19360);
        mcs.joinGroup(InetAddress.getByName("239.0.0.73"));
        byte[] bu=new byte[100];
        DatagramPacket dp=new DatagramPacket(bu,100);
        mcs.receive(dp);
        InetAddress ip=dp.getAddress();
        String sss=new String(dp.getData());
        System.out.println("Server found:"+sss.substring(sss.indexOf("%%")+2,sss.indexOf("^^")));
        s=new Socket(ip,9999);
   }catch(Exception ex){ex.printStackTrace();}

Program explanation

line 2: The client creates a MulticastSocket at port number 19360. It is the port number of our multicast group.
line 3: Joined the group using the ip 239.0.0.73.
line 6: Receiving packet.
line 7: Retrieving IP address of sender (server).
line 8: Retrieving message from datagram packet.
line 9: Extracting server users name from message
line 10: Establishing TCP connection with server using the retrieved IP