Free Data Structures and Algorithms Course









Subscribe below and get all best seller courses for free !!!










OR



Subscribe to all free courses

How to calculate Area of Triangle through a Java program ?.

Program to calculate Area of Triangle in Java



import java.util.Scanner;

public class Triangle {

   public static void main(String[] args) {
      Scanner input = new Scanner(System.in);

      double base = 0;
      double height = 0;
      double area = 0;

      System.out.print("Enter the length of base of triangle : "); 
      base = input.nextDouble();

      System.out.print("Enter the length of height of triangle : "); 
      height = input.nextDouble();

      area = (base * height) / 2;
    
      System.out.println("");
      System.out.println("The Area of Triangle is : "
                  + area);

   }

}


Output of the program : 


Program to demonstrate three dimensional Array in Java

Program to demonstrate three dimensional Array in Java

import java.util.Scanner;

public class ThreeDimensionalArrayDemo {
   public static void main(String args[]) {

       Scanner input = new Scanner(System.in);
  
       int threeDArray[][][] = new int[10][10][10];
       int i = 0, j = 0, k = 0;
  
       System.out.print("Enter the value of i : "); 
       i = input.nextInt();

       System.out.print("Enter the value of j : "); 
       j = input.nextInt();
        
       System.out.print("Enter the value of k : "); 
       k = input.nextInt();
  
       System.out.println("");
  
       for(int m=0; m < i; m++) 
  for(int n=0; n < j; n++)
    for(int p=0; p < k; p++)
      threeDArray[m][n][p] = m * n * p;

       for(int m=0; m < i; m++) {
  for(int n=0; n < j; n++) {
    for(int p=0; p < k; p++) 
      System.out.print(threeDArray[m][n][p] + " "); 
    System.out.println();
  }
  System.out.println();
  }
       }
}

Output of the program : 


 

How Cast Operator works in Java with example ?

Program to demonstrate how Cast Operator works in Java.

public class CastOperator {

  public static void main(String args[]) {
    
     byte b =0;
     int i = 358;
     double d = 462.142;

     System.out.println("Conversion of int to byte: ");
     b = (byte) i;
     System.out.println("i = "+ i +" and b = "+ b);

     System.out.println();
  
     System.out.println("Conversion of double to int: ");
     i = (int) d;
     System.out.println("d = "+ d +" and i = "+ i);
  
     System.out.println();
  
     System.out.println("Conversion of double to byte: ");
     b = (byte) d;
     System.out.println("d = "+ d +" and b = "+ b);
  }
}



Output of the program : 





How to calculate length of hypotenuse of a right angle triangle given the value of base and height in Java ?

Program to calculate length of hypotenuse of a right angle triangle given the value of base and height

Click here to download complete source code  
import java.util.Scanner;

public class RightAngledTriangle 
{
  public static void main(String[] args)
  {
    Scanner input = new Scanner(System.in);

    double hypotenuse = 0;
    double base = 0;
    double height = 0;
  
    System.out.print("Enter the value of base : "); 
    base = input.nextDouble();

    System.out.print("Enter the value of height : "); 
    height = input.nextDouble();

    hypotenuse = Math.sqrt(base * base + height * height);

    System.out.println("");
    System.out.println("The hypotenuse of right-angled triangle is :"
                       + hypotenuse);
  } 
}
Output of the program : 
  

Program to demonstrate how Constructor works in Java ?

A Simple Java program demonstrating how a Constructor works in Java :

package com.hubberspot.objects.example;

class IPL {
  IPL() {  // Constructor 
    System.out.println("This season's IPL teams are :");
    System.out.println("1. Deccan Chargers");
    System.out.println("2. Kolkata Night Riders");
    System.out.println("3. Mumbai Indians");
    System.out.println("4. Chennai Super Kings");
    System.out.println("5. Rajasthan Royals");
    System.out.println("6. Royal Challengers Bangalore");
    System.out.println("7. Kings XI Punjab");
    System.out.println("8. Pune Warriors India");
    System.out.println("9. Delhi Daredevils");
  }
}

public class SimpleConstructor {
  public static void main(String[] args) {
    new IPL();
  }
} 

Output of the program :



How to calculate Volume and Surface Area of Cube in Java ?

Program to calculate Volume and Surface Area of Cube in Java ?

package com.hubberspot.mensuration.example;

import java.util.Scanner;

public class Cube {

  public static void main(String[] args) {
    Scanner input = new Scanner(System.in);

    double edge = 0;

    double volume = 0;
    double surfaceArea = 0;
 
    System.out.print("Enter the length of edge of Cube : "); 
    edge = input.nextDouble();

    volume = (edge * edge * edge);
    surfaceArea = 6 * (edge * edge);

    System.out.println("");
    System.out.println("The Volume of Cube is : " + volume);
    System.out.println("The Surface Area of Cube is : " + surfaceArea);
  }

}


Output of the program :



How to calculate Volume and Surface Area of Cuboid in Java ?

Program to calculate Volume and Surface Area of Cuboid in Java ?

package com.hubberspot.mensuration.example;

import java.util.Scanner;

public class Cuboid {

  public static void main(String[] args) {
    Scanner input = new Scanner(System.in);

    double length = 0;
    double breadth = 0;
    double height = 0;

    double volume = 0;
    double surfaceArea = 0;

    System.out.print("Enter the length of Cuboid : "); 
    length = input.nextDouble();

    System.out.print("Enter the breadth of Cuboid : "); 
    breadth = input.nextDouble();

    System.out.print("Enter the height of Cuboid : "); 
    height = input.nextDouble();

    volume = (length * breadth * height);
    surfaceArea = 2 * (length * breadth + breadth * height + height * length);
  
    System.out.println("");
    System.out.println("The Volume of Cuboid is : " + volume);
    System.out.println("The Surface Area of Cuboid is : " + surfaceArea);

 }
}

Output of the program :



How to find average of N numbers through a Java program ?.

A simple Java program to find average of N numbers





package com.hubberspot.sample.example;

import java.util.Scanner;

public class Average {
  public static void main(String[] args) {
    
    Scanner input = new Scanner(System.in);  
    System.out.print("Enter N number of elements " +
   "for finding average : "); 
 
    final int elements = input.nextInt();;
    System.out.println(""); 
 
    double[] numbers = new double[elements];
    double sum = 0;

    
    for (int i = 0; i < elements; i++) {
      System.out.print("Enter number "+(i+1)+" : " );
      numbers[i] = input.nextDouble();
      sum += numbers[i];
    }
    
    double average = sum / elements;
    
    System.out.println(""); 
    System.out.println("Average is " + average);
    
  }
}
Output of the program : 


 

