In Swing, how to use JTabbedPane to create multiple Tabs

Below are the Swing UI Components used in this example
JPanel
JTabbedPane
JButton
JCheckBox
JComboBox

There are three Tabbed Panes, implemented in below classes.
1.CitiesPanel(extends from JPanel)
2.ColorsPanel(extends from JPanel)
3.FlavorsPanel(extends from JPanel)

CitiesPanel has four JButton components with City names.
When any of these Buttons are clicked, corresponding label on JButton, is set to JTextField.
CitiesPanel implements java.awt.event.ActionListener interface, to handle button click event.

JTabbedPane example
JTabbedPane example

ColorsPanel has three JCheckBox components with Color names.
When any of the check box is selected/unselected, name of check box gets displayed on dialog box, using JOptionPane.
ColorsPanel implements java.awt.event.ItemListener interface, to handle check box check/uncheck event.

JTabbedPane example
JTabbedPane example

FlavorsPanel has a JComboBox, with Fruit names.
When any item is selected from the drop down combox box. The selected item text, is set to JTextField.
FlavorsPanel implements java.awt.event.ItemListener interface, to handle combo box item selected event.

JComboBox-example
JComboBox-example

import javax.swing.*;

import java.awt.event.*;

/* 
 * 
 */

public class TabbedPaneDemo extends JApplet{
public void init()
	{
	JTabbedPane jtp = new JTabbedPane();
	jtp.addTab("Cities", new CitiesPanel());
	jtp.addTab("Colors", new ColorsPanel());
	jtp.addTab("Flavors", new FlavorsPanel());

	getContentPane().add(jtp);
	}

}

class CitiesPanel extends JPanel implements ActionListener{
	JTextField jft;
	public CitiesPanel(){
	JButton b1 = new JButton("Bangalore");
	b1.addActionListener(this);
	add(b1);
	JButton b2 = new JButton("Mumbai");
	b2.addActionListener(this);
	add(b2);
	JButton b3 = new JButton("Chennai");
	b3.addActionListener(this);
	add(b3);
	JButton b4 = new JButton("Delhi");
	b4.addActionListener(this);
	add(b4);

	jft = new JTextField(8);

	add(jft);

	}

	public void actionPerformed(ActionEvent ae)
	{
	String str = ae.getActionCommand();
	jft.setText(str);
	}
}

class ColorsPanel extends JPanel implements ItemListener{

	JCheckBox cb1,cb2,cb3;
	public ColorsPanel(){
	cb1 = new JCheckBox("Yellow");
	add(cb1);

	cb2 = new JCheckBox("Grey");
	add(cb2);

	cb3 = new JCheckBox("Blue");
	add(cb3);

	cb1.addItemListener(this);
	cb2.addItemListener(this);
	cb3.addItemListener(this);
	}

	public void itemStateChanged(ItemEvent ie)
	{
	JCheckBox cb = (JCheckBox)ie.getItem();
	JOptionPane.showMessageDialog(null, "You Selected:"+cb.getText());
	}
}


class FlavorsPanel extends JPanel implements ItemListener{
	JTextField jft1;
	public FlavorsPanel(){
	JComboBox jcb = new JComboBox(); //Drop down menu
	jcb.addItem("Mango");
	jcb.addItem("Orange");
	jcb.addItem("Chocolate");
	add(jcb);

	jft1 = new JTextField(8);
	jft1.setText("No Item Selected");
	add(jft1);

	jcb.addItemListener(this);
	}

	public void itemStateChanged(ItemEvent ie)
	{
	String str = (String)ie.getItem();

	jft1.setText(str);
	}
}

You may also like to read:
Advantages of Swing over Applet

What is an Applet, and its Life Cycle

An Applet, is used to develop Graphical User Interface Programs in Java.

Also Applets can be embedded as part of a HTML form. All Apllets need to inherit from java.applet.Applet class. Below are Life Cycle Methods, which need to be ovveridden in the Derived class of Applet

import java.applet.Applet;
import java.awt.Graphics;

/*
<applet code="AppletLifeCycleExample" width=150 height=150>
</applet>
*/

public class AppletLifeCycleExample extends Applet{

