+ All Categories
Home > Technology > Training report anish

Training report anish

Date post: 07-Dec-2014
Category:
Upload: anish-yadav
View: 657 times
Download: 0 times
Share this document with a friend
Description:
 
Popular Tags:
61
Project Report of Summer Training at HCL CDC On Core Java (J2SE) Submitted By: Under Guidance Of:
Transcript
Page 1: Training report anish

Project Report of

Summer Training at

HCL CDC

On

Core Java (J2SE)

Submitted By: Under Guidance Of:

Anish Yadav Mr. Amit Kumar

(0810910008)

Page 2: Training report anish

Acknowledgement

It’s a great pleasure to present this report of summer training in HCL CDC

(Aligarh) in partial fulfilment of engineering Programme under Aligarh College of

Engineering & Technology, Aligarh affiliated to Gautam Buddh University, Lucknow, Uttar

Pradesh. At the outset, I would like to express my immense gratitude to my training guide for

guiding me right from the inception till the successful completion of the training.

I am falling short of words for expressing my feelings of gratitude towards

him for extending their valuable guidance about applications and support in programming,

critical reviews of project and the report and above all the moral support he had provided me

with all stages of this training. I would also like to thank my friends and all my group

members for their help and cooperation throughout the training.

Anish Yadav

(0810910008)

Page 3: Training report anish

Preface

HCL CDC, one of the leading training COMPANY IN INDIA, has interest in

providing quality education and prepares IT professionals who can meet with the

international standards. Along with this HCL serves in financial services, hi-tech &

manufacturing, aerospace and defence, telecom, retail and CPG. In 1981 NIIT was

established and to increase the computer awareness in 2000 HCL ventured with NIIT.

HCL CDC services have produced thousands of Sun Certified Java

Professionals so far. It is the only institute that has been involved in preparing students for

online exams. Students of HCL CDC services are working in the leading IT companies all

over the world and some of them have got certificate of excellence wherever they are

working.

The achievement of HCL CDC services is consolidated by the fact that the

students have been coming for various courses from various parts of India.

At HCL CDC services the aim is to prepare professionals who have in-depth

knowledge of programming languages. Students at HCL CDC services are taught what

happens in language along with why it happens, so that students are able to develop logical

approach.

Page 4: Training report anish

Project Description

The project under this training was “Housie the game”. That mainly uses

swing and event handling. A typical bingo ticket is shown to the right. It contains twenty-

seven spaces, arranged in nine columns by three rows. Each row contains five numbers and

four blank spaces. Each column contains either one, two, or very rarely three, numbers:

The first column contains numbers from 1 to 9,

The second column numbers from 10 to 19,

The third 20 to 29 and so on up until the last column, which contains numbers

from 80 to 90 (the 90 being placed in this column as well).

The game is presided over by a caller, whose job it is to call out the numbers

and validate winning tickets. He or she will announce the prize or prizes for each game

before starting. The caller will then usually say "Eyes down" to indicate that he is about to

start. He or she then begins to call numbers as they are randomly selected, either by an

electronic random number generator (RNG), by drawing counters from a bag or by using

balls in a mechanical draw machine. Calling may take the format of simple repetition in the

framework, "Both the fives, fifty five", or "Two and three, twenty three", but some numbers

have special calls due to their significance.

The different winning combinations are:

Line – covering a horizontal line of five numbers on the ticket.

Two Lines – covering any two lines on the same ticket.

Full House – covering all fifteen numbers on the ticket.

This game is mainly played in UK, USA and New Zealand. It is famous in

lottery and is mainly used at the time of collection of investment and for charity work.

Page 5: Training report anish

Objective

The objective of this project is in real time utilization of the concepts of java

currently learned. The project covers all the important topics of the java so it is very helpful

in grasping the concepts of java. Java is one of the most famous languages currently being

used so its practical usage is very helpful.

Hardware & Software Requirements:

Housie requires a high configuration system for good performance because it

has to deal with a high load. So, it should be accurate and fast to meet with the demands of

the game. In software, we’ll need Java 1.4 (or above) and any editor for fast development of

such an application. We can write some hardware and software:

JDK (JDK1.7.1 will be best)

Eclipse

Pentium IV 2.33GHz

128 MB RAM

100 MB free hard disk space

Page 6: Training report anish

JAVA

The entire component has been developed using Java technology. Java has

been chosen as the platform because of its feature rich nature. The Java Platform provides

robust end-to-end solutions for networked applications as well as a trusted standard for

embedded applications. So Java was a natural choice for development process.

Characteristics of Java:

Object Oriented:

                    Java is object oriented to the truest sense of the word. Everything in Java is

represented as objects. Variables and methods both are encapsulated in objects. Java is the

purest object-oriented language.

Robust:

Java is a very robust language owing to the following features.

Excellent exception handling facilities.

Memory management relief for the user. User does not have to worry about

allocation and de allocation of memory.

Strict compile-time and runtime checks for data types.

Portable and Architecture-neutral (Platform Independent):

Java is portable and platform independent so much that they satisfy “write

once; run anywhere, anytime, forever”. This feature is implemented in the following ways:

Compiler generates  machine independent byte-code instructions which can be

run on any machine supporting Java Virtual Machine.

Size of primitive data type is machine independent.

Multithreaded:

Page 7: Training report anish

Programs can do many things simultaneously using different threads.

Provide a solution for multi process synchronization.