EOFException : Program to detect end of file in Java

Program to demonstrate EOFException and a way to detect end of file in Java.

package com.hubberspot.exception.example;

import java.io.*;

public class EndOfFileDetection { 
  public static void main(String[] args) {
    try {
      DataOutputStream output = new DataOutputStream
        (new FileOutputStream("C://EndOfFile.dat"));
      output.writeChars("Welcome ") ;
      output.writeChars("to ") ;
      output.writeChars("Hubberspot !.") ;
      output.close();
      
      DataInputStream input = new DataInputStream
        (new FileInputStream("C://EndOfFile.dat"));
      while (true) {
        System.out.print(input.readChar());
      }
    }
    catch (EOFException ex) {
      System.out.println("");
      System.out.println("All data read");
    }
    catch (IOException ex) {
      ex.printStackTrace();
    }
  }
}


Output of the program :



How to check whether a string is a Palindrome or not through a Java program ?.

Program demonstrating simple Palindrome test for a string through a simple Java code.

package com.hubberspot.string.example;

import java.util.Scanner;

public class PalindromeTest {

  public static void main(String[] args) {

    Scanner input = new Scanner(System.in);

    System.out.print("Enter a string to test : ");
    String string = input.nextLine();

    if (palindromeCheck(string))
      System.out.println(string + " is a palindrome");
    else
      System.out.println(string + " is not a palindrome");
    }

  public static boolean palindromeCheck(String string) {

    int low = 0;

    int high = string.length() - 1;

    while (low < high) {
       if (string.charAt(low) != string.charAt(high))
   return false; 

       low++;
       high--;
    }

    return true; 
  }
}

Output of the program : 


 




Video tutorial to demonstrate how to check whether a given string is palindrome or not through a Java program.








How to solve Simple Quadratic Equation in Java ?.

Program to solve Simple Quadratic Equation in Java.





Click here to download complete source code 


import java.util.Scanner;

public class Quadratic
{
  public static void main(String[] args)
  {
    Scanner input = new Scanner(System.in);
  
    double a = 0;
    double b = 0;
    double c = 0;
    double discriminant = 0;
    double d = 0;
  
    System.out.print("Enter the value of a : "); 
    a = input.nextDouble();

    System.out.print("Enter the value of b : "); 
    b = input.nextDouble();

    System.out.print("Enter the value of c : "); 
    c = input.nextDouble();
  
    discriminant = (b * b - 4 * a * c);
  
    d = Math.sqrt(discriminant);
  
    if (discriminant >= 0.0) {
       System.out.println("First root of the equation : "
                   +(-b + d) / (2.0*a));
       
       System.out.println("Second root of the equation : "
                   +(-b - d) / (2.0*a));
    } 
    else 
    {
       System.out.println("The roots are not real numbers.");
    }
  }
} 



Click here to download complete source code 


Output of the program : 
 

How to calculate Nth term and Sum of Arithmetic Progression in Java ?.

Program to calculate Nth term and Sum of Arithmetic Progression in Java

import java.util.Scanner;

public class ArithmeticProgression {
  public static void main(String[] args)
  {
    Scanner input = new Scanner(System.in);

    double firstTerm = 0;
    double numberOfTerms = 0;
    double nthTerm = 0;
    double commonDifference = 0;
    double  sum= 0;
    double term = 0;

    System.out.print("Enter the value of a (First Term) : "); 
    firstTerm = input.nextDouble();

    System.out.print("Enter the value of d (Common Difference) : "); 
    commonDifference = input.nextDouble();

    System.out.print("Enter the value of n (Number of terms) : "); 
    numberOfTerms = input.nextDouble();

    nthTerm = firstTerm + (numberOfTerms - 1) * commonDifference;

    sum = numberOfTerms * (2 * firstTerm + (numberOfTerms - 1) * commonDifference)/2;

    System.out.println("");
    System.out.println("The Arithmetic Progression is as follows :");

    for(int i = 0; i < numberOfTerms; i++){
      term = firstTerm + i * commonDifference;
      System.out.print(term+" + ");
    }

    System.out.println("...");
    System.out.println("The nthTerm of the series : " + nthTerm);
    System.out.println("The Sum of n terms of series : " + sum);
  }
}
Output of the program : 


 

Program to demonstrate how a simple Enum works in Java ?

A Simple Java program demonstrating how a simple Enum works in Java :

package com.hubberspot.objects.example;

enum IplTeams {
        DeccanChargers, KolkataNightRiders, 
 MumbaiIndians, ChennaiSuperKings, 
 RajasthanRoyals, RoyalChallengersBangalore,
 KingsXIPunjab, PuneWarriorsIndia,
 DelhiDaredevils
};

public class SimpleEnumDemo {
  public static void main(String[] args) {
    IplTeams team1 = IplTeams.MumbaiIndians;
    IplTeams team2 = IplTeams.DeccanChargers;
    IplTeams team3 = IplTeams.KolkataNightRiders;
    IplTeams team4 = IplTeams.ChennaiSuperKings;
    IplTeams team5 = IplTeams.RajasthanRoyals;
    IplTeams team6 = IplTeams.RoyalChallengersBangalore;
    IplTeams team7 = IplTeams.KingsXIPunjab;
    IplTeams team8 = IplTeams.PuneWarriorsIndia;
    IplTeams team9 = IplTeams.DelhiDaredevils;
    
    System.out.println("This Season's IPL teams are :");
    System.out.println("1. "+team1);
    System.out.println("2. "+team2);
    System.out.println("3. "+team3);
    System.out.println("4. "+team4);
    System.out.println("5. "+team5);
    System.out.println("6. "+team6);
    System.out.println("7. "+team7);
    System.out.println("8. "+team8);
    System.out.println("9. "+team9);
  }
}


Output of the program :





How to calculate Volume, Curved Surface Area and Total Surface Area of Hemisphere in Java ?

Program to calculate Volume, Curved Surface Area and Total Surface Area of Hemisphere in Java

package com.hubberspot.mensuration.example;

import java.util.Scanner;

public class Hemisphere {

