0% found this document useful (0 votes)
169 views57 pages

UBJSTRAINING

this doc is copy righted to me ..and published in birlasoft for all future trainees ...i wish to share it with all of my regular readers ..i wish it would prove to be of some help to the programmers who are beginning with java...i have executed every basic concept and pasted screenshots of them to show how they run ..

Uploaded by

Uddalak Banerjee
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
169 views57 pages

UBJSTRAINING

this doc is copy righted to me ..and published in birlasoft for all future trainees ...i wish to share it with all of my regular readers ..i wish it would prove to be of some help to the programmers who are beginning with java...i have executed every basic concept and pasted screenshots of them to show how they run ..

Uploaded by

Uddalak Banerjee
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 57

0

Java Training

A pdf file composed by Uddalak Banerjee ,Emp Id -60527 ,Grade –


A0,Date of joining-5th aug,2010 based on Java-training at Birlasoft
conducted by Mr Abhishek Shahi .

Saturday, 11 September 2010


1

CONTENTS
1.Software Requirements

2.Steps to Install Eclipse

3.How to open a project file

4.How to configure build path

5.Sample Java program.

6.Access Modifiers

7.Methods

8.Compilation and Exception Handling using try-catch-finally.

9.Polymorphism concepts

10 Abstract Classes and interfaces

11 Inheritance

12 Composition

13.How to Debug a file in Eclipse.

Saturday, 11 September 2010


2

13.Control Statements

14.Wrapper Classes

15.Creating new Exceptions

16.Static blocks,anonymous classes.

17.File handling.

18.Collection(ArrayList,LinkedList,HashMap)

19.Nested Classes

20 Tomcat Server installation and working

21.How to create .War file

22.How to create Servlet

Saturday, 11 September 2010


3

1.Software Requirements
Softwares to install:

1.eclipse-jee-galileo-SR2-win32

2. jdk-6u3-windows-i586-p

3.apache tomcat 6.0.20.zip

2.Steps To Install Eclipse

Step 1. Cut Eclipse-jee-galileo-SR2-win32 and paste in host folder

Step 2. Install jdk-6u3

Step 3.Create shortcut on desktop

Note:Preferred Setting of workspace based on disk space


availability can be done by manually fixing the path at the time of
installation.

3.HOW TO OPEN A PROJECT FILE

Saturday, 11 September 2010


4

Opening a Project File

Step 1:

File/New/Other/Java/JavaProject/Next/ProjectName(java training)
5

Jre is set to Use execution JRE(default)/

Step 2:

PRESS Next button and set path for src files(Eg javatraining/src)

And class files (Eg: javatraining/bin)

Step 3:
6

Libraries/jreSystemLibrary[javaSE 1.6]

/Addjar(If libraries are available in own project)

PRESS FINISH AND YES

4.How to configure build path

Setting of build path:


7

RightClick Project/Buildpath/Configure buildpaths/Source.

Add Library/JreSystemLibrary

Java Uses Optimisation

Create a file

Src/New/File/Filename

Note:Name Start with Capital Letter


8
9

FILE STRUCTURE studied so far:

For any project we have a project name and followed by two


folders one is source and the other bin.Source folder contains

Java source files and bin contains class files generated by the
compiler on compilation of the source files.

A SAMPLE JAVA program:


10

The output of the above code comes out to be:

Right Click/RunAs/java application


11

Debugging a java file/project

Keys that are used for debugging are :

F5----------used to get into the code

F6----------Debugging-executing each statement and moving to the


next

F3---------Open declaration

Alt+left----Go back at debugging time.

To open the debugging perspective right click on the code and


select java application.

First creating a java application uddalak3.java which contains a


display method , a constructor and a main method under the class
named uddalak3.
12

Now while debugging the code we first open the debug perspective
which looks as follows:

The dots which are clearly evident are the break points.

Use of f3 key gives the following scenario:

Suppose we press f3 on the uddalak3.display() method we get the


to the display method definition with the name display()
highlighted.
13

OOPS(Object Oriented Programming Structure)

Three basic concepts of polymorphism were 1.encapsulation


2.inheritance and 3.polymorphism.

Use of inheritance is to enhance reusability of code.

Use of abstraction is data hiding.

Use of polymorphism is for data security(over riding) and flexibility


in code usage based on need(over loading)

Properties of Class/Object

1.Filename ------------Mandatory

