Vous êtes sur la page 1sur 15

Example of HashMap and HashTable

import java.util.Hashtable;

public class HashMapHashtableExample {

public static void main(String[] args) {

Hashtable<String,String> hashtableobj = new Hashtable<String,

hashtableobj.put("Alive is ", "awesome");
hashtableobj.put("Love", "yourself");
System.out.println("Hashtable object output :"+ hashtableobj);

HashMap hashmapobj = new HashMap();

hashmapobj.put("Alive is ", "awesome");
hashmapobj.put("Love", "yourself");
System.out.println("HashMap object output :"+hashmapobj);


Output : Hashtable object output :{Love=yourself, Alive is =awesome}

HashMap object output :{Alive is =awesome, Love=yourself}

A Simple JTable Example for Display

NEW COURSE: What's New In Java 9
This article shows a simple example of JTable. The JTable component provided as part of the
Swing API in Java is used to display/edit two-dimensional data. This is similar to a spreadsheet.

Let us consider some examples. Say that you want to display a list of employees belonging to an
organization. This should display the various attributes of employees. For example, employee id,
name, hourly rate, part-time status etc. The display will be more like a database table display of
rows and columns. In this case, the id,name, hourly rate are the columns. The number of rows
might differ based on the number of employees in the organization.

First Attempt:

Let us attempt to display such a data with JTable with minimum amount of code. The idea is to
only display the details in the table. The user should not be allowed to edit any data. Also, text-
based columns should be left-aligned and numerical values should be right-aligned.
The following code should help us do that:

package net.codejava.swing;
1 import javax.swing.JFrame;
2 import javax.swing.JScrollPane;
3 import javax.swing.JTable;
import javax.swing.SwingUtilities;
4 public class TableExample extends JFrame
5 {
6 public TableExample()
7 {
//headers for the table
8 String[] columns = new String[] {
9 "Id", "Name", "Hourly Rate", "Part Time"
10 };
12 //actual data for the table in a 2d array
13 Object[][] data = new Object[][] {
{1, "John", 40.0, false },
14 {2, "Rambo", 70.0, false },
15 {3, "Zorro", 60.0, true },
16 };
17 //create table with data
JTable table = new JTable(data, columns);
//add the table to the frame
20 this.add(new JScrollPane(table));
22 this.setTitle("Table Example");
23 this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
24 this.pack();
25 }
27 public static void main(String[] args)
28 {
29 SwingUtilities.invokeLater(new Runnable() {
30 @Override
public void run() {
31 new TableExample();
32 }
33 });
34 }
This code attempts to build a table with minimum amount of effort. First of all, the column headers
are identified and declared in a String array columns. Next, a 2d Object array named data is
declared. Each inner array corresponds to a row of data. Within each array, the columns are
separated by commas.

Difference between abstract class

and interface
Ans) Understanding when to use abstract class or interface, helps in designing systems
better and also it is one of the most common interview question. To begin with lets
understand the difference.

 A class is called abstract when it is declared with keywordabstract. Abstract

class may contain abstract method. It can also contain n numbers of concrete
method. Interface can only contain abstract methods.
 Interface can have only abstract methods. Abstract class can have concerete
and abstract methods.
 The abstract class can have public, private, protected or default variables and
also constants. In interface the variable is by default public final. In nutshell the
interface doesnt have any variables it only has constants.
 A class can extend only one abstract class but a class can implement
multiple interfaces. Abstract class doesn't support multiple inheritance whereas
abstract class does.
 If an interface is implemented its mandatory to implement all of its methods but if
an abstract class is extended its mandatory to implement all abstract methods.
 The problem with an interface is, if you want to add a new feature (method) in its
contract, then you MUST implement those method in all of the classes which
implement that interface. However, in the case of an abstract class, the method
can be simply implemented in the abstract class and the same can be called by
its subclass.

We can re-iterate above points in a tabular form

Abstract class Inteface

Type of At least one abstract method and can have All methods are public
methods multiple concrete methods abstract

Variables Can have public, private, default or protected All variables as public static
Abstract class Inteface

variables final

Inheritance Concrete class can extend only one abstract Class can implement
class. multiple interface

Extends Abstract class can extend abstract class Interface can implement
other interaces

It is also considered that abstract class is faster that interface, since the compiler needs
to find the implementation and figure out the concrete class. But, the results show that
improve in performance is very minimal and it should not be consider during building

When to use abstract class over interface:

Abstract class is mainly used to:

 Define a default behavior for subclasses. It means that all child classes should
have perform same functionality.

 public abstract class VideoStreaming {

 protected void startStreaming() { //it is protected so that it can be
 //start streaming
 }
 public abstract boolean authenticate(String username, String pwd);
 }

 public class Netflix extends VideoStreaming {
 public boolean authenticate (String username, String pwd) {
 //custom implementation
 }

 Define a flow/procedure for a use case and provide some default implementation
and leave some implementation to the subclass.

 public abstract class VideoStreaming {

 public abstract boolean authenticate(String username, String pwd);
 public List<Movies> getMovies() {
 if(authenticate) {
 //get personalized movies
 }
 }
 }
 public class Netflix extends VideoStreaming {
 public boolean authenticate (String username, String pwd) {
 }

Interface can be used to define a contract or behaviour. A class can implement

multiple interfaces. Interface can also act as a contract between two systems to

public interface ISocialLogin {

// by default methods are public and abstract
Credentials facbookLogin() ;
Credentials twitterLogin() ;
public class Netflix extends VideoStreaming implements ISocialLogin {
public boolean authenticate (String username, String password) {
//use social logins here

public Credentials facebookLogin() {

// some implementaion
public Credentials TwitterLogin() {
// some implementaion

Add file filter for JFileChooser dialog

It’s very common to have a file extension filter for open/save dialog like the following

In Swing, we can do that by using method addChoosableFileFilter(FileFilter filter) of the class JFileChooser.
Create a class that extends FileFilter abstract class and overrides its two methods:

o boolean accept(File f): returns true if the file f satisfies a filter condition. The
condition here is the extension of the file.
o String getDescription(): returns a description which is displayed in the dialog’s Files
of type section.

The following code shows an example of adding a filter for files of type PDF:
JFileChooser fileChooser = new JFileChooser();
fileChooser.addChoosableFileFilter(new FileFilter() {

public String getDescription() {

return "PDF Documents (*.pdf)";

public boolean accept(File f) {

if (f.isDirectory()) {
return true;
} else {
return f.getName().toLowerCase().endsWith(".pdf");

However, what if we need to add several filters, such as for .docx, .xlsx files? Well,
one solution is repeating the above code for each file type – but that is not good in
terms of code reusability. So, it’s better to create a separate, generalized class for
extending the FileFilter abstract class, and parameterize the file extension and
description, as shown in the following code:
import java.io.File;
import javax.swing.filechooser.FileFilter;

public class FileTypeFilter extends FileFilter {

private String extension;
private String description;

public FileTypeFilter(String extension, String description) {

this.extension = extension;
this.description = description;

public boolean accept(File file) {

if (file.isDirectory()) {
return true;
return file.getName().endsWith(extension);

public String getDescription() {

return description + String.format(" (*%s)", extension);

Then we can add several file filters as following:

FileFilter docFilter = new FileTypeFilter(".docx", "Microsoft Word
FileFilter pdfFilter = new FileTypeFilter(".pdf", "PDF Documents");
FileFilter xlsFilter = new FileTypeFilter(".xlsx", "Microsoft Excel


Before Java 6, we have to write the above code manually. Fortunately, since Java 6,
Swing adds a new class called FileNameExtensionFilter, which makes adding file
filters easier. For example:
fileChooser.addChoosableFileFilter(new FileNameExtensionFilter("PDF
Documents", "pdf"));

We also can accumulate multiple extensions together:

fileChooser.addChoosableFileFilter(new FileNameExtensionFilter("Images",
"jpg", "png", "gif", "bmp"));

And following is a sample program that shows an open dialog when the button
Browse is clicked, with some filters for: PDF documents, MS Office documents, and
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.filechooser.FileNameExtensionFilter;

* Demo of file extension filter. Applied since Java 1.6
* @author www.codejava.net
public class FileExtensionFilterDemo extends JFrame {
private JButton buttonBrowse;

public FileExtensionFilterDemo() {
super("Demo File Type Filter");
setLayout(new FlowLayout());
buttonBrowse = new JButton("Browse...");
buttonBrowse.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
setSize(300, 100);

public static void main(String[] args) {

try {

} catch (Exception e) { }
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new FileExtensionFilterDemo();

private void showOpenFileDialog() {

JFileChooser fileChooser = new JFileChooser();
fileChooser.addChoosableFileFilter(new FileNameExtensionFilter("PDF
Documents", "pdf"));
fileChooser.addChoosableFileFilter(new FileNameExtensionFilter("MS
Office Documents", "docx", "xlsx", "pptx"));
FileNameExtensionFilter("Images", "jpg", "png", "gif", "bmp"));
int result = fileChooser.showOpenDialog(this);
if (result == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
System.out.println("Selected file: " +

Generate random numbers in Java - How to use the java.util.Random class to

generate desired random number in Java program?

In this tutorial I will teach you how to write Java code using the java.util.Random
class to generate single or a set of random numbers in your program.

We are using the java.util.Random class for generating the random number.

We are using the randomGenerator.nextInt(num) method to generate the random

number. The java.util.Random class is used to generate the random integers, doubles,
int etc..

Following code can be used to generate a random number between 0,1000:

int randomInt = randomGenerator.nextInt(1000);

Following is the code to generate 10 random number between 0 and 1000:

import java.util.Random;

/** Example of Random Number generation in Java*/

public final class RandomGenerator {

public static final void main(String... aArgs){

Random randomGen = new Random();

for (int idx = 1; idx <= 10; ++idx){
int randomInt = randomGen.nextInt(1000);
System.out.println("Generated Number: " + randomInt);


If you run the above code following output will be displayed on the browser:
Cloneable interface in a class points out that it is legal for Object.clone() method to
copy instances of that class. In simple words, a class defines Cloneable Interface if it
wants its object to be cloned. However, it is not necessary that a Cloneable interface
contains a clone() method.

clone( ) method creates a duplicate object that has distinct identity but similar content.

Class that implements Cloneable Interface should override Object.clone method.

It must also be noted that just invoking an Object's clone method on an instance does
not implement the Cloneable interface. If an object's class does not implement the
Cloneable interface, CloneNotSupportedException is thrown.

CloneNotSupportedException is also thrown to indicate that a particular object should

not be cloned.

Example of Clone method:

import java.util.*;

public class CloneTest{

public static void main(String[] args){

Employee emp = new Employee("Amardeep", 50000);


Employee emp1 = (Employee)emp.clone();


emp1.setHireDay(2008, 12, 31);

System.out.println("Employee=" + emp);

System.out.println("copy=" + emp1);

class Employee implements Cloneable{

public Employee(String str, double dou){

name = str;

salary = dou;

public Object clone(){


Employee cloned = (Employee)super.clone();

cloned.hireDay = (Date)hireDay.clone();

return cloned;

catch(CloneNotSupportedException e){


return null;

public void setHireDay(int year, int month, int day){

hireDay = new GregorianCalendar(year,month - 1, day).getTime();

public void raiseSalary(double byPercent){

double raise = salary * byPercent/100;

salary += raise;

public String toString(){

return "[name=" + name+ ",salary=" + salary+ ",hireDay=" + hireDay+ "]";

private String name;

private double salary;

private Date hireDay;

C:\help>javac CloneTest.java

C:\help>java CloneTest

Employee=[name=Amardeep,salary=50000.0,hireDay=Tue Nov 30 00:00:00 GMT+05:30


copy=[name=Amardeep,salary=60000.0,hireDay=Wed Dec 31 00:00:00 GMT+05:30


Copy data from one JTextField to another


In this example, you will learn how to copy the data from one JTextField into another
JTextField. When you run this program it starts with two JTextField. Enter some data
into first JTextfield and select the entered text, right click, copy and then paste into
another JTextField.

JTextField is used in the swing application to develop user input box. It is a

lightweight component that allows the user to enter and edit the data in a single line.

You can use JTextField into your swing applications to develop data entry forms.


When you run the program following output is displayed:

Enter some data into first text field (cell1). Highlight all the text in first cell. After
selecting you right click the mouse button and copy the text of cell 1.

And go cell 2 paste the copied text to cell 2.

Here is the code of Program:

import java.awt.*;
import java.awt.event.*;
import java.awt.datatransfer.*;
import java.io.*;
import java.util.*;
import javax.swing.*;
import javax.swing.text.*;
import javax.swing.table.*;

public class TCPopupEventQueue extends EventQueue {

public JPopupMenu popup;
JTable table;
public BasicAction cut, copy, paste, selectAll;

public TCPopupEventQueue() {

public void createPopupMenu(JTextComponent text){

cut = new CutAction("Cut",null);
copy = new CopyAction("Copy", null);
paste = new PasteAction("Paste",null);
selectAll = new SelectAllAction("Select All",null);

popup = new JPopupMenu();

popup.add( cut );
popup.add( copy );
popup.add( paste );
popup.add( selectAll );

public void showPopup(Component parent, MouseEvent me){

popup.show(parent, me.getX(), me.getY());

protected void dispatchEvent(AWTEvent event){

if(!(event instanceof MouseEvent)){
MouseEvent me = (MouseEvent)event;
if(!me.isPopupTrigger()) {
if( !(me.getSource() instanceof Component) ) {
Component comp = SwingUtilities.getDeepestComponentAt((Component)
me.getSource(),me.getX(), me.getY());
if( !(comp instanceof JTextComponent)){
if(MenuSelectionManager.defaultManager().getSelectedPath().length > 0){
showPopup((Component)me.getSource(), me);
public abstract class BasicAction extends AbstractAction{
JTextComponent comp;

public BasicAction(String text, Icon icon) {

super(text, icon);
putValue(Action.SHORT_DESCRIPTION, text);
public void setTextComponent(JTextComponent comp){
this.comp = comp;
public abstract void actionPerformed(ActionEvent e);
public class CutAction extends BasicAction {
public CutAction(String text, Icon icon) {
super(text, icon);
putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke("ctrl X"));
public void actionPerformed(ActionEvent e){
public boolean isEnabled(){
return comp != null && comp.isEditable() && comp.getSelectedText() != n
public class CopyAction extends BasicAction{
public CopyAction(String text, Icon icon){
putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke("ctrl C"));
public void actionPerformed(ActionEvent e) {
public boolean isEnabled() {
return comp != null && comp.getSelectedText() != null;
public class PasteAction extends BasicAction{
public PasteAction(String text, Icon icon){
putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke("ctrl V"));
public void actionPerformed(ActionEvent e) {
public boolean isEnabled() {
Transferable content = Toolkit.getDefaultToolkit().getSystemClipboard()
return comp != null && comp.isEnabled() && comp.isEditable()
&& content.isDataFlavorSupported(DataFlavor.stringFlavor);

public class SelectAllAction extends BasicAction{

public SelectAllAction(String text, Icon icon){
putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke("ctrl A"));
public void actionPerformed(ActionEvent e){
public boolean isEnabled() {
return comp != null && comp.isEnabled() && comp.getText().length() > 0
&& (comp.getSelectedText() == null ||
comp.getSelectedText().length() < comp.getText().length());
public static void main(String[] args) {
Toolkit.getDefaultToolkit().getSystemEventQueue().push( new TCPopupEventQ
JTextField field = new JTextField(20);
JTextField field1 = new JTextField(20);
JPanel center = new JPanel( new FlowLayout(FlowLayout.LEFT) );

center.add(new JLabel("cell1:"));
center.add(new JLabel("cell2:"));
JPanel content = new JPanel( new FlowLayout(FlowLayout.LEFT) );
content.add( center, BorderLayout.SOUTH );
JFrame frame = new JFrame("cell copy past program");