Gujarati Typing in Java Application

This Example shows how to use the 3rd party font (.ttf) in our java application. This sometime need when we want to use strictly to some of the other languages like Gujarati, etc. We just need to have a .ttf(True Type Font) file which is need to be loaded by programming in our application.

import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.JScrollPane;
import javax.swing.JOptionPane;
import java.io.IOException;
import java.io.InputStream;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.awt.Font;
import java.awt.FontFormatException;

class GujaratiType extends JFrame
{
public Font font,fontUsed;
public GujaratiType()
{
try
{
InputStream myStream = new BufferedInputStream(new FileInputStream("LMG_LAX1.ttf"));
font = Font.createFont(Font.TRUETYPE_FONT, myStream);
fontUsed = font.deriveFont(Font.PLAIN,20);
}
catch(FontFormatException ex)
{
JOptionPane.showMessageDialog(GujaratiType.this,ex,"Error",JOptionPane.ERROR_MESSAGE);
System.exit(0);
}
catch(IOException ex)
{
JOptionPane.showMessageDialog(GujaratiType.this,"System can not find the file : LMG_LAX1.TTF","Error",JOptionPane.ERROR_MESSAGE);
System.exit(0);
}
JTextArea txt = new JTextArea();
txt.setFont(fontUsed);
JScrollPane jsp = new JScrollPane(txt);
add(jsp);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(0,0,300,300);
//setSize(300,300);
setVisible(true);
}
public static void main(String[] a)
{
new GujaratiType();
}
}

FizzBuzz Program

Following is the program for FizzBuzzProblem. It is program to print numbers from 1 to 100, but if the number is multiple of 3 then number should be replaced with "Buzz", if the number is multiple of 5 then number should be replaced with "Fizz", and if the number is multiple of both 3 and 5 then number should be replaced with "FizzBuzz".

public class FizzBuzzProblem
{
    public static void main(String args[])
    {
        for(int i = 1; i <= 100; i++)
        {
            if((i % (3*5)) == 0)
            {
                System.out.println("FizzBuzz");
            }
            else if ((i % 5) == 0)
            {
                System.out.println("Buzz");
              }
            else if ((i % 3) == 0)
            {
                System.out.println("Fizz");
            }
            else
            {
                System.out.println(i);
              }
        }
    }
}

Methods of Iteration we can perform on List

There are five methods we can iterate the List to view its data. I have wrapped up all five methods in one program.

import java.util.List;
import java.util.ListIterator;
import java.util.Iterator;
import java.util.ArrayList;
import java.util.Arrays;

public class ListDemo
{
public static void main(String[] args)
{
List al = new ArrayList();

al.add(0,100);
al.add(1,20);
al.add(2,8);
al.add(3,65);
al.add(4,102);
al.add(5,88);
al.add(6,88);

System.out.println(al+"\n");

Iterator i = al.iterator(); // First Method to iterate
while(i.hasNext())
System.out.print(i.next() + " ");

System.out.println("\n");
Object ob[] = al.toArray(); // Second Method to iterate
Arrays.sort(ob);
for(Object o : ob)
System.out.print(o + " ");

System.out.println("\n");
ListIterator li = al.listIterator();// Third Method to iterate
while(li.hasNext())
System.out.print(li.next() + " ");


System.out.println("\n\nNow in backward");// iterate previous element
System.out.println("--- -- --------");
ListIterator li1 = al.listIterator();
while(li1.hasNext())li1.next();
while(li1.hasPrevious())
System.out.print(li1.previous() + " ");

System.out.println("\n");
for(int i1 = 0 ;i1 < al.size(); i1++) //Forth Method to iterate
{
System.out.print( al.get(i1) + " " );
}

al.set(3,"pranav");
System.out.println("\n");
System.out.println(al+"\n");

}
}

Can Interface have main method ?

First of all try to look at the following code and execute it on your own.

public interface testinterface1
{
String message = "welcome to this group";
static int add ( int a, int b)
{
return a+b;
}
public static void main(String j[])
{
System.out.println(message);
int x=5;
int y=15;
System.out.println(" sum of numbers " + x + " and " + y + " is " + add(x,y));
}
} 

Very first though we may have that this code will not even compile at all and it is true but this will compile in java8. Yes this is true, we can have main method in interface in java8. so try it in java8 and this code will compile for sure. 

Use of intern() in java

First of all, type the below code snippet and save it as Test.java , the compile and run it. and then view the description below code is given.

public class Test{
public static void main(String[] args){
String s1 = "Java";
String s2 = new String("Java");
System.out.println(s1==s2);
s2=s2.intern();
System.out.println(s1==s2);
}
}

