Training Report
Training Report
Training Report
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.
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
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
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; }
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
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; }
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.
return 0; }
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.
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;}
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.
DERIVED CLASS VISIBLITY PUBLIC DERIVATIO N NOT INHERITED PUBLIC PRIVATE DERIVATION NOT INHERITED PRIVATE PROTECTED DERIVATION NOT INHERITED PROTECTED PROTECTED
PROTECTED PRIVATE
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.
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;}
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).
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
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.
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);
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
} 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.
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.
2)
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.
Loaded Hardware Runtime JIF code Interprete Byte code Class Javac Java Greet.loader Generator r verifier class
Object-Oriented Programming
Software Engineering: It is a difficult and unruly discipline which has been tried to be reusable.
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.
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.
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>*}
Or
Class Package Directory Structure:VehicleReport. report GUI Vehicle. Company. domain Shipping / s class / /
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 ;}
Keyword: Words having special meaning for compiler to identify data type or
program construct name.
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
1) Primitive Types: Consist of 8 built-in data types, which can be categorized as follows:
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 ??
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
I. Local
II.Class
initialized automatically, created when class is loaded and continue as long as class.
III.Instance
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
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) {
public class TestScoping{ public static void main (String [] args) { ScopeExample scope=new ScopeExample(); scope.firstMethod () ;}}
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
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.
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;]}
Arrays
Memory View:-
Point [] p; p=new Point [10]; for (int i=0; i<10 ; i++) P[i] =new Point(i,i+1);} return p;}
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];
int [] myArray= {1, 2, 3, 4}; int [] hold= {10, 9, 8, 7}; System.arraycopy(myArray, 0, hold, 0, myArray.length);
Class Design
Code of Sub classingpublic class Manager extends Employee { public String dep;}
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
Showing overriding-
protected String dep; public String getDetails () { return name + dep ;}}
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}}
Overloading Method: Reusing same method name for more than one method in
class, by using different argument list.
Invoking Parent Class Constructor: It is done using keyword super from child
constructors 1st line, providing appropriate argument.
ii.
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 ();
Method- It cant be overridden. Compiler generates code that causes Final Variable- It is not initialized while declaration.
Abstract Class: It cant be instantiated, but can have data attributes, concrete
methods and constructors. Syntax- public abstract class Vehicle
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.
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
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
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:-
2)
implementation problem, so left unhandled. It is also not thrown to calling method. Result Message at run time showing step taken for correction.
EOFException FileNotFoundException NullPointerException NumberFormatException IOException SQLException RuntimeException OutOfMemoryError StackOverflowError AssertionError VirtualMachineError Exception Error Throwable
Handle exception using try-catch-finally block. Declare exceptions that a method can throw e.g. void trouble () throws IOException, OtherException {}
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.
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.
Text-Based Applications
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.
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
File myFile = new File (myfile.txt) ; myFile = new File (MyDocs, myfile.txt); File myDir = new File (MyDocs); myFile = new File (myDir,myfile.txt);
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 () ;}
Use FileWriter class to write characters. Use PrintWriter class to use print and println methods.
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) ;}
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)
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 ();
List list = new ArrayList (); Iterator elements = list.iterator (); while (elements.hasNext ()) { System.out.println (elements.next ()) ;}
java.awt Package: It provides basic GUI components used in Java applets &
applications. User interfaces are built by composing available components.
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
1)
1)
Layout Managers:-
public void launchFrame () { f.setLayout (new FlowLayout ()); f.add (b1); f.pack (); f.setVisible (true) ;}
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) ;}
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) ;}
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.
ActionEv actionPerformed User Pane Butto Fram clicks on ent (ActionEvent e) button l n e { . }
import java.awt.event.*;
public class ButtonHandler implements ActionListener { public void actionPerformed (ActionEvent e) { System.out.println (e.getActionCommand ()) ;}}
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) {}}
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.
if (i==50) {break ;}}}} New Thread Instance r HelloRunner Data Co CPU Thread t of Class de HelloRunn er
Thread Creation
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 ();
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.
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] ; }}
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);
Menu Bar
Menu m1 = new Menu (File); Menu m2 = new Menu (Help); mb.add (m1); mb.setHelpMenu (m2); f.setMenuBar (mb);
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);
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;
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
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.