You are on page 1of 99

PREFACE

Object-Oriented Programming (OOP) has become the preferred programming approach by the software industries, as it offers a powerful way to cope with the complexity of real-world problems. Among the OOP languages available today, C++ and Java are the most widely used languages.

This Training Report is a complete account of the task performed in the Training vacations. It contains a brief introduction of all the concepts and features studied under the course of summer training in C++ and Core Java.

It also illustrates a number examples and the introductory part of all the topics that were covered under the course of summer training. It also includes with it the project that was assigned by the trainer during the training course. Along with this report is a separate project submitted.

ACKNOWLEDGEMENT
I wish to express my heartiest gratitude to Mr. Vijay Kumar (project in charge) for their proper guidance, constant encouragement, constructive suggestions, thought provoking decisions and giving us full opportunity to practically handle the system and without whose supervision this would not be possible. Any bouquets for the merit in this report should go to their door. Any brickbats I am ready to catch myself.

I am also thankful to my family who were in constant support of mine, which helped me carrying the training followed by the project work.

Remembering the almighty, is the constant source of energy and fills in with a positive attitude to carry the all the necessary steps of the course of life.

SHAIL BALA SHARMA DCA-083026

CONTENTS

Beginning with C++ Classes and Objects Arrays, Pointers, Reference & Dynamic Allocation Operators Function Overloading , Copy Constructors, & Default Arguments Operator Overloading Inheritance : Extending Classes Pointers, Virtual Functions and Polymorphism Exception Handling C++ I/O System Basics C++ File I/O Run-Time Type ID & Casting Operators Namespaces, Conversions Functions & other Advanced Topics

BEGINNING WITH C++:


C++ began as an expanded version of C. The C++ extensions were first invented by Bjarne Stroustrup in 1979 at Bell Laboratories in Murray Hill, New Jersey. He initially called the new language "C with Classes." However, in 1983 the name was changed to C++.

Object-Oriented Programming
Object-oriented programming took the best ideas of structured programming and combined them with several new concepts. The result was a different way of organizing a program. In the most general sense, a program can be organized in one of two ways: around its code (what is happening) or around its data (who is being affected). Using only structured programming techniques, programs are typically organized around code. This approach can be thought of as "code acting on

Encapsulation
Encapsulation is the mechanism that binds together code and the data it manipulates, and keeps both safe from outside interference and misuse. In an object-oriented language, code and data may be combined in such a way that a self-contained "black box" is created. When code and data are linked together in this fashion, an object is created. Within an object, code, data, or both may be private to that object or public. Private code or data is known to and accessible only by another part of the object. That is, private code or data may not be accessed by a piece of the program that exists outside the object. When code or data is public, other parts of your program may access it even though it is defined within an object. For all intents and purposes, an object is a variable of a userdefined type. It may seem strange that an object that links both code and data can be thought of as a

variable. However, in object-oriented programming, this is precisely the case. Each time you define a new type of object, you are creating a new data type. Each specific instance of this data type is a compound variable.

Polymorphism
Object-oriented programming languages support polymorphism, which is characterized by the phrase "one interface, multiple methods." In simple terms, polymorphism is the attribute that allows one interface to control access to a general class of actions Polymorphism helps reduce complexity by allowing the same interface to be used to. access a general class of actions. It is the compiler's job to select the specific action (i.e., method) as it applies to each situation. The programmer, don't need to do this selection manually.

Inheritance
Inheritance is the process by which one object can acquire the properties of another object. This is important because it supports the concept of classification. In C++, the class forms the basis for object-oriented programming. The class is used to define the nature of an object, and it is C++'s basic unit of encapsulation.

TYPE
CHAR UNSIGNED CHAR SIGNED CHAR INT UNSIGNED INT SIGNED CHAR SHORT INT UNSIGNED SHORT INT SIGNED SHORT INT LONG INT SIGNED LONG INT UNSIGNED LONG INT FLOAT DOUBLE LONG DOUBLE

BY TES
1
1 1 2 2 2 2 2 2 4

RANGE
-128 to 127 0 to 255 -128 to 127 -32767 to 32767 0 to 65535 -32767 to 32768 -32767 to 32767 0 to 65535 -32767 to 32768 -2147483648 to 2147483647 -2147483648 to 2147483647 0 to 4294967295 3.4E-38 to 3.4E+38 1.7E-308 to 1.7+308 3.4E-4096 to 1.1E+4932

4 4 8 10

Classes
Classes are created using the keyword class. A class declaration defines a new type that links code and data. This new type is then used to declare objects of that class. Thus, a class is a logical abstraction, but an object has physical existence. In other words, an object is an instance of a class. A class declaration is similar syntactically to a structure. In Chapter 11, a simplified general form of a class declaration was shown. Here is the entire general form of a class declaration that does not inherit any other class.

Class class-name { private data and functions access-specifier: data and functions access-specifier: data and functions // ... access-specifier: data and functions } object-list; access-specifier is one of these three C++ keywords: public private protected

Structures and Classes Are Related


Structures are part of the C subset and were inherited from the C language The only difference between a class and a struct is that by default all members are public in a struct and private in a class. In all other respects, structures and classes are equivalent.

Friend Functions
It is possible to grant a nonmember function access to the private members of a class by using a friend. A friend function has access to all private and protected members of the class for which it is a friend. To declare a friend function, include its prototype within the class, preceding it with the keyword friend.

Parameterized Constructors
It is possible to pass arguments to constructor functions. Typically, these arguments help initialize an object when it is created. To create a parameterized constructor, simply add parameters to it the way you would to any other function. When you define the constructor's body, use the parameters to initialize the object. For example, here is a simple class that includes a parameterized constructor:

#include <iostream> using namespace std; class myclass { int a, b; public: myclass(int i, int j) {a=i; b=j;} void show() {cout << a << " " << b;} }; int main() { myclass ob(3, 5); ob.show(); return 0; }

Static Class Members


Both function and data members of a class can be made static. This section explains the consequences of each. Static Data Members When you precede a member variable's declaration with static, you are telling the compiler that only one copy of that variable will exist and that all objects of the class will share that variable.

The Scope Resolution Operator


As you know, the :: operator links a class name with a member name in order to tell the compiler what class the member belongs to.

Nested Classes
It is possible to define one class within another. Doing so creates a nested class. Since a class declaration does, in fact, define a scope, a nested class is valid only within the scope of the enclosing class

Arrays, Pointers, References, and the Dynamic Allocation Operators:

In C++, it is possible to have arrays of objects. The syntax for declaring and using an object array is exactly the same as it is for any other type of array. For example, this program uses a three-element array of objects: #include <iostream> using namespace std; class cl { int i; public: void set_i(int j) { i=j; } int get_i() { return i; } }; int main() { cl ob[3]; int i; for(i=0; i<3; i++) ob[i].set_i(i+1); for(i=0; i<3; i++) cout << ob[i].get_i() << "\n"; return 0; }

Arrays of Objects

Pointers to Objects
Just as you can have pointers to other types of variables, you can have pointers to objects. When accessing members of a class given a pointer to an object, use the arrow (>) operator instead of the dot operator.

#include <iostream> using namespace std; class cl { int i; public: cl(int j) { i=j; } int get_i() { return i; } }; int main() { cl ob(88), *p; p = &ob; // get address of ob cout << p->get_i(); // use -> to call get_i() return 0; }

Type Checking C++ Pointers


There is one important thing to understand about pointers in C++: You may assign one pointer to another only if the two pointer types are compatible. For example, given: int *pi; float *pf; in C++, the following assignment is illegal: pi = pf; // error -- type mismatch

The this Pointer


When a member function is called, it is automatically passed an implicit argument that is a pointer to the invoking object (that is, the object on which the function is called). This pointer is called this.

Pointers to Derived Types

In general, a pointer of one type cannot point to an object of a different type. However, there is an important exception to this rule that relates only to derived classes. To begin, assume two classes called B and D. Further, assume that D is derived from the base class B. In this situation, a pointer of type B * may also point to an object of type D. More generally, a base class pointer can also be used as a pointer to an object of any class derived from that base.

Pointers to Class Members


C++ allows you to generate a special type of pointer that "points" generically to a member of a class, not to a specific instance of that member in an object. This sort of pointer is called a pointer to a class member or a pointer-to-member, for short. A pointer to a member is not the same as a normal C++ pointer. Instead, a pointer to a member provides only an offset into an object of the member's class at which that member can be found. Since member pointers are not true pointers, the . and -> cannot be applied to them. To access a member of a class given a pointer to it, you must use the special pointer-to-member operators .* and >*. #include <iostream> using namespace std; class cl { public: cl(int i) { val=i; } int val; int double_val() { return val+val; } }; int main() { int cl::*data; // data member pointer int (cl::*func)(); // function member pointer cl ob1(1), ob2(2); // create objects data = &cl::val; // get offset of val func = &cl::double_val; // get offset of double_val() cout << "Here are values: "; cout << ob1.*data << " " << ob2.*data << "\n"; cout << "Here they are doubled: "; cout << (ob1.*func)() << " "; cout << (ob2.*func)() << "\n";

return 0; }