  public static void main(String[] args) {
    Scanner input = new Scanner(System.in);

    double radius = 0;
  
    double volume = 0;
    double curvedSurfaceArea = 0;
    double totalSurfaceArea = 0;

    System.out.print("Enter the radius of Hemisphere : "); 
    radius = input.nextDouble();

    volume = (2 * Math.PI * radius * radius * radius) / 3;
  
    curvedSurfaceArea = 2 * (Math.PI * radius * radius);
  
    totalSurfaceArea = 3 * (Math.PI * radius * radius);

    System.out.println("");
    System.out.println("The Volume of Hemisphere is : " + volume);
    System.out.println("The Curved Surface Area of Hemisphere is : "
   + curvedSurfaceArea);
    System.out.println("The Total Surface Area of Hemisphere is : "
   + totalSurfaceArea);


  }

}

Output of the program : 


How to calculate Volume and Surface Area of Sphere in Java ?

Program to calculate Volume and Surface Area of Sphere in Java

Click here to download complete source code

package com.hubberspot.mensuration.example;

import java.util.Scanner;

public class Sphere {
 
  public static void main(String[] args) {
    Scanner input = new Scanner(System.in);

    double radius = 0;
   
    double volume = 0;
    double surfaceArea = 0;

    System.out.print("Enter the radius of Sphere : "); 
    radius = input.nextDouble();

    volume = (4 * Math.PI * radius * radius * radius) / 3;
   
    surfaceArea = 4 * Math.PI * radius * radius;
   
    System.out.println("");
    System.out.println("The Volume of Sphere is : " + volume);
    System.out.println("The Surface Area of Sphere is : " + surfaceArea);


  }

}


Click here to download complete source code

Output of the program : 


How to calculate Volume, Curved Surface Area and Total Surface Area of Cone in Java ?

Program to calculate Volume, Curved Surface Area and Total Surface Area of Cone in Java

package com.hubberspot.mensuration.example;

import java.util.Scanner;


public class Cone {
   public static void main(String[] args) {
      Scanner input = new Scanner(System.in);

      double radius = 0;
      double height = 0;
        
      double slantHeight = 0;
      double volume = 0;
      double curvedSurfaceArea = 0;
      double totalSurfaceArea = 0;

      System.out.print("Enter the radius of base of Cone : "); 
      radius = input.nextDouble();

      System.out.print("Enter the height of Cone : "); 
      height = input.nextDouble();

      volume = (Math.PI * radius * radius * height) / 3;
  
      slantHeight = Math.sqrt(height * height + radius * radius);
  
      curvedSurfaceArea = (Math.PI * radius * slantHeight);
  
      totalSurfaceArea = Math.PI * radius * (radius + slantHeight);

      System.out.println("");
      System.out.println("The Slant height of Cone is : " + slantHeight);
      System.out.println("The Volume of Cone is : " + volume);
      System.out.println("The Curved Surface Area of Cone is : "
   + curvedSurfaceArea);
      System.out.println("The Total Surface Area of Cone is : "
   + totalSurfaceArea);


  }

}



Output of the program :


How to calculate Compound Interest in Java ?.

Program to calculate Compound Interest in Java

import java.util.Scanner;

public class CompoundInterest {

   public static void main(String[] args) {
      Scanner input = new Scanner(System.in);

      double principal = 0;
      double rate = 0;
      double time = 0;

      double compoundInterest = 0;
  
      System.out.print("Enter the Principal amount : "); 
      principal = input.nextDouble();

      System.out.print("Enter the Rate : "); 
      rate = input.nextDouble();

      System.out.print("Enter the Time : "); 
      time = input.nextDouble();

      compoundInterest = principal * Math.pow((1 + rate/100),time); 
  
      System.out.println("");
      System.out.println("The Compound Interest is : "
     + compoundInterest);
  
   }

}






Output of the program :



How to calculate Simple Interest in Java ?.

Program to calculate Simple Interest in Java

import java.util.Scanner;

public class SimpleInterest {

  public static void main(String[] args) {
    Scanner input = new Scanner(System.in);

    double principal = 0;
    double rate = 0;
    double time = 0;

    double simpleInterest = 0;
  
    System.out.print("Enter the Principal amount : "); 
    principal = input.nextDouble();

    System.out.print("Enter the Rate : "); 
    rate = input.nextDouble();

    System.out.print("Enter the Time : "); 
    time = input.nextDouble();

    simpleInterest = (principal * rate * time) / 100;
    
    System.out.println("");
    System.out.println("The Simple Interest is : "
                        + simpleInterest);
  
  }

}


Output of the program :

















Watch the above Java tutorial on Youtube video :

 

How to implement JSplitPane into a Frame in Java using Swing API?.

A Simple program demonstrating the working of JSplitPane in Java using Swing framework.

package com.hubberspot.swing.example;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class SplitPaneDemo extends JFrame {

  static String text = "This is a simple program that demonstrate " + 
    "the use of JSplitPane which is a simple split pane which help " +
    "us in dividing two text areas and giving us a way to put to " + 
    "sample text side by side.";

  public SplitPaneDemo() {
    
    JTextArea textarea1 = new JTextArea(text);
    JTextArea textarea2 = new JTextArea(text);

    textarea1.setLineWrap(true);
    textarea2.setLineWrap(true);
    
    textarea1.setMinimumSize(new Dimension(150, 150));
    textarea2.setMinimumSize(new Dimension(150, 150));
    
    textarea1.setPreferredSize(new Dimension(250, 200));
    JSplitPane splitpane = 
     new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, textarea1, textarea2);
    getContentPane().add(splitpane, BorderLayout.CENTER);
  }

  public static void main(String[] args) {
    setFrame(new SplitPaneDemo(), 500, 400);
  }

  public static void 
  setFrame(final JFrame frame, final int width, final int height)
  {
    SwingUtilities.invokeLater(new Runnable() {
      public void run() {
 frame.setTitle(frame.getClass().getSimpleName());
 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 frame.setSize(width, height);
 frame.setVisible(true);
      }
    });
  }
}


Output of the program :



How to calculate Volume, Curved Surface Area and Total Surface Area of Cylinder in Java ?

Program to calculate Volume, Curved Surface Area and Total Surface Area of Cylinder in Java ?

package com.hubberspot.mensuration.example;

import java.util.Scanner;

public class Cylinder {

