Java For beginners and CSIT and IT students

133
Advanced Java Programming B.Sc.CSIT Seventh Semester By Nabin Jamkatel

Transcript of Java For beginners and CSIT and IT students

Page 1: Java  For beginners and CSIT and IT students

Advanced Java ProgrammingB.Sc.CSIT Seventh Semester

By Nabin Jamkatel

Page 2: Java  For beginners and CSIT and IT students

Unit 1. Programming In Java

Page 3: Java  For beginners and CSIT and IT students

1.1 Introduction to Java• A general-purpose computer programming

language designed to produce programs that will run on any computer system.

• A high-level programming language developed by Sun Microsystems.

• Games Gosling, OAK 1991, changed to Java in 1995,

• OOP - Object Oriented Programming Language

• Platform independent

• Secure, multithreaded, distributed, portable…

Page 4: Java  For beginners and CSIT and IT students

Java Architecture

Page 5: Java  For beginners and CSIT and IT students

Java ArchitectureJava's architecture arises out of four distinct but interrelated technologies:

• The Java programming language

• The Java class file format

• The Java API (Application Programming Interface)

• The JVM (Java Virtual Machine)

Page 6: Java  For beginners and CSIT and IT students

Java Architecture• JVM (Java Virtual Machine) :- The abstract

computer on which all Java programs run.

• Bytecode is a highly optimized set of instructions designed to be executed by the Java run-time system, which is called the Java Virtual Machine (JVM).

• Just-in-time compilation (JIT), also known as dynamic translation, is compilation done during execution of a program – at run time – rather than prior to execution.

• The Java Classloader is a part of the Java Runtime Environment that dynamically loads Java classes into the Java Virtual Machine.

Page 7: Java  For beginners and CSIT and IT students

Advantages of Java

• Java is easy to learn. Java was designed to be easy to use and is therefore easy to write, compile, debug, and learn than other programming languages.

• Java is object-oriented. This allows you to create modular programs and reusable code.

• Java is platform-independent.

Page 8: Java  For beginners and CSIT and IT students

PATH and CLASSPATH VariablesPATH

• The PATH is the system variable that your operating system uses to locate needed executables from the command line or Terminal window.

• %JAVA_HOME%\bin;

CLASSPATH• The CLASSPATH variable is one way to tell applications,

including the JDK tools, where to look for user classes.• The default value of the class path is ".“• -cp command line switch

http://docs.oracle.com/javase/tutorial/essential/environment/paths.html

Page 9: Java  For beginners and CSIT and IT students

Compiling and Running Java Programs

• Open notepad or any text editor

• Type below lines

public class HelloWorld {

public static void main(String[] args) {

System.out.println("Hello World!");

} //end of main

} //end of class

• Save file as HelloWorld.java and open CMD

• Locate above file and type: javac HelloWorld.java

• Again type: java HelloWorld

Page 10: Java  For beginners and CSIT and IT students

1.2 Class and ObjectClass

• A class is the blueprint from which individual objects are created.

• In object-oriented programming, a class is an extensible program-code-template for creating objects, providing initial values for state (member variables) and implementations of behavior (member functions, methods).

Example:

class MyClass{

// constructors, methods, variable,

}

Page 11: Java  For beginners and CSIT and IT students

1.2 Class and ObjectObject

• In the class-based object-oriented programming paradigm, "object" refers to a particular instance of a class where the objectcan be a combination of variables, functions, and data structures.

Example:

MyClass object = new MyClass();

Page 12: Java  For beginners and CSIT and IT students

Creating Classesclass Bicycle {

int cadence; int speed ; int gear;

public Bicycle(){

cadence = 0; speed = 0; 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);

}

}

Page 13: Java  For beginners and CSIT and IT students

Creating Classesclass BicycleDemo {

public static void main(String[] args) {

// Create two different Bicycle objectsBicycle bike1 = new Bicycle();Bicycle bike2 = new Bicycle();

// Invoke methods on those objectsbike1.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();

}}

Page 14: Java  For beginners and CSIT and IT students

Interfaces• A Java interface is a bit like a class, except you can only

declare methods and variables in the interface.

• You cannot actually implement the methods.

• Interfaces are a way to achieve polymorphism in Java.

• Interfaces cannot be instantiated, but rather are implemented.

• A class that implements an interface must implement all of the methods described in the interface, or be an abstract class.

• An interface does not contain any constructors.

• All of the methods in an interface are abstract.

• An interface can extend multiple interfaces

public interface Hockey extends Sports, Event

Page 15: Java  For beginners and CSIT and IT students

Interfacesinterface Bicycle {

void changeCadence(int newValue);

void changeGear(int newValue);

void speedUp(int increment);

void applyBrakes(int decrement);

}

Page 16: Java  For beginners and CSIT and IT students

Interfacesclass ACMEBicycle implements 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);

}}

Page 17: Java  For beginners and CSIT and IT students

Access Modifiers• Access level modifiers determine whether

other classes can use a particular field or invoke a particular method.

Page 18: Java  For beginners and CSIT and IT students

Arrays• An array is a data structure that stores a collection of values

of the same type.• Declaration:

int[] a;String[] str ;

• Initialization:a = new int[100];str = new String[2];

