Tuesday, September 30, 2008

SPRINGLAYOUT

New SpringLayout()
import java.awt.Container;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Spring;
import javax.swing.SpringLayout;
public class MainClass
{
public static void main(String[] args)
{
JFrame aWindow = new JFrame();
aWindow.setBounds(200, 200, 200, 200);
aWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container content = aWindow.getContentPane();
content.add(new SpringLayoutPanel());
aWindow.setVisible(true);
}
}class SpringLayoutPanel extends JPanel
{
public SpringLayoutPanel()
{
SpringLayout layout = new SpringLayout();
setLayout(layout);
JButton[] buttons = new JButton[6];
for (int i = 0; i < buttons.length; i++)
{
buttons[i] = new JButton("Press " + (i + 1));
add(buttons[i]);
}
Spring xSpring = Spring.constant(5, 15, 25);
Spring ySpring = Spring.constant(10, 30, 50);
Spring wSpring = Spring.constant(30, 80, 130);
SpringLayout.Constraints buttonConstr = layout.getConstraints(buttons[0]);
buttonConstr.setX(xSpring);
buttonConstr.setY(ySpring);
for (int i = 0; i < buttons.length; i++)
{
buttonConstr = layout.getConstraints(buttons[i]);
buttonConstr.setHeight(ySpring);
buttonConstr.setWidth(wSpring);
if (i > 0)
{
layout.putConstraint(SpringLayout.WEST, buttons[i], xSpring,
SpringLayout.EAST, buttons[i - 1]);
layout.putConstraint(SpringLayout.NORTH, buttons[i], ySpring,
SpringLayout.SOUTH, buttons[i - 1]);
}
}
SpringLayout.Constraints constr = layout.getConstraints(this);
constr.setConstraint(SpringLayout.EAST, Spring.sum(buttonConstr.getConstraint(SpringLayout.EAST), Spring.constant(15)));
constr.setConstraint(SpringLayout.SOUTH, Spring.sum(buttonConstr.getConstraint(SpringLayout.SOUTH), Spring.constant(10)));
}
}
Spring: constant(int min, int pref, int max)
import java.awt.Container;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Spring;
import javax.swing.SpringLayout;
public class MainClass
{
public static void main(String[] args)
{
JFrame aWindow = new JFrame();
aWindow.setBounds(200, 200, 200, 200);
aWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container content = aWindow.getContentPane();
content.add(new SpringLayoutPanel()); aWindow.setVisible(true);
}
}
class SpringLayoutPanel extends JPanel
{
public SpringLayoutPanel()
{
SpringLayout layout = new SpringLayout();
setLayout(layout);
JButton[] buttons = new JButton[6];
for (int i = 0; i < buttons.length; i++)
{
buttons[i] = new JButton("Press " + (i + 1));
add(buttons[i]);
}
Spring xSpring = Spring.constant(5, 15, 25);
Spring ySpring = Spring.constant(10, 30, 50);
Spring wSpring = Spring.constant(30, 80, 130);
SpringLayout.Constraints buttonConstr = layout.getConstraints(buttons[0]);
buttonConstr.setX(xSpring);
buttonConstr.setY(ySpring);
for (int i = 0; i < buttons.length; i++)
{
buttonConstr = layout.getConstraints(buttons[i]);
buttonConstr.setHeight(ySpring);
buttonConstr.setWidth(wSpring);
if (i > 0)
{
layout.putConstraint(SpringLayout.WEST, buttons[i], xSpring,SpringLayout.EAST, buttons[i - 1]);
layout.putConstraint(SpringLayout.NORTH, buttons[i], ySpring, SpringLayout.SOUTH, buttons[i - 1]);
}
}
SpringLayout.Constraints constr = layout.getConstraints(this);
constr.setConstraint(SpringLayout.EAST, Spring.sum(buttonConstr.getConstraint(SpringLayout.EAST), Spring.constant(15)));
constr.setConstraint(SpringLayout.SOUTH, Spring.sum(buttonConstr.getConstraint(SpringLayout.SOUTH), Spring.constant(10)));
}
}

GRIDLAYOUT

New GridLayout(int rows, int cols)
/* *
Output:
* */
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class MainClass extends JPanel
{
public MainClass()
{
super(new GridLayout(2,2));
add(new JButton("w w w1"));
add(new JButton("w w w2" ));
add(new JButton("w w w3" ));
add(new JButton("www4" ));
}
public static void main(String[] args)
{
JFrame frame = new JFrame();
frame.getContentPane().add(new MainClass());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(200,200);
frame.setVisible(true);
}
}

FLOWLAYOUT

FlowLayout.LEFT
import java.awt.Container;
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
public class MainClass
{
public static void main(String[] args)
{
JFrame aWindow = new JFrame();
aWindow.setBounds(200, 200, 200, 200);
aWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container content = aWindow.getContentPane();
content.setLayout(new FlowLayout(FlowLayout.LEFT));
content.add(new JButton("www.java.com"));
content.add(new JLabel("www.java.com"));
content.add(new JTextField("www.java.com"));
aWindow.setVisible(true);
}
}