   public static void main(String[] args) {
     Scanner input = new Scanner(System.in);

     double radius = 0;
     double height = 0;

     double volume = 0;
     double curvedSurfaceArea = 0;
     double totalSurfaceArea = 0;

     System.out.print("Enter the radius of base of Cylinder : "); 
     radius = input.nextDouble();
  
     System.out.print("Enter the height of Cylinder : "); 
     height = input.nextDouble();

     volume = (Math.PI * radius * radius * height);
     curvedSurfaceArea = 2 * (Math.PI * radius * height);
     totalSurfaceArea = 2 * Math.PI * radius * (radius + height);
  
     System.out.println("");
     System.out.println("The Volume of Cylinder is : " + volume);
     System.out.println("The Curved Surface Area of Cylinder is : "
                   + curvedSurfaceArea);
     System.out.println("The Total Surface Area of Cylinder is : "
    + totalSurfaceArea);
   }

}



Output of the program :



How to implement JFileChooser dialog into a Frame in Java using Swing ?.

A Simple program demonstrating the working of JFileChooser dialog in Java using Swing framework.

package com.hubberspot.swing.example;

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

public class FileChooserDemo extends JFrame {
 
  private JTextField display = new JTextField();
  private JButton open = new JButton("Open");
  private JButton save = new JButton("Save");
 
  public FileChooserDemo() {
    JPanel panel = new JPanel();
    open.addActionListener(new OpenClass());
      panel.add(open);
    save.addActionListener(new SaveClass());
      panel.add(save);
    add(panel, BorderLayout.SOUTH);
    display.setEditable(false);
    panel = new JPanel();
    panel.setLayout(new GridLayout(2,1));
    panel.add(display);
    add(panel, BorderLayout.NORTH);
  }

  class OpenClass implements ActionListener {
    public void actionPerformed(ActionEvent e) {
      JFileChooser chooser = new JFileChooser();
   
      int option = chooser.showOpenDialog(FileChooserDemo.this);
      if(option == JFileChooser.APPROVE_OPTION) {
 display.setText("You chose " + 
 ((chooser.getSelectedFile()!=null)?
 chooser.getSelectedFile().getName():
 "nothing"));
      }
      
      if(option == JFileChooser.CANCEL_OPTION) {
 display.setText("You canceled.");
      }
  }
 }

  class SaveClass implements ActionListener {
    public void actionPerformed(ActionEvent e) {
      JFileChooser chooser = new JFileChooser();
   
      int option = chooser.showSaveDialog(FileChooserDemo.this);
      if(option == JFileChooser.APPROVE_OPTION) {
 display.setText("You chose " + 
 ((chooser.getSelectedFile()!=null)?
 chooser.getSelectedFile().getName():
 "nothing"));
       }
 
      if(option == JFileChooser.CANCEL_OPTION) {
 display.setText("You canceled.");
      }
   }
  }

   public static void main(String[] args) {
     setFrame(new FileChooserDemo(), 200, 100);
   }

   public static void 
     setFrame(final JFrame frame, final int width, final int height) {
     SwingUtilities.invokeLater(new Runnable() {
 public void run() {
   frame.setTitle(frame.getClass().getSimpleName());
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   frame.setSize(width, height);
   frame.setVisible(true);
   }
  });
 }

} 


Output of the program :










How to use Variable Arguments Parameter List in a Java program ?.

A simple Java program demonstrating the use of Variable Arguments Parameter List

package com.hubberspot.objects.example;

class VarArgument
{
  void display(String message, String...names)
  {
    for(String name : names)
      System.out.println(message + name);
  }
}

public class VarArgsDemo
{
  public static void main(String[] args)
  {
     VarArgument var = new VarArgument();
     var.display("Hello " , "Hubberspot");
     var.display("Welcome ", "Jonty", "Michelle", "Tsotsobe");
 }
}


Output of the program :



How to connect to a remote server through a Java program ?

Program to demonstrate a way to connect to a remote server by a simple Java program

package com.hubberspot.networking.example;

import java.io.*;
import java.net.*;

public class RemoteConnection {
  public static void main(String[] args) {
    String host = "tock.usno.navy.mil";
  
    try {
      Socket socket = new Socket(host, 13);
      InputStream timeStream = socket.getInputStream( );
      StringBuffer time = new StringBuffer( );
      int c;
      while ((c = timeStream.read( )) != -1) 
        time.append((char) c);
      String timeString = time.toString().trim( );
      System.out.println("It is " + timeString + " at "
        + host);
    } 
    catch (UnknownHostException e) {
      System.err.println(e);
    }
    catch (IOException e) {
      System.err.println(e);
    }
  } 
} 

Output of the program :

It is Thu May 3 17:08:47 2012 at tock.usno.navy.mil

How to get and print current Date and Time in a Java program ?

Program to demonstrate how to get current Date and Time in Java

package com.hubberspot.object.example;

import java.util.Date;

public class WelcomeDate {

  public static void main(String[] args) {

    System.out.println("Hello, so you are back !");
    System.out.println("Welcome to Hubberspot !");
    System.out.println("Today's date is : "+ new Date());
  }
} 

Output of the program : 



How to use Hashtable in Java with example ?.

Program to demonstrate how to implement Hashtable class in java.util.*; package along with its operations :

package com.hubberspot.collections.example;

import java.util.Hashtable;
import java.util.Enumeration;

public class HashtableExample
{
  public static void main(String args[])
  {
    Hashtable hashtable = new Hashtable();
    String str, name = null;
     
    hashtable.put( "Jonty", 80.2 ); 
    hashtable.put( "Hubberspot", 75.9 );
    hashtable.put( "Java", 105.1 );
    hashtable.put( "Magicman", 65.7 );
    
    System.out.println("Hashtable contains " +
       hashtable.size() + " key value pair."); 

    System.out.println("Retriving all keys from Hashtable");
  
    Enumeration keys = hashtable.keys();
  
    while( keys. hasMoreElements() )
      System.out.println( keys.nextElement() );

    System.out.println("Retriving all values from Hashtable");
  
    Enumeration values = hashtable.elements();
  
    while( values. hasMoreElements() )
      System.out.println( values.nextElement() );
  
    double maximum = 0;
    keys = hashtable.keys();
    values = hashtable.elements();
  
    while( values. hasMoreElements() )
    {
      double percentage = ((Double)values.nextElement())
                 .doubleValue();
      
      str = (String)keys.nextElement();
   
      if(percentage > maximum)
      {
 maximum = percentage;
 name = str;
      }
    }

    System.out.println("Name = " + name);  
    System.out.println("Percentage = " + maximum);  
  }
}


Output of the program :


How to use HashSet in Java with example ?.

Program to demonstrate how to implement HashSet class in java.util.*; package along with its operations :

package com.hubberspot.collections.example;

import java.util.*;