• Assigning value:for (int i = 0; i < 100; i++){

a[i] = i; // fills the array with numbers 0 to 99}

str[0] = “One”;str[1] = “Two”;

Page 19: Java  For beginners and CSIT and IT students

Packages• 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.

Example:

package animals;

interface Animal {

public void eat();

public void travel();

}

http://www.tutorialspoint.com/java/java_packages.htm

Page 20: Java  For beginners and CSIT and IT students

Packagespackage animals; public class MammalInt implements Animal{

public void eat(){ System.out.println("Mammal eats");

} public void travel(){

System.out.println("Mammal travels"); } public int noOfLegs(){ return 0; } public static void main(String args[]){

MammalInt m = new MammalInt();m.eat();m.travel();

}}

Page 21: Java  For beginners and CSIT and IT students

PackagesThe Directory Structure of Packages:

• The name of the package becomes a part of the name of the class.

• The name of the package must match the directory structure where the corresponding bytecode resides.package vehicle; public class Car { // Class implementation. }location of file: ....\vehicle\Car.javaNow, the qualified class name and pathname:

• Class name -> vehicle.Car• Path name -> vehicle\Car.java (in windows)

Page 22: Java  For beginners and CSIT and IT students

PackagesImporting Package:

• Syntax : import java.util.*;package payroll; public class Boss {

public void payEmployee(Employee e) {e.mailCheck();

}}Note: we assumed that Employee class is in payroll package, if it is in package called employee, then either we use import employee.Employee; before Boss class or directly access it as employee.Employee in payEmployee method.

Page 23: Java  For beginners and CSIT and IT students

Inheritance• Inheritance is a mechanism where a new class is derived

from an existing class.• Inheritance can be defined as the process where one

object acquires the properties of another.IS-A Relationship:

• IS-A is a way of saying : This object is a type of that object.public class Animal{ } public class Mammal extends Animal{ } public class Reptile extends Animal{ } public class Dog extends Mammal{ }Now, if we consider the IS-A relationship, we can say:

• Mammal IS-A Animal• Reptile IS-A Animal

instanceof

Page 24: Java  For beginners and CSIT and IT students

Inheritance

HAS-A relationship:

• This determines whether a certain class HAS-A certain thing.

public class Vehicle{}

public class Speed{}

public class Van extends Vehicle{

private Speed sp;

}

This shows that class Van HAS-A Speed.

Page 25: Java  For beginners and CSIT and IT students

InheritanceUsing the Keyword superpublic class Superclass {

public void printMethod() { System.out.println("Printed in Superclass.");

} }public class Subclass extends Superclass {

// overrides printMethod in Superclasspublic void printMethod() {

super.printMethod(); System.out.println("Printed in Subclass");

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

Subclass s = new Subclass(); s.printMethod();

}}

Try with constructor

Page 26: Java  For beginners and CSIT and IT students

1.3 Exception Handling and Threading

Exception Handling

• An exception is a problem that arises during the execution of a program.

Checked exceptions:

• A checked exception is an exception that is typically a user error or a problem that cannot be foreseen by the programmer.

• For example, if a file is to be opened, but the file cannot be found, an exception occurs.

• These exceptions cannot simply be ignored at the time of compilation.

Page 27: Java  For beginners and CSIT and IT students

Exception Handling

Runtime exceptions:

• A runtime exception is an exception that occurs that probably could have been avoided by the programmer.

• As opposed to checked exceptions, runtime exceptions are ignored at the time of compilation.

• Example: Divide by zero, null value manipulation ..

Page 28: Java  For beginners and CSIT and IT students

Exception HandlingCatching Exceptions:

• A method catches an exception using a combination of the try and catchkeywords.

• A try/catch block is placed around the code that might generate an exceptionimport java.io.*; public class ExcepTest{

public static void main(String args[]){try{

int a[] = new int[2]; System.out.println("Access element three :" + a[3]);

}catch(ArrayIndexOutOfBoundsException e){ System.out.println("Exception thrown :" + e);

} finally{System.out.println(“Finally Block");

}}

}

Page 29: Java  For beginners and CSIT and IT students

Exception Handling

Note the following:

• A catch clause cannot exist without a try statement.

• It is not compulsory to have finally clauses when ever a try/catch block is present.

• The try block cannot be present without either catch clause or finally clause.

• Any code cannot be present in between the try, catch, finally blocks.

Page 30: Java  For beginners and CSIT and IT students

Exception Handling

The throws/throw Keywords:

• If a method does not handle a checked exception, the method must declare it using the throws keyword.

• The throws keyword appears at the end of a method's signature.

Page 31: Java  For beginners and CSIT and IT students

Creating Multithreaded Programs

Thread

• A thread is a thread of execution in a program.

• The Java Virtual Machine allows an application to have multiple threads of execution running concurrently.

• Threads are independent.

• Every thread has a priority.

• Threads with higher priority are executed in preference to threads with lower priority.

Page 32: Java  For beginners and CSIT and IT students

Creating Multithreaded ProgramsMultithreading

• Multithreading in java is a process of executing multiple threads simultaneously.

Creating Multithreaded Program using Runnable Interface

Creating Multithreaded Program Extending Thread Class

Page 33: Java  For beginners and CSIT and IT students

Creating Multithreaded ProgramsThread Life Cycle

Page 34: Java  For beginners and CSIT and IT students

Creating Multithreaded ProgramsThread Life Cycle

1) NewThe thread is in new state if you create an instance of Thread class but before the invocation of start() method. 2) RunnableThe thread is in runnable state after invocation of start() method, but the thread scheduler has not selected it to be the running thread. 3) RunningThe thread is in running state if the thread scheduler has selected it. 4) Non-Runnable (Blocked)This is the state when the thread is still alive, but is currently not eligible to run. 5) TerminatedA thread is in terminated or dead state when its run() method exits.

Page 35: Java  For beginners and CSIT and IT students

Creating Multithreaded Programs• isAlive()

• join()

Page 36: Java  For beginners and CSIT and IT students

1.4 File IO:

• File:

• java.io.File

• An abstract representation of file and directory pathnames.

Page 37: Java  For beginners and CSIT and IT students

File IO• Directories:

• java.io.File

