javaseminor
TRANSCRIPT
-
7/27/2019 JavaSeminor
1/71
TOKGISL
WELCOME
-
7/27/2019 JavaSeminor
2/71
JAVA
-
7/27/2019 JavaSeminor
3/71
What is JAVA?
A high level Programming Language.
Java was developed by a group of people at Sun
Microsystems, Inc. in 1991.
Original need for the language.
Redefined need.
Difference with the Native language C .
-
7/27/2019 JavaSeminor
4/71
Why JAVA?4
Object Oriented
Simple & Secure
Architecture Neutral
Portable & Robust Interpreted
High Performance
Distributed Dynamic
Multi-threaded
AWT & Event Handling
Write Once;Run Anywhere,any time,forever
-
7/27/2019 JavaSeminor
5/71
Heart of JAVA
-
7/27/2019 JavaSeminor
6/71
Installing JAVA
Download the Java Development Kit (JDK) for yourplatform. (Its free)
Run the .exe file to install java on your machine.(or)
Follow the instructions given.
-
7/27/2019 JavaSeminor
7/71
Setting Path
Start Control Panel System Advanced
Click on Environment Variables, under SystemVariables, find PATH, and click on it.
In the Edit windows, modifyPATH by adding the
location of the class to the value for PATH. If you do nothave the item PATH, you may select to add a newvariable and add PATH as the name and the location ofthe class as the value.
Close the window. (Or)
In command prompt
set classpath=%path%;.; (Or)
set path=location of class;
-
7/27/2019 JavaSeminor
8/71
Compilation & Execution
To Compile
javac xxx.java
To Execute
java xxx
-
7/27/2019 JavaSeminor
9/71
-
7/27/2019 JavaSeminor
10/71
Elements
Identifiers: names the programmer chooses Keywords: names already in the programming language
Separators (also known as punctuators): punctuationcharacters and paired-delimiters
Operators: symbols that operate on arguments and produceresults
Literals(specified by their type) Numeric: int,float and double
Logical:boolean
Textual: char and String Reference: null
Comments
Line//
Block/* */
-
7/27/2019 JavaSeminor
11/71
Data Types
There are two data types available in Java:
Primitive Data Types
Reference/Object Data Types
-
7/27/2019 JavaSeminor
12/71
Operator
An operator is a symbol (+,-,*,/) that
directs the computer to performcertain mathematical or
logical manipulations
and is usually used to manipulate
data and variables
-
7/27/2019 JavaSeminor
13/71
-
7/27/2019 JavaSeminor
14/71
Control Statements
Selection Statements if, if-else, if-else-if ladder, nested if-else
switch-case
Iteration Statements while do-while
for
Nested loops
Jump Statements break
continue
return
-
7/27/2019 JavaSeminor
15/71
First JAVA Program
public class First
{
public static void main(String args[])
{System.out.println(Java is my passion);
}
}
-
7/27/2019 JavaSeminor
16/71
What all are Object?
KGiSL - iTech
Tangible Things as a car, printer, ...
Roles as employee, boss, ...
Incidents as flight, overflow, ... Interactions as contract, sale, ...
Specifications as colour, shape,
-
7/27/2019 JavaSeminor
17/71
What is Object?
An object is like ablack box.
The internaldetails arehidden.
an object represents anindividual, identifiable item,unit, or entity, either real orabstract, with a well-definedrole in the problem domain.
Or
An "object" is anything towhich a concept applies.
Etc.
-
7/27/2019 JavaSeminor
18/71
Classes
The general form of a class definition is shown here:
class ClassName {
type instance-variable1;
// ...
type instance-variableN;
type methodName1(parameter-list) {
// body of method
}
// ...
type methodNameN(parameter-list) {
// body of method
}
}
-
7/27/2019 JavaSeminor
19/71
Elements of Classes
The data, or variables, defined within a class are calledinstancevariables.
The code is contained within methods.
Collectively, the methods and variables defined within a class arecalled members of the class.
Example:
class Vehicle {
int passengers; // number of passengers
int fuelcap; // fuel capacity in gallons
int mpg; // fuel consumption in miles per gallon// Display the range.
void range() {
System.out.println("Range is " + fuelcap * mpg);
}
-
7/27/2019 JavaSeminor
20/71
Creating Objects
Vehicle minivan; /* declare reference toobject */
minivan = new Vehicle(); /* allocate aVehicle object */
(or)
Vehicle minivan = new Vehicle(); /*create a Vehicle object called minivan*/
minivan.fuelcap= 16; /* Accessing themember of the Vehicle class */
-
7/27/2019 JavaSeminor
21/71
Example
class Vehicle {int passengers; // number of passengers
int fuelcap; // fuel capacity in gallons
int mpg; // fuel consumption in miles per gallon
Vehicle(int p, int f, int m) {
passengers = p;
fuelcap = f;
mpg = m;
}
// Display the range.void range() {
System.out.println("Range is " + fuelcap * mpg);
}
}
-
7/27/2019 JavaSeminor
22/71
class AddMeth {
public static void main(String args[]) {
Vehicle minivan = new Vehicle();Vehicle sportscar = new Vehicle(2,14,12);
// assign values to fields in minivan
minivan.passengers = 7;
minivan.fuelcap = 16;
minivan.mpg = 21;
System.out.print("Minivan can carry " +
minivan.passengers +". ");
minivan.range(); // display range of minivan
System.out.print("Sportscar can carry " +sportscar.passengers +". ");
sportscar.range(); // display range of sportscar.
}
}
-
7/27/2019 JavaSeminor
23/71
static keyword
class StaticDemo {int x; // a normal instance variable
static int y; // a static variable
}
class SDemo {
public static void main(String args[]) {
StaticDemo ob1 = new StaticDemo();
StaticDemo ob2 = new StaticDemo();
ob1.x = 10;
ob2.x = 20;
System.out.println("Of course, ob1.x and ob2.x "+
"are independent.");
System.out.println("ob1.x: " + ob1.x +
"\nob2.x: " + ob2.x);
-
7/27/2019 JavaSeminor
24/71
/* Each object shares one copy of
a static variable. */
System.out.println("The static variable y isshared.");
ob1.y = 19;
System.out.println("ob1.y: " + ob1.y + "\nob2.y:" + ob2.y);
System.out.println("The static variable y can be"+ " accessed through its class.");
StaticDemo.y = 11; /* Can refer to y throughclass name */
System.out.println("StaticDemo.y: " +StaticDemo.y + "\nob1.y: " + ob1.y + "\nob2.y: "+ ob2.y);
}
}
-
7/27/2019 JavaSeminor
25/71
Array Variables
Declaration type var-name[ ];//E.g: int arr[ ];
Memory Allocation
array-var = newtype[size]; // arr=new int[5]; Types: Single and Multi-Dimensional Array
Jagged Array- Different column sized array
Alternative Array Declaration int a[ ] = new int[5];
int[ ] a = new int[5];
-
7/27/2019 JavaSeminor
26/71
Using Command Line Arguments
A command-line argument is the information that directlyfollows the programs name on the command line when it isexecuted.
They are stored as strings in the String arraypassed to
main( ). Example:
class CommandLine {
public static void main(String args[]) {
for(int i=0; i
-
7/27/2019 JavaSeminor
27/71
Inheritance
Using inheritance, you can create a general classthat defines traits common to a set of relateditems.
This class can then be inherited by other, morespecific classes, each adding those things that areunique to it.
A class that is inherited is called a superclass.
The class thatdoes the inheriting is called asubclass.
-
7/27/2019 JavaSeminor
28/71
Types of Inheritance
Single Inheritance Multi Level Inheritance
Hierarchal Inheritance Multiple Inheritance
Hybrid Inheritance
A
B
A
B
C
A
B C
D E
A B
C
A
B C
D E
F
-
7/27/2019 JavaSeminor
29/71
Polymorphism
Overloading In Java it is possible to define two or more methods within the
same class that share the same name, as long as their returntype and parameter declarations(signature) are different.
Overriding In a class hierarchy, when a method in a subclass has the
same name and type signature as a method in its
superclass, then the method in the subclass is said to overridethe method in the superclass.
-
7/27/2019 JavaSeminor
30/71
-
7/27/2019 JavaSeminor
31/71
Abstract class31
Anyclass that contains one or more abstract methodsmust also be declared abstract.
To declare a class abstract, you simply use the abstractkeyword in front of the class keyword at thebeginning of
the class declaration.
An abstract class cannot be directlyinstantiated, but canbe inherited.
Any subclass of an abstract class must either implementall of the abstractmethods in the superclass, or be itselfdeclared abstract.
-
7/27/2019 JavaSeminor
32/71
String Class
Stringis probably the most commonly usedclass in Javas class library.
Every string that created is actually an object of
type String. Even string constants are actuallyString
objects.String myString = "this is a test";
Java defines one operator for String objects: +.String myString = "I" + " like " + "Java.";
-
7/27/2019 JavaSeminor
33/71
Packages
Packagesare containers for classes that are used to keep theclass name space compartmentalized.
The package is both a naming and a visibility controlmechanism.
You can define classes inside a package that are not accessible bycode outside that package.
You can also define class members that are only exposed to othermembers of the same package.
This is the general form of the package statement:package pkg;
-
7/27/2019 JavaSeminor
34/71
Visibility Level34
PrivateNo
ModifierProtected Public
Same class Yes Yes Yes Yes
Same packagesubclass
No Yes Yes Yes
Same package
non-subclass
No Yes Yes Yes
Different package
subclass
No No Yes Yes
Different package
non-subclass
No No No Yes
Note: A class has only two possible access levels default and public.
-
7/27/2019 JavaSeminor
35/71
Interfaces
Defines what a class must do but not how it will do it. Using the keyword interface, you can fully abstract a
class interface from its implementation.
Once it is defined, any number of classes can implementan interface.
Also, one class can implement any number of interfaces.
one interface,multiple methods
-
7/27/2019 JavaSeminor
36/71
Java I/O
Java does provide strong, flexible support for I/O as itrelates to files and networks.
Javas I/O system is cohesive and consistent.
Java programs perform I/O through streams.
Astreamis an abstraction that either produces orconsumes information.
Input stream can abstract many different kinds of input:from a disk file, a keyboard, or a network socket.
Output stream may refer to the console, a disk file, or anetwork connection.
Java implements streams within class hierarchies definedin thejava.io package.
-
7/27/2019 JavaSeminor
37/71
Types of Streams
Java 2 defines two types of streams
Byte StreamsCharacter Streams
37
-
7/27/2019 JavaSeminor
38/71
-
7/27/2019 JavaSeminor
39/71
Character Streams
Characterstreamsprovide a convenient means forhandling input and output of characters.
Character streams are defined by using two classhierarchies.
At the top are two abstract classes,ReaderandWriter.
The abstract classes Reader andWriter define severalkey methods that the other stream classes implement.
Two of the most important methods are read( )andwrite( ).
39
-
7/27/2019 JavaSeminor
40/71
The Predefined Streams
System Class
Stream Variables in, out, err
System.outrefers to the standard output stream.
System.inrefers to standard input stream.
System.errrefers to the standard error stream.
System.in is an object of type InputStream;System.out and System.err are objects of typePrintStream.
40
C l I t U i Ch t
-
7/27/2019 JavaSeminor
41/71
Console Input Using CharacterStreams
The best class for reading console input isBufferedReader, which supports a buffered input stream.
Use InputStreamReader, which converts bytes tocharacters.
To obtain an InputStreamReaderobject, use the constructorshown here:
InputStreamReader(InputStreaminputStream)
Since System.inrefers to an object of type InputStream,it can be used for inputStream.
To construct a BufferedReaderuse the constructor shownhere:
BufferedReader(Reader inputReader)
41
-
7/27/2019 JavaSeminor
42/71
Exception Handling
An exception is an error that occurs at run time.
Exception handling subsystem streamlines error
handling by allowing your program to define a blockof code, called an exception handler, that isexecuted automatically when an error occurs.
Another reason that exception handling is importantis that Java defines standard exceptions for commonprogram errors.
-
7/27/2019 JavaSeminor
43/71
Fundamentals
try: Program statements that you want to monitor for exceptions are
contained within a tryblock.
catch: If an exception occurs within the try block, it is thrown. Your code can
catch this exception (using catch) and handle it in some rational
manner. throw:
System-generated exceptions are automatically thrown by the Javarun-time system. To manuallythrow an exception, use the keywordthrow.
throws:
Any exception that is thrown out of a method must be specified assuch by a throwsclause.
finally:Any code that absolutelymust be executed upon exiting from a try
block is put in a finallyblock.
-
7/27/2019 JavaSeminor
44/71
Example
// Demonstrate exception handling.class ExcDemo {
public static void main(String args[]) {int nums[] = new int[4];try {System.out.println("Before exception is
generated.");// Generate an index out-of-bounds exception.
nums[7] = 10;System.out.println("won't displayed");
}catch(ArrayIndexOutOfBoundsException exc){// catch the exceptionSystem.out.println(Array out of range!");
}System.out.println("After catch statement.");
}
}
-
7/27/2019 JavaSeminor
45/71
Uncaught Exception
// Let JVM handle the error.class NotHandled {
public static void main(String args[]) {
int nums[] = new int[4];
System.out.println("Before exception.");
//generate an index out-of-bounds exception
nums[7] = 10;
}
}
OUTPUT:
Before exception.
Exception in thread "main"
java.lang.ArrayIndexOutOfBoundsException: 7
at NotHandled.main(NotHandled.java:9)
-
7/27/2019 JavaSeminor
46/71
-
7/27/2019 JavaSeminor
47/71
Thread Model
Threads exist in several states.
A thread can be running.
It can be ready to run as soon as it gets CPU time.
A running thread can be suspended.
A suspended thread can then be resumed.
A thread can be blockedwhen waiting for aresource.
At any time, a thread can be terminated.
-
7/27/2019 JavaSeminor
48/71
The main Thread
When a Java program starts up, main threadwhich is created automatically, begins runningimmediately.
It is the thread from which other child threads willbe spawned.
It must be the last thread to finish execution.
It can be controlled through a Threadobject. To get the reference were having the following
method
static Thread currentThread( )
E l
-
7/27/2019 JavaSeminor
49/71
// Controlling the main Thread.
class CurrentThreadDemo {
public static void main(String args[]) {Thread t = Thread.currentThread();
//Prints thread name, priority, name of the group
System.out.println("Current thread: " + t);
t.setName("My Thread"); //change the thread name
System.out.println("After name change: " + t);try {
for(int n = 5; n > 0; n--) {
System.out.println(n);
Thread.sleep(1000); //suspends thread
}
}
catch (InterruptedException e) {
System.out.println("Main thread interrupted");
}
}
}
Example
-
7/27/2019 JavaSeminor
50/71
Type Wrappers
Primitive types, rather than objects, are used for these quantitiesfor the sake of performance.
The primitive types are not part of the object hierarchy, and theydo not inherit Object.
Java provides type wrappers, which are classes thatencapsulate a primitive type within an object.
The type wrappers are Double, Float, Long, Integer, Short,Byte, Character, and Boolean, which are packaged in
java.lang.
All of the numeric type wrappers inherit the abstract classNumber.
Number declares methods that return the value of an object ineach of the different numeric types.
-
7/27/2019 JavaSeminor
51/71
-
7/27/2019 JavaSeminor
52/71
Float Float(double num)
Float(float num)
Float(String str) throws NumberFormatException
Double Double(double num)
Double(String str) throws NumberFormatException
Constants:MIN_VALUE - Minimum value
MAX_VALUE - Maximum value
-
7/27/2019 JavaSeminor
53/71
Converting Numbers to/from Strings
Following methods will convert String object tonumeric types.parseByte()
parseShort()
parseInt()
parseLong()...
Following methods will convert numeric values to
String object. toString()
toBinaryString()
toHexString()
toOctalString()...
-
7/27/2019 JavaSeminor
54/71
Character Wrapper
The constructor for Character is Character(char ch)
Some methods in this class are
static boolean isDigit(char ch) static boolean isLetter(char ch)
static boolean isLetterOrDigit(char ch)
static boolean isLowerCase(char ch)
static boolean isUpperCase(char ch) static boolean isWhitespace(char ch)
static char toLowerCase(char ch)
static char toUpperCase(char ch)
static char toTitleCase(char ch)
-
7/27/2019 JavaSeminor
55/71
Boolean Wrapper
Boolean is a very thin wrapper
It contains the constants TRUE and FALSE
Boolean defines these constructors:Boolean(boolean boolValue)
Boolean(String boolString)
This class has some methods liketoString(), equals(),booleanValue() andvalueOf()
-
7/27/2019 JavaSeminor
56/71
Database Connectivity
Steps :
1) Loading the Driver into application
2) Getting the connection
3) Getting the Permission
4) Executing Sql statements
-
7/27/2019 JavaSeminor
57/71
-
7/27/2019 JavaSeminor
58/71
-
7/27/2019 JavaSeminor
59/71
-
7/27/2019 JavaSeminor
60/71
EVENT HANDLING
-
7/27/2019 JavaSeminor
61/71
NETWORKING
-
7/27/2019 JavaSeminor
62/71
J2EE
-
7/27/2019 JavaSeminor
63/71
N-Tier J2EE Architecture
Web Tier EJB Tier
l f hi
-
7/27/2019 JavaSeminor
64/71
J2EE Platform Architecture
B2BApplications
B2C
Applications
Web
Services
WirelessApplications
Application Server EnterpriseInformation
Systems
ExistingApplications
l
-
7/27/2019 JavaSeminor
65/71
Servlet
Its a Java program. Handle the request from the client and send the
response.
Its a thread based program. Types:
Generic Servlet Protocol Independent
HTTP Servlet Protocol Dependent
Servlet API: javax.servlet.*;
javax.servlet.http.*;
-
7/27/2019 JavaSeminor
66/71
S i M
-
7/27/2019 JavaSeminor
67/71
Session Management
Maintaining the clients state.
Types:1. Hidden Form Fields
2. URL Rewriting
3. Cookies4. Session
-
7/27/2019 JavaSeminor
68/71
RMI
-
7/27/2019 JavaSeminor
69/71
EJB
-
7/27/2019 JavaSeminor
70/71
-
7/27/2019 JavaSeminor
71/71
HIBERNATE