public class HashSetExample
{
 public static void main(String[] args)
 {
  HashSet hashset=new HashSet();
  hashset.add("B");
  hashset.add("A");
  hashset.add("F");

  System.out.println("The contents of set : "
     + hashset);
  
  hashset.add("E");
  hashset.remove("A");

  System.out.println("The contents of set : "
     + hashset);

  TreeSet treeSet = new TreeSet(hashset);

  System.out.println("The tree set contents : "
     + treeSet);
    
 } 
}

Output of the program :


How to use TreeSet in Java with example ?.

Program to demonstrate how to implement TreeSet class in java.util.*; package along with its operations :

package com.hubberspot.collections.example;

import java.util.*;

public class TreeSetExample
{
  public static void main(String[] args)
{
    TreeSet treeSet = new TreeSet();
    
    treeSet.add("d");
    treeSet.add("a");
    treeSet.add("s");
    treeSet.add("f");
    treeSet.add("k");
    
    System.out.println("The contents of set : "
       + treeSet);  

    System.out.println("The size of set : "
       + treeSet.size());
    
    SortedSet sortedSet = treeSet.headSet("d");

    System.out.println("The elements < d are : "
       + sortedSet);

    sortedSet = treeSet.tailSet("d");

    System.out.println("The elements > d are : "
       + sortedSet);

    sortedSet = treeSet.subSet("c", "s");

    System.out.println("The elements > d are : "
       + sortedSet);
    
 } 
}

Output of the program :


How to implement JScrollPane into a Frame in Java using Swing API ?.

A Simple program demonstrating the working of JScrollPane in Java using Swing framework.

package com.hubberspot.swing.example;

import javax.swing.*;
import java.awt.*;

public class ScrollPaneDemo extends JFrame {

  JScrollPane scrollpane;

  public ScrollPaneDemo() {

    String teams[] = { "Deccan Chargers", "Kolkata Night Riders", 
            "Mumbai Indians", "Chennai Super Kings", 
         "Rajasthan Royals", "Royal Challengers Bangalore",
         "Kings XI Punjab", "Pune Warriors India",
         "Delhi Daredevils"
  };

    JList list = new JList(teams);
    scrollpane = new JScrollPane(list);
    getContentPane().add(scrollpane, BorderLayout.CENTER);
  }

  public static void main(String[] args) {
    setFrame(new ScrollPaneDemo(), 300, 150);
  }

  public static void 
  setFrame(final JFrame frame, final int width, final int height) {
    SwingUtilities.invokeLater(new Runnable() {
      public void run() {
        frame.setTitle(frame.getClass().getSimpleName());
 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 frame.setSize(width, height);
 frame.setVisible(true);
      }
    });
  }

}


Output of the program : 


How to use LinkedList in Java with example ?.

Program to demonstrate how to implement LinkedList class in java.util.*; package along with its operations :

package com.hubberspot.collections.example;

import java.util.*;

public class LinkedListExample
{
  public static void main(String[] args)
  {
    LinkedList list=new LinkedList();
    list.add("a");
    list.add("b");
    list.add(new Integer(5));
  
    System.out.println("The contents of array is " + list);
    System.out.println("The size of linkedlist is "
       +list.size());
    
    list.addFirst(new Integer(10));
    System.out.println("The contents of array is " + list);

    list.addLast("c");
    list.add(2,"d");
    list.add(1,"e");
    list.remove(3);
    
    System.out.println("The contents of array is " + list);  
    System.out.println("The size of linkedlist is "
       + list.size());
 } 
}

Output of the program :


Program to implement List on a Frame using Java Swing API

A Simple program demonstrating the working of JList list in Java using Swing framework.

package com.hubberspot.swing.example;

import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.border.Border;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

public class ListDemo extends JFrame {
  private String[] ipl = {
  "Deccan Chargers", "Kolkata Night Riders", 
  "Mumbai Indians", "Chennai Super Kings", 
  "Rajasthan Royals", "Royal Challengers Bangalore",
  "Kings XI Punjab", "Pune Warriors India",
  "Delhi Daredevils"
  };
  private int counter = 0;
  private DefaultListModel model = new DefaultListModel();
  private JList list = new JList(model);
  private JTextArea textarea = new JTextArea(ipl.length, 20);
  private JButton button = new JButton("Add Team");
  private ActionListener listener = new ActionListener() {
    public void actionPerformed(ActionEvent e) {
      if(counter < ipl.length) {
 model.add(0, ipl[counter++]);
      } else {
   button.setEnabled(false);
 }
    }
  };
  
  private ListSelectionListener lstlistener =
     new ListSelectionListener() {
 public void valueChanged(ListSelectionEvent e) {
    if(e.getValueIsAdjusting()) return;
    textarea.setText("");
    for(Object item : list.getSelectedValues())
      textarea.append(item + "\n");
        }
  };

  public ListDemo() {
    textarea.setEditable(false);
    setLayout(new FlowLayout());
    for(int i = 0; i < 4; i++)
      model.addElement(ipl[counter++]);
    add(textarea);
    add(list);
    add(button);
    list.addListSelectionListener(lstlistener);
    button.addActionListener(listener);
  }

  public static void main(String[] args) {
    setFrame(new ListDemo(), 300, 450);
  }

  public static void 
  setFrame(final JFrame frame, final int width, final int height) {
    SwingUtilities.invokeLater(new Runnable() {
       public void run() {
  frame.setTitle(frame.getClass().getSimpleName());
  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  frame.setSize(width, height);
  frame.setVisible(true);
       }
    });
  }
} 

Output of the program : 


 

How to implement Tabbed Pane in a Frame using Java Swing API ?.

A Simple program to demonstrate how to use Tabbed Pane in a Frame using Java Swing API ?.

package com.iplt20.swing.example;

import java.awt.BorderLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

public class TabbedPaneDemo extends JFrame {
  private String[] ipl = {
  "Deccan Chargers", "Kolkata Night Riders", 
  "Mumbai Indians", "Chennai Super Kings", 
  "Rajasthan Royals", "Royal Challengers Bangalore",
  "Kings XI Punjab", "Pune Warriors India",
  "Delhi Daredevils"
  };

  private JTabbedPane tab = new JTabbedPane();
  private JTextField textfield = new JTextField(20);
  
  public TabbedPaneDemo() {
    int i = 0;
    for(String teams : ipl){
      tab.addTab(ipl[i],
      new JTextField("Who will win IPL this year?."));
      i++;
    }

    tab.addChangeListener(new ChangeListener() {
      public void stateChanged(ChangeEvent e) {
 textfield.setText("You selected: " +
          tab.getTitleAt(tab.getSelectedIndex()));
      }
    });
    add(BorderLayout.SOUTH, textfield);
    add(tab);
  }
  
