Java Notes

  • June 2020
  • PDF

This document was uploaded by user and they confirmed that they have the permission to share it. If you are author or own the copyright of this book, please report to us by using this DMCA report form. Report DMCA


Overview

Download & View Java Notes as PDF for free.

More details

  • Words: 24,592
  • Pages: 129
Java Notes *Introduction of java:Java is great programming language for the development of enterprise grade applications. This programming Language is evolved from a language named Oak. Oak was developed in the early nineties at Sun Microsystems as a platform-independent language aimed at allowing entertainment appliances such as video game consoles and VCRs to communicate. Oak was first slated to appear in television set-top boxes designed to provide video-on-demand services. Oak was unsuccessful so in 1995 Sun changed the name to Java and modified the language to take advantage of the growing World Wide Web. Java is an object-oriented language, and this is very similar to C++. Java Programming Language is simplified to eliminate language features that cause common programming errors. Java source code files are compiled into a format called byte code, which can then be executed by a Java interpreter.

*Features of java:•

Platform Independence The Write-Once-Run-Anywhere ideal has not been achieved (tuning for different platforms usually required), but closer than with other languages.



Object Oriented o Object oriented throughout - no coding outside of class definitions, including main(). o An extensive class library available in the core language packages.



Compiler/Interpreter Combo o Code is compiled to bytecodes that are interpreted by a Java virtual machines (JVM) . o This provides portability to any machine for which a virtual machine has been written. o The two steps of compilation and interpretation allow for extensive code checking and improved security.



Robust o Exception handling built-in, strong type checking (that is, all data must be declared an explicit type), local variables must be initialized.



Several dangerous features of C & C++ eliminated: o No memory pointers

o o

No preprocessor Array index limit checking



Automatic Memory Management o Automatic garbage collection - memory management handled by JVM.



Security o No memory pointers o Programs run inside the virtual machine sandbox. o Array index limit checking o Code pathologies reduced by  bytecode verifier - checks classes after loading  class loader - confines objects to unique namespaces. Prevents loading a hacked "java.lang.SecurityManager" class, for example.  security manager - determines what resources a class can access such as reading and writing to the local disk.



Dynamic Binding o The linking of data and methods to where they are located, is done at run-time. o New classes can be loaded while a program is running. Linking is done on the fly. Even if libraries are recompiled, there is no need to recompile code that uses classes in those libraries.





Good Performance o Interpretation of bytecodes slowed performance in early versions, but advanced virtual machines with adaptive and just-in-time compilation and other techniques now typically provide performance up to 50% to 100% the speed of C++ programs.



Threading o Lightweight processes, called threads, can easily be spun off to perform multiprocessing. o Can take advantage of multiprocessors where available o Great for multimedia displays.



Built-in Networking o Java was designed with networking in mind and comes with many classes to develop sophisticated Internet communications.

Features such as eliminating memory pointers and by checking array limits greatly help to remove program bugs. The garbage collector relieves programmers of the big job of memory

management. These and the other features can lead to a big speedup in program development compared to C/C++ programming. JDK is a software development program provided by sun Microsystems. Java Development Kit or JDK comes in various versions and can be downloaded free from the sun Microsystems. JVM compiler, debugger and other tools are used with JDK for developing java based application & java applets. So make sure that your JVM compiler & JDK versions are same. JDK also known as Java 2 Platform That comes in three editions J2ME, J2SE & J2EE. JDK Java Development Kit JVM Java virtual machine

Java SDK Directory Structure The jdk1.5.0 has following directory: Bin directory - The bin directory provides all inessential tools for developing and testing the program through the help of command provided by Java compiler. Demo directory - This directory consists many applications And applets with source code. Include directory - It contains all header files like for 'C' programming language that enables you to combine C code into a Java program. Jre directory- when you run any java program then you have compile it by the help of java interpreter or java Runtime environment(JRE).The SDK uses the internal adaption of JRE, which containing in the jre root directory. Lib directory- this is most important important directory for development tools that contains libraries and it’s supported files. Docs Directory-It is the last directory of software development kit that assistes you to store the java documents. The docs directory is an optional directory Difference between java and c++?

Feature

C

C++

Java

Paradigms

Procedural

Procedural, OOP, Generic

OOP, Generic Programming

Programming

(from Java 5)

Form of Compiled Executable Native Executable Native Code Source Code Code

Java bytecode

Memory management

Manual

Manual

Managed, using a garbage collector

Pointers

Yes, very commonly used.

Yes, very commonly used, No pointers; references are but some form of references used instead. available too.

Preprocessor

Yes

Yes

No

String Type

Character arrays

Character arrays, objects

Objects

Complex Data Types

Structures, unions Structures, unions, classes

Classes

Inheritance

N/A

Multiple class inheritance

Single class inheritance, multiple interface implementation

Operator Overloading

N/A

Yes

No

Automatic coercions

Yes, with warnings Yes, with warnings if loss if loss could occur could occur

Not at all if loss could occur; must cast explicitly

Varied Parameters Yes

Yes

No

Goto Statement

Yes

No

Yes

Data type in java Boolean 1-bit. May take on the values true and false only. true and false are defined constants of the language and are not the same as True and False, TRUE and FALSE, zero and nonzero, 1 and 0 or any other numeric value. Booleans may not be cast into any other type of variable nor may any other variable be cast into a Boolean.

Byte 1 signed byte (two's complement). Covers values from -128 to 127. short 2 bytes, signed (two's complement), -32,768 to 32,767 int 4 bytes, signed (two's complement). -2,147,483,648 to 2,147,483,647. Like all numeric types ints may be cast into other numeric types (byte, short, long, float, double). When lossy casts are done (e.g. int to byte) the conversion is done modulo the length of the smaller type. long 8 bytes signed (two's complement). Ranges from -9,223,372,036,854,775,808 to +9,223,372,036,854,775,807. float 4 bytes, IEEE 754. Covers a range from 1.40129846432481707e-45 to 3.40282346638528860e+38 (positive or negative). Like all numeric types floats may be cast into other numeric types (byte, short, long, int, double). When lossy casts to integer types are done (e.g. float to short) the fractional part is truncated and the conversion is done modulo the length of the smaller type. double 8 bytes IEEE 754. Covers a range from 4.94065645841246544e-324d to 1.79769313486231570e+308d (positive or negative). char 2 bytes, unsigned, Unicode, 0 to 65,535 Variables instance Variables (Non-Static Fields) Technically speaking, objects store their individual states in "non-static fields", that is, fields declared without the static keyword. Non-static fields are also known as instance variables because their values are unique to each instance of a class (to each object, in other words); the currentSpeed of one bicycle is independent from the currentSpeed of another.