C++'s Dynamic Allocation Operators


C++ provides two dynamic allocation operators: new and delete. These operators are used to allocate and free memory at run time. Dynamic allocation is an important part of almost all real-world programs. p_var = new type; delete p_var;

Operator Overloading
The ability to overload operators is one of C++'s most powerful features. It allows the full integration of new class types into the programming environment. After overloading the appropriate operators, you can use objects in expressions in just the same way that you use C++'s built-in data types. Operator overloading also forms the basis of C++'s approach to I/O. You overload operators by creating operator functions. An operator function defines the operations that the overloaded operator will perform relative to the class upon which it will work. An operator function is created using the keyword operator. Operator functions can be either members or nonmembers of a class.

#include <iostream> using namespace std; class loc

{ int longitude, latitude; public:

loc() {} loc(int lg, int lt) { longitude = lg; latitude = lt; } void show() { cout << longitude << " "; cout << latitude << "\n"; } loc operator+(loc op2); }; // Overload + for loc. loc loc::operator+(loc op2) { loc temp; temp.longitude = op2.longitude + longitude; temp.latitude = op2.latitude + latitude; return temp; } int main() { loc ob1(10, 20), ob2( 5, 30); ob1.show(); // displays 10 20 ob2.show(); // displays 5 30 ob1 = ob1 + ob2; ob1.show(); // displays 15 50 return 0;}

Overloading the Shorthand Operators


You can overload any of C++'s "shorthand" operators, such as +=, =, and the like. For example, this function overloads += relative to loc: loc loc::operator+=(loc op2) { longitude = op2.longitude + longitude; latitude = op2.latitude + latitude; return *this; }

Operator Overloading Restrictions


There are some restrictions that apply to operator overloading. You cannot alter the precedence of an operator. You cannot change the number of operands that an operator takes. (You can choose to ignore an operand, however.) Except for the function call operator (described later), operator functions cannot have default arguments. Finally, these operators cannot be overloaded: . : : .* ?

Operator Overloading Using a Friend Function


0ne can overload an operator for a class by using a nonmember function, which is usually a friend of the class. Since a friend function is not a member of the class, it does not have a this pointer. Therefore, an overloaded friend operator function is passed the operands explicitly. This means that a friend function that overloads a binary operator has two parameters, and a friend function that overloads a unary operator has one parameter.

Inheritance
Inheritance is one of the cornerstones of OOP because it allows the creation of hierarchical classifications. Using inheritance, you can create a general class that defines traits common to a set of related items. This class may then be inherited by other, more specific classes, each adding only those things that are unique to the inheriting class.

BASE CLASS VISIBLITY

DERIVED CLASS VISIBLITY PUBLIC DERIVATIO N NOT INHERITED PUBLIC PRIVATE DERIVATION NOT INHERITED PRIVATE PROTECTED DERIVATION NOT INHERITED PROTECTED PROTECTED

PRIVATE PROTECTED PUBLIC

PROTECTED PRIVATE

Base-Class Access Control