   /* Constructor is invoked first, when instance of the Applet is created */
   public AppletLifeCycleExample()
   {
   System.out.println("AppletLifeCycleExample()");
   }

    /*
     * init method is called only once, just before displaying
     * applet window
     */
    public void init() {
    super.init();
    System.out.println("init()");
    }

    /*
     * start method is called, whenever applet is displayed(first time)
     * or re displayed(whenever applet window is maximized, or when navigated back)
     */
    public void start() {
    super.start();
    System.out.println("start()");
    }

    /*
     * stop method is called when ever user navigates away or minimizes
     * the applet.
     */
    public void stop() {
    super.stop();
    System.out.println("stop()");
    }

    /* paint method is called every time applet need to be redrawn
     * It is possible to explicitly invoke paint(), using repaint() method
     */
    public void paint(Graphics g) {
    super.paint(g);
    System.out.println("paint()");
    }

    /*
     * destroy method is called only once when this applet is about to be completely destroyed.
     * Add cleanup code to free resources which are initialized
     * during the init method.
     */
    public void destroy() {
    super.destroy();
    System.out.println("destroy()");
    }

}
Output:
AppletLifeCycleExample()
init()
start()
paint()
stop() --minimized applet--
start() --maximized applet--
paint()
stop() -- again minimized applet--
start() -- again maximized applet--
paint()
stop() -- closed applet--
destroy()

You may also like to read:
Advantages of Swings compared to Applet

Advantages of Swing Over Applets

Both Applet and Swing provides Graphical user interface to Standalone Java Programs. These days Swing has almost replaced Applet, due to below Advantages.
1. Swing is light weight, compared to Applet.
2. Swing has rich set of UI Components, like Image Button, Tabbed Pane,etc…
3. Swing provide common look and feel, across various Platforms, as Swing has built in UI Tool kit. But Applet uses different local UI Tool Kit for each Platform, hence for Applets Look and feel differs across platforms.

Swing UI Component classes are available in javax.swing package.

Below is list of commonly used Swing UI Component classes

UI Component Description
AbstractButton
ButtonGroup
JApplet Swing version of Applet
JButton Swing Button class
JCheckBox Swing Check box class
JComboBox Swing Combo box class
JFrame extended version of java.awt.Frame, which adds support for the JFC/Swing component architecture
JLabel Swing Label class
JOptionPane displays pop up a standard dialog box that prompts users for a value or informs something
JRadioButton Swing radio button class
JScrollPane used to display scroll bars
JTabbedPane Displays Tabbed based windows
JTable To display data in rows and columns
JTextArea editable multiline text
JTextField editable one line text field
JTree Displays Tree hierarchy, For eg. can be used to display Folder structure,etc…

Below is example Login form, using Swing

