Welcome: TO Kgisl
Welcome: TO Kgisl
TO KGISL
JAVA
What is JAVA?
A high level Programming Language. Java was developed by a group of people at Sun
Original need for the language. Redefined need. Difference with the Native language C .
Why JAVA?
4
Object Oriented
Interpreted
High Performance Distributed
Dynamic
Multi-threaded AWT & Event Handling
Heart of JAVA
Installing JAVA
Download the Java Development Kit (JDK) for your
Setting Path
Start Control Panel System Advanced Click on Environment Variables, under System Variables, find PATH, and click on it. In the Edit windows, modify PATH by adding the location of the class to the value for PATH. If you do not have the item PATH, you may select to add a new variable and add PATH as the name and the location of the class as the value. Close the window. (Or) In command prompt set classpath=%path%;.; (Or) set path=location of class;
xxx.java
To Execute
java
xxx
Language Fundamentals
Tokens In a Java program, all characters are grouped into symbols called tokens.
tokens identifier
Elements
Identifiers: names the programmer chooses Keywords: names already in the programming language Separators (also known as punctuators): punctuation characters and paired-delimiters Operators: symbols that operate on arguments and produce results
*/
Data Types
Operator
An operator is a symbol (+,-,*,/) that directs the computer to perform certain mathematical or logical manipulations and is usually used to manipulate data and variables
Types
1.
2.
3. 4.
5.
6. 7.
8.
Arithmetic operators Relational operators Logical operators Assignment operators Increment and decrement operators Conditional operators Bitwise operators Special operators
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
Incidents
Interactions Specifications
as a car, printer, ... as employee, boss, ... as flight, overflow, ... as contract, sale, ... as colour, shape,
KGiSL - iTech
What is Object?
an object represents an
individual, identifiable item, unit, or entity, either real or abstract, with a well-defined role in the problem domain. Or An "object" is anything to which a concept applies. Etc.
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 } }
Elements of Classes
variables. The code is contained within methods. Collectively, the methods and variables defined within a class are called 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); }
The data, or variables, defined within a class are called instance
Creating Objects
Vehicle minivan; /* declare reference to
create a Vehicle object called minivan*/ minivan.fuelcap= 16; /* Accessing the member of the Vehicle class */
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); } }
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. } }
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);
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 through class name */ System.out.println("StaticDemo.y: " + StaticDemo.y + "\nob1.y: " + ob1.y + "\nob2.y: " + ob2.y); } }
Array Variables
Declaration type var-name[ ]; //E.g: int arr[ ]; Memory Allocation array-var = new type[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];
follows the programs name on the command line when it is executed. They are stored as strings in the String array passed to main( ). Example:
class CommandLine { public static void main(String args[]) { for(int i=0; i<args.length; i++) System.out.println("args["+i+"]:"+ args[i]); } }
Try executing this program, as shown here: java CommandLine this is a test 100 -1
Inheritance
Using inheritance, you can create a general class
that defines traits common to a set of related items. This class can then be inherited by other, more specific classes, each adding those things that are unique to it. A class that is inherited is called a superclass. The class that does the inheriting is called a subclass.
Types of Inheritance
Single Inheritance
A
Hierarchal Inheritance
A B D E B E
Multiple Inheritance
A B C A C F
Hybrid Inheritance
D
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 return type 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 override the method in the superclass.
Abstract methods
30
An abstract method is created by specifying the abstract type modifier. An abstract method contains no body and is, therefore, not implemented by the superclass. Thus, a subclass must override it The abstract modifier can be used only on normal methods It cannot be applied to static methods or to constructors. To declare an abstract method, use this general form:
abstract type name(parameter-list); Ex: abstract void moveTo(int deltaX, int deltaY);
Abstract class
31
keyword in front of the class keyword at the beginning of the class declaration.
An abstract class cannot be directly instantiated, but can
be inherited.
Any subclass of an abstract class must either implement
String Class
String is probably the most commonly used
class in Javas class library. Every string that created is actually an object of type String. Even string constants are actually String objects.
String myString = "this is a test";
Packages
Packages are containers for classes that are used to keep the
mechanism.
You can define classes inside a package that are not accessible by
You can also define class members that are only exposed to other
package pkg;
Visibility Level
34
Private
Same class Yes
No Modifier
Yes
Protected Public
Yes Yes
No
No No
Yes
Yes No
Yes
Yes Yes
Yes
Yes Yes
No
No
No
Yes
Note: A class has only two possible access levels default and public.
Interfaces
one interface, multiple methods
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 implement an interface. Also, one class can implement any number of interfaces.
Java I/O
Java does provide strong, flexible support for I/O as it
relates to files and networks. Javas I/O system is cohesive and consistent. Java programs perform I/O through streams. A stream is an abstraction that either produces or consumes 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 a network connection. Java implements streams within class hierarchies defined in the java.io package.
Types of Streams
37
Byte Streams
38
OutputStream.
The abstract classes InputStream and OutputStream
define several key methods that the other stream classes implement.
Two of the most important are read( ) and write( ).
Character Streams
39
hierarchies.
At the top are two abstract classes, Reader and Writer. The abstract classes Reader and Writer define several
write( ).
System Class Stream Variables in, out, err System.out refers to the standard output stream.
characters.
To obtain an InputStreamReader object, use the constructor
shown here:
InputStreamReader(InputStream inputStream)
here:
BufferedReader(Reader inputReader)
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 block of code, called an exception handler, that is executed automatically when an error occurs.
Fundamentals
try:
catch:
Program statements that you want to monitor for exceptions are contained within a try block. 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. System-generated exceptions are automatically thrown by the Java run-time system. To manually throw an exception, use the keyword throw. Any exception that is thrown out of a method must be specified as such by a throws clause. Any code that absolutely must be executed upon exiting from a try block is put in a finally block.
throw:
throws:
finally:
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 exception System.out.println(Array out of range!"); } System.out.println("After catch statement."); } }
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)
Multithreading
A multithreaded program contains two or more parts
lightweight.
Multithreading enables to write very efficient programs
because it lets to utilize the idle time that is present in most programs.
Thread Model
Threads exist in several states.
resource.
At any time, a thread can be terminated.
be spawned.
It must be the last thread to finish execution. It can be controlled through a Thread object. To get the reference were having the following
Example
// 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"); } } }
Type Wrappers
Primitive types, rather than objects, are used for these quantities
Number.
Number declares methods that return the value of an object in
Numeric Wrappers
Byte Byte(byte num) Byte(String str) throws NumberFormatException Short Short(short num) Short(String str) throws NumberFormatException Integer Integer(int num) Integer(String str) throws NumberFormatException Long Long(long num) Long(String str) throws NumberFormatException
Float
Float(double num) Float(float num) Float(String str) throws NumberFormatException Double(double num) Double(String str) throws NumberFormatException
Double
numeric types.
String object.
Character Wrapper
The constructor for Character is
Character(char ch)
static static static static static static static static static boolean isDigit(char ch) boolean isLetter(char ch) boolean isLetterOrDigit(char ch) boolean isLowerCase(char ch) boolean isUpperCase(char ch) boolean isWhitespace(char ch) char toLowerCase(char ch) char toUpperCase(char ch) char toTitleCase(char ch)
Boolean Wrapper
Boolean is a very thin wrapper
Database Connectivity
Steps :
1)
2)
3)
4)
Class.forName("oracle.jdbc.driver.OracleDriver");
COLLECTIONS
APPLET/SWINGS
EVENT HANDLING
NETWORKING
J2EE
Web Tier
EJB Tier
B2C Applications
Web Services
Wireless Applications
Application Server
Servlet
Its a Java program.
JSP
Itll handle the request and response with the client.
Session Management
RMI
EJB
AJAX
HIBERNATE