When a class inherits another, the members of the base class become members of the derived class. Class inheritance uses this general form: class derived-class-name : access base-class-name { // body of class

When a base class' access specifier is private, public and protected members of the base become private members of the derived class. This means that they are still accessible by members of the derived class but cannot be accessed by parts of your program that are not members of either the base or derived class.

Inheritance and protected Members


The protected keyword is included in C++ to provide greater flexibility in the inheritance mechanism. When a member of a class is declared as protected, that member is not accessible by other, nonmember elements of the program. With one important exception, access to a protected member is the same as access to a private memberit can be accessed only by other members of its class. The sole exception to

this is when a protected member is inherited. In this case, a protected member differs substantially from a private one.

It is possible for a derived class to inherit two or more base classes. For example, in this short example, derived inherits both base1 and base2. // An example of multiple base classes. #include <iostream> using namespace std; class base1 { protected: int x; public: void showx() { cout << x << "\n"; } }; class base2 { protected: int y; public: void showy() {cout << y << "\n";} }; // Inherit multiple base classes. class derived: public base1, public base2 { public: void set(int i, int j) { x=i; y=j; }}; int main(){ derived ob;ob.set(10, 20); // provided by derived ob.showx(); // from base1 ob.showy(); // from base2 return 0;}

Inheriting Multiple Base Classes

Virtual Functions and Polymorphism


Virtual Functions
A virtual function is a member function that is declared within a base class and redefined by a derived class. To create a virtual function, precede the function's declaration in the base class with the keyword virtual. When a class containing a virtual function is inherited, the derived class redefines the virtual function to fit its own needs.

Pure Virtual Functions

A base class may not be able to define an object sufficiently to allow a base-class virtual function to be created. Further, in some situations you will want to ensure that all derived classes override a virtual function. To handle these two cases, C++ supports the pure virtual function. A pure virtual function is a virtual function that has no definition within the base class. To declare a pure virtual function, use this general form: virtual type func-name(parameter-list) = 0;

Abstract Classes
A class that contains at least one pure virtual function is said to be abstract. Because an abstract class contains one or more functions for which there is no definition (that is, a pure virtual function), no objects of an abstract class may be created. Instead, an abstract class constitutes an incomplete type that is used as a foundation for derived classes. Although you cannot create objects of an abstract class, you can create pointers and references to an abstract class. This allows abstract classes to support run-time polymorphism, which relies upon base-class pointers and references to select the proper virtual function.

Exception Handling
Exception Handling Fundamentals
C++ exception handling is built upon three keywrds: try, catch, and throw. In the most general terms, program statements that you want to monitor for exceptions are contained in a try block. If an exception (i.e., an error) occurs within the try block, it is thrown (using throw). The exception is caught, using catch, and processed. try { // try block }

catch (type1 arg) { // catch block } catch (type2 arg) { // catch block } catch (type3 arg) { // catch block } .. . catch (typeN arg) { // catch block } The try can be as short as a few statements within one function or as allencompassing as enclosing the main() function code within a try block (which effectively causes the entire program to be monitored).

The C++ I/O System Basics

The C++ Stream Classes:

C++'s Predefined Streams: When a C++ program begins execution, four built-in streams are automatically opened. They are: Stream Meaning Default Device cin Standard input Keyboard cout Standard output Screen cerr Standard error output Screen clog Buffered version of cerr Screen Template Class Characterbased Class Wide-Characterbased Class

basic_streambuf streambuf wstreambuf basic_ios ios wios basic_istream istream wistream basic_ostream ostream wostream basic_iostream iostream wiostream basic_fstream fstream wfstream basic_ifstream ifstream wifstream basic_ofstream ofstream wofstream

Formatting Using the ios Members

Each stream has associated with it a set of format flags that control the way information is formatted. The ios class declares a bitmask enumeration called fmtflags in which the following values are defined. (Technically, these values are defined within ios_base, which, as explained earlier, is a base class for ios.) adjustfield basefield boolalpha dec fixed floatfield hex internal left oct right scientific showbase showpoint showpos skipws unitbuf uppercase.

C++ File I/O


<fstream> and the File Classes To perform file I/O, you must include the header <fstream> in your program. It

defines several classes, including ifstream, ofstream, and fstream. These classes are derived from istream, ostream, and iostream, respectively.

In C++, you open a file by linking it to a stream. Before you can open a file, you must first obtain a stream. There are three types of streams: input, output, and input/output. To create an input stream, you must declare the stream to be of class ifstream. To create an output stream, you must declare it as class ofstream. Streams that will be performing both input and output operations must be declared as class fstream. For example, this fragment creates one input stream, one output stream, and one stream capable of both input and output: ifstream in; // input ofstream out; // output fstream io; // input and output Once you have created a stream, one way to associate it with a file is by using open() . This function is a member of each of the three stream classes. The prototype for each is shown here: void ifstream::open(const char *filename, ios::openmode mode = ios::in);

Opening and Closing a File

void ofstream::open(const char *filename, ios::openmode mode = ios::out | ios::trunc); void fstream::open(const char *filename, ios::openmode mode = ios::in | ios::out);

Here, filename is the name of the file; it can include a path specifier. The value of mode determines how the file is opened. It must be one or more of the following values defined by openmode, which is an enumeration defined by ios (through its base class ios_base). ios::app ios::ate ios::binary ios::in ios::out ios::trunk

Reading and Writing Text Files


It is very easy to read from or write to a text file. Simply use the << and >> operators the same way you do when performing console I/O, except that instead of using cin and cout, substitute a stream that is linked to a file. For example, this program creates a short inventory file that contains each item's name and its cost: #include <iostream> #include <fstream> using namespace std; int main() { ofstream out("INVNTRY"); // output, normal file if(!out) { cout << "Cannot open INVENTORY file.\n"; return 1; } out << "Radios " << 39.95 << endl; out << "Toasters " << 19.95 << endl; out << "Mixers " << 24.80 << endl; out.close(); return 0;

} The following program reads the inventory file created by the previous program and displays its contents on the screen: #include <iostream> #include <fstream> using namespace std; int main() { ifstream in("INVNTRY"); // input if(!in) { cout << "Cannot open INVENTORY file.\n"; return 1; } char item[20]; float cost; in >> item >> cost; cout << item << " " << cost << "\n"; in >> item >> cost; cout << item << " " << cost << "\n"; in >> item >> cost; cout << item << " " << cost << "\n"; in.close(); return 0; }

Another way to read and write blocks of binary data is to use C++'s read() and write() functions. Their prototypes are istream &read(char *buf, streamsize num); ostream &write(const char *buf, streamsize num); The read() function reads num characters from the invoking stream and puts them in the buffer pointed to by buf. The write() function writes num characters to the invoking stream from the buffer pointed to by buf. As mentioned in the preceding chapter, streamsize is a type defined by the C++ library as some form of integer. It is capable of holding the largest number of characters that can be transferred in any one I/O operation.

read( ) and write( )

TABLE OF CONTENTS

Introduction to Java Language Features of Java Object Oriented Programming and its Principles Simple Program in Java Control Statements Data types in Java Arrays Strings Different operators Iteration Statements Nested Loop Jump Statements Constructors Overloading Methods Threads I/O Basics Streams Reading and Writing Files Exception Handling Applet Fundamentals Working with Graphics Menu Bars and Menus Event Handling Jdbc-Odbc Packages in java Java Beans

INTRODUCTION TO JAVA:
Java Technology: Its 1st version was released by Sun Microsystems in 1995. Its features: Programming Language-Syntax similar to C++ Development Environment-Tools like compiler, interpreter, documentation generator, class file packaging, Applets. Application Environment-Run on a machine having Java Runtime Environment.

Deployment Environment-Java Runtime Environment supplied by Java 2 SDK or by browser.

Goals of Java Technology:


Removing pitfalls of other languages like pointer arithmetic, memory management. Object-oriented to visualize program in real life terms. Enables to streamline the code. Enhances speed by reducing compile-link-load-test cycle. Code portability. Multi-threaded programs.

Other Specialty of Java Technology Architecture:


1)

JVM-It stands for Java Virtual Machine. It is an imaginary machine


implemented by emulating in s/w on real machine. It provides platform-independence by providing h/w specifications to which a java code is compiled. Source code--------------compiler------------------Bytecode

2)

Garbage Collection-System-level thread that automatically tracks


allocated memory and frees that can be during idle cycles in JVM.

3) Java Runtime Environment-

Class Loader: It loads classes needed for execution of program, adds security, assign memory addresses to references. Byte code Verifier: It verifies classes for their format, access restriction, parameter list, data conversion, stack flows.

Editions of Java:

J2SE-It includes support for GUI programming, threads, I/O, n/w, XML,
CORBA, applets, Java Beans, remote method invocation, security, db access.

J2ME-It establishes procedure for defining what a particular JVM designed


for an electronic device will provide.

J2EE-It is collection of Java technologies that create platform for


distributed application.

Loaded Hardware Runtime JIF code Interprete Byte code Class Javac Java Greet.loader Generator r verifier class

Operation of the JRE with a Just-In-Time (JIT) Compiler.

Object-Oriented Programming

Software Engineering: It is a difficult and unruly discipline which has been tried to be reusable.

Terms related to Software Engineering:


Library-It is collection of common functions and procedures. Record Structure-Manipulated data in libraries in the form of open record data-structures, like C language struct. Toolkits-Todays equivalent of functional libraries which provide classes and their extensions. Framework-They provide APIs that different vendors can implement to choose amount of flexibility and performance suitable to application.