When the intern() method is invoked on a String, a lookup is performed on a table of interned Strings. If a String object with the same content is already in the table, a reference to the String in the table is returned. 
Otherwise, the String is added to the table and a reference to it is returned. 
The result is that after interning, all Strings with the same content will point to the same object. 
This saves space, and also allows the Strings to be compared using the == operator, which is much faster than comparison with the equals(Object) method.
So in simple way this function my useful in development.

Example of JTabbedPane

Sometime we need to have something like multiple tabs like in chrome we have. So here i am posting a simple example of JTabbedPane which may help you in any way.

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

class TabDemo extends JFrame
{
JTabbedPane tb;
JTextArea txt;
private int tabCounter = 1;
public TabDemo()
{
tb = new JTabbedPane();
addTab();
setJMenuBar(createMenuBar());
getContentPane().add(tb,BorderLayout.CENTER);
//addTab();
setVisible(true);
setBounds(20,20,400,400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private JMenuBar createMenuBar()
{
JMenuBar mb = new JMenuBar();
JMenu file = new JMenu("File");
JMenuItem newFile = new JMenuItem("New");
newFile.setAccelerator(KeyStroke.getKeyStroke('N',KeyEvent.CTRL_DOWN_MASK));
newFile.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
addTab();
}
});
JMenuItem saveFile = new JMenuItem("Save");
saveFile.setAccelerator(KeyStroke.getKeyStroke('S',KeyEvent.CTRL_DOWN_MASK));
saveFile.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
int x = tb.getSelectedIndex();
JScrollPane jsp = (JScrollPane)tb.getComponentAt(x);
JTextArea tx = (JTextArea) jsp.getViewport().getView();
//JOptionPane.showMessageDialog(TabDemo.this,tx.getText());
fileSaver(tx.getText());
}
});
file.add(newFile);
file.add(saveFile);
mb.add(file);
return mb;

}
void addTab()
{
txt = new JTextArea();
JScrollPane txtPnl = new JScrollPane(txt);
JPanel tbPnl = new JPanel();
tbPnl.setOpaque(false);
tbPnl.setLayout(new FlowLayout());
JLabel lbl = new JLabel("Tab - "+tabCounter);
JButton btnClose = new JButton("X");
tbPnl.add(lbl);
tbPnl.add(btnClose);
tb.addTab(null,txtPnl);
btnClose.setActionCommand(""+tabCounter);
btnClose.setFont(new Font("Serif",1,9));
lbl.setFont(new Font("Serif",1,9));
btnClose.setOpaque(false);
btnClose.setBorder(null);
btnClose.setBackground(Color.RED);
ActionListener al = new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
JButton btn =(JButton) e.getSource();
String str = btn.getActionCommand();
for(int i =0 ;i <tb.getTabCount();i++)
{
JPanel pnl = (JPanel)tb.getTabComponentAt(i);
btn = (JButton)pnl.getComponent(1);
String str2 = btn.getActionCommand();
if(str.equals(str2))
{
tb.removeTabAt(i);
tabCounter--;
break;
}
}
}
};
btnClose.addActionListener(al);

//tb.setTabComponentAt(tb.getTabCount()-1 ,lbl);
tb.setTabComponentAt(tb.getTabCount()-1 , tbPnl);
tb.setSelectedIndex(tb.getTabCount() - 1);
tabCounter++;
}
public static void main(String []args)
{
new TabDemo();
}
private void fileSaver(String text)
{
JFileChooser chooser = new JFileChooser();
int result = chooser.showSaveDialog(TabDemo.this);

/*if(result != JFileChooser.APPROVE_OPTION)
{ return false; }*/
File file = chooser.getSelectedFile();
setTitle(file.getName());

try
{
FileOutputStream out = new FileOutputStream(file);
//String str = txt.getText();
byte b[] = text.getBytes();
out.write(b);
out.close();
//return true;
}
catch(Exception ex){}//return false;}
}
}

Now Type the above code in text editor save it as TabDemo.java.
Then compile it by command javac TabDemo.java
and execute it by command java TabDemo

A Simple Enumeration demo in java

Here is a code for simple enum in java.

enum Cal
{
ADD
{
public double compute(double a, double b)
{ return a+b; };
},
SUB
{
public double compute(double a, double b)
{ return a-b; };
},
MUL
{
public double compute(double a, double b)
{ return a*b; };
},
DIV
{
public double compute(double a, double b)
{ return a/b; };
},
MOD
{
public double compute(double a, double b)
{ return a%b; };
},
;

public abstract double compute(double a, double b);


public static void main(String[] ar)
{
String opName = ar[0].toUpperCase();
double a = Double.parseDouble(ar[1]);
double b = Double.parseDouble(ar[2]);

System.out.println(Cal.valueOf(opName).compute(a,b));
}
}