Allow the creation of networked and interactive programs.

Distributed: 

Open access  to remote objects by the use of RMI(Remote Method

Invocation).

Brings a level of abstraction to client/server programming.

Secure:

Security is achieved by confining a java program to the java execution      

environment and not allowing access to other parts of the user computer.

Absence of pointers provides memory related security as encroachment of

memory    is avoided Proper measures for prevention of viral infection and malicious

intent.

Dynamic and Extensible:

Facilitates linking in of new classes, objects and methods.

Supports native methods (methods written in other languages like C ,C++).

Programs carry with them a substantial amount of runtime type information

that is used to verify and resolve accesses to objects at run-time.

High Performance:

                Just-In-Time (JIT) compilers are used to convert byte-code into native machine

code resulting in very high performance. These JIT compilers can be used on a real time,

piece by piece demand basis to perform on-the-fly compilation of byte-code into native-code.

Page 8: Training report anish

Compilation and Interpretation:

Java programs are implemented as a two-stage system.

Compilation: Source code to byte-code and not machine instructions.

Interpretation: Byte-code to machine code (for any system that supports using JVM)

Thus cross-platform programs can be written.

Page 9: Training report anish

Java Fundamentals

Keywords:

Here is a list of keywords in the Java programming language. You cannot use

any of the following as identifiers in your programs. The keywords const and goto are

reserved, even though they are not currently used. true, false, and null might seem like

keywords, but they are actually literals; you cannot use them as identifiers in your programs.

Abstract continue For new switch

assert*** default goto* package synchronized

Boolean do If private This

Break double Implements protected Throw

Byte else Import public throws

Case enum**** Instanceof return transient

Catch extends Int short Try

Char final Interface static Void

Class finally Long strictfp** volatile

const* float Native super while

*  not used

**  added in 1.2***  added in 1.4

****  added in 5.0

Identifiers:

Identifiers are those words in your Java code that you choose. The names you

choose are called identifiers and must adhere to the following rules:

An identifier cannot be a keyword or true, false, or null.

An identifier can consist of letters, digits 0–9, the underscore, or the

Dollar sign.

Page 10: Training report anish

An identifier must start with a letter, an underscore, or a dollar sign.

Data Types:

There are eight primitive data types in java. In java signed data is not

supported. The primitive data types are as follows:

Fig: Java Primitive Data Types

Expressions and Flow Control

Page 11: Training report anish

In java, flow of control and expressions are like C but it has more data types in

comparison to C. I will discuss the control structures of the Java language, covering decision

making and repetition. Topics in this chapter include a discussion on Boolean logic, truth

tables, the if/else statement, the switch statement, the for loop, and while and do/while loops.

Control structures are fundamental to any programming language, not just Java. If you are

already familiar with structures like if statements and while loops, pay close attention to the

details of how these are implemented in Java.

The if Statement:

An if statement consists of a Boolean expression followed by one or more

statements.

If statements have the following syntax:

if(Boolean_expression)

{

//Statements will execute if the Boolean expression is true

}

If the Boolean expression in parentheses is true, the statements within the curly brackets are

executed. If the Boolean expression is false, the statements in curly brackets are skipped over.

In the case of false, the flow of control will jump to the statement that is immediately beyond

the curly brackets.

The if/else Statement:

An if statement can be followed by an optional else statement, which executes

when the Boolean expression is false. The syntax for an if/else looks similar to:

if(Boolean_expression)

{

//Executes when the Boolean expression is true

Page 12: Training report anish

}

else

{

//Executes when the Boolean expression is false

}

With an if/else statement, you are guaranteed that either the if block or the else block will

execute, depending on the value of the Boolean expression.

The switch Statement:

A switch statement allows a variable to be tested for equality against a list of

values. Each value is called a case, and the variable being switched on is checked for each

case.

The syntax for a switch statement looks similar to the following:

switch(variable)

{

case value :

//Statements

Control Structures 61

break; //optional

case value :

//Statements

break; //optional

//You can have any number of case statements.

default : //Optional

//Statements

}

Page 13: Training report anish

The following rules apply to a switch statement:

The variable used in a switch statement can only be an integer value 32 bits or

smaller. That means the only data types that can be switched on are byte, short, int,

and char.

You can have any number of case statements within a switch. Each case is followed

by the value to be compared to and a colon.

The value for a case must be the same data type as the variable in the switch, and it

must be a constant or a literal.

When the variable being switched on is equal to a case, the statements following that

case will execute until a break is reached.

When a break is reached, the switch terminates, and the flow of control jumps to the

next line following the switch statement.

Not every case needs to contain a break. If no break appears, the flow of control will

“fall through” to subsequent cases until a break is reached.

A switch statement can have an optional default case, which must appear at the end

of the switch. The default case can be used for performing a task when none of the

cases is true. No break is needed in the default case.

The while loop:

A while loop is a control structure that allows you to repeat a task a certain

number of times. The syntax for a while loop is:

while(Boolean_expression)

{

//Statements

}

When a while loop is first reached, the Boolean expression is checked. If the Boolean

expression is true, the statements in the body of the loop execute. The flow of control then

goes back up to the Boolean expression, which is checked again. If it is still true, the

statements in the loop execute again. This process repeats until the Boolean expression is

false.

The do/while loop:

Page 14: Training report anish

A do/while loop is similar to a while loop, except that a do/while loop is

guaranteed to execute at least one time. The syntax of a do/while loop is:

do

{

//Statements

}while(Boolean_expression);

Notice that the Boolean expression appears at the end of the loop, so the statements in the

loop execute once before the Boolean is tested. If the Boolean expression is true, the flow of

control jumps back up to do, and the statements in the loop execute again. This process

repeats until the Boolean expression is false.

The for loop:

A for loop is a repetition control structure that allows you to efficiently write a

loop that needs to execute a specific number of times. The syntax of a for loop is:

for(initialization; Boolean_expression; update)

{

//Statements

}

Here is the flow of control in a for loop:

1. The initialization step is executed first, and only once. This step allows you to declare

and initialize any loop control variables. You are not required to put a statement here,

as long as a semicolon appears.

2. Next, the Boolean expression is evaluated. If it is true, the body of the loop is

executed. If it is false, the body of the loop does not execute and flow of control

jumps to the next statement past the for loop.

Page 15: Training report anish

3. After the body of the for loop executes, the flow of control jumps back up to the

update statement. This statement allows you to update any loop control variables.

This statement can be left blank, as long as a semicolon appears after the Boolean

expression.

4. The Boolean expression is now evaluated again. If it is true, the loop executes and the

process repeats itself (body of loop, then update step, then Boolean expression). After

the Boolean expression is false, the for loop terminates.

The break keyword:

The break keyword can be used in any of the loop control structures to cause

the loop to terminate immediately. When a break occurs, no matter what the value is of the

loop counter or the Boolean expression, the flow of control will jump to the next statement

past the loop.

The continue keyword:

The continue keyword can be used in any of the loop control structures. It

causes the loop to immediately jump to the next iteration of the loop.

In a for loop, the continue keyword causes flow of control to immediately jump to the

update statement.

In a while loop or do/while loop, flow of control immediately jumps to the Boolean

expression.

Classes and Objects

Java is strictly an objected-oriented programming language. All the Java code

that you write will appear in either a class or an interface. When you write a program using

Page 16: Training report anish

an object-oriented programming language, you design your program around the objects in the

problem being solved. For each object, a class is written to describe the object’s attributes

and behaviours. By definition, a class is a description of an object. Similarly, an object is

defined to be an instance of a class. An object consists of attributes and behaviours. An

attribute is a feature of the object, something the object “has”. Behaviour is something the

object “does”.

Object Oriented Programming:

Object-oriented programming (OOP) originated from research

done by Xerox’s Palo Alto Research Centre (PARC) in the 1970s. OOP takes an entirely

different approach to developing computer applications. Instead of designing a program

around the tasks that are to be solved, a program is designed around the objects in the

problem domain.

“You can think of procedural programming as writing a procedure for the verbs

in the problem domain, such as paying an employee or computing taxes. You can think

of object-oriented programming as writing a class for each of the nouns in the problem

domain. Granted, this may be oversimplifying OOP, but I want you to conceptually

understand this important difference between OOP and procedural programming.”

Let’s take another look at the example in which a program is to be written to

pay employees of a company on a weekly basis. Instead of approaching this problem from the

point of view of all the little tasks that need to be performed, such as computing an

employee’s pay and taxes, you begin by determining the objects in the problem domain. An

object is any person, thing, or entity that appears in the problem domain. In our example, we

want to pay employees, so the employees are objects. The employees work for a company, so

the company is another object. After further analysis, you might decide that the payroll

department is an object. After you start writing the program, other objects will be discovered

that were not apparent in the initial design.

After you have determined the objects in the problem, you write a class to

describe the attributes and behaviours of each object. For example, we will need an Employee

class that contains the attributes and behaviours of an employee. The attributes of an

Employee object will be what the employee “has,” such as a name, address, employee

Page 17: Training report anish

number, Social Security number, and so on. Each of these attributes will be represented by a

field in the Employee class. The behaviours of an Employee object are what the employee

object “does”(or, more specifically, what we want the object to do). Employees do many

things, but for our purposes, we want to be able to compute their pay and mail them a

paycheck once a week. These desired behaviours become methods in the Employee class.

A Java Class:

A class in Java is declared using the class keyword. A source

code file in Java can contain exactly one public class, and the name of the file must match the

name of the public class with a .java extension.

“You can declare more than one class in a .java file, but at most one of the

classes can be declared public. The name of the source code file must still match the

name of the public class. If there are no public classes in the source code file, the name

of the file is arbitrary."

The fields and methods of a class appear within the curly brackets of the class

declaration. The following code shows a simple class with no fields or methods declared yet.

public class Employee

{

}

Fields of a Class:

The attributes of an object become fields in the corresponding class. A field

within a class consists of the following:

Page 18: Training report anish

Access specifier, which can be public, private, or protected; or the access specifier

an be omitted, giving the field the default access.

Data type.

Name, which is any valid identifier that is followed by a semicolon.

public class Employee

{

public String name; //First and last name

public String address; //Mailing address

public int number; //Employee number

public int SSN; //Social Security number

public double salary; //Employee’s salary

}

Methods of a Class:

Behaviours of an object become methods in the corresponding class. A

method within a class typically consists of the following:

Access specifier

Return value

Name, which can be any valid identifier

List of parameters, which appears within parentheses

Definition of the method

In Java, the definition (often referred to as the body) of a method must appear

Page 19: Training report anish

within the curly brackets that follow the method declaration. The following class

demonstrates methods by adding two methods to the Employee class.