  public static void main(String[] args) {
  setFrame(new TabbedPaneDemo(), 450, 175);
 }

  public static void 
  setFrame(final JFrame frame, final int width, final int height) {
    SwingUtilities.invokeLater(new Runnable() {
      public void run() {
 frame.setTitle(frame.getClass().getSimpleName());
 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 frame.setSize(width, height);
 frame.setVisible(true);
      }
    });
  }
} 


Output of the program :



How to add Text Area to a Frame using Swing API in Java ?

Program to demonstrate adding of Text Area to a Frame.

package com.hubberspot.swing.example;

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;

public class TextAreaDemo extends JFrame {
  private JButton add = new JButton("Add Data");
  private JButton clear = new JButton("Clear Data");
  private JTextArea textarea = new JTextArea(2, 25);

  public TextAreaDemo() {
    add.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
 textarea.setText("Welcome to Hubberspot.com!");
      }
    });

    clear.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
 textarea.setText("");
      }
    });
    setLayout(new FlowLayout());
    add(new JScrollPane(textarea));
    add(add);
    add(clear);
  }

  public static void main(String[] args) {
    setFrame(new TextAreaDemo(), 300, 150);
  }

  public static void 
  setFrame(final JFrame frame, final int width, final int height) {
    SwingUtilities.invokeLater(new Runnable() {
      public void run() {
 frame.setTitle(frame.getClass().getSimpleName());
 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 frame.setSize(width, height);
 frame.setVisible(true);
       }
     });
   }

} 

Output of the program :



















How to create Eclipse Menu and Menu Bar in a simple Frame in Java ?.

Program to demonstrate how to create Eclipse like Menu and Menu Bar in a simple Frame in Java ?.

package com.hubberspot.swing.example;

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

public class MenusDemo extends JFrame {
  private JMenu[] menu = {
    new JMenu("File"),
    new JMenu("Edit"),
    new JMenu("Run"),
    new JMenu("Source"),
    new JMenu("Refactor"),
    new JMenu("Navigate"),
    new JMenu("Search"),
    new JMenu("Project"),
    new JMenu("Window"),
    new JMenu("Help")
  };
  private JMenuItem[] item = {
    new JMenuItem("New"), 
    new JMenuItem("Undo Typing"),
    new JMenuItem("Run"),  
    new JMenuItem("Toggle Comment"),
    new JMenuItem("Android"),
    new JMenuItem("Go Into"),
    new JMenuItem("Search"), 
    new JMenuItem("Open Project"),
    new JMenuItem("New Window"), 
    new JMenuItem("Welcome"),
    new JMenuItem("Open File"), 
    new JMenuItem("Redo"),
    new JMenuItem("Debug"),  
    new JMenuItem("Add Block Comment"),
    new JMenuItem("Rename"), 
    new JMenuItem("Go To"),
    new JMenuItem("File"), 
    new JMenuItem("Close Project"),
    new JMenuItem("New Editor"),
    new JMenuItem("Help Contents"),
    new JMenuItem("Close"), 
    new JMenuItem("Cut"),
    new JMenuItem("Run History"),  
    new JMenuItem("Remove Block Comment"),
    new JMenuItem("Move"), 
    new JMenuItem("Open Declaration"),
    new JMenuItem("Java"),
    new JMenuItem("Build All"),
    new JMenuItem("Open Perspective"), 
    new JMenuItem("Search"),
    new JMenuItem("Close All"), 
    new JMenuItem("Copy"),
    new JMenuItem("Run As"),  
    new JMenuItem("Generate Element Comment"),
    new JMenuItem("Change Method Signature"), 
    new JMenuItem("Open Type Hierarchy"),
    new JMenuItem("Text"), 
    new JMenuItem("Build Project"),
    new JMenuItem("Show View"), 
    new JMenuItem("Dynamic Help")
  };
  
  public MenusDemo() {
    for(int i = 0; i < item.length; i++) {
       menu[i % 10].add(item[i]);
    }
    JMenuBar menubar = new JMenuBar();
    for(JMenu menus : menu)
      menubar.add(menus);
    setJMenuBar(menubar);
    setLayout(new FlowLayout());
 
  }
  public static void main(String[] args) {
    setFrame(new MenusDemo(), 500, 200);
  }

  public static void 
    setFrame(final JFrame frame, final int width, final int height) {
       SwingUtilities.invokeLater(new Runnable() {
   public void run() {
     frame.setTitle(frame.getClass().getSimpleName());
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     frame.setSize(width, height);
     frame.setVisible(true);
   }
 });
    }
} 

Output of the program :







How to add label to a Swing frame in Java ?

Program to demonstrate adding of a Label to a Swing component in Java.

package com.hubberspot.awtSwing.example;

import java.awt.*;
import javax.swing.*;

public class LabelDemo
{
  JFrame frame;
  JLabel label1, label2, label3, label4;
  LabelDemo()
  {
    frame = new JFrame();
    frame.setLayout(new GridLayout(4,1));
        
    label1 = new JLabel(" Left Label "); 
    label2 = new JLabel(" Center Label ",
         JLabel.CENTER);
    
    label3 = new JLabel(" Right Label",
         JLabel.RIGHT); 
    
    label4 = new JLabel(" Image Label", 
        new ImageIcon("c:\\smile.jpg"),JLabel.CENTER);
    
    frame.add(label1); 
    frame.add(label2); 
    frame.add(label3); 
    frame.add(label4);
    frame.setTitle("Welcome to Hubberspot!.");
    frame.setSize(300,300);
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  }
   public static void main(String[] args)
   {
     new LabelDemo();
   }
}


Output of the program :


How to use GridLayout in Java using Swing ?.

A Simple Java Program demonstrating a way to use GridLayout layout using Swing API.

package com.hubberspot.swing.example;

import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

public class GridLayoutDemo extends JFrame {
  public GridLayoutDemo() {
    setLayout(new GridLayout(4,3));
    for(int i = 0; i < 10; i++){
      JTextField textfield= new JTextField();
      textfield.setEditable(false);
      textfield.setText("TextField " + (i));
      add(textfield);
    }
  }
  public static void main(String[] args) {
    setFrame(new GridLayoutDemo(), 300, 200);
  }