To execute this code type the above code in any text editor and compile it by the command javac Cal.java and execute it by command java Cal 10 ADD 20

Differentiate Total Zeros and Total Non Zeros from a whole number

A simple program to differentiate the Zeros and non zeros value from a complete number.

public class DiffZeroNonZero{
public static void main(String[] args){
long no;
try{
no = Long.parseLong(args[0]);
}catch(ArrayIndexOutOfBoundsException ex){
System.out.println("Please provide proper number as argument....");
return;
}
long tmp_z=0,tmp_nz=0,a;
int count_z=0,count_nz=0;
int pos_z = 0;
int pos_nz = 0;
System.out.println("\n\nEntered Nuber Is :-> " + no);
//Storing the number for future use.....
tmp_z = no;
tmp_nz = no;
//Getting the number of zeros and non_zeros from whole number.....
while(no>0){
a = no%10;
if(a!=0)
count_nz++;
else
count_z++;
no=no/10;
}
long zeros[] = new long[count_z];
long non_zeros[] = new long[count_nz];
//Storing the values of zeros and non_zeros in different arrays....
while(tmp_nz>0){
a = tmp_nz%10;
if(a!=0){
non_zeros[pos_nz++]=a;
}
tmp_nz=tmp_nz/10;
}
while(tmp_z>0){
a = tmp_z%10;
if(a!=0){
}else{
zeros[pos_z++]=a;
}
tmp_z=tmp_z/10;
}
//Printing both the arrays to user.....
System.out.print("\n\n Zeros :->" + java.util.Arrays.toString(zeros));
System.out.print("\n\n Non Zeros :->" + java.util.Arrays.toString(non_zeros));
}
}

Default and Escape Button in Java

We may sometimes need to have that when we press the enter key it automatically performs some tasks.
And when we press the escape key it automatically exits the application or like else.
So here is a simple example to do so.

import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.KeyStroke;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.ActionEvent;

public class DefaultEscapeButton extends JFrame
{
JButton btn1,btn2;
        //Preparing ActionListener for escape key pressed
ActionListener al = new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
};
DefaultEscapeButton()
{
setLayout(null);
btn1 = new JButton("Default");
btn1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
System.out.println(btn1.getText());
}
});
btn1.setBounds(10,10,150,30);
btn2 = new JButton("Cancel");
btn2.setBounds(10,50,150,30);
                //This is the code for when Escape key is pressed
getRootPane().registerKeyboardAction(al,KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE,0),JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);


add(btn1);
add(btn2);
getRootPane().setDefaultButton(btn1);
setVisible(true);
setSize(300,300);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args)
{
new DefaultEscapeButton();
}
}

Add Button in Tab of JTabbedPane

There are lots of things we can do in the desktop application using java's swing technology. One of  which here is adding a button to the Tab for some help user to closing the tab, etc. This kind of example can help to build some application having facility for multiple infinite tab like Browser application, or a kind of text editor, etc.

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JToolBar;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;

public class AddButtonToTabBar extends JFrame {
private JTabbedPane tp;
private int tabCounter = 0;

public AddButtonToTabBar() {
super("Editor");
setDefaultCloseOperation(EXIT_ON_CLOSE);

JToolBar jtb = new JToolBar();
JButton btnAdd = new JButton("Add Tab");
ActionListener addTabl = new ActionListener() {
 public void actionPerformed(ActionEvent e) {
addTab();
 }
};
btnAdd.addActionListener(addTabl);
jtb.add(btnAdd);

JPanel pnlURL = new JPanel();
tp = new JTabbedPane();
addTab();
getContentPane().add(jtb, BorderLayout.NORTH);
getContentPane().add(tp, BorderLayout.CENTER);

setSize(700, 700);
setVisible(true);
}

void addTab() {
// A Simple Text editor
JEditorPane ep = new JEditorPane();
ep.setEditable(true);
tp.addTab("Tab - " + tabCounter, new JScrollPane(ep));

//Preparing a button to add 
JButton tabCloseButton = new JButton("X");
tabCloseButton.setActionCommand("" + tabCounter);

//ActionListener for what to do when the button is clicked, here is to close the particular tab
ActionListener al = new ActionListener() {
public void actionPerformed(ActionEvent ae) {
JButton btn = (JButton) ae.getSource(); // It will get the button object which is clicked
String s1 = btn.getActionCommand();
for (int i = 1; i < tp.getTabCount(); i++) {
JPanel pnl = (JPanel) tp.getTabComponentAt(i); // It will return the whole component which we had set in the Tab

// It will get the button component. The parameter for the getComponent 
// is index of the total number of component. Here 1 means the button and 0 means the lable.
btn = (JButton) pnl.getComponent(1);
String s2 = btn.getActionCommand();
if (s1.equals(s2)) {
tp.removeTabAt(i);
break;
}
}
}
};
tabCloseButton.addActionListener(al);

// This condition is to make at least one tab to be in the application.
if (tabCounter != 0) {
JPanel pnl = new JPanel();
pnl.setOpaque(false);
pnl.add(new JLabel("Tab - "+tabCounter));
pnl.add(tabCloseButton);
tp.setTabComponentAt(tp.getTabCount() - 1, pnl);
tp.setSelectedIndex(tp.getTabCount() - 1);
}
tabCounter++;
}

public static void main(String[] args) {
new AddButtonToTabBar();

}
}