public class Employee

{

public String name;

public String address;

public int number;

public int SSN;

public double salary;

public void mailCheck()

{

System.out.println(“Mailing check to “ + name

+ “\n” + address);

}

public double computePay()

{

return salary/52;

}

}

Accessing Fields and Methods:

When you instantiate an object using the new keyword, memory is allocated

for each of the fields and methods in the class. You need a reference to the object to access

these fields and methods using the dot operator. For example, the following statements

declare an Employee object and change the name field of the object:

Employee e = new Employee();

e.name = “Robert Smith”;

Instantiating an Object:

Page 20: Training report anish

In Java, the new keyword is used to instantiate an object. The new operator

creates the object in memory and returns a reference to the newly created object. This object

will remain in memory as long as your program retains a reference to the object. The

following statements declare an Employee reference and use the new keyword to assign the

reference to a new Employee object.

Employee e;

e = new Employee();

The reference e is pointing to the Employee object in memory. The new operator allocates

memory for the object and then “zeroes” the memory so that none of the object’s fields will

contain garbage.

Garbage Collection:

In other OOP languages such as C++, memory has to be explicitly freed by the

programmer. In fact, C++ has a delete keyword that needs to be used to free the memory of

an object. If you forget to delete an object in C++ and you lose any references to it, the

memory can never be freed and you have created what is referred to as a memory leak, which

can wreak havoc on your programs, especially programs that use large amounts of memory or

run for long periods.

In Java, there is no keyword or operator that you can use to remove an object

from memory. Java was designed to avoid the problems of memory leaks that arise in other

languages. A JVM has a low-level thread known as the garbage collector that is constantly

running in the background, looking for objects in your Java program that are no longer being

used and freeing their memory.

Interfaces

An interface is a collection of abstract methods. A class implements an

interface, thereby inheriting the abstract methods of the interface. Unless the class that

implements the interface is abstract, all the methods of the interface need to be defined in the

class. An interface is similar to a class in the following ways:

Page 21: Training report anish

An interface can contain any number of methods.

An interface is written in a file with a .java extension, with the name of

the interface matching the name of the file.

The byte code of an interface appears in a .class file.

Interfaces appear in packages, and their corresponding bytecode file must be in a

directory structure that matches the package name.

However, an interface is different from a class in several ways, including:

You cannot instantiate an interface.

An interface does not contain any constructors.

All of the methods in an interface are abstract.

An interface cannot contain instance fields. The only fields that can appear in an

interface must be declared both static and final.

An interface is not extended by a class; it is implemented by a class.

An interface can extend multiple interfaces.

“An interface is not a class. Writing an interface is similar to writing a

class, but they are two different concepts. A class describes the attributes and

behaviours of an object. An interface contains behaviours that a class implements.”

Interfaces have many uses and benefits. For example, an interface can be used

to expose certain behaviours of a class, without exposing all of the behaviours of a class.

Interfaces can be used to force behaviour on other objects, ensuring that certain methods are

implemented by an object. Interfaces can be used for polymorphism reasons, since an object

can take on the form of an interface type.

Page 22: Training report anish

Exception Handling

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

exception can occur for many different reasons, including the following: a user has entered

invalid data, a file that needs to be opened cannot be found, a network connection has been

lost in the middle of communications, or the JVM has run out of memory.

Some of these exceptions are caused by user error, others by programmer

error, and others by physical resources that have failed in some manner. In this chapter, I will

discuss the various types of exceptions, when you should throw one, and when you should

Page 23: Training report anish

catch one (and times when you do not have a choice), and how to write and throw your own

exceptions. To understand how exception handling works in Java, you need to understand the

three categories of exceptions:

Checked exceptions:

A checked exception is an exception that is typically a user error or a problem

that cannot be foreseen by the programmer. For example, if a file is to be opened, but the file

cannot be found, an exception occurs. Because this type of exception is a checked exception,

it must be dealt with in Java and cannot simply be ignored (as we will see when we discuss

the Handle or Declare Rule).

Runtime exceptions:

A runtime exception is an exception that occurs that probably could have been

avoided by the programmer. As opposed to checked exceptions, runtime exceptions can be

ignored (and should be, in most cases). You should let a runtime exception crash your

program, then find the problem and change your code so that the exception does not arise

again. Examples of runtime exceptions include running off the end of an array, integer

division by zero, referencing a null reference, and casting a reference to an invalid data type.

Errors:

Actually, these are not exceptions at all, but problems that arise beyond the

control of the user or the programmer. Errors are typically ignored in your code because you

can rarely do anything about an error, even if you wanted your program to fix the problem.

For example, if a stack overflow occurs, an error will arise. However, because you are out of

memory, your program will be unable to continue executing. Any code you have written that

attempts to fix the problem won’t get a chance to execute anyway, so errors are often ignored

when designing and writing Java applications.

Flow of Control of Exception:

Exceptions in Java are objects that are thrown by a method. When a method is

invoked, it is pushed onto the method call stack. When a method throws an exception, the

method is popped off the call stack, and the exception is thrown to the previous method on

Page 24: Training report anish

the stack. For example, suppose that main() is at the bottom of the call stack, followed by

method1() and then method2(). If method2() throws an exception, method2() is popped off

the call stack, and the exception is thrown down to method1().

With an exception heading its way, method1() has three choices:

Catch the exception so that it does not go any further down the call stack.

Catch the exception, then throw it back down the call stack.