Class Variables (Static Fields) a class variable is any field declared with the static modifier; this tells the compiler that there is exactly one copy of this variable in existence; regardless of how many times the class has been instantiated. A field defining the number of gears for a particular kind of bicycle could be marked as static since conceptually the same number of gears will apply to all instances. The code static int numGears = 6; would create such a static field. Additionally, the keyword final could be added to indicate that the number of gears will never change. Local Variables Similar to how an object stores its state in fields, a method will often store its temporary state in local variables. The syntax for declaring a local variable is similar to declaring a field (for example, int count = 0;). There is no special keyword designating a variable as local; that determination comes entirely from the location in which the variable is declared — which is between the opening and closing braces of a method. As such, local variables are only visible to the methods in which they are declared; they are not accessible from the rest of the class. Constants in java Even though Java does not have a constant type, you can achieve the same effect by declaring and initializing variables that are static, public, and final. After the variables have been initialized, their value cannot be changed. You can then access the constant value using the name of the variable joined to the name of its class with a period. class Constants02{ public static void main(String[] args){ System.out.println("pi = " + Constants.pi); System.out.println("e = " + Constants.e); }//end main }//end class Constants02 //=======================================================// class Constants{ public static final double pi = 3.14159; public static final double e = 2.71828; }//end class Constants *Operators: Assignment Arithmetic Relational

Logical Desion Control statement *Classes and object With the knowledge you now have of the basics of the Java programming language, you can learn to write your own classes. In this lesson, you will find information about defining your own classes, including declaring member variables, methods, and constructors. You will learn to use your classes to create objects, and how to use the objects you create. This lesson also covers nesting classes within other classes, enumerations, and annotations. Classes This section shows you the anatomy of a class, and how to declare fields, methods, and constructors. Objects This section covers creating and using objects. You will learn how to instantiate an object, and, once instantiated, how to use the dot operator to access the object's instance variables and methods. More on Classes This section covers more aspects of classes that depend on using object references and the dot operator that you learned about in the preceding section: returning values from methods, the this keyword, class vs. instance members, and access control. Nested Classes Static nested classes, inner classes, anonymous inner classes, and local classes are covered. Constructors When you create a new instance (a new object) of a class using the new keyword, a constructor for that class is called. Constructors are used to initialize the instance variables (fields) of an object. Constructors are similar to methods, but with some important differences. •

Constructor name is class name. A constructors must have the same name as the class its in.



Default constructor. If you don't define a constructor for a class, a default parameter less constructor is automatically created by the compiler. The default constructor calls the default parent constructor (super()) and initializes all instance variables to default value (zero for numeric types, null for object references, and false for Booleans).



Default constructor is created only if there are no constructors. If you define any constructor for your class, no default constructor is automatically created.



Differences between methods and constructors. o

There is no return type given in a constructor signature (header). The value is this object itself so there is no need to indicate a return value.

o

There is no return statement in the body of the constructor.

o

The first line of a constructor must either be a call on another constructor in the same class (using this), or a call on the superclass constructor (using super). If the first line is neither of these, the compiler automatically inserts a call to the parameter less super class constructor.

These differences in syntax between a constructor and method are sometimes hard to see when looking at the source. It would have been better to have had a keyword to clearly mark constructors as some languages do. •

This (...) - Calls another constructor in same class. Often a constructor with few parameters will call a constructor with more parameters, giving default values for the missing parameters. Use this to call other constructors in the same class.



Super (...). Use super to call a constructor in a parent class. Calling the constructor for the super class must be the first statement in the body of a constructor. If you are satisfied with the default constructor in the super class, there is no need to make a call to it because it will be supplied automatically. Garbage collection

Since objects are dynamically allocated by using the new operator, you might be wondering how such objects are destroyed and their memory released for later reallocation. In some languages, such as C++, dynamically allocated objects must be manually released by use of a delete operator.

Java takes a different approach; it handles deallocation for you automatically. The technique that accomplishes this is called garbage collection. It works like this: when no references to an object to an object exist, that object is assumed to be no longer needed, and the memory occupied by the object can be reclaimed. There is no explicit need to destroy objects as in C++. Garbage collection only occurs sporadically (if at all) during the execution of your program. It will not occur simply because one or more objects exist that are no longer used. Furthermore, different java run-time implementations will take varying approaches to garbage collection, but for the most part, you should not have to think about it while writing your programs

The finalize () Method

Sometimes an object will need to perform some action when it is destroyed. For example, if an object is holding some non-java resource such as a file handle or window character font, then you might want to make sure these resources are freed before an object is destroyed. To handle such situations, java provides a mechanism called finalization. By using finalization, you can define specific actions that will occur when an object is just about to be reclaimed by the garbage collector.

To add a finalizer to a class, you simply define the finalize() method. The java run time calls that method whenever it is about to recycle an object of that class. Inside the finalize() method you will specify those actions that must be performed before an object is destroyed. The garbage collector runs periodically, checking for objects that are no longer referenced by any running state or indirectly through other referenced objects. Right before an asset is freed, the java run time calls the finalize() method on the object.

The finalize() method has this general form:

protected void finalize() { // finalization code here }

Here, the keyword protected is a specifier that prevents access to finalize() by code defined outside its class.

It is important to understand that finalize() is only called just prior to garbage collection. It is not called when an object goes out-of-scope, for example. This means program should provide other means of releasing system resources, etc., used by the object. It must not rely on finalize() for normal program operation. class demo { int id;

demo(int i)

{ id=i; } public static void main(String ar[]) { System.runFinalizersOnExit(true); demo d=null; for(int i=1;i<5;i++) d=new demo(i); } public void finalize()throws Throwable { System.out.println("finalizr"+id); super.finalize(); } } Class sample1 { Public static void main (String ar[]) { System.out.println (“welcome to java”); } } Session 2: 1. Static:- Static method

When member is declare static it can be access before object of its class are created and without reference to any object. Static method can only access static method static initialization block for setting a static field of class. Execution of static block is done once before java executes any other method of that class is called. class aa { static int a=1; static int b; static void show(int x) { System.out.println("x="+x); System.out.println("x="+b); System.out.println("x="+a); } static { System.out.println("static block"); b=a*4; } public static void main(String ar[]) { aa a1=new aa(); a1.show(20); }

} Java compilar To commence with Java programming, we must know the significance of Java Compiler. When we write any program in a text editor like Notepad, we use Java compiler to compile it. A Java Compiler javac is a programmer set of programs which translates java source code intojava byte code. The output from a Java compiler comes in the form of Java class files (with .class extension). The code contained in files end with the .java extension. The file name must be the same as the class name, asclassname.java. When the javac compiles the source file defined in a .java files, it generates bytecode for the java source file and saves in a class file with a .class extension. The most commonly used Java compiler is javac, included in JDK from Sun Microsystems. Following figure shows the working of the Java compiler:

Once the byte code is generated it can be run on any platform using Java Interpreter (JVM). It interprets byte code (.class file) and converts into machine specific binary code. Then JVM runs the binary code on the host machine. Java debugger Java Debugger Java debugger helps in finding and the fixing of bugs in Java language programs. The Java debugger is denoted as jdb. It works like a command-line debugger for Java classes. jdb session The way to start the jdb session is to have jdb launch a newJVM (Java virtual machine) with the main class. Then the application of the main class is debugged by substituting the

command jdb in command-line. For instance, if the main class of the application is TempClass, the following command is used to debug it: jdb TempClass There is another way to use jdb i.e.to attach jdb to Java VM which is already running. There are few options which are used to debug a VM with jdb. These are: option

purpose

-Xdebug

Enables debugging in the VM

-Xrunjdwp:transport=dt_socket,server=y,suspend=n

Loads in-process debugging libraries and specifies the kind of connection to be made

The following command will run the TempClass application to which the jdb will connect afterwords. % java -Xdebug -Xrunjdwp:transport=dt_socket,address=8000,server=y,suspend=n TempClass Now the jdb will be attached to the VM in this way: % jdb -attach 8000 You can go through the basic jdb commands that the Java debugger supports. cont Ihis command Continues the execution of the debugged application after a breakpoint, exception, or step. run Use run command to start the execution after starting jdb, and setting any necessary breakpoints, use run command to start the execution . When jdb launches the debugged application then only this command is available. print This command is used to display Java objects and primitive values. The actual value is printed for the variables or fields of primitive types. For objects, a short description is printed.

Difference between application and applet In simple terms, an applet runs under the control of a browser, whereas an application runs standalone, with the support of a virtual machine. As such, an applet is subjected to more stringent security restrictions in terms of file and network access, whereas an application can have free reign over these resources. Applets are great for creating dynamic and interactive web applications, but the true power of Java lies in writing full blown applications. With the limitation of disk and network access, it

would be difficult to write commercial applications (though through the user of server based file systems, not impossible). However, a Java application has full network and local file system access, and its potential is limited only by the creativity of its developers.

Abstract class:Any class that contains one or more abstract methods must also be declared abstract. To declare a class abstract, you simply use the abstract keyword in front of the class keyword at the beginning of the class declaration. There can be no objects of an abstract class. That is, an abstract class cannot be directly instantiated with the new operator. Such objects would be useless, because an abstract class is not fully defined. Also, you cannot declare abstract constructors, or abstract static methods. Any subclass of an abstract class must either implement all of the abstract methods in the super class, or be itself declared abstract. Here is a simple example of a class with an abstract method, followed by a class which implements that method: abstract class bb { void show() {} } class nn extends bb { void show() { System.out.println("this is n1 class"); } } class n1 {

public static void main(String ar[]) { bb b=new nn(); b.show(); } }

Inner class:It is possible to nest a class definition within another class & treat the nested class has privilege to access all the members of the member of the class enclosing it. A nested class can either be static or nonstatic a static nested class is one which has static modifier applied. Non static nested class called as inner class. //inner class class outclass { static int a=1; sstatic class inclass { static int b=a+1; int c=3; } } class ioclass

{ public static void main(String ar[]) { System.out.println("a="+outclass.a); System.out.println("a="+outclass.inclass.b); inclass io=new inclass(); System.out.println("a="+io.b); } }

Wrapper class The java programmers does not look at primitive data types as object for example numerical, Boolean and character data are treated in the primitive form for sake of officiency.The java programming language provides wrapper class to manipulate primitive data elements are wrapped in object created around them Each java primitive data type has a corresponding wrapper class object encapsulates a single primitive value. These wrapper classes implement immutable objects.That means that after the primitive value is initialized in the wrapper object then there is no way to change that value. Wrapper class Primitive data type Boolan

wrapper class Bolean

Byte Char

byte char

Short

short

Int

int

Long

long

Float Double

float double

You can construct a wrapper class object by passing the value to wrapped into the appropriate constructors. Int pint=420 Integer wint=new integer(pint); //boxing In p2=wint.intvalue)//unboxing Wrapper classes are useful when convertry primitive data type because of many wrapper class methods available Int x=integer.valu(str).intvalue(); Or Int x=integer.parseint(str);

Unboxing primitive type : If you have to chang the primitive data type to their object equivalents called boxing the you need to use wrapper classes also to get the primitive data type from the object reference data type from the object reference called unboxing you need to use wrapper class methods. All of the boxing and unboxing can clutter up Session 3: Interface:Interfaces form a contract between the class and the outside world 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. an interface is a group of related methods with empty bodies. Interfaces form a contract between the class and the outside world. Interface Bicycle {

void changeCadence(int newValue); void changeGear(int newValue); void speedUp(int increment); void applyBrakes(int decrement); }

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 file system; 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. Exception Handling Basics of exception handling error and abnormal condition arising while executing a program need to be java handle usually code snippets are written such situation. Java occurs various classes to handle exception thus making its program robust. *The class Hierarchy:The object class has a sub class called throw able to handle exceptions and error. The throw able class ha two sub classes. 1. Exception 2.Error:-

Error conditions are normally not trapped by java programs error condition occurring in case of drastic failure (virtual machine error) which cannot be handle by a program these are generated to indicate errors generated by run time environment. The main sub class of exception class is the runtime exception class. An exception is an abnormal condition which occurs during the execution of program exceptions are is event like division by zero. Opening of file that does not exist etc. run time exception class generate error that occurs during the exception of program runtime exception is defined by default for all program. Try catch:-

Whenever there is possibility of exception being generated in a program. It is better to handle explicitly. This can be done by using try and catch are it fixes the error and prevent the program. The code sequence which is to be granted should be placed inside the try block. The catch clause should immediately follow the try block.The catch clause can have statement explaining the cause of exception generated the scope of each catch is restricted to a try block.



Comman exception:-

• ArithmeticException--thrown

if a program attempts to perform division by zero • ArrayIndexOutOfBoundsException--thrown if a program attempts to access an index of an array that does not exist • StringIndexOutOfBoundsException--thrown if a program attempts to access a character at a non-existent index in a String • NullPointerException--thrown if the JVM attempts to perform an operation on an Object that points to no data, or null • NumberFormatException--thrown if a program is attempting to convert a string to a numerical datatype, and the string contains inappropriate characters (i.e. 'z' or 'Q') • ClassNotFoundException--thrown if a program cannot find a class it depends at runtime (i.e., the class's ".class" file cannot be found or was removed from the CLASSPATH) • IOException--actually contained in java.io, but it is thrown if the JVM failed to open an I/O stream

The catch statement also stores an instance of the exception that was caught in the variable that the programmer uses, in the previous example Exception e. While all exceptions are subclasses of Exception, Exception itself is a subclass of Throwable, which contains a nice suite of methods that you can use to get all kinds of information to report about your exceptions: getMessage()--returns the error message reported by the exception in a String • printStackTrace()--prints the stack trace of the exception to standard output, useful for debugging purposes in locating where the exception occurred • printStackTrace(PrintStream s)--prints the stack trace to an alternative output stream • printStackTrace(PrintWriter s)--prints the stack trace to a file, this way you can log stack traces transparent to the user or log for later reference • toString()--if you just decide to print out the exception it will print out this: NAME_OF_EXCEPTION: getMessage(). •

*Program on arithmetic exception class arithmetic { public static void main(string ar[]) { { try { int n=5/0;

System.out.println(“You are trying to devide by zero”); } catch(Arithmetic exception e) { System.out.println(“You are trying to devide by zero”); } } }

Package java.lang Provides classes that are fundamental to the design of the Java programming language. See: Description Interface Summary CharSequence A CharSequence is a readable sequence of characters.

Cloneable

A class implements the Cloneable interface to indicate to the Object.clone() method that it is legal for that method to make a field-for-field copy of instances of that class.

Comparable

This interface imposes a total ordering on the objects of each class that implements it.

Runnable

The Runnable interface should be implemented by any class whose instances are intended to be executed by a thread.

Class Summary

Boolean

The Boolean class wraps a value of the primitive type boolean in an object.

Byte

The Byte class wraps a value of primitive type byte in an object.

Character

The Character class wraps a value of the primitive type char in an object.

Character.Subset

Instances of this class represent particular subsets of the Unicode character set.

Character.UnicodeBlock

A family of character subsets representing the character blocks in the Unicode specification.

Class

Instances of the class Class represent classes and interfaces in a running Java application.

ClassLoader

A class loader is an object that is responsible for loading classes.

Compiler

The Compiler class is provided to support Java-to-native-code compilers and related services.

Double

The Double class wraps a value of the primitive type double in an object.

Float

The Float class wraps a value of primitive type float in an object.

This class extends ThreadLocal to provide inheritance of values from parent thread to child thread: when a child thread is created, the child InheritableThreadLocal receives initial values for all inheritable thread-local variables for which the parent has values. Integer

The Integer class wraps a value of the primitive type int in an object.

Long

The Long class wraps a value of the primitive type long in an object.

Math

The class Math contains methods for performing basic numeric operations such as the elementary exponential, logarithm, square root, and trigonometric functions.

Number

The abstract class Number is the superclass of classes BigDecimal,

BigInteger, Byte, Double, Float, Integer, Long, and Short. Object

Class Object is the root of the class hierarchy.

Package

Package objects contain version information about the implementation and specification of a Java package.

Process

The Runtime.exec methods create a native process and return an instance of a subclass of Process that can be used to control the process and obtain information about it.

Runtime

Every Java application has a single instance of class Runtime that allows the application to interface with the environment in which the application is running.

RuntimePermission

This class is for runtime permissions.

SecurityManager

The security manager is a class that allows applications to implement a security policy.

Short

The Short class wraps a value of primitive type short in an object.

StackTraceElement

An element in a stack trace, as returned by Throwable.getStackTrace().

StrictMath

The class StrictMath contains methods for performing basic numeric operations such as the elementary exponential, logarithm, square root, and trigonometric functions.

String

The String class represents character strings.

StringBuffer

A string buffer implements a mutable sequence of characters.

System

The System class contains several useful class fields and methods.

Thread

A thread is a thread of execution in a program.

ThreadGroup

A thread group represents a set of threads.

ThreadLocal

This class provides thread-local variables.

Throwable

The Throwable class is the superclass of all errors and exceptions in the Java language.

Void

The Void class is an uninstantiable placeholder class to hold a reference to the Class object representing the Java keyword void.

Exception Summary ArithmeticException

Thrown when an exceptional arithmetic condition has occurred.

ArrayIndexOutOfBoundsException

Thrown to indicate that an array has been accessed with an illegal index.

ArrayStoreException

Thrown to indicate that an attempt has been made to store the wrong type of object into an array of objects.

ClassCastException

Thrown to indicate that the code has attempted to cast an object to a subclass of which it is not an instance.

ClassNotFoundException

Thrown when an application tries to load in a class through its string name using: The forName method in class Class.

CloneNotSupportedException

Thrown to indicate that the clone method in class Object has been called to clone an object, but that the object's class does not implement the Cloneable interface.

Exception

The class Exception and its subclasses are a form of Throwable that indicates conditions that a reasonable application might want to catch.

IllegalAccessException

An IllegalAccessException is thrown when an application tries to reflectively create an instance (other than an array), set or get a field, or invoke a method, but the currently executing method does not have access to the definition of the specified class, field, method or

constructor. IllegalArgumentException

Thrown to indicate that a method has been passed an illegal or inappropriate argument.

IllegalMonitorStateException

Thrown to indicate that a thread has attempted to wait on an object's monitor or to notify other threads waiting on an object's monitor without owning the specified monitor.

IllegalStateException

Signals that a method has been invoked at an illegal or inappropriate time.

IllegalThreadStateException

Thrown to indicate that a thread is not in an appropriate state for the requested operation.

IndexOutOfBoundsException

Thrown to indicate that an index of some sort (such as to an array, to a string, or to a vector) is out of range.

InstantiationException

Thrown when an application tries to create an instance of a class using the newInstance method in class Class, but the specified class object cannot be instantiated because it is an interface or is an abstract class.

InterruptedException

Thrown when a thread is waiting, sleeping, or otherwise paused for a long time and another thread interrupts it using the interrupt method in class Thread.

NegativeArraySizeException

Thrown if an application tries to create an array with negative size.

NoSuchFieldException

Signals that the class doesn't have a field of a specified name.

NoSuchMethodException

Thrown when a particular method cannot be found.

NullPointerException

Thrown when an application attempts to use null in a case where an object is required.

NumberFormatException

Thrown to indicate that the application has attempted to convert a string to one of the numeric types, but that the

string does not have the appropriate format.

RuntimeException

RuntimeException is the superclass of those exceptions that can be thrown during the normal operation of the Java Virtual Machine.

SecurityException

Thrown by the security manager to indicate a security violation.

StringIndexOutOfBoundsException

Thrown by String methods to indicate that an index is either negative or greater than the size of the string.

UnsupportedOperationException

Thrown to indicate that the requested operation is not supported.

Error Summary AbstractMethodError

Thrown when an application tries to call an abstract method.

AssertionError

Thrown to indicate that an assertion has failed.

ClassCircularityError

Thrown when a circularity has been detected while initializing a class.

ClassFormatError

Thrown when the Java Virtual Machine attempts to read a class file and determines that the file is malformed or otherwise cannot be interpreted as a class file.

Error

An Error is a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch.

ExceptionInInitializerError

Signals that an unexpected exception has occurred in a static initializer.

IllegalAccessError

Thrown if an application attempts to access or modify a field, or to call a method that it does not have access to.

IncompatibleClassChangeError Thrown when an incompatible class change has occurred to

some class definition. InstantiationError

Thrown when an application tries to use the Java new construct to instantiate an abstract class or an interface.

InternalError

Thrown to indicate some unexpected internal error has occurred in the Java Virtual Machine.

LinkageError

Subclasses of LinkageError indicate that a class has some dependency on another class; however, the latter class has incompatibly changed after the compilation of the former class.

NoClassDefFoundError

Thrown if the Java Virtual Machine or a ClassLoader instance tries to load in the definition of a class (as part of a normal method call or as part of creating a new instance using the new expression) and no definition of the class could be found.

NoSuchFieldError

Thrown if an application tries to access or modify a specified field of an object, and that object no longer has that field.

NoSuchMethodError

Thrown if an application tries to call a specified method of a class (either static or instance), and that class no longer has a definition of that method.

OutOfMemoryError

Thrown when the Java Virtual Machine cannot allocate an object because it is out of memory, and no more memory could be made available by the garbage collector.

StackOverflowError

Thrown when a stack overflow occurs because an application recurses too deeply.

ThreadDeath

An instance of ThreadDeath is thrown in the victim thread when the stop method with zero arguments in class Thread is called.

UnknownError

Thrown when an unknown but serious exception has occurred in the Java Virtual Machine.

UnsatisfiedLinkError

Thrown if the Java Virtual Machine cannot find an appropriate

native-language definition of a method declared native. Thrown when the Java Virtual Machine attempts to read a UnsupportedClassVersionError class file and determines that the major and minor version numbers in the file are not supported.

VerifyError

Thrown when the "verifier" detects that a class file, though well formed, contains some sort of internal inconsistency or security problem.

VirtualMachineError

Thrown to indicate that the Java Virtual Machine is broken or has run out of resources necessary for it to continue operating.

Package java.lang Description Provides classes that are fundamental to the design of the Java programming language. The most important classes are Object, which is the root of the class hierarchy, and Class, instances of which represent classes at run time. Frequently it is necessary to represent a value of primitive type as if it were an object. The wrapper classes Boolean, Character, Integer, Long, Float, and Double serve this purpose. An object of type Double, for example, contains a field whose type is double, representing that value in such a way that a reference to it can be stored in a variable of reference type. These classes also provide a number of methods for converting among primitive values, as well as supporting such standard methods as equals and hashCode. The Void class is a non-instantiable class that holds a reference to a Class object represening the primitive type void. The class Math provides commonly used mathematical functions such as sine, cosine, and square root. The classes String and StringBuffer similarly provide commonly used operations on character strings. Classes ClassLoader, Process, Runtime, SecurityManager, and System provide "system operations" that manage the dynamic loading of classes, creation of external processes, host environment inquiries such as the time of day, and enforcement of security policies. Class Throwable encompasses objects that may be thrown by the throw statement (§14.16). Subclasses of Throwable represent errors and exceptions. Package java.util

Contains the collections framework, legacy collection classes, event model, date and time facilities, internationalization, and miscellaneous utility classes (a string tokenizer, a randomnumber generator, and a bit array). See: Description Interface Summary Collection

The root interface in the collection hierarchy.

Comparator

A comparison function, which imposes a total ordering on some collection of objects.

Enumeration

An object that implements the Enumeration interface generates a series of elements, one at a time.

EventListener A tagging interface that all event listener interfaces must extend. Iterator

An iterator over a collection.

List

An ordered collection (also known as a sequence).

ListIterator

An iterator for lists that allows the programmer to traverse the list in either direction, modifies the list during iteration, and obtains the iterator's current position in the list.

Map

An object that maps keys to values.

Map.Entry

A map entry (key-value pair).

Observer

A class can implement the Observer interface when it wants to be informed of changes in observable objects.

RandomAccess

Marker interface used by List implementations to indicate that they support fast (generally constant time) random access.

Set

A collection that contains no duplicate elements.

SortedMap

A map that further guarantees that it will be in ascending key order, sorted according to the natural ordering of its keys (see the Comparable interface), or

by a comparator provided at sorted map creation time.

SortedSet

A set that further guarantees that its iterator will traverse the set in ascending element order, sorted according to the natural ordering of its elements (see Comparable), or by a Comparator provided at sorted set creation time.

Class Summary AbstractCollection

This class provides a skeletal implementation of the Collection interface, to minimize the effort required to implement this interface.

AbstractList

This class provides a skeletal implementation of the List interface to minimize the effort required to implement this interface backed by a "random access" data store (such as an array).

AbstractMap

This class provides a skeletal implementation of the Map interface, to minimize the effort required to implement this interface.

AbstractSequentialList

This class provides a skeletal implementation of the List interface to minimize the effort required to implement this interface backed by a "sequential access" data store (such as a linked list).

AbstractSet

This class provides a skeletal implementation of the Set interface to minimize the effort required to implement this interface.

ArrayList

Resizable-array implementation of the List interface.

Arrays

This class contains various methods for manipulating arrays (such as sorting and searching).

BitSet

This class implements a vector of bits that grows as needed.

Calendar

Calendar is an abstract base class for converting between a Date object and a set of integer fields such as YEAR, MONTH, DAY, HOUR, and so on.

Collections

This class consists exclusively of static methods that operate on or

return collections. Currency

Represents a currency.

Date

The class Date represents a specific instant in time, with millisecond precision.

Dictionary

The Dictionary class is the abstract parent of any class, such as Hashtable, which maps keys to values.

EventListenerProxy

An abstract wrapper class for an EventListener class which associates a set of additional parameters with the listener.

EventObject

The root class from which all event state objects shall be derived.

GregorianCalendar

GregorianCalendar is a concrete subclass of Calendar and provides the standard calendar used by most of the world.

HashMap

Hash table based implementation of the Map interface.

HashSet

This class implements the Set interface, backed by a hash table (actually a HashMap instance).

Hashtable

This class implements a hashtable, which maps keys to values.

IdentityHashMap

This class implements the Map interface with a hash table, using reference-equality in place of object-equality when comparing keys (and values).

LinkedHashMap

Hash table and linked list implementation of the Map interface, with predictable iteration order.

LinkedHashSet

Hash table and linked list implementation of the Set interface, with predictable iteration order.

LinkedList

Linked list implementation of the List interface.

ListResourceBundle

ListResourceBundle is an abstract subclass of ResourceBundle that manages resources for a locale in a convenient and easy to use list.

Locale

A Locale object represents a specific geographical, political, or

cultural region. Observable

This class represents an observable object, or "data" in the modelview paradigm.

Properties

The Properties class represents a persistent set of properties.

PropertyPermission

This class is for property permissions.

PropertyResourceBundle is a concrete subclass of ResourceBundle PropertyResourceBundle that manages resources for a locale using a set of static strings from a property file. Random

An instance of this class is used to generate a stream of pseudorandom numbers.

ResourceBundle

Resource bundles contain locale-specific objects.

SimpleTimeZone

SimpleTimeZone is a concrete subclass of TimeZone that represents a time zone for use with a Gregorian calendar.

Stack

The Stack class represents a last-in-first-out (LIFO) stack of objects.

StringTokenizer

The string tokenizer class allows an application to break a string into tokens.

Timer

A facility for threads to schedule tasks for future execution in a background thread.

TimerTask

A task that can be scheduled for one-time or repeated execution by a Timer.

TimeZone

TimeZone represents a time zone offset, and also figures out daylight savings.

TreeMap

Red-Black tree based implementation of the SortedMap interface.

TreeSet

This class implements the Set interface, backed by a TreeMap instance.

Vector

The Vector class implements a growable array of objects.

WeakHashMap

A hashtable-based Map implementation with weak keys.

Exception Summary This exception may be thrown by methods that have ConcurrentModificationException detected concurrent modification of an object when such modification is not permissible. EmptyStackException

Thrown by methods in the Stack class to indicate that the stack is empty.

MissingResourceException

Signals that a resource is missing.

NoSuchElementException

Thrown by the nextElement method of an Enumeration to indicate that there are no more elements in the enumeration.

TooManyListenersException

The TooManyListenersException Exception is used as part of the Java Event model to annotate and implement a unicast special case of a multicast Event Source.

The String Class:• String is the name of a predefined class. actual name is java.lang.String The String class is a little special support for literals, like "Hello Class" support for operators: + concatenation += assignment and concatenation, as in s += " Append to end of s";he String class A String object can: tell you it's length tell you if it contains a substring (and where). tell you if it matches a regular expression. tell you what is at any position

create a copy that is all lowercase or uppercase compare itself to another String If you are reading this outside of class, please proceed to the Java API docs for the class java.lang.String ● memorize all the methods and constructors, there may be a test on this... A String object is immutable you can't change it at all. Really! This sounds silly, but there are good reasons for this and it's not really a hassle. ● Using == to compare String objects is rarely what you want only true if they are the same object we usually want to know if two strings hold the same sequence of characters. Use String.equals() You can initialize a String with a literal: String s = "Hello There"; This is basically the same as: String s = new String("Hello There"); ● You can call methods on a literal! int len = "Hello".length(); if ("Fred".equals(s)) System.out.printf("Fred it is\n"); *Converting Strings to primitive types int x = Integer.parseInt("12"); double d = Double.parseDouble("3.141593"); boolean b = Boolean.parseBoolean("false"); String s = new String(); for (int i=0;i<10;i++) { s = s + i; } System.out.println(s); We want a class named Square that has a size.

● We want to be able to print a Square object it should report its size, that's all. we need to write a toString() method. ● We want to be able to tell the Square to draw itself. we will just have it print characters out using System.out.print(). class Square { int size; Square(int x) { size = x; } public String toString() { return("Square of size " + size); } public void Draw() { for (int i=0;i<size;i++) { for (int j=0;j<size;j++) { System.out.print("*"); } System.out.println(); } } public static void main(String[] args) { Square s = new Square(Integer.parseInt(args[0])); System.out.println(s); s.Draw(); } Array:-

Array: Array is the most important thing in any programming language. By definition, array is the static memory allocation. It allocates the memory for the same data type in sequence. It contains multiple values of same types. It also store the values in memory at the fixed size. Multiple types of arrays are used in any programming language such as: one - dimensional, two dimensional or can say multi - dimensional. Declaration of an array: int num[]; or int num = new int[2]; Some times user declares an array and it's size simultaneously. You may or may not be define the size in the declaration time. such as: int num[] = {50,20,45,82,25,63}; In this program we will see how to declare and implementation. This program illustrates that the array working way. This program takes the numbers present in the num[] array in unordered list and prints numbers in ascending order. In this program the sort() function of the java.util.*; package is using to sort all the numbers present in the num[] array. The Arrays.sort() automatically sorts the list of number in ascending order by default. This function held the argument which is the array name num. import java.util.*; public class array{ public static void main(String[] args){ int num[] = {50,20,45,82,25,63}; int l = num.length; int i,j,t; System.out.print("Given number : "); for (i = 0;i < l;i++ ){ System.out.print(" " + num[i]); } System.out.println("\n"); System.out.print("Accending order number : "); Arrays.sort(num); for(i = 0;i < l;i++){ System.out.print(" " + num[i]); } } }

Vector Vectors (the java.util.Vector class) are commonly used instead of arrays, because they expand automatically when new data is added to them. The Java 2 Collections API introduced the similar ArrayList data structure. ArrayLists are unsynchronized and therefore faster than

Vectors, but less secure in a multithreaded environment. The Vector class was changed in Java 2 to add the additional methods supported by ArrayList. See below for a reasons to use each. The description below is for the (new) Vector class. Vectors can hold only Objects and not primitive types (eg, int). If you want to put a primitive type in a Vector, put it inside an object (eg, to save an integer value use the Integer class or define your own class). If you use the Integer wrapper, you will not be able to change the integer value, so it is sometimes useful to define your own class. To Create a Vector You must import either import java.util.Vector; or import java.util.*;. Vectors are implemented with an array, and when that array is full and an additional element is added, a new array must be allocated. Because it takes time to create a bigger array and copy the elements from the old array to the new array, it is a little faster to create a Vector with a size that it will commonly be when full. Of course, if you knew the final size, you could simply use an array. However, for noncritical sections of code programmers typically don't specify an initial size. •

Create a Vector with default initial size Vector v = new Vector();



Create a Vector with an initial size Vector v = new Vector(300);

Common Vector Methods There are many useful methods in the Vector class and its parent classes. Here are some of the most useful. v is a Vector, i is an int index, o is an Object. Method

Description

v.add(o)

adds Object o to Vector v

v.add(i, o)

Inserts Object o at index i, shifting elements up as necessary.

v.clear()

removes all elements from Vector v

v.contains(o)

Returns true if Vector v contains Object o

v.firstElement(i)

Returns the first element.

v.get(i)

Returns the object at int index i.

v.lastElement(i)

Returns the last element.

v.listIterator()

Returns a ListIterator that can be used to go over the Vector. This is a useful

alternative to the for loop. v.remove(i)

Removes the element at position i, and shifts all following elements down.

v.set(i,o)

Sets the element at index i to o.

v.size()

Returns the number of elements in Vector v.

The array parameter can be any Object subclass (eg, String). This returns the vector values in that array (or a larger array if necessary). This is useful when v.toArray(Object[]) you need the generality of a Vector for input, but need the speed of arrays when processing the data. Old and New Vector Methods When the new Collections API was introduced in Java 2 to provide uniform data structure classes, the Vector class was updated to implement the List interface. Use the List methods because they are common to other data structure. If you later decide to use something other than a Vector (eg, ArrayList, or LinkedList, your other code will not need to change. Even up thru the first several versions of Java 2 (SDK 1.4), the language had not entirely changed to use the new Collections methods. For example, the DefaultListModel still uses the old methods, so if you are using a JList, you will need to use the old method names. There are hints that they plan to change this, but still and interesting omission. Replacements for old methods The following methods have been changed from the old to the new Vector API. Old Method

New Method

void addElement(Object)

boolean add(Object)

void copyInto(Object[])

Object[] toArray()

Object elementAt(int)

Object get(int)

Enumeration elements()

Iterator iterator() ListIterator listIterator()

void insertElementAt(Object, int) void add(index, Object) void removeAllElements()

void clear()

boolean removeElement(Object) boolean remove(Object) void removeElementAt(int)

void remove(int)

void setElementAt(int)

Object set(int, Object)

Sample program:import java.util.Vector; import java.util.Collections; public class maximum vector element { public static void main(String[] args) { //create a Vector object Vector v = new Vector(); //Add elements to Vector v.add(new int("500")); v.add(new int("745")); v.add(new int("842")); v.add(new int("900")); v.add(new int("567"));

Object obm = Collections.max(v); System.out.println("Maximum Element of Java Vector is : " + obm); } } Stack:A Stack is like a bucket in which you can put elements one-by-one in sequence and retrieve elements from the bucket according to the sequence of the last entered element. Stack is a collection of data and follows the LIFO (Last in, first out) rule that mean you can insert the elements one-by-one in sequence and the last inserted element can be retrieved at once from the bucket. Elements are inserted and retrieved to/from the stack through the push() and pop() method. This program implements a stack and follows the LIFO rule. It asks you for the number of elements which have to be entered in the stack and then it takes elements for insertion in the

stack. All the elements present in the stack are shown from the last inserted element to the first inserted element. Stack(): Above constructor of the Stack class creates a empty stack which holds the integer type value which is mention with the creation of stack. The Stack class extends the Vector class and both classes are implemented from the java.util.*; package. Stack.push(Object obj): Above method is used to insert or push the data or element in the stack. It takes an object like: data or elements and push its onto the top of the stack. Stack.pop(): This is the method to removes the objects like: data or elements at the top positions of stack. import java.io.*; import java.util.*; public class StackImplement{ Stack stack; String str; int num, n; public static void main(String[] args){ StackImplement q = new StackImplement(); } public StackImplement(){ try{ stack = new Stack(); InputStreamReader ir = new InputStreamReader(System.in); BufferedReader bf = new BufferedReader(ir); System.out.print("Enter number of elements : "); str = bf.readLine(); num = Integer.parseInt(str); for(int i = 1; i <= num; i++){ System.out.print("Enter elements : "); str = bf.readLine(); n = Integer.parseInt(str); stack.push(n); } } catch(IOException e){} System.out.print("Retrieved elements from the stack : "); while (!stack.empty()){ System.out.print(stack.pop()+" "); } }

} HashTable:*Hash Table holds the records according to the unique key value. It stores the non-contiguous key for several values. Hash Table is created using an algorithm (hashing function) to store the key and value regarding to the key in the hash bucket. If you want to store the value for the new key and if that key is already exists in the hash bucket then the situation known as collision occurs which is the problem in the hash table i.e. maintained by the hashing function. The drawback is that hash tables require a little bit more memory, and that you can not use the normal list procedures for working with them. This program simply asks you for the number of entries which have to entered into the hash table and takes one-by-one key and it's value as input. It shows all the elements with the separate key. Code Description: Hashtable hashTable = new Hashtable(): Above code creates the instance of the Hashtable class. This code is using the type checking of the elements which will be held by the hash table. hashTable.put(key, in.readLine()): Above method puts the values in the hash table regarding to the unique key. This method takes two arguments in which, one is the key and another one is the value for the separate key. Map map = new TreeMap(hashTable): Above code creates an instance of the TreeMap for the hash table which name is passed through the constructor of the TreeMap class. This code creates the Map with the help of the instance of the TreeMap class. This map has been created in the program for showing several values and it's separate key present in the hash table. This code has used the type checking. import java.util.*; import java.io.*; public class HashTable{ public static void main(String[] args) throws IOException{ int key; try{ BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); System.out.print("How many elements you want to enter to the hash table : "); int n = Integer.parseInt(in.readLine()); Hashtable hashTable = new Hashtable(); for(int i = 0; i < n; i++){ System.out.print("Enter key for the hash table : "); key = Integer.parseInt(in.readLine()); System.out.print("Enter value for the key : ");

hashTable.put(key, in.readLine()); } Map map = new TreeMap(hashTable); System.out.println(map); } catch(NumberFormatException ne){ System.out.println(ne.getMessage() + " is not a legal value."); System.out.println("Please enter a numeric value."); System.exit(1); } } } *Program to get class directory import java.util.*; import java.lang.*; import java.net.*; public class GetClassDirectory { public static void main(String args[]) { URL url=new Object().getClass().getResource("Object.class"); System.out.println(url); } } *Properties:import java.util.*; public class GetPropertyByName { public static void main(String args[]) { Properties properties = System.getProperties(); Set set = properties.stringPropertyNames(); Iterator iterator = set.iterator(); String key; while (iterator.hasNext()) { key = iterator.next().toString(); System.out.print(key + " : ");

System.out.println(properties.getProperty(key)); } } } *Multithreaded programming in Java:Multithreading allows two parts of the same program to run concurrently. Multitasking is performing two or more tasks at the same time. Nearly all operating systems are capable of multitasking by u Process-based multitasking is running two programs concurrently. Programmers refer to a program as a process. Therefore, you could say that process-based multitasking is program-based multitasking. Thread-based multitasking is having a program perform two tasks at the same time. For example, a word processing program can check the spelling of words in a document while you write the document. This is thread-based multitasking. A good way to remember the difference between process-based multitasking and thread-based multitasking is to think of process-based as working with multiple programs and thread-based as working with parts of one program. The objective of multitasking is to utilize the idle time of the CPU. Think of the CPU as the engine of your car. Your engine keeps running regardless of whether the car is moving. Your objective is to keep your car moving as much as possible so you can get the most miles from a gallon of gas. An idling engine wastes gas. The same concept applies to the CPU in your computer. You want your CPU cycles to be processing instructions and data rather than waiting for something to process. A CPU cycle is somewhat similar to your engine running. It may be hard to believe, but the CPU idles more than it processes in many desktop computers. Let’s say that you are using a word processor to write a document. For the most part, the CPU is idle until you enter a character from the keyboard or move the mouse. Multitasking is designed to use the fraction of a second between strokes to process instructions from either another program or from a different part of the same programming one of two multitasking techniques: process-based multitasking and thread-based multitasking. Thread:-

You construct threads by using the Thread class and the Runnable interface. This means that your class must extend the Thread class or implement the Runnable interface. The Thread class defines the methods you use to manage threads. Method

Description

getName()

Returns the name of the thread.

getPriority()

Returns the priority of the thread.

isAlive()

Determines whether the thread is running.

join()

Pauses until the thread terminates.

run()

The entry point into the thread.

sleep()

Suspends a thread. This method enables you to specify the period

Suspend()

the thread is suspended.

start()

Starts the thread.

The Main Thread Every Java program has one thread, even if you don’t create any threads. This thread is called the main thread because it is the thread that executes when you start your program. The main thread spawns threads that you create. These are called child threads. The main thread is always the last thread to finish executing because typically the main thread needs to release a resource used by the program such as network connections. Programmers can control the main thread by first creating a Thread object and then using method members of the Thread object to control the main thread. You create a Thread object by calling the currentThread() method. The currentThread() method returns a reference to the thread. You then use this reference to control the main thread just like you control any thread, which you’ll learn how to do in this chapter. Let’s create a reference to the main thread and then change the name of the thread from main to Demo Thread. The following program shows how this is done. Here’s what is displayed on the screen when the program runs: Current thread: Thread[main, 5,main] Renamed Thread: Thread[Demo Thread, 5,main] class Demo { Public static void main (String args[] ) { Thread t = Thread.currentThread(); System.out.println("Current thread: " + t); t.setName("Demo Thread"); System.out.println("Renamed Thread: " + t); } }

As you previously learned in this chapter, a thread is automatically created when you execute a program. The objective of this example is to declare a reference to a thread and then assign that reference a reference to the main thread. This is done in the first statement of the main () method. We declare the reference by specifying the name of the class and the name for the reference, which is done in the following line of code: Thread t We acquire a reference to the main thread by calling the currentThread() method member of the Thread class using the following method call: Thread.currentThread() The reference returned by the currentThread() method is then assigned to the reference previously declared in the opening statement. We then display the thread on the screen: Thread[main, 5,main] Information within the square brackets tells us something about the thread. The first appearance of the word main is the name of the thread. The number 5 is the thread’s priority, which is normal priority. The priority ranges from 1 to 10, where 1 is the lowest priority and 10 is the highest. The last occurrence of the word main is the name of the group of threads with which the thread belongs. A thread group is a data structure used to control the state of a collection of threads. You don’t need to be concerned about a thread group because the Java run-time environment handles this. The setName() method is then called to illustrate how you have control over the main thread of your program. The setName() method is a method member of the Thread class and is used to change the name of a thread. This example uses the setName() method to change the main thread’s name from main to Demo Thread. The thread is once again displayed on the screen to show that the name has been changed. Here’s what is displayed: Renamed Thread: Thread[Demo Thread, 5,main] Remember, your program is the main thread, and other portions of your program can also be a thread. You can designate a portion of your program as a thread by creating your own thread. The easiest way to do this is to implement the Runnable interface. Implementing the Runnable interface is an alternative to your class inheriting the Thread class. An interface describes one or more method members that you must define in your own class in order to be compliant with the interface. These methods are described by their method name, argument list, and return value.

The Runnable interface describes the method classes needed to create and interact with a thread. In order to use the Runnable interface in your class, you must define the methods described by the Runnable interface. Fortunately, only you need to define one method described by the Runnable interface—the run() method. The run() method must be a public method, and it doesn’t require an argument list or have a return value. The content of the run() method is the portion of your program that will become the new thread. Statements outside the run() method are part of the main thread. Statements inside the run() method are part of the new thread. Both the main thread and the new thread run concurrently when you start the new thread, which you’ll learn how to do in the next example. The new thread terminates when the run() method terminates. Control then returns to the statement that called the run() method. When you implement the Runnable interface, you’ll need to call the following constructor of the Thread class. This constructor requires two arguments. The first argument is the instance of the class that implements the Runnable interface and tells the constructor where the new thread will be executed. The second argument is the name of the new thread. Here’s the format of the constructor: Thread (Runnable class, String name) The constructor creates the new thread, but it does not start the thread. You explicitly start the new thread by calling the start()method. The start() method calls the run() method you defined in your program. The start() method has no argument list and does not return any values. The following example illustrates how to create and start a new thread. Here’s what is displayed when this program runs: Main thread started Child thread started Child thread terminated Main thread terminated class MyThread implements Runnable{ Thread t; MyThread () { t = new Thread(this, “My thread"); t.start(); } public void run() { System.out.println("Child thread started"); System.out.println("Child thread terminated"); } }

class Demo { public static void main (String args[]){ new MyThread(); System.out.println("Main thread started"); System.out.println("Main thread terminated"); } } This example begins by defining a class called MyThread, which implements the Runnable interface. Therefore, we use the keyword implements to implement the Runnable interface. Next, a reference to a thread is declared. Defining the constructor for the class follows this. The constructor calls the constructor of the Thread class. Because we are implementing the Runnable interface, we need to pass the constructor reference to the instance of the class that will execute the new thread and the name of the new thread. Notice that we use the keyword this as reference to the instance of the class. The keyword this is a reference to the current instance of the class. The constructor returns a reference to the new thread, which is assigned to the reference declared in the first statement in the MyThread class definition. We use this reference to call the start() method. Remember that the start() method calls the run() method. Next,we define the run() method. Statements within the run() method become the portion of the program that executes when the thread executes. There are only two displayed statements in the run() method. Later in this chapter, we’ll expand the run() method to include more interesting statements. Next, we define the program class. The program class explicitly executes the new thread by creating an instance of the MyThread class. This is done by using the new operator and calling the constructor of MyThread. Using isAlive() and join() (Page 6 of 10 ) Typically, the main thread is the last thread to finish in a program. However, there isn’t any guarantee that the main thread won’t finish before a child thread finishes. In the previous example, we told the main method to sleep until the child threads terminate. However, we estimated the time it takes for the child threads to complete processing. If our estimate was too short, a child thread could terminate after the main thread terminates. Therefore, the sleep technique isn’t the best one to use to guarantee that the main thread terminates last. Programmers use two other techniques to ensure that the main thread is the last thread to terminate. These techniques involve calling the isAlive() method and the join() method. Both of these methods are defined in the Thread class. The isAlive() method determines whether a thread is still running. If it is, the isAlive() method returns a Boolean true value; otherwise, a Boolean false is returned. You can use the isAlive()

method to examine whether a child thread continues to run. The join() method works differently than the isAlive() method. The join() method waits until the child thread terminates and “joins” the main thread. In addition, you can use the join() method to specify the amount of time you want to wait for a child thread to terminate. The following example illustrates how to use the isAlive() method and the join() method in your program. This example is nearly the same as the previous example. The difference lies in the main() method of the Demo class definition. After the threads are declared using the constructor of the MyThread class, the isAlive() method is called for each thread. The value returned by the isAlive() method is then displayed on the screen. Next, the join() method is called for each thread. The join() method causes the main thread to wait for all child threads to complete processing before the main thread terminates. Here is what is displayed on the screen when this program runs: Thread Status: Alive Thread 1: true Thread 2: true Thread 3: true Thread 4: true Threads Joining. Thread: 1 Thread: 2 Thread: 3 Thread: 4 Terminating thread: 1 Terminating thread: 2 Terminating thread: 3 Terminating thread: 4 Thread Status: Alive Thread 1: false Thread 2: false Thread 3: false Thread 4: false Terminating thread: main thread. class MyThread implements Runnable { String tName; Thread t; MyThread (String threadName) { tName = threadName; t = new Thread (this, tName); t.start(); } public void run() { try {

System.out.println("Thread: " + tName ); Thread.sleep(2000); } catch (InterruptedException e ) { System.out.println("Exception: Thread " + tName + " interrupted"); } System.out.println("Terminating thread: " + tName ); } } class Demo { public static void main (String args []) { MyThread thread1 = new MyThread ("1"); MyThread thread2 = new MyThread ("2"); MyThread thread3 = new MyThread ("3"); MyThread thread4 = new MyThread ("4"); System.out.println("Thread Status: Alive"); System.out.println("Thread 1: " + thread1.t.isAlive()); System.out.println("Thread 2: " + thread2.t.isAlive()); System.out.println("Thread 3: " + thread3.t.isAlive()); System.out.println("Thread 4: " + thread4.t.isAlive()); try { System.out.println("Threads Joining."); thread1.t.join(); thread2.t.join(); thread3.t.join(); thread4.t.join(); } catch (InterruptedException e) { System.out.println( "Exception: Thread main interrupted."); } System.out.println("Thread Status: Alive"); System.out.println("Thread 1: " + thread1.t.isAlive()); System.out.println("Thread 2: " + thread2.t.isAlive()); System.out.println("Thread 3: " + thread3.t.isAlive()); System.out.println("Thread 4: " + thread4.t.isAlive()); System.out.println( "Terminating thread: main thread.");

} } Setting Thread Priorities

thread has an assigned priority that is used to let more important threads use resources ahead of lower-priority resources. Priority is used as a guide for the operating system to determine which thread gets accesses to a resource such as the CPU. In reality, an operating system takes other factors into consideration. Typically, programmers have little or no control over those other factors. Therefore, they establish a priority for their threads without further concern over those other factors. A priority is an integer from 1 to 10 inclusive, where 10 is the highest priority, referred to as the maximum priority, and 1 is the lowest priority, also known as the minimum priority. The normal priority is 5, which is the default priority for each thread. In general, a thread with a higher priority bumps a thread with a lower priority from using a resource. The lower-priority thread pauses until the higher-priority thread is finished using the resource. Whenever two threads of equal priority need the same resource, the thread that accesses the resource first has use of the resource. What happens to the second thread depends on the operating system under which your program is running. Some operating systems force the second thread to wait until the first thread is finished with the resource. Other operating systems require the first thread to give the second thread access to the resource after a specified time period. This is to ensure that one thread doesn’t hog a resource and prevent other threads from utilizing it. In the real world, the first thread usually pauses while using the resource because another resource it needs isn’t available. It is during this pause that the operating system has the first thread relinquish the resource. The problem is, you don’t know if and when the pause will occur. It is best to always cause a thread to pause periodically whenever the thread is using a resource for a long period time. In this way, the thread shares the resource with other threads. You learn how to pause a thread in the “Suspending and Resuming a Thread” section of this chapter. You need to keep in mind that there is a downside to periodically pausing a thread. Pausing a thread diminishes the performance of your program and could cause a backlog for use of the resource. Therefore, you need to monitor the performance of your program regularly to make sure you are not experiencing this negative aspect of pausing a thread. For now let’s focus on something you do have control over—setting the priority of a thread. You set a thread’s priority by calling the setPriority() method, which is defined in the Thread class. The setPriority() method requires one parameter, which is the integer representing the level of priority. You have two ways in which to represent the priority. You can use an integer from 1 to 10, or you can use final variables defined in the Thread class. These variables are MIN_PRIORITY, MAX_PRIOIRTY, and NORM_PRIOIRTY.

You can determine the priority level of a thread by calling the getPriority() method, which is also defined in the Thread class. The getPriority() method does not requires an argument, and it returns the integer representing the level of priority for the thread. The following example illustrates how to use the setPriority() and getPriority() methods. This example creates two child threads and sets the priority for each. First, the low-priority thread starts, followed by the high-priority thread. Here’s what is displayed when you run this program (notice that the high-priority thread runs ahead of the low-priority thread, even though the lowpriority thread started first):

low priority started high priority started high priority running. low priority running. low priority stopped. high priority stopped. class MyThread implements Runnable { Thread t; private volatile boolean running = true; public MyThread (int p, String tName) { t = new Thread(this,tName); t.setPriority (p); } public void run() { System.out.println(t.getName() + " running."); } public void stop() { running = false; System.out.println(t.getName() + " stopped."); } public void start() { System.out.println(t.getName() + " started"); t.start(); } } class Demo { public static void main(String args[] ) { Thread.currentThread().setPriority(10); MyThread lowPriority = new MyThread (3, "low priority"); MyThread highPriority = new MyThread (7, "high priority");

lowPriority.start(); highPriority.start(); try { Thread.sleep(1000); } catch ( InterruptedException e) { System.out.println("Main thread interrupted."); } lowPriority.stop(); highPriority.stop(); try { highPriority.t.join(); lowPriority.t.join(); } catch (InterruptedException e) { System.out.println( "InterruptedException caught"); } } } Synchronizing Threads A major concern when two or more threads share the same resource is that only one of them can access the resource at one time. Programmers address this concern by synchronizing threads, much the same way baseball players take turns being up to bat. Threads are synchronized in Java through the use of a monitor. Think of a monitor as an object that enables a thread to access a resource. Only one thread can use a monitor at any one time period. Programmers say that the thread owns the monitor for that period of time. The monitor is also called a semaphore. A thread can own a monitor only if no other thread owns the monitor. If the monitor is available, a thread can own the monitor and have exclusive access to the resource associated with the monitor. If the monitor is not available, the thread is suspended until the monitor becomes available. Programmers say that the thread is waiting for the monitor. Fortunately, the task of acquiring a monitor for a resource happens behind the scenes in Java. Java handles all the details for you. You do have to synchronize the threads you create in your program if more than one thread will use the same resource. You have two ways in which you can synchronize threads: You can use the synchronized method or the synchronized statement. The Synchronized Method All objects in Java have a monitor. A thread enters a monitor whenever a method modified by the keyword synchronized is called. The thread that is first to call the synchronized method is

said to be inside the method and therefore owns the method and resources used by the method. Another thread that calls the synchronized method is suspended until the first thread relinquishes the synchronized method. If a synchronized method is an instance method, the synchronized method activates the lock associated with the instance that called the synchronized method, which is the object known as this during the execution of the body of the method. If the synchronized method is static, it activates the lock associated with the class object that defines the synchronized method. Before you learn how to define a synchronized method in your program, let’s see what might happen if synchronization is not used in a program. This is the objective of the following example. This program displays two names within parentheses using two threads. This is a threestep process, where the opening parenthesis, the name, and the closing parenthesis are displayed in separate steps. The example defines three classes: the Parentheses class, the MyThread class, and the Demo class, which is the program class. The Parentheses class defines one method called display(), which receives a string in its argument list and displays the string in parentheses on the screen. The MyThread class defines a thread. In doing so, the constructor of MyThread requires two arguments. The first argument is a reference to an instance of the Parentheses class. The second argument is a string containing the name that will be displayed on the screen. The run() method uses the instance of the Parentheses class to call its display() method, passing the display() method the name that is to appear on the screen. The rest of the action happens in the main() method of the Demo class. The first statement declares an instance of the Parentheses class. The next two classes create two threads. Notice that both threads use the same instance of the Parentheses class. Here’s what is displayed when you run this program. It’s probably not what you expected to see. Each name should be enclosed within its own parentheses. The problem is that the display() method isn’t synchronized. class BlockingQueue extends Queue { public synchronized Object remove() { while (isEmpty()) { wait(); // really this.wait() } return super.remove(); } public synchronized void add(Object o) { super.add(o); notifyAll(); // this.notifyAll() } }

class Parentheses { void display(String s) { System.out.print ("(" + s); try { Thread.sleep (1000); } catch (InterruptedException e) { System.out.println ("Interrupted"); } System.out.println(")"); } } class MyThread implements Runnable { String s1; Parentheses p1; Thread t; public MyThread (Parentheses p2, String s2) { p1= p2; s1= s2; t = new Thread(this); t.start(); } public void run() { p1.display(s1); } } class Demo { public static void main (String args[]) { Parentheses p3 = new Parentheses(); MyThread name1 = new MyThread(p3, "Bob"); MyThread name2 = new MyThread(p3, "Mary"); try { name1.t.join();

name2.t.join(); } catch (InterruptedException e ) { System.out.println( "Interrupted"); } } } The problem with the previous example is that two threads use the same resource concurrently. The resource is the display() method defined in the Parentheses class. In order to have one thread take control of the display() method, we must synchronize the display() method. This is done by using the keyword synchronized in the header of the display() method, which is illustrated in the next example. Here’s what is displayed when you run the next example. This is what you expected to see in the previous example. (Bob) (Mary) class Parentheses { synchronized void display(String s) { System.out.print ("(" + s); try { Thread.sleep (1000); } catch (InterruptedException e) { System.out.println ("Interrupted"); } System.out.println(")"); } } class MyThread implements Runnable { String s1; Parentheses p1; Thread t; public MyThread (Parentheses p2, String s2) { p1= p2; s1= s2; t = new Thread(this); t.start(); } public void run() { p1.display(s1); }

} class Demo{ public static void main (String args[]) { Parentheses p3 = new Parentheses(); MyThread name1 = new MyThread(p3, "Bob"); MyThread name2 = new MyThread(p3, "Mary"); try { name1.t.join(); name2.t.join(); } catch (InterruptedException e ) { System.out.println( "Interrupted"); } } } Suspending and Resuming Threads There might be times when you need to temporarily stop a thread from processing and then resume processing, such as when you want to let another thread use the current resource. You can achieve this objective by defining your own suspend and resume methods, as shown in the following example. This example defines a MyThread class. The MyThread class defines three methods: the run() method, the suspendThread() method, and the resumeThread() method. In addition, the MyThread class declares the instance variable suspended, whose value is used to indicate whether or not the thread is suspended. The run() method contains a for loop that displays the value of the counter variable. Each time the counter variable is displayed, the thread pauses briefly. It then enters a synchronized statement to determine whether the value of the suspended instance variable is true. If so, the wait() method is called, causing the thread to be suspended until the notify() method is called. The suspendThread() method simply assigns true to the suspended instance variable. The resumeThread() method assigns false to the suspended instance variable and then calls the notify() method. This causes the thread that is suspended to resume processing. The main() method of the Demo class declares an instance of MyThread and then pauses for about a second before calling the suspendThread() method and displaying an appropriate message on the screen. It then pauses for about another second before calling the resumeThread() method and again displaying an appropriate message on the screen. The thread continues to display the value of the counter variable until the thread is suspended. The thread continues to display the value of the counter variable once the thread resumes processing. Here’s what is displayed when you run this program:

Thread: 0 Thread: 1 Thread: 2 Thread: 3 Thread: 4 Thread: Suspended Thread: Resume Thread: 5 Thread: 6 Thread: 7 Thread: 8 Thread: 9 Thread exiting. class MyThread implements Runnable { String name; Thread t; boolean suspended; MyThread() { t = new Thread(this, "Thread"); suspended = false ; t.start(); } public void run() { try { for (int i = 0; i < 10; i++) { System.out.println("Thread: " + i ); Thread.sleep(200); synchronized (this) { while (suspended) { wait(); } } } } catch (InterruptedException e ) { System.out.println("Thread: interrupted."); } System.out.println("Thread exiting."); } void suspendThread() { suspended = true; } synchronized void resumeThread() { suspended = false; notify(); } }

class Demo { public static void main (String args [] ) { MyThread t1 = new MyThread(); try{ Thread.sleep(1000); t1.suspendThread(); System.out.println("Thread: Suspended"); Thread.sleep(1000); t1.resumeThread(); System.out.println("Thread: Resume"); } catch ( InterruptedException e) { } try { t1.t.join(); } catch ( InterruptedException e) { System.out.println ( "Main Thread: interrupted"); } } } *Java io package: The Java Input/output (I/O) is a part of java.io package. The java.io package contains a relatively large number of classes that support input and output operations. The classes in the package are primarily abstract classes and stream-oriented that define methods and subclasses which allow bytes to be read from and written to files or other input and output sources. The InputStream and OutputStream are central classes in the package which are used for reading from and writing to byte streams, respectively. The java.io package can be categories along with its stream classes in a hierarchy structure shown below:

InputStream: The InputStream class is used for reading the data such as a byte and array of bytes from an input source. An input source can be a file, a string, or memory that may contain the data. It is an abstract class that defines the programming interface for all input streams that are inherited from it. An input stream is automatically opened when you create it. You cans explicitly close a stream with the close( ) method, or let it be closed implicitly when the object is found as a garbage. The subclasses inherited from the InputStream class can be seen in a hierarchy manner shown below:

InputStream is inherited from the Object class. Each class of the InputStreams provided by the java.io package is intended for a different purpose. OutputStream: The OutputStream class is a sibling to InputStream that is used for writing byte and array of bytes to an output source. Similar to input sources, an output source can be anything such as a file, a string, or memory containing the data. Like an input stream, an output stream is automatically opened when you create it. You can explicitly close an output stream with the close( ) method, or let it be closed implicitly when the object is garbage collected. The classes inherited from the OutputStream class can be seen in a hierarchy structure shown below:

OutputStream is also inherited from the Object class. Each class of the OutputStreams provided by the java.io package is intended for a different purpose. How Files and Streams Work: Java uses streams to handle I/O operations through which the data is flowed from one location to another. For example, an InputStream can flow the data from a disk file to the internal memory and an OutputStream can flow the data from the internal memory to a disk file. The disk-file may be a text file or a binary file. When we work with a text file, we use a character stream where one character is treated as per byte on disk. When we work with a binary file, we use a binary stream. The working process of the I/O streams can be shown in the given diagram.

Files:can read several types of information from files: binary, Java objects, text, zipped files, etc. One of the most common problems is reading lines of text. Example: Copy one file to another This example reads text files using the classes FileReader, BufferedReader, FileWriter, and BufferedWriter. It's a main program without a graphical user interface, reading from the console. To change this to a graphical user interface, use JFileChooser to get a File object instead console input. import java.io.*; public class CopyMultipleFiles{ public static void main(String[] args)throws IOException { BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter Number of files that have to be coppied:"); int n = Integer.parseInt(bf.readLine()); String fileName[] = new String[n]; for (int i=0; i 0){ out.write(buf, 0, len);

} in.close(); out.close(); } catch(FileNotFoundException ex){ System.out.println(ex.getMessage() + " in the specified directory."); System.exit(0); } catch(IOException e){ System.out.println(e.getMessage()); } } } GUI interface javax.swing.JFileChooser creates a standard file dialog and allows you to easily get a File object for reading or writing. See JFileChooser. Working with the text lines The above program does nothing with the lines of text except write them. Typically, you need to get values from the lines. There are several useful ways to extract data from the lines. 1. java.util.Scanner is very useful for parsing fields from a string / file.

Stream:-

Streams: *Streams:streams is a sequence of bytes. *It has to standard types:1.Input streamThe input streams class is super class of all input streams. it provides basic input methods for reading data from an input stream. 2.output streamoutput stream class is a super class of all output stream it provides

basic output method for writing data to an output stream

*Byte stream:This class uses a byte array as it's input source it has two constructors. 1.ByteArrayInputStream(byte ar[]); 2.ByteArrayInputStream(byte arr[],int start,int no of byts);

Import java.io.*; class bdemo { public static void main(String ar[])throws IOException { String tmp="ashwath"; byte b[]=tmp.getBytes(); //convert string into bytes ByteArrayInputStream in=new ByteArrayInputStream(b); for(int i=0;i
} else { System.out.println(character.toUpperCase((char)c)); } } System.out.println(); in.reset();// set the file pointer begining of file }

*ByteArrayOutputStream:This class uses a byte array at the destination it has to constructor 1.ByteArrayOutputStreamIt create a buffer of 32 byte to store the data. 2.ByteArrayOutputStream(int)It create buffer of size int *programe to file output stream import java.io.*; class bdemo { public static void main(String ar[])throws IOException { ByteArrayOutputStream f=new ByteArrayOutputStream(); String s="TMV University";

byte b[]=s.getBytes(); f.write(b1); System.out.println("buffer as a string"); System.out.println(f.toString()); System.out.println("buffer into array"); byte b2[]=f.toByteArray(); for(int i=0;i
1.FileInputStream f=new FileInputStream("temp.txt"); 2.File f=new File("temp.txt");

FileInputStream f2=new FileInputStream(f1); *programe to FileInputStream import java.io.*; class fileclass { public static void main(String ar[])throws IOException { fileInputStream in=new fileInputStream("temp.txt"); System.out.println("available bytes="+in.available()); in.skip(4); int n=in.available(); System.out.println("now available byts"+n); for(int i=0;i
*FileOutputStream f=new FileOutputStream("temp.txt"); file f1=new file("temp.txt"); fileOutputStream f2=new fileOutputStream(f1);

*DataStreamIt has two types DataInputStream & DataDataOutputStream ()

*DataInputStreamThis class is used with the data outstream vicaversa it can be used to read all primitive data types from the stream.

*programe on dataInputStream import java.io.*; class ddemo { public static void main(String ar[])throws IOException { String name; char c; int i; long l; DataInputStream d=new DataInputStream(System.in); try { System.out.println("enter name"); name=d.readLine(); System.out.println("enter integer"); i=Integer.parseInt(d.readLine()); System.out.println("enter the long integer");

l=Long.parseLong(d.readLine()); System.out.println("enter the character"); c=((char)System.in.read()); System.out.println("your name is="+name); System.out.println("integer value is="+i); System.out.println("long integer value is="+l); System.out.println("character is="+c); } catch(Exception e) {} }

*programe import java.io.*; class emp { public static void main(String ar[]) { String name[]=new String[5]; int code[]=new int[5]; Float sal[]=new Float[5]; DataInputStream d=new DataInputStream(System.in) try { for(i=0;i<5;i++)

{ System.out.println("enter empno"+i+1); name[i]=d.readLine(); System.out.println("enter empcode"); code[i]=Integer.parseInt(d.readLine()); System.out.println("enter the salary"); sal[i]=float.parseFloat(d.readLine()); } System.out.println("name is"+"code is"+"salary is"); for(int i=0;i<5;i++) { System.out.println(name[i]+" "+code[i]+" "+sal[i]); }

*DataOutputStream This class is used DataInputStream class. we can write primitive datatype to a stream. import java.io.*; class dataclass { public static void main(String ar[])throws IOException { FileOutputStream f=new FileOutputStream("d:\\myfile.txt"); DataOutputStream d=new DataOutputStream(f); d.write int(123); d.write char('a');

d.write Boolean(true); d.write Byte(12); FileInputStream f1=new FileInputStream("d:\\myfile.txt"); DataInputStream d1=new DataInputStream(f1); int a=d1.readInt(); System.out.println("integer="+a); byte b=d1.readByte(); System.out.println("byte is="+b); Boolean b1=d1.readboolean(); System.out.println("Boolean"+b1); char c=d1.readChar(); System.out.println("char "+c); } } filter streamIt is used to read data from one stream class we can write an primitive datatype to a stream. 1.FilterInputStream -: It is abstract class providing an interface for useful functionality to the other input stream classes.the following classes under the filter input stream. 1.BufferedInputStream 2.DataInputStream 3.PushBackInputStream

2.FilterOutputStreamIt is abstract class providing an interface for useful functionality to other

ouput stream classes.the following classes under the filter output stream. 1.BufferedoutputStream 2.DataOutputStream 3.PrintStream

1.BufferedInputStreamIt is use to prevent the physical read everytime when more data is readed. this class accept input by using a buffered array of bytes.

*Constructor 1.BufferedInputStream(InputStream obj); 2.BufferedInputStream(InputStream obj,int bufsize);

*BufferedOutputStream:It is use to prevent a physical write everytime when we send a piece of data.

*constructor 1.BufferedOutputStream(OutputStream o) 2.BufferedOutputStream(OutputStream,int bufsize); *Programe of BufferedInputStream import java.IO.*; class bufclass { public static void main(String ar[])throws IOException {

String s="ashwath"); byte b1=s.getBytes(); ByteArrayInputStream b=new ByteArrayInputStream(b1); BufferedInputStream buf=new BufferedInputStream (b); int c; while((c=buf.read()!=-1) System.out.println((char)c); for(int i=0;i
3.PushBackInputStreamIt has one byte pushbackBuffer so the last character read can be pushback. import java.io.*; class pdemo { public static void main(String ar[])throws IOException { String s="dog"; byte b[]=s.getBytes(); ByteArrayInputStream ba=new ByteArrayInputStream(b); PushbackInputStream p=new PushbackInputStream(ba); int c; while((c.p.read()!=-1) {

if(c=p.read())=='0') { System.out.print("\n"); p.unread(c); } else { System.out.print((char)c); } } } }

1.PrintStream -; It is use to produce the formatted output while data output stream handles the storage of data printStream handles display. Import java.io.*; class Psdemo { public static void main(String ar[]) { String s="shreya"; int cno=101; double sal=30.00; FileOutputStream f =new FileOutputStream("temp.txt");

PrintStream p=new PrintStream(f); p.println(s); p.println(cno); p.println(sal); } }

*LineNumberInputStream:A LineNumberInputStream is Filter input stream. that counts the number of line terminators as data is read from the input stream. *constructor LineNumberInputStream l=new LineNumberInputStream(file obj) programe: Import java.io.*; class lnum { public static void main(String ar[])throws IOException { int m=ar[0].charAt(0); FileInputStream in=new FileInputStream(c:\\temp.txt"); LineNumberInputStream l=new LineNumberInputStream(in); int ch; while((ch=l.read())!=-1) { if(ch==m)

{ System.out.println((char)ch+" "+l.getLineNumber()); } } }

*StreamTokenizer:It help to identify the patient in the input stream it is a responsible for breaking up the input stream it to tokens. A stream is tokenizer by creating a streamTokenizer with the file object as its source.The loop invoke the next token which returns the tokenbyte of next token. 1.TT_EOF:end of the file is reach 2.TT_EOL:end of line of found 3.TT_word:word is can the stream failed sval contains the word. 4.TT_NUMBERS:NUMBER is scan failed nval contains the value of number scan.

*import java.io.*; class streamdemo { public static void main(string ar[])throws IOException { FileInputStream fr=new FileInputstream("d:\\temp.txt"); StreamTokenizer s =new StreamTokenizer(fr);

int tok; int c=0; //counter string int c1=0; //counter Number while((tok=s.nextToken())!=StreamTokenizer.TT_EOF) { if(tok==StreamTokenizer.TT_WORD) { System.out.println("word found"+s.sval()); c++; } else if(tok==streamTokenizer.TT_NUMBER); { System.out.println("found"+c+"word and"+c1+"number in temp.txt"); } } } } *filereader:Convenience class for reading character files. The constructors of this class assume that the default character encoding and the default byte-buffer size are appropriate. To specify these values yourself, construct an InputStreamReader on a FileInputStream.

*constructor:1)FileReader(file f) 2)charArrayReader:-

It allows the use of character array as input stream it similar to byte array input stream. 3)StringReader:It reads a characters from a string. constructor:StringReader(string s) 4)InputStreamReader:It reads byte from input stream and convert them to character constructor:InputStreamReader(InputStream in) 5)FilterReader:It allows the reading of filter character stream. constructor: filterReader(Reader r) 6)BufferdReader:It accept a reader object as its parameter and adds a buffered of character it is useful becuase of its method readline() constructor:BufferedReader(Reader r)

***************************************************************************** * *)writer classes:The difference betn writer and output stream is that while writers are able to writes characters outputStreamWriterBytes 1) FilterWriter:It anables to write characters to files it is like fileoutputStream.

Constructor:FileWriter(file f); 2)charArrayWriter:It allows the use of a character buffer as an output stream it is same as byteArrayOutputStream. constructor:charArrayWriter(char ch[]) 3)PrintWriter:Print formatted representations of objects to a text-output stream. This class implements all of the print methods found in PrintStream. It does not contain methods for writing raw bytes, for which a program should use unencoded byte streams. PrintWriter(outputstream obj); 4)filterWriter:Abstract class for writing filtered character streams. filterWriter(Writer w); 5)BufferedWriter:Write text to a character-output stream, buffering characters so as to provide for the efficient writing of single characters, arrays, and strings.

The buffer size may be specified, or the default size may be accepted. The default is large enough for most purposes. constructor:BufferedWriter(writer w) 6)OutputStreamWriter:An OutputStreamWriter is a bridge from character streams to byte streams: Characters written to it are translated into bytes according to a specified character encoding. The encoding that it uses may be specified by name, or the platform's default encoding may be accepted. OutputStreamWriter(OutputStream obj);

*Programes for char stream Import java.io.*; public class cust { String name; String grade; String performance; String rating; InputStream r; BufferedReader b; FileOutputStream f; public cust() { try { r=new InputStreamReader(System.in); b=new BufferedReader(r); System.out.println("customer name"); name=b.readLine(); System.out.println("custmorGrader"); grade=b.readLine(); System.out.ptintln("custmor Performance"); performance =b.readLine(); System.out.println("custmor rating");

rating =b.readLine(); r.close(); b.close(); f=new FileOutputStream("custmor.txt"); String temp=name+";"+grade+";"+performance+";"+rating; System.out.println("finish details of custmor"); f.write(temp.getBytes()); f.close(); } catch(FileNotFoundException fn) {} } public static void main(String ar[]) { cust r=new cust(); } } Applet:-

Introduction In this section you will learn about the different components available in the Java AWT package for developing user interface for your program. Following some components of Java AWT are explained : 1. Labels : This is the simplest component of Java Abstract Window Toolkit. This

component is generally used to show the text or string in your application and label never perform any type of action. Syntax for defining the label only and with justification : Label label_name = new Label ("This is the label text.");

Above code simply represents the text for the label. Label label_name = new Label ("This is the label text.", Label.CENTER); Justification of label can be left, right or centered. Above declaration used the center justification of the label using the Label.CENTER. 2. Buttons : This is the component of Java Abstract Window Toolkit and is used to trigger

actions and other events required for your application. The syntax of defining the button is as follows : Button button_name = new Button ("This is the label of the button."); You can change the Button's label or get the label's text by using the Button.setLabel(String) and Button.getLabel() method. Buttons are added to the it's container using the add (button_name) method. 3. Check Boxes : This component of Java AWT allows you to create check boxes in your

applications. The syntax of the definition of Checkbox is as follows : CheckBox checkbox_name = new Checkbox ("Optional check box 1", false); Above code constructs the unchecked Checkbox by passing the boolean valued argument false with the Checkbox label through the Checkbox() constructor. Defined Checkbox is added to it's container using add (checkbox_name) method. You can change and get the checkbox's label using the setLabel (String) and getLabel() method. You can also set and get the state of the checkbox using the setState(boolean) and getState() method provided by the Checkbox class. 4. Radio Button : This is the special case of the Checkbox component of Java AWT

package. This is used as a group of checkboxes which group name is same. Only one Checkbox from a Checkbox Group can be selected at a time. Syntax for creating radio buttons is as follows : CheckboxGroup chkgp = new CheckboxGroup(); add (new Checkbox ("One", chkgp, false); add (new Checkbox ("Two", chkgp, false); add (new Checkbox ("Three",chkgp, false); In the above code we are making three check boxes with the label "One", "Two" and "Three". If you mention more than one true valued for checkboxes then your program takes the last true and show the last check box as checked. 5. Text Area: This is the text container component of Java AWT package. The Text Area

contains plain text. TextArea can be declared as follows: TextArea txtArea_name = new TextArea(); You can make the Text Area editable or not using the setEditable (boolean) method. If you pass the boolean valued argument false then the text area will be non-editable otherwise it will be editable. The text area is by default in editable mode. Text are set in

the text area using the setText(string) method of the TextArea class. 6. Text Field: This is also the text container component of Java AWT package. This

component contains single line and limited text information. This is declared as follows : TextField txtfield = new TextField(20); You can fix the number of columns in the text field by specifying the number in the constructor. In the above code we have fixed the number of columns to 20. 7. awt In this section, you will learn about the java.awt.*; package available with JDK. AWT stands for Abstract Windowing Toolkit. It contains all classes to write the program that interface between the user and different windowing toolkits. You can use the AWT package to develop user interface objects like buttons, checkboxes, radio buttons and menus etc. This package provides following interfaces and classes as follows: 8.

Interfaces and Descriptions of AWT Package: ActionEvent This interface is used for handling events. Adjustable This interface takes numeric value to adjust within the bounded range. Composite This interface defines methods to draw a graphical area. It combines a shape, text, or image etc. CompositeContext This interface allows the existence of several context simultaneously for a single composite object. It handles the state of the operations. ItemSelectable This interface is used for maintaining zero or more selection for items from the item list. KeyEventDispatcher The KeyEventDispatcher implements the current KeyboardFocusManager and it receives KeyEvents before despatching their targets. KeyEventPostProcessor This interface also implements the current KeyboardFocusManager. The KeyboardFocusManager receives the KeyEvents after that dispatching their targets. LayoutManager It defines the interface class and it has layout containers. LayoutManager2 This is the interface extends from the LayoutManager and is subinterface

MenuContainer Paint

PaintContext

PaintGraphics Shape Stroke

Transparency

of that. This interface has all menu containers. This interface is used to color pattern. It used for the Graphics2D operations. This interface also used the color pattern. It provides an important color for the Graphics2D operation and uses the ColorModel. This interface provides print a graphics context for a page. This interface used for represent the geometric shapes. This interface allows the Graphics2D object and contains the shapes to outline or stylistic representation of outline. This interface defines the transparency mode for implementing classes.

9.

Classes and Descriptions of AWT Package: AlphaComposite

AWTEvent AWTEventMulticaster

AWTKeyStroke

This class implements the basic alpha compositing rules. It combines the source and destination pixels to achieve transparency effects to graphics and images. This is a supper class of all AWT Events. This class implements thread-safe multi-cast event and it is despatching for the AWT event. The AWT events defined in the java.awt.event package. This class used to key action on the keyboard or equivalent input devices.

AWTPermission BasicStroke

BorderLayout

BufferCapabilities BufferCapabilities.FlipContents

Button Convas

CardLayout Chaeckbox

CheckboxGroup

CheckboxMenuItem

Choice

Color

This class uses for the AWT permissions. This class defines the basic set of rendering attributes for using outlines of graphics. This class uses to arranging the components. It has five components such as: east, west, north, south and the center. This class has properties of buffers. This class has a typesafe enumeration of buffer. It contains after page-flipping. This class used to create a label button It represents the blank rectanglular area on screen. It can draw or trap input events from the user. It is a layout manager for a comtainer. It is a graphical component. It has two states. True state that means "on" or false sate that means "off". This class to be used together multiple checkbox buttons. This class represents the checkbox and also include the menu. This class represents pop-up menu to user's choice. This class has colors. The default color is RGB color. Color

Component

ComponentOritentation

Container

ContainerOrderFocusTraversalPolicy

Cursor

DefultFocusTraversalPolicy

DefultKeyboardFocusManager

Dialog

Dimension

DisplayMode

library specify the all color, it identified by ColorSpace. This is a graphical representation to interacted by user. It displays on the screen. This class encapsulates the language-sensitive orientation. It also used the order the element of component or text.. A generic AWT container object has other AWT components. It determines the traversal order based on the order of child components in a container. This class represents the bitmap representation of the mouse cursor. This class determines the traversal order on the order of child components of container. This class used for handle the AWT applecations. This is a top label window. It has title and border. It can be used for taking a some input of users. This class describe the height and width of a component in a single object. This class encapsulates the bit depth, height, width and refresh rate of a GraphicsDevice.

Event

EventQueue

FileDialog

FlowLayout

FocusTraversalPolicy

Font

FontMetrics

Frame

GradientPaint

Graphics

Graphics2D

This class available only for the backwards compatilibility. It is a platform independent class. It has both classes underlying peer class and trusted application class. This class displays dialog window. Here user can be select the file. This class arrange the components and flow the left to right. It uses to write lines in a paragraph. This class defines the order in which components traverse particular focus cycle root. This class defines fonts and it uses render text that is visible. This class defines font matrix object.. It encapsulate the information and rendering the paritcular fonts. This class defines toplevel window and it designs the any area of border. With the help of GradientPaint you fill any shapes. This class uses to drawing all types of graphics such as: oval, rectangle etc. This class controls all geometry, coordinate

GraphicsConfigTemplate

GraphicsConfiguration

GraphicsDevice

GraphicsEnvironment

GridBagConstraints

GridBagLayout

GridLayout

Image

ImageCompabilities Insets

transformation, color management etc. It extends form the Graphics class. This class contains a valid GraphicConfiguration. This class describes the characteristics of graphics destination such as printer and monitor. This class describes the graphics devices and it available particular graphics environment. This class is a collection of GraphicsDevices object and Font objects. The GraphicsDevices objects are screen, images and printers etc. This class specify the constraint for components by using the GrideBagLayout class. This class uses the layout manager and uses the vertically and horizontally components. This class is a layout manager. It has rectangular grid components. This class is a supper class of all graphical images. It has compabilities and properties of images. This class represents all types of border's container. It includes borders, blank space and

titles. JobAttributes This class control the print job. JonAttributes.DefaultSelectionType It has default selection states and extends from the java.awt.AttributeValue package. JobAttributes.DestinatinType It possible for the job destinations and extends form the java.awt.AttributeValue package. JobAttributes.DialogType It displays the user dialog and extends from the java.awt.AttributeValue package. JobAttributes.MultipleDocumentHandlingType This class handles the multiple copy states and extends form the java.awt.AttributeValue package. JobAttributes.SidesType It uses multi-page impositions and extends from the java.awt.AttributeValue package. KeyboardFocusManager This class manage the current focus owner, active and focused windows Label It is a component which contains the text in container. List This component uses by the uses and it choose the list of item. MediaTracker This class has status of a number of media objects. It is a utility class. Menu It has pull-down menu components that

MenuBar

MenuComponent

MenuItem

MenuShortcut

PageAttributes PageAttributes.ColorType

PageAttributes.MediaType

PageAttributes.OrientationRequestedType

PageAttributes.OriginType

PageAttributes.PrintQualityType

Panel

displayed as like menu bar. This class has the concept of menu bar and it also bounded into a frame. This is supper class of all menu related components. This is a supper class and it represents the item of menu. This class represents the handling MenuItem through help of keyboard . It controls the output of the printed page. It handles the color states and extends form the java.awt.AttributeValue package. It handles the paper size and extends from the java.awt.AttributeValue package. It handles the possible orientations and extends from the java.awt.AttributeValue package. It handles the origins and extends from the java.awt.AttributeValue package. It handles the print qualities and extends from the java.awt.AttributeValue package. This is a simplest container class. It includes components

Point

Polygon

PopupMenu

PrintJob

Rectangle

RenderingHints

RenderingHints.Key

Robot

Scrollbar

ScrollPane

and other panels. It extends Container and implements to Accessible. The point represents the location of coordinate (x, y) space. It extends Point2D. It has two dimensional region and it bounded by the multiple number of lines. It extends the Menu and specify the positions of components. This class executes a print job and extends from the Object. A rectangle object has length and width and it also specify an area in a coordinate space. It extends Rectangle2D. This class contains rendering hints by using the Graphics2D class. This class used to control the randering and imaging pipelines. This class used to generate the native system input events and it automatically test the java platform implementations. This class provide the user interface components and also include the scroll bar. Which implements the Adjustable interface. It includes the horizontal and vertical scrolling for a single child

ScrollPaneAdjustable

SystemColor

TextArea TextComponent

TextField

TexturePaint

Toolkit

Window

components. The horizontal and vertical state represented by the ScrollPaneAdjustable objects. This class represents the state of horizontal and vertical scrollbar of ScrollPane. This class represents the system's color through the symbolic representation color. The value depends on the actual value of RGB. It displays multi line text. This is a supper class of any component. It allows to editing the some text. It has text component and It allows to editing a single line of text. It provides a way to fill a shape with a texture and specify by the BufferedImage. This is a supper class of all Abstract Windowing Toolkit. It is a top-level window. It has not borders and menubar. It capable for generating the window events like: WindowOpend, WindowClosed.

10.

Exceptions and Descriptions of AWT Package: AWTException This signal displays when an Abstract Windowing Toolkit exception has occurred. FontFormatException When the specified font is bad then this exception to be occurred.

It thrown by the createFont method in the Font class. HeadlessException This exception to be occurs when the codes are not supported by the keyboard, display and Mouse. IllegalComponentStateException The AWT has not suitable state for the requesting operation then it thrown by the IllegalComponentStateException. AWTError It thrown when the Abstract Windowing Toolkit error has occurred.



Difference between applet and swing package.

Swing is light weight Component. Applet is heavy weight Components 2. Swing Using UIManager. Swing has looked and feel according to user view u can change look and feel. Applet Does not provide this facility 3.Swing uses for stand-alone Applications, Swing have main method to execute the program. Applet needs HTML code for Run the Applet 4. Swing uses MVC Model view Controller. Applet not 5. Swings have its own Layout...like most popular Box Layout Applet uses Awt Layouts..Like flowlayout 6. Swings have some Thread rules. Applet doesn’t have any rule. 7. To execute Swing no need any browser By which we can create stand alone application But Here we have to add container and maintain all action control within frame container. To execute Applet programs we should need any one browser like Appletviewer, web browser. Because Applet using browser container to run and all action control within browser container. Examples:-

import java.awt.*; import java.applet.*; // public class GuiExample extends Applet { // A Button to click

Button okButton; // A textField to get text input TextField nameField; // A group of radio buttons // necessary to only allow one radio button to be selected at the same time. CheckboxGroup radioGroup; // The radio buttons to be selected Checkbox radio1; Checkbox radio2; // An independant selection box Checkbox option;

public void init() { // Tell the applet not to use a layout manager. setLayout(null); // initialze the button and give it a text. okButton = new Button("A button"); // text and length of the field nameField = new TextField("A TextField",100); // initialize the radio buttons group radioGroup = new CheckboxGroup(); // first radio button. Gives the label text, tells to which // group it belongs and sets the default state (unselected) radio1 = new Checkbox("Radio1", radioGroup,false);

// same but selected radio2 = new Checkbox("Radio2", radioGroup,true); // Label and state of the checkbox option = new Checkbox("Option",false); // now we will specify the positions of the GUI components. // this is done by specifying the x and y coordinate and //the width and height. okButton.setBounds(20,20,100,30); nameField.setBounds(20,70,100,40); radio1.setBounds(20,120,100,30); radio2.setBounds(140,120,100,30); option.setBounds(20,170,100,30); // now that all is set we can add these components to the applet add(okButton); add(nameField); add(radio1); add(radio2); add(option); } } ActionExample: import java.awt.*; import java.applet.*;

// import an extra class for the ActionListener

import java.awt.event.*; //

// Tells the applet you will be using the ActionListener methods.

public class ActionExample extends Applet implements ActionListener { Button okButton; Button wrongButton; TextField nameField; CheckboxGroup radioGroup; Checkbox radio1; Checkbox radio2; Checkbox radio3; public void init() { // Now we will use the FlowLayout setLayout(new FlowLayout()); okButton = new Button("Action!"); wrongButton = new Button("Don't click!"); nameField = new TextField("Type here Something",35); radioGroup = new CheckboxGroup(); radio1 = new Checkbox("Red", radioGroup,false); radio2 = new Checkbox("Blue", radioGroup,true); radio3 = new Checkbox("Green", radioGroup,false);

add(okButton); add(wrongButton); add(nameField); add(radio1); add(radio2); add(radio3); // Attach actions to the components okButton.addActionListener(this); wrongButton.addActionListener(this); } // Here we will show the results of our actions public void paint(Graphics g) { // If the radio1 box is selected then radio1.getState() will // return true and this will execute if (radio1.getState()) g.setColor(Color.red); // If it was not red we'll try if it is blue else if (radio2.getState()) g.setColor(Color.blue); // Since always one radiobutton must be selected it must be green else g.setColor(Color.green); // Now that the color is set you can get the text out the TextField // like this g.drawString(nameField.getText(),20,100); } // When the button is clicked this method will get automatically called

// This is where you specify all actions. public void actionPerformed(ActionEvent evt) { // Here we will ask what component called this method if (evt.getSource() == okButton) // So it was the okButton, then let's perform his actions // Let the applet perform Paint again. // That will cause the aplet to get the text out of the textField // again and show it. repaint(); // Actions of the wrongButton else if (evt.getSource() == wrongButton) { // Change the text on the button for fun wrongButton.setLabel("Not here!"); // Changes the text in the TextField nameField.setText("That was the wrong button!"); // Lets the applet show that message. repaint(); } } } ImageExample:/* This applet will display a gif on screen

for now the gif file must be in the same directory as this applet */ import java.awt.*; import java.applet.*; // These classes are for Url's. import java.net.*; // public class ImageExample extends Applet { // Your image name; Image my_gif; // The applet base URL URL base; // This object will allow you to control loading MediaTracker mt; public void init() { // initialize the MediaTracker mt = new MediaTracker(this); // The try-catch is necassary when the URL isn't valid // Ofcourse this one is valid, since it is generated by // Java itself. try { // getDocumentbase gets the applet path. base = getDocumentBase();

} catch (Exception e) {} // Here we load the image. // Only Gif and JPG are allowed. Transparant gif also. my_gif = getImage(base,"4.jpg"); // tell the MediaTracker to kep an eye on this image, and give it ID 1; mt.addImage(my_gif,1); // now tell the mediaTracker to stop the applet execution // (in this example don't paint) until the images are fully loaded. // must be in a try catch block. try { mt.waitForAll(); } catch (InterruptedException e) {} // when the applet gets here then the images is loaded. } public void paint(Graphics g) { // now we are going to draw the gif on the screen // (image name,x,y,observer); g.drawImage(my_gif,20,20,this); // you can resize the image easily g.drawImage(my_gif,20,140,30,40,this);

}

} Swing:The Java Swing provides the multiple platform independent APIs interfaces for interacting between the users and GUIs components. All Java Swing classes imports form the import javax.swing.*; package. Java provides an interactive features for design the GUIs toolkit or components like: labels, buttons, text boxes, checkboxes, combo boxes, panels and sliders etc. All AWT flexible components can be handled by the Java Swing. The Java Swing supports the plugging between the look and feel features. The look and feel that means the dramatically changing in the component like JFrame, JWindow, JDialog etc. for viewing it into the several types of window. Here the following APIs interfaces and classes are available: The following interfaces and it's descriptions to be used by the Java swing. Interfaces

Descriptions

Action

This interface performed the action with the ActionListener where the multiple controls are used for same purposes.

BoundedRangeModel

This interface defines the data model of components like: sliders and progressBars.

ButtonModel

It defines the state model for the buttons like: radio buttons, check boxes etc.

CellEditor

This interface used by the developer for creating the new editor and it has the new components implement interfaces. The CellEditor implements the wrapper based approach.

ComboBoxEditor

In this interface, the editor component used to JComboBox components.

ComboBoxModel

This interface represents the data model in a list model with the selected items.

DesktopManager

This interface has JDesktopPane object. The JInternalFrameimplements in the JDesktopPane with the help of DesktopManager.

Icon

This interface used to graphical representation of the components. It has fixed size picture.

JComboBox.KeySelectionManager This interface has KeySelectionManager and used for the

combo box data model. ListCellRenderer

This interface used for paint the cell in the list with the help of "rubber stamps" .

ListModel

This interface used for JList components method. It gets the value of each cell of list.

ListSelectionModel

This interface indicates the components, which are stable or not.

MenuElement

This interface used where the any components are implements in the menu.

MutableComboBoxModel

This interface extends from the ComboBoxModel. It is a mutable version of ComboBoxModel.

Renderer

It defines the requirements of an object for displaying the values.

RootPaneContainer

This interface uses the RootPane properties and it has the components like: JFrame, JInternalFrame and JWindow etc.

Scrollable

This interface provides the scrolling to show the large amount of data with the help of JScrollPane.

ScrollPaneConstants

This interface used for JScrollPane components.

SingleSelectionModel

This interface used to select the one index in a model.

SwingConstants

You can set the components on the screen to own requirements.

UIDefaults.ActiveValue

It constructs the DefaultListCellRenderer.

UIDefaults.LazyValue

This enables one to store an entry in the default table. The entered value is not constructed until first time is a real value is created through it usingLazyValue.createValue() method.

WindowConstants

This interface has two methods setDefaultCloseOperation and getDefaultCloseOperation and provides the window close opration.

The following classes and it's descriptions to be used by the Java swing. Classes

Descriptions

AbstractAction

This class handles the any types of action and provides JFC Action interface.

AbstractButton

This class defines the nature of buttons and menu items.

AbstractCellEditor

It provides a list and contents of the data model.

AbstractListModel

This class defines the data model which provides the list with its contents.

ActionMap

This class works with InputMap and performs any action when the key is pressed.

BorderFactory

This class extends from Object and creates the Border instance in the factory.

Box

It provides the fixed spaces between two components and uses theBoxLayout object of the layout manager.

Box.Filler

This class participates in the Layout and uses the lightweight components.

BoxLayout

This class uses the arranging the multiple components either horizontally or vertically. The Box container uses this class.

ButtonGroup

This class used to create the multiple buttons in a ButtonGroup object.

CellRandererPane

This class used to insert the components like: JList, JTable and JTree.

ComponentInputMap

This class has ComponentInputMap constructor and creates the components with the help of InpuMap.

DebugGraphics

It extends from the Graphics and used to debug the graphics

DefaultBoundedRangeModel

This class provides the implementation of default BoundedRangeModel.

DefaultButtonModel

This class implements the generic ButtonModel.

DefaultCellEditor

It implements the TableCellEditor and TreeCellEditor for the table and tree cells.

DefaultComboBoxModel

It provides the default model for combo boxes.

DefaultDesktopManager

It implements the DesktopManager. The DesktopManager has the JInternalFrame for creating the internal fame in a frame.

DefaultFocusManager

It provides the implementing the FocusManager.

DefaultListCellRanderer

It implements the default ListCellRanderer.

DefaultListCellRanderer.UIResource This extends the DefaultListCellRanderer and implementing in theUIResource. DefaultListModel

It extends the AbstractListModel and implementing thejava.util.Vector.

DefaultListSelectionModel

This class used for select the list in a data model.

DefaultSingleSelectionModel

This class provides the default SingleSelectionModel.

FocusManager

It handles all focus like: gainedFocus and lostFocus.

GrayFilter

It extends the RGBImageFilter and used for disabling the image through the button.

ImageIcon

This class implements the Icon and paints the icons from the images.

InputMap

This class uses the ActionMap to performed the action when you press any key of keyboard. It bounds data between the input event and an object.

InputVerifier

This class helps you when you works with the text fields through the focus.

JApplet

This class extends the Applet and implements the Accessible andRootPaneContainer.

JButton

This class extends the AbstractButton and you can create the new button.

JCheckBox

This class extends the JToggleButton and implements the check box in which buttons are selected or deselected.

JCheckBoxMenuItem

It extends the JMenuItem and determines the items which is selected or deselected.

JColorChooser

It extends the JComponent and implementing the Accessable. Here, you choose and manipulate the colors.

JComboBox

This class extends the JComboBox. It provides the dropdown list where user select only one item or value at a time. But combo box is a combination of multiple text or buttons etc.

JComponent

In java swing, All components are used the JComponent except the top-level containers like: JFrame, JDialog etc.

JDesktopPane

This class extends the JLayeredPane and when you create the object of JInternalFrame to be maintained in the JDesktopPane. The JDesktopPane has DesktopManager.

JDialog

It extends the Dialog. This class used to create the dialog window and when you want to create the custom dialog window with the help ofJOptionPane method.

JEditorPane

This class extends the JTextComponent. It edits the component by the EditorKit.

JFileChooser

This class provides the facility to choosing the file.

JFrame

It extends the Frame and supports the swing components architecture.

JInternalFrame

This class extends from the JComponent and provides the facility to dragging, closing, resizing and menu bar of the internal frame. The JInternalFrame added into the JDesktopPane.

JInternalFrame.JDesktopIcon

It displays the desktop icon and create the instance of JInternalFrame and iconify.

JLabel

This class used to show the small text and image.

JLayeredPane

It has JFC/Swing container that can be used to overlap the

components to each other. JList

This class used to create a list where you select the one or more than objects.

JMenu

This class used to create a new menu where you add the JMenuItems. When you select the item then shows the popup menu items in the JMenuBar.

JMenuBar

It used to create a new menu bar where the JMenu objects are added.

JMenuItem

This class used to create new menu items in the mebus.

JOptionPane

It used to create some different types of dialog box like: message dialog box, error dialog box etc.

JPanel

It extends the JComponent and used to create a new panel.

JPassworkField

It provides the single line text editing. Here, don't available the original characters but view type indication characters are available.

JPopupMenu

This class used to create a popup menu. It provides small window where the various types of choices are available.

JPopupMenu.Separator

Here the popup menu and the separator are available.

JProgressBar

It shows the integer types values in percent within a bounded range to determine the working process.

JRadioButton

It implements the radio button and shows the state of an item selected or deselected.

JRadioButtonMenuItem

It extends the JMenuItem and implements the radio button menu item

JRootPane

This class provides the component behind the scenes by JFrame, JWindow, JDialog etc. for providing the taskorientation and functionality.

JScrollBar

This class used to create a scroll bar. It provides the view content area where you show the content to scroll this.

JScrollPane

It provides the scrollable view components.

JSeparator

This class use the separator among the components.

JSlider

This class provides a control to represent a numeric value by dragging the slider.

JSplitPane

This class used to divides the two components graphically like: top and button, left and right.

JTabbedPane

This class provides the tab component through which you can switch from one component to another component regarding to the specific tab button by clicking on that.

JTable

It provides the user interface component and represents the two dimensional data.

JTextArea

It provides the multi line plain text area.

JTextField

It provides the facility to editing the text in a single line.

JTextPane

This class provides the component like JTexArea for multiple lines text with more capabalities.

JToggleButton

It implements two state button that means selected or deselected.

JToggleButton.ToggleButtonModel It extends the DefaultButtonModel and provides the ToggleButtonmodel. JToolBar

It provides set of command buttons icons that performs the different actions or controls.

JToolBar.Separator

It provides the tool bar separator.

JToolTip

It shows the tool tips related to it's components.

JTree

It shows the data in a hierarchical way.

JTree.DynamicUtilTreeNode

This extends the DefaultMutableTreeNode and create children nodes.

JTree.EmptySelectionModel

It does not allows the any selection.

JViewPort

It gives you about the underlying information.

JWindow

It extends window and shows the any location or area on the desktop. It couldn't any title bar and window management buttons.

KeyStroke

This class controls the key events on the keyboard for the equivalent device.

LayoutFocusTraversalPolicy

This class conducts the sorting objects according to their size, type, position or orientation.

LookAndFeel

It provides the dramatically changes in the component like frame related to the graphics for the application. Through this the application can be done very efficient and easier.

MenuSelectionManager

It has menu selection hierarchy.

OverlayLayout

The layout manager arrange the components.

ProgressMonitor

This class is used to monitoring the progress of any operation to be done.

ProgressMonitorInputStream

This class creates a progress monitor to monitor the progress of reading input from the input stream. It cleanups all the rights when the stream is closed.

RepaintManager

This class manage and override the repaint requests.

ScrollPaneLayout

It implements the LayoutManager and manage the components like: scroll bar, row header, column header etc.

ScrollPaneLayout.UIResource

It extends the ScrollPaneLayout and implements the UIResource.

SizeRequirements

It calculates the size and positions of components.

SizeSequence

It represents the order list of size and it's positions.

SwingUtilities

This class has utilities methods for swing.

Timer

Actions perform the predefined rate.

ToolTipManager

It manages the all tool tips.

UIDefaults

It extends the Hashtable and you set/get the value with

the help of UIManager. UIDefaults.LazyInputMap

This class creates a Input Map through it's createValue() method. The array of key after binding is passed to the constructor of this. Example of binding of key is array of pressing key information (e.g. ctrl + c or alt + f).

UIDefaults.ProxyLazyValue

This class is used to create a lazy value which is used to delay loading of the class to create instance for that.

UIManager

This class has track of the current look and feel details.

UIManager.LookAndFeelInfo

This is the nested class of UIManager class i.e. used for getting information about all the look and feels installed with the softwaredevelopment kit.

ViewportLayout

It implements the LayoutManager and defines the policy for the layout.

The following Exceptions and it's description to be used by the Java swing. Exception

Descriptions

UnsupportedLookAndFeelException

This exception occurred when the look and feel classes are not supported to user's system.

import java.awt.*; import javax.swing.*; public class Applet2 extends JApplet { private Container Panel; public Applet2 () { super (); Panel = getContentPane(); Panel.setBackground (Color.cyan); } public void paint (Graphics g) { int Width;

int Height; super.paint (g); Width = getWidth(); Height = getHeight(); g.drawString ("The applet width is " + Width + " Pixels", 10, 30); g.drawString ("The applet height is " + Height + " Pixels", 10, 50); } } import javax.swing.*; import java.awt.*; import java.awt.event.*; public class Frame1 extends JFrame { private Closer Handler; private JLabel Tag; Frame1 () { Container Pane; Handler = new Closer (); Tag = new JLabel (); Pane = getContentPane (); setTitle ("JFrame Example"); setSize (300,120); Tag.setText ("JLabel"); Pane.add (Tag); addWindowListener (Handler); show (); } public static void main (String args[]) { JFrame f; f = new Frame1 (); } } class Closer extends WindowAdapter { public void windowClosing (WindowEvent event) { System.exit (0); } } import java.awt.event.*; import java.awt.*; import javax.swing.*;

import java.awt.geom.*; public class JPanel1 extends JApplet implements ActionListener { JPanel InputPanel; JLabel Tag; JTextField Entry; CircleCanvas Drawing; public JPanel1 () { LayoutManager Layout; Container Pane; Layout = new FlowLayout (); InputPanel = new JPanel (); Tag = new JLabel (); Entry = new JTextField (); Drawing = new CircleCanvas (); Pane = getContentPane (); InputPanel.setLayout (Layout); Tag.setText ("Diameter "); Tag.setHorizontalAlignment (JLabel.RIGHT); Entry.setColumns (8); Entry.setText ("10"); Entry.setHorizontalAlignment (JTextField.RIGHT); Entry.addActionListener (this); InputPanel.add (Tag); InputPanel.add (Entry); Pane.add (InputPanel, BorderLayout.NORTH); Pane.add (Drawing, BorderLayout.CENTER); } public void actionPerformed (ActionEvent e) { int Diameter; String Text; Text = Entry.getText (); Diameter = Integer.parseInt (Text); Drawing.setDiameter (Diameter); Drawing.repaint (); } } class CircleCanvas extends Canvas {

int Diameter; public CircleCanvas () { setBackground (Color.yellow); } public void setDiameter (int Value) { Diameter = Value; repaint (); } public void paint (Graphics g) { Graphics2D g2; Ellipse2D Circle; int Width; int Height; g2 = (Graphics2D) g; g2.setColor (Color.black); Width = getWidth (); Height = getHeight (); Circle = new Ellipse2D.Double ((double) ((Width - Diameter) / 2), (double) ((Height - Diameter) / 2), (double) Diameter, (double)Diameter); g2.fill (Circle); } } Java Swing Controls Sampler

import java.awt.*; import javax.swing.*; public class Controls extends JApplet { private JButton DemoButton; private JCheckBox DemoCheckBox; private JComboBox DemoComboBox; private JLabel DemoLabel; private JList DemoList; private JPasswordField DemoPassword; private JRadioButton DemoRadioButton; private JScrollBar DemoScrollbar;

private JSlider DemoSlider; private JTextArea DemoTextArea; private JTextField DemoTextField; private LayoutManager Layout; public Controls () { Container Panel; String [] ListData; DemoButton = new JButton(); DemoCheckBox = new JCheckBox(); DemoComboBox = new JComboBox(); DemoLabel = new JLabel(); DemoList = new JList(); DemoPassword = new JPasswordField(); DemoRadioButton = new JRadioButton(); DemoScrollbar = new JScrollBar(); DemoSlider = new JSlider(); DemoTextArea = new JTextArea (3, 15); DemoTextField = new JTextField(); Layout = new FlowLayout (); ListData = new String [2]; Panel = getContentPane(); Panel.setLayout (Layout); Panel.setBackground (Color.green); ListData [0] = "JList"; ListData [1] = "Selection"; Panel.add (DemoLabel); Panel.add (DemoButton); Panel.add (DemoRadioButton); Panel.add (DemoCheckBox); Panel.add (DemoTextField); Panel.add (DemoPassword); Panel.add (DemoTextArea); Panel.add (DemoComboBox); Panel.add (DemoList); Panel.add (DemoSlider); Panel.add (DemoScrollbar); DemoLabel.setText ("JLabel"); DemoButton.setText ("JButton"); DemoCheckBox.setText ("JCheckbox"); DemoComboBox.addItem ("JComboBox");

DemoComboBox.addItem ("Selection"); DemoList.setListData (ListData); DemoPassword.setText ("JPasswordField"); DemoRadioButton.setText ("JRadioButton"); DemoTextArea.setText ("JTextArea"); DemoTextField.setText ("JTextField"); } } import java.awt.*; import java.awt.event.*; import javax.swing.*; public class Button1 extends JApplet implements ActionListener { /* Declaration */ private Container Panel; private LayoutManager Layout; private JButton Button1; private JButton Button2; private JButton Button3; private JTextField Command; public Button1 () { /* Instantiation */ Layout = new FlowLayout (); Panel = getContentPane (); Button1 = new JButton ("Red Background"); Button2 = new JButton ("Yellow Background"); Button3 = new JButton (); Command = new JTextField ("ActionCommand", 20); /* Location */ Panel.setLayout (Layout); Panel.add (Button1); Panel.add (Button2); Panel.add (Button3); Panel.add (Command); /* Configuration */ Button1.addActionListener (this); Button1.setActionCommand ("red"); Button2.setEnabled (false); Button2.addActionListener (this); Button3.addActionListener (this); Command.setEditable (false);

/* Decoration */ Button3.setBackground (Color.black); Button3.setForeground (Color.white); Button3.setText ("White on Black"); Panel.setBackground (Color.yellow); } public void actionPerformed(ActionEvent e) { String Action; Action = e.getActionCommand (); if (Action.equals ("red")) { Panel.setBackground (Color.red); Button1.setEnabled (false); Button2.setEnabled (true); } else if (Action.equals ("Yellow Background")) { Panel.setBackground (Color.yellow); Button1.setEnabled (true); Button2.setEnabled (false); } else if (Action.equals ("White on Black")) { Command.setBackground (Color.black); Command.setForeground (Color.white); Button3.setBackground (Color.white); Button3.setForeground (Color.black); Button3.setText ("Black on White"); } else if (Action.equals ("Black on White")) { Command.setBackground (Color.white); Command.setForeground (Color.black); Button3.setBackground (Color.black); Button3.setForeground (Color.white); Button3.setText ("White on Black"); } Command.setText (Action); } }

import java.awt.*; import java.awt.event.*; import javax.swing.*; public class CheckBox1 extends JApplet implements ItemListener { /* Declaration */ private Container Panel; private LayoutManager Layout;

private JCheckBox Bold; private JCheckBox Italic; private JTextField Result; public CheckBox1 () { /* Instantiation */ Layout = new FlowLayout (); Bold = new JCheckBox ("Bold"); Italic = new JCheckBox ("Italic", true); Result = new JTextField ("", 25); Panel = getContentPane (); /* Location */ Panel.setLayout (Layout); Panel.add (Bold); Panel.add (Italic); Panel.add (Result); Panel.setBackground (Color.yellow); /* Configuration */ Bold.addItemListener (this); Italic.addItemListener (this); Result.setEditable (false); /* Decoration */ Bold.setBackground (Color.yellow); Italic.setBackground (Color.yellow); /* Initialization */ setState (); } private void setState () { String Text; int Style; Font ShowFont; Text = "14 point"; Style = 0; if (Bold.isSelected()) { Style = Style | Font.BOLD; Text += " boldface"; } else { Text += " regular weight"; }

if (Italic.isSelected()) { Style = Style | Font.ITALIC; Text += " Italic"; } else { Text += " Roman"; } Text += " font"; ShowFont = new Font ("SansSerif", Style, 14); Result.setFont (ShowFont); Result.setText (Text); } public void itemStateChanged(ItemEvent e) { setState (); } } import java.awt.*; import java.awt.event.*; import javax.swing.*; public class ComboBox1 extends JApplet implements ItemListener { private Container Panel; private LayoutManager Layout; private JComboBox Selector; private String [] ColorList; private Font SansSerif; public ComboBox1 () { /* Instantiation */ Layout = new FlowLayout (); ColorList = new String [9]; SansSerif = new Font ("SansSerif", Font.BOLD, 14); ColorList [0] = "Red"; ColorList [1] = "Magenta"; ColorList [2] = "Blue"; ColorList [3] = "Cyan"; ColorList [4] = "Green"; ColorList [5] = "Yellow"; ColorList [6] = "White"; ColorList [7] = "Gray"; ColorList [8] = "Black"; Selector = new JComboBox (ColorList);

/* Location */ Panel = getContentPane (); Panel.setLayout (Layout); Panel.add (Selector); Panel.setBackground (Color.yellow); /* Configuration */ Selector.addItemListener (this); /* Decoration */ Selector.setForeground (Color.red); Selector.setFont (SansSerif); /* Initialization */ Selector.setSelectedIndex (5); Selector.setBackground (Color.yellow); } public void itemStateChanged(ItemEvent e) { int Selection; Selection = Selector.getSelectedIndex(); if (Selection == 0) { Panel.setBackground (Color.red); } else if (Selection == 1) { Panel.setBackground (Color.magenta); } else if (Selection == 2) { Panel.setBackground (Color.blue); } else if (Selection == 3) { Panel.setBackground (Color.cyan); } else if (Selection == 4) { Panel.setBackground (Color.green); } else if (Selection == 5) { Panel.setBackground (Color.yellow); } else if (Selection == 6) { Panel.setBackground (Color.white); } else if (Selection == 7) { Panel.setBackground (Color.gray); } else if (Selection == 8) { Panel.setBackground (Color.black); } } } import java.awt.*;

import java.awt.event.*; import javax.swing.*; public class Label1 extends JApplet { /* Declaration */ private Container Panel; private LayoutManager Layout; private JLabel Label1; private JLabel Label2; private JLabel Label3; private JLabel Label4; private JLabel Label5; private JLabel Label6; private JLabel Label7; public Label1 () { /* Instantiation */ Layout = new GridLayout (7, 1); Label1 = new JLabel ("A Simple Label"); Label2 = new JLabel ("A Label with LEFT alignment", JLabel.LEFT); Label3 = new JLabel ("A Label with CENTER alignment", JLabel.CENTER); Label4 = new JLabel ("A Label with RIGHT alignment", JLabel.RIGHT); Label5 = new JLabel ("A Label with LEADING alignment", JLabel.LEADING); Label6 = new JLabel ("A Label with TRAILING alignment", JLabel.TRAILING); Label7 = new JLabel (); Panel = getContentPane (); /* Location */ Panel.setLayout (Layout); Panel.add (Label1); Panel.add (Label2); Panel.add (Label3); Panel.add (Label4); Panel.add (Label5); Panel.add (Label6); Panel.add (Label7); /* Decoration */ Panel.setBackground (Color.yellow); Label7.setHorizontalAlignment (JLabel.CENTER); Label7.setForeground (Color.blue); Label7.setText ("Text added with setText"); } }

import java.awt.*; import java.awt.event.*; import javax.swing.*; public class PasswordField1 extends JApplet implements ActionListener { /* Declaration */ private JPasswordField Input; private JTextField Echo; private Container Panel; private LayoutManager Layout; public PasswordField1 () { /* Instantiation */ Input = new JPasswordField ("Input", 20); Echo = new JTextField ("Echo", 20); Layout = new FlowLayout (); Panel = getContentPane (); /* Location */ Panel.setLayout (Layout); Panel.add (Input); Panel.add (Echo); /* Decoration */ Input.setBackground (Color.green); Echo.setEditable (false); Panel.setBackground (Color.yellow); /* Configuration */ Input.addActionListener (this); } public void actionPerformed (ActionEvent e) { char [] Chars; String Word; Chars = Input.getPassword(); Word = new String(Chars); Echo.setText (Word); } }

import java.awt.*; import java.awt.event.*; import javax.swing.*;

public class RadioButton1 extends JApplet implements ItemListener { private Container Panel; private LayoutManager Layout; private JRadioButton Red; private JRadioButton Yellow; private JRadioButton White; private ButtonGroup Background; public RadioButton1 () { /* Instantiation */ Layout = new FlowLayout (); Panel = getContentPane (); Red = new JRadioButton ("Red Background"); Yellow = new JRadioButton ("Yellow Background", true); White = new JRadioButton (); Background = new ButtonGroup(); /* Location */ Panel.setLayout (Layout); Panel.add (Red); Panel.add (Yellow); Panel.add (White); /* Decoration */ Red.setBackground (Color.red); Yellow.setBackground (Color.yellow); White.setBackground (Color.white); White.setForeground (Color.red); White.setText ("White Background"); Panel.setBackground (Color.yellow); /* Configuration */ Background.add (Red); Background.add (Yellow); Background.add (White); Red.addItemListener (this); Yellow.addItemListener (this); White.addItemListener (this); } public void itemStateChanged (ItemEvent e) { ItemSelectable Source; Source = e.getItemSelectable(); if (Source == Red) { Panel.setBackground (Color.red); } else if (Source == Yellow) {

Panel.setBackground (Color.yellow); } else if (Source == White) { Panel.setBackground (Color.white); } } } import java.awt.*; import javax.swing.*; import java.awt.event.*; public class ScrollBar3 extends JApplet implements AdjustmentListener { /* Declaration */ private Container Panel; private LayoutManager Layout; private JScrollBar HSelector; private JScrollBar VSelector; private Drawing Pad; private JLabel Report; public ScrollBar3 () { /* Instantiation */ Layout = new BorderLayout (); HSelector = new JScrollBar (); VSelector = new JScrollBar (); Report = new JLabel (); Pad = new Drawing (); Panel = getContentPane (); /* Location */ Panel.setLayout (Layout); Panel.add (Report, BorderLayout.SOUTH); Panel.add (HSelector, BorderLayout.NORTH); Panel.add (VSelector, "West"); Panel.add (Pad, "Center"); /* Configuration */ HSelector.setMaximum (200); HSelector.addAdjustmentListener (this); VSelector.setMaximum (200); VSelector.addAdjustmentListener (this); HSelector.setOrientation (JScrollBar.HORIZONTAL); /* Decoration */ Report.setHorizontalAlignment (JTextField.CENTER);

Report.setText ("H = " + HSelector.getValue() + ", V = " + VSelector.getValue()); Pad.setBackground (Color.yellow); Pad.setSize (220, 220); Pad.setOval (HSelector.getValue (), VSelector.getValue ()); } public void adjustmentValueChanged(AdjustmentEvent e) { Report.setText ("H = " + HSelector.getValue () + ", V = " + VSelector.getValue ()); Pad.setOval (HSelector.getValue (), VSelector.getValue ()); Pad.repaint (); } } class Drawing extends Canvas { /* Declaration */ private int Width; private int Height; public void setOval (int X, int Y) { Width = X; Height = Y; } public void paint (Graphics g) { g.drawOval (10, 10, Width, Height); } } import java.awt.*; import java.awt.event.*; import javax.swing.*; public class TextArea1 extends JApplet implements ActionListener { JTextField Input; JTextArea Echo; JTextArea Echo2; Container Panel; LayoutManager Layout; public TextArea1 () { Input = new JTextField ("Input", 20);

Echo = new JTextArea (5, 20); Echo2 = new JTextArea (5, 20); Layout = new FlowLayout (); Panel = getContentPane (); Input.addActionListener (this); Echo.setEditable (false); Echo.setBackground (Color.green); Echo.setLineWrap (true); Panel.setLayout (Layout); Panel.add (Input); Panel.add (Echo); Panel.add (Echo2); Panel.setBackground (Color.yellow); } public void actionPerformed (ActionEvent e) { String Reply; Reply = "The text which was entered into the JTextField was \"" + Input.getText() + "\", and this is the echo with text wrap."; Echo.setText (Reply); Reply = "The text which was entered\ninto the JTextField was\n\"" + Input.getText() + "\",\nand this is the echo with returns."; Echo2.setText (Reply); } import java.applet.Applet; import java.awt.*; import javax.swing.*; public class Box1 extends Applet { LayoutManager Layout; Button [] Buttons; public Box1 () { int i; Layout = new BoxLayout (this, BoxLayout.X_AXIS); setLayout (Layout); Buttons = new Button [5]; for (i = 0; i < 5; ++i) { Buttons[i] = new Button ();

Buttons[i].setLabel ("Button " + (i + 1)); add (Buttons[i]); } } } *create a menubar: import java.awt.event.KeyEvent; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; public class MenuCreation { public static void main(final String args[]) { JFrame frame = new JFrame("MenuSample Example"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JMenuBar menuBar = new JMenuBar(); // File Menu, F - Mnemonic JMenu fileMenu = new JMenu("File"); fileMenu.setMnemonic(KeyEvent.VK_F); menuBar.add(fileMenu); // File->New, N - Mnemonic JMenuItem newMenuItem = new JMenuItem("New", KeyEvent.VK_N); fileMenu.add(newMenuItem); frame.setJMenuBar(menuBar); frame.setSize(350, 250); frame.setVisible(true); } } JApplet, JFrame JWindow, and JDialog can all produce a Container with getContentPane( ) that can contain and display Components. In Container, there’s a method called setLayout( ) that allows you to choose a different layout manager. Other classes, such as JPanel, contain and display components directly and so you also set the layout manager directly, without using the content pane.In this section we’ll explore the various layout managers by placing buttons in them (since that’s the simplest thing to do). There won’t be any

capturing of button events since these examples are just intended to show how the buttons are laid out.

BorderLayout

Applets use a default layout scheme: the BorderLayout (a number of the previous example have changed the layout manager to FlowLayout).Without any other instruction, this takes whatever you add( ) to it and places it in the center, stretching the object all the way out to the edges. However, there’s more to the BorderLayout. This layout manager hasthe concept of four border regions and a center area. When you addsomething to a panel that’s using a BorderLayout you can use theoverloaded add( ) method that takes a constant value as its first argument. This value can be any of the following: BorderLayout. NORTH Top BorderLayout. SOUTH Bottom BorderLayout. EAST Right BorderLayout. WEST Left BorderLayout.CENTER // import javax.swing.*; import java.awt.*; import com.bruceeckel.swing.*; public class BorderLayout1 extends JApplet { public void init() { Container cp = getContentPane(); cp.add(BorderLayout.NORTH, new JButton("North")); cp.add(BorderLayout.SOUTH, new JButton("South")); cp.add(BorderLayout.EAST, new JButton("East")); cp.add(BorderLayout.WEST, new JButton("West")); cp.add(BorderLayout.CENTER, new JButton("Center")); } public static void main(String[] args) { Console.run (new BorderLayout1(), 300, 250); } } ///

For every placement but CENTER, the element that you add is compressed to fit in the smallest amount of space along one dimension while it is stretched to the maximum along the other dimension. CENTER, however, spreads out in both dimensions to occupy the middle.

FlowLayout This simply “flows” the components onto the form, from left to right until the top space is full, then moves down a row and continues flowing. Here’s an example that sets the layout manager to FlowLayout and then places buttons on the form. You’ll notice that with FlowLayout the components take on their “natural” size. A JButton, for example, will be the size of its string // import javax.swing.*; import java.awt.*; import com.bruceeckel.swing.*;

public class FlowLayout1 extends JApplet { public void init() { Container cp = getContentPane(); cp.setLayout(new FlowLayout()); for(int i = 0; i < 20; i++) cp.add(new JButton("Button " + i)); } public static void main(String[] args) { Console.run(new FlowLayout1(), 300, 250); } } ///:~

All components will be compacted to their smallest size in a FlowLayout, so you might get a little bit of surprising behavior.

GridLayout

A GridLayout allows you to build a table of components, and as you add them they are placed left-to-right and top-to-bottom in the grid. In the constructor you specify the number of rows and columns that you need and these are laid out in equal proportions. . // import javax.swing.*; import java.awt.*; import com.bruceeckel.swing.*; public class GridLayout1 extends JApplet { public void init() { Container cp = getContentPane(); cp.setLayout(new GridLayout(7,3)); for(int i = 0; i < 20; i++) cp.add(new JButton("Button " + i)); } public static void main(String[] args) { Console.run(new GridLayout1(), 300, 250); } } ///:~

In this case there are 21 slots but only 20 buttons. The last slot is left empty because no “balancing” goes on with a GridLayout.

GridBagLayout The GridBagLayout provides you with tremendous control in deciding exactly how the regions of your window will lay themselves out and reformat themselves when the window is resized. However, it’s also the most complicated layout manager, and quite difficult to understand. It is intended primarily for automatic code generation by a GUI builder (GUI builders might use GridBagLayout instead of absolute placement). If your design is so complicated that you feel you need to use

Absolute positioning

It is also possible to set the absolute position of the graphical components in this way: 1. Set a null layout manager for your Container: setLayout(null). 2. Call setBounds( ) or reshape( ) (depending on the language version) for each component, passing a bounding rectangle in pixel coordinates. You can do this in the constructor, or in paint( ), depending on what you want to achieve. Some GUI builders use this approach extensively, but this is usually not the best way to generate code.

BoxLayout Because people had so much trouble understanding and working with GridBagLayout, Swing also includes BoxLayout, which gives you many of the benefits of GridBagLayout without the complexity, so you can often use it when you need to do hand-coded layouts (again, if your design becomes too complex, use a GUI builder that generates layouts for you). BoxLayout allows you to control the placement of components either vertically or horizontally, and to control the space between the components using something called “struts and glue.” First, let’s see how to use the BoxLayout directly, in the same way that the other layout managers have been demonstrated: // import javax.swing.*; import java.awt.*; import com.bruceeckel.swing.*; public class BoxLayout1 extends JApplet { public void init() { JPanel jpv = new JPanel(); jpv.setLayout(new BoxLayout(jpv, BoxLayout.Y_AXIS)); for(int i = 0; i < 5; i++) jpv.add(new JButton("jpv " + i)); JPanel jph = new JPanel(); jph.setLayout(new BoxLayout(jph, BoxLayout.X_AXIS)); for(int i = 0; i < 5; i++) jph.add(new JButton("jph " + i)); Container cp = getContentPane(); cp.add(BorderLayout.EAST, jpv); cp.add(BorderLayout.SOUTH, jph); } public static void main(String[] args) { Console.run(new BoxLayout1(), 450, 200); } } ///:~

The constructor for BoxLayout is a bit different than the other layout managers—you provide the Container that is to be controlled by the BoxLayout as the first argument, and the direction of the layout as the second argument. To simplify matters, there’s a special container called Box that uses BoxLayout as its native manager. The following example lays out components horizontally and vertically using Box, which has two static methods to create boxes with vertical and horizontal alignment: //: c14:Box1.java // Vertical and horizontal BoxLayouts. // import javax.swing.*; import java.awt.*; import com.bruceeckel.swing.*; public class Box1 extends JApplet { public void init() { Box bv = Box.createVerticalBox(); for(int i = 0; i < 5; i++) bv.add(new JButton("bv " + i)); Box bh = Box.createHorizontalBox(); for(int i = 0; i < 5; i++) bh.add(new JButton("bh " + i));

806 Thinking in Java www.BruceEckel.com

Container cp = getContentPane(); cp.add(BorderLayout.EAST, bv); cp.add(BorderLayout.SOUTH, bh); } public static void main(String[] args) { Console.run(new Box1(), 450, 200); } } ///:~

Once you have a Box, you pass it as a second argument when adding components to the content pane. Struts add space between components, measured in pixels. To use a strut, you simply add it in between the addition of the components that you want spaced apart: // Adding struts. // import javax.swing.*; import java.awt.*; import com.bruceeckel.swing.*; public class Box2 extends JApplet { public void init() { Box bv = Box.createVerticalBox(); for(int i = 0; i < 5; i++) { bv.add(new JButton("bv " + i)); bv.add(Box.createVerticalStrut(i*10)); } Box bh = Box.createHorizontalBox(); for(int i = 0; i < 5; i++) { bh.add(new JButton("bh " + i)); bh.add(Box.createHorizontalStrut(i*10)); } Container cp = getContentPane(); cp.add(BorderLayout.EAST, bv); cp.add(BorderLayout.SOUTH, bh); } public static void main(String[] args) { Console.run(new Box2(), 450, 300); } } ///:~

Struts separate components by a fixed amount, but glue is the opposite: it separates components by as much as possible. Thus it’s more of a “spring” than “glue” (and the design on which this was based was called “springs and struts” so the choice of the term is a bit mysterious). //: c14:Box3.java // Using Glue. // import javax.swing.*; import java.awt.*; import com.bruceeckel.swing.*; public class Box3 extends JApplet { public void init() { Box bv = Box.createVerticalBox(); bv.add(new JLabel("Hello")); bv.add(Box.createVerticalGlue()); bv.add(new JLabel("Applet")); bv.add(Box.createVerticalGlue()); bv.add(new JLabel("World")); Box bh = Box.createHorizontalBox();

bh.add(new JLabel("Hello")); bh.add(Box.createHorizontalGlue()); bh.add(new JLabel("Applet")); bh.add(Box.createHorizontalGlue()); bh.add(new JLabel("World")); bv.add(Box.createVerticalGlue()); bv.add(bh); bv.add(Box.createVerticalGlue()); getContentPane().add(bv); } public static void main(String[] args) { Console.run(new Box3(), 450, 300); } } ///:~

A strut works in one direction, but a rigid area fixes the spacing between components in both directions: //: c14:Box4.java // Rigid areas are like pairs of struts. // import javax.swing.*; import java.awt.*; import com.bruceeckel.swing.*; public class Box4 extends JApplet { public void init() { Box bv = Box.createVerticalBox(); bv.add(new JButton("Top")); bv.add(Box.createRigidArea(new Dimension(120, 90))); bv.add(new JButton("Bottom")); Box bh = Box.createHorizontalBox(); bh.add(new JButton("Left")); bh.add(Box.createRigidArea(new Dimension(160, 80))); bh.add(new JButton("Right")); bv.add(bh); getContentPane().add(bv); } public static void main(String[] args) { Console.run(new Box4(), 450, 300); } } ///:~

You should be aware that rigid areas are a bit controversial. Since they use absolute values, some people feel that they cause more trouble than they are worth.

Related Documents

Java Java Notes 4
November 2019 66
Java Notes
June 2020 16
Java Notes
June 2020 15
Java Cert Study Notes
November 2019 15