Professional Documents
Culture Documents
Platform independent
Unlike many other programming languages including C and C++ when Java is compiled, it is not compiled into platform specific machine, rather into platform independent byte code. This byte code is distributed over the web and interpreted by virtual Machine (JVM) on whichever platform it is being run.
Reusability of Code Emphasis on data rather than procedure Data is hidden and cannot be accessed by external functions Objects can communicate with each other through functions New data and functions can be easily addedJava has powerful features. The following are some of them:Simple Robust Threaded Reusable Secure Interpreted Portable (Platform Independent) High Performance Distributed Dynamic
Object Oriented Programming is a method of implementation in which programs are organized as cooperative collection of objects, each of which represents an instance of a class, and whose classes are all members of a hierarchy of classes united via inheritance relationships. OOP Concepts Four principles of Object Oriented Programming are Abstraction Encapsulation Inheritance Polymorphism Abstraction Abstraction denotes the essential characteristics of an object that distinguish it from all other kinds of objects and thus provide crisply defined conceptual boundaries, relative to the perspective of the viewer. Encapsulation Encapsulation is the process of compartmentalizing the elements of an abstraction that constitute its structure and behavior ; encapsulation serves to separate the contractual interface of an abstraction and its implementation. Encapsulation * Hides the implementation details of a class. * Forces the user to use an interface to access data * Makes the code more maintainable. Inheritance Inheritance is the process by which one object acquires the properties of another object. Polymorphism Polymorphism is the existence of the classes or methods in different forms or single name denoting different implementations.
Java is Distributed
With extensive set of routines to handle TCP/IP protocols like HTTP and FTP java can open and access the objects across net via URLs.
Java is Multithreaded
One of the powerful aspects of the Java language is that it allows multiple threads of execution to run concurrently within the same program A single Java program can have many different threads executing independently and continuously. Multiple Java applets can run on the browser at the same time sharing the CPU time.
Java is Secure
Java was designed to allow secure execution of code across network. To make Java secure many of the features of C and C++ were eliminated. Java does not use Pointers. Java programs cannot access arbitrary addresses in memory.
Garbage collection
Automatic garbage collection is another great feature of Java with which it prevents inadvertent corruption of memory. Similar to C++, Java has a new operator to allocate memory on the heap for a new object. But it does not use delete operator to free the memory as it is done in C++ to free the memory if the object is no longer needed. It is done automatically with garbage collector.
Java Applications
Java has evolved from a simple language providing interactive dynamic content for web pages to a predominant enterprise-enabled programming language suitable for developing significant and critical applications. Today, It is used for many types of applications including Web based applications, Financial applications, Gaming applications, embedded systems, Distributed enterprise applications, mobile applications, Image processors, desktop applications and many more. This site outlines the building blocks of java by stating few java examples along with some java tutorials.
Keywords
There are certain words with a specific meaning in java which tell (help) the compiler what the program is supposed to do. These Keywords cannot be used as variable names, class names, or method names. Keywords in java are case sensitive, all characters being lower case. Keywords are reserved words that are predefined in the language; see the table below (Taken from Sun Java Site). All the keywords are in lowercase. abstract boolean break byte case catch char class const continue default do double else extends final finally float for goto if implements import instanceof int interface long native new package private this protected throw public throws return transient short try static void strictfp volatile super while switch synchronized
Keywords are marked in yellow as shown in the sample code below /** This class is a Hello World Program used to introduce the Java Language*/ public class HelloWorld { public static void main(String[] args) { System.out.println(Hello World); //Prints output to console } } For more information on different Keywords - Java Keywords Some Tricky Observations: The words virtual, ifdef, typedef, friend, struct and union are all words related to the C programming language. const and goto are Java keywords. The word finalize is the name of a method of the Object class and hence not a keyword. enum and label are not keywords.
Comments
Comments are descriptions that are added to a program to make code easier to understand. The compiler ignores comments and hence its only for documentation of the program. Java supports three comment styles. Block style comments begin with /* and terminate with */ that spans multiple lines. Line style comments begin with // and terminate at the end of the line. (Shown in the above program) Documentation style comments begin with /** and terminate with */ that spans multiple lines. They are generally created using the automatic documentation generation tool, such as javadoc. (Shown in the above program) name of this compiled file is comprised of the name of the class with .class as an extension.
6 JAVA FOR BEGINNERS Character: char Boolean: variable with a value of true or false.
The following chart (Taken from Sun Java Site) summarizes the default values for the java built in data types. Since I thought Mentioning the size was not important as part of learning Java, I have not mentioned it in the below table. The size for each Java type can be obtained by a simple Google search.
Data Type Byte Short Int Long Float Double Char String (object) Boolean Default Value (for fields) 0 0 0 0L 0.0f 0.0d \u0000 null false 0 to 65535 Range -127 to +128 -32768 to +32767
When we declare a variable we assign it an identifier and a data type. For Example String message = hello world In the above statement, String is the data type for the identifier message. If you dont specify a value when the variable is declared, it will be assigned the default value for its data type. Identifier Naming Rules
Can consist of upper and lower case letters, digits, dollar sign ($) and the underscore ( _ ) character. Must begin with a letter, dollar sign, or an underscore Are case sensitive Keywords cannot be used as identifiers Within a given section of your program or scope, each user defined item must have a unique identifier Can be of any length.
A class is nothing but a blueprint for creating different objects which defines its properties and behaviors. An object exhibits the properties and behaviors defined by its class. A class can contain fields and methods to describe the behavior of an object. Methods are nothing but members of a class that provide a service for an object or perform some business logic.
Objects
An object is an instance of a class created using a new operator. The new operator returns a reference to a new instance of a class. This reference can be assigned to a reference variable of the class. The process of creating objects from a class is called instantiation. An object reference provides a handle to an object that is created and stored in memory. In Java, objects can only be manipulated via references, which can be stored in variables.
Interface
An Interface is a contract in the form of collection of method and constant declarations. When a class implements an interface, it promises to implement all of the methods declared in that interface.
Instance Members
Each object created will have its own copies of the fields defined in its class called instance variables which represent an objects state. The methods of an object define its behaviour called instance methods. Instance variables and instance methods, which belong to objects, are collectively called instance members. The dot . notation with a object reference is used to access Instance Members.
Static Members
Static members are those that belong to a class as a whole and not to a particular instance (object). A static variable is initialized when the class is loaded. Similarly, a class can have static methods. Static variables and static methods are collectively known as static members, and are declared with a keyword static. Static members in the class can be accessed either by using the class name or by using the object reference, but instance members can only be accessed via object references. Below is a program showing the various parts of the basic language syntax that were discussed above. /** Comment * Displays "Hello World!" to the standard output. */ public class HelloWorld { String output = ""; static HelloWorld helloObj; //Line 1
public HelloWorld(){ output = "Hello World"; } public String printMessage(){ return output; } public static void main (String args[]) { helloObj = new HelloWorld(); //Line 2 System.out.println(helloObj.printMessage()); } } Class Name: HelloWorld Object Reference: helloObj (in Line 1) Object Created: helloObj (In Line 2) Member Function: printMessage Field: output (String) Static Member: helloObj Instance Member : output (String)
Java Operators
Java Operators
They are used to manipulate primitive data types. Java operators can be classified as unary, binary, or ternarymeaning taking one, two, or three arguments, respectively. A unary operator may appear before (prefix) its argument or after (postfix) its argument. A binary or ternary operator appears between its arguments.
Operators in java fall into 8 different categories:
Java operators fall into eight different categories: assignment, arithmetic, relational, logical, bitwise, compound assignment, conditional, and type.
Assignment Operators Arithmetic Operators Relational Operators Logical Operators Bit wise Operator Compound Assignment Operators Conditional Operator ?:
>>>=
Java has eight different operator types: assignment, arithmetic, relational, logical, bitwise, compound assignment, conditional, and type.
Assignment operators
The java assignment operator statement has the following syntax:
<variable> = <expression>
If the value already exists in the variable it is overwritten by the assignment operator (=).
public class AssignmentOperatorsDemo { public AssignmentOperatorsDemo() { // Assigning Primitive Values int j, k; j = 10; // j gets the value 10. j = 5; // j gets the value 5. Previous value is overwritten. k = j; // k gets the value 5. System.out.println("j is : " + j); System.out.println("k is : " + k); // Assigning References Integer i1 = new Integer("1"); Integer i2 = new Integer("2"); System.out.println("i1 is : " + i1); System.out.println("i2 is : " + i2);
Arithmetic operators
Java provides eight Arithmetic operators. They are for addition, subtraction, multiplication, division, modulo (or remainder), increment (or add 1), decrement (or subtract 1), and negation. An example program is shown below that demonstrates the different arithmetic operators in java. The binary operator + is overloaded in the sense that the operation performed is determined by the type of the operands. When one of the operands is a String object, the other operand is implicitly converted to its string representation and string concatenation is performed.
String message = 100 + Messages; //100 Messages
public class ArithmeticOperatorsDemo { public ArithmeticOperatorsDemo() { int x, y = 10, z = 5; x = y + z; System.out.println("+ operator resulted in " + x); x = y - z; System.out.println("- operator resulted in " + x); x = y * z; System.out.println("* operator resulted in " + x); x = y / z; System.out.println("/ operator resulted in " + x); x = y % z; System.out.println("% operator resulted in " + x); x = y++; System.out.println("Postfix ++ operator resulted in " + x); x = ++z; System.out.println("Prefix ++ operator resulted in " + x); x = -y; System.out.println("Unary operator resulted in " + x); // Some examples of special Cases int tooBig = Integer.MAX_VALUE + 1; // -2147483648 which is // Integer.MIN_VALUE. int tooSmall = Integer.MIN_VALUE - 1; // 2147483647 which is // Integer.MAX_VALUE. System.out.println("tooBig becomes " + tooBig); System.out.println("tooSmall becomes " + tooSmall); System.out.println(4.0 / 0.0); // Prints: Infinity System.out.println(-4.0 / 0.0); // Prints: -Infinity
Relational operators
Relational operators in Java are used to compare 2 or more objects. Java provides six relational operators: greater than (>), less than (<), greater than or equal (>=), less than or equal (<=), equal (==), and not equal (!=). All relational operators are binary operators, and their operands are numeric expressions. Binary numeric promotion is applied to the operands of these operators. The evaluation results in a boolean value. Relational operators have precedence lower than arithmetic operators, but higher than that of the assignment operators. An example program is shown below that demonstrates the different relational operators in java. public class RelationalOperatorsDemo { public RelationalOperatorsDemo( ) { int x = 10, y = 5; System.out.println("x > y : "+(x > y)); System.out.println("x < y : "+(x < y)); System.out.println("x >= y : "+(x >= y)); System.out.println("x <= y : "+(x <= y)); System.out.println("x == y : "+(x == y)); System.out.println("x != y : "+(x != y)); } public static void main(String args[]){ new RelationalOperatorsDemo(); } }
Logical operators
Logical operators return a true or false value based on the state of the Variables. There are six logical, or boolean, operators. They are AND, conditional AND, OR, conditional OR, exclusive OR, and NOT. Each argument to a logical operator must be a boolean data type, and the result
is always a boolean data type. An example program is shown below that demonstrates the different Logical operators in java.
public class LogicalOperatorsDemo { public LogicalOperatorsDemo() { boolean x = true; boolean y = false; System.out.println("x & y : " + (x & y)); System.out.println("x && y : " + (x && y)); System.out.println("x | y : " + (x | y)); System.out.println("x || y: " + (x || y)); System.out.println("x ^ y : " + (x ^ y)); System.out.println("!x : " + (!x)); } public static void main(String args[]) { new LogicalOperatorsDemo(); } }
Given that x and y represent boolean expressions, the boolean logical operators are defined in the Table below.
x y !x x&y x && y true true false false true false true false false false true true true false false false x|y x || y true true true false false true true false x^y
Bitwise operators
Java provides Bit wise operators to manipulate the contents of variables at the bit level. These variables must be of numeric data type ( char, short, int, or long). Java provides seven bitwise operators. They are AND, OR, Exclusive-OR, Complement, Left-shift, Signed Right-shift, and Unsigned Right-shift. An example program is shown below that demonstrates the different Bit wise operators in java. public class BitwiseOperatorsDemo { public BitwiseOperatorsDemo() { int x = 0xFAEF; //1 1 1 1 1 0 1 0 1 1 1 0 1 1 1 1 int y = 0xF8E9; //1 1 1 1 1 0 0 0 1 1 1 0 1 0 0 1
int z; System.out.println("x & y : " + (x & y)); System.out.println("x | y : " + (x | y)); System.out.println("x ^ y : " + (x ^ y)); System.out.println("~x : " + (~x)); System.out.println("x << y : " + (x << y)); System.out.println("x >> y : " + (x >> y)); System.out.println("x >>> y : " + (x >>> y)); //There is no unsigned left shift operator } public static void main(String args[]) { new BitwiseOperatorsDemo(); } } The result of applying bitwise operators between two corresponding bits in the operands is shown in the Table below.
A 1 1 0 0 1 0 1 0 B 0 0 1 1 ~A 1 0 0 0 A&B 1 1 1 0 A|B 0 1 1 0 A^B
Output 3,0,3
/* * The below program demonstrates bitwise operators keeping in mind operator precedence * Operator Precedence starting with the highest is -> |, ^, & */ public class BitwisePrecedenceEx { public static void main(String[] args) { int a = 1 | 2 ^ 3 & 5; int b = ((1 | 2) ^ 3) & 5; int c = 1 | (2 ^ (3 & 5)); System.out.print(a + "," + b + "," + c); } }
The compound operators perform shortcuts in common programming operations. Java has eleven compound assignment operators. Syntax: argument1 operator = argument2. The above statement is the same as, argument1 = argument1 operator argument2. An example program is shown below that demonstrates the different Compound operators in java.
public class CompoundOperatorsDemo { public CompoundOperatorsDemo() { int x = 0, y = 5; x += 3; System.out.println("x : " + x); y *= x; System.out.println("y : " + y); /*Similarly other operators can be applied as shortcuts. Other compound assignment operators include boolean logical , bitwiseand shift operators*/ } public static void main(String args[]) { new CompoundOperatorsDemo(); } }
Conditional operators
The Conditional operator is the only ternary (operator takes three arguments) operator in Java. The operator evaluates the first argument and, if true, evaluates the second argument. If the first argument evaluates to false, then the third argument is evaluated. The conditional operator is the expression equivalent of the if-else statement. The conditional expression can be nested and the conditional operator associates from right to left: (a?b?c?d:e:f:g) evaluates as (a?(b?(c? d:e):f):g) An example program is shown below that demonstrates the Ternary operator in java.
public class TernaryOperatorsDemo { public TernaryOperatorsDemo() { int x = 10, y = 12, z = 0; z = x > y ? x : y; System.out.println("z : " + z); } public static void main(String args[]) { new TernaryOperatorsDemo(); } } /* * The following programs shows that when no explicit parenthesis is used then the conditional operator
Output FFT Type conversion allows a value to be changed from one primitive data type to another. Conversion can occur explicitly, as specified in the program, or implicitly, by Java itself. Java allows both type widening and type narrowing conversions. In java Conversions can occur by the following ways:
Using a cast operator (explicit promotion) Using an arithmetic operator is used with arguments of different data types (arithmetic promotion) A value of one type is assigned to a variable of a different type (assignment promotion)
Operator Precedence
The order in which operators are applied is known as precedence. Operators with a higher precedence are applied before operators with a lower precedence. The operator precedence order of Java is shown below. Operators at the top of the table are applied before operators lower down in the table. If two operators have the same precedence, they are applied in the order they appear in a statement. That is, from left to right. You can use parentheses to override the default precedence.
postfix unary creation/caste multiplicative additive [] . () expr++ expr ++expr expr +expr -expr ! ~ new (type)expr */% +-
16 JAVA FOR BEGINNERS shift relational equality bitwise AND bitwise exclusive OR bitwise inclusive OR logical AND logical OR ternary assignment >> >>> < <= > >= instanceof == != & ^ | && || ?: = op=
Example In an operation such as, result = 4 + 5 * 3 First (5 * 3) is evaluated and the result is added to 4 giving the Final Result value as 19. Note that * takes higher precedence than + according to chart shown above. This kind of precedence of one operator over another applies to all the operators.
Selection Statements
The If Statement
The if statement executes a block of code only if the specified expression is true. If the value is false, then the if block is skipped and execution continues with the rest of the program. You can either have a single statement or a block of code within an if statement. Note that the conditional expression must be a Boolean expression. The simple if statement has the following syntax:
if (<conditional expression>) <statement action> Below is an example that demonstrates conditional execution based on if statement condition.
public class IfStatementDemo { public static void main(String[] args) { <font size=-1> int a = 10, b = 20; if (a > b) System.out.println("a > b"); if (a < b) System.out.println("b > a"); } }
Output
b>a The If-else Statement The if/else statement is an extension of the if statement. If the statements in the if statement fails, the statements in the else block are executed. You can either have a single statement or a block of code within if-else blocks. Note that the conditional expression must be a Boolean expression. The if-else statement has the following syntax: if (<conditional expression>) <statement action> else <statement action> Below is an example that demonstrates conditional execution based on if else statement condition.
public class IfElseStatementDemo { public static void main(String[] args) { int a = 10, b = 20; if (a > b) { System.out.println("a > b"); } else { System.out.println("b > a");
Output b>a Switch Case Statement The switch case statement, also called a case statement is a multi-way branch with several choices. A switch is easier to implement than a series of if/else statements. The switch statement begins with a keyword, followed by an expression that equates to a no long integral value. Following the controlling expression is a code block that contains zero or more labeled cases. Each label must equate to an integer constant and each must be unique. When the switch statement executes, it compares the value of the controlling expression to the values of each case label. The program will select the value of the case label that equals the value of the controlling expression and branch down that path to the end of the code block. If none of the case label values match, then none of the codes within the switch statement code block will be executed. Java includes a default label to use in cases where there are no matches. We can have a nested switch within a case block of an outer switch. Its general form is as follows:
switch (<non-long integral expression>) { case label1: <statement1> case label2: <statement2>
} // end switch When executing a switch statement, the program falls through to the next case. Therefore, if you want to exit in the middle of the switch statement code block, you must insert a break statement, which causes the program to continue executing after the current code block. Below is a java example that demonstrates conditional execution based on nested if else statement condition to find the greatest of 3 numbers. public class SwitchCaseStatementDemo { public static void main(String[] args) { int a = 10, b = 20, c = 30; int status = -1; if (a > b && a > c) { status = 1; } else if (b > c) { status = 2; } else { status = 3; } switch (status) {
case 1: System.out.println("a is the greatest"); break; case 2: System.out.println("b is the greatest"); break; case 3: System.out.println("c is the greatest"); break; default: System.out.println("Cannot be determined"); } } } Output c is the greatest
1. private 2. protected 3. default 4. public public access modifier Fields, methods and constructors declared public (least restrictive) within a public class are visible to any class in the Java program, whether these classes are in the same package or in another package. private access modifier The private (most restrictive) fields or methods cannot be used for classes and Interfaces. It also cannot be used for fields and methods within an interface. Fields, methods or constructors declared private are strictly controlled, which means they cannot be accesses by anywhere outside the enclosing class. A standard design strategy is to make all fields private and provide public getter methods for them. protected access modifier The protected fields or methods cannot be used for classes and Interfaces. It also cannot be used for fields and methods within an interface. Fields, methods and constructors declared protected in a superclass can be accessed only by subclasses in other packages. Classes in the same package can also access protected fields, methods and constructors as well, even if they are not a subclass of the protected members class. default access modifier Java provides a default specifier which is used when no access modifier is present. Any class, field, method or constructor that has no declared access modifier is accessible only by classes in the same package. The default modifier is not used for fields and methods within an interface. Below is a program to demonstrate the use of public, private, protected and default access modifiers while accessing fields and methods. The output of each of these java files depict the Java access specifiers. The first class is SubclassInSamePackage.java which is present in pckage1 package. This java file contains the Base class and a subclass within the enclosing class that belongs to the same class as shown below. package pckage1; class BaseClass { public int x = 10; private int y = 10; protected int z = 10; int a = 10; //Implicit Default Access Modifier
public int getX() { return x; } public void setX(int x) { this.x = x; } private int getY() { return y; } private void setY(int y) { this.y = y; } protected int getZ() { return z; } protected void setZ(int z) { this.z = z; } int getA() { return a; } void setA(int a) { this.a = a; } } public class SubclassInSamePackage extends BaseClass { public static void main(String args[]) { BaseClass rr = new BaseClass(); rr.z = 0; SubclassInSamePackage subClassObj = new SubclassInSamePackage(); //Access Modifiers - Public System.out.println("Value of x is : " + subClassObj.x); subClassObj.setX(20); System.out.println("Value of x is : " + subClassObj.x); //Access Modifiers - Public // If we remove the comments it would result in a compilaton // error as the fields and methods being accessed are private /* System.out.println("Value of y is : "+subClassObj.y); subClassObj.setY(20); System.out.println("Value of y is : "+subClassObj.y);*/ //Access Modifiers - Protected System.out.println("Value of z is : " + subClassObj.z); subClassObj.setZ(30); System.out.println("Value of z is : " + subClassObj.z); //Access Modifiers - Default System.out.println("Value of x is : " + subClassObj.a);
subClassObj.setA(20); System.out.println("Value of x is : " + subClassObj.a); } } Output Value of x is : 10 Value of x is : 20 Value of z is : 10 Value of z is : 30 Value of x is : 10 Value of x is : 20 The second class is SubClassInDifferentPackage.java which is present in a different package then the first one. This java class extends First class (SubclassInSamePackage.java).
import pckage1.*; public class SubClassInDifferentPackage extends SubclassInSamePackage { public int getZZZ() { return z; } public static void main(String args[]) { SubClassInDifferentPackage subClassDiffObj = new SubClassInDifferentPackage(); SubclassInSamePackage subClassObj = new SubclassInSamePackage(); //Access specifiers - Public System.out.println("Value of x is : " + subClassObj.x); subClassObj.setX(30); System.out.println("Value of x is : " + subClassObj.x); //Access specifiers - Private // if we remove the comments it would result in a compilaton // error as the fields and methods being accessed are private /* System.out.println("Value of y is : "+subClassObj.y); subClassObj.setY(20); System.out.println("Value of y is : "+subClassObj.y);*/ //Access specifiers - Protected // If we remove the comments it would result in a compilaton // error as the fields and methods being accessed are protected. /* System.out.println("Value of z is : "+subClassObj.z); subClassObj.setZ(30); System.out.println("Value of z is : "+subClassObj.z);*/ System.out.println("Value of z is : " + subClassDiffObj.getZZZ()); //Access Modifiers - Default // If we remove the comments it would result in a compilaton // error as the fields and methods being accessed are default. /* System.out.println("Value of a is : "+subClassObj.a);
Output Value of x is : 10 Value of x is : 30 Value of z is : 10 The third class is ClassInDifferentPackage.java which is present in a different package then the first one.
import pckage1.*; public class ClassInDifferentPackage { public static void main(String args[]) { SubclassInSamePackage subClassObj = new SubclassInSamePackage(); //Access Modifiers - Public System.out.println("Value of x is : " + subClassObj.x); subClassObj.setX(30); System.out.println("Value of x is : " + subClassObj.x); //Access Modifiers - Private // If we remove the comments it would result in a compilaton // error as the fields and methods being accessed are private /* System.out.println("Value of y is : "+subClassObj.y); subClassObj.setY(20); System.out.println("Value of y is : "+subClassObj.y);*/ //Access Modifiers - Protected // If we remove the comments it would result in a compilaton // error as the fields and methods being accessed are protected. /* System.out.println("Value of z is : "+subClassObj.z); subClassObj.setZ(30); System.out.println("Value of z is : "+subClassObj.z);*/ //Access Modifiers - Default // If we remove the comments it would result in a compilaton // error as the fields and methods being accessed are default. /* System.out.println("Value of a is : "+subClassObj.a); subClassObj.setA(20); System.out.println("Value of a is : "+subClassObj.a);*/ } }
<field declarations (Static and Non-Static)> <method declarations (Static and Non-Static)> <Inner class declarations> <nested interface declarations> <constructor declarations> <Static initializer blocks>
}
Below is an example showing the Objects and Classes of the Cube class that defines 3 fields namely length, breadth and height. Also the class contains a member function getVolume().
public class Cube { int length; int breadth; int height; public int getVolume() { return (length * breadth * height); } }
How do you reference a data member/function?
This is accomplished by stating the name of the object reference, followed by a period (dot), followed by the name of the member inside the object. ( objectReference.member ). You call a method for an object by naming the object followed by a period (dot), followed by the name of the method and its argument list, like this: objectName.methodName(arg1, arg2, arg3).
For example:
Instance Variables
Instance variables stores the state of the object. Each class would have its own copy of the variable. Every object has a state that is determined by the values stored in the object. An object is said to have changed its state when one or more data values stored in the object have been modified. When an object responds to a message, it will usually perform an action, change its state etc. An object that has the ability to store values is often said to have persistence. Consider this simple Java program showing the use of static fields and static methods
// Class and Object initialization showing the Object Oriented concepts in Java class Cube { int length = 10; int breadth = 10; int height = 10; public static int numOfCubes = 0; // static variable public static int getNoOfCubes() { //static method return numOfCubes; } public Cube() { numOfCubes++; // } } public class CubeStaticTest { public static void main(String args[]) { System.out.println("Number of Cube objects = " + Cube.numOfCubes); System.out.println("Number of Cube objects = " + Cube.getNoOfCubes()); } }
Output
done for security reasons with basic classes like String and Integer. It also allows the compiler to make some optimizations, and makes thread safety a little easier to achieve. A final method cant be overridden when its class is inherited. Any attempt to override or hide a final method will result in a compiler error.
public class Cube { int length = 10; int breadth = 10; int height = 10; public int getVolume() { return (length * breadth * height); } public static void main(String[] args) { Cube cubeObj; // Creates a Cube Reference cubeObj = new Cube(); // Creates an Object of Cube
Method Overloading
Method overloading results when two or more methods in the same class have the same name but different parameters. Methods with the same name must differ in their types or number of parameters. This allows the compiler to match parameters and choose the correct method when a number of choices exist. Changing just the return type is not enough to overload a method, and will be a compile-time error. They must have a different signature. When no method matching the input parameters is found, the compiler attempts to convert the input parameters to types of greater precision. A match may then be found without error. At compile time, the right implementation is chosen based on the signature of the method call Below is an example of a class demonstrating Method Overloading public class MethodOverloadDemo { void sumOfParams() { // First Version System.out.println("No parameters"); } void sumOfParams(int a) { // Second Version System.out.println("One parameter: " + a); } int sumOfParams(int a, int b) { // Third Version System.out.println("Two parameters: " + a + " , " + b); return a + b; } double sumOfParams(double a, double b) { // Fourth Version System.out.println("Two double parameters: " + a + " , " + b); return a + b; } public static void main(String args[]) { MethodOverloadDemo moDemo = new MethodOverloadDemo(); int intResult; double doubleResult; moDemo.sumOfParams(); System.out.println(); moDemo.sumOfParams(2); System.out.println(); intResult = moDemo.sumOfParams(10, 20); System.out.println("Sum is " + intResult); System.out.println(); doubleResult = moDemo.sumOfParams(1.1, 2.2); System.out.println("Sum is " + doubleResult); System.out.println(); } }
No parameters One parameter: 2 Two parameters: 10 , 20 Sum is 30 Two double parameters: 1.1 , 2.2 Sum is 3.3000000000000003
Below is a code snippet to shows the interfaces that a Class Implements:
Class cls = java.lang.String.class; Class[] intfs = cls.getInterfaces(); // [java.lang.Comparable, java.lang.CharSequence, java.io.Serializable] // The interfaces for a primitive type is an empty array cls = int.class; intfs = cls.getInterfaces(); // []
Below is a code snippet to show whether a Class Object Represents a Class or Interface:
Class cls = java.lang.String.class; boolean isClass = !cls.isInterface(); // true cls = java.lang.Cloneable.class; isClass = !cls.isInterface(); // false A java constructor has the same name as the name of the class to which it belongs. Constructors syntax does not include a return type, since constructors never return a value. Constructors may include parameters of various types. When the constructor is invoked using the new operator, the types must match those that are specified in the constructor definition. Java provides a default constructor which takes no arguments and performs no special actions or initializations, when no explicit constructors are provided. The only action taken by the implicit default constructor is to call the superclass constructor using the super() call. Constructor arguments provide you with a way to provide parameters for the initialization of an object.
Below is an example of a cube class containing 2 constructors. (one default and one parameterized constructor).
public class Cube1 { int length; int breadth; int height; public int getVolume() { return (length * breadth * height); }
Note: If a class defines an explicit constructor, it no longer has a default constructor to set the state of the objects. If such a class requires a default constructor, its implementation must be provided. Any attempt to call the default constructor will be a compile time error if an explicit default constructor is not provided in such a case.
Output Finished with Parameterized Constructor having 3 params Finished with Parameterized Constructor having 2 params Finished with Default Constructor Finished with Parameterized Constructor having 3 params
Constructor Chaining
Every constructor calls its superclass constructor. An implied super() is therefore included in each constructor which does not include either the this() function or an explicit super() call as its first statement. The super() statement invokes a constructor of the super class. The implicit super() can be replaced by an explicit super(). The super statement must be the first statement of the constructor. The explicit super allows parameter values to be passed to the constructor of its superclass and must have matching parameter types A super() call in the constructor of a subclass will result in the call of the relevant constructor from the superclass, based on the signature of the call. This is called constructor chaining.
Below is an example of a class demonstrating constructor chaining using super() method.
class Cube { int length; int breadth; int height; public int getVolume() { return (length * breadth * height); } Cube() { this(10, 10); System.out.println("Finished with Default Constructor of Cube"); } Cube(int l, int b) { this(l, b, 10); System.out.println("Finished with Parameterized Constructor having 2 params of Cube"); } Cube(int l, int b, int h) { length = l; breadth = b; height = h; System.out.println("Finished with Parameterized Constructor having 3 params of Cube"); } } public class SpecialCube extends Cube { int weight; SpecialCube() { super(); weight = 10; } SpecialCube(int l, int b) { this(l, b, 10); System.out.println("Finished with Parameterized Constructor having 2 params of SpecialCube"); } SpecialCube(int l, int b, int h) { super(l, b, h); weight = 20; System.out.println("Finished with Parameterized Constructor having 3 params of SpecialCube");
Output
Finished with Parameterized Constructor having 3 params of SpecialCube Finished with Parameterized Constructor having 2 params of SpecialCube Volume of SpecialCube1 is : 1000 Weight of SpecialCube1 is : 10 Volume of SpecialCube2 is : 2000 Weight of SpecialCube2 is : 20 The super() construct as with this() construct: if used, must occur as the first statement in a constructor, and it can only be used in a constructor declaration. This implies that this() and super() calls cannot both occur in the same constructor. Just as the this() construct leads to chaining of constructors in the same class, the super() construct leads to chaining of subclass constructors to superclass constructors. if a constructor has neither a this() nor a super() construct as its first statement, then a super() call to the default constructor in the superclass is inserted. Note: If a class only defines non-default constructors, then its subclasses will not include an implicit super() call. This will be flagged as a compile-time error. The subclasses must then explicitly call a superclass constructor, using the super() construct with the right arguments to match the appropriate constructor of the superclass.
Below is an example of a class demonstrating constructor chaining using explicit super() call.
class Cube { int length; int breadth; int height; public int getVolume() { return (length * breadth * height); } Cube(int l, int b, int h) { length = l; breadth = b; height = h; System.out.println("Finished with Parameterized Constructor having 3 params of Cube"); } } public class SpecialCube1 extends Cube { int weight; SpecialCube1() { super(10, 20, 30); //Will Give a Compilation Error without this line weight = 10;
Output
Finished with Parameterized Constructor having 3 params of Cube Volume of SpecialCube1 is : 6000
Java Serialization
Introduction to Object Serialization
Java object serialization is used to persist Java objects to a file, database, network, process or any other system. Serialization flattens objects into an ordered, or serialized stream of bytes. The ordered stream of bytes can then be read at a later time, or in another environment, to recreate the original objects. Java serialization does not cannot occur for transient or static fields. Marking the field transient prevents the state from being written to the stream and from being restored during deserialization. Java provides classes to support writing objects to streams and restoring objects from streams. Only objects that support the java.io.Serializable interface or the java.io.Externalizable interface can be written to streams. public interface Serializable
Only objects of classes that implement java.io.Serializable interface can be serialized or deserialized
GetPersonDetails is the class that is used to Deserialize object from the File (person.txt).
import java.io.FileInputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.util.ArrayList; import java.util.List; public class GetPersonDetails { public static void main(String[] args) { String filename = "person.txt"; List pDetails = null; FileInputStream fis = null; ObjectInputStream in = null; try { fis = new FileInputStream(filename); in = new ObjectInputStream(fis); pDetails = (ArrayList) in.readObject(); in.close(); } catch (IOException ex) { ex.printStackTrace(); } catch (ClassNotFoundException ex) { ex.printStackTrace(); } // print out the size System.out.println("Person Details Size: " + pDetails.size()); System.out.println(); } }
PersonPersist is the class that is used to serialize object into the File (person.txt).
public class PersonPersist { public static void main(String[] args) { String filename = "person.txt"; PersonDetails person1 = new PersonDetails("hemanth", 10, "Male"); PersonDetails person2 = new PersonDetails("bob", 12, "Male"); PersonDetails person3 = new PersonDetails("Richa", 10, "Female"); List list = new ArrayList(); list.add(person1); list.add(person2); list.add(person3); FileOutputStream fos = null; ObjectOutputStream out = null; try { fos = new FileOutputStream(filename); out = new ObjectOutputStream(fos); out.writeObject(list); out.close(); System.out.println("Object Persisted"); } catch (IOException ex) { ex.printStackTrace();
Case 2: Below is an example that demonstrates object Serialization into the database
PersonDetails remains the same as shown above GetPersonDetails remains the same as shown above Create SerialTest Table create table SerialTest( name BLOB, viewname VARCHAR2(30) );
PersonPersist is the class that is used to serialize object into the into the Database Table SerialTest.
import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class PersonPersist { static String userid = "scott", password = "tiger"; static String url = "jdbc:odbc:bob"; static int count = 0; static Connection con = null; public static void main(String[] args) { Connection con = getOracleJDBCConnection(); PersonDetails person1 = new PersonDetails("hemanth", 10, "Male"); PersonDetails person2 = new PersonDetails("bob", 12, "Male"); PersonDetails person3 = new PersonDetails("Richa", 10, "Female"); PreparedStatement ps; try { ps = con.prepareStatement("INSERT INTO SerialTest VALUES (?, ?)"); write(person1, ps); ps.execute(); write(person2, ps); ps.execute(); write(person3, ps); ps.execute(); ps.close(); Statement st = con.createStatement(); ResultSet rs = st.executeQuery("SELECT * FROM SerialTest");
Case 3: Below is an example that demonstrates object Serialization into the database using Base 64 Encoder
PersonDetails remains the same as shown above GetPersonDetails remains the same as shown above Create SerialTest Table create table SerialTest( name BLOB,
PersonPersist is the class that is used to serialize object into the Database Table SerialTest
import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class PersonPersist { static String userid = "scott", password = "tiger"; static String url = "jdbc:odbc:bob"; static int count = 0; static Connection con = null; static String s; public static void main(String[] args) { Connection con = getOracleJDBCConnection(); PersonDetails person1 = new PersonDetails("hemanth", 10, "Male"); PersonDetails person2 = new PersonDetails("bob", 12, "Male"); PersonDetails person3 = new PersonDetails("Richa", 10, "Female"); PreparedStatement ps; try { ps = con.prepareStatement("INSERT INTO SerialTest VALUES (?, ?)"); write(person1, ps); ps.execute(); write(person2, ps); ps.execute(); write(person3, ps); ps.execute(); ps.close(); Statement st = con.createStatement(); ResultSet rs = st.executeQuery("SELECT * FROM SerialTest"); while (rs.next()) { Object obj = read(rs, "Name"); PersonDetails p = (PersonDetails) obj; System.out.println(p.getName() + "\t" + p.getAge() + "\t" + p.getSex()); } rs.close(); st.close(); } catch (Exception e) { } } public static void write(Object obj, PreparedStatement ps) throws SQLException, IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oout = new ObjectOutputStream(baos); oout.writeObject(obj); oout.close(); byte[] buf = baos.toByteArray(); s = new sun.misc.BASE64Encoder().encode(buf); ps.setString(1, s); // ps.setBytes(1, Base64.byteArrayToBase64(baos.toByteArray()));
Below is a program that shows the serialization of a JButton object to a file and a Byte Array Stream. As before theobject to be serialized must implement the Serializable interface.
Java Inheritance
Java Inheritance defines an is-a relationship between a superclass and its subclasses. This means that an object of a subclass can be used wherever an object of the superclass can be used. Class Inheritance in java mechanism is used to build new classes from existing classes. The inheritance relationship is transitive: if class x extends class y, then a class z, which extends class x, will also inherit from class y. For example a car class can inherit some properties from a General vehicle class. Here we find that the base class is the vehicle class and the subclass is the more specific car class. A subclass must use the extends clause to derive from a super class which must be written in the header of the subclass definition. The subclass inherits members of the superclass and hence promotes code reuse. The subclass itself can add its own new behavior and properties. The java.lang.Object class is always at the top of any Class inheritance hierarchy.
class Box { double width; double height;
Output Volume is : 1000.0 width of MatchBox 1 is 10.0 height of MatchBox 1 is 10.0 depth of MatchBox 1 is 10.0 weight of MatchBox 1 is 10.0 What is not possible using java class Inheritance? 1. Private members of the superclass are not inherited by the subclass and can only be indirectly accessed. 2. Members that have default accessibility in the superclass are also not inherited by subclasses in other packages, as these members are only accessible by their simple names in subclasses within the same package as the superclass. 3. Since constructors and initializer blocks are not members of a class, they are not inherited by a subclass. 4. A subclass can extend only one superclass
Output
Constructor of the Super class called Car number: 10 No of Tyres: 5 accessories: true Brand: X Number of Vehicles: 1
Output Volume is : 1000.0 width of MatchBox 1 is 10.0 height of MatchBox 1 is 10.0 depth of MatchBox 1 is 10.0 weight of MatchBox 1 is 10.0
The compile-time rules are there to catch attempted casts in cases that are simply not possible. This happens when we try to attempt casts on objects that are totally unrelated (that is not subclass super class relationship or a class-interface relationship) At runtime a ClassCastException is thrown if the object being cast is not compatible with the new type it is being cast to. Below is an example showing when a ClassCastException can occur during object casting
//X is a supper class of Y and Z which are sibblings. public class RunTimeCastDemo { public static void main(String args[]) { X x = new X(); Y y = new Y(); Z z = new Z(); X xy = new Y(); // compiles ok (up the hierarchy) X xz = new Z(); // compiles ok (up the hierarchy) // Y yz = new Z(); incompatible type (siblings) // Y y1 = new X(); X is not a Y // Z z1 = new X(); X is not a Z X x1 = y; // compiles ok (y is subclass of X) X x2 = z; // compiles ok (z is subclass of X) Y y1 = (Y) x; // compiles ok but produces runtime error Z z1 = (Z) x; // compiles ok but produces runtime error Y y2 = (Y) x1; // compiles and runs ok (x1 is type Y) Z z2 = (Z) x2; // compiles and runs ok (x2 is type Z) // Y y3 = (Y) z; inconvertible types (siblings) // Z z3 = (Z) y; inconvertible types (siblings) Object o = z; Object o1 = (Y) o; // compiles ok but produces runtime error } }
class Ford extends Car { } Let c be a variable of type Car class and f be of class Ford and v be an vehicle interface reference. We can assign the Ford reference to the Car variable: I.e. we can do the following Example 1 c = f; //Ok Compiles fine Where c = new Car(); And, f = new Ford(); The compiler automatically handles the conversion (assignment) since the types are compatible (sub class - super class relationship), i.e., the type Car can hold the type Ford since a Ford is a Car. Example 2 v = c; //Ok Compiles fine c = v; // illegal conversion from interface type to class type results in compilation error Where c = new Car(); And v is a Vehicle interface reference (Vehicle v) The compiler automatically handles the conversion (assignment) since the types are compatible (class interface relationship), i.e., the type Car can be cast to Vehicle interface type since Car implements Vehicle Interface. (Car is a Vehicle). Casting Object References: Explicit Casting Sometimes we do an explicit cast in java when implicit casts dont work or are not helpful for a particular scenario. The explicit cast is nothing but the name of the new type inside a pair of matched parentheses. As before, we consider the same Car and Ford Class
class Car { void carMethod(){ } }
class Ford extends Car { void fordMethod () { } } We also have a breakingSystem() function which takes Car reference (Superclass reference) as an input parameter. The method will invoke carMethod() regardless of the type of object (Car or Ford Reference)
and if it is a Ford object, it will also invoke fordMethod(). We use the instanceof operator to determine the type of object at run time.
public void breakingSystem (Car obj) { obj.carMethod(); if (obj instanceof Ford)
((Ford)obj).fordMethod (); } To invoke the fordMethod(), the operation (Ford)obj tells the compiler to treat the Car object referenced by obj as if it is a Ford object. Without the cast, the compiler will give an error message indicating that fordMethod() cannot be found in the Car definition. The following program shown illustrates the use of the cast operator with references. Note: Classes Honda and Ford are Siblings in the class Hierarchy. Both these classes are subclasses of Class Car. Both Car and HeavyVehicle Class extend Object Class. Any class that does not explicitly extend some other class will automatically extends the Object by default. This code instantiates an object of the class Ford and assigns the objects reference to a reference variable of type Car. This assignment is allowed as Car is a superclass of Ford. In order to use a reference of a class type to invoke a method, the method must be defined at or above that class in the class hierarchy. Hence an object of Class Car cannot invoke a method present in Class Ford, since the method fordMethod is not present in Class Car or any of its superclasses. Hence this problem can be colved by a simple downcast by casting the Car object reference to the Ford Class Object reference as done in the program. Also an attempt to cast an object reference to its Sibling Object reference produces a ClassCastException at runtime, although compilation happens without any error. class Car extends Object { void carMethod() { } } class HeavyVehicle extends Object { } class Ford extends Car { void fordMethod() { System.out.println("I am fordMethod defined in Class Ford"); } } class Honda extends Car {
void fordMethod() { System.out.println("I am fordMethod defined in Class Ford"); } } public class ObjectCastingEx { public static void main(String[] args) { Car obj = new Ford(); // Following will result in compilation error // obj.fordMethod(); //As the method fordMethod is undefined for the Car Type // Following will result in compilation error // ((HeavyVehicle)obj).fordMethod(); //fordMethod is undefined in the HeavyVehicle Type // Following will result in compilation error ((Ford) obj).fordMethod(); //Following will compile and run // Honda hondaObj = (Ford)obj; Cannot convert as they are sibblings } } One common casting that is performed when dealing with collections is, you can cast an object reference into a String.
import java.util.Vector; public class StringCastDemo { public static void main(String args[]) { String username = "asdf"; String password = "qwer"; Vector v = new Vector(); v.add(username); v.add(password); // String u = v.elementAt(0); Cannot convert from object to String Object u = v.elementAt(0); //Cast not done System.out.println("Username : " + u); String uname = (String) v.elementAt(0); // cast allowed String pass = (String) v.elementAt(1); // cast allowed System.out.println(); System.out.println("Username : " + uname); System.out.println("Password : " + pass); } }
instanceof Operator
The instanceof operator is called the type comparison operator, lets you determine if an object belongs to a specific class, or implements a specific interface. It returns true if an object is an instance of the class or if the object implements the interface, otherwise it returns false. Below is an example showing the use of instanceof operator
class Vehicle { String name; Vehicle() { name = "Vehicle"; } } class HeavyVehicle extends Vehicle { HeavyVehicle() { name = "HeavyVehicle"; } } class Truck extends HeavyVehicle { Truck() { name = "Truck"; } } class LightVehicle extends Vehicle { LightVehicle() { name = "LightVehicle"; } } public class InstanceOfExample { static boolean result; static HeavyVehicle hV = new HeavyVehicle(); static Truck T = new Truck(); static HeavyVehicle hv2 = null; public static void main(String[] args) { result = hV instanceof HeavyVehicle; System.out.print("hV is an HeavyVehicle: " + result + "\n"); result = T instanceof HeavyVehicle; System.out.print("T is an HeavyVehicle: " + result + "\n"); result = hV instanceof Truck; System.out.print("hV is a Truck: " + result + "\n"); result = hv2 instanceof HeavyVehicle; System.out.print("hv2 is an HeavyVehicle: " + result + "\n"); hV = T; //Sucessful Cast form child to parent T = (Truck) hV; //Sucessful Explicit Cast form parent to child } }
Output
hV is an HeavyVehicle: true T is an HeavyVehicle: true hV is a Truck: false hv2 is an HeavyVehicle: false Note: hv2 does not yet reference an HeavyVehicle object, instanceof returns false. Also we cant use instanceof operator with siblings.
A class abstract Vehicle might be specified as abstract to represent the general abstraction of a vehicle, as creating instances of the class would not be meaningful. abstract class Vehicle { int numofGears; String color; abstract boolean hasDiskBrake(); abstract int getNoofGears(); } Example of a shape class as an abstract class abstract class Shape { public String color; public Shape() { } public void setColor(String c) { color = c; } public String getColor() { return color; } abstract public double area(); } We can also implement the generic shapes class as an abstract class so that we can draw lines, circles, triangles etc. All shapes have some common fields and methods, but each can, of course, add more fields and methods. The abstract class guarantees that each shape will have the same set of basic properties. We declare this class abstract because there is no such thing as a generic shape. There can only be concrete shapes such as squares, circles, triangles etc.
public class Point extends Shape { static int x, y; public Point() { x = 0; y = 0; } public double area() { return 0; } public double perimeter() { return 0; } public static void print() { System.out.println("point: " + x + "," + y); } public static void main(String args[]) { Point p = new Point();
Output point: 0, 0 Notice that, in order to create a Point object, its class cannot be abstract. This means that all of the abstract methods of the Shape class must be implemented by the Point class. The subclass must define an implementation for every abstract method of the abstract superclass, or the subclass itself will also be abstract. Similarly other shape objects can be created using the generic Shape Abstract class. A big Disadvantage of using abstract classes is not able to use multiple inheritance. In the sense, when a class extends an abstract class, it cant extend any other class.
Java Interface
In Java, this multiple inheritance problem is solved with a powerful construct called interfaces. Interface can be used to define a generic template and then one or more abstract classes to define partial implementations of the interface. Interfaces just specify the method declaration (implicitly public and abstract) and can only contain fields (which are implicitly public static final). Interface definition begins with a keyword interface. An interface like that of an abstract class cannot be instantiated. Multiple Inheritance is allowed when extending interfaces i.e. one interface can extend none, one or more interfaces. Java does not support multiple inheritance, but it allows you to extend one class and implement many interfaces. If a class that implements an interface does not define all the methods of the interface, then it must be declared abstract and the method definitions must be provided by the subclass that extends the abstract class. Example 1: Below is an example of a Shape interface interface Shape { public double area(); public double volume(); } Below is a Point class that implements the Shape interface. public class Point implements Shape { static int x, y; public Point() {
x = 0; y = 0; } public double area() { return 0; } public double volume() { return 0; } public static void print() { System.out.println("point: " + x + "," + y); } public static void main(String args[]) { Point p = new Point(); p.print(); } } Similarly, other shape objects can be created by interface programming by implementing generic Shape Interface. Example 2: Below is a java interfaces program showing the power of interface programming in java Listing below shows 2 interfaces and 4 classes one being an abstract class. Note: The method toString in class A1 is an overridden version of the method defined in the class named Object. The classes B1 and C1 satisfy the interface contract. But since the class D1 does not define all the methods of the implemented interface I2, the class D1 is declared abstract. Also, i1.methodI2() produces a compilation error as the method is not declared in I1 or any of its super interfaces if present. Hence a downcast of interface reference I1 solves the problem as shown in the program. The same problem applies to i1.methodA1(), which is again resolved by a downcast. When we invoke the toString() method which is a method of an Object, there does not seem to be any problem as every interface or class extends Object and any class can override the default toString() to suit your application needs. ((C1)o1).methodI1() compiles successfully, but produces a ClassCastException at runtime. This is because B1 does not have any relationship with C1 except they are siblings. You cant cast siblings into one another. When a given interface method is invoked on a given reference, the behavior that results will be appropriate to the class from which that particular object was instantiated. This is runtime polymorphism based on interfaces and overridden methods.
interface I1 { void methodI1(); // public static by default } interface I2 extends I1 {
void methodI2(); // public static by default } class A1 { public String methodA1() { String strA1 = "I am in methodC1 of class A1"; return strA1; } public String toString() { return "toString() method of class A1"; } } class B1 extends A1 implements I2 { public void methodI1() { System.out.println("I am in methodI1 of class B1"); } public void methodI2() { System.out.println("I am in methodI2 of class B1"); } } class C1 implements I2 { public void methodI1() { System.out.println("I am in methodI1 of class C1"); } public void methodI2() { System.out.println("I am in methodI2 of class C1"); } } // Note that the class is declared as abstract as it does not // satisfy the interface contract abstract class D1 implements I2 { public void methodI1() { } // This class does not implement methodI2() hence declared abstract. } public class InterFaceEx { public static void main(String[] args) { I1 i1 = new B1(); i1.methodI1(); // OK as methodI1 is present in B1 // i1.methodI2(); Compilation error as methodI2 not present in I1 // Casting to convert the type of the reference from type I1 to type I2 ((I2) i1).methodI2(); I2 i2 = new B1(); i2.methodI1(); // OK i2.methodI2(); // OK // Does not Compile as methodA1() not present in interface reference I1 // String var = i1.methodA1(); // Hence I1 requires a cast to invoke methodA1 String var2 = ((A1) i1).methodA1(); System.out.println("var2 : " + var2);
Output I am in methodI1 of class B1 I am in methodI2 of class B1 I am in methodI1 of class B1 I am in methodI2 of class B1 var2 : I am in methodC1 of class A1 var3 : I am in methodC1 of class A1 var4 : toString() method of class A1 var5 : toString() method of class A1 var6 : C1@190d11 I am in methodI1 of class B1 I am in methodI1 of class B1 I am in methodI1 of class B1
}*/ } public class MethodOverridingDemo { public static void main(String[] args) { OverridingClass oc1 = new OverridingClass(); SuperClassWithDifferentMethods sc3 = new OverridingClass(); oc1.method1(); oc1.method2(); // Since its private, the below 2 methods are not visible /* oc1.method3(); oc1.method4();*/ oc1.method5(); try { oc1.method6(); } catch (CustomException e) { e.printStackTrace(); } oc1.method7(); oc1.method8(100); System.out.println("oc1.field1 : " + oc1.field1); System.out.println("oc1.field2 : " + oc1.field2); System.out.println("sc3.field1 : " + sc3.field1); System.out.println("sc3.field2 : " + sc3.field2); sc3.method5(); OverridingClass overClass = new OverridingClass(); SuperClassWithDifferentMethods supClass = (SuperClassWithDifferentMethods) overClass; supClass.method5(); supClass.method1(); } }
Output OverridingClass.method1() SuperClassWithDifferentMethods.method2() OverridingClass.method5() OverridingClass.method6() OverridingClass.method7() OverridingClass.method8() oc1.field1 : 30 oc1.field2 : 40 sc3.field1 : 10 sc3.field2 : 20 SuperClassWithDifferentMethods.method5() SuperClassWithDifferentMethods.method5() OverridingClass.method1() The new method definitions in the subclass OverridingClass have the same signature and the same return type as the methods in the superclass SuperClassWithDifferentMethods. The new overridden method6 definition specifies a subset of the exceptions (CustomException). The new overridden method7 definition also widens the accessibility to public from private. The
overriding method8 also declares the parameter to be final, which is not a part of the method signature and Method Overriding holds good. A static method cannot be overridden to be nonstatic instance method as shown in the overridden method declaration of method9. A static method is class-specific and not part of any object, while overriding methods are invoked on behalf of objects of the subclass. There are no such restrictions on the fields, as for fields only the field names matter. A final method cannot be overridden, an attempt to which will result in a compile-time error. A private method is not accessible outside the class in which it is defined; therefore, a subclass cannot override it. A subclass must use the super keyword in order to invoke an overridden method in the superclass. A subclass cannot override fields of the superclass, but it can hide them. Code in the subclass can use the keyword super to access members, including hidden fields. The following distinction between invoking instance methods on an object and accessing fields of an object must be noted. When an instance method is invoked on an object using a reference, it is the class of the current object denoted by the reference, not the type of the reference, that determines which method implementation will be executed. When a field of an object is accessed using a reference, it is the type of the reference, not the class of the current object denoted by the reference, that determines which field will actually be accessed. This is demonstrated in the above program
String str1 = My name is bob; String str2 = My name is bob; String str3 = My name + is bob; //Compile time expression String name = bob; String str4 = My name is + name; String str5 = new String(My name is bob); In the above code all the String references str1, str2 and str3 denote the same String object, initialized with the character string: My name is bob. But the Strings str4 and str5 denote new String objects. Constructing String objects can also be done from arrays of bytes, arrays of characters, or string buffers. A simple way to convert any primitive value to its string representation is by concatenating it with the empty string ("), using the string concatenation operator (+). public class StringsDemo { public static void main(String[] args) { byte[] bytes = {2, 4, 6, 8}; char[] characters = {'a', 'b', 'C', 'D'}; StringBuffer strBuffer = new StringBuffer("abcde"); // Examples of Creation of Strings String byteStr = new String(bytes); String charStr = new String(characters); String buffStr = new String(strBuffer); System.out.println("byteStr : "+byteStr); System.out.println("charStr : "+charStr); System.out.println("buffStr : "+buffStr); } } Output byteStr : charStr : abCD buffStr : abcde
~~~~~~~~~~~~
String Equality
public class StringsDemo2 { public static void main(String[] args) { String str1 = "My name is bob"; String str2 = "My name is bob"; String str3 = "My name " + "is bob"; //Compile time expression String name = "bob"; String str4 = "My name is " + name; String str5 = new String("My name is bob"); System.out.println("str1 == str2 : " + (str1 == str2));
Output str1 == str2 : true str2 == str3 : true str3 == str1 : true str4 == str5 : false str1 == str4 : false str1 == str5 : false str1.equals(str2) : true str2.equals(str3) : true str3.equals(str1) : true str4.equals(str5) : true str1.equals(str4) : true str1.equals(str5) : true
7. toUpperCase() Converts all of the characters in this String to upper case using the rules of the default locale. 7. toLowerCase() Converts all of the characters in this String to upper case using the rules of the default locale. 9. concat(String str) Concatenates the specified string to the end of this string. 10. indexOf(int ch) Returns the index within this string of the first occurrence of the specified character. 11. indexOf(int ch, int fromIndex) Returns the index within this string of the first occurrence of the specified character, starting the search at the specified index. 12. indexOf(String str) Returns the index within this string of the first occurrence of the specified substring. 13. indexOf(String str, int fromIndex) Returns the index within this string of the first occurrence of the specified substring, starting at the specified index. 14. lastIndexOf(int ch) Returns the index within this string of the last occurrence of the specified character. 15. lastIndexOf(int ch, int fromIndex) Returns the index within this string of the last occurrence of the specified character, searching backward starting at the specified index.
16. lastIndexOf(String str) Returns the index within this string of the rightmost occurrence of the specified substring. 17. lastIndexOf(String str, int fromIndex) Returns the index within this string of the last occurrence of the specified substring, searching backward starting at the specified index. 18. substring(int beginIndex) Returns a new string that is a substring of this string.
19. substring(int beginIndex, int endIndex) Returns a new string that is a substring of this string. 20. replace(char oldChar, char newChar) Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar. 21. trim() Returns a copy of the string, with leading and trailing whitespace omitted. 22. toString() This object (which is already a string!) is itself returned.
public class StringsDemo3 { public static void main(String[] args) { String str1 = "My name is bob"; char str2[] = new char[str1.length()]; String str3 = "bob"; String str4 = "cob"; String str5 = "BoB"; String str6 = "bob"; System.out.println("Length of the String str1 : " + str1.length()); System.out.println("Character at position 3 is : " + str1.charAt(3)); str1.getChars(0, str1.length(), str2, 0); System.out.print("The String str2 is : "); for (int i = 0; i < str2.length; i++) { System.out.print(str2[i]); } System.out.println(); System.out.print("Comparision Test : "); if (str3.compareTo(str4) < 0) { System.out.print(str3 + " < " + str4); } else if (str3.compareTo(str4) > 0) { System.out.print(str3 + " > " + str4); } else { System.out.print(str3 + " equals " + str4); } System.out.println(); System.out.print("Equals Test"); System.out.println("str3.equalsIgnoreCase(5) : " + str3.equalsIgnoreCase(str5)); System.out.println("str3.equals(6) : " + str3.equals(str6)); System.out.println("str1.equals(3) : " + str1.equals(str3)); str5.toUpperCase(); //Strings are immutable System.out.println("str5 : " + str5); String temp = str5.toUpperCase(); System.out.println("str5 Uppercase: " + temp); temp = str1.toLowerCase(); System.out.println("str1 Lowercase: " + str1); System.out.println("str1.concat(str4): " + str1.concat(str4)); String str7temp = " \t\n Now for some Search and Replace Examples "; String str7 = str7temp.trim();
Output Length of the String str1 : 14 Character at position 3 is : n The String str2 is : My name is bob Comparision Test : bob < cob Equals Teststr3.equalsIgnoreCase(5) : true str3.equals(6) : true str1.equals(3) : false str5 : BoB str5 Uppercase: BOB str1 Lowercase: My name is bob str1.concat(str4): My name is bobcob str7 : Now for some Search and Replace Examples newStr : Now for Tome Search and Replace ExampleT Indexof Operations on Strings Index of p in Now for some Search and Replace Examples : 26 Index of for in Now for some Search and Replace Examples : 4 str7.indexOf(for, 30) : -1 str7.indexOf(p', 30) : 36 str7.lastIndexOf(p') : 36 str7.lastIndexOf(p', 4) : -1 SubString Operations on Stringsstr8 : SubString Example str8.substring(5) : ring Example str8.substring(3,6) : Str Below is a program to check for Alpha Numeric characters in the string. public class TestAlphaNumericCharacters { private void isAlphaNumeric(final String input) { boolean isCharFlag = false; boolean isNumberFlag = false;
final char[] chars = input.toCharArray(); for (int x = 0; x < chars.length; x++) { char c = chars[x]; // lowercase && uppercase alphabet if ((c >= 'a') && (c <= 'z') || (c >= 'A') && (c <= 'Z')) { isCharFlag = true; continue; } if ((c >= '0') && (c <= '9')) { // numeric isNumberFlag = true; continue; } } System.out.println("characters are present:" + isCharFlag); System.out.println("Numbers are present :" + isNumberFlag); } public static void main(String[] args) { TestAlphaNumericCharacters tANC = new TestAlphaNumericCharacters(); tANC.isAlphaNumeric("beginn3ers"); } } Output characters are present:true Numbers are present :true Below is a java program to Reverse a string (Reverse by words / characters)
import java.util.*; public class StringReverse { public static void main(String[] args) { String input = "beginner java tutorial"; Stack stack = new Stack(); //A Stack is a Last In First Out Data Structure StringTokenizer stringTokenizer = new StringTokenizer(input); while (stringTokenizer.hasMoreTokens()) { stack.push(stringTokenizer.nextElement()); } System.out.println("Original String: " + input); System.out.print("Reversed String by Words: "); while (!stack.empty()) { System.out.print(stack.pop()); System.out.print(" "); } System.out.println(); System.out.print("Reversed String by characters: "); StringBuffer rev = new StringBuffer(input).reverse(); System.out.print(rev); } }
Output Original String: beginner java tutorial Reversed String by Words: tutorial java beginner Reversed String by characters: lairotut avaj rennigeb
When you run the ToStringDemo program, the output is: Object toString() method : PointCoordinates@119c082
PointCoordinates@119c082 testing
In the above example when we try printing PointCoordinates object, it internally calls the Objects toString() method as we have not overridden the java toString() method. Since out example has no toString method, the default one in Object is used. The format of the default toString method of the Object is as shown below. Class Name, @, and the hex version of the objects hashcode concatenated into a string. The default hashCode method in Object is typically implemented by converting the memory address of the object into an integer. Below is an example shown of the same program by Overriding the default Object toString() method. The toString() method must be descriptive and should generally cover all the contents of the object.
class PointCoordinates { private int x, y; public PointCoordinates(int x, int y) { this.x = x; this.y = y; } public int getX() { return x; } public int getY() { return y; } // Custom toString() Method. public String toString() { return "X=" + x + " " + "Y=" + y; } } public class ToStringDemo2 { public static void main(String args[]) { PointCoordinates point = new PointCoordinates(10, 10); System.out.println(point); String s = point + " testing"; System.out.println(s); } }
Comparing using the equals Method The equals method is used when we need to compare the content of the text present in the String objects. This method returns true when two String objects hold the same content (i.e. the same values). The following Program would print The strings are unequal In the first case and The strings are equal in the second case.
public class StringComparision2 { public static void main(String[] args) { String name1 = "Bob"; String name2 = new String("Bob1"); String name3 = "Bob"; // 1st case if (name1.equals(name2)) { System.out.println("The strings are equal."); } else { System.out.println("The strings are unequal."); } // 2nd case if (name1.equals(name3)) { System.out.println("The strings are equal."); } else { System.out.println("The strings are unequal."); } } }
Comparing using the compareTo Method The compareTo method is used when we need to determine the order of Strings lexicographically. It compares char values similar to the equals method. The compareTo method returns a negative integer if the first String object precedes the second string. It returns zero if the 2 strings being compared are equal. It returns a positive integer if the first String object follows the second string. The following Program would print name2 follows name1 In the first case and name1 follows name3 in the second case.
public class StringComparision3 { public static void main(String[] args) { String name1 = "bob"; String name2 = new String("cob");
Creation of StringBuffers
StringBuffer Constructors
public class StringBufferDemo { public static void main(String[] args) { // Examples of Creation of Strings StringBuffer strBuf1 = new StringBuffer("Bob"); StringBuffer strBuf2 = new StringBuffer(100); //With capacity 100 StringBuffer strBuf3 = new StringBuffer(); //Default Capacity 16 System.out.println("strBuf1 : " + strBuf1); System.out.println("strBuf2 capacity : " + strBuf2.capacity());
StringBuffer Functions
The following program explains the usage of the some of the basic StringBuffer methods like 1. capacity() Returns the current capacity of the String buffer. 2. length() Returns the length (character count) of this string buffer. 3. charAt(int index) The specified character of the sequence currently represented by the string buffer, as indicated by the index argument, is returned. 4. setCharAt(int index, char ch) The character at the specified index of this string buffer is set to ch 5. toString() Converts to a string representing the data in this string buffer 6. insert(int offset, char c) Inserts the string representation of the char argument into this string buffer. Note that the StringBuffer class has got many overloaded insert methods which can be used based on the application need. 7. delete(int start, int end) Removes the characters in a substring of this StringBuffer 8. replace(int start, int end, String str) Replaces the characters in a substring of this StringBuffer with characters in the specified String. 9. reverse() The character sequence contained in this string buffer is replaced by the reverse of the sequence. 10. append(String str) Appends the string to this string buffer. Note that the StringBuffer class has got many overloaded append methods which can be used based on the application need.
Output strBuf1 : Bobby strBuf1 capacity : 21 strBuf2 capacity : 100 strBuf3 capacity : 16 strBuf1 length : 5 strBuf1 charAt 2 : b strBuf1 after setCharAt 1 to t is : Btbby strBuf1 toString() is : Btbby strBuf3 when appended with a String : beginner-java-tutorial strBuf3 when c is inserted at 1 : bceginner-java-tutorial strBuf3 when c is deleted at 1 : b
System.out.println("Computing Division."); int average = totalSum/totalNumber; System.out.println("Average : "+ average); } } An ArithmeticException is thrown at runtime when Line 11 is executed because integer division by 0 is an illegal operation. The Exit main() message is never reached in the main method Output Computing Division. java.lang.ArithmeticException: / by zero Average : 25 Computing Division. at DivideException.division(DivideException.java:11) at DivideException.main(DivideException.java:5) Exception in thread main
Exceptions in Java
Throwable Class The Throwable class provides a String variable that can be set by the subclasses to provide a detail message that provides more information of the exception occurred. All classes of throwables define a one-parameter constructor that takes a string as the detail message. The class Throwable provides getMessage() function to retrieve an exception. It has a printStackTrace() method to print the stack trace to the standard error stream. Lastly It also has a toString() method to print a short description of the exception. For more information on what is printed when the following messages are invoked, please refer the java docs. Syntax String getMessage() void printStackTrace() String toString() Class Exception The class Exception represents exceptions that a program faces due to abnormal or special conditions during execution. Exceptions can be of 2 types: Checked (Compile time Exceptions)/ Unchecked (Run time Exceptions). Class RuntimeException
Runtime exceptions represent programming errors that manifest at runtime. For example ArrayIndexOutOfBounds, NullPointerException and so on are all subclasses of the java.lang.RuntimeException class, which is a subclass of the Exception class. These are basically business logic programming errors. Class Error Errors are irrecoverable condtions that can never be caught. Example: Memory leak, LinkageError etc. Errors are direct subclass of Throwable class.
Unchecked exceptions are RuntimeException and any of its subclasses. Class Error and its subclasses also are unchecked. Unchecked exceptions , however, the compiler doesnt force the programmers to either catch the exception or declare it in a throws clause. In fact, the programmers may not even know that the exception could be thrown. Example: ArrayIndexOutOfBounds Exception. They are either irrecoverable (Errors) and the program should not attempt to deal with them, or they are logical programming errors. (Runtime Exceptions). Checked exceptions must be caught at compile time. Runtime exceptions do not need to be. Errors often cannot be.
These Exception arises during run-time ,that occur due to invalid argument passed to method. The java Compiler does not check the program error during compilation. For Example when you divide a number by zero, run-time exception is raised. There are many types of unchecked exceptions in java. Some of the common exceptions are: 1)Arithmetic Exception -very common exception which occurs when there is any error in the arithemetic operation u specify. 2)NullPointer Exception - happens if u specify a wrong or unavailable destination 3)ArrayIndexOutOfBounds Exception - happens if u point the unavailable index of the array 4)NegativeArraySizeException -happens when u specify negative size for array 5)NumberFormat Exception -happens in the case of wrong number format.
Exception Arithmetic Exception Class Cast Exception Array Store Exception Array Index Out Of Bounds Exception Null Pointer Exception
Reason for Exception These Exception occurs, when you divide a number by zero causes an Arithmetic Exception These Exception occurs, when you try to assign a reference variable of a class to an incompatible reference variable of another class These Exception occurs, when you assign an array which is not compatible with the data type of that array These Exception occurs, when you assign an array which is not compatible with the data type of that array These Exception occurs, when you try to implement an application without referencing the object and allocating to a memory These Exception occurs, when you try to convert a string variable in an incorrect format to integer (numeric format) that is not compatible with each other These are Exception, when you declare an array of negative size.
Exceptions are handled using a try-catch-finally construct, which has the Syntax try { <code>
} catch (<exception type1> <parameter1>) { // 0 or more <statements> } } finally { // finally block <statements> }
try Block: The java code that you think may produce an exception is placed within a try block for a suitable catch block to handle the error. If no exception occurs the execution proceeds with the finally block else it will look for the matching catch block to handle the error. Again if the matching catch handler is not found execution proceeds with the finally block and the default exception handler throws an exception.. If an exception is generated within the try block, the remaining statements in the try block are not executed.
catch Block: Exceptions thrown during execution of the try block can be caught and handled in a catch block. On exit from a catch block, normal execution continues and the finally block is executed (Though the catch block throws an exception). finally Block: A finally block is always executed, regardless of the cause of exit from the try block, or whether any catch block was executed. Generally finally block is used for freeing resources, cleaning up, closing connections etc. If the finally clock executes a control transfer statement such as a return or a break statement, then this control statement determines how the execution will proceed regardless of any return or control statement present in the try or catch. The following program illustrates the scenario.
try { <code> } catch (<exception type1> <parameter1>) { // 0 or more <statements> } } finally { <statements> } Output Computing Division. Exception : / by zero Finally Block Executes. Exception Occurred result : -1 Below is a program showing the Normal Execution of the Program. Please note that no NullPointerException is generated as was expected by most people public class DivideException2 { public static void main(String[] args) { int result = division(100,0); // Line 2 System.out.println("result : "+result); } public static int division(int totalSum, int totalNumber) { int quotient = -1; System.out.println("Computing Division."); try{ quotient = totalSum/totalNumber; } catch(Exception e){ System.out.println("Exception : "+ e.getMessage()); } finally{ if(quotient != -1){ System.out.println("Finally Block Executes"); System.out.println("Result : "+ quotient); }else{ System.out.println("Finally Block Executes. Exception Occurred"); return quotient; } } return quotient; // finally block
Output Computing Division. Exception : / by zero Finally Block Executes. Exception Occurred Main Program Terminating As shown above when the divide by zero calculation is attempted, an ArithmeticException is thrown. and program execution is transferred to the catch statement. Because the exception is thrown from the try block, the remaining statements of the try block are skipped. The finally block executes. Defining new EXCEPTIONS!! We can have our own custom Exception handler to deal with special exception conditions instead of using existing exception classes. Custom exceptions usually extend the Exception class directly or any subclass of Exception (making it checked). The super() call can be used to set a detail message in the throwable. Below is an example that shows the use of Custom exceptions along with how the throw and throws clause are used. class BadTemperature extends Exception{ BadTemperature( String reason ){ super ( reason ); } } class TooHot extends BadTemperature{ TooHot(){ super ("Default messaeg : Hot"); } TooHot(String message){ super (message); } } class TooCold extends BadTemperature{ TooCold(){ super ("Default messaeg : Cold"); } TooCold(String message){ super (message); } } class TempertureObject{ int temperature;
TempertureObject( int temp ) { temperature = temp; } void test() throws TooHot, TooCold { if ( temperature < 70 ) throw new TooCold("Very Cold"); if ( temperature > 80 ) throw new TooHot("Very Hot"); } } public class ExceptionExample1{ private static void temperatureReport( TempertureObject batch ){ try{ batch.test(); System.out.println( "Perfect Temperature" ); } catch ( BadTemperature bt ){ System.out.println( bt.getMessage( ) ); } } public static void main( String[] args ){ temperatureReport( new TempertureObject( 100 ) ); temperatureReport( new TempertureObject( 50 ) ); temperatureReport( new TempertureObject( 75 ) ); } } Output Very Hot Very Cold Perfect Temperature
There are many types of exceptions in java: Some of the common exceptions are: 1)Arithmetic Exception -very common exception which occurs when there is any error in the arithemetic operation u specify. 2)NullPointer Exception - happens if u specify a wrong or unavailable destination 3)ArrayIndexOutOfBounds Exception happens if u point the unavailable index of the array 4)NegativeArraySizeException -happens when u specify negative size for array 5)NumberFormat Exception -happens in the case of wrong number format throw, throws statement
A program can explicitly throw an exception using the throw statement besides the implicit exception thrown. The general format of the throw statement is as follows:
throw <exception reference>; The Exception reference must be of type Throwable class or one of its subclasses. A detail message can be passed to the constructor when the exception object is created. throw new TemperatureException(Too hot); A throws clause can be used in the method prototype. Method() throws <ExceptionType1>,, <ExceptionTypen> { } Each <ExceptionTypei> can be a checked or unchecked or sometimes even a custom Exception. The exception type specified in the throws clause in the method prototype can be a super class type of the actual exceptions thrown. Also an overriding method cannot allow more checked exceptions in its throws clause than the inherited method does. When an exception is thrown, normal execution is suspended. The runtime system proceeds to find a matching catch block that can handle the exception. Any associated finally block of a try block encountered along the search path is executed. If no handler is found, then the exception is dealt with by the default exception handler at the top level. If a handler is found, execution resumes with the code in its catch block. Below is an example to show the use of a throws and a throw statement. public class DivideException3 { public static void main(String[] args) { try{ int result = division(100,10); result = division(100,0); System.out.println("result : "+result); } catch(ArithmeticException e){ System.out.println("Exception : "+ e.getMessage()); } } public static int division(int totalSum, int totalNumber) throws ArithmeticException { int quotient = -1; System.out.println("Computing Division."); try{ if(totalNumber == 0){ throw new ArithmeticException("Division attempt by 0"); } quotient = totalSum/totalNumber; } finally{ if(quotient != -1){
System.out.println("Finally Block Executes"); System.out.println("Result : "+ quotient); }else{ System.out.println("Finally Block Executes. Exception Occurred"); } } return quotient; } } Output Computing Division. Finally Block Executes Result : 10 Computing Division. Finally Block Executes. Exception Occurred Exception : Division attempt by 0
Using break and return with Exceptions
This example demonstrates the use of the break, continue and return statements with exceptions. Note that the finally block is executed always except when the return statement is executed. public class ExceptionExample6 { public static void main(String[] args) { int x = 10, y = 2; int counter = 0; boolean flag = true; while (flag) { start: try { if ( y > 1 ) break start; if ( y < 0 ) return; x = x / y; System.out.println ( "x : " + x + " y : "+y ); } catch ( Exception e ) { System.out.println ( e.getMessage() ); } finally { ++counter; System.out.println ( "Counter : " + counter ); }
It should be known by now that we can have multiple catch blocks for a particular try block to handle many different kind of exceptions that can be generated. Below is a program to demonstrate the use of multiple catch blocks. import java.io.DataInputStream; import java.io.IOException; import javax.swing.JOptionPane; public class ExceptionExample7{ static int numerator, denominator; public ExceptionExample7( int t, int b ){ numerator = t; denominator = b; } public int divide( ) throws ArithmeticException{ return numerator/denominator; } public static void main( String args[] ){ String num, denom; num = JOptionPane.showInputDialog(null, "Enter the Numerator"); denom = JOptionPane.showInputDialog(null, "Enter the Denominator"); try{ numerator = Integer.parseInt( num ); denominator = Integer.parseInt( denom ); } catch ( NumberFormatException nfe ){ System.out.println( "One of the inputs is not an integer" ); return;
} catch ( Exception e ){ System.out.println( "Exception: " + e.getMessage( ) ); return; } ExceptionExample7 d = new ExceptionExample7( numerator, denominator ); try{ double result = d.divide( ); JOptionPane.showMessageDialog(null, "Result : " + result); } catch ( ArithmeticException ae ){ System.out.println( "You can't divide by zero" ); } finally{ System.out.println( "Finally Block is always Executed" ); } } }
Step 2: Create a Method for getting the reference to the Singleton Object
public class SingletonObjectDemo { private static SingletonObject singletonObject; // Note that the constructor is private private SingletonObjectDemo() { // Optional Code } public static SingletonObjectDemo getSingletonObject() { if (singletonObject == null) { singletonObject = new SingletonObjectDemo(); } return singletonObject; } }
We write a public static getter or access method to get the instance of the Singleton Object at runtime. First time the object is created inside this method as it is null. Subsequent calls to this method returns the same object created as the object is globally declared (private) and the hence the same referenced object is returned. Step 3: Make the Access method Synchronized to prevent Thread Problems. public static synchronized SingletonObjectDemo getSingletonObject() It could happen that the access method may be called twice from 2 different classes at the same time and hence more than one object being created. This could violate the design patter principle. In order to prevent the simultaneous invocation of the getter method by 2 threads or classes simultaneously we add the synchronized keyword to the method declaration Step 4: Override the Object clone method to prevent cloning We can still be able to create a copy of the Object by cloning it using the Objects clone method. This can be done as shown below SingletonObjectDemo clonedObject = (SingletonObjectDemo) obj.clone(); This again violates the Singleton Design Patterns objective. So to deal with this we need to override the Objects clone method which throws a CloneNotSupportedException exception. public Object clone() throws CloneNotSupportedException { throw new CloneNotSupportedException(); }
The below program shows the final Implementation of Singleton Design Pattern in java, by using all the 4 steps mentioned above.
class SingletonClass { private static SingletonClass singletonObject; /** A private Constructor prevents any other class from instantiating. */ private SingletonClass() { // Optional Code } public static synchronized SingletonClass getSingletonObject() { if (singletonObject == null) { singletonObject = new SingletonClass(); } return singletonObject; } public Object clone() throws CloneNotSupportedException { throw new CloneNotSupportedException(); } } public class SingletonObjectDemo { public static void main(String args[]) { // SingletonClass obj = new SingletonClass(); //Compilation error not allowed SingletonClass obj = SingletonClass.getSingletonObject(); // Your Business Logic System.out.println("Singleton object obtained"); } }
Another approach We dont need to do a lazy initialization of the instance object or to check for null in the get method. We can also make the singleton class final to avoid sub classing that may cause other problems.
public class SingletonClass { private static SingletonClass ourInstance = new SingletonClass(); public static SingletonClass getInstance() { return singletonObj; } private SingletonClass() { } }
In Summary, the job of the Singleton class is to enforce the existence of a maximum of one object of the same type at any given time. Depending on your implementation, your class and all of its data might be garbage collected. Hence we must ensure that at any point there must be a live reference to the class when the application is running.
Threads are lightweight compared to processes Threads share the same address space and therefore can share both data and code Context switching between threads is usually less expensive than between processes Cost of thread intercommunication is relatively low that that of process intercommunication Threads allow different tasks to be performed concurrently.
The following figure shows the methods that are members of the Object and Thread Class.
Thread Creation
There are two ways to create thread in java;
Implement the Runnable interface (java.lang.Runnable) By Extending the Thread class (java.lang.Thread)
1. A class implements the Runnable interface, providing the run() method that will be executed by the thread. An object of this class is a Runnable object. 2. An object of Thread class is created by passing a Runnable object as argument to the Thread constructor. The Thread object now has a Runnable object that implements the run() method. 3. The start() method is invoked on the Thread object created in the previous step. The start() method returns immediately after a thread has been spawned. 4. The thread ends when the run() method ends, either by normal completion or by throwing an uncaught exception. Below is a program that illustrates instantiation and running of threads using the runnable interface instead of extending the Thread class. To start the thread you need to invoke the start() method on your object.
class RunnableThread implements Runnable { Thread runner; public RunnableThread() { }
Output thread3 Thread[thread1,5,main] Thread[thread2,5,main] Thread[thread3,5,main] Thread[main,5,main]private This approach of creating a thread by implementing the Runnable Interface must be used whenever the class being used to instantiate the thread object is required to extend some other class.
1. A class extending the Thread class overrides the run() method from the Thread class to define the code executed by the thread. 2. This subclass may call a Thread constructor explicitly in its constructors to initialize the thread, using the super() call. 3. The start() method inherited from the Thread class is invoked on the object of the class to make the thread eligible for running.
Below is a program that illustrates instantiation and running of threads by extending the Thread class instead of implementing the Runnable interface. To start the thread you need to invoke the start() method on your object.
class XThread extends Thread { XThread() { } XThread(String threadName) { super(threadName); // Initialize thread. System.out.println(this); start(); } public void run() { //Display info about this particular thread System.out.println(Thread.currentThread().getName()); } } public class ThreadExample { public static void main(String[] args) { Thread thread1 = new Thread(new XThread(), "thread1"); Thread thread2 = new Thread(new XThread(), "thread2"); // The below 2 threads are assigned default names Thread thread3 = new XThread(); Thread thread4 = new XThread(); Thread thread5 = new XThread("thread5"); //Start the threads thread1.start(); thread2.start(); thread3.start(); thread4.start(); try { //The sleep() method is invoked on the main thread to cause a one second delay. Thread.currentThread().sleep(1000); } catch (InterruptedException e) { } //Display info about the main thread System.out.println(Thread.currentThread()); } }
Output
Thread[thread5,5,main] thread1 thread5 thread2 Thread-3 Thread-2 Thread[main,5,main] When creating threads, there are two reasons why implementing the Runnable interface may be preferable to extending the Thread class:
Extending the Thread class means that the subclass cannot extend any other class, whereas a class implementing the Runnable interface has this option. A class might only be interested in being runnable, and therefore, inheriting the full overhead of the Thread class would be excessive.
An example of an anonymous class below shows how to create a thread and start it:
( new Thread() { public void run() { for(;;) System.out.println(Stop the world!); } } ).start();
~~~~~~~~~~~~
Thread Synchronization
With respect to multithreading, Synchronization is a process of controlling the access of shared resources by the multiple threads in such a manner that only one thread can access a particular resource at a time. In non synchronized multithreaded application, it is possible for one thread to modify a shared object while another thread is in the process of using or updating the objects value. Synchronization prevents such type of data corruption which may otherwise lead to dirty reads and significant errors.Generally critical sections of the code are usually marked with synchronized keyword. Examples of using Thread Synchronization is in The Producer/Consumer Model. Locks are used to synchronize access to a shared resource. A lock can be associated with a shared resource. Threads gain access to a shared resource by first acquiring the lock associated with the object/block of code. At any given time, at most only one thread can hold the lock and thereby have access to the shared resource. A lock thus implements mutual exclusion.
The object lock mechanism enforces the following rules of synchronization:
94 JAVA FOR BEGINNERS A thread must acquire the object lock associated with a shared resource, before it can enter the shared resource. The runtime system ensures that no other thread can enter a shared resource if another thread already holds the object lock associated with the shared resource. If a thread cannot immediately acquire the object lock, it is blocked, that is, it must wait for the lock to become available. When a thread exits a shared resource, the runtime system ensures that the object lock is also relinquished.If another thread is waiting for this object lock, it can proceed to acquire the lock in order to gain access to the shared resource.
Classes also have a class-specific lock that is analogous to the object lock. Such a lock is actually a lock on the java.lang.Class object associated with the class. Given a class A, the reference A.class denotes this unique Class object. The class lock can be used in much the same way as an object lock to implement mutual exclusion.
There can be 2 ways through which synchronized can be implemented in Java:
Synchronized statements are same as synchronized methods. A synchronized statement can only be executed after a thread has acquired the lock on the object/class referenced in the synchronized statement.
Synchronized Methods
Synchronized methods are methods that are used to control access to an object. A thread only executes a synchronized method after it has acquired the lock for the methods object or class. .If the lock is already held by another thread, the calling thread waits. A thread relinquishes the lock simply by returning from the synchronized method, allowing the next thread waiting for this lock to proceed. Synchronized methods are useful in situations where methods can manipulate the state of an object in ways that can corrupt the state if executed concurrently. This is called a race condition. It occurs when two or more threads simultaneously update the same value, and as a consequence, leave the value in an undefined or inconsistent state. While a thread is inside a synchronized method of an object, all other threads that wish to execute this synchronized method or any other synchronized method of the object will have to wait until it gets the lock. This restriction does not apply to the thread that already has the lock and is executing a synchronized method of the object. Such a method can invoke other synchronized methods of the object without being blocked. The non-synchronized methods of the object can of course be called at any time by any thread.
Below is an example shows how synchronized methods and object locks are used to coordinate access to a common object by multiple threads. If the synchronized keyword is removed, the message is displayed in random fashion.
public class SyncMethodsExample extends Thread {
static String[] msg = { "Beginner", "java", "tutorial,", ".,", "com", "is", "the", "best" }; public SyncMethodsExample(String id) { super(id); } public static void main(String[] args) { SyncMethodsExample thread1 = new SyncMethodsExample("thread1: "); SyncMethodsExample thread2 = new SyncMethodsExample("thread2: "); thread1.start(); thread2.start(); boolean t1IsAlive = true; boolean t2IsAlive = true; do { if (t1IsAlive && !thread1.isAlive()) { t1IsAlive = false; System.out.println("t1 is dead."); } if (t2IsAlive && !thread2.isAlive()) { t2IsAlive = false; System.out.println("t2 is dead."); } } while (t1IsAlive || t2IsAlive); } void randomWait() { try { Thread.currentThread().sleep((long) (3000 * Math.random())); } catch (InterruptedException e) { System.out.println("Interrupted!"); } } public synchronized void run() { SynchronizedOutput.displayList(getName(), msg); } } class SynchronizedOutput { // if the 'synchronized' keyword is removed, the message // is displayed in random fashion public static synchronized void displayList(String name, String list[]) { for (int i = 0; i < list.length; i++) { SyncMethodsExample t = (SyncMethodsExample) Thread .currentThread(); t.randomWait(); System.out.println(name + list[i]); } } }
Output
thread1: Beginner thread1: java thread1: tutorial, thread1: ., thread1: com thread1: is thread1: the
thread1: best t1 is dead. thread2: Beginner thread2: java thread2: tutorial, thread2: ., thread2: com thread2: is thread2: the thread2: best t2 is dead.
Class Locks
Synchronized Blocks
Static methods synchronize on the class lock. Acquiring and relinquishing a class lock by a thread in order to execute a static synchronized method, proceeds analogous to that of an object lock for a synchronized instance method. A thread acquires the class lock before it can proceed with the execution of any static synchronized method in the class, blocking other threads wishing to execute any such methods in the same class. This, of course, does not apply to static, non-synchronized methods, which can be invoked at any time. Synchronization of static methods in a class is independent from the synchronization of instance methods on objects of the class. A subclass decides whether the new definition of an inherited synchronized method will remain synchronized in the subclass.The synchronized block allows execution of arbitrary code to be synchronized on the lock of an arbitrary object. The general form of the synchronized block is as follows: synchronized (<object reference expression>) { <code block> } A compile-time error occurs if the expression produces a value of any primitive type. If execution of the block completes normally, then the lock is released. If execution of the block completes abruptly, then the lock is released. A thread can hold more than one lock at a time. Synchronized statements can be nested. Synchronized statements with identical expressions can be nested. The expression must evaluate to a non-null reference value, otherwise, a NullPointerException is thrown. The code block is usually related to the object on which the synchronization is being done. This is the case with synchronized methods, where the execution of the method is synchronized on the lock of the current object: public Object method() { synchronized (this) { // Synchronized block on current object // method block } }
Once a thread has entered the code block after acquiring the lock on the specified object, no other thread will be able to execute the code block, or any other code requiring the same object lock, until the lock is relinquished. This happens when the execution of the code block completes normally or an uncaught exception is thrown. Object specification in the synchronized statement is mandatory. A class can choose to synchronize the execution of a part of a method, by using the this reference and putting the relevant part of the method in the synchronized block. The braces of the block cannot be left out, even if the code block has just one statement. class SmartClient { BankAccount account; // public void updateTransaction() { synchronized (account) { // (1) synchronized block account.update(); // (2) } } } In the previous example, the code at (2) in the synchronized block at (1) is synchronized on the BankAccount object. If several threads were to concurrently execute the method updateTransaction() on an object of SmartClient, the statement at (2) would be executed by one thread at a time, only after synchronizing on the BankAccount object associated with this particular instance of SmartClient. Inner classes can access data in their enclosing context. An inner object might need to synchronize on its associated outer object, in order to ensure integrity of data in the latter. This is illustrated in the following code where the synchronized block at (5) uses the special form of the this reference to synchronize on the outer object associated with an object of the inner class. This setup ensures that a thread executing the method setPi() in an inner object can only access the private double field myPi at (2) in the synchronized block at (5), by first acquiring the lock on the associated outer object. If another thread has the lock of the associated outer object, the thread in the inner object has to wait for the lock to be relinquished before it can proceed with the execution of the synchronized block at (5). However, synchronizing on an inner object and on its associated outer object are independent of each other, unless enforced explicitly, as in the following code: class Outer { // (1) Top-level Class private double myPi; // (2) protected class Inner { // (3) Non-static member Class public void setPi() { // (4) synchronized(Outer.this) { // (5) Synchronized block on outer object myPi = Math.PI; // (6) } } } }
98 JAVA FOR BEGINNERS Below example shows how synchronized block and object locks are used to coordinate access to shared objects by multiple threads.
public class SyncBlockExample extends Thread { static String[] msg = { "Beginner", "java", "tutorial,", ".,", "com", "is", "the", "best" }; public SyncBlockExample(String id) { super(id); } public static void main(String[] args) { SyncBlockExample thread1 = new SyncBlockExample("thread1: "); SyncBlockExample thread2 = new SyncBlockExample("thread2: "); thread1.start(); thread2.start(); boolean t1IsAlive = true; boolean t2IsAlive = true; do { if (t1IsAlive && !thread1.isAlive()) { t1IsAlive = false; System.out.println("t1 is dead."); } if (t2IsAlive && !thread2.isAlive()) { t2IsAlive = false; System.out.println("t2 is dead."); } } while (t1IsAlive || t2IsAlive); } void randomWait() { try { Thread.currentThread().sleep((long) (3000 * Math.random())); } catch (InterruptedException e) { System.out.println("Interrupted!"); } } public void run() { synchronized (System.out) { for (int i = 0; i < msg.length; i++) { randomWait(); System.out.println(getName() + msg[i]); } } } }
Output
thread1: Beginner thread1: java thread1: tutorial, thread1: ., thread1: com thread1: is thread1: the thread1: best t1 is dead. thread2: Beginner thread2: java
thread2: tutorial, thread2: ., thread2: com thread2: is thread2: the thread2: best t2 is dead. Synchronized blocks can also be specified on a class lock: synchronized (<class name>.class) { <code block> } The block synchronizes on the lock of the object denoted by the reference <classname>.class. A static synchronized method classAction() in class A is equivalent to the following declaration: static void classAction() { synchronized (A.class) { // Synchronized block on class A // } }
by executing a synchronized instance method of the object by executing the body of a synchronized block that synchronizes on the object by executing a synchronized static method of a class
Thread States
A Java thread is always in one of several states which could be running, sleeping, dead, etc. A thread can be in any of the following states:
New Thread state (Ready-to-run state) Runnable state (Running state) Not Runnable state Dead state
New Thread
A thread is in this state when the instantiation of a Thread object creates a new thread but does not start it running. A thread starts life in the Ready-to-run state. You can call only the start()
or stop() methods when the thread is in this state. Calling any method besides start() or stop() causes an IllegalThreadStateException.
Runnable
When the start() method is invoked on a New Thread() it gets to the runnable state or running state by calling the run() method. A Runnable thread may actually be running, or may be awaiting its turn to run.
Not Runnable
A thread becomes Not Runnable when one of the following four events occurs:
When sleep() method is invoked and it sleeps for a specified amount of time When suspend() method is invoked When the wait() method is invoked and the thread waits for notification of a free resource or waits for the completion of another thread or waits to acquire a lock of an object. The thread is blocking on I/O and waits for its completion
the name of the thread, the priority of the thread, and the name of the group to which it belongs.
Here, the run() method put itself to sleep for one second and becomes Not Runnable during that period. A thread can be awakened abruptly by invoking the interrupt() method on the sleeping thread object or at the end of the period of time for sleep is over. Whether or not it will actually start running depends on its priority and the availability of the CPU. Hence I hereby list the scenarios below to describe how a thread switches form a non runnable to a runnable state:
If a thread has been put to sleep, then the specified number of milliseconds must elapse (or it must be interrupted). If a thread has been suspended, then its resume() method must be invoked If a thread is waiting on a condition variable, whatever object owns the variable must relinquish it by calling either notify() or notifyAll(). If a thread is blocked on I/O, then the I/O must complete.
Dead State
A thread enters this state when the run() method has finished executing or when the stop() method is invoked. Once in this state, the thread cannot ever run again.
Thread Priority
In Java we can specify the priority of each thread relative to other threads. Those threads having higher priority get greater access to available resources then lower priority threads. A Java thread inherits its priority from the thread that created it. Heavy reliance on thread priorities for the behavior of a program can make the program non portable across platforms, as thread scheduling is host platformdependent. You can modify a threads priority at any time after its creation using the setPriority() method and retrieve the thread priority value using getPriority() method. The following static final integer constants are defined in the Thread class:
MIN_PRIORITY (0) Lowest Priority NORM_PRIORITY (5) Default Priority MAX_PRIORITY (10) Highest Priority
The priority of an individual thread can be set to any integer value between and including the above defined constants. When two or more threads are ready to be executed and system resource becomes available to execute a thread, the runtime system (the thread scheduler) chooses the Runnable thread with the highest priority for execution. If two threads of the same priority are waiting for the CPU, the thread scheduler chooses one of them to run in a > round-robin fashion. The chosen thread will run until one of the following conditions is true:
a higher priority thread becomes Runnable. (Pre-emptive scheduling) it yields, or its run() method exits on systems that support time-slicing, its time allotment has expired
Thread Scheduler
Schedulers in JVM implementations usually employ one of the two following strategies:
Preemptive scheduling
If a thread with a higher priority than all other Runnable threads becomes Runnable, the scheduler will preempt the running thread (is moved to the runnable state) and choose the new higher priority thread for execution.
Time-Slicing or Round-Robin scheduling
A running thread is allowed to execute for a fixed length of time (a time slot its assigned to), after which it moves to the Ready-to-run state (runnable) to await its turn to run again.
A thread scheduler is implementation and platform-dependent; therefore, how threads will be scheduled is unpredictable across different platforms.
Yielding
A call to the static method yield(), defined in the Thread class, will cause the current thread in the Running state to move to the Runnable state, thus relinquishing the CPU. The thread is then at the mercy of the thread scheduler as to when it will run again. If there are no threads waiting in the Ready-to-run state, this thread continues execution. If there are other threads in the Ready-to-run state, their priorities determine which thread gets to execute. The yield() method gives other threads of the same priority a chance to run. If there are no equal priority threads in the Runnable state, then the yield is ignored.
final void wait(long timeout) throws InterruptedException final void wait(long timeout, int nanos) throws InterruptedException final void wait() throws InterruptedException The wait() call can specify the time the thread should wait before being timed out. An another thread can invoke an interrupt() method on a waiting thread resulting in an InterruptedException. This is a checked exception and hence the code with the wait() method must be enclosed within a try catch block. notify() method signatures final void notify() final void notifyAll()
A thread usually calls the wait() method on the object whose lock it holds because a condition for its continued execution was not met. The thread leaves the Running state and transits to the Waiting-for-notification state. There it waits for this condition to occur. The thread relinquishes ownership of the object lock. The releasing of the lock of the shared object by the thread allows other threads to run and execute synchronized code on the same object after acquiring its lock. The wait() method causes the current thread to wait until another thread notifies it of a condition change. A thread in the Waiting-for-notification state can be awakened by the occurrence of any one of these three incidents: 1. Another thread invokes the notify() method on the object of the waiting thread, and the waiting thread is selected as the thread to be awakened. 2. The waiting thread times out. 3. Another thread interrupts the waiting thread.
Notify
Invoking the notify() method on an object wakes up a single thread that is waiting on the lock of this object. A call to the notify() method has no consequences if there are no threads in the wait set of the object. The notifyAll() method wakes up all threads in the wait set of the shared object. Below program shows three threads, manipulating the same stack. Two of them are pushing elements on the stack, while the third one is popping elements off the stack. This example illustrates how a thread waiting as a result of calling the wait() method on an object, is notified by another thread calling the notify() method on the same object
class StackClass { private Object[] stackArray; private volatile int topOfStack; StackClass(int capacity) { stackArray = new Object[capacity]; topOfStack = -1; } public synchronized Object pop() { System.out.println(Thread.currentThread() + ": popping"); while (isEmpty()) { try { System.out.println(Thread.currentThread() + ": waiting to pop"); wait(); } catch (InterruptedException e) { e.printStackTrace(); } } Object obj = stackArray[topOfStack]; stackArray[topOfStack--] = null; System.out.println(Thread.currentThread() + ": notifying after pop"); notify(); return obj;
public class WaitAndNotifyExample { public static void main(String[] args) { StackClass stack = new StackClass(5); new StackPusher("One", stack); new StackPusher("Two", stack); new StackPopper("Three", stack); System.out.println("Main Thread sleeping."); try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Exit from Main Thread."); } }
The field topOfStack in class StackClass is declared volatile, so that read and write operations on this variable will access the master value of this variable, and not any copies, during runtime. Since the threads manipulate the same stack object and the push() and pop() methods in the class StackClassare synchronized, it means that the threads synchronize on the same object.
How the program uses wait() and notify() for inter thread communication.
(1) The synchronized pop() method - When a thread executing this method on the StackClass object finds that the stack is empty, it invokes the wait() method in order to wait for some other thread to fill the stack by using the synchronized push. Once an other thread makes a push, it invokes the notify method. (2)The synchronized push() method - When a thread executing this method on the StackClass object finds that the stack is full, i t invokes the wait() method to await some other thread to remove an element to provide space for the newly to be pushed element. Once an other thread makes a pop, it invokes the notify method.
~~~~~~~~~~~~
Joining
A thread invokes the join() method on another thread in order to wait for the other thread to complete its execution. Consider a thread t1 invokes the method join() on a thread t2. The join() call has no effect if thread t2 has already completed. If thread t2 is still alive, then thread t1 transits to the Blockedfor-join-completion state.
Below is a program showing how threads invoke the overloaded thread join method.
public class ThreadJoinDemo { public static void main(String[] args) { Thread t1 = new Thread("T1"); Thread t2 = new Thread("T2");
Output
Wait for the child threads to finish. Thread T1 is not alive. Thread T2 is not alive. Exit from Main Thread.
Deadlock
There are situations when programs become deadlocked when each thread is waiting on a resource that cannot become available. The simplest form of deadlock is when two threads are each waiting on a resource that is locked by the other thread. Since each thread is waiting for the other thread to relinquish a lock, they both remain waiting forever in the Blocked-for-lockacquisition state. The threads are said to be deadlocked. Thread t1 at tries to synchronize first on string o1 and then on string o2. The thread t2 does the opposite. It synchronizes first on string o2 then on string o1. Hence a deadlock can occur as explained above.
Below is a program that illustrates deadlocks in multithreading applications
public class DeadLockExample { String o1 = "Lock "; String o2 = "Step "; Thread t1 = (new Thread("Printer1") { public void run() { while (true) { synchronized (o1) { synchronized (o2) { System.out.println(o1 + o2); } } } } }); Thread t2 = (new Thread("Printer2") { public void run() { while (true) {
Note: The following methods namely join, sleep and wait name the InterruptedException in its throws clause and can have a timeout argument as a parameter. The following methods namely wait, notify and notifyAll should only be called by a thread that holds the lock of the instance on which the method is invoked. The Thread.start method causes a new thread to get ready to run at the discretion of the thread scheduler. The Runnable interface declares the run method. The Thread class implements the Runnable interface. Some implementations of the Thread.yield method will not yield to a thread of lower priority. A program will terminate only when all user threads stop running. A thread inherits its daemon status from the thread that created it
A Collections Framework is defined by a set of interfaces, concrete class implementations for most of the interfaces and a set of standard utility methods and algorithms. In addition, the framework also provides several abstract implementations, which are designed to make it easier for you to create new and different implementations for handling collections of data.
Collection
Set List Iterator (Not a part of the Collections Framework) SortedSet Map SortedMap
Collection Interface
Concrete Classes
The concrete classes that are specific implementations of the core interfaces, providing data structures that a java program can use.
Note: Concrete Classes for the Map is shown in the previous section. Standard utility methods and algorithms that can be used to perform various operations on collections, such as sorting, searching or creating customized collections.
The collections stores object references, rather than objects themselves. Hence primitive values cannot be stored in a collection directly. They need to be encapsulated (using wrapper classes) into an Object prior to storing them into a Collection (such as HashSet, HashMap etc). The references are always stored as type Object. Thus, when you retrieve an element from a collection, you get an Object rather then the actual type of the collection stored in the database. Hence we need to downcast it to the Actual Type while retrieving an element from a collection. One of the capabilities of the Collection Framework is to create a new Collection object and populate it with the contents of an existing Collection object of a same or different actual type.
Below is an example program showing the storing and retrieving of a few Collection Types
import java.util.*;
public class CollectionsDemo { public static void main(String[] args) { List a1 = new ArrayList(); a1.add("Beginner"); a1.add("Java"); a1.add("tutorial"); System.out.println(" ArrayList Elements"); System.out.print("\t" + a1); List l1 = new LinkedList(); l1.add("Beginner"); l1.add("Java"); l1.add("tutorial"); System.out.println(); System.out.println(" LinkedList Elements"); System.out.print("\t" + l1); Set s1 = new HashSet(); // or new TreeSet() will order the elements; s1.add("Beginner"); s1.add("Java"); s1.add("Java"); s1.add("tutorial"); System.out.println(); System.out.println(" Set Elements"); System.out.print("\t" + s1); Map m1 = new HashMap(); // or new TreeMap() will order based on keys m1.put("Windows", "98"); m1.put("Win", "XP"); m1.put("Beginner", "Java"); m1.put("Tutorial", "Site"); System.out.println(); System.out.println(" Map Elements"); System.out.print("\t" + m1); } }
Output
ArrayList Elements [Beginner, Java, tutorial] LinkedList Elements [Beginner, Java, tutorial] Set Elements [tutorial, Beginner, Java] Map Elements {Tutorial=Site, Windows=98, Win=XP, Beginner=Java}
Java ArrayList Java LinkedList Java TreeSet Java HashMap Java Vector Java HashTable Java HashSet
ArrayList
public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, Serializable
Resizable-array implementation of the List interface. A java ArrayList is used to store an ordered group of elements where duplicates are allowed. Implements all optional list operations, and permits all elements, including null. This class is similar to Vector, except that it is unsynchronized. The size, isEmpty, get, set, iterator, and listIterator operations run in constant time. ArrayLists give great performance on get() and set() methods, but do not perform well on add() and remove() methods when compared to a LinkedList. An ArrayList capacity is the size of the array used to store the elements in the list. As elements are added to an ArrayList, its capacity grows automatically. It is an Array based implementation where elements of the List can be accessed directly through get() method.
To prevent unsynchronized access to the list: List list = Collections.synchronizedList(new ArrayList()); Below is an ArrayList Example showing how collections are manipulated using an ArrayList
import java.util.List; import java.util.ArrayList; import java.util.Iterator; import java.util.ListIterator; import java.util.Collections; import java.util.Random; public class ArrayListExample { public static void main(String[] args) { // ArrayList Creation List arraylistA = new ArrayList(); List arraylistB = new ArrayList(); // Adding elements to the ArrayList for (int i = 0; i < 5; i++) { arraylistA.add(new Integer(i)); } arraylistB.add("beginner"); arraylistB.add("java"); arraylistB.add("tutorial"); arraylistB.add("."); arraylistB.add("com");
Output ArrayList arraylistA > 0 , 1 , 2 , 3 , 4 , ArrayList arraylistA > 0 , 1 , 2 , 3 , 4 , ArrayList arraylistB > beginner , java , tutorial , . , com , java , site , Using ListIterator to retrieve ArrayList Elements ArrayList arraylistA > 0,1,2,3,4, java was found at : 1 java was found at : 5 from the last New Sub-List(arraylistA) from index 3 to 5: [3, 4] Sorted ArrayList arraylistA > [0, 1, 2, 3, 4] Reversed ArrayList arraylistA > [4, 3, 2, 1, 0] Is arraylistA empty? false arraylistA.equals(arraylistC)? true ArrayList arraylistA after shuffling its elements> 3 , 2 , 1 , 0 , 4 , Array Element [0] = 3 Array Element [1] = 2 Array Element [2] = 1 Array Element [3] = 0 Array Element [4] = 4
Linked List
A LinkedList is used to store an ordered group of elements where duplicates are allowed. A LinkedList is based on a double linked list where elements of the List are typically accessed through add() and remove() methods.
Below is an LinkedList Example showing how collections are manipulated using an LinkedList import java.util.List; import java.util.LinkedList; import java.util.Iterator; import java.util.ListIterator; import java.util.Collections; import java.util.Random; public class LinkedListExample { public static void main(String[] args) { // LinkedList Creation List linkedListA = new LinkedList(); List linkedListB = new LinkedList(); // Adding elements to the LinkedList for (int i = 0; i < 5; i++) { linkedListA.add(new Integer(i)); } linkedListB.add("beginner"); linkedListB.add("java"); linkedListB.add("tutorial"); linkedListB.add("."); linkedListB.add("com"); linkedListB.add("java"); linkedListB.add("site"); // Iterating through the LinkedList to display the Contents. Iterator i1 = linkedListA.iterator(); System.out.println("LinkedList linkedListA --> "); while (i1.hasNext()) { System.out.println(i1.next() + " , "); } System.out.println(); System.out.println("LinkedList linkedListA --> "); for (int j = 0; j < linkedListA.size(); j++) { System.out.println(linkedListA.get(j) + " , "); } System.out.println(); Iterator i2 = linkedListB.iterator(); System.out.println("LinkedList linkedListB --> ");
//
while (i2.hasNext()) { System.out.println(i2.next() + " , "); } System.out.println(); System.out.println(); System.out.println("Using ListIterator to retrieve LinkedList Elements"); System.out.println(); ListIterator li1 = linkedListA.listIterator(); // next(), hasPrevious(), hasNext(), hasNext() nextIndex() can be used with a // ListIterator interface implementation System.out.println("LinkedList linkedListA --> "); while (li1.hasNext()) { System.out.println(li1.next() + " , "); } System.out.println(); // Searching for an element in the LinkedList int index = linkedListB.indexOf("java"); System.out.println("'java' was found at : " + index); int lastIndex = linkedListB.lastIndexOf("java"); System.out.println("'java' was found at : " + lastIndex+ " from the last"); System.out.println(); // Getting the subList from the original List List subList = linkedListA.subList(3, linkedListA.size()); System.out.println("New Sub-List(linkedListA) from index 3 to " + linkedListA.size() + ": " + subList); System.out.println(); // Sort an LinkedList System.out.println("Sorted LinkedList linkedListA --> "); Collections.sort(linkedListA); System.out.println(linkedListA); System.out.println(); // Reversing an LinkedList System.out.println("Reversed LinkedList linkedListA --> "); Collections.reverse(linkedListA); System.out.println(linkedListA); System.out.println(); // Checking emptyness of an LinkedList System.out.println("Is linkedListA empty? "+ linkedListA.isEmpty()); System.out.println(); // Checking for Equality of LinkedLists LinkedList LinkedListC = new LinkedList(linkedListA); System.out.println("linkedListA.equals(LinkedListC)? " + linkedListA.equals(LinkedListC)); System.out.println(); Shuffling the elements of an LinkedList in Random Order Collections.shuffle(linkedListA, new Random()); System.out.println("LinkedList linkedListA after shuffling its elements--> "); i1 = linkedListA.iterator(); while (i1.hasNext()) { System.out.println(i1.next() + " , ");
} System.out.println(); System.out.println(); // Converting an LinkedList to an Array Object[] array = linkedListA.toArray(); for (int i = 0; i < array.length; i++) { System.out.println("Array Element [" + i + "] = " + array[i]); } System.out.println(); // Clearing LinkedList Elements linkedListA.clear(); System.out.println("linkedListA after clearing : " + linkedListA); System.out.println(); } } Output LinkedList linkedListA > 0 , 1 , 2 , 3 , 4 , LinkedList linkedListA > 0 , 1 , 2 , 3 , 4 , LinkedList linkedListB > beginner , java , tutorial , . , com , java , site , Using ListIterator to retrieve LinkedList Elements LinkedList linkedListA > 0,1,2,3,4, java was found at : 1 java was found at : 5 from the last New Sub-List(linkedListA) from index 3 to 5: [3, 4] Sorted LinkedList linkedListA > [0, 1, 2, 3, 4] Reversed LinkedList linkedListA > [4, 3, 2, 1, 0] Is linkedListA empty? false linkedListA.equals(LinkedListC)? true LinkedList linkedListA after shuffling its elements> 3 , 2 , 4 , 0 , 1 , Array Element [0] = 3 Array Element [1] = 2 Array Element [2] = 4 Array Element [3] = 0 Array Element [4] = 1 linkedListA after clearing : []
TreeSet
public class TreeSet<E> extends AbstractSet<E> implements SortedSet<E>, Cloneable, Serializable
This class implements the Set interface and guarantees that the sorted set will be in ascending element order, sorted according to the natural order of the elements or by the comparator provided at set creation time, depending on which constructor is used. This implementation not synchronized provides guaranteed log(n) time cost for the basic operations (add, remove and contains).
To prevent unsynchronized access to the Set.: SortedSet s = Collections.synchronizedSortedSet(new TreeSet(..)); Below is a TreeSet Example showing how collections are manipulated using a TreeSet
import java.util.Set; import java.util.TreeSet; import java.util.Iterator; public class TreeSetExample { public static void doTreeSetExample() { } public static void main(String[] args) { Set treeSet = new TreeSet(); // the treeset stores Integer objects into the TreeSet for (int i = 0; i < 5; i++) { treeSet.add(new Integer(i)); } // Since its a Integer Object Set adding any other elements in the Same // set will produce a // ClassCastException exception at runtime. // treeSet.add("a string"); System.out.println("The elements of the TreeSet are : "); Iterator i = treeSet.iterator(); while (i.hasNext()) { System.out.println(i.next() + "\t"); } } }
HashMap
The java HashMap class does not guarantee that the order will remain constant over time. This implementation provides constant-time performance for the basic operations (get and put), assuming the hash function disperses the elements properly among the buckets. The HashMap implementation is not synchronized. If multiple threads access this map concurrently, and at least one of the threads modifies the map structurally, it must be synchronized externally.
To prevent unsynchronized access to the Map: Map m = Collections.synchronizedMap(new HashMap()); Below is a HashMap Example used to store the number of words that begin with a given letter
/* * Using a HashMap to store the number of words that begin with a given letter. */ import java.util.HashMap; public class HashMapExample { static String[] names = { "heman", "bob", "hhh", "shawn", "scot","shan", "keeth" }; private static HashMap counter = new HashMap(); private static Integer cnt = null; public static void main(String args[]) { for (int i = 0; i < names.length; i++) { cnt = (Integer) (counter.get(new Character(names[i].charAt(0)))); if (cnt == null) { counter.put(new Character(names[i].charAt(0)),new Integer("1")); } else { counter.put(new Character(names[i].charAt(0)), new Integer(cnt.intValue() + 1)); } } System.out.println("\nnumber of words beginning with each letter is shown below "); System.out.println(counter.toString()); } }
Output number of words beginning with each letter is shown below {s=3, b=1, k=1, h=2}
Vector
public class Vector<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, Serializable
The Vector class implements a growable array of objects where the size of the vector can grow or shrink as needed dynamically. Like an array, it contains components that can be accessed using an integer index. An application can increase the capacity of a vector before inserting a large number of components; this reduces the amount of incremental reallocation.
Below is a Vector Example showing how collections are manipulated using a Vector
import java.awt.Container; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.util.Enumeration; import java.util.NoSuchElementException; import java.util.Vector; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JTextField; public class VectorDemo extends JFrame { private JLabel jlbString = new JLabel("Enter a string"); public VectorDemo() { super("Vector class demo"); // Made final as it can be accessed by inner classes final JLabel jlbStatus = new JLabel(); Container contentPane = getContentPane(); final Vector vector = new Vector(1); contentPane.setLayout(new FlowLayout()); contentPane.add(jlbString); final JTextField jtfInput = new JTextField(10); contentPane.add(jtfInput); JButton jbnAdd = new JButton("Add"); jbnAdd.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { vector.addElement(jtfInput.getText().trim()); jlbStatus.setText("Appended to end: "+ jtfInput.getText().trim()); jtfInput.setText(""); } }); contentPane.add(jbnAdd); JButton jbnRemove = new JButton("Remove"); jbnRemove.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) {
Output
HashTable
HashTable is synchronized. Iterator in the HashMap is fail-safe while the enumerator for the Hashtable isnt. Hashtable doesnt allow nulls
Below is a HashTable Example showing how collections are manipulated using a HashTable Please Note that It must be Compiled in Java 1.4.
// Demonstrates the Hashtable class of the java.util package. public class HashTableDemo extends JFrame { public HashTableDemo() { super(" Hashtable Sourcecode Example"); final JLabel jlbStatus = new JLabel(); final Hashtable hashTable = new Hashtable(); final JTextArea display = new JTextArea(4, 20); display.setEditable(false); JPanel jplNorth = new JPanel(); jplNorth.setLayout(new BorderLayout()); JPanel jplNorthSub = new JPanel(); jplNorthSub.add(new JLabel("Name (Key)")); final JTextField jtfFirstName = new JTextField(8); jplNorthSub.add(jtfFirstName); jplNorthSub.add(new JLabel("Phone No")); final JTextField jtfPhone = new JTextField(8); jplNorthSub.add(jtfPhone); jplNorth.add(jplNorthSub, BorderLayout.NORTH); jplNorth.add(jlbStatus, BorderLayout.SOUTH); JPanel jplSouth = new JPanel(); jplSouth.setLayout(new GridLayout(2, 5)); JButton jbnAdd = new JButton("Add"); jbnAdd.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String strNum = jtfPhone.getText().trim(); String strName = jtfFirstName.getText().trim(); if ((strNum != null && strNum.equals("")) || (strName != null && strName.equals(""))) { JOptionPane.showMessageDialog(HashTableDemo.this, "Please enter both Name and Phone No"); return; } int num = 0; try { num = Integer.parseInt(strNum); } catch (NumberFormatException ne) { ne.printStackTrace(); } EmployeeDetails emp = new EmployeeDetails(strName, num); Object val = hashTable.put(strName, emp); if (val == null) jlbStatus.setText("Added: " + emp.toString()); else
Output
HashSet
The HashSet class implements the Set interface. It makes no guarantee that the order of elements will remain constant over time. This class is not synchronized and permits a null element. This class offers constant time performance for the basic operations (add, remove, contains and size), assuming the hash function disperses the elements properly among the buckets. To prevent unsynchronized access to the Set: Set s = Collections.synchronizedSet(new HashSet());
Below is a HashSet Example showing how collections are manipulated using a HashSet
import java.util.*; public class HashSetExample { private static String names[] = { "bob", "hemanth", "hhh", "hero", "shawn", "bob", "mike", "Rick", "rock", "hemanth", "mike", "undertaker" }; public static void main(String args[]) { ArrayList aList; aList = new ArrayList(Arrays.asList(names)); System.out.println("The names elements " + aList); HashSet ref = new HashSet(aList); // create a HashSet Iterator i = ref.iterator(); System.out.println(); System.out.println("Unique names are: "); while (i.hasNext()) System.out.println(i.next() + " "); System.out.println(); } }
Output The names elements [bob, hemanth, hhh, hero, shawn, bob, mike, Rick, rock, hemanth, mike, undertaker] Unique names are: hhh hero bob Rick shawn hemanth rock mike undertaker
Output 1. Add to a Date Operation c1.getTime() : Sat Mar 31 10:47:54 IST 2007 c1.get(Calendar.YEAR): 2007 Todays date in Date Format : Sat Mar 31 10:47:54 IST 2007 c1.set(1999,0 ,20) : Wed Jan 20 10:47:54 IST 1999 Date + 20 days is : 09-02-1999 2. Subtract to a date Operation Date is : 20-01-1999 Date roll down 1 month : 20-12-1999 Date is : 20-01-1999 Date minus 1 month : 20-12-1998 3. No of Days between 2 dates Days Between Wed Jan 20 10:47:54 IST 1999 and Fri Jan 22 10:47:54 IST 1999 is 2 4. No of Days in a month for a given date Days in 6th month for year 1999 is 31 5. Validate a given date Unparseable date: 20031315 6. Comparision of 2 dates 15-03-2000 is less than 15-03-2001 7. Get the day for a given date The day for Sat Mar 31 10:47:54 IST 2007 is Saturday -
What is the GregorianCalendar class? The GregorianCalendar provides support for traditional Western calendars. What is the SimpleTimeZone class? The SimpleTimeZone class provides support for a Gregorian calendar.
Java Swing
Java Swings Tutorial What is Swings in java ?
A part of The JFC Swing Java consists of Look and feel Accessibility Java 2D Drag and Drop, etc Compiling & running programs
if you do not explicitly add a GUI component to a container, the GUI component will not be displayed when the container appears on the screen.
Swing, which is an extension library to the AWT, includes new and improved components that enhance the look and functionality of GUIs. Swing can be used to build Standalone swing gui Apps as well as Servlets and Applets. It employs a model/view design architecture. Swing is more portable and more flexible than AWT. Swing Model/view design: The view part of the MV design is implemented with a component object and the UI object. The model part of the MV design is implemented by a model object and a change listener object. Swing is built on top of AWT and is entirely written in Java, using AWTs lightweight component support. In particular, unlike AWT, t he architecture of Swing components makes it easy to customize both their appearance and behavior. Components from AWT and Swing can be mixed, allowing you to add Swing support to existing AWT-based programs. For example, swing components such as JSlider, JButton and JCheckbox could be used in the same program with standard AWT labels, textfields and scrollbars. You could subclass the existing Swing UI, model, or change listener classes without having to reinvent the entire implementation. Swing also has the ability to replace these objects on-the-fly.
100% Java implementation of components Pluggable Look & Feel Lightweight components Uses MVC Architecture Model represents the data View as a visual representation of the data Controller takes input and translates it to changes in data Three parts Component set (subclasses of JComponent) Support classes Interfaces
In Swing, classes that represent GUI components have names beginning with the letter J. Some examples are JButton, JLabel, and JSlider. Altogether there are more than 250 new classes and 75 interfaces in Swing twice as many as in AWT. Java Swing class hierarchy The class JComponent, descended directly from Container, is the root class for most of Swings user interface components.
Swing contains components that youll use to build a GUI. I am listing you some of the commonly used Swing components. To learn and understand these swing programs, AWT Programming knowledge is not required.
Output
Note: Below are some links to java swing tutorials that forms a helping hand to get started with java programming swing.
JPanel is Swings version of the AWT class Panel and uses the same default layout, FlowLayout. JPanel is descended directly from JComponent. JFrame is Swings version of Frame and is descended directly from that class. The components added to the frame are referred to as its contents; these are managed by the contentPane. To add a component to a JFrame, we must use its contentPane instead. JInternalFrame is confined to a visible area of a container it is placed in. It can be iconified , maximized and layered. JWindow is Swings version of Window and is descended directly from that class. Like Window, it uses BorderLayout by default. JDialog is Swings version of Dialog and is descended directly from that class. Like Dialog, it uses BorderLayout by default. Like JFrame and JWindow, JDialog contains a rootPane hierarchy including a contentPane, and it allows layered and glass panes. All dialogs are modal, which means the current thread is blocked until user interaction with it has been completed. JDialog class is intended as the basis for creating custom dialogs; however, some of the most common dialogs are provided through static methods in the class JOptionPane. JLabel, descended from JComponent, is used to create text labels. The abstract class AbstractButton extends class JComponent and provides a foundation for a family of button classes, including JButton. JTextField allows editing of a single line of text. New features include the ability to justify the text left, right, or center, and to set the texts font. JPasswordField (a direct subclass of JTextField) you can suppress the display of input. Each character entered can be replaced by an echo character. This allows confidential input for passwords, for example. By default, the echo character is the asterisk, *. JTextArea allows editing of multiple lines of text. JTextArea can be used in conjunction with class JScrollPane to achieve scrolling. The underlying JScrollPane can be forced to always or never have either the vertical or horizontal scrollbar; JButton is a component the user clicks to trigger a specific action. JRadioButton is similar to JCheckbox, except for the default icon for each class. A set of radio buttons can be associated as a group in which only one button at a time can be selected. JCheckBox is not a member of a checkbox group. A checkbox can be selected and deselected, and it also displays its current state. JComboBox is like a drop down box. You can click a drop-down arrow and select an option from a list. For example, when the component has focus, pressing a key that corresponds to the first character in some entrys name selects that entry. A vertical scrollbar is used for longer lists. JList provides a scrollable set of items from which one or more may be selected. JList can be populated from an Array or Vector. JList does not support scrolling directly, instead, the list must be associated with a scrollpane. The view port used by the scroll pane can also have a user-defined border. JList actions are handled using ListSelectionListener.
JTabbedPane contains a tab that can have a tool tip and a mnemonic, and it can display both text and an image. JToolbar contains a number of components whose type is usually some kind of button which can also include separators to group related components within the toolbar. FlowLayout when used arranges swing components from left to right until theres no more space available. Then it begins a new row below it and moves from left to right again. Each component in a FlowLayout gets as much space as it needs and no more. BorderLayout places swing components in the North, South, East, West and center of a container. You can add horizontal and vertical gaps between the areas. GridLayout is a layout manager that lays out a containers components in a rectangular grid. The container is divided into equal-sized rectangles, and one component is placed in each rectangle. GridBagLayout is a layout manager that lays out a containers components in a grid of cells with each component occupying one or more cells, called its display area. The display area aligns components vertically and horizontally, without requiring that the components be of the same size. JMenubar can contain several JMenus. Each of the JMenus can contain a series of JMenuItem s that you can select. Swing provides support for pull-down and popup menus. Scrollable JPopupMenu is a scrollable popup menu that can be used whenever we have so many items in a popup menu that exceeds the screen visible height. Java Swing Projects
Java Swing Calculator developed using Java Swing. It is a basic four-function calculator java program source code. Java Swing Address Book demonstrates how to create a simple free address book program using java swing and jdbc. Also you will learn to use the following swing components like Jbuttons, JFrames, JTextFields and Layout Manager (GridBagLayout).
Java JDBC
The JDBC ( Java Database Connectivity) API defines interfaces and classes for writing database applications in Java by making database connections. Using JDBC you can send SQL, PL/SQL statements to almost any relational database. JDBC is a Java API for executing SQL statements and supports basic SQL functionality. It provides RDBMS access by allowing you to embed SQL inside Java code. Because Java can run on a thin client, applets embedded in Web pages can contain downloadable JDBC code to enable remote database access. You will learn how to create a table, insert values into it, query the table, retrieve results, and update the table with the help of a JDBC Program example.
Although JDBC was designed specifically to provide a Java interface to relational databases, you may find that you need to write Java code to access non-relational databases as well.
JDBC Architecture
Java application calls the JDBC library. JDBC loads a driver which talks to the database. We can change database engines without changing database code.
In this step of the jdbc connection process, we load the driver class by calling Class.forName() with the Driver class name as an argument. Once loaded, the Driver class creates an instance of itself. A client can connect to Database Server through JDBC Driver. Since most of the Database servers support ODBC driver therefore JDBC-ODBC Bridge driver is commonly used. The return type of the Class.forName (String ClassName) method is Class. Class is a class in java.lang package. try { Class.forName(sun.jdbc.odbc.JdbcOdbcDriver); //Or any other driver } catch(Exception x){ System.out.println( Unable to load the driver class! ); } 2. Creating a oracle jdbc Connection The JDBC DriverManager class defines objects which can connect Java applications to a JDBC driver. DriverManager is considered the backbone of JDBC architecture. DriverManager class manages the JDBC drivers that are installed on the system. Its getConnection() method is used to establish a connection to a database. It uses a username, password, and a jdbc url to establish
a connection to the database and returns a connection object. A jdbc Connection represents a session/connection with a specific database. Within the context of a Connection, SQL, PL/SQL statements are executed and results are returned. An application can have one or more connections with a single database, or it can have many connections with different databases. A Connection object provides metadata i.e. information about the database, tables, and fields. It also contains methods to deal with transactions. JDBC URL Syntax:: jdbc: <subprotocol>: <subname> JDBC URL Example:: jdbc: <subprotocol>: <subname>Each driver has its own subprotocol Each subprotocol has its own syntax for the source. Were using the jdbc odbc subprotocol, so the DriverManager knows to use the sun.jdbc.odbc.JdbcOdbcDriver. try{ Connection dbConnection=DriverManager.getConnection(url,loginName,Password) } catch( SQLException x ){ System.out.println( Couldnt get connection! ); } 3. Creating a jdbc Statement object, Once a connection is obtained we can interact with the database. Connection interface defines methods for interacting with the database via the established connection. To execute SQL statements, you need to instantiate a Statement object from your connection object by using the createStatement() method. Statement statement = dbConnection.createStatement(); A statement object is used to send and execute SQL statements to a database.
Three kinds of Statements
Statement: Execute simple sql queries without parameters. Statement createStatement() Creates an SQL Statement object. Prepared Statement: Execute precompiled sql queries with or without parameters. PreparedStatement prepareStatement(String sql) returns a new PreparedStatement object. PreparedStatement objects are precompiled SQL statements. Callable Statement: Execute a call to a database stored procedure. CallableStatement prepareCall(String sql) returns a new CallableStatement object. CallableStatement objects are SQL stored procedure call statements.
4. Executing a SQL statement with the Statement object, and returning a jdbc resultSet.
Statement interface defines methods that are used to interact with database via the execution of SQL statements. The Statement class has three methods for executing statements: executeQuery(), executeUpdate(), and execute(). For a SELECT statement, the method to use is executeQuery . For statements that create or modify tables, the method to use is executeUpdate. Note: Statements that create a table, alter a table, or drop a table are all examples of DDL statements and are executed with the method executeUpdate. execute() executes an SQL statement that is written as String object. ResultSet provides access to a table of data generated by executing a Statement. The table rows are retrieved in sequence. A ResultSet maintains a cursor pointing to its current row of data. The next() method is used to successively step through the rows of the tabular results. ResultSetMetaData Interface holds information on the types and properties of the columns in a ResultSet. It is constructed from the Connection object.
Test JDBC Driver Installation
import javax.swing.JOptionPane; public class TestJDBCDriverInstallation_Oracle { public static void main(String[] args) { StringBuffer output = new StringBuffer(); output.append(Testing oracle driver installation \n); try { String className = sun.jdbc.odbc.JdbcOdbcDriver; Class driverObject = Class.forName(className); output.append(Driver : +driverObject+\n); output.append(Driver Installation Successful); JOptionPane.showMessageDialog(null, output); } catch (Exception e) { output = new StringBuffer(); output.append(Driver Installation FAILED\n); JOptionPane.showMessageDialog(null, output); System.out.println(Failed: Driver Error: + e.getMessage()); } } }
if(con!= null){ System.out.println(Got Connection.); DatabaseMetaData meta = con.getMetaData(); System.out.println(Driver Name : +meta.getDriverName()); System.out.println(Driver Version : +meta.getDriverVersion()); }else{ System.out.println(Could not Get Connection); } } public static Connection getOracleJDBCConnection(){ try { Class.forName(sun.jdbc.odbc.JdbcOdbcDriver); } catch(java.lang.ClassNotFoundException e) { System.err.print(ClassNotFoundException: ); System.err.println(e.getMessage()); } try { con = DriverManager.getConnection(url, userid, password); } catch(SQLException ex) { System.err.println(SQLException: + ex.getMessage()); } return con; } }
The ResultSet interface provides methods for retrieving and manipulating the results of executed queries, and ResultSet objects can have different functionality and characteristics. These characteristics are result set type, result set concurrency, and cursor holdability. The type of a ResultSet object determines the level of its functionality in two areas: the ways in which the cursor can be manipulated, and how concurrent changes made to the underlying data source are reflected by the ResultSet object. The sensitivity of the ResultSet object is determined by one of three different ResultSet types:
TYPE_FORWARD_ONLY the result set is not scrollable i.e. the cursor moves only forward, from before the first row to after the last row. TYPE_SCROLL_INSENSITIVE the result set is scrollable; its cursor can move both forward and backward relative to the current position, and it can move to an absolute position. TYPE_SCROLL_SENSITIVE the result set is scrollable; its cursor can move both forward and backward relative to the current position, and it can move to an absolute position.
Before you can take advantage of these features, however, you need to create a scrollable ResultSet object. The following line of code illustrates one way to create a scrollable ResultSet object: Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); ResultSet srs = stmt.executeQuery(..); The first argument is one of three constants added to the ResultSet API to indicate the type of a ResultSet object: TYPE_FORWARD_ONLY, TYPE_SCROLL_INSENSITIVE, and TYPE_SCROLL_SENSITIVE. The second argument is one of two ResultSet constants for specifying whether a result set is read-only or updatable: CONCUR_READ_ONLY and CONCUR_UPDATABLE. If you do not specify any constants for the type and updatability of a ResultSet object, you will automatically get one that is TYPE_FORWARD_ONLY and CONCUR_READ_ONLY.
141 JAVA FOR BEGINNERS last() - moves the cursor to the last row in the ResultSet object. Returns true if the cursor is now positioned on the last row and false if the ResultSet object does not contain any rows. beforeFirst() - positions the cursor at the start of the ResultSet object, before the first row. If the ResultSet object does not contain any rows, this method has no effect. afterLast() - positions the cursor at the end of the ResultSet object, after the last row. If the ResultSet object does not contain any rows, this method has no effect. relative(int rows) - moves the cursor relative to its current position. absolute(int n) - positions the cursor on the n-th row of the ResultSet object.
Type 1: JDBC-ODBC Bridge Advantage The JDBC-ODBC Bridge allows access to almost any database, since the databases ODBC drivers are already available. Disadvantages 1. Since the Bridge driver is not written fully in Java, Type 1 drivers are not portable. 2. A performance issue is seen as a JDBC call goes through the bridge to the ODBC driver, then to the database, and this applies even in the reverse process. They are the slowest of all driver types. 3. The client system requires the ODBC Installation to use the driver. 4. Not good for the Web.
Type 2: Native api/ Partly Java Driver Advantage The distinctive characteristic of type 2 jdbc drivers are that they are typically offer better performance than the JDBC-ODBC Bridge as the layers of communication (tiers) are less than that of Type 1 and also it uses Native api which is Database specific. Disadvantage 1. Native API must be installed in the Client System and hence type 2 drivers cannot be used for the Internet. 2. Like Type 1 drivers, its not written in Java Language which forms a portability issue. 3. If we change the Database we have to change the native api as it is specific to a database 4. Mostly obsolete now 5. Usually not thread safe.
Type 3: All Java/ Net-Protocol Driver Advantage 1. This driver is server-based, so there is no need for any vendor database library to be present on client machines. 2. This driver is fully written in Java and hence Portable. It is suitable for the web. 3. There are many opportunities to optimize portability, performance, and scalability. 4. The net protocol can be designed to make the client JDBC driver very small and fast to load. 5. The type 3 driver typically provides support for features such as caching (connections, query results, and so on), load balancing, and advanced system administration such as logging and auditing. 6. This driver is very flexible allows access to multiple databases using one driver. 7. They are the most efficient amongst all driver types. Disadvantage It requires another server application to install and maintain. Traversing the recordset may take longer, since the data comes through the backend server.
Type 4: Native-protocol/all-Java driver Advantage 1. The major benefit of using a type 4 jdbc drivers are that they are completely written in Java to achieve platform independence and eliminate deployment administration issues. It is most suitable for the web. 2. Number of translation layers is very less i.e. type 4 JDBC drivers dont have to translate database requests to ODBC or a native connectivity interface or to pass the request on to another server, performance is typically quite good. 3. You dont need to install special software on the client or server. Further, these drivers can be downloaded dynamically. Disadvantage With type 4 drivers, the user needs a different driver for each database.
Employees:
Employee_ID 6323 5768 1234 5678 Name Hemanth Bob Shawn Michaels
import javax.swing.JOptionPane; import java.sql.*; public class JDBCProgram{ static String userid=scott, password = tiger; static String url = jdbc:odbc:bob; // String url = jdbc:mySubprotocol:myDataSource; ? static Statement stmt; static Connection con; public static void main(String args[]){
JOptionPane.showMessageDialog (null,JDBC Programming showing Creation of Tables); int choice = -1; do{ choice = getChoice(); if (choice != 0){ getSelected(choice); } } while ( choice != 0); System.exit(0);
public static int getChoice() { String choice; int ch; choice = JOptionPane.showInputDialog(null, 1. Create Employees Table\n+ 2. Create Products Table\n+ 0. Exit\n\n+ Enter your choice); ch = Integer.parseInt(choice); return ch; } public static void getSelected(int choice){ if(choice==1){ createEmployees(); } if(choice==2){ createOrders(); } } public static Connection getConnection() { Class.forName (sun.jdbc.odbc.JdbcOdbcDriver); ame); ? try {
//Class.forName(myDriver.ClassN
JDBC
Insert
We will insert data into the tables Employees and Orders as created in the previous tutorial, one row at a time, supplying the information to be stored in each column of that row using a jdbc insert query statement. The values to be inserted into the columns are listed in the same order that the columns were declared when the table was created. Below is a JDBC Program showing the use of executeUpdate() to create a table and insert row into using java jdbc insert data statement. For my website I am creating the following 2 tables (Employee, Orders) as a part of the JDBC tutorial for insert in jdbc insert query. Employee_ID is the primary key which forms a relation between the 2 tables. CREATE TABLE Employees (Employee_ID INTEGER,Name VARCHAR(30) ); Employees: Employee_ID 6323 5768 1234 5678 Orders: CREATE TABLE Orders (Prod_ID INTEGER,ProductName VARCHAR(20), Employee_ID INTEGER ); Prod_ID 543 432 876 Product Name Belt Bottle Ring Employee_ID 6323 1234 5678 Name Hemanth Bob Shawn Michaels
Iinsert using JDBC Insert Statement import javax.swing.JOptionPane; import java.sql.*; public class JDBCProgram{ //JDBC Insert Example static String userid=scott, password = tiger; static String url = jdbc:odbc:bob; // String url = jdbc:mySubprotocol:myDataSource; ? static Statement stmt; static Connection con; public static void main(String args[]){ JOptionPane.showMessageDialog (null,JDBC Programming showing Insertion of Table Data);
int choice = -1; do{ choice = getChoice(); if (choice != 0){ getSelected(choice); } } while ( choice != 0); System.exit(0); } public static int getChoice() { String choice; int ch; choice = JOptionPane.showInputDialog(null, 1. Create Employees Table\n+ 2. Create Products Table\n+ 3. Insert data into Employees Table\n+ 4. Insert data into Products Table\n+ 0. Exit\n\n+ Enter your choice); ch = Integer.parseInt(choice); return ch; } public static void getSelected(int choice){ if(choice==1){ createEmployees(); } if(choice==2){ createOrders(); } if(choice==3){ insertEmployees(); } if(choice==4){ insertOrders(); } } public static Connection getConnection() { try { Class.forName (sun.jdbc.odbc.JdbcOdbcDriver); //Class.forName(my Driver.ClassName); ? } catch(java.lang.ClassNotFoundException e)
{ System.err.print(ClassNotFoundException: ); System.err.println(e.getMessage()); } try { con = DriverManager.getConnection(url, userid, password); } catch(SQLException ex) { System.err.println(SQLException: + ex.getMessage()); } return con; } /*CREATE TABLE Employees ( Employee_ID INTEGER, Name VARCHAR(30) );*/ public static void createEmployees() { Connection con = getConnection(); String createString; createString = create table Employees ( +Employee_ID INTEGER, + Name VARCHAR(30)); try { stmt = con.createStatement(); stmt.executeUpdate(createString); stmt.close(); con.close(); } catch(SQLException ex) { System.err.println(SQLException: + ex.getMessage()); } JOptionPane.showMessageDialog(null,Employees Table Created); } /*CREATE TABLE Orders ( Prod_ID INTEGER, ProductName VARCHAR(20), Employee_ID INTEGER );*/ public static void createOrders() { Connection con = getConnection(); String createString; createString = create table Orders ( + Prod_ID INTEGER, +ProductName
VARCHAR(20), +Employee_ID INTEGER ); try { stmt = con.createStatement(); stmt.executeUpdate(createString); stmt.close(); con.close(); } catch(SQLException ex) { System.err.println(SQLException: + ex.getMessage()); } JOptionPane.showMessageDialog(null,Orders Table Created); } /*Employee_ID Name 6323 Hemanth 5768 Bob 1234 Shawn 5678 Michaels */ public static void insertEmployees() { Connection con = getConnection(); String insertString1, insertString2, insertString3, insertString4; insertString1 = insert into Employees values(6323, Hemanth); insertString2 = insert into Employees values(5768, Bob); insertString3 = insert into Employees values(1234, Shawn); insertString4 = insert into Employees values(5678, Michaels); try { stmt = con.createStatement(); stmt.executeUpdate(insertString1); stmt.executeUpdate(insertString2); stmt.executeUpdate(insertString3); stmt.executeUpdate(insertString4); stmt.close(); con.close(); } catch(SQLException ex) { System.err.println(SQLException: + ex.getMessage()); } JOptionPane.showMessageDialog(null,Data Inserted into Employees Table); }
/*
*/ public static void insertOrders() { Connection con = getConnection(); String insertString1, insertString2, insertString3, insertString4; insertString1 = insert into Orders values(543, Belt, 6323); insertString2 = insert into Orders values(432, Bottle, 1234); insertString3 = insert into Orders values(876, Ring, 5678); try { stmt = con.createStatement(); stmt.executeUpdate(insertString1); stmt.executeUpdate(insertString2); stmt.executeUpdate(insertString3); stmt.close(); con.close(); } catch(SQLException ex) { System.err.println(SQLException: + ex.getMessage()); } JOptionPane.showMessageDialog(null,Data Inserted into Orders Table); } }//End of class
We can use Java JDBC Select statement in a java program to retrieve the data and display it for the respective Tables. JDBC returns results in a ResultSet object, so we need to declare an instance of the class ResultSet to hold our results. Select is the SQL keyword that performs a query. We invoke the jdbc select query (executequery) method, using the jdbc select data statement as the parameter. The tabular results of the query are captured in the ResultSet object, results. Note that executeQuery() always returns a ResultSet although it need not have any rows in it. The return value for an executeQuery is a ResultSet object containing the results of the query sent to the DBMS, To process each row in the ResultSet, we use the next() method. This method moves the pointer through the rows of data. The ResultSet maintains a cursor pointing to the current row. Because this cursor is initially positioned before the first row, we must call next() before we can see any rows at all. Below is a JDBC Program showing the use of executeQuery() to retrieve values from ResultSets using jdbc programming.
For my website I am creating the following 2 tables (Employee, Orders) as a part of the JDBC tutorial.
Employee_ID is the primary key which forms a relation between the 2 tables.
CREATE TABLE Employees (Employee_ID INTEGER,Name VARCHAR(30) );
Employees Table:
Employee_ID 6323 5768 1234 5678 Name Hemanth Bob Shawn Michaels
Orders Table: CREATE TABLE Orders (Prod_ID INTEGER,ProductName VARCHAR(20), Employee_ID INTEGER );
insertEmployees(); } if(choice==4){ insertOrders(); } if(choice==5){ retrieveEmployees(); } if(choice==6){ retrieveOrders(); } } public static Connection getConnection() { try { Class.forName(sun.jdbc.odbc.JdbcOdbcDriver); //Class.forName(myDriver.ClassName); ? } catch(java.lang.ClassNotFoundException e) { System.err.print(ClassNotFoundException: ); System.err.println(e.getMessage()); } try { con = DriverManager.getConnection(url, userid, password); } catch(SQLException ex) { System.err.println(SQLException: + ex.getMessage()); } return con; } /*CREATE TABLE Employees ( Employee_ID INTEGER, Name VARCHAR(30) );*/ public static void createEmployees() { Connection con = getConnection(); String createString; createString = create table Employees ( +Employee_ID INTEGER, + Name VARCHAR(30)); try { stmt = con.createStatement(); stmt.executeUpdate(createString); stmt.close(); con.close(); } catch(SQLException ex) { System.err.println(SQLException: + ex.getMessage()); } JOptionPane.showMessageDialog(null,Employees Table Created); } /*CREATE TABLE Orders (
Prod_ID INTEGER, ProductName VARCHAR(20), Employee_ID INTEGER );*/ public static void createOrders() { Connection con = getConnection(); String createString; createString = create table Orders ( + Prod_ID INTEGER, + ProductName VARCHAR(20), + Employee_ID INTEGER ); try { stmt = con.createStatement(); stmt.executeUpdate(createString); stmt.close(); con.close(); } catch(SQLException ex) { System.err.println(SQLException: + ex.getMessage()); } JOptionPane.showMessageDialog(null,Orders Table Created); } /*Employee_ID Name 6323 Hemanth 5768 Bob 1234 Shawn 5678 Michaels */ public static void insertEmployees() { Connection con = getConnection(); String insertString1, insertString2, insertString3, insertString4; insertString1 = insert into Employees values(6323, Hemanth); insertString2 = insert into Employees values(5768, Bob); insertString3 = insert into Employees values(1234, Shawn); insertString4 = insert into Employees values(5678, Michaels); try { stmt = con.createStatement(); stmt.executeUpdate(insertString1); stmt.executeUpdate(insertString2); stmt.executeUpdate(insertString3); stmt.executeUpdate(insertString4); stmt.close(); con.close(); } catch(SQLException ex) { System.err.println(SQLException: + ex.getMessage()); } JOptionPane.showMessageDialog(null,Data Inserted into Employees Table);
} /*
*/ public static void insertOrders() { Connection con = getConnection(); String insertString1, insertString2, insertString3, insertString4; insertString1 = insert into Orders values(543, Belt, 6323); insertString2 = insert into Orders values(432, Bottle, 234); insertString3 = insert into Orders values(876, Ring, 5678); try { stmt = con.createStatement(); stmt.executeUpdate(insertString1); stmt.executeUpdate(insertString2); stmt.executeUpdate(insertString3); stmt.close(); con.close(); } catch(SQLException ex) { System.err.println(SQLException: + ex.getMessage()); } JOptionPane.showMessageDialog(null,Data Inserted into Orders Table); } public static void retrieveEmployees(){ Connection con = getConnection(); String result = null; String selectString; selectString = select * from Employees; result =Employee_ID\t\tName\n; try { stmt = con.createStatement(); ResultSet rs = stmt.executeQuery(selectString); while (rs.next()) { int id = rs.getInt(Employee_ID); String name = rs.getString(Name); result+=id+\t\t+ name+\n; } stmt.close(); con.close(); } catch(SQLException ex) { System.err.println(SQLException: + ex.getMessage()); } JOptionPane.showMessageDialog(null, result); } public static void retrieveOrders(){ Connection con = getConnection();
String result = null; String selectString; selectString = select * from Orders; result =Prod_ID\t\tProductName\t\tEmployee_ID\n; try { stmt = con.createStatement(); ResultSet rs = stmt.executeQuery(selectString); while (rs.next()) { int pr_id = rs.getInt(Prod_ID); String prodName = rs.getString(ProductName); int id = rs.getInt(Employee_ID); result +=pr_id+\t\t+ prodName+\t\t+id+\n; } stmt.close(); con.close(); } catch(SQLException ex) { System.err.println(SQLException: + ex.getMessage()); } JOptionPane.showMessageDialog(null, result); } }//End of class
We can use java jdbc update statements in a java program to update the data for a Table. Below is a program showing the use of jdbc executeupdate (uses jdbc update query) to update a table. The return value for a jdbc sql update is an int that indicates how many rows of a table were updated. For instance in a statement like int n = stmt.executeUpdate(); For my website I am creating the following 2 tables (Employee, Orders) as a part of the JDBC update table statement. Employee_ID is the primary key which forms a relation between the 2 tables. CREATE TABLE Employees (Employee_ID INTEGER,Name VARCHAR(30) ); Employees: Employee_ID 6323 5768 1234 5678 Orders: CREATE TABLE Orders (Prod_ID INTEGER,ProductName VARCHAR(20), Employee_ID INTEGER ); Prod_ID 543 432 876 Product Name Belt Bottle Ring Employee_ID 6323 1234 5678 Name Hemanth Bob Shawn Michaels
Below is a jdbc update example import javax.swing.JOptionPane; import java.sql.*; public class JDBCProgram{ static String userid=scott, password = tiger; static String url = jdbc:odbc:bob; // String url = jdbc:mySubprotocol:myDataSource; ? static Statement stmt; static Connection con;
public static void main(String args[]){ JOptionPane.showMessageDialog (null,JDBC Programming showing Updation of Table Data); int choice = -1; do{ choice = getChoice(); if (choice != 0){ getSelected(choice); } } while ( choice != 0); System.exit(0); } public static int getChoice() { String choice; int ch; choice = JOptionPane.showInputDialog(null, 1. Create Employees Table\n+ 2. Create Products Table\n+ 3. Insert data into Employees Table\n+ 4. Insert data into Orders Table\n+ 5. Retrieve data for Employees Table\n+ 6. Retrieve data for Orders Table\n+ 7. Update Employees Table\n+ 0. Exit\n\n+ Enter your choice); ch = Integer.parseInt(choice); return ch; } public static void getSelected(int choice){ if(choice==1){ createEmployees(); } if(choice==2){ createOrders(); } if(choice==3){ insertEmployees(); } if(choice==4){ insertOrders(); } if(choice==5){
retrieveEmployees(); } if(choice==6){ retrieveOrders(); } if(choice==7){ updateEmployees(); //Uses JDBC Update Statement } } public static Connection getConnection() { try { Class.forName(sun.jdbc.odbc.JdbcOdbcDriver); //Class.forName(myDriver.ClassName); ? } catch(java.lang.ClassNotFoundException e) { System.err.print(ClassNotFoundException: ); System.err.println(e.getMessage()); } try { con = DriverManager.getConnection(url, userid, password); } catch(SQLException ex) { System.err.println(SQLException: + ex.getMessage()); } return con; } /*CREATE TABLE Employees ( Employee_ID INTEGER, Name VARCHAR(30) );*/ public static void createEmployees() { Connection con = getConnection(); String createString; createString = create table Employees ( + Employee_ID INTEGER, + Name
VARCHAR(30)); try { stmt = con.createStatement(); stmt.executeUpdate(createString); stmt.close(); con.close(); } catch(SQLException ex) { System.err.println(SQLException: + ex.getMessage()); } JOptionPane.showMessageDialog(null,Employees Table Created); } /*CREATE TABLE Orders ( Prod_ID INTEGER, ProductName VARCHAR(20), Employee_ID INTEGER );*/ public static void createOrders() { Connection con = getConnection(); String createString; createString = create table Orders ( + Prod_ID INTEGER, + ProductName VARCHAR(20), + Employee_ID INTEGER ); try { stmt = con.createStatement(); stmt.executeUpdate(createString); stmt.close(); con.close(); } catch(SQLException ex) { System.err.println(SQLException: + ex.getMessage()); } JOptionPane.showMessageDialog(null,Orders Table Created); } /*Employee_ID 6323 Name Hemanth
5768 Bob 1234 Shawn 5678 Michaels */ public static void insertEmployees() { Connection con = getConnection(); String insertString1, insertString2, insertString3, insertString4; insertString1 = insert into Employees values(6323, Hemanth); insertString2 = insert into Employees values(5768, Bob); insertString3 = insert into Employees values(1234, Shawn); insertString4 = insert into Employees values(5678, Michaels); try { stmt = con.createStatement(); stmt.executeUpdate(insertString1); stmt.executeUpdate(insertString2); stmt.executeUpdate(insertString3); stmt.executeUpdate(insertString4); stmt.close(); con.close(); } catch(SQLException ex) { System.err.println(SQLException: + ex.getMessage()); } JOptionPane.showMessageDialog(null,Data Inserted into Employees Table); } /* Prod_ID 543 432 876 ProductName Belt Bottle Ring Employee_ID 6323 1234 5678
*/ public static void insertOrders() { Connection con = getConnection(); String insertString1, insertString2, insertString3, insertString4; insertString1 = insert into Orders values(543, Belt, 6323); insertString2 = insert into Orders values(432, Bottle, 1234);
insertString3 = insert into Orders values(876, Ring, 5678); try { stmt = con.createStatement(); stmt.executeUpdate(insertString1); stmt.executeUpdate(insertString2); stmt.executeUpdate(insertString3); stmt.close(); con.close(); } catch(SQLException ex) { System.err.println(SQLException: + ex.getMessage()); } JOptionPane.showMessageDialog(null,Data Inserted into Orders Table); } public static void retrieveEmployees(){ Connection con = getConnection(); String result = null; String selectString; selectString = select * from Employees; result =Employee_ID\t\tName\n; try { stmt = con.createStatement(); ResultSet rs = stmt.executeQuery(selectString); while (rs.next()) { int id = rs.getInt(Employee_ID); String name = rs.getString(Name); result+=id+\t\t+ name+\n; } stmt.close(); con.close(); } catch(SQLException ex) { System.err.println(SQLException: + ex.getMessage()); } JOptionPane.showMessageDialog(null, result); } public static void retrieveOrders(){ Connection con = getConnection(); String result = null; String selectString; selectString = select * from Orders; result
=Prod_ID\t\tProductName\t\tEmployee_ID\n; try { stmt = con.createStatement(); ResultSet rs = stmt.executeQuery(selectString); while (rs.next()) { int pr_id = rs.getInt(Prod_ID); String prodName = rs.getString(ProductName); int id = rs.getInt(Employee_ID); result +=pr_id+\t\t+ prodName+\t\t+id+\n; } stmt.close(); con.close(); } catch(SQLException ex) { System.err.println(SQLException: + ex.getMessage()); } JOptionPane.showMessageDialog(null, result); } public static void updateEmployees(){ Connection con = getConnection(); String updateString1; updateString1 = update Employees set name = hemanthbalaji where Employee_id = 6323; try { stmt = con.createStatement(); stmt.executeUpdate(updateString1); stmt.close(); con.close(); } catch(SQLException ex) { System.err.println(SQLException: + ex.getMessage()); } JOptionPane.showMessageDialog(null,Data Updated into Employees Table); } }//End of class
PreparedStatement pstmt = con.prepareStatement(update Orders set pname = ? where Prod_Id = ?); pstmt.setInt(2, 100); pstmt.setString(1, Bob); pstmt.executeUpdate(); An important feature of a PreparedStatement object is that, unlike a Statement object, it is given an SQL statement when it is created. This SQL statement is sent to the DBMS right away, where it is compiled. As a result, the PreparedStatement object contains not just an SQL statement, but an SQL statement that has been precompiled. This means that when the PreparedStatement is executed, the DBMS can just run the PreparedStatement SQL statement without having to compile it first. Using Prepared Statements in jdbc, objects can be used for SQL statements with no parameters, you probably use them most often for SQL statements that take parameters. The advantage of using SQL statements that take parameters is that you can use the same statement and supply it with different values each time you execute it. For my website I am creating the following 2 tables (Employee, Orders) as a part of the JDBC tutorial. Employee_ID is the primary key which forms a relation between the 2 tables
CREATE TABLE Employees (Employee_ID INTEGER,Name VARCHAR(30) );
Employees:
Employee_ID 6323 5768 1234 5678 Name Hemanth Bob Shawn Michaels
JOptionPane.showMessageDial og(null,JDBC Programming showing Updation of Table Data); int choice = -1; do{ choice = getChoice(); if (choice != 0){ getSelected(choice); } }
while ( choice != 0); System.exit(0); } public static int getChoice() { String choice; int ch; choice = JOptionPane.showInputDialog(null, 1. Create Employees Table\n+ 2. Create Products Table\n+ 3. Insert data into Employees Table\n+ 4. Insert data into Orders Table\n+ 5. Retrieve data for Employees Table\n+ 6. Retrieve data for Orders Table\n+ 7. Update Employees Table\n+ 8. Update Employees Table Using a Prepared Statement\n+ 9. Update many records of Orders Table Using a Prepared Statement\n+ 10. List the name of employees who bought CDsn+ 0. Exit\n\n+ Enter your choice); ch = Integer.parseInt(choice); return ch; } public static void getSelected(int choice){ if(choice==1){ createEmployees(); } if(choice==2){ createOrders(); } if(choice==3){ insertEmployees(); } if(choice==4){ insertOrders(); } if(choice==5){ retrieveEmployees(); } if(choice==6){ retrieveOrders(); } if(choice==7){ updateEmployees(); } if(choice==8){
updateEmployeesPrepared(); } if(choice==9){ updateOrdersPrepared(); } if(choice==10){ dynamicQuery(); } } public static Connection getConnection() { try { Class.forName(sun.jdbc.odbc.JdbcOdbcDriver); //Class.forName(myDriver.ClassName); ? } catch(java.lang.ClassNotFoundException e) { System.err.print(ClassNotFoundException: ); System.err.println(e.getMessage()); } try { con = DriverManager.getConnection(url, userid, password); } catch(SQLException ex) { System.err.println(SQLException: + ex.getMessage()); } return con; } /*CREATE TABLE Employees ( Employee_ID INTEGER, Name VARCHAR(30) );*/ public static void createEmployees() { Connection con = getConnection(); String createString; createString = create table Employees ( + Employee_ID INTEGER, + Name VARCHAR(30)); try { stmt = con.createStatement(); stmt.executeUpdate(createString);
stmt.close(); con.close(); } catch(SQLException ex) { System.err.println(SQLException: + ex.getMessage()); } JOptionPane.showMessageDialog(null,Employees Table Created); } /*CREATE TABLE Orders ( Prod_ID INTEGER, ProductName VARCHAR(20), Employee_ID INTEGER );*/ public static void createOrders() { Connection con = getConnection(); String createString; createString = create table Orders ( + Prod_ID INTEGER, + ProductName VARCHAR(20), + Employee_ID INTEGER ); try { stmt = con.createStatement(); stmt.executeUpdate(createString); stmt.close(); con.close(); } catch(SQLException ex) { System.err.println(SQLException: + ex.getMessage()); } JOptionPane.showMessageDialog(null,Orders Table Created); } /*Employee_ID Name 6323 Hemanth 5768 Bob 1234 Shawn 5678 Michaels */ public static void insertEmployees() { Connection con = getConnection();
String insertString1, insertString2, insertString3, insertString4; insertString1 = insert into Employees values(6323, Hemanth); insertString2 = insert into Employees values(5768, Bob); insertString3 = insert into Employees values(1234, Shawn); insertString4 = insert into Employees values(5678, Michaels); try { stmt = con.createStatement(); stmt.executeUpdate(insertString1); stmt.executeUpdate(insertString2); stmt.executeUpdate(insertString3); stmt.executeUpdate(insertString4); stmt.close(); con.close(); } catch(SQLException ex) { System.err.println(SQLException: + ex.getMessage()); } JOptionPane.showMessageDialog(null,Data Inserted into Employees Table); } /* Prod_ID 543 432 876 ProductName Belt Bottle Ring Employee_ID 6323 1234 5678
*/ public static void insertOrders() { Connection con = getConnection(); String insertString1, insertString2, insertString3, insertString4; insertString1 = insert into Orders values(543, Belt, 6323); insertString2 = insert into Orders values(432, Bottle, 1234); insertString3 = insert into Orders values(876, Ring, 5678); try { stmt = con.createStatement(); stmt.executeUpdate(insertString1);
stmt.executeUpdate(insertString2); stmt.executeUpdate(insertString3); stmt.close(); con.close(); } catch(SQLException ex) { System.err.println(SQLException: + ex.getMessage()); } JOptionPane.showMessageDialog(null,Data Inserted into Orders Table); } public static void retrieveEmployees(){ Connection con = getConnection(); String result = null; String selectString; selectString = select * from Employees; result =Employee_ID\t\tName\n; try { stmt = con.createStatement(); ResultSet rs = stmt.executeQuery(selectString); while (rs.next()) { int id = rs.getInt(Employee_ID); String name = rs.getString(Name); result+=id+\t\t+ name+\n; } stmt.close(); con.close(); } catch(SQLException ex) { System.err.println(SQLException: + ex.getMessage()); } JOptionPane.showMessageDialog(null, result); } public static void retrieveOrders(){ Connection con = getConnection(); String result = null; String selectString; selectString = select * from Orders; result =Prod_ID\t\tProductName\t\tEmployee_ID\n; try { stmt = con.createStatement(); ResultSet rs = stmt.executeQuery(selectString); while (rs.next()) {
int pr_id = rs.getInt(Prod_ID); String prodName = rs.getString(ProductName); int id = rs.getInt(Employee_ID); result +=pr_id+\t\t+ prodName+\t\t+id+\n; } stmt.close(); con.close(); } catch(SQLException ex) { System.err.println(SQLException: + ex.getMessage()); } JOptionPane.showMessageDialog(null, result); } public static void updateEmployees(){ Connection con = getConnection(); String updateString1; updateString1 = update Employees set name = hemanthbalaji where Employee_id = 6323; try { stmt = con.createStatement(); stmt.executeUpdate(updateString1); stmt.close(); con.close(); } catch(SQLException ex) { System.err.println(SQLException: + ex.getMessage()); } JOptionPane.showMessageDialog(null,Data Updated into Employees Table); } public static void updateEmployeesPrepared(){ Connection con = getConnection(); // create prepared statement try { pstmt = con.prepareStatement (update Employees set name = ? where Employee_Id = ?); pstmt.setString(1, hemanthbob); //Note index starts with 1 pstmt.setInt(2, 6323); pstmt.executeUpdate();
pstmt.close(); con.close(); } catch(SQLException ex) { System.err.println(SQLException: + ex.getMessage()); } JOptionPane.showMessageDialog(null,Data Updated into Employees Table); } public static void updateOrdersPrepared(){ int [] productIds = {543, 432, 876}; String [] productNames = {cds, dvds, Espresso}; int len = productNames.length; Connection con = getConnection(); try { pstmt = con.prepareStatement (update Orders set productname = ? where Prod_Id = ?); for(int i = 0; i < len; i++) { pstmt.setInt(2, productIds[i]); pstmt.setString(1, productNames[i]); pstmt.executeUpdate(); } pstmt.close(); con.close(); } catch(SQLException ex) { System.err.println(SQLException: + ex.getMessage()); } JOptionPane.showMessageDialog(null,Data Updated into Orders Table); } public static void dynamicQuery(){ Connection con = getConnection(); String result = null; String selectString; selectString = select Employees.name from Employees, Orders where productname = cds + and Employees.employee_id = Orders.employee_id ; result =Name\n; try {
stmt = con.createStatement(); ResultSet rs = stmt.executeQuery(selectString); while (rs.next()) { String name = rs.getString(Name); result+=name+\n; } stmt.close(); con.close(); } catch(SQLException ex) { System.err.println(SQLException: + ex.getMessage()); } JOptionPane.showMessageDialog(null, result); } }//End of class