100% found this document useful (1 vote)
101 views43 pages

Introduction To Java

Intro to Java discusses why Java was created, how it is compiled and run, its uses for web programming and applications, and an overview of key Java concepts like classes, objects, packages, and exceptions. Java aims to be platform independent, secure, and robust. It uses a compiler to convert Java code to bytecode that runs on a Java Virtual Machine on any device.

Uploaded by

Rohit Bhatia
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
Download as ppt, pdf, or txt
100% found this document useful (1 vote)
101 views43 pages

Introduction To Java

Intro to Java discusses why Java was created, how it is compiled and run, its uses for web programming and applications, and an overview of key Java concepts like classes, objects, packages, and exceptions. Java aims to be platform independent, secure, and robust. It uses a compiler to convert Java code to bytecode that runs on a Java Virtual Machine on any device.

Uploaded by

Rohit Bhatia
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1/ 43

Intro 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

this makes it great for Web programming

Its more secure

Must Run on Any Architecture


WRITE ONCE, RUN ANYWHERE!
Program in Java

debug

pretty portable

Java Compiler

Java Bytecode

Java Virtual Machine

Java Virtual Machine

Javas Compiler + Interpreter

Editor

Compiler

7 K

Hello.java

:
Hello.class

Interpreter

Interpreter

:
Hello, World!

Java on the Web: Java Applets


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

Java on the Web: J2EE


Thin clients (minimize download) Java all server side


JSPs
Servlets

Client EJB

Server

THIS IS WHAT YOULL BE DOING!!

JDBC

The Java programming environment

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

High performance through Just in time compilation + runtime modification of code

Multi-threaded

Java Features

Well defined primitive data types: int, float, double, char, etc.

int 4 bytes [2,147,648, 2,147,483,647]

Control statements similar to C++: if-then-else, switch, while, for

Interfaces
Exceptions Packages AWT,Swing..etc

JDK Java Development Kit

javac

javadoc

Java compiler

java

generates HTML documentation (docs) from source

Java interpreter

appletviewer

jar

tests applets without a browser

packs classes into jar files (packages)

All these are command-line tools, no GUI

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

Usually JDK is installed separately and an IDE is installed on top of it.

10

How are Java programs written?

Define a class HelloWorld and store it into a file: HelloWorld.java:


public class HelloWorld { public static void main (String[] args) { System.out.println(Hello, World); } }

Compile HelloWorld.java
javac HelloWorld.java

Output: HelloWorld.class

Run
java HelloWorld

Output: Hello, World


11

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

The class or instances of the class (an object of the class)

12

How to define expressions?

Arithmetic: +, -, *,/, %, =
8 + 3 * 2 /4 Use standard precedence and associativity rules

Predicates: ==, !=, >, <, >=, <=


public class Demo {
public static void main (String[] argv) {
boolean b; b = (2 + 2 == 4); System.out.println(b);

}
13

How are simple methods defined?


Every method is defined inside a Java class definition
public class Movie {
public static int movieRating(int s, int a, int d) {
return s+a+d;

} public class Demo {


public static void main (String argv[]) {
int script = 6, acting = 9, directing = 8; displayRating(script, acting, directing);

} public static void displayRating(int s, int a, int d){


System.out.print(The rating of this movie is); System.out.println(Movie.movieRating(s, a, d));

14

Java: A tiny intro


How are Java programs written? How are variables declared?

How are expressions specified?


How are control structures defined? How to define simple methods? What are classes and objects? What about exceptions?

15

What are classes and objects?


Classes: templates for constructing instances Fields
Instance variables Static variables

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

How are instance methods defined?


Instance methods take an implicit parameter: instance on which method is invoked
public class Movie {
public int script, acting, directing; public int rating() {
return script + acting + directing;

} public class Demo {


public static void main (String argv[]) {
Movie m = new Movie(); m.script = 6; m.acting = 9; m.directing = 8; System.out.print(The rating of this movie is); System.out.println(m.rating());

}
17

How to extend classes?

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

units of organizing related Classes, Interfaces, Sub packages Why?


Reduce name clashing Limit visibility of names

Java programs typically organized in terms of packages and subpackages


Each package may then be divided into several packages, subpackages, and classes Each class can then be stored in a separate file
package mypackage;

Each source file starts with something like:

Code in source file is now part of mypackage


19

Packages contd.
package onto.java.entertainment; public abstract class Attraction { }

package onto.java.entertainment; public class Movie extends class Attraction {}

package onto.java.entertainment; import java.io.*; import java.util.*; public class Auxiliaries { }

Where to store packages? How does Java find packages?

Export and Import


Access control
20

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.

Hierarchical Structure of Throwable Class

Object
Throwable Error Exception

...

RuntimeException ... ...

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

Check and Handle the Exception


try { // } catch (ExceptionType1 identifier) { // } catch (ExceptionType2 identifier) { // } finally { // } [ExceptionHandler.java]

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

Using a GUI Component


1.

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

Anatomy of an Application GUI


GUI Internal structure

JFrame
JPanel containers

JFrame

JPanel
JButton

JButton
JLabel

JLabel

Procedure to create GUI Components


1. 2. 3. 4. 5.

Create it Configure it Add children (if container) Add to parent (if not JFrame) Listen to it

order important

Build from bottom up

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:

FlowLayout GridLayout BorderLayout BoxLayout

These classes implement the java.awt.LayoutManager interface.

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:

ActionListener ChangeListener ItemListener etc.

The same object can serve as different types of listeners (as long as its class implements all the corresponding interfaces).

16-36

Keyboard Events

The KeyListener interface defines three methods:


void keyPressed (KeyEvent e) void keyReleased (KeyEvent e) void keyTyped (KeyEvent e)

One key pressed and released causes several 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:

public void keyTyped (KeyEvent e) { char ch = e.getKeyChar(); if (ch == A) ... }


17-38

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:

VK_LEFT, VK_RIGHT, VK_UP, VK_DOWN VK_HOME, VK_END, VK_PAGE_UP, ...etc.

Cursor keys Home, etc.


17-39

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

The MouseListener interface defines five methods:


void mousePressed (MouseEvent e) void mouseReleased (MouseEvent e) void mouseClicked (MouseEvent e) void mouseEntered (MouseEvent e) void mouseExited (MouseEvent e)

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

The MouseMotionListener interface adds two methods:


Called when the mouse has moved These methods are often used together with with a button MouseListener methods (the same class implements held down void mouseMoved (MouseEvent e) void mouseDragged (MouseEvent e)

both interfaces).

17-43

You might also like