Not catch the exception, thereby causing method1() to be popped off the call stack,

with the exception continuing down the call stack to main().

This flow of control continues down the call stack, no matter how many

methods appear on the call stack. Each method further down the call stack

either catches the exception and stops this process, catches the exception and

throws it again, or simply does nothing and lets the exception fall through to

the next method.

What happens when we reach the bottom of the call stack? Well, if an exception

is thrown to main(), then main() had better catch the exception or the program

will terminate. When an exception reaches the bottom of a call stack and

no method has stopped it along the way, the JVM will crash and inform you of

the details of the exception.

Let’s look at an example of what happens when an exception is ignored all the way down the

call stack. The following CrashDemo program has three methods: main(), method1(), and

method2(). Study the program and try to determine what happens when it executes.

public class CrashDemo

{

public static void main(String [] args)

{

System.out.println(“Inside main...”);

int [] values = {1, 2, 3, 4};

Page 25: Training report anish

System.out.println(“Invoking method1...”);

method1(values);

System.out.println(“*** Back in main ***”);

}

public static void method1(int [] x)

{

System.out.println(“\nInside method1...”);

method2(x);

System.out.println(“*** Back in method1 ***”);

}

public static void method2(int [] y)

{

System.out.println(“\nInside method2”);

System.out.println(y[5]);

System.out.println(“*** Leaving method2 ***”);

}

}

Throwable Classes:

The three types of exceptions share a common parent: the java.lang.Throwable

class. Only objects of type Throwable can be thrown by the JVM. The Throwable class has

two child classes: Exception and Error.

Methods of Throwable Class:

Exceptions are Java objects of type Throwable. When you

catch an exception, you catch a reference to a Java object. Each exception class is different

and has its own set of useful methods, but because all exceptions extend from Throwable,

you can also invoke the methods of the Throwable class on any caught exception.

The following is a description of some of the methods in Throwable. Be sure

to check the documentation for a complete description of all the methods in the Throwable

class.

public String getMessage(). Returns a detailed message about the exception that has

occurred. This message is initialized in the Throwable constructor.

Page 26: Training report anish

public Throwable getCause(). Returns the cause of the exception as represented by a

Throwable object. This cause is initialized using either one of the Throwable constructors or

the initCause() method.

public String toString(). Returns the name of the class concatenated with the result of

getMessage().

public void printStackTrace(). Prints the result of toString() along with the stack trace to

System.err, the error output stream. (System.err is the command prompt for your Java

programs running on Windows.) This method is overloaded for sending the stack trace to an

output stream that you specify.

public StackTraceElement [] getStackTrace(). Returns an array containing each element

on the stack trace. The element at index 0 represents the top of the call stack, and the last

element in the array represents the method at the bottom of the call stack. This method allows

your application to programmatically iterate through each line of the call stack.

public Throwable fillInStackTrace(). Fills the stack trace of this Throwable object with the

current stack trace, adding to any previous information in the stack trace.

The methods in Throwable are designed to assist you in determining how and

where the problem occurred.

Catching Exception:

A method catches an exception using a combination of the try and catch

keywords. A try/catch block is placed around the code that might generate an exception.

Code within a try/catch block is referred to as protected code, and the syntax for using

try/catch looks like the following:

try

{

//Protected code

}catch(ExceptionName e1)

Page 27: Training report anish

{

//Catch block

}

A catch statement involves declaring the type of exception you are trying to catch. If an

exception occurs in protected code, the catch block (or blocks) that follow the try is checked.

If the type of exception that occurred is listed in a catch block, the exception is passed to the

catch block much as an argument is passed into a method parameter.

Multiple Catch Blocks:

A try block can be followed by multiple catch blocks. The syntax for multiple

catch blocks looks like the following:

try

{

//Protected code

}catch(ExceptionType1 e1)

{

//Catch block

}catch(ExceptionType2 e2)

{

//Catch block

}catch(ExceptionType3 e3)