  public static void 
  setFrame(final JFrame frame, final int width, final int height) {
    SwingUtilities.invokeLater(new Runnable() {
      public void run() {
 frame.setTitle(frame.getClass().getSimpleName());
 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 frame.setSize(width, height);
 frame.setVisible(true);
      }
    });
  }
} 

Output of the program : 


 

How to use FlowLayout in Java using Swing ?.

A Simple Java Program demonstrating a way to use FlowLayout layout using Swing API.

package com.hubberspot.swing.example;

import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

public class FlowLayoutDemo extends JFrame {
  public FlowLayoutDemo() {
    setLayout(new FlowLayout());
    for(int i = 0; i < 20; i++){
 add(new JButton("Button " + i));
 JTextField textfield= new JTextField();
 textfield.setEditable(false);
 textfield.setText("TextField " + (i));
 add(textfield);
    }
  }
  public static void main(String[] args) {
    setFrame(new FlowLayoutDemo(), 400, 400);
  }

  public static void 
  setFrame(final JFrame frame, final int width, final int height) {
     SwingUtilities.invokeLater(new Runnable() {
 public void run() {
          frame.setTitle(frame.getClass().getSimpleName());
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   frame.setSize(width, height);
   frame.setVisible(true);
 }
    });
 }
} 

Output of the program : 


 

How to use Combo Box (Drop-Down list) in Java using Swing API ?

A Simple program demonstrating the use of Combo Box (Drop-Down list) in Java using Swing.


Click here to download complete source code 


package com.hubberspot.swing.example;

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

public class ComboBoxDemo extends JFrame {
  private String[] languages = {
    "Java", "C++", "C", "Python",
    "JavaScript", "Perl", "Ruby", "C#"
  };
  
  private JTextField textfield1 = new JTextField
   ("Top Programming Languages : ");

  private JTextField textfield2 = new JTextField(15);
  private JComboBox comboBox = new JComboBox();
  
  private int count = 0;

  public ComboBoxDemo() {
 for(int i = 0; i < languages.length; i++)
   comboBox.addItem(languages[count++]);
 textfield1.setEditable(false);

 comboBox.addActionListener(new ActionListener() { 
   public void actionPerformed(ActionEvent e) {
  textfield2.setText("You Selected : " +      
       ((JComboBox)e.getSource()).getSelectedItem());
   }
 });
 
 setLayout(new FlowLayout());
 add(textfield1);
 add(textfield2);
 add(comboBox);    
 }
 
  public static void main(String[] args) {
 setFrame(new ComboBoxDemo(), 250, 150);
  }

  public static void 
  setFrame(final JFrame frame, final int width, final int height) {
 SwingUtilities.invokeLater(new Runnable() {
   public void run() {
     frame.setTitle(frame.getClass().getSimpleName());
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     frame.setSize(width, height);
     frame.setVisible(true);
   }
 });
 }

}
Output of the program : 



 



Video tutorial to demonstrate how to use Combo Box (Drop Down list) in Java using Swing API.







Video tutorial to demonstrate how to create a simple Swing Application in Java.







How to use BorderLayout in Java using Swing ?.

A Simple Java Program demonstrating a way to use BorderLayout layout using Swing API.

package com.hubberspot.swing.example;

import java.awt.BorderLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;

public class BorderLayoutDemo extends JFrame {
  public BorderLayoutDemo() {
    add(BorderLayout.NORTH, new JButton("North"));
    add(BorderLayout.SOUTH, new JButton("South"));
    add(BorderLayout.EAST, new JButton("East"));
    add(BorderLayout.WEST, new JButton("West"));
    add(BorderLayout.CENTER, new JButton("Center"));
  }
  public static void main(String[] args) {
    setFrame(new BorderLayoutDemo(), 300, 200);
  }

  public static void 
  setFrame(final JFrame frame, final int width, final int height) {
       SwingUtilities.invokeLater(new Runnable() {
   public void run() {
     frame.setTitle(frame.getClass().getSimpleName());
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     frame.setSize(width, height);
     frame.setVisible(true);
   }
       });
  }
}

Output of the program :



How to add Image button to a Frame using Swing API in Java ?

Program to demonstrate adding of Image Button to a Frame

package com.hubberspot.awtSwing.example;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class ButtonTest implements ActionListener
{
  JFrame frame;
  JButton button1, button2,button3;
  JTextField textfield;
  ButtonTest()
  {
    frame = new JFrame("Button Test");
    button1 = new JButton("Yes");
    button2 = new JButton("No");
    button3 = new JButton("Image Button", 
        new ImageIcon("c:\\smile.jpg"));
    button1.setMnemonic('Y');
    button2.setMnemonic('N');
    textfield = new JTextField(20);

    frame.setLayout(new FlowLayout());
    frame.add(textfield);
    frame.add(button1);
    frame.add(button2);
    frame.add(button3);

    button1.addActionListener(this);
    button2.addActionListener(this);

    frame.pack();
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   }
   public void actionPerformed(ActionEvent event)
   {
     if(event.getSource()==button1)
       textfield.setText("You clicked YES");
     else
        textfield.setText("You clicked NO");
   }
   public static void main(String[] args)
   {
     new ButtonTest();
   }
}

Output of the program :






How to use break and continue statements in Java ?

break and continue statements in Java

In Java, we use break and continue statements frequently. We use in conditions where we want to get out of the loops. Normally we have to wait for the condition for getting an exit from the loops, this is performance hit as we are done with our task and still loop is getting executed. Keyword break is used to get such functionality. Whenever program execute a break statement in a loop, the control of execution passes to the next statement right after the currently executing loop. Whereas, in some cases we may want to take control to the beginning of the loop, bypassing the loop statements which have not yet been executed. This can be done using the continue statement.

A Simple Program demonstrating use of break and continue statements in Java

package com.hubberspot.control.example;

public class BreakAndContinueDemo {
  public static void main(String[] args) {
    for(int i = 0; i < 100; i++) {
      if(i == 80) 
       break; 
      if(i % 8 != 0) 
       continue; 
      System.out.print(i + " ");
    }
  }
} 
Output of the program :

0 8 16 24 32 40 48 56 64 72

What is difference between equals() method and == operator in Java ?

What is difference between equals() method and == operator in Java ? .
Equals( ) method and == has very vital role to play when comparing two objects of any kind. Both of the equals( ) method and == operator returns true when two objects reference compared with each other points to same objects. While the comparisons change when we override equals method. String class has overridden this method , thats why they show different behavior as demonstrated below.