• A directory is a File which can contains a list of other files and directories. You use File object to create directories, to list down files available in a directory. String dirname = "/tmp/user/java/bin";

File d = new File(dirname);

// Create directory now.

d.mkdirs();

Page 38: Java  For beginners and CSIT and IT students

I/O Stream Classes

• FileInputStream A FileInputStream obtains input bytes from a file in a file system.

• FileOutputStream A file output stream is an output stream for writing data to a File or to a FileDescriptor.

• FileReader Convenience class for reading character files.

• FileWriter Convenience class for writing character files.

• InputStreamReader …

Page 39: Java  For beginners and CSIT and IT students

Byte Streams• Java byte streams are used to perform input and

output of 8-bit bytes.

• All byte stream classes are descended from InputStream and OutputStream

• Though there are many classes related to byte streams but the most frequently used classes are , FileInputStream and FileOutputStream.

• Following is an example which makes use of these two classes to copy an input file into an output file:

Page 40: Java  For beginners and CSIT and IT students

Byte Streamsimport java.io.*;

public class CopyFile {

public static void main(String args[]) throws IOException {

FileInputStream in = null;

FileOutputStream out = null;

try {

in = new FileInputStream("input.txt");

out = new FileOutputStream("output.txt");

int c;

while ((c = in.read()) != -1) {

out.write(c);

}

}finally {

if (in != null) {

in.close();

}

if (out != null) {

out.close();

}

}

}

}

Page 41: Java  For beginners and CSIT and IT students

Character Streams• Java Character streams are used to perform input

and output for 16-bit unicode.

• FileReader and FileWriter.

• Reads / Writes two bytes at a time.

• Input and output done with stream classes automatically translates to and from the local character set (internationalization ). So, more convenient than Byte Streams.

Page 42: Java  For beginners and CSIT and IT students

Character Streamsimport java.io.*;

public class CopyFile {

public static void main(String args[]) throws IOException {

FileReader in = null;

FileWriter out = null;

try {

in = new FileReader("input.txt");

out = new FileWriter("output.txt");

int c;

while ((c = in.read()) != -1) {

out.write(c);

}

}finally {

if (in != null) {

in.close();

}

if (out != null) {

out.close();

}

}

}

}

Page 43: Java  For beginners and CSIT and IT students

Reading Fileimport java.io.*;

public class ReadFileExample {

public static void main(String[] args) {

File file = new File("D:/robots.txt");

FileInputStream fis = null;

try {

fis = new FileInputStream(file);

System.out.println("Total file size to read (in bytes) : "

+ fis.available());

int content;

while ((content = fis.read()) != -1) {

// convert to char and display it

System.out.print((char) content);

}

} catch (IOException e) {

e.printStackTrace();

} finally {

try {

if (fis != null)

fis.close();

} catch (IOException ex) {

ex.printStackTrace();

}

}

}

}

Page 44: Java  For beginners and CSIT and IT students

Writing to Fileimport java.io..*;

