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.