{//Catch block}

GUI Programming

GUI, which stands for graphical user interface, refers to that portion of a

program that the user visually sees and interacts with. The GUI is an essential part of

programs that run on windows-based operating systems such as Windows, Macintosh, and

Unix. Almost every Windows program you have used is probably a GUI program: for

example, Microsoft Word or Internet Explorer.

When Java was first released in 1995, it contained a GUI API referred to as

the Abstract Windowing Toolkit (AWT). This API contained classes like Frame to represent

Page 28: Training report anish

a typical window, Button to represent buttons, Menu to represent a window’s menu, and so

on. The classes and interfaces of the AWT are in the java.awt packages. Although it is a

useful and important API, the AWT had its shortcomings, including a lack of support for

many popular GUI components. It’s not that the AWT is not useful, but it was a lot of work

for those initial Java GUI programmers to create the look and feel that they wanted their GUI

programs to have.

“AWT components are referred to as heavyweight components because their

implementation relies heavily on the underlying operating system. The look and feel of

AWT components depend on the platform the program is running on. For example, an

AWT button will look like a Windows button when the program is run on a Windows

platform. The same button will look like a Macintosh button when the program is run

on a Macintosh platform.”

Aware of the need for a more robust API for creating GUI applications, Sun

Microsystems teamed together with Netscape (and other industry partners) and created

Swing. Swing is actually a part of the Java Foundation Classes (JFC), a collection of

technologies that includes Swing, AWT, Java 2D, Java Drag and Drop, the Accessibility

APIs, and others. The classes and interfaces of Swing are found in the javax.swing packages.

Swing is different from AWT in that Swing components are 100 percent Java,

thereby not relying on the native operating system or platform. This allows Swing

components to have a pluggable look and feel, meaning that you can decide what you want

your GUI components to look like. For example, if you want a button to look like a Windows

button, even if the program is executed on a Macintosh or Unix platform, you can denote

your Swing program as having the Windows look and feel. With the Windows look and feel,

the Swing program will look like a Windows program, no matter what operating system the

program runs on.

import java.awt.*;

import java.awt.event.*;

import javax.swing.*; //notice javax

public class Frame1 extends JFrame

Page 29: Training report anish

{

JPanel pane = new JPanel();

Frame1() // the frame constructor method

{

super("My Simple Frame"); setBounds(100,100,300,100);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

Container con = this.getContentPane(); // inherit main frame

con.add(pane); // add the panel to frame

// customize panel here

// pane.add(someWidget);

setVisible(true); // display this frame

}

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

}

Layout Managers:

A container uses a layout manager to determine both the location and size of

the components within the container. A container can be assigned one layout manager, which

is done using the setLayout() method of the java.awt.Container class:

public void setLayout(LayoutManager m)

Page 30: Training report anish

LayoutManager is an interface that all the layout managers’ classes must

implement. You can create your own layout manager by writing a class that implements the

methods of the LayoutManager interface (no small task), or you can use one of the many

layout managers of the AWT and Swing APIs, including the following:

java.awt.FlowLayout. Lays out components in a left-to-right flow, with each component

given its preferred size. A Panel has FlowLayout by default.

java.awt.BorderLayout. Divides a container into five regions, allowing one component to

be added to each region. A Frame and the content pane of a JFrame have BorderLayout by

default.

java.awt.GridLayout. Divides a container into a grid of rows and columns, with one

component added to each region of the grid and each component having the same size.

java.awt.GridBagLayout. Divides a container into regions similar to GridLayout, except

that components do not need to be the same size. Components can span more than one row or

column.

java.awt.CardLayout. Each component added to the container is treated as a card, with only

one card being visible at a time (similar to a deck of cards).

javax.swing.BoxLayout. Allows components to be laid out vertically or horizontally.

BoxLayout is similar to GridBagLayout, but it is generally easier to use.

javax.swing.SpringLayout. Lays out components with a secified distance between the edges

of each component.

javax.swing.OverlayLayout. Displays components over the top of each other, similarly to

CardLayout. This is a useful layout manager for creating tabbed panes.

Any container can use any layout manager. Notice that Frame objects and the

content pane of JFrame objects have BorderLayout by default

Page 31: Training report anish

Pluggable Look and Feel:

Swing components have what is referred to as a pluggable look and feel

(PLAF), allowing their appearance to be independent of the underlying platform. You can

create your own look and feel—determining colors, fonts, and backgrounds for all your

components. Creating your own look and feel involves a fair amount of coding and artistic

skills and is beyond the scope of this book.

However, Swing comes with a built-in look and feel for Windows, Macintosh,

and Motif, which is a Unix look and feel. There is also a default Swing look and feel, known

as the Metal look and feel. (In its earliest stages, Swing was referred to as Metal.) The

javax.swing.UIManager class maintains the current look and feel for a Java program using

Swing. In particular, the UIManager class contains methods for determining and changing the

current look and feel:

public static void setLookAndFeel(LookAndFeel x). Throws Unsupported-

LookAndFeelException. Changes the current look and feel for this Java programto the given

LookAndFeel object.

public static void setLookAndFeel(String s). Throws UnsupportedLookAnd-

FeelException. Changes the current look and feel for this Java program to the given class

name, which is a class that implements LookAndFeel.

public static LookAndFeel getLookAndFeel(). Returns the current look and feel for this

Java program as a LookAndFeel object. The LookAndFeel class is in the javax.swing

package and encapsulates a pluggable look and feel. The following classes represent the four

built-in pluggable look-and-feel components of Swing:

com.sun.java.swing.plaf.motif.MotifLookAndFeel. Creates a Motif look and feel, which is

the user interface for many Unix operating systems.

com.sun.java.swing.plaf.windows.WindowsLookAndFeel. Creates a Microsoft Windows

look and feel.

Page 32: Training report anish

com.sun.java.swing.plaf.mac.MacLookAndFeel. Creates a Macintosh look and feel. (Note

that as of J2SE 1.4, this look and feel is not completed yet.)

javax.swing.plaf.metal.MetalLookAndFeel. Creates a Metal look and feel, which is the

default for Swing applications.

GUI Components and Event Handling

Events in Java are fired and handled using a design known as the delegation

model. With the delegation model, a source generates an event and a listener handles it,

creating an object-oriented approach to handling events. (A class is written to handle the

events of a component.) There are three major players in the delegation model:

Page 33: Training report anish

The source of the event. In GUI programming, the component is the source of the event.

Events are Java objects that are instantiated by the component and passed as an argument to

any listeners.

An event listener. A listener of an event registers itself with the source of the event. When

an event occurs, the source of the event invokes a method on the listener.

An interface. The interface contains the methods that the listener must implement and that

the source of the event invokes when the event occurs.

The Event Listener Interface:

The event listener interface contains the methods that the event source invokes

on the listener, and it provides the means of communication between the source of the event

and the listener of the event. Each type of event has a corresponding listener interface.

“Java uses a standard naming convention for event classes and listener

interfaces: The name of the event class uses the convention

<Name>Event, and the corresponding listener interface uses the

convention <Name>Listener. For example, the ActionEvent class is

associated with the one method of the ActionListener interface, and the

WindowEvent class is associated with the seven methods of the

WindowListener interface.”

An event listener interface extends the java.util.EventListener interface. The

EventListener interface does not contain any methods, but is used for tagging an event

listener interface for use with the delegation model of event handling. For example, the

ActionListener interface is defined as:

package java.awt.event;

public interface ActionListener extends java.util.EventListener

{

public void actionPerformed(ActionEvent e);

}

Page 34: Training report anish

Creating an Event Listener:

If a listener wants to listen to a particular type of event, then the listener must

implement the corresponding event listener interface. From a programming point of view,

this means you need to write a class that implements the listener interface. If you want to

listen for an ActionEvent, you write a class that implements ActionListener. If you want to

listen for a WindowEvent, you write a class that implements WindowListener.

Therefore, I need to write a class that implements ActionListener. When the

actionPerformed() method is invoked, I know that the Button has been clicked, but I want to

change the background color of the window. I need to design my ActionListener class so that

it has a reference to the window. The following RandomColor class is an ActionListener that,

in its constructor, initializes a field to point to a Container whose color is to be changed. By

using a reference of type Container, this allows the RandomColor class to change the color of

not just a window, but any Container.

“Storing the data and other components that a listener needs as fields in

the listener class is a common technique when designing a listener class. Typically, these

fields are initialized in the constructor or by adding mutator (set) methods.”

import java.awt.*;

import java.awt.event.*;

public class RandomColor implements ActionListener

{

private Container container;

public RandomColor(Container c)

{

container = c;

}

public void actionPerformed(ActionEvent e)

{

System.out.println(e + “ just occurred.”);

int red, green, blue;

red = (int) (Math.random() * 256);

Page 35: Training report anish

green = (int) (Math.random() * 256);

blue = (int) (Math.random() * 256);

Color color = new Color(red, green, blue);

container.setBackground(color);

}

}

Network Programming

The term network programming refers to writing programs that execute across

multiple devices (computers), in which the devices are all connected to each other using a

network. The java.net package of the J2SE APIs contains a collection of classes and

interfaces that provide the low-level communication details, allowing you to write programs

that focus on solving the problem at hand. The java.net package provides support for the two

common network protocols:

Page 36: Training report anish

TCP: TCP stands for Transmission Control Protocol, which allows for reliable

communication between two applications. TCP is typically used over the Internet Protocol,

which is referred to as TCP/IP.

UDP: UDP stands for User Datagram Protocol, a connection-less protocol that allows for

packets of data to be transmitted between applications. In the following sections, we take a

look at the way these two protocols compare.

Transmission Control Protocol:

Transmission Control Protocol (TCP) is often compared to making a telephone

call. If you want to telephone someone, the person needs to have a phone, needs a phone

number, and needs to be waiting for an incoming call. After the person you are calling

answers the telephone, you now have a reliable, two-way communication stream, allowing

either person to talk to the other (even at the same time). If one person hangs up the phone,

the communication is over.

The java.net.ServerSocket and java.net.Socket classes are the only two classes

you will probably ever need to create a TCP/IP connection between two computers unless

you require a secure connection, in which case you would use the SSLServerSocket and

SSLSocket classes in the javax.net.ssl package.

User Datagram Protocol:

User Datagram Protocol (UDP) provides a protocol for sending packets of

data called datagrams between applications. If TCP is similar to placing a telephone call,

UDP can be compared to mailing someone a letter. The datagram packet is like a letter,

where a client sends a datagram to a server without actually connecting to the server. This

makes UDP an unreliable communication protocol when compared to TCP, where the client

and server are directly connected.

The java.net.DatagramPacket and java.net.DatagramSocket classes are used

to send and receive datagram packets; I will show you how this is done in the

upcoming section Overview of Datagram Packets.

Sockets:

Page 37: Training report anish

If TCP is similar to placing a telephone call, a socket is the telephone. Sockets

provide the communication mechanism between two computers using TCP. A client program

creates a socket on its end of the communication and attempts to connect that socket to a

server. When the connection is made, the server creates a socket object on its end of the

communication. The client and server can now communicate by writing to and reading from

the socket. The java.net package contains classes that provide all of the low-level

communication for you. For example, the java.net.Socket class represents a socket, and the

java.net.ServerSocket class provides a mechanism for the server program to listen for clients

and establish connections with them. The following steps occur when establishing a TCP

connection between two computers using sockets:

1. The server instantiates a ServerSocket object, denoting which port number

communication is to occur on.

2. The server invokes the accept() method of the ServerSocket class. This method waits

until a client connects to the server on the given port.

3. After the server is waiting, a client instantiates a Socket object, specifying the server

name and port number to connect to.

4. The constructor of the Socket class attempts to connect the client to the specified

server and port number. If communication is established, the client now has a Socket

object capable of communicating with the server.

5. On the server side, the accept() method returns a reference to a new socket on the

server that is connected to the client’s socket.

Server Socket Class:

The java.net.ServerSocket class is used by server applications to obtain a port

and listen for client requests. The ServerSocket class has four constructors:

Page 38: Training report anish

public ServerSocket(int port) throws IOException: Attempts to create a server socket

bound to the specified port. An exception occurs if the port is already bound by another

application. The port parameter can be 0, which creates the socket on any free port.

public ServerSocket(int port, int backlog) throws IOException: Similar to the previous

constructor, the backlog parameter specifies how many incoming clients to store in a wait

queue. If the queue is full, clients attempting to connect to this port will receive an exception.

If the value is 0, the default queue size of the native platform is used.

public ServerSocket(int port, int backlog, InetAddress address) throws

IOException:Similar to the previous constructor, the InetAddress parameter specifies the

local IP address to bind to. The InetAddress is used for servers that may have multiple IP

addresses, allowing the server to specify which of its IP addresses to accept client requests

on.

public ServerSocket() throws IOException: Creates an unbound serversocket. When using

this constructor, use the bind() method when youare ready to bind the server socket. Notice

that each of the constructors throws an IOException when something goes wrong. However,

if the ServerSocket constructor does not throw an exception, it means that your application

has successfully bound to the specified port and is ready for client requests. Here are some of

the common methods of the ServerSocket class:

public int getLocalPort(): Returns the port that the server socket is listening on. This

method is useful if you passed in 0 as the port number in a constructor and let the server find

a port for you.

public Socket accept() throws IOException: Waits for an incoming client. This method

blocks until either a client connects to the server on the specified port or the socket times out,

assuming that the time-out value has been set using the setSoTimeout() method. Otherwise,

this method blocks indefinitely.

public void setSoTimeout(int timeout): Sets the time-out value for how long the server

socket waits for a client during the accept().

Page 39: Training report anish

public void bind(SocketAddress host, int backlog): Binds the socket to the specified server

and port in the SocketAddress object. Use this method if you instantiated the ServerSocket

using the no-argument constructor.

Database Programming

The JDBC API is an API for accessing data in a tabular format, which

includes every popular database as well as spreadsheet applications such as Microsoft Excel

and files that contain tabular data.

java.sql. Referred to as the JDBC Core API.

Page 40: Training report anish

javax.sql. Referred to as the JDBC Optional Package API. (In JDBC 2.0, this package was

formerly known as the JDBC Standard Extension API.)

“JDBC is not an acronym, but rather a trademarked name, although you

will commonly hear it referred to as Java Database Connectivity. The term JDBC

evolved from the acronym ODBC, which stands for Open Database Connectivity, a

technology designed to simplify database programming by making the code to access a

database independent of the actual database used.

JDBC provides the same capabilities as ODBC, allowing Java programs

to contain database-independent code. This means that a Java program thataccesses a

database is not only portable across JVMs (since it’s a Java program), but portable

across databases, since it uses JDBC.”

The JDBC API provides a mechanism for Java code to be portable across

databases. JDBC simplifies the creation and execution of Structured Query Language (SQL)

statements. SQL is a language used to communicate with a database and access its contents.

Connecting to Drivers:

After you have a data source name created, there are two ways to establish a

connection to the database using JDBC. (See the Web site’s URL provided in the

Introduction for instructions on how to do this for Windows and Microsoft Access.)

Use the static method getConnection() in the java.sql.DriverManager class, which

takes in a URL representing the data source name.

Use JNDI (Java Naming and Directory Interface) to look up the data source name,

which is returned as a javax.sql.DataSource object, and then use the getConnection()

method of the DataSource class.

import java.sql.*;

public class DriverManagerDemo

Page 41: Training report anish

{

public static void main(String [] args)

{

String url = “jdbc:odbc:” + args[0];

System.out.println(“Attempting to connect to “ + url);

try

{

System.out.println(“Loading the driver...”);

Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);

System.out.println(“Establishing a connection...”);

Connection connection =

DriverManager.getConnection(url);

System.out.println(“Connect to “

+ connection.getCatalog() + “ a success!”);

}

catch (Exception e)

{

e.printStackTrace();

}

}

}