2.Access Modifier-----Mandatory

3.Package

4.Methods
14

5.Classname------------Mandatory

Important

1. There can be multiple classes in a program but one of them


has to be of same name as file name(It should be public)
2. Whatever class has main method the file should be of the
same name (as the class containing main())
3. There could not be more than one public class in the file.

CHECK POINTS:

Q1.If 2 classes without access modifier is used what will happen?

Ans:It would produce an error.

Defination of Methods:

<Access modifier> <Returntype> Methodname( parameters)

Example:

Public void main (String args[])

Access Modifiers

1.Public(Anyone can access)

2.Private(Only by you)

3.Protected(Somehow associated to you to access your data)

4.Default(Concept of package)

*Default cannot be accessed outside the host folder

#In Methods there is no concept called Default.

Saturday, 11 September 2010


15

#Without Object incase of main jvm creates an object.

COMPILATION

Javac <*.java>

Options

-D----- destination of class file to be specified at command prompt.

EXECUTION

Java *.class

JAVA VIRTUAL MACHINE

1.JVM(Java Virtual Machine)

2.JRE(Group of class files required to execute a program)

3.API(Application Programming Interface)

#States the a program is to be written.It is collection of jar files.

a.Library

b.Jar(java archive) It is a zip file

c.package

JVM is an O.S on top of another O.S

Saturday, 11 September 2010


16

STAGES OF PROJECT EXECUTION

Step 1:Requirement Analysis

Step 2:Design

Step 3:Coding

Step 4:Testing

Default variable:-When a class is used as a variable to generate other classes


then it is a default variable.

Static (Onle one variable across all objects)[life=class file]

Instance(associated with the object)[life =object file]

Local(within some member function)[life=block]


17

Properties of “final” keyword:::

1.FINAL cannot be inherited .


2.Final method cannot be overridden.
3.But final can be called by some other method.

Final variables are constants.


Constants------------1.static and 2.final

CHECK POINT:
IF A VARIABLE IS DECLARED FINAL THEN WILL IT BE AUTOMATICALLY
STATIC?
HERE
18

HER

HERE,FATHER IS THE PARENT/BASE CLASS


SON1,SON2 ARE THE CHILD/DERIVED

Keywords needed are:1. implements and 2.extends

Example:-
Class father{
Public House;
Protected V1;
}

Class Son1 extends Father {

}
-Son1 can access protected variable V1.
19

Cases:
Son 1 extends Father is Right
Son 2 extends Father is Right

Cases:
Son1 extends Father is wrong
Son 2 extends Son1 is wrong

Overloading
It is the process of using the same function name with variable number
of parameters .
20

Polymorphism involves two basic concepts:


1.Overriding+Overloading
2.Static +Runtime Binding

Interfaces
Properties of interfaces are as follows:

1.Variables are static and final


2.public
3.METHODS without implementation
21

Key points:
1.Interfaces extend other interfaces
2.classes extend classes
22

3.classes implement one or more interfaces at the same time but


extend only one class at a time.

Examples:

Binding
1.static [ Example: child1 objclass1= new child1();]
2.runtime[ Example: objclass1=objParent;]

Compositions
-Without extending ,inheriting direct use.
-protected members cannot be used.
#Interface to be created in separate file

Marker Interfaces
THESE interfaces have no body.
Eg : public interface Root{
}

Comments
23

1. /* */
2. /** **/
3. //

Parent objclass1= new Child1();


//Reference of child 1 to parent
Root objclass1=new child();
//interface implementation in Parent.

Compositions

The above example demonstrates that in a file even without using”


extends “or” implements “ ,we can create objects of one class in
another class.

ASSIGNMENT
1.Write a Calculator Program
Sum()
Sub()
Mult()
Div()
24

Calculate()—in calculator class.

Use Extends
Try Debugging
Note Error
Solution to the above assignment as executed by uddalak banerjee
,Employee id=60527 ,grade =”A0” ,date of joining 5th aug ,2010 is as
follows:
25

OUTPUT DISPLAYED:

//18.08.2010

Control Statements

1 .if else
26

2 switch

3.while

4. do while

5 for

Syntax of the above control statements is demonstrated as below:

For each statements


These are statements used for handling arrays.
Eg:
for(int a:arr)
{
System.out.println(a);
}

Operators:
Unary: Eg ++,--
Binary:Eg +,-,*,\
27