public class WriteFileExample {

public static void main(String[] args) {

FileOutputStream fop = null;

File file;

String content = "This is the text content";

try {

file = new File("d:/newfile.txt");

fop = new FileOutputStream(file);

// if file doesnt exists, then create it

if (!file.exists()) {

file.createNewFile();

}

// get the content in bytes

byte[] contentInBytes = content.getBytes();

fop.write(contentInBytes);

fop.flush();

fop.close();

System.out.println("Done");

} catch (IOException e) {

e.printStackTrace();

} finally {

try {

if (fop != null) {

fop.close();

}

} catch (IOException e) {

e.printStackTrace();

Page 45: Java  For beginners and CSIT and IT students

File Input Streamread() method

• Reads a byte of data from this input stream (InputStream class). This method blocks if no input is yet available.

• The methods returns the next byte of data, or -1 if the end of the file is reached.

Page 46: Java  For beginners and CSIT and IT students

RandomAccessFile• The Java.io.RandomAccessFile class file behaves like a large array

of bytes stored in the file system.

• Instances of this class support both reading and writing to a random access file.

• RandomAccessFile(File file, String mode)

Page 47: Java  For beginners and CSIT and IT students

RandomAccessFile

Page 48: Java  For beginners and CSIT and IT students

File IO

Page 49: Java  For beginners and CSIT and IT students

Introduction to Java NIO• Non-blocking I/O (usually called NIO, and sometimes called

"New I/O") is a collection of Java programming language APIs that offer features for intensive I/O operations. Beginning with version 1.4

• It supports a buffer-oriented, channel-based approach to I/O operations.

• Package java.nio

• NIO subsystem does not replace the stream-based I/O classes found in java.io.

NIO buffers

• NIO data transfer is based on buffers (java.nio.Buffer and related classes). These classes represent a contiguous extent of memory, together with a small number of data transfer operations.

Page 50: Java  For beginners and CSIT and IT students

Unit 2:User Interface Components with Swing

Page 51: Java  For beginners and CSIT and IT students

2.1 Swing and MVC Design PatternsSwing

• Swing is a GUI widget toolkit for Java.

• It is part of Oracle's Java Foundation Classes (JFC) — an API for providing a graphical user interface (GUI) for Java programs.

• FC consists of the Abstract Window Toolkit (AWT), Swing and Java 2D.

• Swing is currently in the process of being replaced by JavaFX.

Page 52: Java  For beginners and CSIT and IT students

Design Patterns• A design pattern in architecture and computer

science is a formal way of documenting a solution to a design problem in a particular field of expertise.

• The idea was introduced by the architect Christopher Alexander in the field of architecture and has been adapted for various other disciplines, including computer science.

• MVC Pattern

• Singleton Pattern

• Factory Pattern

http://www.tutorialspoint.com/design_pattern/

Page 53: Java  For beginners and CSIT and IT students

MVC Pattern• MVC Pattern is a software architectural

pattern for implementing user interfaces.

• It divides a given software application into three interconnected parts, i.e. Model, View and Controller.

• The Model, which stores the content

• The View, which displays the content

• The Controller, which handles user input

Page 54: Java  For beginners and CSIT and IT students

MVC Pattern

Page 55: Java  For beginners and CSIT and IT students

MVC Analysis of Swing Buttons

• Swing Buttons use MVC Pattern internally

• DefaultButtonModel implements ButtonModelwhich can define the state of the various kinds of buttons. Model provides information like whether the button is Enabled, is Pressed …

JButton button = new JButton("Blue");ButtonModel model = button.getModel();

model.isEnabled();

• The JButton uses a class called BasicButtonUIfor the view and a class called ButtonUIListeneras controller.

Page 56: Java  For beginners and CSIT and IT students

Swing Container Hierarchy

Page 57: Java  For beginners and CSIT and IT students

2.2 Layout ManagementLayout Manager

• A layout manager is an object that implements the LayoutManager interface and determines the size and position of the components within a container.

Setting the Layout Manager

Using the JPanel constructor. For example:JPanel panel = new JPanel(new BorderLayout());

Using setLayout method. For example:

Container contentPane = frame.getContentPane(); contentPane.setLayout(new FlowLayout());

Page 58: Java  For beginners and CSIT and IT students

Layout ManagementBorder Layout

• A BorderLayout places components in up to five areas: top, bottom, left, right, and center.

• All extra space is placed in the center area.

BorderLayout(int horizontalGap, int verticalGap)

Page 59: Java  For beginners and CSIT and IT students

Layout ManagementGrid Layout

• GridLayout simply makes a bunch of components equal in size and displays them in the requested number of rows and columns.

GridLayout(int rows, int cols)

GridLayout(int rows, int cols, int hgap, int vgap)

Page 60: Java  For beginners and CSIT and IT students

Layout ManagementGridbag Layout

• GridBagLayout is a sophisticated, flexible layout manager.

• It aligns components by placing them within a grid of cells, allowing components to span more than one cell.

• The rows in the grid can have different heights, and grid columns can have different widths.

Page 61: Java  For beginners and CSIT and IT students

Layout ManagementGroup Layout

• GroupLayout works with the horizontal and vertical layouts separately.

• The layout is defined for each dimension independently.

• Consequently, however, each component needs to be defined twice in the layout.

http://docs.oracle.com/javase/tutorial/uiswing/layout/groupExample.html

Page 62: Java  For beginners and CSIT and IT students

Layout ManagementUsing No Layout Manager

• There will be times when you don’t want to bother with layout managers but just want to drop a component at a fixed location (sometimes called absolute positioning).

• 1. Set the layout manager to null.

• 2. Add the component you want to the container.

• 3. Specify the position and size that you want:

frame.setLayout(null);JButton ok = new JButton("OK");frame.add(ok);ok.setBounds(10, 10, 30, 15);

void setBounds(int x, int y, int width, int height)

moves and resizes a component.

Page 63: Java  For beginners and CSIT and IT students

Layout ManagementCustom layout Managers

• Every layout manager must implement at least the following five methods, which are required by the LayoutManager interface:

1. void addLayoutComponent(String s, Component c);

2. void removeLayoutComponent(Component c);

3. Dimension preferredLayoutSize(Container parent);

4. Dimension minimumLayoutSize(Container parent);

5. void layoutContainer(Container parent);

Page 64: Java  For beginners and CSIT and IT students

Layout Management• void addLayoutComponent(String, Component) Called by the Container

class's add methods. Layout managers that do not associate strings with their components generally do nothing in this method.

• void removeLayoutComponent(Component) Called by the Container methods remove and removeAll. Layout managers override this method to clear an internal state they may have associated with the Component.

• Dimension preferredLayoutSize(Container) Called by the Container class's getPreferredSize method, which is itself called under a variety of circumstances. This method should calculate and return the ideal size of the container, assuming that the components it contains will be at or above their preferred sizes. This method must take into account the container's internal borders, which are returned by the getInsets method.

• Dimension minimumLayoutSize(Container) Called by the Container getMinimumSize method, which is itself called under a variety of circumstances. This method should calculate and return the minimum size of the container, assuming that the components it contains will be at or above their minimum sizes. This method must take into account the container's internal borders, which are returned by the getInsets method.

• void layoutContainer(Container) Called to position and size each of the components in the container. A layout manager's layoutContainer method does not actually draw components. It simply invokes one or more of each component's setSize, setLocation, and setBounds methods to set the component's size and position.

Page 65: Java  For beginners and CSIT and IT students

Layout Management

http://docs.oracle.com/javase/tutorial/uiswing/layout/custom.html

Page 66: Java  For beginners and CSIT and IT students

2.3 Text Input

Page 67: Java  For beginners and CSIT and IT students

2.4 Choice Components:

Page 68: Java  For beginners and CSIT and IT students

2.5 Menus:A menu bar at the top of a window contains the names of the pull-down menus. Clicking on a name opens the menu containing menu items and submenus.

Page 69: Java  For beginners and CSIT and IT students

2.5 Menus:Keyboard MnemonicsJMenuItem aboutItem = new JMenuItem("About", 'A');

JMenu helpMenu = new JMenu("Help");helpMenu.setMnemonic('H');

Accelerators

• Use the setAccelerator method to attach an accelerator key to a menu item.

• The setAccelerator method takes an object of type Keystroke.

• openItem.setAccelerator(KeyStroke.getKeyStroke("ctrl O"));

Page 70: Java  For beginners and CSIT and IT students

2.5 Menus:Enabling and Disabling Menu Items

• To enable or disable a menu item, use the setEnabledmethod:

saveItem.setEnabled(false);

Page 71: Java  For beginners and CSIT and IT students

2.5 Menus:Toolbars

• A toolbar is a button bar that gives quick access to the most commonly used commands in a program.

• What makes toolbars special is that you can move them elsewhere.

JToolBar bar = new JToolBar();bar.add(blueButton);

Tooltips

• Tooltip is a info label displayed over a button when mouse hover’s in it.

blueButton.setToolTipText("Blue Button");

Page 72: Java  For beginners and CSIT and IT students

2.6 Dialog Boxes:Modal dialog box

• A modal dialog box won’t let users interact with the remaining windows of the application until he or she deals with it. Eg. a file dialog box

Modeless dialog box

• A modeless dialog box lets the user enter information in both the dialog box and the remainder of the application. Eg. a toolbar.

Page 73: Java  For beginners and CSIT and IT students

2.6 Dialog Boxes:Option Dialogs

• The JOptionPane has four static methods to show dialogs:

JOptionPane.showMessageDialog(null, "alert", "alert", JOptionPane.ERROR_MESSAGE);

http://docs.oracle.com/javase/7/docs/api/javax/swing/JOptionPane.html

Page 74: Java  For beginners and CSIT and IT students

2.6 Dialog Boxes:Creating Dialogs

1. In your new dialogbox class extend JDialog class

2. In the constructor of your dialog box, call the constructor of the superclass JDialog.

3. Add the user interface components of the dialog box.

4. Add the event handlers.

5. Set the size for the dialog box.

• When you call the superclass constructor, you will need to supply the owner frame, the title of the dialog, and the modality.

• The owner frame controls where the dialog is displayed.

• The modality specifies which other windows of your application are blocked while the dialog is displayed

Page 75: Java  For beginners and CSIT and IT students

2.6 Dialog Boxes:

• Creating Dialog Example

Page 76: Java  For beginners and CSIT and IT students

2.6 Dialog Boxes:

• Data Exchange Example

Page 77: Java  For beginners and CSIT and IT students

2.6 Dialog Boxes:File Choosers

• Swing provides a JFileChooser class that allows you to display a file dialog box.

• showOpenDialog to display a dialog for opening a file

• showSaveDialog to display a dialog for saving a file

• The button for accepting a file is then automatically labeled Open or Save.

• You can also supply your own button label with the showDialog method.

Page 78: Java  For beginners and CSIT and IT students

2.6 Dialog Boxes:File Choosers Steps

1. Make a JFileChooser object. For example:JFileChooser chooser = new JFileChooser();

2. Set the directory by calling the setCurrentDirectorymethod.For example, to use the current working directorychooser.setCurrentDirectory(new File("."));

3. If you have a default file name that you expect the user to choose:chooser.setSelectedFile(new File(filename));

4. Show the dialog box by calling :int result = chooser.showOpenDialog(parent);int result = chooser.showSaveDialog(parent);You can also call the showDialog method and pass an explicit text for the approve button:int result = chooser.showDialog(parent, "Select");

Page 79: Java  For beginners and CSIT and IT students

2.6 Dialog Boxes:File Choosers Example:

Page 80: Java  For beginners and CSIT and IT students

2.6 Dialog Boxes:Color Choosers:

• Except JFileChooser class, Swing provides only one additional chooser, the JColorChooser.

• Use it to let users pick a color value.

Color selectedColor = JColorChooser.showDialog(parent, title, initialColor);

Page 81: Java  For beginners and CSIT and IT students

Java Architecture

Page 82: Java  For beginners and CSIT and IT students

Local Applets

<applet

codebase="tictactoe"

code="TicTacToe.class"

width=120

height=120>

</applet>

Page 83: Java  For beginners and CSIT and IT students

Remote Applets

• A remote applet is one that is located on another computer system.

• This computer system may be located in the building next door or it may be on the other side of the world-it makes no difference to your Java-compatible browser.

• No matter where the remote applet is located, it's downloaded onto your computer via the Internet. Your browser must, of course, be connected to the Internet at the time it needs to display the remote applet.

Page 84: Java  For beginners and CSIT and IT students

Remote Applets

<applet codebase="http://www.myconnect.com/applets/"

code="TicTacToe.class"

width=120

height=120>

</applet>

In the first case, codebase specifies a local folder, and in the second case, it specifies the URL at which the applet is located.

Page 85: Java  For beginners and CSIT and IT students

Life Cycle of an Applet

Page 86: Java  For beginners and CSIT and IT students

Life Cycle of an Applet

• init: This method is intended for whatever initialization is needed for your applet. It is called after the param tags inside the applet tag have been processed.

• start: This method is automatically called after the browser calls the init method. It is also called whenever the user returns to the page containing the applet after having gone off to other pages.

Page 87: Java  For beginners and CSIT and IT students

Life Cycle of an Applet

• stop: This method is automatically called when the user moves off the page on which the applet sits. It can, therefore, be called repeatedly in the same applet.

• destroy: This method is only called when the browser shuts down normally. Because applets are meant to live on an HTML page, you should not normally leave resources behind after a user leaves the page that contains the applet.

Page 88: Java  For beginners and CSIT and IT students

Life Cycle of an Applet

• paint: Invoked immediately after the start() method, and also any time the applet needs to repaint itself in the browser. The paint() method is actually inherited from the java.awt.

Page 89: Java  For beginners and CSIT and IT students

Distributed Application using RMI

Page 90: Java  For beginners and CSIT and IT students

Distributed Application• A distributed application is software that is executed or run on

multiple computers within a network.

• These applications interact in order to achieve a specific goal or task.

• Traditional applications relied on a single system to run them. Even in the client-server model, the application software had to run on either the client, or the server that the client was accessing. However, distributed applications run on both simultaneously.

• The very nature of an application may require the use of a communication network that connects several computers: for example, data produced in one physical location and required in another location.

Page 91: Java  For beginners and CSIT and IT students

Distributed Application• There are many cases in which the use of a single computer would

be possible in principle, but the use of a distributed system is beneficial for practical reasons. For example, it may be more cost-efficient to obtain the desired level of performance by using a cluster of several low-end computers, in comparison with a single high-end computer.

Page 92: Java  For beginners and CSIT and IT students

Remote Method Invocation (RMI)• Remote Method Invocation (RMI) allows a Java object

that executes on one machine to invoke a method of a Java object that executes on another machine.

• This is an important feature, because it allows you to build distributed applications.

Page 93: Java  For beginners and CSIT and IT students

RMI LayersStub and Skeleton Layer

• The stub and skeleton layer is responsible for marshaling and unmarshaling the data and transmitting and receiving them to/from the Remote Reference Layer

Remote Reference Layer

• The Remote reference layer is responsible for carrying out the invocation.

Transport Layer

• The Transport layer is responsible for setting up connections, managing requests, monitoring them and listening for incoming calls

Page 94: Java  For beginners and CSIT and IT students

RMI Mechanism• Locate remote objects. Applications can use various mechanisms to

obtain references to remote objects. For example, an application can register its remote objects with RMI's simple naming facility, the RMI registry.

• Communicate with remote objects. Details of communication between remote objects are handled by RMI.

• Load class definitions for objects that are passed around. Because RMI enables objects to be passed back and forth, it provides mechanisms for loading an object's class definitions as well as for transmitting an object's data.

Page 95: Java  For beginners and CSIT and IT students

RMI Registry• Essentially the RMI registry is a place for the server to register

services it offers and a place for clients to query for those services.

• RMI Registry acts a broker between RMI servers and the clients.

A Simple Client/Server Application Using RMI

• This section provides step-by-step directions for building a simple client/server application by using RMI. The server receives a request from a client, processes it, and returns a result.

Page 96: Java  For beginners and CSIT and IT students

Java Network Programming

Page 97: Java  For beginners and CSIT and IT students

Java Network ProgrammingIntroduction to Network Programming

• The term network programming refers to writing programs that execute across multiple devices (computers), in which the devices are all connected to each other using a network.

• The java.net package of the J2SE APIs contains a collection of classes and interfaces that provide the low-level communication details, allowing you to write programs that focus on solving the problem at hand.

Page 98: Java  For beginners and CSIT and IT students

Java Network ProgrammingTCP:

TCP stands for Transmission Control Protocol, which allows for reliable communication between two applications. TCP is typically used over the Internet Protocol, which is referred to as TCP/IP.

UDP:

UDP stands for User Datagram Protocol, a connection-less protocol that allows for packets of data to be transmitted between applications.

• The speed for TCP is slower than UDP. UDP is faster because there is no error-checking for packets.

• In TCP, there is absolute guarantee that the data transferred remains intact and arrives in the same order in which it was sent. In UDP, there is no guarantee that the messages or packets sent would reach at all.

Page 99: Java  For beginners and CSIT and IT students

Java Network ProgrammingIP Address : (Ex: 192.168.1.1)

An Internet Protocol address (IP address) is a numerical label assigned to each device (e.g., computer, printer) participating in a computer network that uses the Internet Protocol for communication.

Port Number:

In TCP/IP and UDP networks, an endpoint to a logical connection. The port number identifies what type of port it is. For example, port 80 is used for HTTP traffic.

Page 100: Java  For beginners and CSIT and IT students

Java Network ProgrammingSocket:

A socket is one endpoint of a two-way communication link between two programs running on the network. A socket is bound to a port number so that the TCP layer can identify the application that data is destined to be sent to.

• An endpoint is a combination of an IP address and a port number. Every TCP connection can be uniquely identified by its two endpoints. That way you can have multiple connections between your host and the serve

Page 101: Java  For beginners and CSIT and IT students

Java Network ProgrammingURL

It is an acronym for Uniform Resource Locator and is a reference (an address) to a resource on the Internet. A URL has two main components: Protocol identifier: For the URL http://example.com , the protocol identifier is http . Resource name: For the URLhttp://example.com , the resource name is example.com .

java.net.URL

Class URL represents a Uniform Resource Locator, a pointer to a "resource" on the World Wide Web. A resource can be something as simple as a file or a directory, or it can be a reference to a more complicated object, such as a query to a database or to a search engine.

Page 102: Java  For beginners and CSIT and IT students

Java Network Programmingjava.net.URLConnection

The abstract class URLConnection is the superclass of all classes (HttpURLConncetion…) that represent a communications link between the application and a URL. Instances of this class can be used both to read from and to write to the resource referenced by the URL. In general, creating a connection to a URL is a multistep process using openConnection() and connect()

• The connection object is created by invoking the openConnectionmethod on a URL.

• The setup parameters and general request properties are manipulated.

• The actual connection to the remote object is made, using the connect method.

• The remote object becomes available. The header fields and the contents of the remote object can be accessed.

Page 103: Java  For beginners and CSIT and IT students

Java Network ProgrammingURL & URLConnection Example

Page 104: Java  For beginners and CSIT and IT students

Java Network Programming

• Creating a client/server application using TCP Sockets

• Creating a client/server application using UDP Datagram

Page 105: Java  For beginners and CSIT and IT students

Java Database Programming

Page 106: Java  For beginners and CSIT and IT students

Java Database ProgrammingRelational Database Overview

• A database is a means of storing information in such a way that information can be retrieved from it.

• In simplest terms, a relational database is one that presents information in tables with rows and columns.

• A table is referred to as a relation in the sense that it is a collection of objects of the same type (rows).

• Data in a table can be related according to common keys or concepts, and the ability to retrieve related data from a table is the basis for the term relational database. A Database Management System (DBMS) handles the way data is stored, maintained, and retrieved.

• In the case of a relational database, a Relational Database Management System (RDBMS) performs these tasks.

Page 107: Java  For beginners and CSIT and IT students

Java Database ProgrammingJDBC API

• JDBC API is a Java API that can access any kind of tabular data, especially data stored in a Relational Database. JDBC works with Java on a variety of platforms, such as Windows, Mac OS, and the various versions of UNIX.

• java.sql package

Page 108: Java  For beginners and CSIT and IT students

Java Database ProgrammingDriver Manager and JDBC Drivers

• JDBC drivers implement the defined interfaces in the JDBC API for interacting with your database server.

• An individual database system is accessed via a specific JDBC driver that implements the java.sql.Driver interface.

• Drivers exist for nearly all popular RDBMS systems, though few are available for free.

• Sun bundles a free JDBC-ODBC bridge driver with the JDK to allow access to standard ODBC data sources, such as a Microsoft Access database.

• An easy way to load the driver class is to use the Class.forName() method:

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

Page 109: Java  For beginners and CSIT and IT students

Java Database ProgrammingDriver Manager and JDBC Drivers

• When the driver is loaded into memory, it registers itself with the java.sql.DriverManager class as an available database driver.

• The next step is to ask the DriverManager class to open a connection to a given database, where the database is specified by a specially formatted URL. The method used to open the connection is DriverManager.getConnection() . It returns a class that implements the java.sql.Connection interface:

Connection con = DriverManager.getConnection("jdbc:odbc:somedb", "user", "passwd");

Page 110: Java  For beginners and CSIT and IT students

Java Database ProgrammingJDBC Driver Types

• JDBC driver implementations vary because of the wide variety of operating systems and hardware platforms in which Java operates.

• Sun has divided the implementation types into four categories, Types 1, 2, 3, and 4, which is explained below:

• Type 1: JDBC-ODBC Bridge Driver:

• Type 2: JDBC-Native API:

• Type 3: JDBC-Net pure Java:

• Type 4: 100% pure Java:

Reference

http://www.tutorialspoint.com/jdbc/jdbc-driver-types.htm

Page 111: Java  For beginners and CSIT and IT students

Java Database ProgrammingIntroduction to ODBC

• ODBC (Open Database Connectivity) is a standard programming language middleware API for accessing database management systems (DBMS).

• The designers of ODBC aimed to make it independent of database systems and operating systems. An application written using ODBC can be ported to other platforms, both on the client and server side, with few changes to the data access code.

• ODBC was originally developed by Microsoft during the early 1990s.

Page 112: Java  For beginners and CSIT and IT students

Java Database ProgrammingConnecting Database using JDBC ODBC Driver

Page 113: Java  For beginners and CSIT and IT students

Web Programming Using Java Servlet APIs

Page 114: Java  For beginners and CSIT and IT students

Web Programming Using Java Servlet APIsIntroduction to CGI

• Common Gateway Interface (CGI) are programs run by the web server (at "server side").

• CGI is a standard method used to generate dynamic content on Web pages and Web applications. CGI, when implemented on a Web server, provides an interface between the Web server and programs that generate the Web content.

Page 115: Java  For beginners and CSIT and IT students

Web Programming Using Java Servlet APIsIntroduction to Web Server

• A Web Server is a computer system that processes requests via HTTP.

• The term can refer either to the entire system, or specifically to the software that accepts and supervises the HTTP requests.

• The most common use of web servers is to host websites, but there are other uses such as gaming, data storage, running enterprise applications, handling email, FTP, or other web uses.

Page 116: Java  For beginners and CSIT and IT students

Web Programming Using Java Servlet APIsServlet Defination

• A Servlet is a small Java program that runs within a Web server.

• Servlets receive and respond to requests from Web clients, usually across HTTP, the HyperText Transfer Protocol.

• To implement this interface, you can write a generic servlet that extends javax.servlet.GenericServlet or an HTTP servlet that extends javax.servlet.http.HttpServlet.

Page 117: Java  For beginners and CSIT and IT students

Web Programming Using Java Servlet APIsHTTP request response model of Servlet

Page 118: Java  For beginners and CSIT and IT students

Web Programming Using Java Servlet APIsAdvantages of Servlet over CGI

• Better performance: because it creates a thread for each request not process.

• Portability: because it uses java language.

• Robust: Servlets are managed by JVM so no need to worry about momory leak, garbage collection etc.

• Secure: because it uses java language.

Reference

http://www.dineshonjava.com/2013/12/advantages-of-servlets-over-cgi.html#.VMTkxixsvm4

Page 119: Java  For beginners and CSIT and IT students

Web Programming Using Java Servlet APIsServlet Life Cycle Methods

The init() method :

• The init method is designed to be called only once. It is called when the servlet is first created, and not called again for each user request.

public void init() throws ServletException { // Initialization code... }

The service() method :

• The servlet container (i.e. web server) calls the service() method to handle requests coming from the client( browsers) and to write the formatted response back to the client.

• The service () method is called by the container and service method invokes doGet, doPost, doPut, doDelete, etc. methods as appropriate.

public void service(ServletRequest request, ServletResponseresponse) throws ServletException, IOException{ }

Page 120: Java  For beginners and CSIT and IT students

Web Programming Using Java Servlet APIsServlet Life Cycle Methods

The doGet() Method

• A GET request results from a normal request for a URL or from an HTML form that has no METHOD specified and it should be handled by doGet() method.

public void doGet(HttpServletRequest request, HttpServletResponseresponse) throws ServletException, IOException { // Servlet code }

• The doPost() Method

• A POST request results from an HTML form that specifically lists POST as the METHOD and it should be handled by doPost() method.

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Servlet code }

Page 121: Java  For beginners and CSIT and IT students

Web Programming Using Java Servlet APIsServlet Life Cycle Methods

The destroy() method :

• The destroy() method is called only once at the end of the life cycle of a servlet.

public void destroy() { // Finalization code... }

Page 122: Java  For beginners and CSIT and IT students

Web Programming Using Java Servlet APIsServlet API

javax.servlet

• The javax.servlet package contains a number of classes and interfaces that describe and define the contracts between a servletclass and the runtime environment provided for an instance of such a class by a conforming servlet container.

• RequestDispatcher : Defines an object that receives requests from the client and sends them to any resource (such as a servlet, HTML file, or JSP file) on the server.

• Servlet: Defines methods that all servlets must implement.

• ServletConfig : A servlet configuration object used by a servletcontainer to pass information to a servlet during initialization. ServletContext : Defines a set of methods that a servlet uses to communicate with its servlet container, for example, to get the MIME type of a file, dispatch requests, or write to a log file. …

Page 123: Java  For beginners and CSIT and IT students

Web Programming Using Java Servlet APIsCreating Java Servlet

Compile

servlet-api.jar should be included while doing compile

javac -cp .;F:\apache-tomcat-7.0.23\lib\servlet-api.jar HelloWorld.java

A HelloWolrld.class will be created if compile is success.

Deploy

• Copy HelloWorld.class into <Tomcat-installation-directory>/webapps/ROOT/WEB-INF/classes

Page 124: Java  For beginners and CSIT and IT students

Web Programming Using Java Servlet APIs• Create following entries in web.xml file located in <Tomcat-

installation-directory>/webapps/ROOT/WEB-INF/

<servlet>

<servlet-name>HelloWorld</servlet-name>

<servlet-class>HelloWorld</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>HelloWorld</servlet-name>

<url-pattern>/HelloWorld</url-pattern>

</servlet-mapping>

• Above entries to be created inside <web-app>...</web-app> of web.xml

• Now start Tomcat (startup.bat in bin folder of Tomcat installation)and hit http://localhost:8080/HelloWorld in browser.

Page 125: Java  For beginners and CSIT and IT students

Web Programming Using Java Servlet APIsSession

• A period devoted to a particular activity.

• A session is a way to store information (in variables) to be used across multiple pages.

Saving in Session

String username=request.getParameter("txtusername");

HttpSession session = request.getSession(true);

session.setAttribute("username", username);

Getting from Session

String username=(String) session.getAttribute("username");

//session.invalidate()

Page 126: Java  For beginners and CSIT and IT students

Web Programming Using Java Servlet APIsCookie

• A cookie, also known as an HTTP cookie, web cookie, Internet cookie, or browser cookie, is a small piece of data sent from a website (web application) and stored in a user's web browser while the user is browsing that website (web app).

• A cookie, the information is stored on the user’s computer.

Creating Cookie

String username=request.getParameter("txtUsername");

Cookie cookie=new Cookie("username", username); cookie.setMaxAge(60*60*24*30); response.addCookie(cookie);

Page 127: Java  For beginners and CSIT and IT students

Web Programming Using Java Servlet APIsGetting Cookie

Cookie cookies[] = request.getCookies();

Cookie mycookie = null;

if (cookies != null) {

for (int i = 0; i < cookies.length; i++) {

if (cookies[i].getName().equals("username")) {

mycookie = cookies[i];

break;

}

}

}

String userName = mycookie.getValue();

Page 128: Java  For beginners and CSIT and IT students

Introductory Concept of Java Beans

Page 129: Java  For beginners and CSIT and IT students

Introductory Concept of Java BeansJava Beans

• JavaBeans are classes that encapsulate many objects into a single object (the bean).

• They are serializable, have a 0-argument constructor, and allow access to properties using getter and setter methods.

• The name "Bean" was to encompass this standard, which aims to create reusable software components for Java.

• There is no restriction on the capability of a Bean.

• It may perform a simple function, such as obtaining an inventory value, or a complex function, such as forecasting the performance of a stock portfolio.

Page 130: Java  For beginners and CSIT and IT students

Introductory Concept of Java BeansBean Development Kit (BDK)

BDK is (according to allinterview.com):

• Bean Development Kit is a tool that enables to create,configure and connect a set of Beans and it can be used to test Beans without writing a code.

and according to mindprods glossary:

• Bean Development Kit. It is now obsolete. Code-building features of modern IDEs take over much of the function of the BDK.

Bean Builder

Bean Builder is a pure Java application, built over market proven and open standards such as XML, Java Beans, and JFC/Swing.

http://www.cs.wustl.edu/~kjg/cs102/Notes/JavaBeans/

http://www.javaworld.com/article/2077005/client-side-java/the-beanbox--sun-s-javabeans-test-container.html

Page 131: Java  For beginners and CSIT and IT students

Introductory Concept of Java BeansPersistance

• Persistence is the ability to save the current state of a Bean, including the values of a Bean’s properties and instance variables, to nonvolatile storage and to retrieve them at a later time.

Take Reference from below provided ebook

CHAPTER 29 Java Beans

Java: The Complete Reference™ - Herbert Schildt

Page 132: Java  For beginners and CSIT and IT students

Introductory Concept of Java BeansCreating a New Bean

Page 133: Java  For beginners and CSIT and IT students

Questions ???