Forces that guided s/w design to move from low-level constructs to higher levels

Simplification-It was at work when early language designers built high-level language constructs (if, for) out of raw machine codes. Abstraction-It hides private implementation detail behind public interfaces and led to development of subroutines in high-level language, pairing of functions & data into object.

Important terms and their syntax related to Java

Class-A way to define new type of objects in java. It is a blueprint of model of object being described. Syntax<modifier>* class <class name> { <attribute_declaration>* <constructor_declaration>* <method_declaration>*}

Attribute-Set of data elements that define objects. Syntax<modifier>* <type> <name> [=<initial_value>];

Method-Set of behaviors that manipulate objects or perform interactions b/w related objects.

Syntax<modifier>* <return_type> <name> (<argument>*) { <statement>*}

Constructor-Set of instructions designed to initialize an instance. Syntax[<modifier>] <class_name> (<argument>*) { <statement>*}

Setter-Storage access methods that set values for private attributes. Syntax<modifier>* <return_type> <setName> (<argument>*) { <statement>*}

Getter- Retrieval access methods that supply values for private attributes. Syntax<modifier>*<return_type><getName> (<argument>*) { <statement>*}

Package: Way of grouping classes, sub-packages or both.


SyntaxPackage <top_pkg_name> [. <sub_pkg_name>]*;

Import Statement: It makes classes in other packages accessible to current class


by telling compiler where to find classes. Syntaximport <pkg_name> [. <sub_pkg_name>]. <class_name>;

Or

import <pkg_name> [. <sub_pkg_name>].*;

Class Package Directory Structure:VehicleReport. report GUI Vehicle. Company. domain Shipping / s class / /

Identifiers, Keywords and Types

Comments: Statements to enhance understandability of program. It has three


permissible styles:-

//comment on one line /*comment on one *or more lines */

/**comments in documentation generated automatically to serve as *description of declared item */

Statement: One or more lines of code terminated with semicolon (;).


e.g. - truth = a+ b + c + d + e; Same as truth = a +b +c d + e+ f;

Block or Compound Statement: Group of statements bound by opening and


closing braces. e.g. - {x=y+1; y=x+1 ;}

White Space: It includes spaces, tabs and new lines to enhance the clarity of
source code. e.g. - compare {int x; x=23*54 ;} With: {int x; x=23*54 ;}

Identifiers: Case-sensitive names of unlimited length for variable, class or


method. e.g. Identifier _user_name thisOne - keyword can be part of name. $change generally not used.

Keyword: Words having special meaning for compiler to identify data type or
program construct name.

Java Programming Language Keywords:-

Switch New For Continue Abstract Synchronized Package Goto Default Assert This Private If Do Boolean Throw Protected implements Double Break Throws Public Import Else Byte Transient Return Instanceof Enum Case Try Short Int Extends Catch Void Static Interface Final Char Volatile Strictfp Long Finally Class while super native float cont

Basic Programming language types:-

1) Primitive Types: Consist of 8 built-in data types, which can be categorized as follows:

Logical-boolean: Represented using boolean type


SyntaxBoolean truth=true;

Textual-char: Represents a 16-bit, unsigned Unicode character.


SyntaxChar c=a; - the letter a

Char a=\t; - a tab

Char b=\u????-specific Unicode character

Integral-byte, short, int and long: Each type is represented using


one of the keywords byte, short, int, or long. All numerical types represented as signed numbers. SyntaxInt i=2; - decimal form for integer 2 Int j=077 0 indicates octal value Int k=0x 0x indicates hexadecimal value Int l=2L L indicates decimal 2 as long

Floating Point-float and double: Format defined by The Java

Language Specification to be Institute of Electrical and Electronics Engineers 754. Forms3.14-a double 3.14F-a float

2) Class Types: To create objects and variables that refer to objects called reference variables. e.g. Memory Allocation and Layout: MyDate my_birth- allocates memory for reference
Declaration my_birth of object reference ??

MyDate my_birth = new MyDate (); year month day my_birt 0 a ? h

c ?

Assigning References
int x=7; int y=x; //x is allocated memory // y is allocated memory

MyDate s=new MyDate (22, 7, 1964); //s refers to MyDate obj MyDate t=s; //t refers to same object no memory allocated

Pass-by-Value: It means argument value in calling method cant change from within the called method. But when object instance is passed as argument, contents of object can be changed in called method. Expressions and Flow Control

Different variables and their scope:-

I. Local

methods and constructor, which are initialized explicitly before use.

Variable- Variables defined inside method, and as parameter of

II.Class

initialized automatically, created when class is loaded and continue as long as class.

Variable- Variables defined outside method, labeled static,

III.Instance

automatically, created when object is constructed and continue as long as object.

Variable- Variables defined outside method, initialized

Value Variable Default Values of Primitive Types 0 Byte 0 Short 0 Int 0L Long 0.0F Float 0.0D Double \u0000 Char False Boolean null Reference types

Variable Scope Example:-

public class ScopeExample{ private int i=1; public void firstMethod() { int i=4, j=5; this.i=i+j; secondMethod (7) ;} public void secondMethod(int i) {

int j=8; this.i=i+j;}}

public class TestScoping{ public static void main (String [] args) { ScopeExample scope=new ScopeExample(); scope.firstMethod () ;}}

Operators: 1) Logical Operator-Relational and logical operators return Boolean.


Supporting Boolean operators-! (NOT), & (AND), ^ (XOR),| (OR). e.g. - int i=1; if (i) if (i! = 0) //generates a compiler error // correct

2) Short-Circuit Logical Operators-&& (AND) and || (OR).2nd sub


expression is skipped when 1st is false. e.g. MyDate d=reservation.getDepartureDate (); if ((d! = null) && (d.day > 31)) { // do something with d}

3) Bitwise Logical Operators- Bitwise logical operations, including


logical and shift operations, perform low-level operations directly on binary representation used in integers. Operators- ~ (Bitwise NOT), & (Bitwise AND),| (Bitwise OR).

4) Right-Shift Operators >> and >>> >> - performs arithmetic or signed right shift. e.g. 256 >> 4 returns 256/2*2*2*2 = 16 -256 >> 4 returns -256/2*2*2*2 = 16

>>> - logical or unsigned works on bit pattern. e.g. 1010 2 >> gives 111010

1010 >>> 2 gives 001010

5) Left-Shift Operator <<- It causes 1st operand multiplied by 2 raised to


no specified by 2nd operand. e.g. - 128 << 1 returns 128 * 2 = 256 16 << 2 returns 16 * 2*2 =64

6) String Concatenation With +- It performs concatenation of String


objects, producing a new String, even if either argument is String. e.g. - String salutation = Dr.; String name = Pete + + Sey; String title = salutation + + name; Result of title Dr. Pete Sey

Associative R to L L to R L to R L to R L to R L to R L to R L to R L to R

Operators ++ -- - ~ ! ( <data_type> ) / % + << >> >>> < > >= >= instanceof == != & ^ |

Casting- Assigning value of one type to variable of another type, so that compiler
confirms no loss of data.

e.g. - int squashed = 99L; int squashed = (int) 99L;

//Wrong, needs a cast // ok

Promotion and Casting of Expressions- Conditional statements that enable selective execution of portion of programme according to expression.