Ternary:?

ABSTRACT
abstract class a{
public int sum(int a,int b);
}

Properties of abstact classes:


1.In interfaces all methods are abstract
2.All extending classes of abstract classes must give body to all the
abstract methods
3.We may not have abstract methods in an abstract class hence we
use abstract classes when we already have interfaces.

HOW TO UNDERSTAND WHETHER TO USE AN INTERFACE OR AN


ABSTRACT CLASSES
28

Suppose we need to implement the above scenario of automobile


industry in java.In that case we define car as an interface.The
reason behind using car as an interface is that car contains a few
basic things like 4 wheels ,an engine,popularshaft(for power
transmission),chasse etc.Now, while Maruti ,Ford and Hyundai all
build cars of different engine capacity and with different chasse
design and popular shaft sizes and shapes each of these
companies(classes) essentially implement the basic features like 4
wheels ,engine,popularshaft,chasse etc.So we define the contracts
in the interface which essentially contains the basic ingrediants
which are later given body by the sub classes which implement the
interface(car).

Data Types
Int
Float
Double
Char
Long
29

Boolean
Byte
String

Wrapper Classes
Data Transfer takes place as objects only.

Uses of Wrapper classes


1.Wrapper Classes are used in case of type casting
2.Provides objects necessary for data transfer.
Use:
int INUM=10;

Integer iobj=Integer.parseInt(INUM);

All Datatypes have wrapper classes.

Long.intValue()----converts it into integer value.

Autoboxing
It was used to reduce overhead involved in type conversion.
30

[Available in java 5]

All exceptions created from runtime exceptions are unchecked


exceptions.
31

TRY-CATCH

For SQL code SQLexception must be caught.

Something to muse over:


Q.Can Main method be used as a part of abstract class?

Q.Can Main method be used in another class than abstract class when it is
already declared public?

Class Example:

Abstract public class AbstractTest{

Public int sum(int a ,int b){}

Abstract public float calcInterest(int p,int r,int t);

19.08.2010
32

Q.identify errors :

Abstract class A{

Public sum(int a ,Integer b)

Float f=a+b;

System.out.println(f);

Ans:

Abstract class A{

Public void sum(int a ,Integer b)

Float f=a+b;

System.out.println(f);

Creating Exceptions of your own

public class MyException extends Exception{

My Exception(String S){

Super (s);/*calls constructor of base class

Assignment no 2

Saturday, 11 September 2010


33

Q1. Create static block example.

Q2.Create new exception.

Q3.Try implementing

Integer i=null;

Integer j=10;

System.out.println(i+j);

Q4.Try implementing ‘constructor calling’ based on following:

Q5.Implement the following code and note the error:

Public class A{

Public void int1(int a,Integer b)

Float f=a+b;

System.out.Println(f);

Q6. Create an exception try passing a String


34

Q7.Try Finally without catch in a try block

Q8.Try File Reader example.

Solution to the assignment is as follows:(as implemented by me UDDALAK


BANERJEE EMP NO 60527)
35

PACKAGES:
36

Throws

Catch(IOException e){

Throw newMyexception(“Hello”);

/*creates new instance of our MyException class*/

Throw blocks are written within catch block.

For every new Exception there has to be a try catch block .

Public int sum(int a,int b){

Return a+b;

Public int div(int a,int b) throws Exception

Return a/b;/*can throw exception so it has to be accompanied by a try catch


exception*/
37

*’Throws’ keyword is used to delegate responsibility of catching the


exception to calling code.

*A TRY BLOCK CAN HAVE MULTIPLE CATCH BLOCKS .

HIERARCHY IS LOWEST TO UPPER (Eg.we start with the lowest exception like
divide by zero exception then follow it up with its bigger parent exception
Arithmetic Exception and Then Exception .)

FINALLY

Syntax:

Try{

Catch(Exception e)

finally(){
38

/*this block is always executed irrespective of whether catch exceptions


match or not*/

Garbage collection

By initialising Null we make an object eligible for garbage collection.

Finalize{

// called when object is ready for garbage collection

//it may or may not run immediately.

Use(finally)

1. To release handle after usage(Deadlock prevention)


2. Operations which must be executed always.

IO
Standard Outputs:
Console
Printer device
File
Database
StandardInputs:
mouse
keyboard
scanner
**Object is foremost parent of any class in Java
//20.08.2010

Nested Classes

Public Outerclass{
Class SuperClass{
}
}

Saturday, 11 September 2010


39

Incase of methods if a class is created within a method then the scope


of the class is limited to that method.

Class Outerclass{

Class Superclass{
}
Static class Test{
Int i;}}
Way to access
System.out.println(Outerclass.Test.i);

Anonymous Inner Class


Anonymous class scope is in method itself.
It is not mandatory to create interface to use anonymous classes.We
can create base classes and extend it so as to use anonymous classes.
40

List
1.ArrayList
2.LinkedList
3.Vector

Map
41

1.HashMap
2.HashTable

Advantages of Linked List


1.Random memory allocation can be done by Linked List
2. Modification is fast
DisAdvantages(LinkedList)
1.Traversal is slow

Synchronized method
One process can access a resource then simultaneously another
process cannot access the same resource.
Note:Synchronized method should be small block of code
Synchronize{ }
Points to note:
#HashTable is synchronized but HashMap is not.
#In a Map of values are stored in the form of ArrayList then one key
value may point to multiple values.
#Vectors are no more used .Preferably ArrayList and LinkedLists are
used.

Assignments :
1. Create List of 10 values

Remove 5th element and 8th element

Add new value 5th and change 10th element

2.Try Employee Example

3.Create a class which has certain parameters:

Int day;----------------------------------------display Topics(day);

String Training Name;----------------------display Training(day);

List Topics;-------------------------------------add Training(); removeTraining();

Saturday, 11 September 2010


42

The answers to the assignment as executed by uddalak banerjee


empid=60527 ,grade=a0,date of joining =5th aug, 2010

Ans 1:

Ans 2:
43

Ans 3:
44

TOMCAT CONFIG

Bin/startup.bat/CreateShortcut
Now go to Start>Run>cmd
45

And then repeat the following steps –(in the present case tomcat 6 has
been installed in d drive within ubj folder .SO accordingly the path is
traced as follows:

Set Path
Once we had tried out all the steps we find the error message as
displayed.Neither the JAVA_HOME .....(as displayed).

Rightclick on Mycomputer and go to System properties tab


46

Click on environment variables\Add new Variable\JAVA_HOME


Set the path of jdk as installed in the computer there as value.
In this case the path of jdk installed in my computer was ---
C:\Program Files\Java\jdk1.6.0_03
47

WEB APPLICATION STRUCTURE:


48

STEPS REQUIRED TO CREATE WEB PROJECTS


File\New\Other\Web\Dynamic Web Project\Proj Name

HOW TO CREATE WAR FILE:

<?xml version="1.0" ?>


<!--
=======================================================================
-->
<!--
Build file
-->
<!- -IT USUALLY IS COMPOSED OF <project name> WHICH IN THIS CASE IS TRAINING
APPLICATION and a default tag which indicates the execution of which part of the code
The projectname.war file is to be created.Base directory indicates the directory where
the project is present .Similarly all the subdirectories necessary for the execution for the
project are provided with corresponding paths in the form of <values> tag.
=======================================================================
-->
- <project name="Training Application" default="deploy" basedir=".">
<property name="app.name" value="bsltraining" />
<property name="tomcat.deploy.dir" value="e:\training\tomcat6\webapps" />
<property name="lib.dir" value="${basedir}\WebContent\WEB-INF\lib" />
<property name="webinf.dir" value="${basedir}\WebContent\WEB-INF" />
<property name="build.dir" value="${basedir}\build" />
<property name="src.dir" value="${basedir}\src" />
49

<property name="dist.dir" value="${basedir}\dist" />

<!—target tag is used to define the various activities that take place subsequently.The first
activity that is performed during creation of a .war file is that all previous instances of
build and dist directories for the project is deleted.
-- >
- <target name="clean">
<delete dir="dist" />
<delete dir="build" />
</target>
<!--
===================================================================
-->
-<!--
The Classpath needs to be set for the build file.This is done be
specifying the fileset tag .jar files were also included by the include tag
to the fileset.
--> - <!--
===================================================================
--> - <path id="build.classpath">
- <fileset dir="${lib.dir}">
<include name="**/*.jar" />
</fileset>
</path>
- <!--
===================================================================
-->
- <!--
Prepares the build directory .depends=”clean” implies that the prepare
block is to be executed only when clean block has been executed properly
.In the prepare block we created the file structure necessary for a web
project .A web project essentially contains a lib file ,classes file and
the web.xml file under the WEBINF folder which had been already discussed
previously in the structuring of web projects section.So in this section we
prepare the directory structure by making directories through the mkdir tag
and specifying the location where it is to be created.
-->
- <!--
===================================================================
-->
- <target name="prepare" depends="clean">
<mkdir dir="dist" />
<mkdir dir="${build.dir}/WEB-INF/lib" />
<mkdir dir="${build.dir}/WEB-INF/classes" />
<mkdir dir="${build.dir}/jsp" />
</target>
<!--
===================================================================
-->
<!--
Compiles the source code to build directory.Compile block depends on
prepare blocks execution.So only when the prepare block has been correctly
executed the compile block is to be executed.Compilation of the file
requires the java compiler(javac) which again requires a source and
destination directories which are specified by srcdir and destdir
-->
<!--

Saturday, 11 September 2010


50

===================================================================
-->
- <target name="compile" depends="prepare" description="Compiles the Service class
files">
- <javac srcdir="${src.dir}" destdir="${build.dir}/WEB-INF/classes" debug="true"
deprecation="${deprecation}" optimize="${optimize}">
<classpath refid="build.classpath" />
</javac>
- <copy todir="${build.dir}/WEB-INF/lib" includeemptydirs="yes" overwrite="yes">
<fileset dir="${lib.dir}" />
</copy>
- <copy todir="${build.dir}/jsp" includeemptydirs="yes" overwrite="yes">
<fileset dir="${basedir}\WebContent\jsp" />
</copy>
<copy file="${webinf.dir}\web.xml" todir="${build.dir}\WEB-INF" />
</target>
- <!--
===================================================================
-->
- <!--
Prepares war .prepare war block of code is executed only when compile block
has been correctly executed(Hence we used depends=”compile”).War files base
directory is the current build directory which we just created and the
destination directory is the dist.dir which we had just created and this is
the place where the .war is to be placed after it is created.Web xml
reference is the position of the file web.xml which is needed to specify
the components of the project.
--> <!--
===================================================================
-->
- <target name="prepare-war" depends="compile" description="Creates the WAR
File">
<war basedir="${build.dir}/" destfile="${dist.dir}/${app.name}.war"
webxml="${webinf.dir}/web.xml" />
</target>
<!--
===================================================================
-->
<!--
Deploys to Tomcat Server.The deploy block is dependent on the prepare war b
lock of code.To execute the deploy block the correct execution of prepare
war block is necessary.In this block we copy the .war file just created in
the dist directory to the tomcat.deploy directory.
-->
<!--
===================================================================
-->
- <target name="deploy" depends="prepare-war" description="Deploys to Tomcat
Server">
<copy file="${dist.dir}\${app.name}.war" todir="${tomcat.deploy.dir}" />
</target>
</project>

Saturday, 11 September 2010


51

SERVLET
Servlet is used to trigger different classes.Jsp is used to mainly to
create View/Presentation Layer.

METHODS OF SIGNIFICANCE WHILE IMPLEMENTING A SERVLET:


SendError
doPut
doDelete
forward
include
sendRedirect
Other important topics to be covered are
printContent
Contenttype

Creation of a web project is demonstrated as below:

Step 1:
First a project is created by File/new/Others/Dynamic Web Project.
Step 2:
52

Then a project name is given to the project which in our instance is


uddalakweb

Press NEXT
Step 3:

Select the default output folder as build1\classes.Press Finish.

Step 4:
Create a folder named classes under the WebContent\WEB_INF.

Step 5:
Create folders named “ build “and “dist” under the uddalakweb
project.
Note:build and dist folders are created for the purpose of .war file
creation.
53

Step 6:
Create a Jsp folder under the WebContent folder.
Note:This folder is used to store the jsp files.

Step 7:
Create a servlet by src/CreateServlet/package/Servlet
54

The new servlet looks like:

Step 8:
55

Copy servlet-api.jar from tomcat6/lib folder and paste it in


WEB_INF/lib

Step 9:
Make the build.xml file as already prescribed in .war creation.Deploy it
using ant build.
56

Step 10:
Execute the application and use web browser to access the servlet.

NOTE:Everytime on producing any change in the application .Build the


application again and remove the old .war file manually .

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy