Introduction To Java
Introduction To Java
ROHIT BHATIA ROHTAK INST. OF ENGG. & MGT. Whats the first question youve got to ask about a language named Java?
Why Java?
Its the current hot language Its almost entirely object-oriented It has a vast library of predefined objects and operations Its more platform independent
debug
pretty portable
Java Compiler
Java Bytecode
Editor
Compiler
7 K
Hello.java
:
Hello.class
Interpreter
Interpreter
:
Hello, World!
Clients download applets via Web browser Browser runs applet in a Java Virtual Machine (JVM)
Applet
Client
Server
Interactive web, security, and client consistency Slow to download, inconsistent VMs (besides, flash won this war)
5
Client EJB
Server
JDBC
Compared to C++:
no header files, macros, pointers and references, unions, operator overloading, templates, etc.
Object-orientation: Classes + Inheritance Distributed: RMI, Servlet, Distributed object programming. Robust: Strong typing + no pointer + garbage collection Secure: Type-safety + access control Architecture neutral: architecture neutral representation Portable Interpreted
Multi-threaded
Java Features
Well defined primitive data types: int, float, double, char, etc.
Interfaces
Exceptions Packages AWT,Swing..etc
javac
javadoc
Java compiler
java
Java interpreter
appletviewer
jar
Java IDE
GUI front end for JDK Integrates editor, javac, java, appletviewer, debugger, other tools:
specialized Java editor with syntax highlighting, autoindent, tab setting, etc. clicking on a compiler error message takes you to the offending source code line
10
Compile HelloWorld.java
javac HelloWorld.java
Output: HelloWorld.class
Run
java HelloWorld
Qualifiers
public any class* may access (no qualifier) package protected only the class* and classes* in the same package may access protected only the class* and decendent classes* may access private only the class* may access
12
Arithmetic: +, -, *,/, %, =
8 + 3 * 2 /4 Use standard precedence and associativity rules
}
13
14
15
Methods
Instance Static
class Point { public double x, y; } Point lowerleft = new Point(); Point upperRight = new Point(); Point middlePoint = new Point(); lowerLeft.x = 0.0; lowerLeft.y = 0.0; upperRight.x = 1280.0; upperRight.y = 1024.0 middlePoint.x = 640.0; middlePoint.y = 512.0
16
}
17
Inheritance: mechanism for extending behavior of classes; leads to construction of hierarchy of classes [Note: no multiple inheritance] What happens when class C extends class D:
Inherits instance variables Inherits static variables Inherits instance methods Inherits static methods C can:
Add new instance variables Add new methods (static and dynamic) Modify methods (only implementation) Cannot delete anything
18
Packages
Each package may then be divided into several packages, subpackages, and classes Each class can then be stored in a separate file
package mypackage;
Packages contd.
package onto.java.entertainment; public abstract class Attraction { }
Exception
Error occurred in execution time Abnormal termination of program Wrong execution result Provide an exception handling mechanism in language system
Improve the reliability of application program Allow simple program code for exeception check and handling into source
Exception Definition
Treat exception as an object All exceptions are instances of a class extended from Throwable class or its subclass.
Generally, a programmer makes new exception class to extend the Exception class which is subclass of Throwable class.
Object
Throwable Error Exception
...
System-Defined Exception
IndexOutOfBoundsException :
When beyond the bound of index in the object which use index, such as array, string, and vector When assign object of incorrect type to element of array When using a negative size of array When refer to object as a null pointer When violate security. Caused by security manager When the thread which is not owner of monitor involves wait or notify method
ArrayStoreException :
NegativeArraySizeException :
NullPointerException :
SecurityException :
IllegalMonitorStateException :
Exception Handling
try-catch-finally Statement
AWT to Swing
AWT: Abstract Windowing Toolkit import java.awt.* Swing: new with Java2 import javax.swing.* Extends AWT Tons o new improved components Standard dialog boxes, tooltips, Look-and-feel, skins Event listeners
2.
3.
4.
Create it Instantiate object: b = new JButton(press me); Configure it Properties: b.text = press me; [avoided in java] Methods: b.setText(press me); Add it panel.add(b); JButton Listen to it Events: Listeners
JFrame
JPanel containers
JFrame
JPanel
JButton
JButton
JLabel
JLabel
Create it Configure it Add children (if container) Add to parent (if not JFrame) Listen to it
order important
Create: Frame Panel Components Listeners Add: (bottom up) listeners into components components into panel panel into frame
Listener
JLabel
JButton
JPanel
JFrame
Layouts
A layout manager is a strategy for placing components on the content pane or another component (usually a panel). In Java, the content pane and any GUI component is a Container. A layout is chosen by calling the containers setLayout method.
16-31
Layouts (contd)
Layouts are used to achieve some degree of platform independence and scalability. awt/Swing support several layout managers. Here we consider four:
16-32
FlowLayout
Places components in a line as long as they fit, then starts the next line. Uses best judgement in spacing components. Centers by default. Lets each component assume its natural (preferred) size. Often used for placing buttons on panels.
16-33
FlowLayout (contd)
Container c = getContentPane(); c.setLayout(new FlowLayout()); c.add (new JButton ("Back to Start")); c.add (new JButton ("Previous Slide")); c.add (new JButton ("Next Slide")); c.add (new JButton ("Last Slide")); c.add (new JButton ("Exit"));
16-34
GUI Events
Components (except JLabel) can generate events. Events are captured and processed by listeners objects equipped to handle a particular type of events. Different types of events are processed by different types of listeners.
16-35
Listeners
Different types of listeners are described as interfaces:
The same object can serve as different types of listeners (as long as its class implements all the corresponding interfaces).
16-36
Keyboard Events
17-37
Keyboard Events
Use keyTyped to capture character keys (that is, keys that correspond to printable characters). e.getKeyChar() returns a char, the typed character:
Keyboard Events
Use keyPressed or keyReleased to handle action keys, such as cursor keys, <Enter>, function keys, and so on. e.getKeyCode() returns and int, the keys virtual code. The KeyEvent class defines constants for numerous virtual keys. For example:
Mouse Events
Mouse events are captured by an object which is a MouseListener and possibly a MouseMotionListener. A mouse listener is often attached to a JPanel component. It is not uncommon for a panel to serve as its own mouse listener:
public MyPanel() { ... addMouseListener(this); addMouseMotionListener(this); // optional
17-40
Mouse Events
Called when the mouse cursor One click and release causes several calls. Using only mouseReleased is usually a safe bet. enters/exits components visible area
17-41
Mouse Events
Mouse listener methods receive a MouseEvent object as a parameter. A mouse event can provide the coordinates of the event and other information:
public void mousePressed (MouseEvent e) { int x = e.getX(); int y = e.getY(); int b = e.getButton(); }
17-42
Mouse Events
both interfaces).
17-43