Program to demonstrate the difference between equals() method and == operator in Java

package com.hubberspot.operators.example;

public class EqualityTest {
  public static void main(String[] args) {
    String string1 = new String("Test");
    String string2 = new String("Test");
    
    String string3 = new String("New Test");
    String string4 = new String("Old Test");
    
    System.out.println("string1 == string2 : "
       + (string1 == string2));
    System.out.println("string1 != string2 : "
       + (string1 != string2));

    System.out.println("string3 == string4 : " 
       + (string3 == string4));
    System.out.println("string3 != string4 : "
       + (string3 != string4));
    
    System.out.println("string1.equals(string2) : "
       +string1.equals(string2));
    
    System.out.println("string3.equals(string4) : "
       +string3.equals(string4));
  }
}

Output of the program :



How to add Radio Buttons to a Swing frame in Java using JRadioButton class?

Program to demonstrate adding of a Radio Button to a Swing component in Java using JRadioButton class.

package com.hubberspot.awtSwing.example;

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

public class RadioButtonDemo extends JFrame {
  private JTextField textfield = new JTextField(16);
  private ButtonGroup groups = new ButtonGroup();
  private JRadioButton
  radiobutton1 = new JRadioButton("Java", false),
  radiobutton2 = new JRadioButton("C++", false),
  radiobutton3 = new JRadioButton("JavaScript", false);

  private ActionListener actionlistener = new ActionListener() {
    public void actionPerformed(ActionEvent event) {
  textfield.setText("I Like " +
  ((JRadioButton)event.getSource()).getText());
    }
  };

  public RadioButtonDemo() {
    radiobutton1.addActionListener(actionlistener);
    radiobutton2.addActionListener(actionlistener);
    radiobutton3.addActionListener(actionlistener);
    groups.add(radiobutton1); 
    groups.add(radiobutton2); 
    groups.add(radiobutton3);

    textfield.setEditable(false);

    setLayout(new FlowLayout());

    add(textfield);
    add(radiobutton1);
    add(radiobutton2);
    add(radiobutton3);
  }
  public static void main(String[] args) {
    setFrame(new RadioButtonDemo(), 225, 150);
  }

  public static void 
  setFrame(final JFrame frame, final int width, final int height) {
    SwingUtilities.invokeLater(new Runnable() {
       public void run() {
   frame.setTitle(frame.getClass().getSimpleName());
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   frame.setSize(width, height);
   frame.setVisible(true);
 }
     });
  }

}

Output of the program : 








How to read information from Server Socket through TCP Client Socket ?.

Program to read information from Server Socket through TCP Client Socket

package com.hubberspot.networking.example;

import java.net.*; 
import java.io.*;

public class MyServerSocket
{
  public static void main(String args[]) 
 throws UnknownHostException, IOException
  {
    ServerSocket ss=new ServerSocket(4444);
    System.out.println("Server Started");
    Socket s = ss.accept(); 

  }
}


package com.hubberspot.networking.example;

import java.net.*; 
import java.io.*;

public class MyClientSocket
{
  public static void main(String args[]) 
  { 
    try{
      InetAddress addr = InetAddress.getByName("localhost");
      Socket s=new Socket (addr, 4444);
      System.out.println (s.getInetAddress());
      System.out.println (s.getPort());
      System.out.println (s.getLocalPort());
      s.close();
    }
     catch(Exception e)
       { e.printStackTrace(); }
  }
}


First compile both files. Run the server and run the client program.

Output of the program :



How to add Event Handling to a Button using Anonymous class in Java

Program to demonstrate event handling in a Swing Button using anonymous class.
package com.hubberspot.awtSwing.example;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

class ButtonEventHandling 
{
  JFrame frame;
  JButton button;
  JTextField textField;

  ButtonEventHandling()
  {
    frame=new JFrame("Welcome to Hubberspot");
    frame.setLayout(new FlowLayout());
    button=new JButton("Like Us!");
    textField=new JTextField(20);

    button.addActionListener(new ActionListener()
    {
      public void actionPerformed(ActionEvent ae) 
      {
 textField.setText("Thanks for liking Hubberspot!");
      }
    });

    frame.setSize(100,100);
    frame.add(textField);
    frame.add(button);

    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  }
 
  public static void main(String[] args)
  {
    new ButtonEventHandling();
  }
}

Output of the program :

How to implement Comparator Interface in Java with an example ?

Program to demonstrate the implementation of Comparator Interface in Java

package com.hubberspot.collections.example;

import java.util.*;

class Student 
{
  public String name; 
  public double percentage;
 
  Student(String name, double percentage)
  {
    this.name = name; this.percentage = percentage; 
  }
 
  public String toString()
  {
    return "\nName = " + name + "\n"+
           "Percentage = " + percentage+"\n";
  }
}

class CompareWithPercentage implements Comparator
{
  public int compare(Object obj1, Object obj2)
  {
    Student o1 = (Student)obj1;
    Student o2 = (Student)obj2;
  
    if(o1.percentage == o2.percentage)
       return 0;

    if(o1.percentage > o2.percentage)
       return 1;
    return -1;
  }
}

public class ComparatorExample
{
  public static void main(String[] args)
  {
    ArrayList list = new ArrayList();

    list.add(new Student("Dinesh",76.2));
    list.add(new Student("Jonty",96.5));
    list.add(new Student("Gunjan",81.7));
    list.add(new Student("Parishrut",62.1));
  
    System.out.println("Before Sorting : \n" + list);
  
    Collections.sort(list,new CompareWithPercentage());
  
    System.out.println("\nAfter Sorting : \n" + list);
  }
}

Output of the program :


How to add Event Handling to a Button in Java using Swing API

Program to demonstrate event handling in a Swing Button.
package com.hubberspot.awtSwing.example;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

class ButtonEventHandling implements ActionListener
{
  JFrame frame;
  JButton button;
  JTextField textField;

  ButtonEventHandling()
  {
    frame=new JFrame("Welcome to Hubberspot");
    frame.setLayout(new FlowLayout());
    button=new JButton("Like Us!");
    textField=new JTextField(20);

    button.addActionListener(this);

    frame.setSize(100,100);
    frame.add(textField);
    frame.add(button);

    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  } 

  public void actionPerformed(ActionEvent ae) 
  {
    textField.setText("Thanks for liking Hubberspot!");
  } 

  public static void main(String[] args)
  {
    new ButtonEventHandling();
  }
}
Output of the program :


 
© 2021 Learn Java by Examples Template by Hubberspot