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);
    }
}


Java Program to Display First N Terms of an Arithmetic Progression

This post contains java program to display first n terms of an AP (arithmetic progression). Generally the following equation to find nth term of arithmetic progression is used.

nth term of AP = a + (n - 1) * d

where a is first term and d is common difference. Using a loop we will display each term until we reach nth term. But here since we use a loop, for the program it is enough to keep on adding the common difference. We need not to use the above equation each time. The java program to display first n terms of a arithmetic progression (AP) is as follows:
public class APTerms {
public static void main(String[] arg)
    {
    int a,d,n;
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter first term, common difference and n (number of terms)");
    a=sc.nextInt()-(d=sc.nextInt());
    n=sc.nextInt();
    for(int i=0;i<n;i++)
        System.out.print(" "+(a+=d));
    }
}

Java Program to Display First N Terms of Geometric Progression

This post contains java program to display first n terms of a GP (geometric progression). Generally the following equation to find nth term of geometric progression is used.

Nth term of GP =  a * r(n-1)
Using a loop we will display each term until we reach nth term. But here since we use a loop, for the program it is enough to keep on multiplying with the common ratio. We need not to use the above equation each time. The java program to display first n terms of a geometric progression (GP) is as follows:

import java.util.Scanner;

public class GPTerms {
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.print("\n"+a);
    for(int i=1;i<n;i++)
        System.out.print(" "+(a*=r));
    }
}

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.

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.

How to Filter Filetypes using File Extensions in JFileChooser - Java File Chooser

how to filter files in Jfilechooser by file types or file formats using extensions in filename java codefile name file type filefilter file filter filtering files
Screenshot of following example java program
In java, to browse files or folders from the file system, we use the JFileChooser class. You can use  the JFileChooser object in two modes, save mode or open mode. Here we discuss about filtering file type by file extensions for opening the file. By default, the JFileChooser object will have an AcceptAllFileFilter. This file filter will allow the user to select file of any file type. The file filter will display text All files. If you want to restrict the file chooser to open only one type of file, you should first remove the AcceptAllFileFilter. To do this, call the following method:

myfilechooser.removeChoosableFileFilter(createoropenchooser.getAcceptAllFileFilter());


What Does Modal and Modeless (Non Modal) Mean in Java

In java, the dialogue boxes in JOptionPane class are very popular. Now when we use dialogue boxes, whether it is message dialogue box, input dialogue or any other,  we may sometimes need to make the parent container (often JFrame or JWindow) not focusable. In another words, we may have to prevent a (parent) component taking input from the user while one of its member component is active. (You may have noticed that when error message boxes are displayed, you cannot click its parent window on many software until you dismiss it by clicking 'OK' or 'close'). Such a property of a member or child component, is called modality. In java, you can use JDialog with or without modality. A JDialog can be either modal or modeless.
A Modal dialog box is a dialog box that blocks input to some other top-level windows in the application. The modal dialog box captures the window focus until it is closed, usually in response to a button press.
A Modeless dialog box is a dialog box that does not block input to any other top level window while it is shown.
See following java code example:

How to Get User Related Informations in Java

In java, there are some methods that will help you to know some user related informations. Here also,

System.getProperty() 
method can give some informations about the user like:

User account name
User Working directory
User Home directory

To get the username of current user on the computer just call

System.getProperty("user.name")

It will return the current username as a string.


To get the working directory of current user on the computer call

System.getProperty("user.dir")

It will return the path of working directory of current user as a string.