Following conditional statements are used in Java: If: Two-way branching. Simple- if (<Boolean_expression>)) {

<statement_or_block> ;} Complex- if (<Boolean_expression>)) { <statement_or_block> ;} else { <statement_or_block> ;} switch: Multiple-way branching. Compatible types for <expression> - int, byte, short, char, enumerated, constant.

switch(<expression>){ case<constant 1>: <statement_or_block>* [break;] case<constant 2>: <statement_or_block>* [break;] default: <statement_or_block>*

[break;]}

Looping Statements: They enable to execute blocks of statements repeatedly.

Java supports 3 types of loop constructs:

for: When loop execution time is predetermined.


Syntax- for (<init_expr> ;< test_expr> ;< alter_expr>) { statement_or_block> ;}

while: When loop execution time is not predetermined.


Syntax- while (<test_expr>) { statement_or_block> ;}

do/while: When loop execution time is not predetermined.


Syntax- do { statement_or_block> } while (<test_expr>);

Special loop Flow Control:


break [<label>] ; To prematurely exit from innermost loop. Continue[<label>]; To skip and jump to end of loop, then passing to loop-control. <label> : <statement> labeled statement identifies any valid statement to which control must be passed.

Arrays

Array: It is an object that refers to a group of object by a common name.

Declaring Array: It creates a reference that can be used to refer to an array.


e.g. char [] s; Point [] p; same as char s [];

//where Point is a class

Creating Array: It is done using new keyword like all objects.


e.g. s = new char [26]; // creates array of 26 char values and elements are initialized to default value,\u0000. p = new Point [10]; //creates an array of 10 references of type Point.

Program for creating reference arrays:-

Memory View:-

Point P Execution Stack public Point [] this createArray() mai n

Point [] p; p=new Point [10]; for (int i=0; i<10 ; i++) P[i] =new Point(i,i+1);} return p;}

Initializing Arrays: Assigning values to each element of array, which is essential


for the security of system. e.g. - String [] names= {George,Jen}; MyDate [] date = {new MyDate (22, 7, 1964)};

Array Bounds: In Java, all array indices begin at 0 and no. of elements in an
array is stored as part of array object in length attribute. e.g. for (int i=0; i<list.length; i++) { Systm.out.println (list[i]) ;}}

Enhanced for Loop: It has been added in J2SE version 5.0 to make array
iteration easier, which is handled by compiler.

e.g. public void printElements (int [] list) { for (int element: list) { System.out.println (element) ;}}

Array Resizing: Array cant be resized, but same reference variable can be used
to refer to an entirely new array. e.g. int [] myArray = new int [6]; myArray = new int [10];

Copying Arrays: It is done by System.arraycopy method which copies


references.

Program for copying arrays:-

int [] myArray= {1, 2, 3, 4}; int [] hold= {10, 9, 8, 7}; System.arraycopy(myArray, 0, hold, 0, myArray.length);

Class Design

Sub classing: Mechanism that enable to define a class in terms of previously


defined class. Diagram showing sub classing:Manager Employee +dep: +name: String= String +birthDate: Date +getDetails (): String

Code of Sub classingpublic class Manager extends Employee { public String dep;}

Single Inheritance: Java permits to extend one other class only.


Diagram showing Single Inheritance:-

Engineer Manager Employee +dep: +dep : +name: String= String +birthDate: Date +getDetails (): String

Access Control: Variables & methods can be at one of four access levels:
public, protected, default, or private. Classes can public or default.

Accessibility Criteria:-

Yes Private Modifier Yes Default Universal Yes Protecte Yes d Public

Same Class

Same Package

Subclass

Overriding Methods: Defining method in subclass which matches in name,


return type, argument list to that in parent method.

Showing overriding-

public class Employee{ protected String name;

public String getDetails(){ return name;}}

public class Manager extends Employee {

protected String dep; public String getDetails () { return name + dep ;}}

Polymorphism: Referring subclass object with parent class reference.


e.g. Employee e=new Manager (); e.dep = sales; // legal // illegal

Virtual Method Invocation: Behavior associated with object to which variable


refers is actually determined at run time, not by compiler. e.g. Employee e=new Manager (); e.getDetails (); // Invokes method of Manager Class

Heterogeneous Collection: Collection of dissimilar objects, all having common


ancestor, the Object class. e.g. Employee [] staff = new Employee [1024]; staff [0] = new Manager (); staff [1] = new Employee ();