Write the above program, save it as AddButtonToTabBar.java , compile it and run it.

Open Other applications using java

Sometime in our application we need to open any other 3rd party applications like notepad, music applications, etc. We can do the same using java by using Process class which is already available in java.lang package. Here is the simple program for the opening a notepad application.

public class OpenApplication 
{
public static void main(String[] args) throws Exception 
{
try
{
Process p = Runtime.getRuntime().exec("notepad.exe");
p.waitFor(); //waits for the application to close
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
}

In above example whatever we write in the exec() method it will execute if it is executable. This method will only except the executable file having extension of .exe if the file is not having the .exe extension it will throw the java.io.IOException.

Now write & save the program, compile it and run it.

Duplicate element in Array

Very often question may be asked in education or in any interview is to find the duplicate element in array. Here is an example to find it using java. I have describe it by two ways there can be lots of ways but this two methods I have found usable.

public class DuplicateInArray{
public static void main(String[] args){
String[] arr1 = {"Test","Hi", "Test","Hello","test","Hi"};

// Using Brute force method
System.out.println("Using Brute force method\n============================");
for(int i=0; i < arr1.length-1; i++){
for(int j=i+1; j < arr1.length; j++){
if( (arr1[i].equals(arr1[j])) && (i != j) ){
System.out.println(arr1[i] + " : " + arr1[j]);
}
}
}

//Using Hash set method
System.out.println("\nUsing Hash set method\n============================");
java.util.HashSet<String> set = new java.util.HashSet<String>();
for(String element : arr1){
if(!(set.add(element))){
System.out.println(element);
}
}

System.out.println(set);
}
}

Write the above program and save it as DuplicateInArray.java and compile it as javac DuplicateInArray.java and execute it as java DuplicateInArray.

Directory Counter in Java

Here is a simple example for directory counter. This example will just count the directory/folders where the .class file be. For example the .class will be in the root directory or in C:/ directory it will count all the folders in it excepts sub-folders.

import java.io.File;

public class DirCount{
static int count = 0;
public static void main(String[] args){
if(args.length == 0){
System.out.println("Usage : DirCount <FolderPath>");
System.exit(0);
}
try{
File f = new File(args[0]);
File[] fs = f.listFiles();
for(File ff : fs){
if(ff.isDirectory()){
count++;
}
}
System.out.println("Total Numbers of directories : " + count);
}catch(Exception ex){
System.out.println("Provide proper path");
}
}
}

Write the above program and save it as DirCount.java.
Now compile the program by command javac DirCount.java and execute the class file by java DirCount

Object Cloning

Java have verity of facilities in the programming, One of which is Object cloning.

For Object Cloning we first have implement the Cloneable interface and have to implement its method clone() which returns the Object type.

Object cloning is use to save the time of processing task to make exact copy of the object. We can also do it by the new keyword but it will take a lot of time in crating copy of the object. So here is the simple example of object cloning.

class Test implements Cloneable{
int x = 0;
public Object clone(){
try{
return super.clone();
}
catch(CloneNotSupportedException ex){
System.out.println(ex.getMessage());
}
return null;
}

public void setNum(int x){
this.x = x;
}
public int getNum(){
return this.x;
}
}

class TestDemo{
public static void main(String[] args){
Test origin = new Test();
origin.setNum(20);
System.out.println("before : " + origin.getNum());

Test copy = (test)origin.clone();
copy.setNum(40);

System.out.println("after copy: " + copy.getNum());
System.out.println("after origin: " + origin.getNum());


}
}

Write the above program in any text editor (recommended notepad/notepad++) save it as TestDemo.java.
Compile it by the command javac TestDemo.java and execute it by java TestDemo.