To get the home directory (user's home folder) of current user on the computer call

System.getProperty("user.home")

It will return the path to home directory (folder) of current user as a string.

How to Get Operating System Information in Java

Using java, you can gather some information about the operating system of the computer system on which the code is running. That us java provides some API classes that will help you to know about the operating system of the computer on which your application program is running. You can use System.getProperty() method for this purpose. There are some system property keys (strings) which can be used to get the respective information. The parameter to the System.getProperty() method is a string, the property key. The following values for the parameter string will give operating system related informations.

"os.arch"
Operating system architecture

"os.name"
Name of the operating system.

"os.version"
Version of Operating system.

Usage examples:

The following java program displays the Operating system related informations using getProperty() method.
System.out.println("Operating system architecture:"+System.getProperty("os.arch") ); System.out.println("Operating system Name:"+System.getProperty("os.name") ); System.out.println("Operating system version:"+System.getProperty("os.version") );

How to Get JRE installation Directory in a Java Application

To get the java runtime environment (JRE) installation directory of a computer, we can use the getProperty() method in System class. The key to be used for System.getProperty() method to get the java JRE installation directory is "java.home". System.getProperty("java.home") will return the java runtime environment(JRE) installation directory path as a string. the following code will display the jre installation directory path:


System.out.println(System.getProperty("java.home"));

How to Get Class Path in a Java Application


Class Path is the Path used to find directories and JAR archives containing class files. Elements of the class path are separated by platform-specific characters. To get class path from a running java application, you may use the getProperty() method in System class. The following java code will show you how to get class path in java.

String classpath=System.getProperty("java.class.path");
System.out.println("Class path="+ classpath);

Why FileOutputStream or BufferedWriter Does Not Write New Line to File

The new-line character is system dependent. It depends on operating system. It can be \n, \r, \r\n or something else depending on the operating system. So, when we are writing a cross platform java program, it is important to take care when we use a line separator or new line character. It is always safe to use system specific line separator provided by JVM. You can get the system specific newline character in different ways.

Method 1:

System.lineSeparator() instead of new line character. The java method Sytem.lineSeparator() returns the newline character (line separator) as a strong. If you are appending a string on another with a line separator in between, it can be done as follows.

line1+System.lineSeparator()+line2

Method 2:

You can also get the line separator using the getProperty() method with property key line.separator.

System.getProperty("line.separator");

Method 3:

If your are using a BufferedReader object to write text into a file, you can use the newLine() method to write a newline into the file. If br is a BufferedReader object, br.newLine() will write a newline (line separator) into the file.

Method 4:

If you want to get the line separator as a character, you may use the static member Character.LINE_SEPARATOR. It returns the Unicode newline character.

How to Make a Timer Controlled Progress Bar in Java

Java progress bar value updated using timer. update JProgressBar by thread, set progress of progress bar using timer thread
timer controlled progress bar in java
For some applications we require to use timer and progress-bars. Java has a swing class called
JProgressBar to create progress bars. It can have horizontal or vertical orientation. We can set the maximum and minimum values for JProgressBar. It can also have an indeterminate state in which the progressbar does not show a definite value and plays an animation to show that the process is in progress. JProgressBar can be used in indeterminate mode when neither can you determine how long a process would take to complete nor can you track its progress. In some other cases, you may have to use timers. Java provides a Timer class (Java.util.Timer). But you can create a very simple and flexible timer if you want. If the timer does not have crucial importance, you can use a thread that sleeps for every one second as a timer. I have been using such threads as timers for a long time and never failed. Such timers may fail (although very rarely) when the processor has very heavy workload.

Whatever, in a simple example, we will see how to create a timer using thread and how to use JProgressBar. In this example we control the JProgressBar using the timer. The progress in JProgressBar is set calling the method setValue(). In this example we are using a 1 minute timer. The progress bar should show the progress of timer. The java code for timer controlled JProgressBar is as follows:

Problem With JProgressBar setValue Method? JProgressBar Value Not Updating - Solution

I had a problem with a JProgressBar. I called setValue() method of the java swing class JProgressBar for an object but the JProgressBar is still sowing zero progress.This problem may occur for many people. People use the words:

Jprogressbar setvalue not upadting
jprogressbar.setvalue not working
jprogressbar setvalue problem

for googling this problem. All these keyword combinations have a presumption that the problem is with java not on our part, Actually, the problem is on our part but it is a silly mistake. I know two reasons for such problem.

Java Program to Send Image between Computers using UDP and Display it

java program java code java application to send image files (photos or pictures) between computer using UDP across Network
Java program to send image file over network using UDP
This was one of my experiments in Networking Lab. The aim was to write a java program to send a
picture (image) from a computer to another via network using UDP protocol and to display it at the receiving end. Simply, this is the java code to make a java application which can send images from one computer to another over a network. The program uses UDP (User Datagram Protocol). For both the computers (on either ends) the same code is enough. This app can act as a image sender or a receiver. The program uses a Progress bar (JProgressBar) to show the progress of the data transfer. Remember, transferring files over UDP is not easy because UDP does not guarantee ordered delivery, and not even successful delivery. So, here in this program, to ensure ordered delivery, the sender sends next chunk of data (DatagramPacket) only after receiving an acknowledgement for last sent packet. For acknowledgement, i used a string "ACK".

Chat Room Application using UDP in Java

UDP chatroom application in java source code Chatting using java UDP java chat application java group chat application
Java Chat room application using UDP
The following is a Java program for chatting. This chatting application uses UDP (User Datagram
Protocol) for chatting. The application gives you to options. One is to create a new chat room and the other is to join a chat room. The one who creates the chat room acts as a server for the chatroom. Others can join this chatroom id they know his IP address. This simple java chat room application is enough for server and clients. The GUI is basic one and not too attractive. Also i have used JOptionPane to reduce code. You may make improvements to the code. The chat rooms are not password protected. Anyone who know the server's IP address are granted access to the chat room. If you wish, you may improve the program. This Group chat application using java can be used in Local area networks. This code for java group chat program can be modified to enable chatting in multiple chat rooms. Try it.

How to download a file from internet Using java if URL is Given

Let us see how to download a file from internet in java. It is so simple. The following java program is a program which will download any file if the URL to the file to be downloaded is given. It also asks the user for destination to save the file. It displays the file size also. It also prints (displays) the progress of download. It uses the classes HttpURLConnection, URL, FileOutputStream, JFileChooser etc. The following java code is a simple java program to download a file from internet using URL. Here in this case, user has to give the file name and extension.


How to Easily Copy a File to Another File or Location in Java

The Files class in java has many useful static methods to copy and move files, create temporary files or folders etc. To copy a file from one location to another in Java, there is a static method copy in Files class. The Files class is in java.nio.file package. The method Files.copy() takes three arguments (parameters) : Path of source file (as object of Path class), Path of destination file ( as object of Path class ) and an option parameter. The option parameter can be one of the following:

StandardCopyOption.REPLACE_EXISTING
If the target file exists, then the target file is replaced.

StandardCopyOption.COPY_ATTRIBUTES
Attempts to copy the file attributes associated with this file to the target file. The exact file attributes
that are copied is platform and file system dependent and therefore unspecified.

StandardCopyOption.NOFOLLOW_LINKS
Symbolic links are not followed. If the file is a symbolic link, then the symbolic link itself, not the target of the link, is copied.

You have to import java.nio.file.StandardCopyOption to use option parameters.

try{
File sourcefile=new File("audio.mp3");
File destination=new File(System.getProperty("java.io.tmpdir")+"\\temp.mp3");
Files.copy(sourcefile.toPath(),destination.toPath(),StandardCopyOption.COPY_ATTRIBUTES);
} catch (IOException ex) {
ex.printStackTrace();
}

For the copy method, there are two other overloaded method definitions. In one, instead of source file's path, inputstream is the first parameter and the rest are same. For the other overloaded definition, an outputstream object is the second parameter instead of destination path object and the rest are same.

Similarly, to move a file from one location to another, there is a method move() in Files class. The parameters of this method is also same as those of copy method.

How to Get Path to Temp Directory for Current User in Java

In some cases, you may need to create temporary files. It is preferred to create temporary files and folders in the current user's temporary folder (temp directory) because, the user will be able to clean unwanted files. To get the path to the temp folder of current user, java provides a property key to be used with

System.getProperty()
. it is
"java.io.tmpdir"
.


The following code displays the path to the temporary folder for the current user.
System.out.println("temp directory ="+System.getProperty("java.io.tmpdir"));

How to Get Center Point of Screen in Java

If you want position your JFrame in center of screen, there is method for that. Read this post:

The LocalGraphicsEnvironment in Java will give you the center point of the display or screen. There is a static method getLocalGraphicsEnvironment() in GraphicsEnvironment class. To get the center point of the screen, you may use the following java code:


Point centre=GraphicsEnvironment.getLocalGraphicsEnvironment().getCenterPoint();

You should include these import statements in the file.

import java.awt.Point; import java.awt.GraphicsEnvironment;

How to Set JFrame in Center of Screen

By default, a java application appears at top left corner of the screen. You might have seen that most of the applications appear in the middle of the screen. I will tell you how to center your java application on screen.

To set JFrame in center of Just call this.setLocationRelativeTo(null); in constructor of the JFrame. If you are using Netbeans IDE, it should be after calling initComponents() method. But if you call setLocation() method of JFrame after this, your JFrame will get relocated.

In most cases this works and this is enough. if you want to get the center point of the screen, just refer to the following post:

How to Get Center Point of Screen in Java

How to Set Background Color of a JFrame in Java

It is easy to set Background color of a JFrame in java. But still many people cannot do it (me too was once like this). Most such people may have tried this java code to set java JFrame background color: setBackground(Color.BLACK);. But this won't work. Instead, you should set the background color of the ContentPane of the JFrame. So, use the following code to set Background color of Frame in your Java Application.

getContentPane().setBackground(Color.BLACK);

or


getContentPane().setBackground(new Color(34,172,176));

Keep in mind that you have to import java.awt.Color; You can use the first one if you don't know RGB values of the desired color. Most common colors are defined as constants in Font class. If you know the RGB color values for your desired color, you can use the second example.

How to Change Look and Feel of a Java Application

The following code fragment which can be used within main method or in constructor of the class tells you how to change the look and feel of a java program (java application). This sample code sets the LookAndFeel of the java application into Windows Look and Feel.


Java Application Source Code to Scroll Text Along JFrame

This is a simple java program for beginners to show how to scroll text in the JFrame. The program uses an anonymous (unnamed) thread object to move the scroll or move the text. The Thread moves two JLabel objects (containing text) by repeatedly calling setLocation(int x, int y) method of JLabel. The speed of the motion of text in this program can be changed by changing value of i or changing sleep period of the thread.


Free, Simple and Light weight Download Manager Java Application - Application and Source Code

This is a free Internet Download Manager Application for PC developed in java and free to use. It is
very light weight with size only below 50KB. This download manager allows pause and resume for downloads and requires java jre 1.8 to run. The program source code is given below. This will help you to understand how to download files from internet using java. The program may help you to understand how to pause and resume downloads in a java program. The application also provides drag and drop support. You can drag a link to file to be downloaded from browser in to the drag and drop area (drop target) in the application and it will automatically start download or add to the download queue. This will also help you study how to use Drag and Drop and how to set a drop target.

Download free Download Manager Application for Computer


You may download the  lightweight java Download Manager Software from following link:

https://drive.google.com/file/d/0B5WYaNmq5rbueUl5bW03VllIc2M/view?usp=sharing

View Source code


Free Two Person Text Chatting Application Software for Local Networks using Java With Source Code

two person text chat program java program java code java source code program code free chatting application free local network chatting free LAN Chatting LAN messenger
Java text Chatting program
Free two person chat program for local networks. This java text chatting application can be used for two person chatting within private or local networks. This java application uses TCP connection.

How to use

Both users should open this java application in their computer. One of them should click Make a Connection  while the other should enter the first person's ip address in the textfield provided and click Connect to this IP.

YouTube Video Locator For YouTube Partners (Uploaders) to Check Keyword Optimisation in YouTube

In this post, i am sharing an application which will help you to check the search engine optimization of your youtube video. The inputs for this java application are your channel address and the keywords to search for. The application will tell you in which page does your video come for that combination of keywords. This app was coded by myself when i was a youtube uploader. This can be useful for YouTube partners (uploaders). You require JRE 1.8 or later installed in your computer to run this lightweight application software. You can locate your video in youtube search results and check how much search optimised is your video for the given keyword. You can download the java application from following link.

Download YTViewer Youtube Video Locator for YouTube Partners (YouTube upoaders)

Bank Application in Java - Simulation of Banking Services in Java

Java Banking services simulation application java program java source code java code java simple sample banking application banking software
Java Banking services simulation application
This is a simple bank simulation application in java. The application first asks username and password. The default username and password for the application :

username: operator1
password: password

You can change this username and password in the application. This java bank application software supports following banking services.


  • Opening a new account
  • Money Withdrawal from the bank account
  • Making Deposits in the accout
  • Transfer of funds


TCP Server Client Two Person Chat Program in Java with GUI

Server-Client chat program or two way chat using TCP connection is a common problem for java practical labs or networking labs. Here this post introduces a simple lightweight Server client two person chat program using java. The program uses ServerSocket and Socket classes available in java.net package. This program is written so as to use the same as server or as client. Both the persons who chat use the same program. One should select hosting (acting as server) while the other could connect to him by entering the server ip address. I have added screenshots of the program also.
See Screenshots

Simple Pause and Resume Supported Download Manager using Java

In this post i am adding a simple download manager made using java programming language. The file is light weight. This java application supports pause and resume. You can resume a paused download at any time if the url is resume supported. This java desktop application maintains a simple download queue. You can directly drag and drop download links into this java download manager app or add paste links. When the app exits, it saves it current progress and download queue so that you can easily resume the download in this java download manager desktop app when you start the application later.
free download manager for computer in java. lightweight and compact
Free Java Download Manager for 

Features:

  • Light weight
  • Pause and resume supported
  • Drag and drop download links
  • Download queuing supported.
  • Source code available


Download DownloadManager.jar (app) here.


Clock Application using Java - Java Source Code for Analog Clock Application

For my java practical lab experiments, i had to create an analog clock using java. So, i created a
Java analogue clock application applicaion program source code Analogue clock using java programming language. Analog clock application using java
Analog Clock Application using Java.
simple analog clock using java. The program source code is added below. It makes use of java 2D Graphics Object and draws the clock in the screen. The clock displays all the three hands (hour hand, second hand and minute hand). The program source code is as follows. The screenshot of the java analog clock application is also added.

Simple Java Calculator Program Using Java Applet

Java calculator application using java applet JAppet and Swing components. how to make Simple java calculator applet. Java program source code for simple calculator applet
Screenshot of Simple calculator applet in java
This post shows a sample Calculator Program using Java Applet. This program uses the JApplet Class and Swing components in the program. The full source code is given below. This is a java Applet program for a simple calculator with operations addition, subtraction, division and multiplication on floating point numbers. It also have the C (clear) button. This Java Calculator applet was created by myself for my practical lab experiment. I think this may be useful for beginners in java.

How to Remove Title bar from JFrame of Java Application

To remove the title bar completely, there is a method called setUndecorated() in java. It takes a boolean variable. If the boolean is true, the title bar will be removed. The following one is an example. The method setUndecorated() invoked with a true boolean argument, will remove the title bar from the JFrame MyJFrame. The method is called here from the constructor. You may call it anywhere from within the class scope.

How to Close or Exit a Java App When some Button is Clicked

To close a Java app, System.exit() can be used. This function can be used to close the app if an error occurs or no error is occurred. If no, error occurred, the argument  of the function should be 0. This method terminates the currently running Java Virtual Machine. The argument stands for status code; by convention, a nonzero status code indicates abnormal termination. If you are calling the System.exit() function without any errors (in normal case), just give the argument as zero. This method calls the exit method in class Runtime.

How to Use System.getProperty() - Keys for System Properties

There is a method getProperty() in System class in java. As the name indicates, this java method is used to get System specific, operating system specific or user specific properties. There are different keys which are strings passed as parameter to the getProperty() method.

Usage

The following sample java code will show you how to use the getProperty method in System class. The key is a string. The System.getProperty() method takes a string parameter (argument). Based on the string passed, the method System.getProperty() returns different properties as string. In this example,we pass "java.io.tmpdir" as the parameter, which is the key to get the temporary directory (temp directory) for the current user account.

String property = "java.io.tmpdir"; String tempDir = System.getProperty(property); System.out.println("temp directory ="+ tempDir );


Similarly, for each property, there is a key. Below, the keys for different properties are listed.
"file.separator"
Gives the character that separates components of a file path. This is "/" on UNIX and "\" on Windows. This character is used in File paths for cross platform java applications
"java.class.path"
Returns the path used to find directories and JAR archives containing class files. Elements of the class path are separated by a platform-specific character specified in the path.separator property.
"java.home"
Returns the installation directory for Java Runtime Environment (JRE)
"java.vendor"
Returns the name of JRE vendor
"java.vendor.url"
Returns the URL of JRE vendor
"java.version"
Returns the version number of JRE
"line.separator"
Returns the character sequence used by operating system to separate lines in text files. This is operating system specific. It can be '\n', '\r' or "\r\n".
"os.arch"
Returns the operating system architecture
"os.name"
Returns the name of the Operating system
"os.version"
Returns the version of the Opposing system.
"path.separator"
Returns path separator character used in java.class.path
"user.dir"
Returns the path to the working directory of current user in the computer.
"user.home"
Returns the path to the home directory of current user.
"user.name"
Returns the name of current user (user account name)