FlowLayout.RIGHT
/* *
Output:
* */
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class MainClass extends JPanel
{
public MainClass()
{
super(new FlowLayout(FlowLayout.RIGHT, 10, 3));
add(new JButton("w w w.j a v a . c o m"));
add(new JButton("w w w.j a v a . c o m"));
add(new JButton("w w w.j a v a.c o m"));
add(new JButton("www.j a v a.c o m));
}
public static void main(String[] args)
{
JFrame frame = new JFrame();
frame.getContentPane().add(new MainClass());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(200, 200);
frame.setVisible(true);
}
}

CARDLAYOUT

New CardLayout(int hgap, int vgap)
import java.awt.CardLayout;
import java.awt.Container;
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.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class MainClass
{
public static void main(String[] args)
{
JFrame aWindow = new JFrame();
aWindow.setBounds(200, 200, 200, 200);
aWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container content = aWindow.getContentPane();
content.add(new CardLayoutPanel());
aWindow.setVisible(true);
}
}
class CardLayoutPanel extends JPanel implements ActionListener
{
CardLayout card = new CardLayout(50, 50);
public CardLayoutPanel()
{
setLayout(card);
JButton button;
for (int i = 1; i <= 6; i++)
{
add(button = new JButton("Press " + i), "Card" + i);
button.addActionListener(this);
}
} // Handle button events
public void actionPerformed(ActionEvent e)
{
card.next(this);
}
}
CardLayout: next(Container parent)
import java.awt.CardLayout;
import java.awt.Container;
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.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class MainClass
{
public static void main(String[] args)
{
JFrame aWindow = new JFrame();
aWindow.setBounds(200, 200, 200, 200);
aWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container content = aWindow.getContentPane();
content.add(new CardLayoutPanel());
aWindow.setVisible(true);
}
}
class CardLayoutPanel extends JPanel implements ActionListener
{
CardLayout card = new CardLayout(50, 50);
public CardLayoutPanel()
{
setLayout(card);
JButton button;
for (int i = 1; i <= 6; i++)
{
add(button = new JButton("Press " + i), "Card" + i);
button.addActionListener(this);
}
} // Handle button events
public void actionPerformed(ActionEvent e)
{
card.next(this);
}
}

BORDERLAYOUT

BorderLayout.CENTER
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JToggleButton;
public class MainClass
{
public static void main(String args[])
{
JFrame f = new JFrame("JToggleButton Sample");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new JToggleButton("North"), BorderLayout.NORTH);
f.add(new JToggleButton("East"), BorderLayout.EAST);
f.add(new JToggleButton("West"), BorderLayout.WEST);
f.add(new JToggleButton("Center"), BorderLayout.CENTER);
f.add(new JToggleButton("South"), BorderLayout.SOUTH);
f.setSize(300, 200);
f.setVisible(true);
}
}
New BorderLayout()
import java.awt.BorderLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class MainClass extends JPanel
{
public MainClass()
{
JButton btn1 = new JButton("Button1");
JButton btn2 = new JButton("Button2");
JButton btn3 = new JButton("Button3");
JButton btn4 = new JButton("Button4");
JButton btn5 = new JButton("Button5");
JButton btn6 = new JButton("Button6");
setLayout(new BorderLayout()); add("North", btn1);
add("West", btn2);
add("Center", btn3);
add("Center", btn4);
add("South", btn5);
add("East", btn6);
}
public static void main(String[] args)
{
JFrame frame = new JFrame();
frame.getContentPane().add(new MainClass());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(200, 200);
frame.setVisible(true);
}
}

AWT MOUSE EVENT

AWTEvent.MOUSE_EVENT_MASK
// This example is from the book _Java AWT Reference_ by John Zukowski.
// Written by John Zukowski. Copyright (c) 1997 O'Reilly & Associates.
// You may study, use, modify, and distribute this example for any purpose.
// This example is provided WITHOUT WARRANTY either expressed or
import java.awt.AWTEvent;
import java.awt.AWTEventMulticaster;
import java.awt.Component;
import java.awt.Frame;
import java.awt.ItemSelectable;
import java.awt.SystemColor;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.MouseEvent;
class ItemEventComponent extends Component implements ItemSelectable
{
boolean selected;
int i = 0;
ItemListener itemListener = null;
ItemEventComponent()
{
enableEvents(AWTEvent.MOUSE_EVENT_MASK);
}
public Object[] getSelectedObjects()
{
Object o[] = new Object[1];
o[0] = new Integer(i);
return o;
}
public void addItemListener(ItemListener l)
{
itemListener = AWTEventMulticaster.add(itemListener, l);
}
public void removeItemListener(ItemListener l)
{
itemListener = AWTEventMulticaster.remove(itemListener, l);
}
public void processEvent(AWTEvent e)
{
if (e.getID() == MouseEvent.MOUSE_PRESSED)
{
if (itemListener != null)
{
selected = !selected;
i++;
itemListener.itemStateChanged(new ItemEvent(this, ItemEvent.ITEM_STATE_CHANGED,
getSelectedObjects(),
(selected ? ItemEvent.SELECTED : ItemEvent.DESELECTED)));
}
}
}
}
public class MainClass extends Frame implements ItemListener
{
MainClass() {
super("Listening In");
ItemEventComponent c = new ItemEventComponent();
add(c, "Center");
c.addItemListener(this);
c.setBackground(SystemColor.control);
setSize(200, 200);
}
public void itemStateChanged(ItemEvent e)
{
Object[] o = e.getItemSelectable().getSelectedObjects();
Integer i = (Integer) o[0];
System.out.println(i);
}
public static void main(String args[])
{
MainClass f = new MainClass();
f.show();
}

APPLETSTUB

implements AppletStub
import java.applet.Applet;
import java.applet.AppletContext;
import java.applet.AppletStub;
import java.applet.AudioClip;
import java.awt.Button;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Panel;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Iterator;
public class MainClass extends Applet implements ActionListener
{
static MainClass myApplet;
static MyStub myStub;
Image im;
public void init()
{
System.out.println("Code base = " + getCodeBase());
System.out.println("Document base = " + getDocumentBase());
System.out.println("\ninit () called");
System.out.println("isActive () returns " + isActive());
Button b = new Button("Visit www.java2s.com");
b.addActionListener(this);
add(b);
b = new Button("Audio");
b.addActionListener(this);
add(b);
String imageName = getParameter("image");
if (imageName != null)
im = getImage(getCodeBase(), imageName);
}
public void start()
{
System.out.println("start () called");
System.out.println("isActive () returns " + isActive());
}
public void paint(Graphics g)
{
if (im != null)
g.drawImage(im, 0, 0, this);
}
public void actionPerformed(ActionEvent e)
{
if (e.getActionCommand().equals("Audio"))
{
String soundName = getParameter("audio");
if (soundName != null)
{
AudioClip ac = getAudioClip(getDocumentBase(), soundName);
ac.play();
}
return;
}
try
{
URL u = new URL("http://www.java2s.com");
getAppletContext().showDocument(u);
}
catch (MalformedURLException exc)
{
System.out.println(e);
}
}
public void stop()
{
System.out.println("stop () called");
System.out.println("isActive () returns " + isActive());
}
public void destroy()
{
System.out.println("destroy () called");
System.out.println("isActive () returns " + isActive());
}
public static void main(String[] args)
{
Frame frame = new Frame("AppletAndApp as an Application");
myApplet = new MainClass();
frame.add(new Panel().add(myApplet));
frame.addNotify();
myApplet.setStub(myStub = new MyStub(args));
myApplet.init();
frame.setSize(300, 200);
frame.setVisible(true);
myStub.setActive(true);
myApplet.start();
frame.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent w)
{
myStub.setActive(false);
myApplet.stop();
myApplet.destroy();
System.exit(0);
}
}
}
}class MyStub implements AppletStub
{
private boolean active = false;
private Hashtable ht = new Hashtable();
private MyContext context;
MyStub(String[] args)
{
context = new MyContext();
if ((args.length & 1) != 0)
return;
for (int i = 0; i < args.length; i += 2)
ht.put(args[i], args[i + 1]);
}
public boolean isActive()
{
return active;
}
public URL getDocumentBase()
{
URL u = null;
try
{
u = new URL("file:/C:./x.html");
}
catch (MalformedURLException e)
{
}
return u;
}
public URL getCodeBase()
{
URL u = null;
try
{
u = new URL("file:/C:./");
}
catch (MalformedURLException e)
{
}
return u;
}
public String getParameter(String name)
{
return (String) ht.get(name);
}
public AppletContext getAppletContext()
{
return context;
}
public void appletResize(int width, int height)
{
}
public void setActive(boolean active)
{
this.active = active;
}
}
class MyContext implements AppletContext
{
public AudioClip getAudioClip(URL url)
{
return Applet.newAudioClip(url);
}
public Image getImage(URL url)
{
Toolkit tk = Toolkit.getDefaultToolkit();
return tk.getImage(url);
}
public Applet getApplet(String name)
{
return null;
}
public Enumeration getApplets()
{
return null;
}
public void showDocument(URL url)
{
System.out.println("Showing document " + url);
}
public void showDocument(URL url, String frame)
{
try
{
showDocument(new URL(url.toString() + frame));
}
catch (MalformedURLException e)
{
}
}
public void showStatus(String message)
{
System.out.println(message);
}
public void setStream(String key, InputStream stream) throws IOException
{
}
public InputStream getStream(String key)
{
return null;
}
public Iterator getStreamKeys() { return null;
}
}

CONTEXT SHOW DOCUMENT

AppletContext: showDocument(URL url,String target)
import java.applet.AppletContext;i
mport java.awt.Graphics;
import java.net.URL;
import javax.swing.JApplet;
public class MainClass extends JApplet
{
public void paint(Graphics g)
{
AppletContext ac = getAppletContext();
try
{
URL url = new URL("http://www.java2s.com");
ac.showDocument(url, "frame2");
}
catch (Exception e)
{
showStatus("Exception: " + e);
}
g.drawString("ShowDocument Applet", 10, 25);
}
}

APPLETCONTEXT