Polymorphic Arguments: Writing methods that accept generic object and work
properly on any object of its subclass. e.g. public class TaxService { public TaxRate findTaxRate (Employee e) {

// do calculations}} // Meanwhile, elsewhere in application class TaxService taxSvc = new TaxService (); Manger m = new Manager (); TaxRate t = taxSvcfindTaxRate (m);

Instanceof operator: It lets know what actual object has been passed using
reference to parent class. e.g. public void doSomething (Employee e) { if (e instanceof Manager) {//process } else if (e instanceof Engineer) {//process } else {//process any other Employee}}

Casting Objects: It is done to access full functionality of object by casting


reference, where parent class reference refers to subclass object. e.g. public void doSomething (Employee e) { if (e instanceof Manager) { Manager m = (Manager e) ;}}

Overloading Method: Reusing same method name for more than one method in
class, by using different argument list.

e.g. public void println (int i) public void println (float f)

Overloading Constructor: Multiple constructors in a class.


e.g. public Employee (String name, Date dob) Public Employee (String name)

Invoking Parent Class Constructor: It is done using keyword super from child
constructors 1st line, providing appropriate argument.

Object Class: Root of all java classes.


e.g. public class Employee Equivalent to: public class Employee extends Object

Wrapper Classes: To manipulate primitive data elements as objects, elements


are wrapped in object created around them. e.g. 1) int pInt = 420; Integer wInt = new Integer (pInt); Int p2 = wInt.intValue (); // boxing // Unboxing

2) int x = Integer.valueof (str).intValue (); Or: int x = Integer.parseInt (STR);

Advanced Class Features

Static Keyword: It declares member as associated with class.

Common uses are as:i.

Class Attribute- Class variable shared among instances.


SyntaxPublic static int counter=34;

ii.

Class Method: To access local variables, static attributes, and parameters


of static method without instance of class. e.g.

public static int getCount () //inside class Count2 Accessed as: Count2.getCount ();
iii.

Static Initializes: Code in static block that are not part of method, and
executed once when class is loaded, in order they appear in class. SyntaxCounter = Integer.getInteger (a).intValue ();

Final Keyword: It declares members as unchangeable.

Common uses are as:I. Final

Class- It cant be sub classed, done so that methods cant be

overridden. e.g. java.lang.String


II.Final

Method- It cant be overridden. Compiler generates code that causes Final Variable- It is not initialized while declaration.

direct call to method, rather than virtual method invocation.


III.Blank

IV. SyntaxPrivate final long id;

Abstract Class: It cant be instantiated, but can have data attributes, concrete
methods and constructors. Syntax- public abstract class Vehicle

Abstract Method: Method declared by super class, but implementation supplied


by sub class. SyntaxPublic abstract double calFuel ()

Interface: Public interface of a class is contract b/w client code and class that
provides service. Concrete class implements interface by defining all methods declared by interface. Syntax for interfacePublic interface Flyer Syntax for Concrete classPublic class Airplane implements Flyer

Facts related to interface: Many classes implement same interface A class can implement more than one interface Methods are implicitly public and abstract Attributes are implicitly public, static and final.

The Flyer Example (Mixture of inheritance & implementation):-

Bird Airplan Anim Interfac +takeoff al e () +takeoff +eat Flyer +land () () +takeoff +eat () +land () () +land ()

Syntax for bird classPublic class Bird extends Animal implements Flyer

Multiple Interface: A class can implement more than one interface.

Exceptions and Assertions

Exceptions: Mechanism describing what to do when something unexpected


occurs in program.

Try-catch statement: Mechanism for figuring out which exception was thrown
and how to recover from it. It can be used on smaller chunks of code.

Syntaxtry {

// code might throw one or more exception } catch (MyException e) { // code to execute if MyException is thrown

Call Stack Mechanism: If a statement throws an exception and is not handled in


immediately enclosing method, it is thrown to calling method, if not handled it is finally thrown to main () and even if not handled here, it is printed to standard o/p and program stops executing.

Finally Clause: It defines block of code that always executes, regardless of


whether an exception was thrown. Syntaxtry {//code } catch (Exception e) {//code } finally {//code}

Exception Categories-

Class java.lang.throwable: It acts as parent class for all objects that can be
thrown. Methods retrieve error message associated with exception.

Subclasses of Throwable:-

1) Error- Unchecked exception that cause severe problem from which


recovery is difficult, if not impossible, not thrown to calling method. Running out of memory. e.g.

2)

RuntimeException- Unchecked exception that cause design or

implementation problem, so left unhandled. It is also not thrown to calling method. Result Message at run time showing step taken for correction.

3) Exception- Checked exceptions that indicate difficulty at runtime, mostly


caused by environmental effects, thrown to calling method. e.g. File not found.

Diagram showing subclasses of Throwable class:-

EOFException FileNotFoundException NullPointerException NumberFormatException IOException SQLException RuntimeException OutOfMemoryError StackOverflowError AssertionError VirtualMachineError Exception Error Throwable

Handle Rule: It declares, if checked exception occurs, method containing that


point must define explicitly required actions, which are as-

Handle exception using try-catch-finally block. Declare exceptions that a method can throw e.g. void trouble () throws IOException, OtherException {}

Method Overriding and Exceptions: When overriding a method that throws


exceptions, the overriding method can declare only exceptions that are either the same class or a subclass of the exceptions. e.g.

public class TestA { public void methodA () throws IOException {}}

public class TestB1 { public void methodA () throws IOException {}} //compiles properly public class TestB2 { public void methodA () throws IOException {}} //does not compile

Assertions: To test assumptions about local program logic inside a method and
not external exceptions. They can be removed entirely from code.

Permitted Syntactic forms for assertion statements:-

Assert<Boolean_expression>;

Assert<Boolean_expression> : <detail_expression>; Boolean_expression-false: AssertionError is thrown which is not caught and program terminates. Boolean_expression-true: <detail_expression> is converted to string and used to supplement message that prints when assertion is reported.

Recommended Uses of Assertion: Provide valuable documentation about programmers assumptions and exceptions. Should be used to verify internal logic of a single method or a single group of tightly coupled methods.

Example of Good Uses of Assertions:-

Internal Variants Control Flow Invariants Post conditions Class Invariants

Text-Based Applications

Command-Line Arguments: It follows name program class and is stored in an


array of String objects passed to the static main () method. e.g. java TestArray arg1 arg2 another arg

Properties Class: Its object contains mapping b/w property names (String) &
values (String). It has two main methods for retrieving a property value: getProperty (String) and getProperty (String, String).

Console I/O: Java2SDK supports console I/O with 3 public variables on the
java.lang.System class:

System.out: PrintStream object that refers initially to terminal window. System.in: InputStream object that refers initially to keyboard. System.err: PrintStream object that refers initially to terminal window.

Writing to Standard Output: PrintStream method (System.out.prinln ()) prints


primitive, character buffer, arbitrary object and adds a newline character at the end. e.g. void println (boolean) void println (char []) void println (Object)

Simple Formatted O/P: Java version 1.5 provides C language-style printf


functionality that provides standard formatted O/P from program.

Common Formatting Codes:-

F %o newline character octal, or Description Inserts argument Formats integer, point number Cod %% % characteras string %n %f %s %d floating decimal, o hexadecimal e %g %x r m a

Simple Formatted I/P: java.util.Scanner class provides formatted I/P


functionality. It provides methods for getting primitive values and to block as it waits for I/P from user.

File Class: It defines platform-independent methods for manipulating file


maintained by native file system, but does not permit to access contents. e.g.

File myFile = new File (myfile.txt) ; myFile = new File (MyDocs, myfile.txt); File myDir = new File (MyDocs); myFile = new File (myDir,myfile.txt);

File Stream I/O

J2SE platform supports file i/p in two forms:

Use FileReader class to read characters. Use BufferedReader class to use readLine method.

Syntax for File Inputtry { BufferedReader in=new BufferedReader(new FileReader (file)); String s; S=in.readLine (); while (s!= null) { System.out.println (s); S=in.readLine () ;} } catch (IOException e) { e.printStackTrace () ;}

J2SE platform supports file o/p in two forms:

Use FileWriter class to write characters. Use PrintWriter class to use print and println methods.

Syntax for File Output-

try { InputStreamReader isr=new InputStreamReader (System.in); BufferedReader in=new BufferedReader (isr); PrintWriter out=new PrintWriter (new FileWriter (file)); String s; While ((s=in.readLine ())! = null) { Out.println(s) ;}

} catch (IOException e) { e.printStackTrace () ;}

Collections API: It is a Java 2 SDK feature.


Collection- Group of objects called elements; implementations determine


whether there is specific ordering and duplicates allowed. Set- Unordered collection; no duplicates permitted. Instantiated asSet set=new HashSet (); Methodset.add (one); List list=new ArrayList (); list.add (new Integer (4));

List- Ordered collection; duplicates are permitted.


Instantiated asMethod-

Diagram of Collection Interface and Class Hierarchy-

LinkedL ArrayLi HashS <<interface>> <<interface <<Interface>> ist st et >> Collection List +add (element: Object): Set (index: int, element: Object) boolean +get (): int +size(index: int): Object +set (index: boolean +isEmpty (): int, element Object)

Collections in JDK Version 1.1:


Vector Class: Implements List interface. Stack Class: Extension of Vector class. Hashtable Class: Implements Map interface. Properties Class: Extension of Hashtable class.

Generics: It provides information for compiler about type of collection used, so


type checking is resolved automatically at run time. e.g. -

Code without genericsArrayList list=new ArrayList (); List.add (0, new Integer (42)); int total= ((Integer) list.get (0)).intValue ();

Code with genericsArrayList<Integer> list=new ArrayList<Integer> (); List.add (0, new Integer (42)); int total= list.get (0).intValue ();

Iterators: Interface enables to scan forward through any collection.

Code Demonstrating Use of Iterator:-

List list = new ArrayList (); Iterator elements = list.iterator (); while (elements.hasNext ()) { System.out.println (elements.next ()) ;}

Building Java GUIs

java.awt Package: It provides basic GUI components used in Java applets &
applications. User interfaces are built by composing available components.

Basic Overview of Package:-

ErrorsExceptionsApplet TextAre Dialog Panel Button (java.applet BorderLayout Java.lang.Obje AWTError AWTException package) a Frame Window Canvas GridLayout ct TextFiel Container Toolkit d Label MenuComponent List Component TextComponent

Components Used in Building Java GUIs: -

1)