import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.DataInputStream;
import java.io.DataOutputStream;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class LoginForm implements ActionListener {

	JFrame jf;
	JPanel p1, p2;
	JLabel l1, l2;
	JTextField t1, t2;
	JButton b1, b2;
	public Font f2 = new Font("Calibrie", Font.BOLD, 13);
	JLabel name = new JLabel("Login Form");

	public Font f1 = new Font("Bell MT", Font.BOLD, 14);

	LoginForm() {

	jf = new JFrame("Login-Form");
	p1 = new JPanel();
	p2 = new JPanel();
	p1.setLayout(null);
	jf.setLayout(null);

	name.setBounds(80, 0, 300, 50);
	name.setFont(f2);
	name.setForeground(Color.blue);
	p1.add(name);

	l1 = new JLabel("Username:");
	l1.setBackground(Color.LIGHT_GRAY);
	l2 = new JLabel("Password:");
	l2.setBackground(Color.LIGHT_GRAY);

	t1 = new JTextField(15);

	t2 = new JTextField(15);

	b1 = new JButton("SUBMIT");
	b2 = new JButton("CANCEL");

	l1.setBounds(50, 50, 100, 30);
	l2.setBounds(50, 100, 100, 30);

	t1.setBounds(150, 50, 150, 30);
	t2.setBounds(150, 100, 150, 30);

	b1.setBounds(70, 200, 100, 30);
	b1.setForeground(Color.RED);
	b1.setBackground(Color.black);
	b1.setFont(f1);
	b2.setBounds(190, 200, 100, 30);
	b2.setForeground(Color.RED);
	b2.setBackground(Color.black);
	b2.setFont(f1);
	p1.setBounds(50, 50, 350, 300);
	p1.setBackground(Color.LIGHT_GRAY);

	p2.setBounds(1, 1, 460, 400);
	p2.setBackground(Color.DARK_GRAY);

	p1.add(l1);
	p1.add(l2);
	p1.add(t1);
	p1.add(t2);
	p1.add(b1);
	p1.add(b2);

	jf.add(p1);
	jf.add(p2);

	jf.setBounds(100, 50, 471, 437);
	jf.setVisible(true);

	b1.addActionListener(this);
	b2.addActionListener(this);
	}

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

	public void actionPerformed(ActionEvent e) {

	if (e.getSource() == b1) {

	String uname = t1.getText();
	String pwd = t2.getText();

	if (name.equals("")) {
	JOptionPane.showMessageDialog(null, "Enter UserName");
	} else if (pwd.equals("")) {
	JOptionPane.showMessageDialog(null, "Enter Password");
	} else {
	JOptionPane.showMessageDialog(null, "Your username:"+uname+" pwd is:"+pwd);
	t1.setText("");
	t2.setText("");
	}
	}

	if (e.getSource() == b2) {
	t1.setText("");
	t2.setText("");
	}

	}
}

You may also like to read:

Similarities and differences between Vector and ArrayList

Similarities between Vector and ArrayList

1. Both are classes in java.util package
2. Both ArrayList and Vector are implemented from java.util.Collection interface.
Both are based on dynamic arrays
3. Collections class static methods can be applied to both Vector and ArrayList
4. Both can store duplicates, and maintains insertion order of elements.

Differences between Vector and ArrayList

ArrayList
Vector
ArrayList is not Synchronized, by default Vector is synchronized
ArrayList implements methods of Collection interface Vector provides other legacy methods, in addition to methods of Collection interface
ArrayList is Faster, as it is not Synchronized Vector is slower, as it is Synchronized
ArrayList is not Legacy class. ArrayList is introduced along with Collection Framework, in Java 1.2 Vector is Legacy class, and exists since initial version of Java. In Java 1.2, Vector has been accommodated in Collection Framework, and its Legacy methods were preserved, as well
When no more room exists to store an added element, size is increased by half of current size In case of Vector size gets increased by the current size

Methods declared in Collection interface

You may also like to read:
When to use List or Set
What are Synchronized Collections

How to use HashSet, to store our own objects
What is Map?

Java Servlet and Life Cycle

A Servlet is a Java Program, which runs on any Web Server(Tomcat Server, Glass Fish Server, Web Logic, Web Sphere). Servlet receives request from Web Browser on Client Machine. Below are Life cycle methods for a Servlet.

public void init(ServletConfig config);
This method is invoked when Servlet instance does not exist, and on receiving first request from Web Browser. init() method is not invoked, for each and every request. Constructor of Servlet is executed before init() method.

public void service(ServletRequest request, ServletResponse response);
This method is invoked, whenever a request is received from Web Browser. This method processes, and provides response to the Request. This method further invokes doGet() or doPost() method, based on GET or POST HTTP Request.

