Search This Blog

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

Java Program to Display a String in Reverse Order Without Using Loop or Another Array

In this post, we will see a java program to reverse a string without using any loops or temporary array. Such programming questions are often asked in interviews. It is so simple. We make use of recursion to store the string temporarily. Actually, we do not use any loop. We can easily do it without using any loops. Nor we need to declare an extra array. But when we make use of recursion, stack is used internally for calling each instance of the recursive method. Remember, we should not use the reverse method in StringBuilder class or StringBuffer class. The following java program displays the string in reverse order.


import java.util.Scanner;

public class StrRev{
static int len;
static String str;

static void recurse(int i)
{
    if(i<len-1)
        recurse(i+1);
    System.out.print(str.charAt(i));
}

public static void main(String[] arg)
    {
    System.out.println("Enter string");
    Scanner sc = new Scanner(System.in);
    str=sc.nextLine();
    len=str.length();
    recurse(0);
    }
}

In the above java program we just displayed the string in reverse order. we did not reverse the string in memory. In the following java program, we will see how to rearrange the string in reverse order without using any loops or extra arrays.

import java.util.Scanner;

public class StrRev{
static int len;
static char[] str;

static void recurse(int i)
{
    char a=str[i];
    if(i<len-1)
        recurse(i+1);
    str[len-i-1]=a;
}

public static void main(String[] arg)
    {
    System.out.println("Enter string");
    Scanner sc = new Scanner(System.in);
    str=sc.nextLine().toCharArray();
    len=str.length;
    recurse(0);
    System.out.println(String.copyValueOf(str));
    }
}

In the above java program, we stored the input string initially as a character array. Using a recursive method, we rearranged the character array in reverse order. Then we displayed the character array as a string

Java Program to Find Minimum of Two Numbers

Java Program to compare three numbers and display the minimum of two numbers. Here, we will see a simple java program to display the smaller number among two input numbers. This program takes first input as the number of sets of numbers (a set contains two numbers whose minimum is to be displayed). Then it takes numbers as sets of 2 numbers. For every pair of numbers, the java program displays the smaller number. The following java program does it. It makes use of the ternary operator (conditional operator) and Scanner class in java.


import java.util.Scanner;

public class MinofTwo {

public static void main(String[] arg)   
    {
    Scanner sc = new Scanner(System.in);
    int n=sc.nextInt(),a,b;
    while(n>0)
        {
        System.out.println((a=sc.nextInt())<(b=sc.nextInt())?a:b);
        n--;
        }
    }
}

Java Program to Find Minimum of Three

It is the basics of any programming language to compare three numbers and display the minimum of the three. Here, we will see a short java program to display the smallest number among three input numbers. This program takes first input as the number of sets of numbers (a set contains three numbers whose minimum is to be displayed). Then it takes numbers as sets of three numbers. for every three number, the java program displays the smallest of them. The following program does it. It makes use of the ternary operator (conditional operator) and Scanner class.

import java.util.Scanner;

public class MinOfThree {
public static void main(String[] arg)
 
    {
    Scanner sc = new Scanner(System.in);
    int n=sc.nextInt(),a,b,c;
    while(n>0)
        {
        if((a=sc.nextInt())>(b=sc.nextInt()))
            System.out.println(b<(c=sc.nextInt())?b:c);
        else
            System.out.println(a<(c=sc.nextInt())?a:c);
        n--;
        }
    }
}


Java Program to Reverse a String

Here, we will see a java program to reverse a string. The string is read and is displayed in reverse order. Java program to display an input string in reverse order.


import java.util.Scanner;

public class BMI {
public static void main(String[] arg)
    {
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter a string");
    String s=sc.nextLine();
    for(int i=s.length()-1;i>=0;i--)
            System.out.print(s.charAt(i));
    }
}

Java Program to Find Sum of First N Terms of an Arithmetic Progression

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

sum of first n terms = (n / 2) * (2 * a + (n - 1) * d)
sum of first n terms of an arithmetic progression, equation to find sum of an ap,
Sum of first n terms of an AP (arithmetic progression)

Now, we will see a java program to find sum of first n terms of an AP. The java program is as follows:


import java.util.Scanner;

public class SumofAP {
public static void main(String[] arg)
    {
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter first term, common difference and n (number of terms)");
    int a=sc.nextInt(),d=sc.nextInt(),n=sc.nextInt();
    System.out.print("Sum: "+n*(2*a+(n-1)*d)/2);
    }
}