Containers: GUI components are added to container using add method.


It is of 2 main types-

Window- Free-standing native window on display that is


independent of other containers.

It is also of 2 main types-

Frame: It can be resized.


e.g. - public FrameExample () { f= new Frame (Hello);} public void LaunchFrame () { f.setSize (17, 17); f.setBackground (color.blue); f.setVisible (true);

Dialog: It can be moved and resized.

Panel- It identifies rectangular area into which components are


placed. It must be placed in Window to be displayed. e.g. - public FrameWithPanel (String title) { f=new Frame (title); p= new Panel (); } public void launchFrame () { f.setSize (17, 17); f.setBackground (color.blue); f.setVisible (true); p.setSize (2, 2); f.add (p); p. setBackground (color.blue); f.setVisible (true) ;}

1)

Positioning and Sizing Components: It is determined by layout


manager. A container keeps reference to particular instance of layout manager and invokes it whenever required.

Container Layout: Layout of components in a container is governed by layout


manager. Each container has default layout manager associated with it that can be changed using setLayout.

Diagram of Default Layout Manager:-

Applet Pan Dialog Frame Windo Contain Compon el w er ent

Layout Managers:-

FlowLayout: Default layout manager of Panel & Applet. It positions


components on line-by-line basis and permits components to have preferred size. e.g. - public LayoutExample () { f=new Frame (GUI Example); b1 = new Button (Press me) ;}

public void launchFrame () { f.setLayout (new FlowLayout ()); f.add (b1); f.pack (); f.setVisible (true) ;}

BorderLayout: Default layout manager of Frame & Dialog classes.


Diagram of BorderLayout:-

Cent Ea We Sout Nort er st h

e.g. - public BorderExample () {

f=new Frame (Border Layout); b1 = new Button (Press me) ;} public void launchFrame () { f.add (b1, BorderLayout.NORTH); f.setSize (2, 3); f.setVisible (true) ;}

GridLayout: It is created with specified no of rows and columns and then


components fill up cells.

e.g. - public GridExample () { f=new Frame (GridExample); b1 = new Button (Press me) ;} public void launchFrame () { f.setLayout (new GridLayout (3, 2)); f.add (b1); f.pack (); f.setVisible (true) ;}

GUI Event Handling

Events: Objects reported only to registered listeners. Every event has


corresponding listener interface that mandates which methods must be defined in a class suited to receive that event. Class that implements interface defines those methods, and can be registered as listener.

Event Sources: ActionEvent instance is an object that contains information about


events that just occurred. It contains:

getActionCommand- returns command name. getModifiers- returns modifiers.

Delegation Model: It came with JDK Version 1.1. Events are sent to originator
component, but it is up to each component event to listeners which contain event handlers that receive & process event.

Diagram of Delegation Model:-

ActionEv actionPerformed User Pane Butto Fram clicks on ent (ActionEvent e) button l n e { . }

e.g. public void launchFrame () { b.addActionListener (new ButtonHandler ());

f.add (b, BorderLayout.CENTER); f.pack (); f.setVisible (true) ;}

import java.awt.event.*;

public class ButtonHandler implements ActionListener { public void actionPerformed (ActionEvent e) { System.out.println (e.getActionCommand ()) ;}}

Implementing Multiple Interfaces and Listening to Multiple Sources:-

public class TwoListener implements MouseMotionListener, MouseListener

public void mouseDragged (MouseEvent e1) {} public void mouseEntered (MouseEvent e2) {} public void mouseDragged (MouseExited e3) {}}

Event Adapters: Adapter classes implement each interface containing more than one method, which are empty. Their extended classes override required methods. Syntaxpublic class MouseClickedHandler extends MouseAdapter { Public void mouseClicked (MouseEvent e) {}}

Event Handling Using Inner Classes:-

Class MyMouseMotionListener extends MouseMotionAdapter { Public void mouseDragged (MouseEvent e) { String s = Mouse dragging: X = + e.geX () + Y= + .NET (); Tf.setText (s) ;}}

//

somewhere in program f.addMouseMotionListener (new MyMouseMotionListener ()); f.addMouseListener (new MouseClickHandler ());

Threads

thread: Encapsulation of virtual CPU with its own code & data. It is referred
through an instance of Thread object.

Creating the Thread: A Thread constructor takes an argument that is instance of


Runnable, and is made from class that implements Runnable interface. e.g.public class ThreadTester { public static void main (String [] args) { HelloRunner r = new HelloRunner (); Thread t = new Thread (r); t.start () ;}} class HelloRunner implements Runnable { int i; public void run () {i =0; while (true) {System.out.println (i++);

if (i==50) {break ;}}}} New Thread Instance r HelloRunner Data Co CPU Thread t of Class de HelloRunn er

Thread Creation

Thread Scheduling: threads are preemptive, but not necessarily time-sliced.


All runnable threads are kept in pools according to priority.

Fundamental Thread State Diagram:-

Run start Complete Dea New Event Unblocke Schedul Runnin Runnabl Blocke s Blocked er g e d

e.g.-