public void destroy();
This method is invoked, when Servlet instance gets destroyed, which may occur, when no requests, or when Web Server is shutdown, or garbage collection, to reclaim memory,etc…

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LifeCycle extends HttpServlet
{

	public LifeCycle()
	{
		System.out.println("Am from default constructor");
	}

	public void init(ServletConfig config)
	{
		System.out.println("Am from Init method...!");
	}

        public void doGet(HttpServletRequest req,HttpServletResponse res)
                throws ServletException,IOException
        {
            System.out.println("Am from doGet method...!");
            PrintWriter out = res.getWriter();

            out.println(" from doGet()
"); } public void doPost(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException { System.out.println("Am from doPost method...!"); PrintWriter out = res.getWriter(); out.println(" from doPost()
"); } public void destroy() { System.out.println("Am from Destroy methods"); } } Output(on Server Console, when request is sent to Web Server): INFO: Am from default constructor INFO: Am from Init method...! INFO: Am from doGet method...!

It is required to be aware of Servlet Life Cycle methods, to develop efficient Java Servlets.

You may also like to read:
Purpose of Filter in Servlets
How many implicit objects are in JSP
Program to send HTTP Request to Web Server

Methods in Object class

As known java.lang.Object is base class, of all classes in Java.

Below are the methods of Object class, that means each and every object can invoke below methods.

Method Declaration Method Details
1 protected Object clone() creates a copy of current object, and returns
2 boolean equals(Object obj); This method returns whether the object(sent as parameter) is equal to invoking object.
3 protected void finalize(); When there are no more references to the object, garbage collector, may invoke this method.(This method acts just like destructor of the c plus plus class)
4 Class getClass(); returns runtime class of the invoking.
5 int hashCode(); returns unique hash code value of invoking object. This is used to uniquely identify each object.
6 final void notify(); wakes up single thread that is waiting on this object’s monitor.
7 final void notifyAll(); wakes up all threads that are waiting on this object’s monitor.
8 String toString(); returns string representation of invoking object.
9 void wait(); causes current thread to wait until another thread invokes notify() or notifyAll() method for this object.
10 void wait(long timeout_millis); causes current thread to wait until either another thread invokes the notify() or notifyAll() method for this object, or specified amount of time(sent as parameter) has been elapsed.
11 void wait(long timeout_millis, int timeout_nanos); causes current thread to wait until another thread invokes notify() or notifyAll() method for theobject, or some other thread interrupts the current thread, or a certain amount of real time(sent as parameters) has been elapsed.

final methods in Object class

Below are final methods in Object class
getClass(), wait(), wait(long), wait(long,int), notify(), notifyAll() methods are final, and cannot be overridden.

Below non final methods can be overridden.
clone(), equals(), hashCode(), toString() methods are non final, and can be overridden by any class

Below is an example showing that java.lang.Object is Base class

class Test{

}

public class ObjectSuperClass {
	public static void main(String args[])
	{
	Test obj = new Test();
	Class c = obj.getClass();
	Class sc = c.getSuperclass();

	System.out.println("Super class of Test is: "+sc.getName());
	}
}

Output:
Super class of Test is: java.lang.Object

Also note that instance of java.lang.Object class can be created.

No class can exist in Java, which is not Derived class of Object class. All Java classes, by default inherit from java.lang.Object class.

An object of java.lang.Object class, can refer to any object in Java.
Since Object is base class of all classes, Conversion of any object to String, checking for equality of objects, etc… is being supported by each and every object in Java

You may also like to read:
Can we have static method in abstract class
How many types of inheritance in Java
How to implement Adapter pattern using inheritance

purpose of static members

A member of a class may be delcared as static.

A static member, is associated with the class(in which it is delcared), and not with the indidvidual objects.
Since static members are associated with class, they can be directly accessed with class name.
static members can be accessed, even before creation of object of the class.

A data members declared as static has common storage and value for the class, i..e for all objects of the class.

From a non static method both static and non static data members and member methods can be used or invoked.
Where as from static method only static members can be used or invoked. So, to invoke non static methods, from a static method, we need to create object of class, whose method need to be invoked.

this keyword cannot be used in static methods, as both of them contradict. static is unrelated to object, where as this refers to current object.

static example

//Example of static keyword
class Abcd
{
	static public int i;
	//i value is common to all object of Abcd
	//static members are associated with class, and not with object

	int j;
	//each object of Abcd, can have different value of j


	public int getI()
	{
	return i;
	}

	public int getJ()
	{
	stTest();
	return j;
	}

	//static data members/methods can be used in non static methods
	//but a static method can refer only static methods or data members
	public static void stTest()
	{

	System.out.println("This is static method");
	//j = 10; //error, only static variables can be referenced
	}
}

public class StaticExample {

	float met1()
	{
	return 0.0f;
	}

	public static void main(String args[])
	{
	Abcd.i = 50;

	//Abcd.j = 20;
	//Compile error, j cannot be accessed directly with class name
	//because j is non static

	StaticExample se = new StaticExample();
	se.met1();

	Abcd.stTest();

	Abcd obj = new Abcd();
	//obj.j = 34;
	//obj.i = 20;

	System.out.println("Abcd.i is "+Abcd.i);
	System.out.println("obj.j is "+obj.j);
	}
}

You may also like to read:
this keyword
How to declare static block
Are static constructors possible?
purpose of static method in abstract class

Can we have multiple Servlet Filters?

As already briefed in Servlet , a Servlet is a Server Side Java Program, which runs on Web Server or Application Server, and provides HTTP response to the HTTP request received from a Web Browser, such as Filter does Preprocessing and post processing

A Servlet Filter is used to perform pre processing and post processing a request to a servlet.

How Servlet Filter can be used

Below are few scenarios where Filters can be used
1. To decrypt a request(received , and to encrypt response(before sending to client/browser)
2. For profiling purpose, how much time server takes to process a request, and respond.
3. To log client IP address, in a file or to a database table.
4. To block requests from certain range of IP address.

struts2 is dependent on servlet Filter concept, this shows how powerful Servlet Filter concept is.

Filter interface
Methods in Filter interface, which need to be implemented.

Deployment Descriptor web.xml

Multiple filters can be configured

Advantages of Servlet Filter

Filters are dynamically pluggable.
They can be plugged in, plugged out , without any source code changes.
Filter
Plugging and need not go through development cycle, and hence

How to configure Filter in web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">

    <filter>
    <filter-name>MyFilter

Filter example

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.*;

public class MyFilter implements Filter{

public void init(FilterConfig arg0) throws ServletException
{
    System.out.println("init() in MyFilter");
}

public void doFilter(ServletRequest req, ServletResponse resp,
    FilterChain chain) throws IOException, ServletException {

    PrintWriter out=resp.getWriter();

   //Do not process request from local host
    if(req.getRemoteAddr().equals("127.0.0.1"))
    {
        out.print("Your IP addr is blocked. Retry later");
        return;
    }

    out.print("<br>myfilter is invoked before");
    chain.doFilter(req, resp);//sends request to next resource

    out.print("<br>myfilter is invoked after");

    System.out.println("doFilter() in MyFilter");
    }

public void destroy() {
    System.out.println("destroy() in MyFilter");
    }
}

servlet code

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class NewServlet extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
         response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.print("<br>welcome to servlet<br>");
    }
}

struts2 is dependent on servlet Filter concept, this shows how powerful Servlet Filter concept is.

How to configure multiple Filters to a Servlet?

Yes, it is possible to have multiple Filters, which need to be configured in Deployment Descriptor(web.xml). The order in which these filters get invoked is the order in which they are configured in web.xml.

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">

        <filter>
        <filter-name>MyFilter</filter-name>
        <filter-class>MyFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>MyFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <filter>
        <filter-name>NewFilter</filter-name>
        <filter-class>NewFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>NewFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <servlet>
        <servlet-name>NewServlet</servlet-name>
        <servlet-class>NewServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>NewServlet</servlet-name>
        <url-pattern>/NewServlet</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
</web-app>

Below is an example of Web.xml, which has below two Filters

1. MyFilter.java - Logs Clients IP Address to Server Console, similarly,

Below is source code of NewFilter.java


Below is source code of MyFilter.java

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.*;

public class MyFilter implements Filter{

public void init(FilterConfig arg0) throws ServletException
{
    System.out.println("init() in MyFilter");
}

public void doFilter(ServletRequest req, ServletResponse resp,
    FilterChain chain) throws IOException, ServletException {

    PrintWriter out=resp.getWriter();


    if(req.getRemoteAddr().equals("127.0.0.1"))
    {
        out.print("Your IP addr is blocked. Retry later");
        return;
    }

    out.print("
myfilter is invoked before"); chain.doFilter(req, resp);//sends request to next resource out.print("
myfilter is invoked after"); System.out.println("doFilter() in MyFilter"); } public void destroy() { System.out.println("destroy() in MyFilter"); } }

2. NewFilter.java - Just prints log on Web Server Console

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.*;

public class NewFilter implements Filter{

public void init(FilterConfig arg0) throws ServletException
{
    System.out.println("init() in NewFilter");
}

public void doFilter(ServletRequest req, ServletResponse resp,
    FilterChain chain) throws IOException, ServletException {

    PrintWriter out=resp.getWriter();
    out.print("
filter is invoked before"); chain.doFilter(req, resp);//sends request to next resource out.print("
filter is invoked after"); System.out.println("doFilter() in NewFilter"); } public void destroy() { System.out.println("destroy() in NewFilter"); } }

No Source code changes are required in the servlet.

How to map Filter to a specific URLs or Servlet(s)?

It is possible to map Filters to a specific URLS or Servlet(s). This is possible by adjusting means it Filter gets invoked for all Servlets. By chaging it to below

Filter gets invoked only when urls starting with abc are requested, from Web Browser

    <filter-mapping>
        <filter-name>MyFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

You may also like to read:
What is Servlet Life Cycle?
What are implicit objects in JSP

Why rethrow an Exception in Java?

What is rethrowing an Exception

When an Exception is thrown from your code,
1. You can handle handle the Exception completely, by using try and catch blocks you handle the Exception, and further throw the Exception object. OR
2. Use throws with method declaration, to indicate that invokers of the method need to handle the Exception, or further throws it.

Another option we have here is a combination of above both. That is, the Exception is handled, with try, catch blocks, and further throw the Exception.

Below is an example, of the same.

class TDemo22{
	public void met2() throws Exception
	{
	try
	{
	String str="2abcd3";

	int i = Integer.parseInt(str);
	}
	catch(Exception ep)
	{
	System.out.println("Exception catching");
	throw ep;
	}
	}
}

public class NumberFormatDemo {
	public static void main(String args[])
	{
	try{
	TDemo22 td2 = new TDemo22();
	td2.met2();

	}catch(Exception e)
	{
	e.printStackTrace();
	}
	}
}

There are two different ways, an Exception can be re thrown.
1. catch an Exception, and further throw same Exception object(as shown in above example)
2. catch an Exception, and further create a new Exception object, and throw it(as shown in below example)

class MyException extends Exception{
}

class TDemo22{
	public void met2() throws Exception
	{
	try
	{
	String str="2abcd3";

	int i = Integer.parseInt(str);
	}
	catch(Exception ep)
	{
	System.out.println("Exception catching");
	throw new MyException(); //re throwing a new Exception object
	}
	}
}

public class NumberFormatDemo {
	public static void main(String args[])
	{
	try{
	TDemo22 td2 = new TDemo22();
	td2.met2();

	}catch(Exception e)
	{
	e.printStackTrace();
	}
	}
}

When rethrowing an Exception may be required?
1. When you want to partially handle Exception situation, and further let invokers of your method, to handle the Exception.
2. When you want to hide class name of your internal exception, and rethrow another Exception.

You may also like to read:
How to print stack trace to a log file
List of inbuilt exception in Java
What is RuntimeException
How to create your own Exception?

Difference between System.exit and assert, in Java

System.exit(int) is a method in java.lang package, where as assert is a keyword.

assert is used for debugging purpose, and assert to work, explicit enabling is required by providing -ea JVM argument. When assert expression gets evaluated to false, AssertionError exception is thrown.

For System.exit() to execute, no such explicit enabling is required. When System.exit() is executed, program terminates by providing exit code to Operating System.

Below is declaration of System.exit() method

public static void exit(int status_code);

System.exit() is generally used with below arguments
System.exit(0) – indicates that java program terminated normally
System.exit(1) – indicates that java program terminated abnormally
System.exit(-1)- indicates that java program terminated abnormally

Below is an example for System.exit()

public class SystemExitDemo {
public static void main(String args[])
{
try{
	String str="2sdjhfgsdjhfgsdjh3";

	int i = Integer.parseInt(str);

	}catch(Exception e)
	{
	e.printStackTrace();
	System.exit(1);//abnormal termination
	}
	System.exit(0);//normal termination
	}
}

You may also like to read:
What are data Wrapper classes in Java?
What is non static block, when to use it?
How to use assert
Purpose of System.getProperty() method