implements AppletContext
import java.applet.Applet;
import java.applet.AppletContext;
import java.applet.AppletStub;
import java.applet.AudioClip;
import java.awt.Button;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Panel;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Iterator;
public class MainClass extends Applet implements ActionListener
{
static MainClass myApplet;
static MyStub myStub;
Image im;
public void init()
{
System.out.println("Code base = " + getCodeBase());
System.out.println("Document base = " + getDocumentBase());
System.out.println("\ninit () called");
System.out.println("isActive () returns " + isActive());
Button b = new Button("Visit www.java2s.com");
b.addActionListener(this);
add(b);
b = new Button("Audio");
b.addActionListener(this);
add(b);
String imageName = getParameter("image");
if (imageName != null)
im = getImage(getCodeBase(), imageName);
}
public void start()
{
System.out.println("start () called");
System.out.println("isActive () returns " + isActive());
}
public void paint(Graphics g)
{
if (im != null)
g.drawImage(im, 0, 0, this);
}
public void actionPerformed(ActionEvent e)
{
if (e.getActionCommand().equals("Audio"))
{
String soundName = getParameter("audio");
if (soundName != null)
{
AudioClip ac = getAudioClip(getDocumentBase(), soundName);
ac.play();
}
return;
}
try
{
URL u = new URL("http://www.java2s.com");
getAppletContext().showDocument(u);
}
catch (MalformedURLException exc)
{
System.out.println(e);
}
}
public void stop()
{
System.out.println("stop () called");
System.out.println("isActive () returns " + isActive());
}
public void destroy()
{
System.out.println("destroy () called");
System.out.println("isActive () returns " + isActive());
}
public static void main(String[] args)
{
Frame frame = new Frame("AppletAndApp as an Application");
myApplet = new MainClass();
frame.add(new Panel().add(myApplet));
frame.addNotify();
myApplet.setStub(myStub = new MyStub(args));
myApplet.init();
frame.setSize(300, 200);
frame.setVisible(true);
myStub.setActive(true);
myApplet.start();
frame.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent w)
{
myStub.setActive(false);
myApplet.stop();
myApplet.destroy();
System.exit(0);
}
}
}
}class MyStub implements AppletStub { private boolean active = false; private Hashtable ht = new Hashtable(); private MyContext context; MyStub(String[] args) { context = new MyContext(); if ((args.length & 1) != 0) return; for (int i = 0; i < u =" null;" u =" new" u =" null;" u =" new" active =" active;" tk =" Toolkit.getDefaultToolkit();"> getStreamKeys() { return null; }}

GET IMAGE

Applet: getImage(URL url, String name)
import java.applet.Applet;
import java.awt.Graphics;
import java.awt.Image;
public class ImageApplet extends Applet
{
Image im;
public void init()
{
im = getImage(getDocumentBase(), "image.jpg");
}
public void paint(Graphics g)
{
g.drawImage(im, 0, 0, this);
}
}

APPLET GET DOCUMENT BASE

Applet: getDocumentBase()
import java.applet.Applet;
import java.awt.Graphics;
import java.awt.Image;
public class ImageApplet extends Applet
{
Image im;
public void init()
{
im = getImage(getDocumentBase(), "image.jpg");
}
public void paint(Graphics g)
{
g.drawImage(im, 0, 0, this);
}
}

ACTIONLISTENER IN APPLETS

implements ActionListener
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class MainClass extends JPanel implements ActionListener
{
JTextField jtf = new JTextField(15);
public MainClass()
{
add(jtf);
jtf.addActionListener(this);
} // Show text when user presses ENTER.
public void actionPerformed(ActionEvent ae)
{
System.out.println(jtf.getText());
}
public static void main(String[] args)
{
JFrame frame = new JFrame();
frame.getContentPane().add(new MainClass());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(200, 200);
frame.setVisible(true);
}
}

DEADLOCKS AND SYNCHRONIZATION

What is a deadlock?
We say that a set of processes or threads is deadlocked when each thread is waiting for an event that only another process in the set can cause. Another way to illustrate a deadlock is to build a directed graph whose vertices are threads or processes and whose edges represent the "is-waiting-for" relation. If this graph contains a cycle, the system is deadlocked. Unless the system is designed to recover from deadlocks, a deadlock causes the program or system to hang.
Synchronization deadlocks in Java programs
Deadlocks can occur in Java because the synchronized keyword causes the executing thread to block while waiting for the lock, or monitor, associated with the specified object. Since the thread might already hold locks associated with other objects, two threads could each be waiting for the other to release a lock; in such a case, they will end up waiting forever. The following example shows a set of methods that have the potential for deadlock. Both methods acquire locks on two lock objects, cacheLock and tableLock, before they proceed. In this example, the objects acting as locks are global (static) variables, a common technique for simplifying application-locking behavior by performing locking at a coarser level of granularity:
Listing 1. A potential synchronization deadlock
public static Object cacheLock = new Object();
public static Object tableLock = new Object();
...
public void oneMethod() {
synchronized (cacheLock) {
synchronized (tableLock) {
doSomething();
}
}
}
public void anotherMethod() {
synchronized (tableLock) {
synchronized (cacheLock) {
doSomethingElse();
}
}
}
Now, imagine that thread A calls oneMethod() while thread B simultaneously calls anotherMethod(). Imagine further that thread A acquires the lock on cacheLock, and, at the same time, thread B acquires the lock on tableLock. Now the threads are deadlocked: neither thread will give up its lock until it acquires the other lock, but neither will be able to acquire the other lock until the other thread gives it up. When a Java program deadlocks, the deadlocking threads simply wait forever. While other threads might continue running, you will eventually have to kill the program, restart it, and hope that it doesn't deadlock again.
class A
{
synchronized void foo(B b)
{
String name = Thread.currentThread().getName();
System.out.println(name + " entered A.foo");
try
{
Thread.sleep(1000);
}
catch (Exception e)
{
System.out.println("A Interrupted");
}
System.out.println(name + " trying to call B.last()");
b.last();
}
synchronized void last()
{
System.out.println("Inside A.last");
}
}
class B
{
synchronized void bar(A a)
{
String name = Thread.currentThread().getName();
System.out.println(name + " entered B.bar");
try
{
Thread.sleep(1000);
}
catch (Exception e)
{
System.out.println("B Interrupted");
}
System.out.println(name + " trying to call A.last()");
a.last();
}
synchronized void last()
{
System.out.println("Inside A.last");
}
}
class Deadlock implements Runnable
{
A a = new A();
B b = new B();
Deadlock()
{
Thread.currentThread().setName("MainThread");
Thread t = new Thread(this, "RacingThread");
t.start();
a.foo(b); // get lock on a in this thread.
System.out.println("Back in main thread");
}
public void run()
{
b.bar(a); // get lock on b in other thread.
System.out.println("Back in other thread");
}
public static void main(String args[])
{
new Deadlock();
}
}

GARBAGE COLLECTION

The process of disposing of dead objects is called garbage collection.
Encouraging the Java Virtual Machine (JVM) to do some garbage collecting and recover the memory.
class Sphere
{
double radius; // Radius of a sphere
Sphere()
{
} // Class constructor
Sphere(double theRadius)
{
radius = theRadius; // Set the radius
}
}
public class MainClass
{
public static void main(String[] arg)
{
Sphere sp = new Sphere();
System.gc();
}
}

INSTANCE AND CLASS VARIABLES

Understanding Instance and Class Members
In this section, we discuss the use of the static keyword to create fields and methods that belong to the class, rather than to an instance of the class.
Class VariablesWhen a number of objects are created from the same class blueprint, they each have their own distinct copies of instance variables. In the case of the Bicycle class, the instance variables are cadence, gear, and speed. Each Bicycle object has its own values for these variables, stored in different memory locations.
Sometimes, you want to have variables that are common to all objects. This is accomplished with the static modifier. Fields that have the static modifier in their declaration are called static fields or class variables. They are associated with the class, rather than with any object. Every instance of the class shares a class variable, which is in one fixed location in memory. Any object can change the value of a class variable, but class variables can also be manipulated without creating an instance of the class.
Public non-final statics are not recommended for applets because you can't make any assumptions on how the browser will implement the Java Virtual Machine (JVM). If your applet defines a public non-final static as a way of implementing a global variable, that variable may be clobbered when subsequent applets are launched. If your applet defines a public non-final static as a way of communicating between applets, you may find that the applets do not share the same JVM and are unable to communicate. For example, suppose you want to create a number of Bicycle objects and assign each a serial number, beginning with 1 for the first object. This ID number is unique to each object and is therefore an instance variable. At the same time, you need a field to keep track of how many Bicycle objects have been created so that you know what ID to assign to the next one. Such a field is not related to any individual object, but to the class as a whole. For this you need a class variable, numberOfBicycles, as follows:
public class Bicycle
{
private int cadence;
private int gear;
private int speed;
// add an instance variable for the object ID
private int id;
// add a class variable for the number of Bicycle objects instantiated
private static int numberOfBicycles = 0;
......
}
Class variables are referenced by the class name itself, as in
Bicycle.numberOfBicycles
This makes it clear that they are class variables.
You can use the Bicycle constructor to set the id instance variable and increment the numberOfBicycles class variable:
public class Bicycle
{
private int cadence;
private int gear;
private int speed;
private int id;
private static int numberOfBicycles = 0;
public Bicycle(int startCadence, int startSpeed, int startGear){
gear = startGear;
cadence = startCadence;
speed = startSpeed;
// increment number of Bicycles and assign ID number
id = ++numberOfBicycles;
}
// new method to return the ID instance variable
public int getID() {
return id;
}
.....
}

Class MethodsThe Java programming language supports static methods as well as static variables. Static methods, which have the static modifier in their declarations, should be invoked with the class name, without the need for creating an instance of the class, as in
ClassName.methodName(args)
A common use for static methods is to access static fields. For example, we could add a static method to the Bicycle class to access the numberOfBicycles static field:
public static int getNumberOfBicycles() {
return numberOfBicycles;
}
Not all combinations of instance and class variables and methods are allowed:
Instance methods can access instance variables and instance methods directly.
Instance methods can access class variables and class methods directly.
Class methods can access class variables and class methods directly.
Class methods cannot access instance variables or instance methods directly—they must use an object reference. Also, class methods cannot use the this keyword as there is no instance for this to refer to.
ConstantsThe static modifier, in combination with the final modifier, is also used to define constants. The final modifier indicates that the value of this field cannot change.
For example, the following variable declaration defines a constant named PI, whose value is an approximation of pi (the ratio of the circumference of a circle to its diameter):
static final double PI = 3.141592653589793;
Constants defined in this way cannot be reassigned, and it is a compile-time error if your program tries to do so. By convention, the names of constant values are spelled in uppercase letters. If the name is composed of more than one word, the words are separated by an underscore (_).
If a primitive type or a string is defined as a constant and the value is known at compile time, the compiler replaces the constant name everywhere in the code with its value. This is called a compile-time constant. If the value of the constant in the outside world changes (for example, if it is legislated that pi actually should be 3.975), you will need to recompile any classes that use this constant to get the current value.
The Bicycle ClassAfter all the modifications made in this section, the Bicycle class is now:
public class Bicycle
{
private int cadence;
private int gear;
private int speed;
private int id;
private static int numberOfBicycles = 0;
public Bicycle(int startCadence, int startSpeed, int startGear)
{
gear = startGear;
cadence = startCadence;
speed = startSpeed;
id = ++numberOfBicycles;
}
public int getID()
{
return id;
}
public static int getNumberOfBicycles()
{
return numberOfBicycles;
}
public int getCadence()
{
return cadence;
}
public void setCadence(int newValue)
{
cadence = newValue;
}
public int getGear()
{
return gear;
}
public void setGear(int newValue)
{
gear = newValue;
}
public int getSpeed()
{
return speed;
}
public void applyBrake(int decrement)
{
speed -= decrement;
}
public void speedUp(int increment)
{
speed += increment;
}
}

INITIALIZING FIELDS

Initializing Fields
As you have seen, you can often provide an initial value for a field in its declaration:
public class BedAndBreakfast {
public static int capacity = 10; //initialize to 10
private boolean full = false; //initialize to false
}
This works well when the initialization value is available and the initialization can be put on one line. However, this form of initialization has limitations because of its simplicity. If initialization requires some logic (for example, error handling or a for loop to fill a complex array), simple assignment is inadequate. Instance variables can be initialized in constructors, where error handling or other logic can be used. To provide the same capability for class variables, the Java programming language includes static initialization blocks.
It is not necessary to declare fields at the beginning of the class definition, although this is the most common practice. It is only necessary that they be declared and initialized before they are used.
Static Initialization BlocksA static initialization block is a normal block of code enclosed in braces, { }, and preceded by the static keyword. Here is an example:
static {
// whatever code is needed for initialization goes here
}
A class can have any number of static initialization blocks, and they can appear anywhere in the class body. The runtime system guarantees that static initialization blocks are called in the order that they appear in the source code.
There is an alternative to static blocks —you can write a private static method:
class Whatever {
public static varType myVar = initializeClassVariable();

private static varType initializeClassVariable() {
//initialization code goes here
}
}
The advantage of private static methods is that they can be reused later if you need to reinitialize the class variable.
Initializing Instance MembersNormally, you would put code to initialize an instance variable in a constructor. There are two alternatives to using a constructor to initialize instance variables: initializer blocks and final methods.
Initializer blocks for instance variables look just like static initializer blocks, but without the static keyword:
{
// whatever code is needed for initialization goes here
}
The Java compiler copies initializer blocks into every constructor. Therefore, this approach can be used to share a block of code between multiple constructors.
A final method cannot be overridden in a subclass. This is discussed in the lesson on interfaces and inheritance. Here is an example of using a final method for initializing an instance variable:
class Whatever {
private varType myVar = initializeInstanceVariable();

protected final varType initializeInstanceVariable() {
//initialization code goes here
}
}
This is especially useful if subclasses might want to reuse the initialization method. The method is final because calling non-final methods during instance initialization can cause problems. Joshua Bloch describes this in more detail in Effective Java.

USING THIS KEYWORD

Using the this Keyword
Within an instance method or a constructor, this is a reference to the current object — the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this.
Using this with a Field
The most common reason for using the this keyword is because a field is shadowed by a method or constructor parameter.
For example, the Point class was written like this

public class Point {
public int x = 0;
public int y = 0;

//constructor
public Point(int a, int b) {
x = a;
y = b;
}
}

but it could have been written like this:
public class Point {
public int x = 0;
public int y = 0;

//constructor
public Point(int x, int y) {
this.x = x;
this.y = y;
}
}

Each argument to the second constructor shadows one of the object's fields—inside the constructor x is a local copy of the constructor's first argument. To refer to the Point field x, the constructor must use this.x.
Using this with a Constructor
From within a constructor, you can also use the this keyword to call another constructor in the same class. Doing so is called an explicit constructor invocation. Here's another Rectangle class, with a different implementation from the one in the Objects section.
public class Rectangle {
private int x, y;
private int width, height;

public Rectangle() {
this(0, 0, 0, 0);
}
public Rectangle(int width, int height) {
this(0, 0, width, height);
}
public Rectangle(int x, int y, int width, int height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
...
}

This class contains a set of constructors. Each constructor initializes some or all of the rectangle's member variables. The constructors provide a default value for any member variable whose initial value is not provided by an argument. For example, the no-argument constructor calls the four-argument constructor with four 0 values and the two-argument constructor calls the four-argument constructor with two 0 values. As before, the compiler determines which constructor to call, based on the number and the type of arguments.
If present, the invocation of another constructor must be the first line in the constructor

RETURNING A VALUE FROM A METHOD

Returning a Value from a Method
A method returns to the code that invoked it when it
completes all the statements in the method,
reaches a return statement, or
throws an exception (covered later), whichever occurs first.
You declare a method's return type in its method declaration. Within the body of the method, you use the return statement to return the value.
Any method declared void doesn't return a value. It does not need to contain a return statement, but it may do so. In such a case, a return statement can be used to branch out of a control flow block and exit the method and is simply used like this:
return;
If you try to return a value from a method that is declared void, you will get a compiler error.
Any method that is not declared void must contain a return statement with a corresponding return value, like this:
return returnValue;
The data type of the return value must match the method's declared return type; you can't return an integer value from a method declared to return a boolean.
The getArea() method in the Rectangle class that was discussed in the sections on objects returns an integer:
// a method for computing the area of the rectangle
public int getArea() {
return width * height;
}
This method returns the integer that the expression width*height evaluates to.
The area method returns a primitive type. A method can also return a reference type. For example, in a program to manipulate Bicycle objects, we might have a method like this:
public Bicycle seeWhosFastest(Bicycle myBike, Bicycle yourBike, Environment env) {
Bicycle fastest;
// code to calculate which bike is faster, given
// each bike's gear and cadence and given
// the environment (terrain and wind)
return fastest;
}
Returning a Class or InterfaceIf this section confuses you, skip it and return to it after you have finished the lesson on interfaces and inheritance.
When a method uses a class name as its return type, such as whosFastest does, the class of the type of the returned object must be either a subclass of, or the exact class of, the return type. Suppose that you have a class hierarchy in which ImaginaryNumber is a subclass of java.lang.Number, which is in turn a subclass of Object, as illustrated in the following figure.
The class hierarchy for ImaginaryNumberNow suppose that you have a method declared to return a Number:
public Number returnANumber() {
...
}
The returnANumber method can return an ImaginaryNumber but not an Object. ImaginaryNumber is a Number because it's a subclass of Number. However, an Object is not necessarily a Number — it could be a String or another type.
You can override a method and define it to return a subclass of the original method, like this:
public ImaginaryNumber returnANumber() {
...
}
This technique, called covariant return type, means that the return type is allowed to vary in the same direction as the subclass.

CLASSES AND DECLERATION

Classes
The introduction to object-oriented concepts in the lesson titled ObjectOrientedProgrammingConcepts used a bicycle class as an example, with racing bikes, mountain bikes, and tandem bikes as subclasses. Here is sample code for a possible implementation of a Bicycle class, to give you an overview of a class declaration. Subsequent sections of this lesson will back up and explain class declarations step by step. For the moment, don't concern yourself with the details.
public class Bicycle {

// the Bicycle class has three fields
public int cadence;
public int gear;
public int speed;

// the Bicycle class has one constructor
public Bicycle(int startCadence, int startSpeed, int startGear) {
gear = startGear;
cadence = startCadence;
speed = startSpeed;
}

// the Bicycle class has four methods
public void setCadence(int newValue) {
cadence = newValue;
}

public void setGear(int newValue) {
gear = newValue;
}

public void applyBrake(int decrement) {
speed -= decrement;
}

public void speedUp(int increment) {
speed += increment;
}

}
A class declaration for a MountainBike class that is a subclass of Bicycle might look like this:
public class MountainBike extends Bicycle {

// the MountainBike subclass has one field
public int seatHeight;
// the MountainBike subclass has one constructor
public MountainBike(int startHeight, int startCadence, int startSpeed, int startGear) {
super(startCadence, startSpeed, startGear);
seatHeight = startHeight;
}

// the MountainBike subclass has one method
public void setHeight(int newValue) {
seatHeight = newValue;
}
}
MountainBike inherits all the fields and methods of Bicycle and adds the field seatHeight and a method to set it (mountain bikes have seats that can be moved up and down as the terrain demands). Declaring Classes
You've seen classes defined in the following way:
class MyClass {
//field, constructor, and method declarations
}
This is a class declaration. The class body (the area between the braces) contains all the code that provides for the life cycle of the objects created from the class: constructors for initializing new objects, declarations for the fields that provide the state of the class and its objects, and methods to implement the behavior of the class and its objects.
The preceding class declaration is a minimal one—it contains only those components of a class declaration that are required. You can provide more information about the class, such as the name of its superclass, whether it implements any interfaces, and so on, at the start of the class declaration. For example,
class MyClass extends MySuperClass implements YourInterface {
//field, constructor, and method declarations
}
means that MyClass is a subclass of MySuperClass and that it implements the YourInterface interface.
You can also add modifiers like public or private at the very beginning—so you can see that the opening line of a class declaration can become quite complicated. The modifiers public and private, which determine what other classes can access MyClass, are discussed later in this lesson. The lesson on interfaces and inheritance will explain how and why you would use the extends and implements keywords in a class declaration. For the moment you do not need to worry about these extra complications.
In general, class declarations can include these components, in order:
Modifiers such as public, private, and a number of others that you will encounter later.
The class name, with the initial letter capitalized by convention.
The name of the class's parent (superclass), if any, preceded by the keyword extends. A class can only extend (subclass) one parent.
A comma-separated list of interfaces implemented by the class, if any, preceded by the keyword implements. A class can implement more than one interface.
The class body, surrounded by braces, {}.

BITWISE AND BITSHIFT OPERATORS

Bitwise and Bit Shift Operators
The Java programming language also provides operators that perform bitwise and bit shift operations on integral types. The operators discussed in this section are less commonly used. Therefore, their coverage is brief; the intent is to simply make you aware that these operators exist.
The unary bitwise complement operator "~" inverts a bit pattern; it can be applied to any of the integral types, making every "0" a "1" and every "1" a "0". For example, a byte contains 8 bits; applying this operator to a value whose bit pattern is "00000000" would change its pattern to "11111111".
The signed left shift operator "<<" shifts a bit pattern to the left, and the signed right shift operator ">>" shifts a bit pattern to the right. The bit pattern is given by the left-hand operand, and the number of positions to shift by the right-hand operand. The unsigned right shift operator ">>>" shifts a zero into the leftmost position, while the leftmost position after ">>" depends on sign extension.
The bitwise & operator performs a bitwise AND operation.
The bitwise ^ operator performs a bitwise exclusive OR operation.
The bitwise operator performs a bitwise inclusive OR operation.
The following program, BitDemo, uses the bitwise AND operator to print the number "2" to standard output.
class BitDemo {
public static void main(String[] args) {
int bitmask = 0x000F;
int val = 0x2222;
System.out.println(val & bitmask); // prints "2"
}
}

EQUALITY,RELATIONAL,CONDITIONAL OREPATORS

Equality, Relational, and Conditional Operators
The Equality and Relational Operators
The equality and relational operators determine if one operand is greater than, less than, equal to, or not equal to another operand. The majority of these operators will probably look familiar to you as well. Keep in mind that you must use "==", not "=", when testing if two primitive values are equal.
== equal to
!= not equal to
> greater than
>= greater than or equal to
< less than
<= less than or equal to
The following program, ComparisionDemo, tests the comparison operators:
class ComparisonDemo {
public static void main(String[] args){
int value1 = 1;
int value2 = 2;
if(value1 == value2) System.out.println("value1 == value2");
if(value1 != value2) System.out.println("value1 != value2");
if(value1 > value2) System.out.println("value1 > value2");
if(value1 < value2) System.out.println("value1 < value2");
if(value1 <= value2) System.out.println("value1 <= value2");
}
}
Output:
value1 != value2
value1 < value2
value1 <= value2
The Conditional Operators
The && and operators perform Conditional-AND and Conditional-OR operations on two boolean expressions. These operators exhibit "short-circuiting" behavior, which means that the second operand is evaluated only if needed.
&& Conditional-AND
Conditional-OR
The following program, ConditionalDemo1,tests these operators:
class ConditionalDemo1 {
public static void main(String[] args){
int value1 = 1;
int value2 = 2;
if((value1 == 1) && (value2 == 2)) System.out.println("value1 is 1 AND value2 is 2");
if((value1 == 1) (value2 == 1)) System.out.println("value1 is 1 OR value2 is 1");
}
}
Another conditional operator is ?:, which can be thought of as shorthand for an if-then-else statement (discussed in the ControlFlowStatements section of this lesson). This operator is also known as the ternary operator because it uses three operands. In the following example, this operator should be read as: "If someCondition is true, assign the value of value1 to result. Otherwise, assign the value of value2 to result."
The following program, ConditionalDemo2, tests the ?: operator:
class ConditionalDemo2
{
public static void main(String[] args)
{
int value1 = 1;
int value2 = 2;
int result;
boolean someCondition = true;
result = someCondition ? value1 : value2;
System.out.println(result);
}
}
Because someCondition is true, this program prints "1" to the screen. Use the ?: operator instead of an if-then-else statement if it makes your code more readable; for example, when the expressions are compact and without side-effects (such as assignments).
The Type Comparison Operator instanceof
The instanceof operator compares an object to a specified type. You can use it to test if an object is an instance of a class, an instance of a subclass, or an instance of a class that implements a particular interface.
The following program, InstanceofDemo, defines a parent class (named Parent), a simple interface (named MyInterface), and a child class (named Child) that inherits from the parent and implements the interface.
class InstanceofDemo
{
public static void main(String[] args)
{
Parent obj1 = new Parent();
Parent obj2 = new Child();
System.out.println("obj1 instanceof Parent: " + (obj1 instanceof Parent));
System.out.println("obj1 instanceof Child: " + (obj1 instanceof Child));
System.out.println("obj1 instanceof MyInterface: " + (obj1 instanceof MyInterface));
System.out.println("obj2 instanceof Parent: " + (obj2 instanceof Parent));
System.out.println("obj2 instanceof Child: " + (obj2 instanceof Child));
System.out.println("obj2 instanceof MyInterface: " + (obj2 instanceof MyInterface));
}
}
class Parent{}
class Child extends Parent implements MyInterface{}
interface MyInterface{}
Output:
obj1 instanceof Parent: true
obj1 instanceof Child: false
obj1 instanceof MyInterface: false
obj2 instanceof Parent: true
obj2 instanceof Child: true
obj2 instanceof MyInterface: true
When using the instanceof operator, keep in mind that null is not an instance of anything.

ASSIGNMENT,ARITHMETIC AND URINARY OPERATORS

The Simple Assignment Operator
One of the most common operators that you'll encounter is the simple assignment operator "=". You saw this operator in the Bicycle class; it assigns the value on its right to the operand on its left:
int cadence = 0;
int speed = 0;
int gear = 1;
This operator can also be used on objects to assign object references, as discussed in creating a object.The Arithmetic Operators
The Java programming language provides operators that perform addition, subtraction, multiplication, and division. There's a good chance you'll recognize them by their counterparts in basic mathematics. The only symbol that might look new to you is "%", which divides one operand by another and returns the remainder as its result.
+ additive operator (also used for String concatenation)
- subtraction operator
* multiplication operator
/ division operator
% remainder operator.
The following program ArithmeticDemo, tests the arithmetic operators.
class ArithmeticDemo
{
public static void main (String[] args)
{
int result = 1 + 2; // result is now 3
System.out.println(result);
result = result - 1; // result is now 2
System.out.println(result);
result = result * 2; // result is now 4
System.out.println(result);
result = result / 2; // result is now 2
System.out.println(result);
result = result + 8; // result is now 10
result = result % 7; // result is now 3
System.out.println(result);
}
}
You can also combine the arithmetic operators with the simple assignment operator to create compound assignments.
For example, x+=1; and x=x+1; both increment the value of x by 1.
The + operator can also be used for concatenating (joining) two strings together, as shown in the following program:
class ConcatDemo {
public static void main(String[] args){
String firstString = "This is";
String secondString = " a concatenated string.";
String thirdString = firstString+secondString;
System.out.println(thirdString);
}
}
By the end of this program, the variable thirdString contains "This is a concatenated string.", which gets printed to standard output.
The Unary Operators
The unary operators require only one operand; they perform various operations such as incrementing/decrementing a value by one, negating an expression, or inverting the value of a boolean.
+ Unary plus operator; indicates positive value (numbers are positive without this, however)
- Unary minus operator; negates an expression
++ Increment operator; increments a value by 1
-- Decrement operator; decrements a value by 1
! Logical complement operator; inverts the value of a boolean
The following program, urinary demo,tests the unary operators:
class UnaryDemo {
public static void main(String[] args){
int result = +1; // result is now 1
System.out.println(result);
result--; // result is now 0
System.out.println(result);
result++; // result is now 1
System.out.println(result);
result = -result; // result is now -1
System.out.println(result);
boolean success = false;
System.out.println(success); // false
System.out.println(!success); // true
}
}
The increment/decrement operators can be applied before (prefix) or after (postfix) the operand. The code result++; and ++result; will both end in result being incremented by one. The only difference is that the prefix version (++result) evaluates to the incremented value, whereas the postfix version (result++) evaluates to the original value. If you are just performing a simple increment/decrement, it doesn't really matter which version you choose. But if you use this operator in part of a larger expression, the one that you choose may make a significant difference.
The following program, PrePostDEmo, illustrates the prefix/postfix unary increment operator:
class PrePostDemo {
public static void main(String[] args){
int i = 3;
i++;
System.out.println(i); // "4"
++i;
System.out.println(i); // "5"
System.out.println(++i); // "6"
System.out.println(i++); // "6"
System.out.println(i); // "7"
}
}

OBJECT-ORIENTED PROGRAMMING CONCEPTS

What Is an Object?
An object is a software bundle of related state and behavior. Software objects are often used to model the real-world objects that you find in everyday life. This lesson explains how state and behavior are represented within an object, introduces the concept of data encapsulation, and explains the benefits of designing your software in this manner.
Objects are key to understanding object-oriented technology. Look around right now and you'll find many examples of real-world objects: your dog, your desk, your television set, your bicycle.
Real-world objects share two characteristics: They all have state and behavior. Dogs have state (name, color, breed, hungry) and behavior (barking, fetching, wagging tail). Bicycles also have state (current gear, current pedal cadence, current speed) and behavior (changing gear, changing pedal cadence, applying brakes). Identifying the state and behavior for real-world objects is a great way to begin thinking in terms of object-oriented programming.
Take a minute right now to observe the real-world objects that are in your immediate area. For each object that you see, ask yourself two questions: "What possible states can this object be in?" and "What possible behavior can this object perform?". Make sure to write down your observations. As you do, you'll notice that real-world objects vary in complexity; your desktop lamp may have only two possible states (on and off) and two possible behaviors (turn on, turn off), but your desktop radio might have additional states (on, off, current volume, current station) and behavior (turn on, turn off, increase volume, decrease volume, seek, scan, and tune). You may also notice that some objects, in turn, will also contain other objects. These real-world observations all translate into the world of object-oriented programming.
A software object.
Software objects are conceptually similar to real-world objects: they too consist of state and related behavior. An object stores its state in fields (variables in some programming languages) and exposes its behavior through methods (functions in some programming languages). Methods operate on an object's internal state and serve as the primary mechanism for object-to-object communication. Hiding internal state and requiring all interaction to be performed through an object's methods is known as data encapsulation — a fundamental principle of object-oriented programming.
Consider a bicycle, for example:
A bicycle modeled as a software object.By attributing state (current speed, current pedal cadence, and current gear) and providing methods for changing that state, the object remains in control of how the outside world is allowed to use it. For example, if the bicycle only has 6 gears, a method to change gears could reject any value that is less than 1 or greater than 6.
Bundling code into individual software objects provides a number of benefits, including:
Modularity: The source code for an object can be written and maintained independently of the source code for other objects. Once created, an object can be easily passed around inside the system.
Information-hiding: By interacting only with an object's methods, the details of its internal implementation remain hidden from the outside world.
Code re-use: If an object already exists (perhaps written by another software developer), you can use that object in your program. This allows specialists to implement/test/debug complex, task-specific objects, which you can then trust to run in your own code.
Pluggability and debugging ease: If a particular object turns out to be problematic, you can simply remove it from your application and plug in a different object as its replacement. This is analogous to fixing mechanical problems in the real world. If a bolt breaks, you replace it, not the entire machine.
What Is a Class?
In the real world, you'll often find many individual objects all of the same kind. There may be thousands of other bicycles in existence, all of the same make and model. Each bicycle was built from the same set of blueprints and therefore contains the same components. In object-oriented terms, we say that your bicycle is an instance of the class of objects known as bicycles. A class is the blueprint from which individual objects are created.
class Bicycle
{
int cadence = 0;
int speed = 0;
int gear = 1;
void changeCadence(int newValue)
{
cadence = newValue;
}
void changeGear(int newValue)
{
gear = newValue;
}
void speedUp(int increment)
{
speed = speed + increment;
}
void applyBrakes(int decrement)
{
speed = speed - decrement;
}
void printStates()
{
System.out.println("cadence:"+cadence+" speed:"+speed+" gear:"+gear);
}
}
The syntax of the Java programming language will look new to you, but the design of this class is based on the previous discussion of bicycle objects. The fields cadence, speed, and gear represent the object's state, and the methods (changeCadence, changeGear, speedUp etc.) define its interaction with the outside world.
You may have noticed that the Bicycle class does not contain a main method. That's because it's not a complete application; it's just the blueprint for bicycles that might be used in an application. The responsibility of creating and using new Bicycle objects belongs to some other class in your application. individual objects are created.
class BicycleDemo
{
public static void main(String[] args)
{ // Create two different Bicycle objects
Bicycle bike1 = new Bicycle();
Bicycle bike2 = new Bicycle(); // Invoke methods on those objects bike1.changeCadence(50);
bike1.speedUp(10);
bike1.changeGear(2);
bike1.printStates();
bike2.changeCadence(50);
bike2.speedUp(10);
bike2.changeGear(2);
bike2.changeCadence(40);
bike2.speedUp(10);
bike2.changeGear(3);
bike2.printStates();
}
}
The output of this test prints the ending pedal cadence, speed, and gear for the two bicycles: cadence:50 speed:10 gear:2
cadence:40 speed:20 gear:3.
What Is Inheritance?
Different kinds of objects often have a certain amount in common with each other. Mountain bikes, road bikes, and tandem bikes, for example, all share the characteristics of bicycles (current speed, current pedal cadence, current gear). Yet each also defines additional features that make them different: tandem bicycles have two seats and two sets of handlebars; road bikes have drop handlebars; some mountain bikes have an additional chain ring, giving them a lower gear ratio.
Object-oriented programming allows classes to inherit commonly used state and behavior from other classes. In this example, Bicycle now becomes the superclass of MountainBike, RoadBike, and TandemBike. In the Java programming language, each class is allowed to have one direct superclass, and each superclass has the potential for an unlimited number of subclasses.

The syntax for creating a subclass is simple. At the beginning of your class declaration, use the extends keyword, followed by the name of the class to inherit from: class MountainBike extends Bicycle {
// new fields and methods defining a mountain bike would go here
}
This gives MountainBike all the same fields and methods as Bicycle, yet allows its code to focus exclusively on the features that make it unique. This makes code for your subclasses easy to read. However, you must take care to properly document the state and behavior that each superclass defines, since that code will not appear in the source file of each subclass.
What Is an Interface?
As you've already learned, objects define their interaction with the outside world through the methods that they expose. Methods form the object's interface with the outside world; the buttons on the front of your television set, for example, are the interface between you and the electrical wiring on the other side of its plastic casing. You press the "power" button to turn the television on and off.
In its most common form, an interface is a group of related methods with empty bodies. A bicycle's behavior, if specified as an interface, might appear as follows:
interface Bicycle {
void changeCadence(int newValue);
void changeGear(int newValue);
void speedUp(int increment);
void applyBrakes(int decrement);
}
To implement this interface, the name of your class would change (to ACMEBicycle, for example), and you'd use the implements keyword in the class declaration:
class ACMEBicycle implements Bicycle {
// remainder of this class implemented as before
}
Implementing an interface allows a class to become more formal about the behavior it promises to provide. Interfaces form a contract between the class and the outside world, and this contract is enforced at build time by the compiler. If your class claims to implement an interface, all methods defined by that interface must appear in its source code before the class will successfully compile.
What Is a Package?
A package is a namespace that organizes a set of related classes and interfaces. Conceptually you can think of packages as being similar to different folders on your computer. You might keep HTML pages in one folder, images in another, and scripts or applications in yet another. Because software written in the Java programming language can be composed of hundreds or thousands of individual classes, it makes sense to keep things organized by placing related classes and interfaces into packages.
The Java platform provides an enormous class library (a set of packages) suitable for use in your own applications. This library is known as the "Application Programming Interface", or "API" for short. Its packages represent the tasks most commonly associated with general-purpose programming. For example, a String object contains state and behavior for character strings; a File object allows a programmer to easily create, delete, inspect, compare, or modify a file on the filesystem; a Socket object allows for the creation and use of network sockets; various GUI objects control buttons and checkboxes and anything else related to graphical user interfaces. There are literally thousands of classes to choose from. This allows you, the programmer, to focus on the design of your particular application, rather than the infrastructure required to make it work.

Monday, September 29, 2008

SUBTYPING

Subtyping
As you already know, it's possible to assign an object of one type to an object of another type provided that the types are compatible. For example, you can assign an Integer to an Object, since Object is one of Integer's supertypes: Object someObject = new Object();
Integer someInteger = new Integer(10);
someObject = someInteger; // OK
In object-oriented terminology, this is called an "is a" relationship. Since an Integer is a kind of Object, the assignment is allowed. But Integer is also a kind of Number, so the following code is valid as well: public void someMethod(Number n){
// method body omitted
}
someMethod(new Integer(10)); // OK
someMethod(new Double(10.1)); // OK
The same is also true with generics. You can perform a generic type invocation, passing Number as its type argument, and any subsequent invocation of add will be allowed if the argument is compatible with Number: Box box = new Box();
box.add(new Integer(10)); // OK
box.add(new Double(10.1)); // OK
Now consider the following method: public void boxTest(Box n){
// method body omitted
}
What type of argument does it accept? By looking at its signature, we can see that it accepts a single argument whose type is Box. But what exactly does that mean? Are you allowed to pass in Box or Box, as you might expect? Surprisingly, the answer is "no", because Box and Box are not subtypes of Box.
Understanding why becomes much easier if you think of tangible objects — things you can actually picture — such as a cage: // A cage is a collection of things, with bars to keep them in.
interface Cage extends Collection;
The Collection interface is the root interface of the collection hierarchy; it represents a group of objects. Since a cage would be used for holding a collection of objects (the animals), it makes sense to include it in this example.
A lion is a kind of animal, so Lion would be a subtype of Animal: interface Lion extends Animal {}
Lion king = ...;
Where we need some animal, we're free to provide a lion: Animal a = king;
A lion can of course be put into a lion cage: Cage lionCage = ...;
lionCage.add(king);
and a butterfly into a butterfly cage: interface Butterfly extends Animal {}
Butterfly monarch = ...;
Cage butterflyCage = ...;
butterflyCage.add(monarch);
But what about an "animal cage"? English is ambiguous, so to be precise let's assume we're talking about an "all-animal cage":
Cage animalCage = ...;
This is a cage designed to hold all kinds of animals, mixed together. It must have bars strong enough to hold in the lions, and spaced closely enough to hold in the butterflies. Such a cage might not even be feasible to build, but if it is, then: animalCage.add(king);
animalCage.add(monarch);
Since a lion is a kind of animal (Lion is a subtype of Animal), the question then becomes, "Is a lion cage a kind of animal cage? Is Cage a subtype of Cage?". By the above definition of animal cage, the answer must be "no". This is surprising! But it makes perfect sense when you think about it: A lion cage cannot be assumed to keep in butterflies, and a butterfly cage cannot be assumed to hold in lions. Therefore, neither cage can be considered an "all-animal" cage: animalCage = lionCage; // compile-time error
animalCage = butterflyCage; // compile-time error
Without generics, the animals could be placed into the wrong kinds of cages, where it would be possible for them to escape.

BOUNDED TYPE PARAMETERS

Bounded Type Parameters
There may be times when you'll want to restrict the kinds of types that are allowed to be passed to a type parameter. For example, a method that operates on numbers might only want to accept instances of Number or its subclasses. This is what bounded type parameters are for.
To declare a bounded type parameter, list the type parameter's name, followed by the extends keyword, followed by its upper bound, which in this example is Number. Note that, in this context, extends is used in a general sense to mean either "extends" (as in classes) or "implements" (as in interfaces).


/**
* This version introduces a bounded type parameter.
*/
public class Box {

private T t;

public void add(T t) {
this.t = t;
}

public T get() {
return t;
}

public void inspect(U u){
System.out.println("T: " + t.getClass().getName());
System.out.println("U: " + u.getClass().getName());
}

public static void main(String[] args) {
Box integerBox = new Box();
integerBox.add(new Integer(10));
integerBox.inspect("some text"); // error: this is still String!
}
}

By modifying our generic method to include this bounded type parameter, compilation will now fail, since our invocation of inspect still includes a String:
Box.java:21: inspect(U) in Box cannot
be applied to (java.lang.String)
integerBox.inspect("10");
^
1 error

To specify additional interfaces that must be implemented, use the & character, as in:




GENERIC METHODS AND CONSTRUCTORS

Generic Methods and Constructors
Type parameters can also be declared within method and constructor signatures to create generic methods and generic constructors. This is similar to declaring a generic type, but the type parameter's scope is limited to the method or constructor in which it's declared.
/**
* This version introduces a generic method.
*/
public class Box {
private T t;
public void add(T t) {
this.t = t;
}
public T get() {
return t;
}
public void inspect(U u){
System.out.println("T: " + t.getClass().getName());
System.out.println("U: " + u.getClass().getName());
}
public static void main(String[] args) {
Box integerBox = new Box();
integerBox.add(new Integer(10));
integerBox.inspect("some text");
}
}
Here we've added one generic method, named inspect, that defines one type parameter, named U. This method accepts an object and prints its type to standard output. For comparison, it also prints out the type of T. For convenience, this class now also has a main method so that it can be run as an application.
The output from this program is:
T: java.lang.Integer
U: java.lang.String
By passing in different types, the output will change accordingly.
A more realistic use of generic methods might be something like the following, which defines a static method that stuffs references to a single item into multiple boxes: public static void fillBoxes(U u, List> boxes) {
for (Box box : boxes) {
box.add(u);
}
}
To use this method, your code would look something like the following: Crayon red = ...;
List> crayonBoxes = ...;
The complete syntax for invoking this method is:
Box.fillBoxes(red, crayonBoxes);
Here we've explicitly provided the type to be used as U, but more often than not, this can be left out and the compiler will infer the type that's needed:
Box.fillBoxes(red, crayonBoxes); // compiler infers that U is Crayon
This feature, known as type inference, allows you to invoke a generic method as you would an ordinary method, without specifying a type between angle brackets.

GENERICS

Introduction
In any nontrivial software project, bugs are simply a fact of life. Careful planning, programming, and testing can help reduce their pervasiveness, but somehow, somewhere, they'll always find a way to creep into your code. This becomes especially apparent as new features are introduced and your code base grows in size and complexity.
Fortunately, some bugs are easier to detect than others. Compile-time bugs, for example, tell you immediately that something is wrong; you can use the compiler's error messages to figure out what the problem is and fix it, right then and there. Runtime bugs, however, can be much more problematic; they don't always surface immediately, and when they do, it may be at a point in time that's far removed from the actual cause of the problem.
Generics add stability to your code by making more of your bugs detectable at compile time. Some programmers choose to learn generics by studying the Java Collections Framework; after all, generics are heavily used by those classes. However, since we haven't yet covered collections, this chapter will focus primarily on simple "collections-like" examples that we'll design from scratch. This hands-on approach will teach you the necessary syntax and terminology while demonstrating the various kinds of problems that generics were designed to solve.
A Simple Box ClassLet's begin by designing a nongeneric Box class that operates on objects of any type. It need only provide two methods: add, which adds an object to the box, and get, which retrieves it: public class Box {
private Object object;
public void add(Object object) {
this.object = object;
}
public Object get() {
return object;
}
}
Since its methods accept or return Object, you're free to pass in whatever you want, provided that it's not one of the primitive types. However, should you need to restrict the contained type to something specific (like Integer), your only option would be to specify the requirement in documentation (or in this case, a comment), which of course the compiler knows nothing about:
public class BoxDemo1 {
public static void main(String[] args) {
// ONLY place Integer objects into this box!
Box integerBox = new Box();
integerBox.add(new Integer(10));
Integer someInteger = (Integer)integerBox.get();
System.out.println(someInteger);
}
}
The BoxDemo1 program creates an Integer object, passes it to add, then assigns that same object to someInteger by the return value of get. It then prints the object's value (10) to standard output. We know that the cast from Object to Integer is correct because we've honored the "contract" specified in the comment. But remember, the compiler knows nothing about this — it just trusts that our cast is correct. Furthermore, it will do nothing to prevent a careless programmer from passing in an object of the wrong type, such as String:
public class BoxDemo2 {
public static void main(String[] args) {
// ONLY place Integer objects into this box!
Box integerBox = new Box();
// Imagine this is one part of a large application
// modified by one programmer.
integerBox.add("10"); // note how the type is now String
// ... and this is another, perhaps written
// by a different programmer
Integer someInteger = (Integer)integerBox.get();
System.out.println(someInteger);
}
}
In BoxDemo2 we've stored the number 10 as a String, which could be the case when, say, a GUI collects input from the user. However, the existing cast from Object to Integer has mistakenly been overlooked. This is clearly a bug, but because the code still compiles, you wouldn't know anything is wrong until runtime, when the application crashes with a ClassCastException: Exception in thread "main"
java.lang.ClassCastException:
java.lang.String cannot be cast to java.lang.Integer
at BoxDemo2.main(BoxDemo2.java:6)
If the Box class had been designed with generics in mind, this mistake would have been caught by the compiler, instead of crashing the application at runtime.

CLASSPATH

Managing Source and Class Files
Many implementations of the Java platform rely on hierarchical file systems to manage source and class files, although The Java Language Specification does not require this. The strategy is as follows.
Put the source code for a class, interface, enumeration, or annotation type in a text file whose name is the simple name of the type and whose extension is .java. For example:
// in the Rectangle.java file
package graphics;
public class Rectangle() {
. . .
}
Then, put the source file in a directory whose name reflects the name of the package to which the type belongs:
.....\graphics\Rectangle.java
The qualified name of the package member and the path name to the file are parallel, assuming the Microsoft Windows file name separator backslash (for Unix, use the forward slash).
class name
graphics.Rectangle
pathname to file
graphics\Rectangle.java
As you should recall, by convention a company uses its reversed Internet domain name for its package names. The Example company, whose Internet domain name is example.com, would precede all its package names with com.example. Each component of the package name corresponds to a subdirectory. So, if the Example company had a com.example.graphics package that contained a Rectangle.java source file, it would be contained in a series of subdirectories like this:
....\com\example\graphics\Rectangle.java
When you compile a source file, the compiler creates a different output file for each type defined in it. The base name of the output file is the name of the type, and its extension is .class. For example, if the source file is like this
// in the Rectangle.java file
package com.example.graphics;
public class Rectangle{
. . .
}
class Helper{
. . .
}
then the compiled files will be located at:
\com\example\graphics\Rectangle.class
\com\example\graphics\Helper.class
Like the .java source files, the compiled .class files should be in a series of directories that reflect the package name. However, the path to the .class files does not have to be the same as the path to the .java source files. You can arrange your source and class directories separately, as:
\sources\com\example\graphics\Rectangle.java
\classes\com\example\graphics\Rectangle.class
By doing this, you can give the classes directory to other programmers without revealing your sources. You also need to manage source and class files in this manner so that the compiler and the Java Virtual Machine (JVM) can find all the types your program uses.
The full path to the classes directory, \classes, is called the class path, and is set with the CLASSPATH system variable. Both the compiler and the JVM construct the path to your .class files by adding the package name to the class path. For example, if
\classes
is your class path, and the package name is
com.example.graphics,
then the compiler and JVM look for .class files in
\classes\com\example\graphics.
A class path may include several paths, separated by a semicolon (Windows) or colon (Unix). By default, the compiler and the JVM search the current directory and the JAR file containing the Java platform classes so that these directories are automatically in your class path.
Setting the CLASSPATH System VariableTo display the current CLASSPATH variable, use these commands in Windows and Unix (Bourne shell):
In Windows: C:\> set CLASSPATH
In Unix: % echo $CLASSPATH
To delete the current contents of the CLASSPATH variable, use these commands:
In Windows: C:\> set CLASSPATH=
In Unix: % unset CLASSPATH; export CLASSPATH
To set the CLASSPATH variable, use these commands (for example):
In Windows: C:\> set CLASSPATH=C:\users\george\java\classes
In Unix: % CLASSPATH=/home/george/java/classes; export CLASSPATH

USING PACKAGE

Using Package Members
The types that comprise a package are known as the package members.
To use a public package member from outside its package, you must do one of the following:
Refer to the member by its fully qualified name
Import the package member
Import the member's entire package Each is appropriate for different situations, as explained in the sections that follow.
Referring to a Package Member by Its Qualified NameSo far, most of the examples in this tutorial have referred to types by their simple names, such as Rectangle and StackOfInts. You can use a package member's simple name if the code you are writing is in the same package as that member or if that member has been imported.
However, if you are trying to use a member from a different package and that package has not been imported, you must use the member's fully qualified name, which includes the package name. Here is the fully qualified name for the Rectangle class declared in the graphics package in the previous example.
graphics.Rectangle
You could use this qualified name to create an instance of graphics.Rectangle:
graphics.Rectangle myRect = new graphics.Rectangle();
Qualified names are all right for infrequent use. When a name is used repetitively, however, typing the name repeatedly becomes tedious and the code becomes difficult to read. As an alternative, you can import the member or its package and then use its simple name.
Importing a Package MemberTo import a specific member into the current file, put an import statement at the beginning of the file before any type definitions but after the package statement, if there is one. Here's how you would import the Rectangle class from the graphics package created in the previous section.
import graphics.Rectangle;
Now you can refer to the Rectangle class by its simple name.
Rectangle myRectangle = new Rectangle();
This approach works well if you use just a few members from the graphics package. But if you use many types from a package, you should import the entire package.
Importing an Entire PackageTo import all the types contained in a particular package, use the import statement with the asterisk (*) wildcard character.
import graphics.*;
Now you can refer to any class or interface in the graphics package by its simple name.
Circle myCircle = new Circle();
Rectangle myRectangle = new Rectangle();
The asterisk in the import statement can be used only to specify all the classes within a package, as shown here. It cannot be used to match a subset of the classes in a package. For example, the following does not match all the classes in the graphics package that begin with A.
import graphics.A*; //does not work
Instead, it generates a compiler error. With the import statement, you generally import only a single package member or an entire package.
Note: Another, less common form of import allows you to import the public nested classes of an enclosing class. For example, if the graphics.Rectangle class contained useful nested classes, such as Rectangle.DoubleWide and Rectangle.Square, you could import Rectangle and its nested classes by using the following two statements.
import graphics.Rectangle;
import graphics.Rectangle.*;
Be aware that the second import statement will not import Rectangle.
Another less common form of import, the static import statement, will be discussed at the end of this section.
For convenience, the Java compiler automatically imports three entire packages for each source file: (1) the package with no name, (2) the java.lang package, and (3) the current package (the package for the current file).
Apparent Hierarchies of PackagesAt first, packages appear to be hierarchical, but they are not. For example, the Java API includes a java.awt package, a java.awt.color package, a java.awt.font package, and many others that begin with java.awt. However, the java.awt.color package, the java.awt.font package, and other java.awt.xxxx packages are not included in the java.awt package. The prefix java.awt (the Java Abstract Window Toolkit) is used for a number of related packages to make the relationship evident, but not to show inclusion.
Importing java.awt.* imports all of the types in the java.awt package, but it does not import java.awt.color, java.awt.font, or any other java.awt.xxxx packages. If you plan to use the classes and other types in java.awt.color as well as those in java.awt, you must import both packages with all their files:
import java.awt.*;
import java.awt.color.*;
Name AmbiguitiesIf a member in one package shares its name with a member in another package and both packages are imported, you must refer to each member by its qualified name. For example, the graphics package defined a class named Rectangle. The java.awt package also contains a Rectangle class. If both graphics and java.awt have been imported, the following is ambiguous.
Rectangle rect;
In such a situation, you have to use the member's fully qualified name to indicate exactly which Rectangle class you want. For example,
graphics.Rectangle rect;
The Static Import StatementThere are situations where you need frequent access to static final fields (constants) and static methods from one or two classes. Prefixing the name of these classes over and over can result in cluttered code. The static import statement gives you a way to import the constants and static methods that you want to use so that you do not need to prefix the name of their class.
The java.lang.Math class defines the PI constant and many static methods, including methods for calculating sines, cosines, tangents, square roots, maxima, minima, exponents, and many more. For example,
public static final double PI 3.141592653589793
public static double cos(double a)
Ordinarily, to use these objects from another class, you prefix the class name, as follows.
double r = Math.cos(Math.PI * theta);
You can use the static import statement to import the static members of java.lang.Math so that you don't need to prefix the class name, Math. The static members of Math can be imported either individually:
import static java.lang.Math.PI;
or as a group:
import static java.lang.Math.*;
Once they have been imported, the static members can be used without qualification. For example, the previous code snippet would become:
double r = cos(PI * theta);
Obviously, you can write your own classes that contain constants and static methods that you use frequently, and then use the static import statement. For example,
import static mypackage.MyConstants.*;

NAMING PACKAGE

Naming a Package
With programmers worldwide writing classes and interfaces using the Java programming language, it is likely that many programmers will use the same name for different types. In fact, the previous example does just that: It defines a Rectangle class when there is already a Rectangle class in the java.awt package. Still, the compiler allows both classes to have the same name if they are in different packages. The fully qualified name of each Rectangle class includes the package name. That is, the fully qualified name of the Rectangle class in the graphics package is graphics.Rectangle, and the fully qualified name of the Rectangle class in the java.awt package is java.awt.Rectangle.
This works well unless two independent programmers use the same name for their packages. What prevents this problem? Convention.
Naming ConventionsPackage names are written in all lowercase to avoid conflict with the names of classes or interfaces.
Companies use their reversed Internet domain name to begin their package names—for example, com.example.orion for a package named orion created by a programmer at example.com.
Name collisions that occur within a single company need to be handled by convention within that company, perhaps by including the region or the project name after the company name (for example, com.company.region.package).
Packages in the Java language itself begin with java. or javax.
In some cases, the internet domain name may not be a valid package name. This can occur if the domain name contains a hyphen or other special character, if the package name begins with a digit or other character that is illegal to use as the beginning of a Java name, or if the package name contains a reserved Java keyword, such as "int". In this event, the suggested convention is to add an underscore. For example:
Legalizing Package Names
Domain Name Package Name Prefix
clipart-open.org org.clipart_open
free.fonts.int int_.fonts.free
poetry.7days.com com._7days.poetry

CREATING PACKAGE

To create a package, you choose a name for the package (naming conventions are discussed in the next section) and put a package statement with that name at the top of every source file that contains the types (classes, interfaces, enumerations, and annotation types) that you want to include in the package.
The package statement (for example, package graphics;) must be the first line in the source file. There can be only one package statement in each source file, and it applies to all types in the file.
Note: If you put multiple types in a single source file, only one can be public, and it must have the same name as the source file. For example, you can define public class Circle in the file Circle.java, define public interface Draggable in the file Draggable.java, define public enum Day in the file Day.java, and so forth.
You can include non-public types in the same file as a public type (this is strongly discouraged, unless the non-public types are small and closely related to the public type), but only the public type will be accessible from outside of the package. All the top-level, non-public types will be package private.
If you put the graphics interface and classes listed in the preceding section in a package called graphics, you would need six source files, like this:
//in the Draggable.java file
package graphics;
public interface Draggable {
. . .
}
//in the Graphic.java file
package graphics;
public abstract class Graphic {
. . .
}
//in the Circle.java file
package graphics;
public class Circle extends Graphic implements Draggable {
. . .
}
//in the Rectangle.java file
package graphics;
public class Rectangle extends Graphic implements Draggable {
. . .
}
//in the Point.java file
package graphics;
public class Point extends Graphic implements Draggable {
. . .
}
//in the Line.java file
package graphics;
public class Line extends Graphic implements Draggable {
. . .
}
If you do not use a package statement, your type ends up in an unnamed package. Generally speaking, an unnamed package is only for small or temporary applications or when you are just beginning the development process. Otherwise, classes and interfaces belong in named packages.

PACKAGES

Definition: A package is a grouping of related types providing access protection and name space management. Note that types refers to classes, interfaces, enumerations, and annotation types. Enumerations and annotation types are special kinds of classes and interfaces, respectively, so types are often referred to in this lesson simply as classes and interfaces.
The types that are part of the Java platform are members of various packages that bundle classes by function: fundamental classes are in java.lang, classes for reading and writing (input and output) are in java.io, and so on. You can put your types in packages too.
Suppose you write a group of classes that represent graphic objects, such as circles, rectangles, lines, and points. You also write an interface, Draggable, that classes implement if they can be dragged with the mouse.
//in the Draggable.java file
public interface Draggable {
. . .
}
//in the Graphic.java file
public abstract class Graphic {
. . .
}
//in the Circle.java file
public class Circle extends Graphic implements Draggable {
. . .
}
//in the Rectangle.java file
public class Rectangle extends Graphic implements Draggable {
. . .
}
//in the Point.java file
public class Point extends Graphic implements Draggable {
. . .
}
//in the Line.java file
public class Line extends Graphic implements Draggable {
. . .
}
You should bundle these classes and the interface in a package for several reasons, including the following:
You and other programmers can easily determine that these types are related.
You and other programmers know where to find types that can provide graphics-related functions.
The names of your types won't conflict with the type names in other packages because the package creates a new namespace.
You can allow types within the package to have unrestricted access to one another yet still restrict access for types outside the package.

BRANCHING STATEMENTS

Branching Statements:
Break statements:
The break statement is a branching statement that contains two forms: labeled and unlabeled. The break statement is used for breaking the execution of a loop (while, do-while and for) . It also terminates the switch statements.
Syntax:
break; // breaks the innermost loop or switch statement.
break label; // breaks the outermost loop in a series of nested loops.
Example: When if statement evaluates to true it prints "data is found" and comes out of the loop and executes the statements just following the loop.
Continue statements:
This is a branching statement that are used in the looping statements (while, do-while and for) to skip the current iteration of the loop and resume the next iteration .
Syntax: continue;Example:
Return statements:It is a special branching statement that transfers the control to the caller of the method. This statement is used to return a value to the caller method and terminates execution of method. This has two forms: one that returns a value and the other that can not return. the returned value type must match the return type of method.
Syntax:
return;
return values;
return; //This returns nothing. So this can be used when method is declared with void return type.return expression; //It returns the value evaluated from the expression.
Example: Here Welcome() function is called within println() function which returns a String value This is printed to the screen.