public class Runner implements Runnable { public void run () { while (true) {// code try {thread.sleep (10); } catch (InterruptedException e) {}}}}

Terminating a Thread: This is done using flag that indicates run method should
exit. thread cant be run then. Syntaxr.stopRunning ();

Basic Control of Threads:

Testing Threads: isAlive method determines if thread is alive. Accessing Thread Priority: Priority is integer value.
getPriority Determines current priority of thread. setPriority Set priority of thread. Putting Threads on Hold: Temporarily blocking execution of thread. Thread.sleep () Halt thread for period of time. join Causes current thread to wait until thread on which join method is called terminates.

Other Ways to Create Threads: Thread class implements Runnable interface,


so thread can be created by extending Thread. Syntaxpublic class MyThread extends Thread { public void run () {}}

Synchronized keyword: It enables interaction with flag, associated with every


object in Java, and provides exclusive access to code that affects shared data.

Releasing Lock Flag: When thread that holds lock passes end of synchronized
code block for which block was obtained.

Deadlock: This occurs when thread is waiting for a lock held by another thread,
but the other thread is waiting for a lock already held by the 1st method.

public objectchar pop () { Waiting Data or Codeor lock for State Behavi synchronized (this) { or idx--; return data[idx] ; }}

Thread Trying to Execute synchronized

Thread Interaction wait and notify: When a thread executes synchronized


code that contains a wait call on a particular object, that thread is placed in wait pool of that object. When notify call is executed on a particular object, an arbitrary thread is moved from that objects wait pool to lockpool. e.g. - wait () wait (long timeout)

pop Method: It must be synchronized. If stack is empty in pop method,


executing thread must wait. e.g. public synchronized char pop () { char c; while (buffer.size () == 0) { try {this.wait (); } catch (InterruptedException e) {} c = buffer.remove (buffer.size () -1); return c ;}

push Method: It affects thread buffer and must also be synchronized.

e.g. public synchronized void push (char c) { this.notify (); buffer.add (c) ;}

GUI-Based Application s

Descriptions:-AWT Component

Component Type Button rectangular box for receiving mouse clicks Description Canvas panel used for drawing Component parent of all AWT components Container parent of all AWT containers Dialog A top-level Window with title & border Frame Base class of all GUI Windows Label A text string component List Component that contains dynamic set of items Menu contains set of menu items Panel Basic container class to create complex layouts TextArea Enables user to enter block of text TextField Enables user to enter single line of text Window Base class of all GUI Windows

Creating MenuBar: Horizontal menu and can be added to Frame object only.
e.g. Frame f = new Frame (MenuBar); MenuBar mb = new MenuBar (); f.setMemuBar (mb);

O/P of above code:-

Menu Bar

Creating Menu: It provides basic pull-down menu.

e.g. Frame f = new Frame (Menu); MenuBar mb = new MenuBar ();

Menu m1 = new Menu (File); Menu m2 = new Menu (Help); mb.add (m1); mb.setHelpMenu (m2); f.setMenuBar (mb);

Creating MenuItem: These are text leaf nodes of a menu tree.

e.g. MenuItem mi1 = new MenuItem (New); MenuItem mi2 = new MenuItem (Save); mi1.addActionListener (this); mi2.addActionListener (this); m1.add (mi1); m1.addSeparator (); m1.add (mi2);

O/P of above code:-

Ne File Help MenuIte w m Sav e

Concept of DATABASE CONNECTIVITY: The JDBC API contains classes and interfaces for connecting to a database and performing SQL statements. You need a JDBC driver for a Java application to connect to a database. There are four types of drivers referred to as Type 1, 2, 3, and 4. Each

type of driver has its benefits. The java.sql.DriverManager class can be used to obtain a connection to a database. The java.sql.Connection interface represents the database connection. The javax.sql.DataSource class can also be used to obtain a connection to a database. This is the preferred technique when connecting to a database from within a J2EE application or environment that provides JNDI. SQL stands for Structured Query Language and is the language used by most databases for accessing and updating data. There are three types of statements: simple statements, prepared statements, and callable statements, which are used for stored procedures. The java.sql.Statement interface represents simple statements, the java.sql.PreparedStatement interface represents prepared statements, and the java.sql.CallableStatement interface represents callable statements. Each of these is obtained using the Connection object. The java.sql.ResultSet interface represents a result set, the data returned from an SQL query.

Defining a Package To create a package is quite easy: simply include a package command as the first statement in a Java source file. Any classes declared within that file will belong to the specified package. The package statement defines a name space in which classes are stored. If you omit the package statement, the class names are put into the default package, which has no name. (This is why you havent had to worry about packages before now.) While the default package is fine for short, sample programs, it is inadequate for real applications. Most of the time, you will define a package for your code. This is the general form of the package statement: package pkg; Here, pkg is the name of the package. For example, the following statement creates a package called MyPackage. package MyPackage; Java uses file system directories to store packages. For example, the .class files for any classes you declare to be part of MyPackage must be stored in a directory called MyPackage. Remember that case is significant, and the directory name must match the package name exactly. More than one file can include the same package statement. The package statement xsimply specifies to which package the classes defined in a file belong. It does not exclude other classes in other files from being part of that same package. Most

real-world packages are spread across many files. You can create a hierarchy of packages. To do so, simply separate each package name from the one above it by use of a period. The general form of a multileveled package statement is shown here: package pkg1[.pkg2[.pkg3]]; A package hierarchy must be reflected in the file system of your Java development system. For example, a package declared as package java.awt.image;

Finding Packages and CLASSPATH

As just explained, packages are mirrored by directories. This raises an important question: How does the Java run-time system know where to look for packages that you create? The answer has two parts. First, by default, the Java run-time system uses the current working directory as its starting point. Thus, if your package is in the current directory, or a subdirectory of the current directory, it will be found. Second, you can specify a directory path or paths by setting the CLASSPATH environmental variable. For example, consider the following package specification. package MyPack; In order for a program to find MyPack, one of two things must be true. Either the program is executed from a directory immediately above MyPack, or CLASSPATH must be set to include the path to MyPack. The first alternative is the easiest (and doesnt require a change to CLASSPATH), but the second alternative lets your program find MyPack no matter what directory the program is in. Ultimately, the choice is yours. What Is a Java Bean? A Java Bean is a software component that has been designed to be reusable in a variety of different environments. There is no restriction on the capability of a Bean. It may perform a simple function, such as checking the spelling of a document, or a complex function, such as forecasting the performance of a stock portfolio. A Bean may be visible to an end user. One example of this is a button on a graphical user interface. A Bean may also be invisible to a user. Software to decode a stream of multimedia information in real time is an example of this type of building block. Finally, a Bean may be designed to work autonomously on a users workstation or to work in

cooperation with a set of other distributed components. Software to generate a pie chart from a set of data points is an example of a Bean that can execute locally. Advantages of Java Beans A software component architecture provides standard mechanisms to deal with software building blocks. The following list enumerates some of the specific benefits that Java technology provides for a component developer: A Bean obtains all the benefits of Javas write-once, run-anywhere paradigm. The properties, events, and methods of a Bean that are exposed to an application builder tool can be controlled. A Bean may be designed to operate correctly in different locales, which makes it useful in global markets. Auxiliary software can be provided to help a person configure a Bean. This software is only needed when the design-time parameters for that component are being set. It does not need to be included in the run-time environment. The configuration settings of a Bean can be saved in persistent storage and restored at a later time. A Bean may register to receive events from other objects and can generate events that are sent to other objects.

Introduction:
This project is based on simple usage of awt, with the introduction of event handling and swings for look. Notepad works as a text Editor and controls the processing of the application. It provides the platform to program with the scripting languages and many more features that are needed for an efficient text editing. In addition to the normal features provided by the notepad it has a special look of its cursor that makes it different from other notepads.

Front end:Java is the most efficient front end . It uses the concept of buttons , forms, applets, layouts etc. which are easy to handle.

System Requirement Specification:The requirement specification is based on system definition. Requirement specification wil state what of the software rather than implying how of the software.

User Requirements:-

Minimal manual work No wastage of time Reduced cost Reduction in human errors

Hardware Requirements:32 MB RAM 1 GB Hard Disk Space

Software Requirements:32 BIT OPERATING SYSTEM 9X/2000 JAVA

Notepad saving the files

CONCLUSION
This training report as well as the project report is interwoven with my deep involvement with the concepts of C++ and Core Java. This is an involvement which led to my participation in the world of programming with the wonderful and to be more precise the powerful world of Java and C++. I found, while working in the training and with the project a very friendly environment and a exposure to vast knowledge that would be worth remembered throughout my life. Being my first training and also the first chance to get an exposure to industrial institute was a great experience and also a sea full of knowledge. During it I had the opportunity of working under very good programmers of Niit hamirpur who, were a great source of knowledge and inspiration. I earnest hope and pray that the development resulting from the training and the project will eventually help me to become a good programmer.

You might also like