Search This Blog

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