Conclusion

Java offers the real possibility that most programs can be written in a type-safe

language. However, for Java to be broadly useful, it needs to have more expressive power

than it does at present.

This project addresses one of the areas where more power is needed. It extends

Java with a mechanism for parametric polymorphism, which allows the definition and

implementation of generic abstractions. The paper gives a complete design for the extended

Page 42: Training report anish

language. The proposed extension is small and conservative and the paper discusses the

rationale for many of our decisions. The extension does have some impact on other parts of

Java, especially Java arrays, and the Java class library.

The project also explains how to implement the extensions. We first sketched

two designs that do not change the JVM, but sacrifice some space or time performance. Our

implementation avoids these performance problems. We had three main goals: to allow all

instantiations to share the same bytecodes (avoiding code blow up), to have good

performance when using parameterized code, and to have little impact on the performance of

code that does not use parameterization.

The implementation discussed in Section 3 meets these goals. In that section,

we described some small extensions to the virtual machine specification that are needed to

support parameterized abstractions; we also described the designs of the bytecode verifier and

interpreter, and the runtime structures they rely on.

Preliminary performance results from our implementation of the extended

bytecode interpreter show roughly a 2% penalty for the presence of parameterized code, but a

speedup for parameterized code of 17%, by eliminating runtime checks. We expect that some

simple performance tuning can improve these results.

Bibliography

www.java.com/getjava/

www.oracle.com/technetwork/java/javase/

Page 43: Training report anish

download.oracle.com/javase/tutorial/


Recommended