1 JAVA FOR BEGINNERS

Introduction to Java Programming
Introduction to Computer Science using Java
Java is a simple and yet powerful object oriented programming language and it is in many respects similar to C++. Java originated at Sun Microsystems, Inc. in 1991. It was conceived by James Gosling, Patrick Naughton, Chris Warth, Ed Frank, and Mike Sheridan at Sun Microsystems, Inc. It was developed to provide a platform-independent programming language.

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.

Java Virtual Machine
What is the Java Virtual Machine? What is its role? Java was designed with a concept of ‘write once and run everywhere’. Java Virtual Machine plays the central role in this concept. The JVM is the environment in which Java programs execute. It is a software that is implemented on top of real hardware and operating system. When the source code (.java files) is compiled, it is translated into byte codes and then placed into (.class) files. The JVM executes these bytecodes. So Java byte codes can be thought of as the machine language of the JVM. A JVM can either interpret the bytecode one instruction at a time or the bytecode can be compiled further for the real microprocessor using what is called a just-in-time compiler. The JVM must be implemented on a particular platform before compiled programs can run on that platform.

Object Oriented Programming
Since Java is an object oriented programming language it has following features:
• • • • •

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

2 JAVA FOR BEGINNERS

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.

3 JAVA FOR BEGINNERS

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.

class names. keywords. or method names. struct and union are all words related to the C programming language. Keywords in java are case sensitive. . The word finalize is the name of a method of the Object class and hence not a keyword. Once you get these basic language concepts you can continue with the other object oriented programming language concepts. all characters being lower case. //Prints output to console } } For more information on different Keywords . All the keywords are in lowercase. literals. 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.4 JAVA FOR BEGINNERS Basic Language Elements (Identifiers.out. Keywords are reserved words that are predefined in the language. white spaces and comments) This part of the java tutorial teaches you the basic language elements and syntax for the java programming language. ifdef. friend. typedef.Java Keywords Some Tricky Observations: The words virtual. see the table below (Taken from Sun Java Site). const and goto are Java keywords. Keywords There are certain words with a specific meaning in java which tell (help) the compiler what the program is supposed to do.println(”Hello World”). enum and label are not keywords. These Keywords cannot be used as variable names.

The data type indicates the attributes of the variable. An Identifier must be unique within a scope of the Java program. Java supports three comment styles. a type.  Integer: byte. short. and a scope.out. and long. int. The programmer assigns the names to variables.println("a : "+a).  Floating Point: float and double . Variables have a data type.out. They are not automatically initialized. public class localVariableEx { public static int a. (Shown in the above program) name of this compiled file is comprised of the name of the class with . known as identifiers. such as javadoc. The compiler will generate an error as a result of the attempt to access the local variables before a value has been assigned. We can also create our own data types. Java has four main primitive data types built into the language. All variables have a name. The compiler ignores comments and hence its only for documentation of the program.5 JAVA FOR BEGINNERS Comments Comments are descriptions that are added to a program to make code easier to understand. You can also create your own composite data types. System. such as the range of values that can be stored and the operators that can be used to manipulate the variable. Variable. public static void main(String[] args) { int b. (Shown in the above program) Documentation style comments begin with /** and terminate with */ that spans multiple lines. Identifiers and Data Types Variables are used for data that change during program execution. Block style comments begin with /* and terminate with */ that spans multiple lines. //Compilation error }} Note in the above example. Line style comments begin with // and terminate at the end of the line. Variables declared inside of a block or method are called local variables. Java has four main primitive data types built into the language.class as an extension. that indicates the kind of value they can store. They are generally created using the automatic documentation generation tool. a compilation error results in where the variable is tried to be accessed and not at the place where its declared without any value.println("b : "+b). System.

Identifier Naming Rules • • • • • • Can consist of upper and lower case letters. The size for each Java type can be obtained by a simple Google search. each user defined item must have a unique identifier Can be of any length. digits. Must begin with a letter. dollar sign ($) and the underscore ( _ ) character. I have not mentioned it in the below table. For Example String message = “hello world” In the above statement. .6 JAVA FOR BEGINNERS  Character: char  Boolean: variable with a value of true or false. or an underscore Are case sensitive Keywords cannot be used as identifiers Within a given section of your program or scope.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. Data Type Byte Short Int Long Float Double Char String (object) Boolean Default Value (for fields) 0 0 0 0L 0.0f 0. The following chart (Taken from Sun Java Site) summarizes the default values for the java built in data types. If you don’t specify a value when the variable is declared. Since I thought Mentioning the size was not important as part of learning Java. dollar sign. String is the data type for the identifier message. it will be assigned the default value for its data type.

An object reference provides a handle to an object that is created and stored in memory. Instance variables and instance methods. Static variables and static methods are collectively known as static members. Objects An object is an instance of a class created using a new operator. it promises to implement all of the methods declared in that interface. The new operator returns a reference to a new instance of a class. Methods are nothing but members of a class that provide a service for an object or perform some business logic.7 JAVA FOR BEGINNERS Classes A class is nothing but a blueprint for creating different objects which defines its properties and behaviors. and are declared with a keyword static. The process of creating objects from a class is called instantiation. Below is a program showing the various parts of the basic language syntax that were discussed above. A class can contain fields and methods to describe the behavior of an object. which belong to objects. Static Members Static members are those that belong to a class as a whole and not to a particular instance (object). In Java. a class can have static methods. objects can only be manipulated via references. Interface An Interface is a contract in the form of collection of method and constant declarations. This reference can be assigned to a reference variable of the class. are collectively called instance members. */ public class HelloWorld { String output = "". An object exhibits the properties and behaviors defined by its class. //Line 1 . The dot ‘. which can be stored in variables. The methods of an object define its behaviour called instance methods. When a class implements an interface. but instance members can only be accessed via object references. Similarly.’ notation with a object reference is used to access Instance Members. static HelloWorld helloObj. Static members in the class can be accessed either by using the class name or by using the object reference. Instance Members Each object created will have its own copies of the fields defined in its class called instance variables which represent an object’s state. A static variable is initialized when the class is loaded. /** Comment * Displays "Hello World!" to the standard output.

printMessage()). } public static void main (String args[]) { helloObj = new HelloWorld().println(helloObj.8 JAVA FOR BEGINNERS public HelloWorld(){ output = "Hello World". } public String printMessage(){ return output. } } 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 .out. //Line 2 System.

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 (=). compound assignment. // Assigning References Integer i1 = new Integer("1").out. . System. k. Previous value is overwritten. relational. two. Assignment Operators Arithmetic Operators Relational Operators Logical Operators Bit wise Operator Compound Assignment Operators Conditional Operator ?: = + * / % > < >= <= && || & & | ^ += -= *= /= ++ -== != | ! ^ >> >>> %= <<= >>= >>>= Java has eight different operator types: assignment.out.out. relational. Java operators can be classified as unary. logical. or ternary—meaning taking one. A binary or ternary operator appears between its arguments. respectively. j = 5. A unary operator may appear before (prefix) its argument or after (postfix) its argument. // k gets the value 5. public class AssignmentOperatorsDemo { public AssignmentOperatorsDemo() { // Assigning Primitive Values int j. System.println("k is : " + k). conditional. bitwise. // j gets the value 5.println("i1 is : " + i1). and type. or three arguments. and type. binary. arithmetic. compound assignment.println("j is : " + j). j = 10. conditional. Integer i2 = new Integer("2"). System.out. Operators in java fall into 8 different categories: Java operators fall into eight different categories: assignment. bitwise. k = j.9 JAVA FOR BEGINNERS Java Operators They are used to manipulate primitive data types. // j gets the value 10. logical. arithmetic.println("i2 is : " + i2). System.

println("i1 is : " + i1). } } Arithmetic operators Java provides eight Arithmetic operators.0). System. increment (or add 1).out.MAX_VALUE + 1.out. z = 5.MAX_VALUE.MIN_VALUE .z.out.operator resulted in " + x). y = 10.out.out.println(-4.println(4. String message = 100 + “Messages”. subtraction. When one of the operands is a String object.0 / 0. //”100 Messages” public class ArithmeticOperatorsDemo { public ArithmeticOperatorsDemo() { int x. System. } public static void main(String args[]) { new AssignmentOperatorsDemo().0). x = y % z. // (k = (j = 10)) System. int tooSmall = Integer.MIN_VALUE.out.println("Unary operator resulted in " + x). x = -y. System.10 JAVA FOR BEGINNERS i1 = i2. // 2147483647 which is // Integer. System.0 / 0.println("tooBig becomes " + tooBig). System. the other operand is implicitly converted to its string representation and string concatenation is performed. System. An example program is shown below that demonstrates the different arithmetic operators in java. division. // Prints: Infinity System. // Multiple Assignments k = j = 10. multiplication. System.out. System. x = y .out. System. x = ++z.println("+ operator resulted in " + x).println("k is : " + k).println(". System. The binary operator + is overloaded in the sense that the operation performed is determined by the type of the operands.println("Prefix ++ operator resulted in " + x). They are for addition. modulo (or remainder).println("Postfix ++ operator resulted in " + x).out.out. x = y + z. // Prints: -Infinity . // -2147483648 which is // Integer.out.println("% operator resulted in " + x). and negation. System. System. x = y * z. System. x = y++.println("j is : " + j).println("i2 is : " + i2).1.println("* operator resulted in " + x).out.out. // Some examples of special Cases int tooBig = Integer. System. decrement (or subtract 1).println("tooSmall becomes " + tooSmall).out.out. x = y / z.println("/ operator resulted in " + x).out.

// result: 1 by integer division.out. } public static void main(String args[]) { new ArithmeticOperatorsDemo().out.11 JAVA FOR BEGINNERS System. conditional AND. Each argument to a logical operator must be a boolean data type. OR.out.println("x != y : "+(x != y)). System.println("x == y : "+(x == y)).out. } } Logical operators Logical operators return a true or false value based on the state of the Variables. An example program is shown below that demonstrates the different relational operators in java. They are AND.0F / 8. and NOT. System. d1 gets the value // 1. and their operands are numeric expressions.5 System. // Prints: NaN double d1 = 12 / 8.println("x < y : "+(x < y)). Java provides six relational operators: greater than (>).println("x <= y : "+(x <= y)). public class RelationalOperatorsDemo { public RelationalOperatorsDemo( ) { int x = 10. System.println(0.out. operators.println("d1 is " + d1).0. Relational operators have precedence lower than arithmetic operators.out. double d2 = 12.out. } public static void main(String args[]){ new RelationalOperatorsDemo(). equal (==). There are six logical. System. The evaluation results in a boolean value. Binary numeric promotion is applied to the operands of these operators. } } Relational operators Relational operators in Java are used to compare 2 or more objects. // result: 1. and not equal (!=).0 / 0. and the result .out. System. All relational operators are binary operators. but higher than that of the assignment operators. conditional OR. less than or equal (<=). less than (<). System. greater than or equal (>=). y = 5. exclusive OR. System.println("x >= y : "+(x >= y)).println("x > y : "+(x > y)). or boolean.println("d2 iss " + d2).0).out.

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.out. Exclusive-OR. public class LogicalOperatorsDemo { public LogicalOperatorsDemo() { boolean x = true.12 JAVA FOR BEGINNERS is always a boolean data type.println("x && y : " + (x && y)). System.out. the boolean logical operators are defined in the Table below. int.out.out.println("x ^ y : " + (x ^ y)). } public static void main(String args[]) { new LogicalOperatorsDemo(). Java provides seven bitwise operators. boolean y = false.out. These variables must be of numeric data type ( char. System. System.println("!x : " + (!x)). and Unsigned Right-shift. or long). //1 1 1 1 1 0 0 0 1 1 1 0 1 0 0 1 . Signed Right-shift. Complement. } } Given that x and y represent boolean expressions.println("x & y : " + (x & y)).println("x | y : " + (x | y)). short. System. System. They are AND. //1 1 1 1 1 0 1 0 1 1 1 0 1 1 1 1 int y = 0xF8E9. An example program is shown below that demonstrates the different Bit wise operators in java. public class BitwiseOperatorsDemo { public BitwiseOperatorsDemo() { int x = 0xFAEF. System. Left-shift. An example program is shown below that demonstrates the different Logical operators in java. OR.out.println("x || y: " + (x || y)).

& */ public class BitwisePrecedenceEx { public static void main(String[] args) { int a = 1 | 2 ^ 3 & 5.out. System.out.3 /* * The below program demonstrates bitwise operators keeping in mind operator precedence * Operator Precedence starting with the highest is -> |.println("~x : " + (~x)). 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.println("x ^ y : " + (x ^ y)). } } . System.out. System. System.0." + b + ". //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.println("x >> y : " + (x >> y)). int c = 1 | (2 ^ (3 & 5)).print(a + ".println("x & y : " + (x & y)). ^.13 JAVA FOR BEGINNERS int z. System.out. System.println("x | y : " + (x | y)). int b = ((1 | 2) ^ 3) & 5." + c).out.out.println("x >>> y : " + (x >>> y)).out.out. System. System.println("x << y : " + (x << y)).

out. Other compound assignment operators include boolean logical . Syntax: argument1 operator = argument2.out. } public static void main(String args[]) { new TernaryOperatorsDemo().14 JAVA FOR BEGINNERS Compound operators The compound operators perform shortcuts in common programming operations. public class CompoundOperatorsDemo { public CompoundOperatorsDemo() { int x = 0. An example program is shown below that demonstrates the different Compound operators in java. bitwiseand shift operators*/ } public static void main(String args[]) { new CompoundOperatorsDemo(). /*Similarly other operators can be applied as shortcuts. evaluates the second argument. y = 5. y = 12. } } Conditional operators The Conditional operator is the only ternary (operator takes three arguments) operator in Java.println("z : " + z).println("y : " + y). z = 0. z = x > y ? x : y. if true. System. If the first argument evaluates to false.out. The conditional operator is the expression equivalent of the if-else statement. Java has eleven compound assignment operators. x += 3. 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. The above statement is the same as. The operator evaluates the first argument and. then the third argument is evaluated. System. } } /* * The following programs shows that when no explicit parenthesis is used then the conditional operator .println("x : " + x). public class TernaryOperatorsDemo { public TernaryOperatorsDemo() { int x = 10. argument1 = argument1 operator argument2. System. y *= x.

You can use parentheses to override the default precedence. from left to right. postfix unary creation/caste multiplicative additive [] . they are applied in the order they appear in a statement. } } Output FFT Type conversion allows a value to be changed from one primitive data type to another. Operators at the top of the table are applied before operators lower down in the table. Operators with a higher precedence are applied before operators with a lower precedence. System. () expr++ expr– ++expr –expr +expr -expr ! ~ new (type)expr */% +- . The operator precedence order of Java is shown below. That is.15 JAVA FOR BEGINNERS * evaluation is from right to left */ public class BooleanEx1 { static String m1(boolean b) { return b ? "T" : "F". Java allows both type widening and type narrowing conversions. If two operators have the same precedence. by Java itself. boolean t3 = ((false ? false : true) ? false : true) ? false : true. or implicitly. boolean t2 = false ? false : (true ? false : (true ? false : true)). Conversion can occur explicitly. } public static void main(String[] args) { boolean t1 = false ? false : true ? false : true ? false : true.println(m1(t1) + m1(t2) + m1(t3)).out. as specified in the program. 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.

· Transfer statements: break. result = 4 + 5 * 3 First (5 * 3) is evaluated and the result is added to 4 giving the Final Result value as 19. return. Note that ‘*’ takes higher precedence than ‘+’ according to chart shown above. Java Control Flow Statements Java Control statements control the order of execution in a java program. based on data values and conditional logic. · Loop statements: while. This kind of precedence of one operator over another applies to all the operators. try-catch-finally and assert. · Selection statements: if. continue. We use control statements when we want to change the default sequential order of execution Selection Statements The If Statement .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. if-else and switch. do-while and for. There are three main categories of control flow statements.

out. Note that the conditional expression must be a Boolean expression.out.println("b > a"). then the if block is skipped and execution continues with the rest of the program. 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. . if (a > b) { System. You can either have a single statement or a block of code within an if statement. 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. if (a < b) System.println("a > b"). b = 20. public class IfStatementDemo { public static void main(String[] args) { <font size=-1> int a = 10.out. Note that the conditional expression must be a Boolean expression. If the statements in the if statement fails.out. You can either have a single statement or a block of code within if-else blocks. } else { System. if (a > b) System. If the value is false.println("b > a"). } } Output b>a The If-else Statement The if/else statement is an extension of the if statement.17 JAVA FOR BEGINNERS The if statement executes a block of code only if the specified expression is true. b = 20.println("a > b"). the statements in the else block are executed. public class IfElseStatementDemo { public static void main(String[] args) { int a = 10.

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. int status = -1. } else if (b > c) { status = 2. A switch is easier to implement than a series of if/else statements. c = 30. if (a > b && a > c) { status = 1. If none of the case label values match. Java includes a default label to use in cases where there are no matches. which causes the program to continue executing after the current code block. followed by an expression that equates to a no long integral value. public class SwitchCaseStatementDemo { public static void main(String[] args) { int a = 10. the program falls through to the next case. Below is a java example that demonstrates conditional execution based on nested if else statement condition to find the greatest of 3 numbers. Its general form is as follows: switch (<non-long integral expression>) { case label1: <statement1> case label2: <statement2> … case labeln: <statementn> default: <statement> } // end switch When executing a switch statement.18 JAVA FOR BEGINNERS } } } Output b>a Switch Case Statement The switch case statement. } switch (status) { . } else { status = 3. also called a case statement is a multi-way branch with several choices. if you want to exit in the middle of the switch statement code block. you must insert a break statement. b = 20. When the switch statement executes. Following the controlling expression is a code block that contains zero or more labeled cases. it compares the value of the controlling expression to the values of each case label. Therefore. The switch statement begins with a keyword. Each label must equate to an integer constant and each must be unique. We can have a nested switch within a case block of an outer switch. then none of the codes within the switch statement code block will be executed.

19 JAVA FOR BEGINNERS case 1: System. constructors. Java provides a number of access modifiers to help you set the level of access you want for classes as well as the fields. break.out. break. To take advantage of encapsulation.out. a class can control what information or data can be accessible by other classes.println("b is the greatest"). case 2: System.println("c is the greatest").println("a is the greatest"). break.out. case 3: System.e. Access Modifiers . A member has package or default accessibility when no accessibility modifier is specified. default: System. } } } Output c is the greatest Introduction to Java Access Modifiers Java Access Specifiers The access to classes. methods and constructors in your classes.out.println("Cannot be determined"). you should minimize access whenever possible. methods and fields are regulated using access modifiers i.

methods and constructors as well. whether these classes are in the same package or in another package. package pckage1.20 JAVA FOR BEGINNERS 1. protected and default access modifiers while accessing fields and methods. method or constructor that has no declared access modifier is accessible only by classes in the same package. even if they are not a subclass of the protected member’s class. field. //Implicit Default Access Modifier . public public access modifier Fields. Fields. methods or constructors declared private are strictly controlled. methods and constructors declared protected in a superclass can be accessed only by subclasses in other packages.java which is present in pckage1 package. A standard design strategy is to make all fields private and provide public getter methods for them. Classes in the same package can also access protected fields. methods and constructors declared public (least restrictive) within a public class are visible to any class in the Java program. Any class. int a = 10. protected access modifier The protected fields or methods cannot be used for classes and Interfaces. The first class is SubclassInSamePackage. It also cannot be used for fields and methods within an interface. class BaseClass { public int x = 10. default 4. private. This java file contains the Base class and a subclass within the enclosing class that belongs to the same class as shown below. private access modifier The private (most restrictive) fields or methods cannot be used for classes and Interfaces. Below is a program to demonstrate the use of public. It also cannot be used for fields and methods within an interface. The output of each of these java files depict the Java access specifiers. Fields. protected int z = 10. protected 3. private 2. private int y = 10. which means they cannot be accesses by anywhere outside the enclosing class. default access modifier Java provides a default specifier which is used when no access modifier is present. The default modifier is not used for fields and methods within an interface.

subClassObj. } private void setY(int y) { this.println("Value of z is : " + subClassObj. subClassObj.*/ //Access Modifiers .out. //Access Modifiers . System. subClassObj. } } public class SubclassInSamePackage extends BaseClass { public static void main(String args[]) { BaseClass rr = new BaseClass(). SubclassInSamePackage subClassObj = new SubclassInSamePackage().a = a.Default System. } protected int getZ() { return z. } private int getY() { return y.21 JAVA FOR BEGINNERS public int getX() { return x.z = 0.println("Value of x is : " + subClassObj.out. System. //Access Modifiers .z).setZ(30).Protected System.x).out. } protected void setZ(int z) { this.println("Value of z is : " + subClassObj. .Public System.Public // If we remove the comments it would result in a compilaton // error as the fields and methods being accessed are private /* System.out.x).println("Value of x is : " + subClassObj. //Access Modifiers .out.a).y). rr.setX(20).out. System.println("Value of y is : "+subClassObj.y = y. } public void setX(int x) { this.z = z.z).setY(20).out.println("Value of y is : "+subClassObj.println("Value of x is : " + subClassObj. } int getA() { return a.x = x.y). } void setA(int a) { this.

println("Value of x is : " + subClassObj.setX(30).println("Value of y is : "+subClassObj. //Access specifiers .Public System.out. System.println("Value of x is : " + subClassObj.java).out.getZZZ()).z). import pckage1. /* System. } } 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.a).out.a). public class SubClassInDifferentPackage extends SubclassInSamePackage { public int getZZZ() { return z.22 JAVA FOR BEGINNERS subClassObj.println("Value of a is : "+subClassObj.println("Value of x is : " + subClassObj.y).Protected // If we remove the comments it would result in a compilaton // error as the fields and methods being accessed are protected.out.x).println("Value of y is : "+subClassObj.Default // If we remove the comments it would result in a compilaton // error as the fields and methods being accessed are default.y). This java class extends First class (SubclassInSamePackage.out.Private // if we remove the comments it would result in a compilaton // error as the fields and methods being accessed are private /* System.out.out. /* System. } public static void main(String args[]) { SubClassInDifferentPackage subClassDiffObj = new SubClassInDifferentPackage(). //Access Modifiers . //Access specifiers . subClassObj.setA(20).z).out.*/ //Access specifiers . System. System.println("Value of z is : "+subClassObj.x). subClassObj.*. SubclassInSamePackage subClassObj = new SubclassInSamePackage().println("Value of z is : "+subClassObj. .out.setZ(30). System.setY(20).println("Value of z is : " + subClassDiffObj. subClassObj.java which is present in a different package then the first one.*/ System.

out.23 JAVA FOR BEGINNERS subClassObj.*.Default // If we remove the comments it would result in a compilaton // error as the fields and methods being accessed are default.out. System. System.x).a). /* System.java which is present in a different package then the first one.println("Value of y is : "+subClassObj.out. public class ClassInDifferentPackage { public static void main(String args[]) { SubclassInSamePackage subClassObj = new SubclassInSamePackage().z).println("Value of y is : "+subClassObj.println("Value of z is : "+subClassObj.println("Value of x is : " + subClassObj.println("Value of a is : "+subClassObj.*/ //Access Modifiers .println("Value of a is : "+subClassObj.setY(20).Private // If we remove the comments it would result in a compilaton // error as the fields and methods being accessed are private /* System.y).a).*/ } } Output Value of x is : 10 Value of x is : 30 .println("Value of x is : " + subClassObj. subClassObj.x).y). System.Public System.setZ(30).setA(20).*/ } } Output Value of x is : 10 Value of x is : 30 Value of z is : 10 The third class is ClassInDifferentPackage. subClassObj.println("Value of z is : "+subClassObj. System. subClassObj. //Access Modifiers .out.Protected // If we remove the comments it would result in a compilaton // error as the fields and methods being accessed are protected.a). subClassObj.setX(30).out.out.z). import pckage1.out. /* System. //Access Modifiers .out.*/ //Access Modifiers . System.out.println("Value of a is : "+subClassObj.setA(20).

Methods are nothing but members of a class that provide a service for an object or perform some business logic. A class has the following general syntax: . A class can contain fields and methods to describe the behavior of an object. Methods define the operations that can be performed in java programming. Java fields and member functions names are case sensitive. Java class objects exhibit the properties and behaviors defined by its class.24 JAVA FOR BEGINNERS Java Classes and Objects Introduction to Java Classes A class is nothing but a blueprint or a template for creating different objects which defines its properties and behaviors. Current states of a class’s corresponding object are stored in the object’s instance variables.

int breadth. like this: objectName. public int getVolume() { return (length * breadth * height).height = 4.getvolume() Class Variables – Static Fields We use class variables also know as Static fields when we want to share characteristics across all objects within a class. When you declare a field to be static. arg3).25 JAVA FOR BEGINNERS <class modifiers>class<class name> <extends clause> <implements clause>{ // Dealing with Classes (Class body) <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. . arg2. followed by the name of the method and its argument list. and not necessarily using a reference to an individual object within the class. You call a method for an object by naming the object followed by a period (dot).member ). For example: cubeObject.methodName(arg1. It is declared using static keyword. } } How do you reference a data member/function? This is accomplished by stating the name of the object reference. Static variables can be accessed even though no objects of that class exist. followed by a period (dot). int height.length = 4. only a single instance of the associated variable is created common to all the objects of that class. it affects all objects of the class. ( objectReference. cubeObject. followed by the name of the member inside the object. public class Cube { int length. breadth and height.breadth = 4. We can access a class variable by using the name of the class. cubeObject. Also the class contains a member function getVolume(). Hence when one object changes the value of a class variable. cubeObject.

methods in the java. Each class would have its own copy of the variable. Variables defined in an interface are implicitly final.out. similar to Class variables can be invoked without having an instance of the class.out.getNoOfCubes()).. A final class can’t be extended i.26 JAVA FOR BEGINNERS Class Methods – Static Methods Class methods. } public Cube() { numOfCubes++.numOfCubes). // } } public class CubeStaticTest { public static void main(String args[]) { System.Math package are class methods. You cannot call non-static methods from inside a static method. methods and classes as final. // static variable public static int getNoOfCubes() { //static method return numOfCubes. these items cannot be changed. System. For example. You can’t change value of a final variable (is a constant). int breadth = 10. When an object responds to a message. This is . Once marked as final.e. } } Output Number of Cube objects = 0 Number of Cube objects = 0 Final Variable. Methods and Classes In Java we can mark fields. Every object has a state that is determined by the values stored in the object. Instance Variables Instance variables stores the state of the object. 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. final class may not be subclassed. An object is said to have changed its state when one or more data values stored in the object have been modified. Class methods are often used to provide global functions for Java programs.lang. it will usually perform an action. public static int numOfCubes = 0. int height = 10. change its state etc.println("Number of Cube objects = " + Cube. An object that has the ability to store values is often said to have persistence.println("Number of Cube objects = " + Cube.

Any attempt to override or hide a final method will result in a compiler error. Some of the object class methods are equals toString() wait() notify() notifyAll() hashcode() clone() An object is an instance of a class created using a new operator. // Creates an Object of Cube . In Java. } public static void main(String[] args) { Cube cubeObj. you must also allocate memory for the object by using the new operator. public int getVolume() { return (length * breadth * height). This reference can be assigned to a reference variable of the class. Each time you create an object. If you want to create an object of the class and have the reference variable associated with this object. Below is an example showing the creation of Cube objects by using the new operator. The new operator returns the location of the object which you assign o a reference type. This process is called instantiating an object or creating an object instance. you use the new operator to instantiate the object. int height = 10. An object reference provides a handle to an object that is created and stored in memory. It also allows the compiler to make some optimizations. such as integer or float. objects can only be manipulated via references. Introduction to Java Objects The Object Class is the super class for all classes in Java. public class Cube { int length = 10. a new set of instance variables comes into existence which defines the characteristics of that object. When you create a new object. A final method can’t be overridden when its class is inherited. The new operator returns a reference to a new instance of a class. An object encapsulates state and behavior.27 JAVA FOR BEGINNERS done for security reasons with basic classes like String and Integer. Creating variables of your class type is similar to creating variables of primitive data types. // Creates a Cube Reference cubeObj = new Cube(). which can be stored in variables. and makes thread safety a little easier to achieve. The process of creating objects from a class is called instantiation. int breadth = 10.

println(). intResult = moDemo. When no method matching the input parameters is found.out. moDemo. System. } } .1. moDemo.println("Volume of Cube is : " + cubeObj. " + b).out. } int sumOfParams(int a.28 JAVA FOR BEGINNERS System. double b) { // Fourth Version System. and will be a compile-time error. System.2).println(). System. System. A match may then be found without error. the compiler attempts to convert the input parameters to types of greater precision. 2. } } Method Overloading Method overloading results when two or more methods in the same class have the same name but different parameters.println("Two parameters: " + a + " .println("One parameter: " + a). " + b).println("Sum is " + intResult). System.println("No parameters"). 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. int b) { // Third Version System.out.out. } double sumOfParams(double a.sumOfParams().out. They must have a different signature. System. doubleResult = moDemo.out. At compile time.getVolume()).sumOfParams(10.out. return a + b. double doubleResult.println("Sum is " + doubleResult). This allows the compiler to match parameters and choose the correct method when a number of choices exist.println("Two double parameters: " + a + " .out. 20). } public static void main(String args[]) { MethodOverloadDemo moDemo = new MethodOverloadDemo().println(). int intResult.sumOfParams(2). } void sumOfParams(int a) { // Second Version System.println(). return a + b. Methods with the same name must differ in their types or number of parameters.sumOfParams(1. Changing just the return type is not enough to overload a method.out.out.out.

Java provides a default constructor which takes no arguments and performs no special actions or initializations.lang. public class Cube1 { int length.class. } .getInterfaces().class. int height. public int getVolume() { return (length * breadth * height).isInterface(). java. // false A java constructor has the same name as the name of the class to which it belongs.1 .isInterface().29 JAVA FOR BEGINNERS Output No parameters One parameter: 2 Two parameters: 10 .String. since constructors never return a value.lang. the types must match those that are specified in the constructor definition. int breadth. (one default and one parameterized constructor). intfs = cls.Comparable. // [] Below is a code snippet to show whether a Class Object Represents a Class or Interface: Class cls = java. The only action taken by the implicit default constructor is to call the superclass constructor using the super() call.lang.Serializable] // The interfaces for a primitive type is an empty array cls = int. boolean isClass = !cls.io. Below is an example of a cube class containing 2 constructors. Constructors may include parameters of various types.class.CharSequence. When the constructor is invoked using the new operator. 2.lang.2 Sum is 3. Constructor’s syntax does not include a return type.3000000000000003 Below is a code snippet to shows the interfaces that a Class Implements: Class cls = java. // true cls = java. Class[] intfs = cls. isClass = !cls. when no explicit constructors are provided.lang. Constructor arguments provide you with a way to provide parameters for the initialization of an object.getInterfaces(). 20 Sum is 30 Two double parameters: 1. // [java. java.Cloneable.class.String.

30 JAVA FOR BEGINNERS Cube1() { length = 10. Since the constructors in a class all have the same name as the class.getVolume()). The this() call in a constructorinvokes the an other constructor with the corresponding parameter list within the same class. its implementation must be provided. int height. height = 10. Java requires that any this() call must occur as the first statement in a constructor. int h) { length = l. 30). public int getVolume() { return (length * breadth * height).out. The above example shows that the Cube1 constructor is overloaded one being the default constructor and the other being a parameterized constructor. cubeObj2 = new Cube1(10.println("Volume of Cube1 is : " + cubeObj1. int b. cubeObj1 = new Cube1(). It is possible to use this() construct. breadth = 10. . Java Overloaded Constructors Like methods. constructors can also be overloaded. 10). <font size=-1> System. 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. } Cube2() { this(10.println("Finished with Default Constructor"). Below is an example of a cube class containing 3 constructors which demostrates the this() method in Constructors context public class Cube2 { int length. 20. it no longer has a default constructor to set the state of the objects. cubeObj2. } } Note: If a class defines an explicit constructor. />their signatures are differentiated by their parameter lists.println("Volume of Cube1 is : " + cubeObj2. int breadth.getVolume()). height = h. System. breadth = b.out.out. } Cube1(int l. System. to implement local chaining of constructors in a class. If such a class requires a default constructor. Calling the default constructor to create a Cube object results in the second and third parameterized constructors being called as well. } public static void main(String[] args) { Cube1 cubeObj1.

20.println("Volume of Cube1 is : " + cubeObj1.println("Finished with Parameterized Constructor having 3 params").getVolume()). 10). int h) { length = l. int h) { length = l.println("Finished with Parameterized Constructor having 3 params").println("Finished with Parameterized Constructor having 2 params").println("Volume of Cube1 is : " + cubeObj1. 20. System. } Cube2() { this(10. 10). int b) { this(l. 30).out. } } public class Cube2 { int length. cubeObj1 = new Cube2(). cubeObj2 = new Cube2(10.out. } } 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 . } Cube2(int l.getVolume()).31 JAVA FOR BEGINNERS } Cube2(int l. System. breadth = b. cubeObj2 = new Cube2(10.out. int height. height = h. b.out.out. System.println("Finished with Default Constructor").println("Volume of Cube2 is : " + cubeObj2. int b. System. height = h.println("Finished with Parameterized Constructor having 2 params"). 10).out. } Cube2(int l. } Cube2(int l. public int getVolume() { return (length * breadth * height). int breadth. System. breadth = b.getVolume()). int b) { this(l. } public static void main(String[] args) { Cube2 cubeObj1. int b. System. } public static void main(String[] args) { Cube2 cubeObj1.out. cubeObj1 = new Cube2().println("Volume of Cube2 is : " + cubeObj2.out. System. System.getVolume()). b. 30). cubeObj2.out. cubeObj2. System.

int h) { super(l. height = h. } SpecialCube(int l. System.println("Finished with Parameterized Constructor having 2 params of Cube").32 JAVA FOR BEGINNERS Volume of Cube1 is : 1000 Volume of Cube2 is : 6000 Constructor Chaining Every constructor calls its superclass constructor. System. } Cube(int l. weight = 20. System. 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. .out. based on the signature of the call. } } public class SpecialCube extends Cube { int weight. int h) { length = l.println("Finished with Default Constructor of Cube"). h).println("Finished with Parameterized Constructor having 3 params of Cube"). } SpecialCube(int l. The super statement must be the first statement of the constructor. } Cube() { this(10. b. 10). 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. weight = 10. 10).println("Finished with Parameterized Constructor having 3 params of SpecialCube"). SpecialCube() { super(). int height.out. int b. int b.println("Finished with Parameterized Constructor having 2 params of SpecialCube"). This is called constructor chaining. } Cube(int l. System. The implicit super() can be replaced by an explicit super(). b. Below is an example of a class demonstrating constructor chaining using super() method. 10). b. int b) { this(l.out. class Cube { int length.out. int b) { this(l.out. The super() statement invokes a constructor of the super class. int breadth. public int getVolume() { return (length * breadth * height). breadth = b. System.

public int getVolume() { return (length * breadth * height). System. class Cube { int length. System. and it can only be used in a constructor declaration. then its subclasses will not include an implicit super() call. 30). This implies that this() and super() calls cannot both occur in the same constructor.println("Finished with Parameterized Constructor having 3 params of Cube"). Just as the this() construct leads to chaining of constructors in the same class. breadth = b. } } 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. System.out.weight). System. 20. Note: If a class only defines non-default constructors. SpecialCube specialObj2 = new SpecialCube(10.println("Weight of SpecialCube2 is : " + specialObj2. int height. int h) { length = l. height = h. then a super() call to the default constructor in the superclass is inserted. Below is an example of a class demonstrating constructor chaining using explicit super() call.33 JAVA FOR BEGINNERS } public static void main(String[] args) { SpecialCube specialObj1 = new SpecialCube().weight).out. SpecialCube1() { super(10. } Cube(int l.println("Volume of SpecialCube2 is : " + specialObj2. the super() construct leads to chaining of subclass constructors to superclass constructors.println("Volume of SpecialCube1 is : " + specialObj1.out. 20). System.getVolume()).println("Weight of SpecialCube1 is : " + specialObj1. must occur as the first statement in a constructor. if a constructor has neither a this() nor a super() construct as its first statement.out. //Will Give a Compilation Error without this line weight = 10. int b. } } public class SpecialCube1 extends Cube { int weight.getVolume()). int breadth. . 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. This will be flagged as a compile-time error.out.

The ordered stream of bytes can then be read at a later time.Serializable interface or the java. System.io. or in another environment. } } 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. or serialized stream of bytes. (Marker Interface) . Java provides classes to support writing objects to streams and restoring objects from streams. Serialization flattens objects into an ordered.34 JAVA FOR BEGINNERS } public static void main(String[] args) { SpecialCube1 specialObj1 = new SpecialCube1(). process or any other system.io. to recreate the original objects.Externalizable interface can be written to streams.println("Volume of SpecialCube1 is : "+ specialObj1. public interface Serializable • The Serializable interface has no methods or fields.out. Java serialization does not cannot occur for transient or static fields. database.getVolume()). Only objects that support the java. network. Marking the field transient prevents the state from being written to the stream and from being restored during deserialization.

These high-level streams are each chained to a low-level stream. such as FileInputStream or FileOutputStream. this.Serializable interface can be serialized or deserialized Transient Fields and Java Serialization The transient keyword is a modifier applied to instance variables in a class. private int age. Case 1: Below is an example that demonstrates object Serialization into a File PersonDetails is the bean class that implements the Serializable interface import java.such as a process ID or a time lapse. The low-level streams handle the bytes of data. } public String getName() { return name. } public void setAge(int age) { this. The writeObject method saves the state of the class by writing the individual fields to the ObjectOutputStream.name = name.35 JAVA FOR BEGINNERS • Only objects of classes that implement java. int age. or variables that contain local information.Serializable.io. } public String getSex() { return sex. public class PersonDetails implements Serializable { private String name. It specifies that the variable is not part of the persistent state of the object and thus never saved during serialization. this. String sex) { this.age = age. private String sex. You can use the transient keyword to describe temporary variables. } public void setName(String name) { this. The readObject method is used to deserialize the object from the object input stream. } public int getAge() { return age.sex = sex. Input and Output Object Streams ObjectOutputStream is the primary output stream class that implements the ObjectOutput interface for serializing objects. ObjectInputStream is the primary input stream class that implements the ObjectInput interface for deserializing objects.age = age.name = name. public PersonDetails(String name. } .io.

try { fos = new FileOutputStream(filename). List pDetails = null. out = new ObjectOutputStream(fos). list. import java. PersonDetails person1 = new PersonDetails("hemanth".printStackTrace(). pDetails = (ArrayList) in.txt).add(person2).io. } catch (IOException ex) { ex. try { fis = new FileInputStream(filename).util.ObjectInputStream. PersonDetails person2 = new PersonDetails("bob".size()). } } PersonPersist is the class that is used to serialize object into the File (person.out. "Male"). out. "Female").out. in = new ObjectInputStream(fis).36 JAVA FOR BEGINNERS public void setSex(String sex) { this. System. FileOutputStream fos = null. . public class GetPersonDetails { public static void main(String[] args) { String filename = "person. out. PersonDetails person3 = new PersonDetails("Richa".println("Person Details Size: " + pDetails.IOException.List.writeObject(list).close().printStackTrace(). public class PersonPersist { public static void main(String[] args) { String filename = "person. FileInputStream fis = null. list. } catch (ClassNotFoundException ex) { ex.util.printStackTrace().println(). "Male"). 10.println("Object Persisted"). } catch (IOException ex) { ex. List list = new ArrayList().txt".out. } } GetPersonDetails is the class that is used to Deserialize object from the File (person. list.add(person1).FileInputStream. 12.ArrayList. System.txt". 10. } // print out the size System. import java. import java. in.add(person3).sex = sex.txt).close(). import java.io.io. ObjectInputStream in = null. ObjectOutputStream out = null.readObject(). import java.

Connection.ObjectOutputStream.sql. public static void main(String[] args) { Connection con = getOracleJDBCConnection().SQLException.ByteArrayOutputStream. import java. import java. viewname VARCHAR2(30) ).io.ResultSet.close().IOException. ?)"). 10.sql.sql. import java. ps.createStatement(). ps). ps. import java. "Male"). import java.execute().DriverManager. write(person3. write(person1.ObjectInputStream. PersonDetails person3 = new PersonDetails("Richa".ByteArrayInputStream. PersonDetails person1 = new PersonDetails("hemanth". import java. import java.execute(). static Connection con = null. "Male"). PersonDetails person2 = new PersonDetails("bob". ps.prepareStatement("INSERT INTO SerialTest VALUES (?. try { ps = con.sql. ps.io.PreparedStatement.io. import java. PersonPersist is the class that is used to serialize object into the into the Database Table SerialTest. 12. password = "tiger". import java. ResultSet rs = st. public class PersonPersist { static String userid = "scott". Statement st = con.sql. .executeQuery("SELECT * FROM SerialTest"). write(person2.sql. static String url = "jdbc:odbc:bob". PreparedStatement ps.io. 10.io.37 JAVA FOR BEGINNERS } } } ——————————————————————————– 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. "Female"). static int count = 0.execute(). ps). import java. ps).Statement. import java.

setInt(2. IOException. } catch (Exception e) { } } public static void write(Object obj.jdbc. } try { con = DriverManager. } return null. ObjectOutputStream oout = new ObjectOutputStream(baos). . } catch (java.toByteArray()). st. PreparedStatement ps) throws SQLException. ++count). return objectIn. ps.println(e.JdbcOdbcDriver"). } catch (SQLException ex) { System.getBytes(column).out.getConnection(url.getMessage()).err.close().getName() + "\t" + p.println(p.ClassNotFoundException e) { System.writeObject(obj).getAge() + "\t" + p.close(). String column) throws SQLException.err.setBytes(1.forName("sun. PersonDetails p = (PersonDetails) obj. ps.lang. userid. System. oout. baos.print("ClassNotFoundException: ").getSex()). } return con. } } ——————————————————————————– 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.readObject().38 JAVA FOR BEGINNERS while (rs.println("SQLException: " + ex. } public static Object read(ResultSet rs. ClassNotFoundException { byte[] buf = rs. } rs. System. oout. IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(). if (buf != null) { ObjectInputStream objectIn = new ObjectInputStream( new ByteArrayInputStream(buf)).getMessage()).next()) { Object obj = read(rs. } public static Connection getOracleJDBCConnection() { try { Class.odbc. password).close(). "Name").err.

sql.println(p. 12.sql. "Name"). import java. ObjectOutputStream oout = new ObjectOutputStream(baos). static String url = "jdbc:odbc:bob".sql.BASE64Encoder(). ps.ByteArrayOutputStream. PersonDetails person2 = new PersonDetails("bob".close().execute().io.out. PreparedStatement ps.byteArrayToBase64(baos. IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(). 10.execute(). ps).IOException.encode(buf). s).getAge() + "\t" + p. ps).io. import java. ps. password = "tiger". 10.ResultSet. import java.close(). ps). PreparedStatement ps) throws SQLException. // ps.close(). import java.setString(1. ps. PersonDetails p = (PersonDetails) obj.close().io.writeObject(obj). import java.createStatement().misc. System.ObjectOutputStream. "Male").sql. PersonDetails person1 = new PersonDetails("hemanth". write(person2. import java. } rs.setBytes(1.ObjectInputStream. static String s. import java. "Female"). write(person1. oout. st.io.PreparedStatement. static Connection con = null.DriverManager.Connection. ?)"). import java. Base64.toByteArray())). write(person3.prepareStatement("INSERT INTO SerialTest VALUES (?. import java.sql.executeQuery("SELECT * FROM SerialTest"). PersonPersist is the class that is used to serialize object into the Database Table SerialTest import java.SQLException. while (rs.Statement.execute(). try { ps = con. "Male"). ResultSet rs = st. static int count = 0. public class PersonPersist { static String userid = "scott". Statement st = con.io. . PersonDetails person3 = new PersonDetails("Richa".getName() + "\t" + p.next()) { Object obj = read(rs. s = new sun. public static void main(String[] args) { Connection con = getOracleJDBCConnection(). import java. } catch (Exception e) { } } public static void write(Object obj.toByteArray().ByteArrayInputStream. ps. byte[] buf = baos.39 JAVA FOR BEGINNERS viewname VARCHAR2(30) ). ps.getSex()).sql. oout.

io.close(). System. } catch (java. } return null.misc.forName("sun. } } Below is a program that shows the serialization of a JButton object to a file and a Byte Array Stream.odbc.dat")). import java.io.ByteArrayOutputStream.getName() + "\t" + p.getSex()).getConnection(url.ObjectOutputStream. } public static Connection getOracleJDBCConnection() { try { Class.println(p.lang.jdbc. } catch (SQLException ex) { System.getBytes(column))).dat" ObjectOutput out = new ObjectOutputStream( new FileOutputStream("filename. if (buf != null) { ObjectInputStream objectIn = new ObjectInputStream( new ByteArrayInputStream(buf)). userid.err. out. } try { con = DriverManager. // Get the bytes of the serialized object . out.err. ps.decodeBuffer(s). import java.ClassNotFoundException e) { System. out.err.swing.println("SQLException: " + ex.base64ToByteArray(new // String(rs.io. baos. } public static Object read(ResultSet rs. System. ++count). import java.getMessage()).readObject(). out = new ObjectOutputStream(bos). PersonDetails is the bean class that implements the Serializable interface import java. String column) throws SQLException. public class ObjectSerializationExample { public static void main(String args[]) { try { Object object = new javax. } return con. // byte[] buf = Base64.writeObject(object). ClassNotFoundException { byte[] buf = new sun.io.getMessage()). out.FileOutputStream.40 JAVA FOR BEGINNERS ps.JdbcOdbcDriver").close().JButton("Submit").ObjectOutput.out.setInt(2.writeObject(object).println(e.BASE64Decoder().print("ClassNotFoundException: ").toByteArray()). As before theobject to be serialized must implement the Serializable interface. // Contains the object PersonDetails p = (PersonDetails) obj. password). Object obj = objectIn. // Serialize to a byte array ByteArrayOutputStream bos = new ByteArrayOutputStream(). IOException.setBytes(1.getAge() + "\t" + p. // Serialize to a file namely "filename.

For example a car class can inherit some properties from a General vehicle class. The subclass itself can add its own new behavior and properties. A subclass must use the extends clause to derive from a super class which must be written in the header of the subclass definition. } } } Java Inheritance Java Inheritance defines an is-a relationship between a superclass and its subclasses. .printStackTrace(). Here we find that the base class is the vehicle class and the subclass is the more specific car class.Object class is always at the top of any Class inheritance hierarchy. will also inherit from class y. Class Inheritance in java mechanism is used to build new classes from existing classes.lang. The java. } catch (Exception e) { e. which extends class x.41 JAVA FOR BEGINNERS byte[] buf = bos. The inheritance relationship is transitive: if class x extends class y. This means that an object of a subclass can be used wherever an object of the superclass can be used. then a class z.toByteArray(). class Box { double width. The subclass inherits members of the superclass and hence promotes code reuse. double height.

} } Output Volume is : 1000.out. depth = d. A subclass can extend only one superclass .getVolume(). System.0 height of MatchBox 1 is 10.println("weight of MatchBox 1 is " + mb1. height = h.println("height of MatchBox 1 is " + mb1.height). they are not inherited by a subclass. 10.width). } public static void main(String args[]) { MatchBox mb1 = new MatchBox(10. } } public class MatchBox extends Box { double weight.println("depth of MatchBox 1 is " + mb1.0 depth of MatchBox 1 is 10.42 JAVA FOR BEGINNERS double depth. double h.println("width of MatchBox 1 is " + mb1. System.0 What is not possible using java class Inheritance? 1. System. 2.depth). MatchBox() { } MatchBox(double w. 3.out. 10. Members that have default accessibility in the superclass are also not inherited by subclasses in other packages. double d) { width = w. Private members of the superclass are not inherited by the subclass and can only be indirectly accessed. Since constructors and initializer blocks are not members of a class. } void getVolume() { System. double h. d). System.out. Box() { } Box(double w. weight = m.0 width of MatchBox 1 is 10. double d.out.weight).out.0 weight of MatchBox 1 is 10. h.println("Volume is : " + width * height * depth). double m) { super(w. 10). 4. mb1. as these members are only accessible by their simple names in subclasses within the same package as the superclass.

println("accessories: " + accessories).out.println("accessories: " + isPresent()). counter++. // Not Inherited. noOfTyres = 5. System.println("Constructor of the Super class called"). getNoOfVehicles(). } } public class VehicleDetails { // (3) public static void main(String[] args) { new Car(). accessories = true.out. // Not Inherited. } public void switchOff() { accessories = false. System.43 JAVA FOR BEGINNERS class Vehicle { // Instance fields int noOfTyres.println("Vehicle Brand: " + brand).println("Counter: " + counter). } } Output .out. // check if accessorees present or not protected String brand.out.printCarInfo(). } public boolean isPresent() { return accessories.out. } } class Car extends Vehicle { private int carNo = 10.println("Car number: " + carNo).out. } // Static methods public static void getNoOfVehicles() { System. System.println("No of Tyres: " + noOfTyres).println("Brand: " + brand). // System. // no of tyres private boolean accessories. } // Instance methods public void switchOn() { accessories = true. brand = "X". // Inherited.out.out. } private void getBrand() { System. // Inherited. // Brand of the car // Static fields private static int counter. // System.println("Brand: " + getBrand()). // Inherited.out. // System. // No of Vehicle objects created // Constructor Vehicle() { System. // Inherited. public void printCarInfo() { System.out. // Not Inherited.println("Number of Vehicles: " + counter).

increment(). but as an instance of the current class’s super class. Using this and super you have full control on whether to call a method or field present in the same class or to call from the immediate superclass.0 height of MatchBox 1 is 10.0 depth of MatchBox 1 is 10. The this reference to the current object is useful in situations where a local variable hides.0 . Counter increment() { i++. as static code is not executed in the context of any object.print().println("i = " + i). or shadows.0 weight of MatchBox 1 is 10.44 JAVA FOR BEGINNERS Constructor of the Super class called Car number: 10 No of Tyres: 5 accessories: true Brand: X Number of Vehicles: 1 this and super keywords The two keywords.out. The keyword super also references the current object.increment(). } } public class CounterDemo extends Counter { public static void main(String[] args) { Counter x = new Counter().increment(). } void print() { System. this and super to help you explicitly name the field or method that you want. class Counter { int i = 0. return this. Note that the this reference cannot be used in a static context. a field with the same name. it can do so using the this reference. This keyword is used as a reference to the current object which is an instance of the current class. x. If a method needs to pass the current object to another method. } } Output Volume is : 1000.0 width of MatchBox 1 is 10.

Any object reference can be assigned to a reference variable of the type Object.The casting of object references depends on the relationship of the classes involved in the same hierarchy.45 JAVA FOR BEGINNERS Java Object Typecasting Object Reference Type Casting In java object typecasting one object reference can be type cast into another object reference. it is a downcast. When we cast a reference along the class hierarchy in a direction from the sub classes towards the root. The cast can be to its own class type or to one of its subclass or superclass types or interfaces. There are compile-time rules and runtime rules for casting in java. it is an upcast. There can be 2 casting java scenarios · Upcasting · Downcasting When we cast a reference along the class hierarchy in a direction from the root class towards the children or subclasses. We need not use a cast operator in this case. How to Typecast Objects with a dynamically loaded Class ? . . because the Object class is a superclass of every Java class.

incompatible type (siblings) // Y y1 = new X(). // compiles and runs ok (x2 is type Z) // Y y3 = (Y) z. // compiles ok but produces runtime error Z z1 = (Z) x. * A reference variable whose type is a super class of the class from which the object was instantiated. X xy = new Y(). 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. 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. // compiles ok (z is subclass of X) Y y1 = (Y) x. Consider an interface Vehicle. Object o1 = (Y) o. The following example shows the automatic conversion of object references handled by the compiler interface Vehicle { } class Car implements Vehicle { . // compiles ok (up the hierarchy) // Y yz = new Z(). // compiles ok (y is subclass of X) X x2 = z. X is not a Y // Z z1 = new X(). a super class Car and its subclass Ford. // compiles ok but produces runtime error } } Casting Object References: Implicit Casting using a Compiler In general an implicit cast is done when an Object reference is assigned (cast) to: * A reference variable whose type is the same as the class from which the object was instantiated. // compiles ok (up the hierarchy) X xz = new Z(). Z z = new Z(). // compiles ok but produces runtime error Y y2 = (Y) x1. * A reference variable whose type is an interface that is implemented by a super class of the class from which the object was instantiated. inconvertible types (siblings) // Z z3 = (Z) y.46 JAVA FOR BEGINNERS The compile-time rules are there to catch attempted casts in cases that are simply not possible. X is not a Z X x1 = y. // compiles and runs ok (x1 is type Y) Z z2 = (Z) x2. Y y = new Y(). An Object as Object is a super class of every Class. * A reference variable whose type is an interface that is implemented by the class from which the object was instantiated. public class RunTimeCastDemo { public static void main(String args[]) { X x = new X(). inconvertible types (siblings) Object o = z.

We can assign the Ford reference to the Car variable: I. Example 2 v = c. the type Car can be cast to Vehicle interface type since Car implements Vehicle Interface.. And. the type Car can hold the type Ford since a Ford is a Car. //Ok Compiles fine Where c = new Car(). we can do the following Example 1 c = f. f = new Ford(). //Ok Compiles fine c = v. The explicit cast is nothing but the name of the new “type” inside a pair of matched parentheses. And v is a Vehicle interface reference (Vehicle v) The compiler automatically handles the conversion (assignment) since the types are compatible (class – interface relationship). 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. As before.e.e.47 JAVA FOR BEGINNERS } 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. (Car is a Vehicle). i. The compiler automatically handles the conversion (assignment) since the types are compatible (sub class . Casting Object References: Explicit Casting Sometimes we do an explicit cast in java when implicit casts don’t work or are not helpful for a particular scenario.e.super class relationship). i. // illegal conversion from interface type to class type results in compilation error Where c = new Car().. The method will invoke carMethod() regardless of the type of object (Car or Ford Reference) .

Also an attempt to cast an object reference to its Sibling Object reference produces a ClassCastException at runtime. it will also invoke fordMethod().fordMethod (). 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.println("I am fordMethod defined in Class Ford"). the compiler will give an error message indicating that fordMethod() cannot be found in the Car definition. Any class that does not explicitly extend some other class will automatically extends the Object by default.out. We use the instanceof operator to determine the type of object at run time. } To invoke the fordMethod(). The following program shown illustrates the use of the cast operator with references. Both these classes are subclasses of Class Car. 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. if (obj instanceof Ford) ((Ford)obj). the operation (Ford)obj tells the compiler to treat the Car object referenced by obj as if it is a Ford object.48 JAVA FOR BEGINNERS and if it is a Ford object. class Car extends Object { void carMethod() { } } class HeavyVehicle extends Object { } class Ford extends Car { void fordMethod() { System. This assignment is allowed as Car is a superclass of Ford. public void breakingSystem (Car obj) { obj. although compilation happens without any error. Without the cast. In order to use a reference of a class type to invoke a method. } } class Honda extends Car { . the method must be defined at or above that class in the class hierarchy.carMethod(). Note: Classes Honda and Ford are Siblings in the class Hierarchy. This code instantiates an object of the class Ford and assigns the object’s reference to a reference variable of type Car. Both Car and HeavyVehicle Class extend Object Class.

// cast allowed System.println("Username : " + u). v. // Following will result in compilation error // obj.fordMethod(). Cannot convert as they are sibblings } } One common casting that is performed when dealing with collections is. Vector v = new Vector(). } } public class ObjectCastingEx { public static void main(String[] args) { Car obj = new Ford().fordMethod().elementAt(0).println(). // String u = v.elementAt(1).println("Password : " + pass). public class StringCastDemo { public static void main(String args[]) { String username = "asdf".49 JAVA FOR BEGINNERS void fordMethod() { System.out.add(password). System.out. import java. //fordMethod is undefined in the HeavyVehicle Type // Following will result in compilation error ((Ford) obj).add(username).elementAt(0).Vector. System. Cannot convert from object to String Object u = v.util. String password = "qwer".println("I am fordMethod defined in Class Ford").out.out. //As the method fordMethod is undefined for the Car Type // Following will result in compilation error // ((HeavyVehicle)obj). you can cast an object reference into a String.elementAt(0).println("Username : " + uname).fordMethod(). //Following will compile and run // Honda hondaObj = (Ford)obj. String uname = (String) v. // cast allowed String pass = (String) v. //Cast not done System.out. v. } } Output Username : asdf Username : asdf Password : qwer instanceof Operator .

result = T instanceof HeavyVehicle. System. static HeavyVehicle hV = new HeavyVehicle(). //Sucessful Explicit Cast form parent to child } } Output .out.print("hV is a Truck: " + result + "\n"). System.print("T is an HeavyVehicle: " + result + "\n"). otherwise it returns false. It returns true if an object is an instance of the class or if the object implements the interface. or implements a specific interface. } } class LightVehicle extends Vehicle { LightVehicle() { name = "LightVehicle". } } public class InstanceOfExample { static boolean result. System. } } class HeavyVehicle extends Vehicle { HeavyVehicle() { name = "HeavyVehicle". result = hV instanceof Truck. Below is an example showing the use of instanceof operator class Vehicle { String name. } } class Truck extends HeavyVehicle { Truck() { name = "Truck". result = hv2 instanceof HeavyVehicle. hV = T. public static void main(String[] args) { result = hV instanceof HeavyVehicle.print("hV is an HeavyVehicle: " + result + "\n").print("hv2 is an HeavyVehicle: " + result + "\n").out. Vehicle() { name = "Vehicle". System. lets you determine if an object belongs to a specific class.50 JAVA FOR BEGINNERS The instanceof operator is called the type comparison operator.out.out. static HeavyVehicle hv2 = null. static Truck T = new Truck(). //Sucessful Cast form child to parent T = (Truck) hV.

Abstract classes are declared with the abstract keyword. an abstract class can contain fields that describe the characteristics and methods that describe the actions that a class can perform. . and actual implementations must be provided for the abstract methods. An abstract class cannot be instantiated. You need to create a subclass that provides an implementation for the abstract method. If a class has any abstract methods. whether declared or inherited. These are called abstract methods. It can only be used as a superclass for other classes that extend the abstract class. Any implementation specified can. the entire class must be declared abstract. An object must have an implementation for all of its methods. The abstract method declaration must then end with a semicolon rather than a block. An abstract class can include methods that contain no implementation. Like any other class. they must be subclassed.51 JAVA FOR BEGINNERS 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. Abstract classes cannot be instantiated. Java Abstract class and Interface Abstract Class in java Java Abstract classes are used to declare common characteristics of subclasses. Abstract classes are used to provide a template or design for concrete subclasses down the inheritance tree. be overridden by additional subclasses. Also we can’t use instanceof operator with siblings. of course. Abstract methods are used to provide a template for the classes that inherit the abstract methods. instanceof returns false.

We declare this class abstract because there is no such thing as a generic shape. abstract class Vehicle { int numofGears. } public static void main(String args[]) { Point p = new Point(). } public double area() { return 0. as creating instances of the class would not be meaningful. y = 0. String color.52 JAVA FOR BEGINNERS A class abstract Vehicle might be specified as abstract to represent the general abstraction of a vehicle. All shapes have some common fields and methods. } public double perimeter() { return 0. circles. } public static void print() { System. The abstract class guarantees that each shape will have the same set of basic properties. } We can also implement the generic shapes class as an abstract class so that we can draw lines. y.out. abstract int getNoofGears(). } abstract public double area(). abstract boolean hasDiskBrake().println("point: " + x + ". public Shape() { } public void setColor(String c) { color = c. public class Point extends Shape { static int x. public Point() { x = 0." + y). circles. of course. but each can. There can only be concrete shapes such as squares. add more fields and methods. } public String getColor() { return color. . triangles etc. } Example of a shape class as an abstract class abstract class Shape { public String color. triangles etc.

} } Output point: 0. Interface can be used to define a generic template and then one or more abstract classes to define partial implementations of the interface. this multiple inheritance problem is solved with a powerful construct called interfaces. In the sense. A big Disadvantage of using abstract classes is not able to use multiple inheritance. This means that all of the abstract methods of the Shape class must be implemented by the Point class. one interface can extend none. or the subclass itself will also be abstract. The subclass must define an implementation for every abstract method of the abstract superclass. its class cannot be abstract. in order to create a Point object. public Point() { .print(). 0 Notice that. then it must be declared abstract and the method definitions must be provided by the subclass that extends the abstract class. public class Point implements Shape { static int x. Example 1: Below is an example of a Shape interface interface Shape { public double area(). Interfaces just specify the method declaration (implicitly public and abstract) and can only contain fields (which are implicitly public static final). Java does not support multiple inheritance. Similarly other shape objects can be created using the generic Shape Abstract class. Java Interface In Java. If a class that implements an interface does not define all the methods of the interface. it can’t extend any other class. Interface definition begins with a keyword interface. when a class extends an abstract class.53 JAVA FOR BEGINNERS p. public double volume(). y. An interface like that of an abstract class cannot be instantiated.e. } Below is a Point class that implements the Shape interface. Multiple Inheritance is allowed when extending interfaces i. but it allows you to extend one class and implement many interfaces. one or more interfaces.

This is because B1 does not have any relationship with C1 except they are “siblings”. 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. } public double volume() { return 0." + y). } } Similarly. Note: The method toString in class A1 is an overridden version of the method defined in the class named Object. But since the class D1 does not define all the methods of the implemented interface I2. } public static void main(String args[]) { Point p = new Point(). The classes B1 and C1 satisfy the interface contract. // public static by default } interface I2 extends I1 { . When a given interface method is invoked on a given reference. This is runtime polymorphism based on interfaces and overridden methods. but produces a ClassCastException at runtime. ((C1)o1). You can’t cast siblings into one another. which is again resolved by a downcast. Hence a downcast of interface reference I1 solves the problem as shown in the program. the behavior that results will be appropriate to the class from which that particular object was instantiated. p.54 JAVA FOR BEGINNERS x = 0. other shape objects can be created by interface programming by implementing generic Shape Interface. When we invoke the toString() method which is a method of an Object. interface I1 { void methodI1(). } public double area() { return 0. } public static void print() { System. The same problem applies to i1.methodA1().methodI2() produces a compilation error as the method is not declared in I1 or any of its super interfaces if present.methodI1() compiles successfully.out.print(). Also. i1. 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. y = 0.println("point: " + x + ". the class D1 is declared abstract.

out.methodA1(). i2.55 JAVA FOR BEGINNERS void methodI2().methodA1(). // OK as methodI1 is present in B1 // i1. i1.methodI2().println("I am in methodI1 of class B1"). } } class C1 implements I2 { public void methodI1() { System. I2 i2 = new B1().out.println("I am in methodI2 of class C1"). } public String toString() { return "toString() method of class A1".methodI1(). // public static by default } class A1 { public String methodA1() { String strA1 = "I am in methodC1 of class A1". return strA1. Compilation error as methodI2 not present in I1 // Casting to convert the type of the reference from type I1 to type I2 ((I2) i1).println("var2 : " + var2). } public void methodI2() { System. } } class B1 extends A1 implements I2 { public void methodI1() { System. // OK // Does not Compile as methodA1() not present in interface reference I1 // String var = i1. } } // 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.out.out.println("I am in methodI2 of class B1"). } public void methodI2() { System. } public class InterFaceEx { public static void main(String[] args) { I1 i1 = new B1().println("I am in methodI1 of class C1").methodI2().methodI1().methodI2().out. // OK i2. . System. // Hence I1 requires a cast to invoke methodA1 String var2 = ((A1) i1).

println("var6 : " + var6).out. System. System.methodI1(). Produces a ClassCastException } } 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 .56 JAVA FOR BEGINNERS String var3 = ((B1) i1). System. // 3 /* * * B1 does not have any relationship with C1 except they are "siblings".methodI1(). // 2 ((B1) o1). * * Well. I1 i3 = new C1(). * */ // ((C1)o1).println("var5 : " + var5). you can't cast siblings into one another.out.methodI1().out.toString(). System. does not compile as Object class does not define // methodI1() // To solve the probelm we need to downcast o1 reference. String var6 = i3.println("var4 : " + var4). String var5 = i2.methodI1().toString().methodA1(). // o1. // It prints the Object toString() method Object o1 = new B1().out.toString(). String var4 = i1.methodI1(). // 1 ((I2) o1).println("var3 : " + var3). We can do it // in the following 4 ways ((I1) o1).

public void method1() { System.. The new method definition must have the same method signature (i. } public final void method2() { System.57 JAVA FOR BEGINNERS Java Method Overriding Method Overriding is achieved when a subclass overrides non-static methods defined in the superclass.e. So if a subclass has its method parameters as final it doesn’t really matter for method overriding scenarios as it still holds true. . protected static int field2 = 20. or a subset of the exception classes (including their subclasses) specified in the throws clause of the overridden method in the super class A program to explain the different concepts of Java Method Overridding class CustomException extends Exception { } class SuperClassWithDifferentMethods { protected int field1 = 10. The new method definition can only specify all or none.method2()").method1()").println("SuperClassWithDifferentMethods.out. Only parameter types and return type are chosen as criteria for matching method signature.out. The new method definition cannot narrow the accessibility of the method. method name and parameters) and return type.println("SuperClassWithDifferentMethods. but it can widen it. following which the new method implementation in the subclass that is executed.

println("OverridingClass.method5()"). .println("SuperClassWithDifferentMethods.println("OverridingClass.method8()"). } public static void method9() { System. } public void method8(final int x) { System.method2()"). } private final void method4() { System. } public static void method5() { System.println("OverridingClass.method3()"). } } class OverridingClass extends SuperClassWithDifferentMethods { public int field1 = 30.method6()").println("SuperClassWithDifferentMethods. } public void method6() throws CustomException { System.out.println("SuperClassWithDifferentMethods.method6()"). } public void method6() throws Exception { System.out.method8()").out.method7()").println("OverridingClass.method1()").println("OverridingClass.out. public void method1() { System. } //We can't override a public final method /* public final void method2(){ System.method5()").out.out. } private void method8(int x) { System.println("OverridingClass.println("SuperClassWithDifferentMethods. } private void method7() { System.method9()").println("SuperClassWithDifferentMethods.println("OverridingClass.println("OverridingClass.println("OverridingClass. } public void method7() { System.out. public static int field2 = 40.method4()").println("SuperClassWithDifferentMethods.out. } //A static method cannot be overridden to be non-static instance method /*public void method9() { System.out.println("SuperClassWithDifferentMethods.out.out.58 JAVA FOR BEGINNERS } private void method3() { System.out. }*/ private void method3() { System.method9()").method7()"). } public static void method5() { System.out.method3()").out.out.method4()"). } private final void method4() { System.out.

oc1.method6().field2 : 40 sc3.method7(). The .method6() OverridingClass.method2() OverridingClass.field2 : " + oc1.method3().method5().*/ oc1. sc3.method2().method1() SuperClassWithDifferentMethods.field1 : " + oc1.out.field2).method8(100).method5() OverridingClass.method5(). supClass. System.field1 : 10 sc3. try { oc1.59 JAVA FOR BEGINNERS }*/ } public class MethodOverridingDemo { public static void main(String[] args) { OverridingClass oc1 = new OverridingClass().out.out. The new overridden method6 definition specifies a subset of the exceptions (CustomException). oc1. supClass. } } Output OverridingClass.field2). } oc1.method7() OverridingClass.method1().println("sc3.method8() oc1.println("oc1.field1).method5() SuperClassWithDifferentMethods. } catch (CustomException e) { e. System. System.method5() OverridingClass. SuperClassWithDifferentMethods sc3 = new OverridingClass().field1 : " + sc3.printStackTrace().field1 : 30 oc1.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 below 2 methods are not visible /* oc1.field2 : " + sc3. System. oc1. oc1. SuperClassWithDifferentMethods supClass = (SuperClassWithDifferentMethods) overClass.method5(). OverridingClass overClass = new OverridingClass().out.println("oc1. // Since its private.println("sc3.field2 : 20 SuperClassWithDifferentMethods.field1).method1().method4(). The new overridden method7 definition also widens the accessibility to public from private.

A subclass must use the ‘super’ keyword in order to invoke an overridden method in the superclass. it is the type of the reference. therefore. The java. including hidden fields.e. A static method cannot be overridden to be nonstatic instance method as shown in the overridden method declaration of method9. as for fields only the field names matter. i. When a field of an object is accessed using a reference.60 JAVA FOR BEGINNERS overriding method8 also declares the parameter to be final. while overriding methods are invoked on behalf of objects of the subclass. The reference value of a string literal can be assigned to another String reference. There are no such restrictions on the fields. but it can hide them. .lang. Since a string literal is a reference. A private method is not accessible outside the class in which it is defined. The substring( ) method is used to obtain a selected portion of a String. A static method is class-specific and not part of any object.String class is final which implies no class and extend it. This is demonstrated in the above program Java String Class Strings in java Java String Class is immutable. not the type of the reference. Strings in java. an attempt to which will result in a compile-time error. which is not a part of the method signature and Method Overriding holds good.String class creation A simple String can be created using a string literal enclosed inside double quotes as shown. When an instance method is invoked on an object using a reference. one difference being that the String objects can be used with the += and + operators for concatenation. not the class of the current object denoted by the reference. A java. A subclass cannot override fields of the superclass. String str1 = “My name is bob”. that determines which field will actually be accessed. it can be manipulated like any other String reference. that determines which method implementation will be executed.lang. A final method cannot be overridden. If 2 or more Strings have the same set of characters in the same sequence then they share the same reference in memory. once created and initialized.lang. Below illustrates this phenomenon. it is the class of the current object denoted by the reference. Two useful methods for String objects are equals( ) and substring( ). cannot be changed on the same reference. Code in the subclass can use the keyword super to access members. Java. The equals( ) method is used for testing whether two Strings contain the same value.String class differs from other classes. a subclass cannot override it. The following distinction between invoking instance methods on an object and accessing fields of an object must be noted.

String str4 = “My name is” + name. } } Output byteStr : charStr : abCD buffStr : abcde –~~~~~~~~~~~~– String Equality public class StringsDemo2 { public static void main(String[] args) { String str1 = "My name is bob".out. System. arrays of characters. String str5 = new String("My name is bob"). 8}. //Compile time expression String name = “bob”. public class StringsDemo { public static void main(String[] args) { byte[] bytes = {2. In the above code all the String references str1. 4.println("charStr : "+charStr). StringBuffer strBuffer = new StringBuffer("abcde"). System. String charStr = new String(characters).out.61 JAVA FOR BEGINNERS String str1 = “My name is bob”. String str2 = “My name is bob”. String buffStr = new String(strBuffer). //Compile time expression String name = "bob". // Examples of Creation of Strings String byteStr = new String(bytes). String str2 = "My name is bob". System. String str3 = “My name ”+ “is bob”. Constructing String objects can also be done from arrays of bytes.println("byteStr : "+byteStr). A simple way to convert any primitive value to its string representation is by concatenating it with the empty string (”"). char[] characters = {'a'. String str3 = "My name " + "is bob". str2 and str3 denote the same String object. initialized with the character string: “My name is bob”. or string buffers. String str4 = "My name is " + name.out. String str5 = new String(“My name is bob”).println("str1 == str2 : " + (str1 == str2)). System. .out. 'D'}. 'b'.println("buffStr : "+buffStr). using the string concatenation operator (+). 'C'. But the Strings str4 and str5 denote new String objects. 6.

out.equals(str2) : true str2. charAt(int index) Returns the character at the specified index. System.out. compareTo(String anotherString) Compares two strings lexicographically.equals(str4)). } } Output str1 == str2 : true str2 == str3 : true str3 == str1 : true str4 == str5 : false str1 == str4 : false str1 == str5 : false str1.equals(str1) : true str4. System.println("str1. 3.equals(str1)). int srcEnd.println("str1 == str5 : " + (str1 == str5)).equals(str3) : " + str2.out.println("str2.out.println("str3.out.println("str4.equals(str2)).println("str1.equals(str5) : " + str4.println("str3 == str1 : " + (str3 == str1)).equals(str5)).out.equals(str5) : " + str1. System. 6. 4.out.62 JAVA FOR BEGINNERS System. char[] dst.out.out. equalsIgnoreCase(String anotherString) Compares this String to another String. . System. equals(Object anObject) Compares this string to the specified object. ignoring case considerations. length() Returns the length of this string.equals(str2) : " + str1. 2. System. 1. System. int dstBegin) Copies characters from this string into the destination character array.equals(str1) : " + str3. System.println("str1 == str4 : " + (str1 == str4)). System.equals(str4) : true str1. getChars(int srcBegin. 5.out.out.equals(str4) : " + str1. System.println("str4 == str5 : " + (str4 == str5)).equals(str3)). System.println("str2 == str3 : " + (str2 == str3)).equals(str5) : true str1.println("str1.equals(str5) : true Java String Functions The following program explains the usage of the some of the basic String methods like .equals(str3) : true str3.equals(str5)).

int fromIndex) Returns the index within this string of the last occurrence of the specified character. 7. . 12. 9. 14. lastIndexOf(int ch) Returns the index within this string of the last occurrence of the specified character. 11. lastIndexOf(int ch. 15. indexOf(String str. 13. indexOf(int ch) Returns the index within this string of the first occurrence of the specified character.63 JAVA FOR BEGINNERS 7. 17. int fromIndex) Returns the index within this string of the last occurrence of the specified substring. int fromIndex) Returns the index within this string of the first occurrence of the specified character. searching backward starting at the specified index. int fromIndex) Returns the index within this string of the first occurrence of the specified substring. starting the search at the specified index. 10. lastIndexOf(String str) Returns the index within this string of the rightmost occurrence of the specified substring. starting at the specified index. searching backward starting at the specified index. concat(String str) Concatenates the specified string to the end of this string. indexOf(String str) Returns the index within this string of the first occurrence of the specified substring. 16. indexOf(int ch. lastIndexOf(String str. substring(int beginIndex) Returns a new string that is a substring of this string. toUpperCase() Converts all of the characters in this String to upper case using the rules of the default locale. toLowerCase() Converts all of the characters in this String to upper case using the rules of the default locale. 18.

System. //Strings are immutable System.equals(str3)).print("Equals Test"). char str2[] = new char[str1.length()]. int endIndex) Returns a new string that is a substring of this string.toUpperCase().print("Comparision Test : "). System.println("Character at position 3 is : " + str1. System.toUpperCase().out.println("Length of the String str1 : " + str1.trim().equals(str6)).out. i < str2.println("str3. String str7temp = " \t\n Now for some Search and Replace Examples ".length(). str2.print(str3 + " equals " + str4). with leading and trailing whitespace omitted.out.out.println().out. String str3 = "bob".println("str1. } System.toLowerCase(). System. System.compareTo(str4) > 0) { System. if (str3.println("str1 Lowercase: " + str1).compareTo(str4) < 0) { System.out.println("str3. String str6 = "bob".getChars(0. char newChar) Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.out. str1. for (int i = 0.out. public class StringsDemo3 { public static void main(String[] args) { String str1 = "My name is bob". String str4 = "cob".concat(str4)). substring(int beginIndex.println("str5 : " + str5). System. 0).equalsIgnoreCase(5) : " + str3. } System. String str7 = str7temp.out. System. 22. trim() Returns a copy of the string.print(str2[i]). 21.equalsIgnoreCase(str5)).println("str1. System.equals(6) : " + str3. 20.out.equals(3) : " + str1.out. str1.out. System. toString() This object (which is already a string!) is itself returned.out.charAt(3)). i++) { System. String temp = str5.concat(str4): " + str1.out.length()).print(str3 + " > " + str4).print("The String str2 is : ").print(str3 + " < " + str4).out. temp = str1.64 JAVA FOR BEGINNERS 19. } else if (str3. .out.println("str5 Uppercase: " + temp).println().length.out. System. String str5 = "BoB". System. } else { System. replace(char oldChar.out. str5.

println("str7. System.lastIndexOf(’p') : 36 str7.out.println("Index of p in " + str7 + " : " + str7.out.substring(3.out.lastIndexOf(’p'.println("newStr : " + newStr). 4) : " + str7.indexOf("for".out.indexOf(for. 30)).indexOf('p'.equalsIgnoreCase(5) : true str3.out.lastIndexOf('p'. System.substring(3.println("str7.replace('s'.println("indexof Operations on Strings").lastIndexOf('p'.substring(5) : " + sub5). String newStr = str7. System. 30) : " + str7.indexOf(’p'. 30) : 36 str7.println("Index of for in " + str7 + " : " + str7.equals(3) : false str5 : BoB str5 Uppercase: BOB str1 Lowercase: My name is bob str1. 30) : -1 str7. System.println("str7 : " + str7).out. String str8 = "SubString Example".indexOf("for")).substring(3. 6).6) : " + sub3_6). System. // "Str" System. System. System.substring(5). } } 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.out. // "ring Example" String sub3_6 = str8. boolean isNumberFlag = false. System.indexOf(for.print("SubString Operations on Strings"). System.6) : Str Below is a program to check for Alpha Numeric character’s in the string.indexOf('p'. 30) : " + str7.out.lastIndexOf('p') : " + str7.println("str8. String sub5 = str8. 4) : -1 SubString Operations on Stringsstr8 : SubString Example str8.println("str8. 4)).out. 30)).out.substring(5) : ring Example str8.println("str8 : " + str8).out. public class TestAlphaNumericCharacters { private void isAlphaNumeric(final String input) { boolean isCharFlag = false.out. System. 'T').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('p')). .65 JAVA FOR BEGINNERS System.println("str7.println("str7.lastIndexOf('p')). System.out.equals(6) : true str1.

for (int x = 0. continue.println(). while (!stack. public class StringReverse { public static void main(String[] args) { String input = "beginner java tutorial". } if ((c >= '0') && (c <= '9')) { // numeric isNumberFlag = true. System.print(" ").*.hasMoreTokens()) { stack.length.println("Numbers are present :" + isNumberFlag).out.print("Reversed String by Words: "). // lowercase && uppercase alphabet if ((c >= 'a') && (c <= 'z') || (c >= 'A') && (c <= 'Z')) { isCharFlag = true. System. } } Output characters are present:true Numbers are present :true Below is a java program to Reverse a string (Reverse by words / characters) import java.out. } System.out.out.reverse(). } } . StringBuffer rev = new StringBuffer(input).out.util.toCharArray(). System.empty()) { System. //A Stack is a Last In First Out Data Structure StringTokenizer stringTokenizer = new StringTokenizer(input). Stack stack = new Stack().out.print(rev).push(stringTokenizer.out. continue.print("Reversed String by characters: ").println("Original String: " + input). System.print(stack. x++) { char c = chars[x].isAlphaNumeric("beginn3ers"). tANC. } System.nextElement()). System. while (stringTokenizer.out. x < chars.println("characters are present:" + isCharFlag).out. } public static void main(String[] args) { TestAlphaNumericCharacters tANC = new TestAlphaNumericCharacters(). } } System.pop()).66 JAVA FOR BEGINNERS final char[] chars = input.

67 JAVA FOR BEGINNERS Output Original String: beginner java tutorial Reversed String by Words: tutorial java beginner Reversed String by characters: lairotut avaj rennigeb Java toString Method Implementing toString method in java is done by overriding the Object’s toString method. y. } } public class ToStringDemo { public static void main(String args[]) { PointCoordinates point = new PointCoordinates(10. int y) { this.out. 10). class PointCoordinates { private int x. It is defined in Object class.println("Object toString() method : " + point). } public int getY() { return y.x = x. public PointCoordinates(int x. This method can be overridden to customize the String representation of the Object. Below is a program showing the use of the Object’s Default toString java method. } public int getX() { return x. // using the Default Object.y = y. this. // implicitly call toString() on object as part of string concatenation . The java toString() method is used when we need a string representation of an object.toString() Method System.

68 JAVA FOR BEGINNERS
String s = point + " testing"; System.out.println(s); } }

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 Object’s 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 object’s 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); } }

When you run the ToStringDemo2 program, the output is:

69 JAVA FOR BEGINNERS

X=10 Y=10 X=10 Y=10 testing

Java String Comparison
Java String compare to determine Equality
java string compare can be done in many ways as shown below. Depending on the type of java string compare you need, each of them is used. * == Operator * equals method * compareTo method Comparing using the == Operator The == operator is used when we have to compare the String object references. If two String variables point to the same object in memory, the comparison returns true. Otherwise, the comparison returns false. Note that the ‘==’ operator does not compare the content of the text present in the String objects. It only compares the references the 2 Strings are pointing to. The following Program would print “The strings are unequal” In the first case and “The strings are equal” in the second case.
public class StringComparision1 { public static void main(String[] args) { String name1 = "Bob"; String name2 = new String("Bob"); String name3 = "Bob"; // 1st case

70 JAVA FOR BEGINNERS
if (name1 == name2) { System.out.println("The strings are equal."); } else { System.out.println("The strings are unequal."); } // 2nd case if (name1 == name3) { System.out.println("The strings are equal."); } else { System.out.println("The strings are unequal."); } } }

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");

inserting. //With capacity 100 StringBuffer strBuf3 = new StringBuffer().compareTo(name2) < 0) { System. StringBuffer strBuf2 = new StringBuffer(100).println("The strings are equal.out.println("strBuf2 capacity : " + strBuf2. StringBuffer can be changed dynamically.println("The strings are equal. // 1st case if (name1.compareTo(name2) == 0) { System. deleting. A StringIndexOutOfBoundsException is thrown if an index is not valid when using wrong index in String Buffer manipulations Creation of StringBuffers StringBuffer Constructors public class StringBufferDemo { public static void main(String[] args) { // Examples of Creation of Strings StringBuffer strBuf1 = new StringBuffer("Bob").out.capacity()).println("name1 follows name3"). Comparing Ascii Uppercase will be smaller then Lower Case if (name1. } else if (name1.println("name3 follows name1").compareTo(name3) == 0) { System. } else { System.println("name1 follows name2").println("strBuf1 : " + strBuf1). Since the StringBuffer class does not override the equals() method from the Object class. } } } Java StringBuffer StringBuffer Class StringBuffer class is a mutable class unlike the String class which is immutable.").out. } else if (name1.out. Both the capacity and character string of a StringBuffer Class. . String buffers are preferred when heavy modification of character strings is involved (appending. //Default Capacity 16 System. } else { System. modifying etc).out.71 JAVA FOR BEGINNERS String name3 = "Bob".out. } // 2nd case. Strings can be obtained from string buffers.out.println("name2 follows name1")."). contents of string buffers should be converted to String objects for string comparison.out. System.compareTo(name3) < 0) { System.

72 JAVA FOR BEGINNERS
System.out.println("strBuf3 capacity : " + strBuf3.capacity()); } }

Output strBuf1 : Bob strBuf2 capacity : 100 strBuf3 capacity : 16

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.

73 JAVA FOR BEGINNERS

11. setLength(int newLength) Sets the length of this String buffer.
public class StringBufferFunctionsDemo { public static void main(String[] args) { // Examples of Creation of Strings StringBuffer strBuf1 = new StringBuffer("Bobby"); StringBuffer strBuf2 = new StringBuffer(100); //With capacity 100 StringBuffer strBuf3 = new StringBuffer(); //Default Capacity 16 System.out.println("strBuf1 : " + strBuf1); System.out.println("strBuf1 capacity : " + strBuf1.capacity()); System.out.println("strBuf2 capacity : " + strBuf2.capacity()); System.out.println("strBuf3 capacity : " + strBuf3.capacity()); System.out.println("strBuf1 length : " + strBuf1.length()); System.out.println("strBuf1 charAt 2 : " + strBuf1.charAt(2)); // A StringIndexOutOfBoundsException is thrown if the index is not valid. strBuf1.setCharAt(1, 't'); System.out.println("strBuf1 after setCharAt 1 to t is : " + strBuf1); System.out .println("strBuf1 toString() is : " + strBuf1.toString()); strBuf3.append("beginner-java-tutorial"); System.out.println("strBuf3 when appended with a String : " + strBuf3.toString()); strBuf3.insert(1, 'c'); System.out.println("strBuf3 when c is inserted at 1 : " + strBuf3.toString()); strBuf3.delete(1, 'c'); System.out.println("strBuf3 when c is deleted at 1 : " + strBuf3.toString()); strBuf3.reverse(); System.out.println("Reversed strBuf3 : " + strBuf3); strBuf2.setLength(5); strBuf2.append("jdbc-tutorial"); System.out.println("strBuf2 : " + strBuf2); // We can clear a StringBuffer using the following line strBuf2.setLength(0); System.out.println("strBuf2 when cleared using setLength(0): " + strBuf2); } }

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

74 JAVA FOR BEGINNERS

Reversed strBuf3 : b strBuf2 :

Understanding Java Exceptions
Exceptions in java are any abnormal, unexpected events or extraordinary conditions that may occur at runtime. They could be file not found exception, unable to get connection exception and so on. On such conditions java throws an exception object. Java Exceptions are basically Java objects. No Project can never escape a java error exception. Java exception handling is used to handle error conditions in a program systematically by taking the necessary action. Exception handlers can be written to catch a specific exception such as Number Format exception, or an entire group of exceptions by using a generic exception handlers. Any exceptions not specifically handled within a Java program are caught by the Java run time environment An exception is a subclass of the Exception/Error class, both of which are subclasses of the Throwable class. Java exceptions are raised with the throw keyword and handled within a catch block. A Program Showing How the JVM throws an Exception at runtime public class DivideException { public static void main(String[] args) { division(100,4); // Line 1 division(100,0); // Line 2 System.out.println("Exit main()."); } public static void division(int totalSum, int totalNumber) {

main(DivideException. The class Throwable provides getMessage() function to retrieve an exception. For more information on what is printed when the following messages are invoked.lang. System. Lastly It also has a toString() method to print a short description of the exception.println("Average : "+ average). The “Exit main()” message is never reached in the main method Output Computing Division. int average = totalSum/totalNumber.").out.ArithmeticException: / by zero Average : 25 Computing Division. Class RuntimeException . 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. It has a printStackTrace() method to print the stack trace to the standard error stream.75 JAVA FOR BEGINNERS System. please refer the java docs.division(DivideException. All classes of throwables define a one-parameter constructor that takes a string as the detail message. java.println("Computing Division.out.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. } } An ArithmeticException is thrown at runtime when Line 11 is executed because integer division by 0 is an illegal operation. Exceptions can be of 2 types: Checked (Compile time Exceptions)/ Unchecked (Run time Exceptions).java:11) at DivideException. at DivideException.

Errors are direct subclass of Throwable class. NullPointerException and so on are all subclasses of the java. These exception are the object of the Exception class or any of its subclasses except Runtime Exception class. Exception ClassNotFoundException Instantiation Exception Illegal Access Exception Not Such Method Exception Reason for Exception This Exception occurs when Java run-time system fail to find the specified class mentioned in the program This Exception occurs when you create an object of an abstract class and interface This Exception occurs when you create an object of an abstract class and interface This Exception occurs when the method you call does not exist in class Unchecked exceptions are RuntimeException and any of its subclasses. Unchecked exceptions . Class Error and its subclasses also are unchecked. Checked Exceptions forces programmers to deal with the exception that may be thrown. the compiler doesn’t force the programmers to either catch the exception or declare it in a throws clause. the programmers may not even know that the exception could be thrown. LinkageError etc. .76 JAVA FOR BEGINNERS Runtime exceptions represent programming errors that manifest at runtime. lang package. They are either irrecoverable (Errors) and the program should not attempt to deal with them. which is a subclass of the Exception class. Checked and Unchecked Exceptions Checked exceptions are subclass’s of Exception excluding class RuntimeException and its subclasses. Errors often cannot be. This exception is thrown when there is an error in input-output operation. Class Error Errors are irrecoverable condtions that can never be caught.lang. or pass the exception on to its caller. In this case operation is normally terminated. These condition arises due to invalid input. however. These are basically business logic programming errors. In fact.io. When a checked exception occurs in a method. Example: Arithmetic exception. List of Checked ExceptionsFollowing are the list of various checked exception that defined in the java. (Runtime Exceptions). or they are logical programming errors. For example ArrayIndexOutOfBounds. problem with your network connectivity and problem in database. Checked exceptions must be caught at compile time.IOException is a checked exception. Example: Memory leak.RuntimeException class. the method must either catch the exception and take the appropriate action. Runtime exceptions do not need to be.java. Example: ArrayIndexOutOfBounds Exception.

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. For Example when you divide a number by zero. Exception Arithmetic Exception Class Cast Exception Array Store Exception Array Index Out Of Bounds Exception Null Pointer Exception Number Format Exception Negative ArraySizeException Exception Statement Syntax Reason for 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 divide a number by zero causes an Arithmetic Exception These Exception occurs.that occur due to invalid argument passed to method.77 JAVA FOR BEGINNERS These Exception arises during run-time . run-time exception is raised. 2)NullPointer Exception .happens if u specify a wrong or unavailable destination 3)ArrayIndexOutOfBounds Exception . There are many types of unchecked exceptions in java. when you declare an array of negative size. when you try to implement an application without referencing the object and allocating to a memory These Exception occurs. when you assign an array which is not compatible with the data type of that array These Exception occurs. 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.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. which has the Syntax try { <code> . The java Compiler does not check the program error during compilation. when you assign an array which is not compatible with the data type of that array These Exception occurs. Exceptions are handled using a try-catch-finally construct.

regardless of the cause of exit from the try block. . Again if the matching catch handler is not found execution proceeds with the finally block and the default exception handler throws an exception. If no exception occurs the execution proceeds with the finally block else it will look for the matching catch block to handle the error. If the finally clock executes a control transfer statement such as a return or a break statement. catch Block: Exceptions thrown during execution of the try block can be caught and handled in 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. cleaning up. Generally finally block is used for freeing resources.78 JAVA FOR BEGINNERS } 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.. the remaining statements in the try block are not executed. or whether any catch block was executed. 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. closing connections etc. On exit from a catch block. If an exception is generated within the try block.

Exception Occurred result : -1 Below is a program showing the Normal Execution of the Program. } catch(Exception e){ System. // finally block .println("Finally Block Executes. } public static int division(int totalSum.out.out. try{ quotient = totalSum/totalNumber. return quotient. 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. System.0).println("Computing Division.println("result : "+result). int totalNumber) { int quotient = -1. System. Exception Occurred").println("Finally Block Executes"). }else{ System.getMessage()). // Line 2 System. Exception : / by zero Finally Block Executes.out.println("Exception : "+ e.out.").out.println("Result : "+ quotient). } } return quotient.79 JAVA FOR BEGINNERS try { <code> } catch (<exception type1> <parameter1>) { // 0 or more <statements> } } finally { <statements> } Output Computing Division.out. } finally{ if(quotient != -1){ System.

For each try block there can be zero or more catch blocks. } catch(Exception e){ System. be An exception consists of a block of code called a try block. a block of code called a catch block. 3. Exception Occurred"). 2. catch and finally Blocks 1.").out.getMessage()).80 JAVA FOR BEGINNERS } } Output null (And not NullPointerException) Rules for try.println("Computing Division. int totalNumber) { int quotient = -1.println("Result : "+ quotient).out. } } } } . The catch blocks and finally block must always appear in conjunction with a try block.out. public class DivideException1 { public static void main(String[] args) { division(100.0). } public static void division(int totalSum. The order exception handlers in the catch block must be from the most specific exception Java exception handling mechanism enables you to catch exceptions in java using try.out.println("Exception : "+ e. System. but only one finally block.out.out. catch. finally block. Let’s examine each of these in detail.println("Result is : "+quotient). } finally{ if(quotient != -1){ System. System. // Line 2 System.out.println("Finally Block Executes. A try block must be followed by either at least one catch block or one finally block. and the finally block. 4.println("Finally Block Executes").println("Main Program Terminating"). System. try{ quotient = totalSum/totalNumber. }else{ System.

Below is an example that shows the use of Custom exception’s along with how the throw and throws clause are used. The super() call can be used to set a detail message in the throwable. } } class TooHot extends BadTemperature{ TooHot(){ super ("Default messaeg : Hot"). . Defining new EXCEPTIONS!! We can have our own custom Exception handler to deal with special exception conditions instead of using existing exception classes. } TooHot(String message){ super (message). } TooCold(String message){ super (message). } } class TempertureObject{ int temperature. Because the exception is thrown from the try block. Custom exceptions usually extend the Exception class directly or any subclass of Exception (making it checked).81 JAVA FOR BEGINNERS Output Computing Division. Exception Occurred Main Program Terminating As shown above when the divide by zero calculation is attempted. Exception : / by zero Finally Block Executes. The finally block executes. an ArithmeticException is thrown. class BadTemperature extends Exception{ BadTemperature( String reason ){ super ( reason ). and program execution is transferred to the catch statement. the remaining statements of the try block are skipped. } } class TooCold extends BadTemperature{ TooCold(){ super ("Default messaeg : Cold").

throws statement A program can explicitly throw an exception using the throw statement besides the implicit exception thrown.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.test(). } } public class ExceptionExample1{ private static void temperatureReport( TempertureObject batch ){ try{ batch. System. The general format of the throw statement is as follows: .println( bt.getMessage( ) ). } catch ( BadTemperature bt ){ System. temperatureReport( new TempertureObject( 50 ) ). 2)NullPointer Exception . temperatureReport( new TempertureObject( 75 ) ). } void test() throws TooHot.82 JAVA FOR BEGINNERS TempertureObject( int temp ) { temperature = temp.out.println( "Perfect Temperature" ). } } 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. if ( temperature > 80 ) throw new TooHot("Very Hot"). TooCold { if ( temperature < 70 ) throw new TooCold("Very Cold"). } } public static void main( String[] args ){ temperatureReport( new TempertureObject( 100 ) ).out.

then the exception is dealt with by the default exception handler at the top level. The runtime system proceeds to find a matching catch block that can handle the exception. result = division(100. normal execution is suspended. Method() throws <ExceptionType1>. int totalNumber) throws ArithmeticException { int quotient = -1. <ExceptionTypen> { } Each <ExceptionTypei> can be a checked or unchecked or sometimes even a custom Exception. } catch(ArithmeticException e){ System. When an exception is thrown.out. If a handler is found. Also an overriding method cannot allow more checked exceptions in its throws clause than the inherited method does.println("Exception : "+ e. throw new TemperatureException(”Too hot”). Below is an example to show the use of a throws and a throw statement. A detail message can be passed to the constructor when the exception object is created.getMessage()).10).println("Computing Division. A throws clause can be used in the method prototype.out. public class DivideException3 { public static void main(String[] args) { try{ int result = division(100.out.…. } } public static int division(int totalSum. Any associated finally block of a try block encountered along the search path is executed.println("result : "+result).83 JAVA FOR BEGINNERS throw <exception reference>. } finally{ if(quotient != -1){ . System. The Exception reference must be of type Throwable class or one of its subclasses. The exception type specified in the throws clause in the method prototype can be a super class type of the actual exceptions thrown. } quotient = totalSum/totalNumber."). execution resumes with the code in its catch block. System. try{ if(totalNumber == 0){ throw new ArithmeticException("Division attempt by 0"). If no handler is found.0).

x = x / y. if ( y < 0 ) return.println("Finally Block Executes"). Note that the finally block is executed always except when the return statement is executed.out.println("Result : "+ quotient). public class ExceptionExample6 { public static void main(String[] args) { int x = 10.println ( e. } . System. } catch ( Exception e ) { System. boolean flag = true. int counter = 0. while (flag) { start: try { if ( y > 1 ) break start.println ( "x : " + x + " y : "+y ). Exception Occurred Exception : Division attempt by 0 Using break and return with Exceptions This example demonstrates the use of the break.out. System.getMessage() ).out. System. } } return quotient. } finally { ++counter.out. } } Output Computing Division. Finally Block Executes Result : 10 Computing Division. continue and return statements with exceptions.84 JAVA FOR BEGINNERS System.println ( "Counter : " + counter ).out. }else{ System.println("Finally Block Executes. Finally Block Executes.out. y = 2. Exception Occurred").

IOException. denom.85 JAVA FOR BEGINNERS --y. int b ){ numerator = t. } } } Output Counter : 1 x : 10 y : 1 Counter : 2 / by zero Counter : 3 Counter : 4 Handling Multiple Exceptions 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.parseInt( denom ). denom = JOptionPane.out. import javax.io.println( "One of the inputs is not an integer" ). denominator = Integer. public class ExceptionExample7{ static int numerator. } catch ( NumberFormatException nfe ){ System. } public int divide( ) throws ArithmeticException{ return numerator/denominator.DataInputStream.swing.io. return. num = JOptionPane. "Enter the Denominator"). try{ numerator = Integer. import java.showInputDialog(null. "Enter the Numerator"). Below is a program to demonstrate the use of multiple catch blocks. denominator = b. denominator.JOptionPane.parseInt( num ). public ExceptionExample7( int t. import java. } public static void main( String args[] ){ String num.showInputDialog(null. .

println( "You can't divide by zero" ). If programmers create a new connection object in every class that requires it. return. that govern the instantiation process.out. JOptionPane. Java Help is an extensible. A static modifier is applied to the instance method that returns the object as it then makes this method a class level method that can be accessed without creating an object. One such scenario where it might prove useful is when we develop the help Module in a project. This design pattern proposes that at any time there can only be one instance of a singleton (object) created by the JVM.showMessageDialog(null. In this scenario by using a singleton connection class we can maintain a single connection object which can be used throughout the application.println( "Finally Block is always Executed" ). } catch ( ArithmeticException ae ){ System.getMessage( ) ). Implementing Singleton Pattern To implement this design pattern we need to consider the following 4 steps: . platform-independent help system that enables authors and developers to incorporate online help into applications. The class’s default constructor is made private.out. Java Singleton pattern belongs to the family of design patterns. } } } Java Singleton Design Pattern Java has several design patterns Singleton Pattern being the most commonly used. Singletons can be used to create a Connection Pool.divide( ). } finally{ System. which prevents the direct instantiation of the object by others (Other Classes). } ExceptionExample7 d = new ExceptionExample7( numerator.println( "Exception: " + e.86 JAVA FOR BEGINNERS } catch ( Exception e ){ System.out. then its clear waste of resources. "Result : " + result). try{ double result = d. denominator ).

First time the object is created inside this method as it is null. } . // Note that the constructor is private private SingletonObjectDemo() { // Optional Code } public static SingletonObjectDemo getSingletonObject() { if (singletonObject == null) { singletonObject = new SingletonObjectDemo(). 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. } return singletonObject. public Object clone() throws CloneNotSupportedException { throw new CloneNotSupportedException(). This again violates the Singleton Design Pattern’s objective.87 JAVA FOR BEGINNERS Step 1: Provide a default Private constructor public class SingletonObjectDemo { // Note that the constructor is private private SingletonObjectDemo() { // Optional Code } } Step 2: Create a Method for getting the reference to the Singleton Object public class SingletonObjectDemo { private static SingletonObject singletonObject.clone(). 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. } } We write a public static getter or access method to get the instance of the Singleton Object at runtime. Step 3: Make the Access method Synchronized to prevent Thread Problems. This could violate the design patter principle. This can be done as shown below SingletonObjectDemo clonedObject = (SingletonObjectDemo) obj. 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 Object’s clone method. So to deal with this we need to override the Object’s clone method which throws a CloneNotSupportedException exception.

} } Another approach We don’t need to do a lazy initialization of the instance object or to check for null in the get method. */ private SingletonClass() { // Optional Code } public static synchronized SingletonClass getSingletonObject() { if (singletonObject == null) { singletonObject = new SingletonClass(). 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. public class SingletonClass { private static SingletonClass ourInstance = new SingletonClass().88 JAVA FOR BEGINNERS The below program shows the final Implementation of Singleton Design Pattern in java.println("Singleton object obtained"). //Compilation error not allowed SingletonClass obj = SingletonClass. . class SingletonClass { private static SingletonClass singletonObject. } public Object clone() throws CloneNotSupportedException { throw new CloneNotSupportedException(). // Your Business Logic System.getSingletonObject().out. } return singletonObject. /** A private Constructor prevents any other class from instantiating. 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. } } public class SingletonObjectDemo { public static void main(String args[]) { // SingletonClass obj = new SingletonClass(). public static SingletonClass getInstance() { return singletonObj. We can also make the singleton class final to avoid sub classing that may cause other problems. } private SingletonClass() { } } In Summary. Depending on your implementation. by using all the 4 steps mentioned above.

A thread is an independent path of execution within a program. Multithreading has several advantages over Multiprocessing such as. Every thread in Java is created and controlled by the java. . Many threads can run concurrently within a program.Thread class. • • • • • 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. and these threads can run concurrently. either asynchronously or synchronously.89 JAVA FOR BEGINNERS Java Threads Introduction to Threads Multithreading refers to two or more tasks executing concurrently within a single program. A Java program can have many threads.lang. The following figure shows the methods that are members of the Object and Thread Class.

2. providing the run() method that will be executed by the thread. An object of this class is a Runnable object. 3. A class implements the Runnable interface. public RunnableThread() { } .90 JAVA FOR BEGINNERS Thread Creation There are two ways to create thread in java.lang. The run() method contains the logic of the thread. either by normal completion or by throwing an uncaught exception. • • Implement the Runnable interface (java. The thread ends when the run() method ends. The Thread object now has a Runnable object that implements the run() method. An object of Thread class is created by passing a Runnable object as argument to the Thread constructor. Below is a program that illustrates instantiation and running of threads using the runnable interface instead of extending the Thread class. We need to override the run() method into our class which is the only method that needs to be implemented. 4. The procedure for creating threads based on the Runnable interface is as follows: 1. } One way to create a thread in java is to implement the Runnable Interface and then instantiate an object of the class. class RunnableThread implements Runnable { Thread runner. The start() method returns immediately after a thread has been spawned.Thread) Implementing the Runnable Interface The Runnable Interface Signature public interface Runnable { void run().lang.Runnable) By Extending the Thread class (java. To start the thread you need to invoke the start() method on your object. The start() method is invoked on the Thread object created in the previous step.

5.main] Thread[main. thread2.5. // (1) Create a new thread. } catch (InterruptedException e) { } //Display info about the main thread System.currentThread()). "thread2").sleep(1000). } public void run() { //Display info about this particular thread System.currentThread(). RunnableThread thread3 = new RunnableThread("thread3"). //Start the threads thread1.out.start().println(Thread.main] Thread[thread3. A class extending the Thread class overrides the run() method from the Thread class to define the code executed by the thread.currentThread()). runner. 3. Thread thread2 = new Thread(new RunnableThread(). The start() method inherited from the Thread class is invoked on the object of the class to make the thread eligible for running. using the super() call. This subclass may call a Thread constructor explicitly in its constructors to initialize the thread. "thread1").out.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. // (2) Start the thread. try { //delay for one second Thread.out.getName()).5. } } Output thread3 Thread[thread1. 2.println(runner.start(). Extending Thread Class The procedure for creating threads based on extending the Thread is as follows: 1. threadName).start().println(Thread. } } public class RunnableExample { public static void main(String[] args) { Thread thread1 = new Thread(new RunnableThread(). .91 JAVA FOR BEGINNERS public RunnableThread(String threadName) { runner = new Thread(this. System.5.main] Thread[thread2.

there are two reasons why implementing the Runnable interface may be preferable to extending the Thread class: . } } public class ThreadExample { public static void main(String[] args) { Thread thread1 = new Thread(new XThread().sleep(1000). Thread thread4 = new XThread().currentThread().start(). To start the thread you need to invoke the start() method on your object. Thread thread5 = new XThread("thread5"). start(). } } Output Thread[thread5.currentThread()). } catch (InterruptedException e) { } //Display info about the main thread System. "thread1"). Thread thread2 = new Thread(new XThread(). // Initialize thread.5.main] When creating threads. class XThread extends Thread { XThread() { } XThread(String threadName) { super(threadName).println(this). //Start the threads thread1.out.start().getName()).currentThread(). thread3.5.println(Thread.start().start().println(Thread. } public void run() { //Display info about this particular thread System. System. thread2. // The below 2 threads are assigned default names Thread thread3 = new XThread(). Thread.out. "thread2").main] thread1 thread5 thread2 Thread-3 Thread-2 Thread[main. thread4.92 JAVA FOR BEGINNERS Below is a program that illustrates instantiation and running of threads by extending the Thread class instead of implementing the Runnable interface. try { //The sleep() method is invoked on the main thread to cause a one second delay.out.

inheriting the full overhead of the Thread class would be excessive.out. Threads gain access to a shared resource by first acquiring the lock associated with the object/block of code. In non synchronized multithreaded application. Examples of using Thread Synchronization is in “The Producer/Consumer Model”. Synchronization prevents such type of data corruption which may otherwise lead to dirty reads and significant errors. 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. At any given time. } } ).start(). at most only one thread can hold the lock and thereby have access to the shared resource. –~~~~~~~~~~~~– Thread Synchronization With respect to multithreading. A lock thus implements mutual exclusion. whereas a class implementing the Runnable interface has this option.Generally critical sections of the code are usually marked with synchronized keyword. it is possible for one thread to modify a shared object while another thread is in the process of using or updating the object’s value.println(”Stop the world!”). The object lock mechanism enforces the following rules of synchronization: .. An example of an anonymous class below shows how to create a thread and start it: ( new Thread() { public void run() { for(.93 JAVA FOR BEGINNERS • • Extending the Thread class means that the subclass cannot extend any other class. A lock can be associated with a shared resource. A class might only be interested in being runnable.) System. Locks are used to synchronize access to a shared resource. and therefore.

Synchronized Methods Synchronized methods are methods that are used to control access to an object. The non-synchronized methods of the object can of course be called at any time by any thread. Classes also have a class-specific lock that is analogous to the object lock. it must wait for the lock to become available. 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. The class lock can be used in much the same way as an object lock to implement mutual exclusion. This restriction does not apply to the thread that already has the lock and is executing a synchronized method of the object. Such a lock is actually a lock on the java. A synchronized statement can only be executed after a thread has acquired the lock on the object/class referenced in the synchronized statement. If the ’synchronized’ keyword is removed. public class SyncMethodsExample extends Thread { .If the lock is already held by another thread. it can proceed to acquire the lock in order to gain access to the shared resource. it is blocked. A thread relinquishes the lock simply by returning from the synchronized method. the calling thread waits. Below is an example shows how synchronized methods and object locks are used to coordinate access to a common object by multiple threads. Given a class A. This is called a race condition. While a thread is inside a synchronized method of an object. A thread only executes a synchronized method after it has acquired the lock for the method’s object or class.lang.class denotes this unique Class object. . allowing the next thread waiting for this lock to proceed. 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. before it can enter the shared resource.  When a thread exits a shared resource. and as a consequence. If a thread cannot immediately acquire the object lock. the runtime system ensures that the object lock is also relinquished. the reference A. It occurs when two or more threads simultaneously update the same value.If another thread is waiting for this object lock. the message is displayed in random fashion. Such a method can invoke other synchronized methods of the object without being blocked. 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. that is.94 JAVA FOR BEGINNERS  A thread must acquire the object lock associated with a shared resource.Class object associated with the class. There can be 2 ways through which synchronized can be implemented in Java: • • synchronized methods synchronized blocks Synchronized statements are same as synchronized methods. leave the value in an undefined or inconsistent state.

println("Interrupted!").currentThread().start().isAlive()) { t2IsAlive = false. ".95 JAVA FOR BEGINNERS static String[] msg = { "Beginner". } public static void main(String[] args) { SyncMethodsExample thread1 = new SyncMethodsExample("thread1: "). boolean t2IsAlive = true. } } while (t1IsAlive || t2IsAlive).")."). } } } Output thread1: Beginner thread1: java thread1: tutorial.isAlive()) { t1IsAlive = false.out. t. "the". thread1: . System.random())). String list[]) { for (int i = 0.println("t1 is dead. } if (t2IsAlive && !thread2. "is".". msg). "java".start().length.randomWait(). "best" }.out.println("t2 is dead. "com". System. } catch (InterruptedException e) { System. thread1: com thread1: is thread1: the . thread2. boolean t1IsAlive = true. "tutorial.sleep((long) (3000 * Math. } void randomWait() { try { Thread. the message // is displayed in random fashion public static synchronized void displayList(String name. System. i < list. do { if (t1IsAlive && !thread1. public SyncMethodsExample(String id) { super(id).currentThread(). } } public synchronized void run() { SynchronizedOutput. thread1.out. i++) { SyncMethodsExample t = (SyncMethodsExample) Thread .displayList(getName(). } } class SynchronizedOutput { // if the 'synchronized' keyword is removed.. SyncMethodsExample thread2 = new SyncMethodsExample("thread2: ").out.".println(name + list[i])..

A subclass decides whether the new definition of an inherited synchronized method will remain synchronized in the subclass. thread2: . does not apply to static. 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. proceeds analogous to that of an object lock for a synchronized instance method. Class Locks Synchronized Blocks Static methods synchronize on the class lock. Synchronized statements can be nested. If execution of the block completes normally.. Synchronization of static methods in a class is independent from the synchronization of instance methods on objects of the class. The expression must evaluate to a non-null reference value. thread2: Beginner thread2: java thread2: tutorial.The synchronized block allows execution of arbitrary code to be synchronized on the lock of an arbitrary object. Acquiring and relinquishing a class lock by a thread in order to execute a static synchronized method. of course. otherwise. Synchronized statements with identical expressions can be nested. then the lock is released. which can be invoked at any time. then the lock is released. 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. thread2: com thread2: is thread2: the thread2: best t2 is dead. 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 } } . non-synchronized methods. The code block is usually related to the object on which the synchronization is being done. A thread can hold more than one lock at a time. If execution of the block completes abruptly. This is the case with synchronized methods.96 JAVA FOR BEGINNERS thread1: best t1 is dead. a NullPointerException is thrown. This.

// (2) } } } In the previous example. // … public void updateTransaction() { synchronized (account) { // (1) synchronized block account. This happens when the execution of the code block completes normally or an uncaught exception is thrown. even if the code block has just one statement. If several threads were to concurrently execute the method updateTransaction() on an object of SmartClient. However. in order to ensure integrity of data in the latter. unless enforced explicitly. synchronizing on an inner object and on its associated outer object are independent of each other. // (6) } } } } . the code at (2) in the synchronized block at (1) is synchronized on the BankAccount object.PI.97 JAVA FOR BEGINNERS Once a thread has entered the code block after acquiring the lock on the specified object. or any other code requiring the same object lock. 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). The braces of the block cannot be left out. // (2) protected class Inner { // (3) Non-static member Class public void setPi() { // (4) synchronized(Outer. by first acquiring the lock on the associated outer object. as in the following code: class Outer { // (1) Top-level Class private double myPi. 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. until the lock is relinquished. A class can choose to synchronize the execution of a part of a method.this) { // (5) Synchronized block on outer object myPi = Math. Object specification in the synchronized statement is mandatory. 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). If another thread has the lock of the associated outer object. class SmartClient { BankAccount account. no other thread will be able to execute the code block. only after synchronizing on the BankAccount object associated with this particular instance of SmartClient. Inner classes can access data in their enclosing context. by using the this reference and putting the relevant part of the method in the synchronized block. An inner object might need to synchronize on its associated outer object.update(). the statement at (2) would be executed by one thread at a time.

println("t2 is dead.isAlive()) { t2IsAlive = false. } } while (t1IsAlive || t2IsAlive).println(getName() + msg[i]). public class SyncBlockExample extends Thread { static String[] msg = { "Beginner".random())). "com". public SyncBlockExample(String id) { super(id). } } } } Output thread1: Beginner thread1: java thread1: tutorial.out. boolean t1IsAlive = true. i < msg.start(). "is". i++) { randomWait()..out. thread2.out) { for (int i = 0.".out. } } public void run() { synchronized (System. System.98 JAVA FOR BEGINNERS Below example shows how synchronized block and object locks are used to coordinate access to shared objects by multiple threads. "best" }.start(). SyncBlockExample thread2 = new SyncBlockExample("thread2: ").isAlive()) { t1IsAlive = false. boolean t2IsAlive = true.println("Interrupted!").length. } public static void main(String[] args) { SyncBlockExample thread1 = new SyncBlockExample("thread1: "). "java".sleep((long) (3000 * Math. } void randomWait() { try { Thread.. } catch (InterruptedException e) { System. thread1: . thread1: com thread1: is thread1: the thread1: best t1 is dead."). do { if (t1IsAlive && !thread1.println("t1 is dead.currentThread(). thread1. System.". "tutorial. System. "the". thread2: Beginner thread2: java .out."). ". } if (t2IsAlive && !thread2.

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 can hold a lock on an object • • • 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. A static synchronized method classAction() in class A is equivalent to the following declaration: static void classAction() { synchronized (A. sleeping. You can call only the start() .class) { // Synchronized block on class A // … } } In summary.. thread2: .class) { <code block> } The block synchronizes on the lock of the object denoted by the reference <classname>. thread2: com thread2: is thread2: the thread2: best t2 is dead. dead.99 JAVA FOR BEGINNERS thread2: tutorial.class. Synchronized blocks can also be specified on a class lock: synchronized (<class name>. A thread starts life in the Ready-to-run state. etc.

.100 JAVA FOR BEGINNERS or stop() methods when the thread is in this state. Note: Thread. Dead State A thread enters this state when the run() method has finished executing or when the stop() method is invoked. 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. and the name of the group to which it belongs. then its resume() method must be invoked  If a thread is waiting on a condition variable. the run() method put itself to sleep for one second and becomes Not Runnable during that period.  If a thread has been suspended. Whether or not it will actually start running depends on its priority and the availability of the CPU.sleep(1000). 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. Once in this state. whatever object owns the variable must relinquish it by calling either notify() or notifyAll().currentThread(). A Runnable thread may actually be running. then the I/O must complete. or may be awaiting its turn to run. Here. 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.currentThread() may return an output like Thread[threadA. Calling any method besides start() or stop() causes an IllegalThreadStateException. the priority of the thread. then the specified number of milliseconds must elapse (or it must be interrupted). 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. the thread cannot ever run again.5.main] The output shown in bold describes • • • the name of the thread.  If a thread is blocked on I/O. The thread is blocking on I/O and waits for its completion Example: Thread.

Time-Slicing or Round-Robin scheduling A running thread is allowed to execute for a fixed length of time (a time slot it’s assigned to). 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. the scheduler will preempt the running thread (is moved to the runnable state) and choose the new higher priority thread for execution.101 JAVA FOR BEGINNERS –~~~~~~~~~~~~– Thread Priority In Java we can specify the priority of each thread relative to other threads. or its run() method exits on systems that support time-slicing. the runtime system (the thread scheduler) chooses the Runnable thread with the highest priority for execution. . 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. after which it moves to the Ready-to-run state (runnable) to await its turn to run again. (Pre-emptive scheduling) it yields. “If two threads of the same priority are waiting for the CPU. You can modify a thread’s priority at any time after its creation using the setPriority() method and retrieve the thread priority value using getPriority() method. Heavy reliance on thread priorities for the behavior of a program can make the program non portable across platforms. the thread scheduler chooses one of them to run in a > round-robin fashion. When two or more threads are ready to be executed and system resource becomes available to execute a thread. Those threads having higher priority get greater access to available resources then lower priority threads. The chosen thread will run until one of the following conditions is true: • • • a higher priority thread becomes Runnable. A Java thread inherits its priority from the thread that created it. as thread scheduling is host platform–dependent.

The Thread class has several overloaded versions of the sleep() method. One thread gets the resource and the others go back to waiting. the call will result in an IllegalMonitorStateException. then the yield is ignored. how threads will be scheduled is unpredictable across different platforms. The notifyAll() method wakes up all the threads waiting on the resource. before entering the runnable state where it takes its turn to run again. therefore. Sleeping and Waking Up The thread class contains a static method named sleep() that causes the currently running thread to pause its execution and transit to the Sleeping state. otherwise. The threads execute wait() and notify() (or notifyAll()) methods on the shared object for this purpose. The yield() method gives other threads of the same priority a chance to run. wait() method signatures final void wait(long timeout) throws InterruptedException final void wait(long timeout. If there are no equal priority threads in the “Runnable” state. The thread will sleep for at least the time specified in its argument. it will throw an InterruptedException when it awakes and gets to execute. will cause the current thread in the Running state to move to the Runnable state. The thread is then at the mercy of the thread scheduler as to when it will run again. notify() and wait() are methods of the Object class. Waiting and Notifying Waiting and notifying provide means of thread inter-communication that synchronizes on the same object. If there are other threads in the Ready-to-run state. The notifyAll(). If a thread is interrupted while sleeping. notify() method signatures final void notify() final void notifyAll() . int nanos) throws InterruptedException final void wait() throws InterruptedException The wait() call can specify the time the thread should wait before being timed out. this thread continues execution. their priorities determine which thread gets to execute. the awakened threads compete for the resource.102 JAVA FOR BEGINNERS A thread scheduler is implementation and platform-dependent. defined in the Thread class. thus relinquishing the CPU. 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. The method does not relinquish any lock that the thread might have. If there are no threads waiting in the Ready-to-run state. Yielding A call to the static method yield(). These methods can be invoked only from within a synchronized context (synchronized method or synchronized block). In this situation.

A call to the notify() method has no consequences if there are no threads in the wait set of the object. The thread relinquishes ownership of the object lock. stackArray[topOfStack--] = null.println(Thread.println(Thread. System. wait(). is notified by another thread calling the notify() method on the same object class StackClass { private Object[] stackArray. private volatile int topOfStack.println(Thread.printStackTrace().103 JAVA FOR BEGINNERS A thread usually calls the wait() method on the object whose lock it holds because a condition for its continued execution was not met.out. Below program shows three threads. The waiting thread times out. } public synchronized Object pop() { System.out. This example illustrates how a thread waiting as a result of calling the wait() method on an object. and the waiting thread is selected as the thread to be awakened. There it waits for this condition to occur. 3.currentThread() + ": waiting to pop"). 2. } } Object obj = stackArray[topOfStack]. Another thread interrupts the waiting thread. A thread in the Waiting-for-notification state can be awakened by the occurrence of any one of these three incidents: 1. return obj. . } catch (InterruptedException e) { e. Notify Invoking the notify() method on an object wakes up a single thread that is waiting on the lock of this object. The thread leaves the Running state and transits to the Waiting-for-notification state. StackClass(int capacity) { stackArray = new Object[capacity]. The notifyAll() method wakes up all threads in the wait set of the shared object. manipulating the same stack.out. while the third one is popping elements off the stack. topOfStack = -1. notify(). The wait() method causes the current thread to wait until another thread notifies it of a condition change. while (isEmpty()) { try { System. 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. Two of them are pushing elements on the stack.currentThread() + ": popping").currentThread() + ": notifying after pop"). Another thread invokes the notify() method on the object of the waiting thread.

StackClass stack) { super(threadName). notify().currentThread() + ": waiting to push"). start(). } } } class StackPusher extends StackUser { // Stack Pusher StackPusher(String threadName.out.1. StackClass stack) { super(threadName. StackUser(String threadName.printStackTrace(). this. } } class StackPopper extends StackUser { // Stack Popper StackPopper(String threadName.currentThread() + ": notifying after push").out. } public void run() { while (true) { stack. wait().println(Thread. } catch (InterruptedException e) { e.currentThread() + ": pushing"). } } stackArray[++topOfStack] = element.pop().push(new Integer(1)).stack = stack.104 JAVA FOR BEGINNERS } public synchronized void push(Object element) { System. while (isFull()) { try { System.out. } public boolean isFull() { return topOfStack >= stackArray. StackClass stack) { super(threadName. } } abstract class StackUser extends Thread { protected StackClass stack. } public void run() { while (true) { stack. stack).out. System. setDaemon(true). System. } } } .println(this).println(Thread.length . } public boolean isEmpty() { return topOfStack < 0.println(Thread. stack).

printStackTrace(). during runtime.println("Exit from Main Thread. it means that the threads synchronize on the same object. stack). } } The field topOfStack in class StackClass is declared volatile.out. 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. it invokes the notify method. Once an other thread makes a pop. so that read and write operations on this variable will access the master value of this variable. new StackPusher("One". it invokes the notify method. Below is a program showing how threads invoke the overloaded thread join method. try { Thread. Since the threads manipulate the same stack object and the push() and pop() methods in the class StackClassare synchronized. stack). (1) The synchronized pop() method . Consider a thread t1 invokes the method join() on a thread t2. (2)The synchronized push() method . it invokes the wait() method in order to wait for some other thread to fill the stack by using the synchronized push. new StackPopper("Three". public class ThreadJoinDemo { public static void main(String[] args) { Thread t1 = new Thread("T1"). stack). then thread t1 transits to the Blockedfor-join-completion state.105 JAVA FOR BEGINNERS public class WaitAndNotifyExample { public static void main(String[] args) { StackClass stack = new StackClass(5). Thread t2 = new Thread("T2"). Once an other thread makes a push. If thread t2 is still alive. How the program uses wait() and notify() for inter thread communication.")."). and not any copies. .out.sleep(500).When a thread executing this method on the StackClass object finds that the stack is full.println("Main Thread sleeping. } catch (InterruptedException e) { e. System. The join() call has no effect if thread t2 has already completed.When a thread executing this method on the StackClass object finds that the stack is empty. } System. –~~~~~~~~~~~~– Joining A thread invokes the join() method on another thread in order to wait for the other thread to complete its execution. new StackPusher("Two".

Thread t1 at tries to synchronize first on string o1 and then on string o2.isAlive()) System. } catch (InterruptedException e) { System.println("Main Thread interrupted.println("Wait for the child threads to finish. t1. Exit from Main Thread. } System. It synchronizes first on string o2 then on string o1.out. String o2 = "Step ". t2.isAlive()) System.println("Thread T2 is not alive."). they both remain waiting forever in the Blocked-for-lockacquisition state. Below is a program that illustrates deadlocks in multithreading applications public class DeadLockExample { String o1 = "Lock ".out. Thread T2 is not alive.106 JAVA FOR BEGINNERS try { System.println("Exit from Main Thread."). The thread t2 does the opposite. The simplest form of deadlock is when two threads are each waiting on a resource that is locked by the other thread. Thread T1 is not alive. Thread t1 = (new Thread("Printer1") { public void run() { while (true) { synchronized (o1) { synchronized (o2) { System. } } Output Wait for the child threads to finish. } } } } }).out. Deadlock There are situations when programs become deadlocked when each thread is waiting on a resource that cannot become available.join().out.join().").println("Thread T1 is not alive. Hence a deadlock can occur as explained above. Since each thread is waiting for the other thread to relinquish a lock.println(o1 + o2). The threads are said to be deadlocked. if (!t2. if (!t1.").out. Thread t2 = (new Thread("Printer2") { public void run() { while (true) { .out.").

} } Note: The following methods namely join. which are designed to make it easier for you to create new and different implementations for handling collections of data. } } } } }). A program will terminate only when all user threads stop running. notify and notifyAll should only be called by a thread that holds the lock of the instance on which the method is invoked.util package. Some collections allow duplicate elements while others do not. dLock. The following methods namely wait. They are basically used to group multiple elements into a single unit. sleep and wait name the InterruptedException in its throws clause and can have a timeout argument as a parameter. the framework also provides several abstract implementations. A Collections Framework mainly contains the following 3 parts A Collections Framework is defined by a set of interfaces. The Thread. retrieved. Objects can be stored. Some implementations of the Thread.t2.start(). The 6 core Interfaces used in the Collection framework are: • Collection . and manipulated as elements of collections. A thread inherits its daemon status from the thread that created it Java Collections Framework A collection represents a group of objects.println(o2 + o1).start method causes a new thread to get ready to run at the discretion of the thread scheduler.out. public static void main(String[] args) { DeadLockExample dLock = new DeadLockExample().t1. Employee names database etc. Some collections are ordered and others are not. The Thread class implements the Runnable interface. concrete class implementations for most of the interfaces and a set of standard utility methods and algorithms. known as its elements.yield method will not yield to a thread of lower priority. dLock. Collection is a Java Interface. In addition.107 JAVA FOR BEGINNERS synchronized (o2) { synchronized (o1) { System. Collections can be used in various scenarios like Storing phone numbers. Core Collection Interfaces The core interfaces that define common functionality and allow collections to be manipulated independent of their implementation. This framework is provided in the java. The Runnable interface declares the run method.start().

providing data structures that a java program can use. Collection Interface Concrete Classes The concrete classes that are specific implementations of the core interfaces.108 JAVA FOR BEGINNERS • • • • • • Set List Iterator (Not a part of the Collections Framework) SortedSet Map SortedMap Note: Collection and Map are the two top-level interfaces. .

util. searching or creating customized collections. such as sorting. Hence primitive values cannot be stored in a collection directly. HashMap etc). They need to be encapsulated (using wrapper classes) into an Object prior to storing them into a Collection (such as HashSet. Thus. you get an Object rather then the actual type of the collection stored in the database. 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. How are Collections Used • • • The collections stores object references. Standard utility methods and algorithms that can be used to perform various operations on collections. The references are always stored as type Object. Hence we need to downcast it to the Actual Type while retrieving an element from a collection. rather than objects themselves.109 JAVA FOR BEGINNERS Note: Concrete Classes for the Map is shown in the previous section. . when you retrieve an element from a collection.*. Below is an example program showing the storing and retrieving of a few Collection Types import java.

Set s1 = new HashSet().put("Tutorial". } } Output ArrayList Elements [Beginner.out.put("Windows". System. Map m1 = new HashMap().out. s1.println(" ArrayList Elements").print("\t" + m1). s1. Java] Map Elements {Tutorial=Site. "98"). // or new TreeSet() will order the elements.println().add("Beginner"). System. "Java").out. Windows=98. Beginner=Java} Java Collections Source Code Examples On the following pages in this tutorial I have described how elements can be manipulated by different collections namely. .add("Java"). a1.out. l1. tutorial] LinkedList Elements [Beginner.println().out.110 JAVA FOR BEGINNERS public class CollectionsDemo { public static void main(String[] args) { List a1 = new ArrayList().print("\t" + l1). m1. System.put("Win". "Site"). System.add("Java").print("\t" + s1).add("tutorial"). Java. m1.println(" LinkedList Elements"). l1. System. a1. tutorial] Set Elements [tutorial.out. System. Win=XP. System.put("Beginner". // or new TreeMap() will order based on keys m1.add("Beginner").add("Beginner").out. s1. "XP"). m1.print("\t" + a1).add("tutorial").out.println(" Map Elements"). System. l1. Java.println(" Set Elements").println(). System. System.out.add("Java"). Beginner. List l1 = new LinkedList().out.add("Java"). a1. s1.add("tutorial"). System.out.

ArrayList. ArrayList’s give great performance on get() and set() methods.util. A java ArrayList is used to store an “ordered” group of elements where duplicates are allowed.Iterator.add("beginner"). import java.List. import java. import java. RandomAccess. Serializable • • • • • Resizable-array implementation of the List interface. Implements all optional list operations. An ArrayList capacity is the size of the array used to store the elements in the list. and listIterator operations run in constant time. Below is an ArrayList Example showing how collections are manipulated using an ArrayList import java. arraylistB. but do not perform well on add() and remove() methods when compared to a LinkedList."). except that it is unsynchronized.util. its capacity grows automatically.ListIterator.add(".util. // Adding elements to the ArrayList for (int i = 0.Collections. arraylistB. It is an Array based implementation where elements of the List can be accessed directly through get() method.synchronizedList(new ArrayList(…)). As elements are added to an ArrayList. List arraylistB = new ArrayList(). and permits all elements. i < 5. .111 JAVA FOR BEGINNERS • • • • • • • 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>.add("java").add("tutorial"). This class is similar to Vector. import java.util. The size. Cloneable.util. import java. arraylistB. including null.add(new Integer(i)). iterator. arraylistB. public class ArrayListExample { public static void main(String[] args) { // ArrayList Creation List arraylistA = new ArrayList().add("com"). get.Random. To prevent unsynchronized access to the list: List list = Collections. isEmpty. i++) { arraylistA. set.util. } arraylistB.

out.println(). Collections.println(arraylistA). } System. System. // Sort an ArrayList System. // Checking for Equality of ArrayLists ArrayList arraylistC = new ArrayList(arraylistA).println("ArrayList arraylistA --> ").next() + " . System. System.out. System. // Shuffling the elements of an ArrayList in Random Order .println("New Sub-List(arraylistA) from index 3 to " + arraylistA.out. System. System. // next().out.println(arraylistA.out.out.out.out. System.out.next() + " .out.next() + " .lastIndexOf("java"). Iterator i1 = arraylistA. } System.out.println().out.println("'java' was found at : " + lastIndex + " from the last").out. // Getting the subList from the original List List subList = arraylistA.out.add("java"). System.println("ArrayList arraylistA --> "). int lastIndex = arraylistB. hasNext() nextIndex() can be used with a // ListIterator interface implementation System.println("Sorted ArrayList arraylistA --> ").add("site"). System.println("ArrayList arraylistA --> "). System.println(li1.out.out.hasNext()) { System. System.sort(arraylistA). arraylistB.println().hasNext()) { System. // Iterating through the ArrayList to display the Contents.println().println(). Collections. hasNext().println("Using ListIterator to retrieve ArrayList Elements").println("'java' was found at : " + index). for (int j = 0.iterator().out. // Searching for an element in the ArrayList int index = arraylistB.indexOf("java").out.println().println(). System.out. System.println(i2.listIterator().size() + ": " + subList).get(j) + " .println(). while (li1.println(). while (i1. "). System. arraylistA. } System.out.reverse(arraylistA).subList(3.println("arraylistA. System.size().println("ArrayList arraylistB --> ").out. System. "). "). Iterator i2 = arraylistB.out.println(). j++) { System.112 JAVA FOR BEGINNERS arraylistB.println().size()).equals(arraylistC)).out . j < arraylistA. while (i2.println(arraylistA).out.iterator(). System.equals(arraylistC)? " + arraylistA.out.println("Is arraylistA empty? "+ arraylistA. ").out. System. } System.isEmpty()). hasPrevious().println(). ListIterator li1 = arraylistA.hasNext()) { System.out.out.out. // Reversing an ArrayList System. // Checking emptyness of an ArrayList System.println("Reversed ArrayList arraylistA --> ").out.println(i1.

println(i1.println("arraylistA after clearing : " + arraylistA). } } Output ArrayList arraylistA –> 0 . 4] Sorted ArrayList arraylistA –> [0.out . i < array. System. 0] Is arraylistA empty? false arraylistA.out. 2 . Array Element [0] = 3 Array Element [1] = 2 Array Element [2] = 1 Array Element [3] = 0 Array Element [4] = 4 arraylistA after clearing : [] . i1 = arraylistA. for (int i = 0. 2 . System. 1 . 3 . 4 . 2. } System. 2 . } System. System.hasNext()) { System.println().iterator(). new Random()). 4] Reversed ArrayList arraylistA –> [4. System. ‘java’ was found at : 1 ‘java’ was found at : 5 from the last New Sub-List(arraylistA) from index 3 to 5: [3. java . 3.out. . // Clearing ArrayList Elements arraylistA.println("ArrayList arraylistA after shuffling its elements--> "). 0 . 3 . 4 . ArrayList arraylistA –> 0 . 1.out.toArray(). Using ListIterator to retrieve ArrayList Elements ArrayList arraylistA –> 0. i++) { System. 1 .clear(). 3.1. site . . com .113 JAVA FOR BEGINNERS Collections.out.next() + " .equals(arraylistC)? true ArrayList arraylistA after shuffling its elements–> 3 . java . 2. tutorial .println(). ").shuffle(arraylistA.length.out. 4 .println().3. // Converting an ArrayList to an Array Object[] array = arraylistA.out.4. 1 . ArrayList arraylistB –> beginner .println().out.println("Array Element [" + i + "] = " + array[i]).2. while (i1. 1.

add("java").hasNext()) { System.iterator(). } System.util.println("LinkedList linkedListB --> "). linkedListB.List.util.add("site"). } linkedListB. List linkedListB = new LinkedList(). import java. linkedListB.Random. ").add("java"). import java. j++) { System. import java. linkedListB.println(). linkedListB.114 JAVA FOR BEGINNERS Linked List • • A LinkedList is used to store an “ordered” group of elements where duplicates are allowed.add(".out. System.out. linkedListB.println().println("LinkedList linkedListA --> "). A LinkedList is based on a double linked list where elements of the List are typically accessed through add() and remove() methods.ListIterator.println(i1.LinkedList.size(). Iterator i2 = linkedListB.iterator().add("beginner").util. // Iterating through the LinkedList to display the Contents.util. import java.util.out. Iterator i1 = linkedListA. "). . for (int j = 0.println(linkedListA.get(j) + " .println("LinkedList linkedListA --> ").out. while (i1.next() + " . // Adding elements to the LinkedList for (int i = 0. i++) { linkedListA. import java.util. linkedListB.add("com").out. } System.Collections. i < 5. System."). Below is an LinkedList Example showing how collections are manipulated using an LinkedList import java.add(new Integer(i)).Iterator. System. j < linkedListA.out.out.add("tutorial"). public class LinkedListExample { public static void main(String[] args) { // LinkedList Creation List linkedListA = new LinkedList().

println("Reversed LinkedList linkedListA --> ").println("New Sub-List(linkedListA) from index 3 to " + linkedListA.115 JAVA FOR BEGINNERS // while (i2.listIterator(). .lastIndexOf("java").hasNext()) { System.out.out.println("Is linkedListA empty? "+ linkedListA.out.println("Sorted LinkedList linkedListA --> "). "). new Random()). // Sort an LinkedList System.println("linkedListA.println().println(i2. Collections.hasNext()) { System.out.out. ListIterator li1 = linkedListA. // Checking for Equality of LinkedLists LinkedList LinkedListC = new LinkedList(linkedListA). System. System.println(). linkedListA.equals(LinkedListC)).println().out. "). hasPrevious().out. } System.println("Using ListIterator to retrieve LinkedList Elements").println().equals(LinkedListC)? " + linkedListA.println(). // Searching for an element in the LinkedList int index = linkedListB.subList(3. while (li1. System. // Checking emptyness of an LinkedList System. // Getting the subList from the original List List subList = linkedListA. } System.out.out. ").next() + " .println("'java' was found at : " + lastIndex+ " from the last").out.sort(linkedListA).out. System.out.println().out. Shuffling the elements of an LinkedList in Random Order Collections.shuffle(linkedListA.out.println("'java' was found at : " + index).out. System.out.println(li1. System.next() + " .println(). int lastIndex = linkedListB. System. System. i1 = linkedListA. System.out.println(linkedListA).println("LinkedList linkedListA after shuffling its elements--> "). System.indexOf("java").size()). // Reversing an LinkedList System.println("LinkedList linkedListA --> ").out.iterator().println().out. // next().println().out. System.out. while (i1. System.out. System. System.isEmpty()). Collections.println().size() + ": " + subList).out. System.out.println(i1.hasNext()) { System. System. hasNext().next() + " .println(linkedListA).reverse(linkedListA). hasNext() nextIndex() can be used with a // ListIterator interface implementation System.out.

println("linkedListA after clearing : " + linkedListA). 4] Reversed LinkedList linkedListA –> [4. i++) { System.println(). 3. System.println("Array Element [" + i + "] = " + array[i]). 2.clear().out. 1 . 2 . System. // Converting an LinkedList to an Array Object[] array = linkedListA. ‘java’ was found at : 1 ‘java’ was found at : 5 from the last New Sub-List(linkedListA) from index 3 to 5: [3. tutorial . site .equals(LinkedListC)? true LinkedList linkedListA after shuffling its elements–> 3 .2. 2 . for (int i = 0.out.out. com . 4 .toArray().println().1. java .3. 1 . 2 . // Clearing LinkedList Elements linkedListA.println(). Array Element [0] = 3 Array Element [1] = 2 Array Element [2] = 4 Array Element [3] = 0 Array Element [4] = 1 linkedListA after clearing : [] . 4 . 0] Is linkedListA empty? false linkedListA. java . 3 . LinkedList linkedListA –> 0 . 3 .out. 0 . 3.out.out.116 JAVA FOR BEGINNERS } System. System. } } Output LinkedList linkedListA –> 0 . 2.length. } System. 4] Sorted LinkedList linkedListA –> [0. 1. 4 . 1 . i < array. Using ListIterator to retrieve LinkedList Elements LinkedList linkedListA –> 0. 1.4. . .println(). LinkedList linkedListB –> beginner .

// the treeset stores Integer objects into the TreeSet for (int i = 0. i++) { treeSet. } // Since its a Integer Object Set adding any other elements in the Same // set will produce a // ClassCastException exception at runtime. import java. import java. Serializable • • This class implements the Set interface and guarantees that the sorted set will be in ascending element order. remove and contains).synchronizedSortedSet(new TreeSet(. System. depending on which constructor is used.println("The elements of the TreeSet are : ").println(i. } } } Output The elements of the TreeSet are : 0 1 2 3 4 . sorted according to the natural order of the elements or by the comparator provided at set creation time. To prevent unsynchronized access to the Set. Iterator i = treeSet.: SortedSet s = Collections.TreeSet.add(new Integer(i)). while (i.next() + "\t").util.)).util.iterator().add("a string").out. Below is a TreeSet Example showing how collections are manipulated using a TreeSet import java. i < 5.out.Iterator.117 JAVA FOR BEGINNERS TreeSet public class TreeSet<E> extends AbstractSet<E> implements SortedSet<E>.hasNext()) { System..Set. public class TreeSetExample { public static void doTreeSetExample() { } public static void main(String[] args) { Set treeSet = new TreeSet(). // treeSet. This implementation not synchronized provides guaranteed log(n) time cost for the basic operations (add. Cloneable.util.

To prevent unsynchronized access to the Map: Map m = Collections.new Integer("1")). if (cnt == null) { counter. System. private static Integer cnt = null. "scot".put(new Character(names[i]. If multiple threads access this map concurrently. i++) { cnt = (Integer) (counter. } } System. This implementation provides constant-time performance for the basic operations (get and put).118 JAVA FOR BEGINNERS HashMap • • • The java HashMap class does not guarantee that the order will remain constant over time.toString()). "hhh".length. private static HashMap counter = new HashMap(). */ import java. assuming the hash function disperses the elements properly among the buckets.out.println(counter.out. } } Output number of words beginning with each letter is shown below {s=3. "keeth" }.intValue() + 1)). b=1. public class HashMapExample { static String[] names = { "heman".println("\nnumber of words beginning with each letter is shown below "). The HashMap implementation is not synchronized. 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.HashMap.util. new Integer(cnt.charAt(0)). "bob".synchronizedMap(new HashMap(…)). "shawn". and at least one of the threads modifies the map structurally.charAt(0)). h=2} . i < names."shan". public static void main(String args[]) { for (int i = 0. it must be synchronized externally.put(new Character(names[i].get(new Character(names[i]. k=1. } else { counter.charAt(0)))).

swing.event. Below is a Vector Example showing how collections are manipulated using a Vector import java. import java. import java.JLabel. } }).JButton. public class VectorDemo extends JFrame { private JLabel jlbString = new JLabel("Enter a string").awt.awt.ActionEvent.event.event.Container. import java.util.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { .setLayout(new FlowLayout()).add(jbnAdd).ActionListener. contentPane. Cloneable. import java.swing. RandomAccess.getText().awt. import java.setText("Appended to end: "+ jtfInput.swing.NoSuchElementException. it contains components that can be accessed using an integer index. Like an array. import java. contentPane. import javax. Serializable • • • The Vector class implements a growable array of objects where the size of the vector can grow or shrink as needed dynamically. import java. jtfInput.Vector. contentPane.FlowLayout.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { vector. jbnAdd.add(jtfInput). jlbStatus.WindowAdapter.getText(). Container contentPane = getContentPane(). JButton jbnRemove = new JButton("Remove").util. final JTextField jtfInput = new JTextField(10).swing. // Made final as it can be accessed by inner classes final JLabel jlbStatus = new JLabel(). final Vector vector = new Vector(1).JTextField. public VectorDemo() { super("Vector class demo"). jbnRemove.awt.WindowEvent.add(jlbString).119 JAVA FOR BEGINNERS Vector public class Vector<E> extends AbstractList<E> implements List<E>.Enumeration.awt. import javax. import javax. JButton jbnAdd = new JButton("Add"). import javax.JFrame.swing. import javax.addElement(jtfInput.event.JOptionPane.trim()).util.trim()).awt. import java.setText(""). contentPane. this reduces the amount of incremental reallocation. An application can increase the capacity of a vector before inserting a large number of components.

addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { jlbStatus.trim().add(jbnRemove).indexOf(jtfInput. } .add(jbnContains). } else { jlbStatus.setText("Element found at location " + vector. } } }).add(jbnFirst). contentPane. jbnEmpty. jbnContains.setText("Last element: " + vector.firstElement()).addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { jlbStatus.removeElement(jtfInput. } } }).addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String searchKey = jtfInput.trim()+ " not in vector"). jbnLast. JButton jbnLast = new JButton("Last"). JButton jbnFindElement = new JButton("Find").isEmpty() ? "Vector is empty": "Vector is not empty"). JButton jbnEmpty = new JButton("Is Empty?"). contentPane.add(jbnEmpty).trim())). } } }). } catch (NoSuchElementException exception) { jlbStatus.120 JAVA FOR BEGINNERS // Returns true if element in vector if (vector.setText(exception. } }).addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { jlbStatus.setText("Removed: " + jtfInput.setText("First element: " + vector.trim())) jlbStatus.lastElement()). } }).setText(jtfInput. JButton jbnFirst = new JButton("First").setText("Vector contains " + searchKey). jbnFirst. contentPane. contentPane. contentPane.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { jlbStatus.getText()).setText(exception.add(jbnLast).getText().setText("Vector does not contain " + searchKey).getText().getText().contains(searchKey)) { jlbStatus.toString()). else jlbStatus. if (vector. jbnFindElement.toString()).getText(). } catch (NoSuchElementException exception) { jlbStatus. JButton jbnContains = new JButton("Contains").setText(vector.

setText("Size = " + vector.exit(0). } }).hasMoreElements()) buf. setSize(300.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Enumeration enum1 = vector. JOptionPane.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { jlbStatus.trimToSize().addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { vector. contentPane. "Contents of Vector". setVisible(true). while (enum1. jlbStatus.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System. contentPane. } }). JButton jbnSize = new JButton("Size/Capacity").add(jbnFindElement). } }). jbnTrim. buf. contentPane.add(jbnSize). Capacity = " + vector. contentPane.add(jbnDisplay).nextElement()).setText("Vector trimmed to size"). } }). StringBuffer buf = new StringBuffer().elements(). JButton jbnDisplay = new JButton("Display"). } } Output .PLAIN_MESSAGE).add(jlbStatus).add(jbnTrim).121 JAVA FOR BEGINNERS }).capacity()). JButton jbnTrim = new JButton("Trim"). vectorDemo. contentPane.toString(). jbnDisplay.append(enum1. jbnSize. JOptionPane. } public static void main(String args[]) { VectorDemo vectorDemo = new VectorDemo().showMessageDialog(null. 200).size() + ".append(" ").

jplNorthSub.add(jlbStatus.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String strNum = jtfPhone. if (val == null) jlbStatus. JPanel jplNorthSub = new JPanel(). Object val = hashTable. jplNorth.trim().add(jtfPhone). 5)). if ((strNum != null && strNum.put(strName.add(new JLabel("Phone No")). jplNorthSub. display.setText("Added: " + emp.this. jplNorth. final JTextArea display = new JTextArea(4.add(jtfFirstName).showMessageDialog(HashTableDemo. num). jplNorthSub. try { num = Integer. } EmployeeDetails emp = new EmployeeDetails(strName. emp).setEditable(false). } int num = 0. // Demonstrates the Hashtable class of the java. Hashtable doesn’t 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.trim(). final JTextField jtfFirstName = new JTextField(8).getText(). BorderLayout. else . 20). Iterator in the HashMap is fail-safe while the enumerator for the Hashtable isn’t.add(jplNorthSub.util package.equals(""))) { JOptionPane.setLayout(new BorderLayout()). jplNorth. "Please enter both Name and Phone No").equals("")) || (strName != null && strName. BorderLayout.122 JAVA FOR BEGINNERS HashTable • • • HashTable is synchronized. } catch (NumberFormatException ne) { ne. jplNorthSub. final JLabel jlbStatus = new JLabel(). JPanel jplNorth = new JPanel().toString()). String strName = jtfFirstName.parseInt(strNum). final Hashtable hashTable = new Hashtable(). jbnAdd.SOUTH).4. jplSouth. final JTextField jtfPhone = new JTextField(8).NORTH).setLayout(new GridLayout(2. JButton jbnAdd = new JButton("Add").getText().printStackTrace(). JPanel jplSouth = new JPanel(). return.add(new JLabel("Name (Key)")). public class HashTableDemo extends JFrame { public HashTableDemo() { super(" Hashtable Sourcecode Example").

jbnGet.getText(). } }). jplSouth.setText("Added: " + emp. JButton jbnContains = new JButton("Contains key").setText("HashTable Emptied"). jplSouth. } }). JButton jbnRemove = new JButton("Remove Name").addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Object val = hashTable.get(jtfFirstName.getText()+" not in table"). else jlbStatus. JButton jbnDisplay = new JButton("List objects").add(jbnContains).isEmpty()).toString()).add(jbnGet).toString() + ".addActionListener(new ActionListener() { . } }).addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Object val = hashTable.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { hashTable. jbnDisplay. } }).setText("Remove: " + val. jbnContains.getText() .remove(jtfFirstName. JButton jbnClear = new JButton("Clear table").setText("Get: " + jtfFirstName.getText()+ " not in table"). Replaced: " + val. } }). jbnClear.containsKey(jtfFirstName. jplSouth.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { jlbStatus.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { jlbStatus.toString()).123 JAVA FOR BEGINNERS jlbStatus. else jlbStatus. JButton jbnIsEmpty = new JButton("Empty ?").setText("Contains key: "+ hashTable.setText("Remove: " + jtfFirstName.trim())). jplSouth.toString()). jlbStatus.setText("Empty: " + hashTable. JButton jbnGet = new JButton("Get").trim()). jplSouth. } }).getText(). jbnRemove.trim()). jplSouth.clear().add(jbnClear). if (val != null) jlbStatus.setText("Get: " + val. jbnIsEmpty. if (val != null) jlbStatus.add(jbnIsEmpty).add(jbnRemove).add(jbnAdd).

jbnKeys.elements(). JOptionPane. } } Output .JOptionPane.setText(buf.CENTER).) buf.append('\n').add(jbnKeys).PLAIN_MESSAGE).exit(0).add(new JScrollPane(display). } }).addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { StringBuffer buf = new StringBuffer().keys(). 300). for (Enumeration enum = hashTable.NORTH). BorderLayout.SOUTH). } public static void main(String args[]) { HashTableDemo hashTableDemo = new HashTableDemo(). c.append(enum. for (Enumeration enum = hashTable.nextElement()). enum. jplSouth.) buf. c.hasMoreElements(). jplSouth.enum."Display Keys of HashTable ".nextElement()).toString().toString()). JButton jbnKeys = new JButton("List keys").showMessageDialog(null.add(jplSouth. BorderLayout. display. c. } public String toString() { return name + " " + phoneNp. } }). int phNo) { name = fName. setSize(540.append('\n'). public EmployeeDetails(String fName.hasMoreElements(). private int phoneNp.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.add(jbnDisplay).append(enum. phoneNp = phNo. setVisible(true). BorderLayout.124 JAVA FOR BEGINNERS public void actionPerformed(ActionEvent e) { StringBuffer buf = new StringBuffer(). buf. } } class EmployeeDetails { private String name. Container c = getContentPane().add(jplNorth. } }). hashTableDemo.

out.out.next() + " "). aList = new ArrayList(Arrays.iterator().println().out. while (i. // create a HashSet Iterator i = ref. To prevent unsynchronized access to the Set: Set s = Collections.println("Unique names are: ").hasNext()) System. mike. hemanth. This class is not synchronized and permits a null element. Below is a HashSet Example showing how collections are manipulated using a HashSet import java. remove.*. System. It makes no guarantee that the order of elements will remain constant over time. shawn. "hhh". hero. public static void main(String args[]) { ArrayList aList.125 JAVA FOR BEGINNERS HashSet • • • • • The HashSet class implements the Set interface. HashSet ref = new HashSet(aList). assuming the hash function disperses the elements properly among the buckets.println("The names elements " + aList). This class offers constant time performance for the basic operations (add. System. "hemanth". "hemanth".println(i. "undertaker" }. } } Output The names elements [bob. "shawn".asList(names)). "rock". System. Rick.out. contains and size). hemanth. "hero". "mike". hhh.synchronizedSet(new HashSet(…)).out. "mike".println(). System. "Rick". rock. mike. public class HashSetExample { private static String names[] = { "bob".util. undertaker] Unique names are: hhh hero bob Rick shawn hemanth rock mike undertaker . "bob". bob.

Time. Serializable Direct Known Subclasses: Date.util. . Comparable.Object extended by java.126 JAVA FOR BEGINNERS Java Date Utility Java Date API java. with millisecond precision. Timestamp public class Date extends Object implements Serializable.util.lang.Date All Implemented Interfaces: Cloneable. Cloneable. Comparable The class Date represents a specific instant in time. Class Date java.

import java.println("-------------------------------------"). public class DateUtility { /* Add Day/Month/Year to a Date add() is used to add values to a Calendar object. System. See the following example.DATE). Calendar c1 = Calendar.text.println("2.set(1999.text. import java.127 JAVA FOR BEGINNERS Java Date Source Code import java. The operation only affects the specified field while add() adjusts other Calendar fields.YEAR.getInstance(). Add to a Date Operation\n").util. You specify which Calendar field is to be affected by the operation (Calendar.Calendar.20) : " + c1.add(Calendar. roll() makes january rolls to december in the same year while add() substract the YEAR field for the correct result.getInstance(). import java. public static void addToDate() { System. // System.util.getTime()).ParseException.get(Calendar.format(c1. */ public static final String DATE_FORMAT = "dd-MM-yyyy". Subtract to a date Operation\n"). Hence add() is preferred even for subtraction by using a negative element. You specify which Calendar field is to be affected by the operation (Calendar. Calendar c1 = Calendar. c1.month.println("c1. } /*Substract Day/Month/Year to a Date roll() is used to substract values to a Calendar object. Calendar.SimpleDateFormat.get(Calendar.Date. Calendar. SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT).0 . 20).DateFormat. c1.out. System. simply use a negative argument.DATE). 0. import java.println("c1. . SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT).println().text.MONTH. 20).YEAR. System.println("Date + 20 days is : "+ sdf. System.println("1.out.getTime() : " + c1.println("Todays date in Calendar Format : "+c1). //See Java DOCS for different date formats // public static final String DATE_FORMAT = "yyyy-MM-dd".date) System.out. roll() does the same thing except you specify if you want to roll up (add 1) or roll down (substract 1) to the specified Calendar field.out. c1. Note: To substract.YEAR)). //(year.getTime()). */ public static void subToDate() { System.set(1999.out. 20).out.out.out. Date d1 = new Date().out.set(1999. //Gets a calendar using the default time zone and locale. Calendar.getTime())).MONTH.out. System.YEAR): "+ c1.println("Todays date in Date Format : " + d1).DATE.println("c1. System. Calendar. 0.

128 JAVA FOR BEGINNERS
System.out.println("Date is : " + sdf.format(c1.getTime())); // roll down, substract 1 month c1.roll(Calendar.MONTH, false); System.out.println("Date roll down 1 month : "+ sdf.format(c1.getTime())); c1.set(1999, 0, 20); System.out.println("Date is : " + sdf.format(c1.getTime())); c1.add(Calendar.MONTH, -1); // substract 1 month System.out.println("Date minus 1 month : "+ sdf.format(c1.getTime())); System.out.println(); System.out.println("-------------------------------------"); } public static void daysBetween2Dates() { System.out.println("3. No of Days between 2 dates\n"); Calendar c1 = Calendar.getInstance(); //new GregorianCalendar(); Calendar c2 = Calendar.getInstance(); //new GregorianCalendar(); c1.set(1999, 0, 20); c2.set(1999, 0, 22); System.out.println("Days Between " + c1.getTime() + " and " + c2.getTime() + " is"); System.out.println((c2.getTime().getTime() - c1.getTime() .getTime()) / (24 * 3600 * 1000)); System.out.println(); System.out.println("-------------------------------------"); } public static void daysInMonth() { System.out.println("4. No of Days in a month for a given date\n"); Calendar c1 = Calendar.getInstance(); // new GregorianCalendar(); c1.set(1999, 6, 20); int year = c1.get(Calendar.YEAR); int month = c1.get(Calendar.MONTH); // int days = c1.get(Calendar.DATE); int[] daysInMonths = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30,31 }; daysInMonths[1] += DateUtility.isLeapYear(year) ? 1 : 0; System.out.println("Days in " + month + "th month for year" + year + "is " + daysInMonths[c1.get(Calendar.MONTH)]); System.out.println(); System.out.println("-------------------------------------"); } public static void validateAGivenDate() { System.out.println("5. Validate a given date\n"); String dt = "20011223"; String invalidDt = "20031315"; String dateformat = "yyyyMMdd"; Date dt1 = null, dt2 = null; try { SimpleDateFormat sdf = new SimpleDateFormat(dateformat); sdf.setLenient(false); dt1 = sdf.parse(dt); dt2 = sdf.parse(invalidDt); System.out.println("Date is ok = " + dt1 + "(" + dt + ")"); } catch (ParseException e) { System.out.println(e.getMessage()); } catch (IllegalArgumentException e) {

129 JAVA FOR BEGINNERS
System.out.println("Invalid date"); } System.out.println(); System.out.println("-------------------------------------"); } public static void compare2Dates() { System.out.println("6. Comparision of 2 dates\n"); SimpleDateFormat fm = new SimpleDateFormat("dd-MM-yyyy"); Calendar c1 = Calendar.getInstance(); Calendar c2 = Calendar.getInstance(); c1.set(2000, 02, 15); c2.set(2001, 02, 15); System.out.println(fm.format(c1.getTime()) + " is "); if (c1.before(c2)) { System.out.println("less than " + fm.format(c2.getTime())); } else if (c1.after(c2)) { System.out.println("greater than " + fm.format(c2.getTime())); } else if (c1.equals(c2)) { System.out.println("is equal to " + fm.format(c2.getTime())); } System.out.println(); System.out.println("-------------------------------------"); } public static void getDayofTheDate() { System.out.println("7. Get the day for a given date\n"); Date d1 = new Date(); String day = null; DateFormat f = new SimpleDateFormat("EEEE"); try { day = f.format(d1); } catch (Exception e) { e.printStackTrace(); } System.out.println("The day for " + d1 + " is " + day); System.out.println(); System.out.println("-------------------------------------"); } //Utility Method to find whether an Year is a Leap year or Not public static boolean isLeapYear(int year) { if ((year % 100 != 0) || (year % 400 == 0)) { return true; } return false; } public static void main(String args[]) { addToDate(); //Add day, month or year to a date field. subToDate(); //Subtract day, month or year to a date field. daysBetween2Dates(); //The "right" way would be to compute the Julian day number of //both dates and then do the subtraction. daysInMonth();//Find the number of days in a month for a date validateAGivenDate();//Check whether the date format is proper compare2Dates(); //Compare 2 dates

130 JAVA FOR BEGINNERS
getDayofTheDate(); } }

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 ——————————————————-

131 JAVA FOR BEGINNERS What is the GregorianCalendar class? The GregorianCalendar provides support for traditional Western calendars. the GUI component will not be displayed when the container appears on the screen. etc Compiling & running programs • ‘javac <program. . What is the SimpleTimeZone class? The SimpleTimeZone class provides support for a Gregorian calendar.java>’ && ‘java <program>’ Or JCreator / IDE • if you do not explicitly add a GUI component to a container. 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.

Swing Model/view design: The “view part” of the MV design is implemented with a component object and the UI object. or change listener classes without having to reinvent the entire implementation. descended directly from Container. For example. swing components such as JSlider. which is an extension library to the AWT. Components from AWT and Swing can be mixed. Swing also has the ability to replace these objects on-the-fly. is the root class for most of Swing’s user interface components. . Some examples are JButton. Altogether there are more than 250 new classes and 75 interfaces in Swing — twice as many as in AWT. classes that represent GUI components have names beginning with the letter J. JLabel. You could subclass the existing Swing UI. Java Swing class hierarchy The class JComponent. Swing is more portable and more flexible than AWT. and JSlider. Swing is built on top of AWT and is entirely written in Java.132 JAVA FOR BEGINNERS Swing. t he architecture of Swing components makes it easy to customize both their appearance and behavior. textfields and scrollbars. using AWT’s lightweight component support. Swing can be used to build Standalone swing gui Apps as well as Servlets and Applets. In particular. The “model part” of the MV design is implemented by a model object and a change listener object. • • • • 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. model. It employs a model/view design architecture. allowing you to add Swing support to existing AWT-based programs. includes new and improved components that enhance the look and functionality of GUIs. JButton and JCheckbox could be used in the same program with standard AWT labels. unlike AWT.

Basically. the idea behind this Hello World program is to learn how to create a java program. setVisible(true). compile and run it. this.swing. add(jlbHelloWorld).setSize(100.swing. //import statements //Check if window closes automatically. 100).JLabel. } HelloWorldFrame() { JLabel jlbHelloWorld = new JLabel("Hello World"). import javax. Otherwise add suitable code public class HelloWorldFrame extends JFrame { public static void main(String args[]) { new HelloWorldFrame(). Java Swing Examples Below is a java swing code for the traditional Hello World program. // pack(). AWT Programming knowledge is not required. } } Output . To create your java source code you can use any editor( Text pad/Edit plus are my favorites) or you can use an IDE like Eclipse.133 JAVA FOR BEGINNERS Swing contains components that you’ll use to build a GUI. I am listing you some of the commonly used Swing components. import javax. To learn and understand these swing programs.JFrame.

Like Dialog. when the component has focus. The underlying JScrollPane can be forced to always or never have either the vertical or horizontal scrollbar. A set of radio buttons can be associated as a group in which only one button at a time can be selected. JFrame is Swing’s version of Frame and is descended directly from that class. JList provides a scrollable set of items from which one or more may be selected. JButton is a component the user clicks to trigger a specific action. JComboBox is like a drop down box. or center. the list must be associated with a scrollpane. JTextField allows editing of a single line of text. some of the most common dialogs are provided through static methods in the class JOptionPane. By default. instead. JPasswordField (a direct subclass of JTextField) you can suppress the display of input. the echo character is the asterisk. JDialog contains a rootPane hierarchy including a contentPane. For example. Each character entered can be replaced by an echo character. for example. A vertical scrollbar is used for longer lists. Like Window. . You can click a drop-down arrow and select an option from a list. however. To add a component to a JFrame. it uses BorderLayout by default. JDialog is Swing’s version of Dialog and is descended directly from that class. JWindow is Swing’s version of Window and is descended directly from that class. FlowLayout. we must use its contentPane instead. Like JFrame and JWindow. right. pressing a key that corresponds to the first character in some entry’s name selects that entry. and to set the text’s font. JList actions are handled using ListSelectionListener. JTextArea can be used in conjunction with class JScrollPane to achieve scrolling. It can be iconified . New features include the ability to justify the text left. JList does not support scrolling directly. and it also displays its current state. it uses BorderLayout by default. This allows confidential input for passwords. these are managed by the contentPane. JRadioButton is similar to JCheckbox. descended from JComponent. The view port used by the scroll pane can also have a user-defined border. *. • • • • • • • • • • • • • • JPanel is Swing’s version of the AWT class Panel and uses the same default layout. JCheckBox is not a member of a checkbox group. except for the default icon for each class. The abstract class AbstractButton extends class JComponent and provides a foundation for a family of button classes. JPanel is descended directly from JComponent. JList can be populated from an Array or Vector. JTextArea allows editing of multiple lines of text. including JButton.134 JAVA FOR BEGINNERS Note: Below are some links to java swing tutorials that forms a helping hand to get started with java programming swing. All dialogs are modal. A checkbox can be selected and deselected. and it allows layered and glass panes. JInternalFrame is confined to a visible area of a container it is placed in. is used to create text labels. maximized and layered. JLabel. JDialog class is intended as the basis for creating custom dialogs. The components added to the frame are referred to as its contents. which means the current thread is blocked until user interaction with it has been completed.

GridBagLayout is a layout manager that lays out a container’s components in a grid of cells with each component occupying one or more cells. The display area aligns components vertically and horizontally. query the table. and update the table with the help of a JDBC Program example. Java Swing Projects • • Java Swing Calculator developed using Java Swing. You can add horizontal and vertical gaps between the areas. Swing provides support for pull-down and popup menus. Using JDBC you can send SQL. retrieve results. PL/SQL statements to almost any relational database. BorderLayout places swing components in the North. FlowLayout when used arranges swing components from left to right until there’s no more space available. Each of the JMenu’s can contain a series of JMenuItem ’s that you can select. Java Swing Address Book demonstrates how to create a simple free address book program using java swing and jdbc. It is a basic four-function calculator java program source code. without requiring that the components be of the same size. South. 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. applets embedded in Web pages can contain downloadable JDBC code to enable remote database access. and it can display both text and an image. You will learn how to create a table. . West and center of a container. JDBC is a Java API for executing SQL statements and supports basic SQL functionality. and one component is placed in each rectangle. Each component in a FlowLayout gets as much space as it needs and no more. JMenubar can contain several JMenu’s. insert values into it. 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. Also you will learn to use the following swing components like Jbuttons. It provides RDBMS access by allowing you to embed SQL inside Java code. GridLayout is a layout manager that lays out a container’s components in a rectangular grid. East. The container is divided into equal-sized rectangles. Because Java can run on a thin client. JTextFields and Layout Manager (GridBagLayout). Then it begins a new row below it and moves from left to right again.135 JAVA FOR BEGINNERS • • • • • • • • JTabbedPane contains a tab that can have a tool tip and a mnemonic. Java JDBC The JDBC ( Java Database Connectivity) API defines interfaces and classes for writing database applications in Java by making database connections. JFrames. called its display area.

the Driver class creates an instance of itself. password. It uses a username. and a jdbc url to establish . A client can connect to Database Server through JDBC Driver.*. Once loaded. Creating a oracle jdbc Connection The JDBC DriverManager class defines objects which can connect Java applications to a JDBC driver. import java.odbc. In this step of the jdbc connection process. The return type of the Class. The star ( * ) indicates that all of the classes in the package java. we load the driver class by calling Class. DriverManager is considered the backbone of JDBC architecture. We can change database engines without changing database code. DriverManager class manages the JDBC drivers that are installed on the system. //Or any other driver } catch(Exception x){ System. try { Class. JDBC Architecture Java application calls the JDBC library.sql. Its getConnection() method is used to establish a connection to a database. you must first import the java.sql are to be imported.JdbcOdbcDriver”). Class is a class in java.out. 1. Loading a database driver.Java Database Connectivity Steps Before you can create a java jdbc connection to the database. } 2. JDBC Basics . Since most of the Database servers support ODBC driver therefore JDBC-ODBC Bridge driver is commonly used.lang package.jdbc.forName() with the Driver class name as an argument.forName (String ClassName) method is “Class”.136 JAVA FOR BEGINNERS Although JDBC was designed specifically to provide a Java interface to relational databases.println( “Unable to load the driver class!” ).sql package. you may find that you need to write Java code to access non-relational databases as well. JDBC loads a driver which talks to the database.forName(”sun.

Creating a jdbc Statement object. try{ Connection dbConnection=DriverManager. Statement statement = dbConnection.odbc. PL/SQL statements are executed and results are returned. . and returning a jdbc resultSet. Connection interface defines methods for interacting with the database via the established connection.getConnection(url.JdbcOdbcDriver. you need to instantiate a Statement object from your connection object by using the createStatement() method. tables. information about the database.createStatement(). Three kinds of Statements Statement: Execute simple sql queries without parameters. To execute SQL statements. Statement createStatement() Creates an SQL Statement object.”Password”) } catch( SQLException x ){ System. Callable Statement: Execute a call to a database stored procedure. 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. A jdbc Connection represents a session/connection with a specific database. PreparedStatement objects are precompiled SQL statements. and fields.println( “Couldn’t get connection!” ).137 JAVA FOR BEGINNERS a connection to the database and returns a connection object. CallableStatement objects are SQL stored procedure call statements. } 3. so the DriverManager knows to use the sun. SQL. Prepared Statement: Execute precompiled sql queries with or without parameters. Within the context of a Connection. 4.”loginName”. A statement object is used to send and execute SQL statements to a database. PreparedStatement prepareStatement(String sql) returns a new PreparedStatement object. CallableStatement prepareCall(String sql) returns a new CallableStatement object. We’re using the jdbc odbc subprotocol. Once a connection is obtained we can interact with the database.out. or it can have many connections with different databases.e. A Connection object provides metadata i.jdbc. An application can have one or more connections with a single database. Executing a SQL statement with the Statement object. It also contains methods to deal with transactions.

The Statement class has three methods for executing statements: executeQuery(). and execute(). output. public class TestJDBCDriverInstallation_Oracle { public static void main(String[] args) { StringBuffer output = new StringBuffer().jdbc. JDBC Driver Example import java. } catch (Exception e) { output = new StringBuffer(). import java.append(”Testing oracle driver installation \n”). password = “tiger”.Connection. output).DatabaseMetaData. alter a table.append(”Driver : “+driverObject+”\n”). or drop a table are all examples of DDL statements and are executed with the method executeUpdate.JdbcOdbcDriver”. For statements that create or modify tables. output). output.getMessage()).138 JAVA FOR BEGINNERS Statement interface defines methods that are used to interact with database via the execution of SQL statements. output.SQLException. JOptionPane. The table rows are retrieved in sequence. the method to use is executeUpdate.forName(className).JOptionPane. System. static String url = “jdbc:odbc:bob”. } } } Java JDBC Connection Example. JOptionPane.swing. public static void main(String[] args) throws Exception { Connection con = getOracleJDBCConnection(). A ResultSet maintains a cursor pointing to its current row of data. the method to use is executeQuery .sql. static Connection con = null.println(”Failed: Driver Error: ” + e. Test JDBC Driver Installation import javax. The next() method is used to successively step through the rows of the tabular results.DriverManager.sql. Class driverObject = Class. ResultSetMetaData Interface holds information on the types and properties of the columns in a ResultSet.showMessageDialog(null. ResultSet provides access to a table of data generated by executing a Statement. It is constructed from the Connection object.append(”Driver Installation FAILED\n”). execute() executes an SQL statement that is written as String object.showMessageDialog(null. output. executeUpdate(). For a SELECT statement. try { String className = “sun.sql.append(”Driver Installation Successful”).odbc. . import java. Note: Statements that create a table.sql. public class JDBCDriverInformation { static String userid=”scott”. import java.out.

getDriverVersion()).ClassNotFoundException e) { System.err.getMetaData().out.println(”Got Connection. A cursor can be thought of as a pointer to the rows of the result set that has the ability to keep track of which row is currently being accessed. System.139 JAVA FOR BEGINNERS if(con!= null){ System.println(”SQLException: ” + ex.lang.out.out. password).getMessage()).println(”Driver Version : “+meta.err.”).getMessage()). userid.err. }else{ System.println(”Could not Get Connection”). DatabaseMetaData meta = con.println(”Driver Name : “+meta. } catch(java. } } JDBC Result Sets ResultSet and Cursors The rows that satisfy a particular query are called the result set.odbc.getConnection(url. System. } return con. The JDBC Resultset example is shown in the next sections to follow. } catch(SQLException ex) { System.jdbc. A user can access the data in a result set using a cursor one row at a time from top to bottom.print(”ClassNotFoundException: “). Types of Result Sets . System.getDriverName()). The JDBC API supports a cursor to move both forward and backward and also allowing it to move to a specified row or to a row whose position is relative to another row.println(e.JdbcOdbcDriver”). } } public static Connection getOracleJDBCConnection(){ try { Class. } try { con = DriverManager.out.forName(”sun. The number of rows returned in a result set can be zero or more.

To move the cursor. and it can move to an absolute position. Result Set Methods When a ResultSet object is first created. from before the first row to after the last row. its cursor can move both forward and backward relative to the current position. If you do not specify any constants for the type and updatability of a ResultSet object. however. and it can move to an absolute position.”). and ResultSet objects can have different functionality and characteristics. The type of a ResultSet object determines the level of its functionality in two areas: the ways in which the cursor can be manipulated. 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.TYPE_SCROLL_SENSITIVE.140 JAVA FOR BEGINNERS The ResultSet interface provides methods for retrieving and manipulating the results of executed queries. and how concurrent changes made to the underlying data source are reflected by the ResultSet object.. you can use the following methods:  next() . Returns true if the cursor is now positioned on the first row and false if the ResultSet object does not contain any rows. Before you can take advantage of these features.CONCUR_READ_ONLY). TYPE_SCROLL_INSENSITIVE. The following line of code illustrates one way to create a scrollable ResultSet object: Statement stmt = con.moves the cursor forward one row.moves the cursor to the first row in the ResultSet object. you need to create a scrollable ResultSet object. The first argument is one of three constants added to the ResultSet API to indicate the type of a ResultSet object: TYPE_FORWARD_ONLY.moves the cursor backwards one row. and TYPE_SCROLL_SENSITIVE. . ResultSet.  TYPE_SCROLL_SENSITIVE — the result set is scrollable.  previous() . Returns true if the cursor is now positioned on a row and false if the cursor is positioned before the first row. 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. These characteristics are result set type.createStatement(ResultSet. and cursor holdability. its cursor can move both forward and backward relative to the current position.  TYPE_SCROLL_INSENSITIVE — the result set is scrollable.  first() . result set concurrency. the cursor is positioned before the first row.executeQuery(”…. ResultSet srs = stmt. Returns true if the cursor is now positioned on a row and false if the cursor is positioned after the last row.e. you will automatically get one that is TYPE_FORWARD_ONLY and CONCUR_READ_ONLY. the cursor moves only forward.

JDBC Driver Types JDBC drivers are divided into four types or levels.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. before the first row. If the ResultSet object does not contain any rows. The JDBC-ODBC Bridge driver is recommended only for experimental use or .141 JAVA FOR BEGINNERS  last() . this method has no effect. after the last row. If the ResultSet object does not contain any rows.  relative(int rows) . ODBC is a generic API.positions the cursor at the start of the ResultSet object.  afterLast() .  beforeFirst() . this method has no effect.moves the cursor relative to its current position.positions the cursor at the end of the ResultSet object. The different types of jdbc drivers are: Type 1: JDBC-ODBC Bridge driver (Bridge) Type 2: Native-API/partly Java driver (Native) Type 3: AllJava/Net-protocol driver (Middleware) Type 4: All Java/Native-protocol driver (Pure) 4 types of jdbc drivers are elaborated in detail as shown below: Type 1 : JDBC Driver JDBC-ODBC Bridge driver The Type 1 driver translates all JDBC calls into ODBC calls and sends them to the ODBC driver.  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. then to the database. They are the slowest of all driver types. The client system requires the ODBC Installation to use the driver. and this applies even in the reverse process. since the database’s ODBC drivers are already available. this driver is specific to a particular database. Since the Bridge driver is not written fully in Java. Disadvantages 1.e.142 JAVA FOR BEGINNERS when no other alternative is available. . A performance issue is seen as a JDBC call goes through the bridge to the ODBC driver. Type 1 drivers are not portable. Example: Oracle will have oracle native api. Not good for the Web. Type 2 : JDBC Driver Native-API/partly Java driver The distinctive characteristic of type 2 jdbc drivers are that Type 2 drivers convert JDBC calls into database-specific calls i. 3. 2. 4. Some distinctive characteristic of type 2 jdbc drivers are shown below.

If we change the Database we have to change the native api as it is specific to a database 4. Usually not thread safe. 3. Type 3 : JDBC Driver All Java/Net-protocol driver Type 3 database requests are passed through the network to the middle-tier server. Disadvantage 1. Like Type 1 drivers. 2. Native API must be installed in the Client System and hence type 2 drivers cannot be used for the Internet. If the middle-tier server can in turn use Type1. Type 2 or Type 4 drivers. it’s not written in Java Language which forms a portability issue. . Mostly obsolete now 5.143 JAVA FOR BEGINNERS 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. The middle-tier then translates the request to the database.

They are the most efficient amongst all driver types. Disadvantage It requires another server application to install and maintain. and scalability. This driver is fully written in Java and hence Portable. load balancing. since the data comes through the backend server. This driver is very flexible allows access to multiple databases using one driver. and so on). This driver is server-based. 6. . There are many opportunities to optimize portability. It is suitable for the web. 7. so there is no need for any vendor database library to be present on client machines. query results. The type 3 driver typically provides support for features such as caching (connections. Type 4 : JDBC Driver Native-protocol/all-Java driver The Type 4 uses java networking libraries to communicate directly with the database server.144 JAVA FOR BEGINNERS Type 3: All Java/ Net-Protocol Driver Advantage 1. performance. Traversing the recordset may take longer. 5. 3. 4. 2. The net protocol can be designed to make the client JDBC driver very small and fast to load. and advanced system administration such as logging and auditing.

the user needs a different driver for each database. performance is typically quite good. JDBC Create Table . these drivers can be downloaded dynamically. Disadvantage With type 4 drivers. 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. Number of translation layers is very less i. 3. Further. It is most suitable for the web. 2.e.145 JAVA FOR BEGINNERS Type 4: Native-protocol/all-Java driver Advantage 1. You don’t need to install special software on the client or server. type 4 JDBC drivers don’t have to translate database requests to ODBC or a native connectivity interface or to pass the request on to another server.

*. You can relate one database table to another by causing a given column in the table to derive its value from the value of a column in another table. Columns are also known as fields. Because you can link tables together you can easily extract data from multiple tables with a single query. Prod_ID 543 432 876 Product Name Belt Bottle Ring Employee_ID 6323 1234 5678 import javax. CREATE TABLE Employees (Employee_ID INTEGER.146 JAVA FOR BEGINNERS Create SQL Table Tables are composed of rows and columns. Orders) Employee_ID is the primary key which forms a relation between the 2 tables.sql. Each row represents a record in the database. password = “tiger”.JOptionPane. public static void main(String args[]){ . if your query mechanism supports this type of query. Such a column is called a key. import java. or attributes. If the tables had no columns in common. static Connection con. then there would be no way to relate them to one another. Employees: Employee_ID 6323 5768 1234 5678 Name Hemanth Bob Shawn Michaels Orders: CREATE TABLE Orders (Prod_ID INTEGER. For my website I am creating the following 2 tables (Employee. ? static Statement stmt. // String url = “jdbc:mySubprotocol:myDataSource”.swing.In order to integrate your tables into a single database. you’ll need to ensure that each table has a column that contains a value unique to that table. Below is a JDBC Program showing the use of executeUpdate() to create a table jdbc programming. Employee_ID INTEGER).ProductName VARCHAR(20). public class JDBCProgram{ static String userid=”scott”. static String url = “jdbc:odbc:bob”.Name VARCHAR(30)).

} catch(SQLException ex) { System.lang. } try { con = DriverManager. } public static void getSelected(int choice){ if(choice==1){ createEmployees().ClassN } catch(java. return ch. “1.err. } .println(”SQLException: ” + ex.forName(”myDriver.getConnection(url. if (choice != 0){ getSelected(choice). choice = JOptionPane.err. Create Products Table\n”+ “0.println(e.odbc.ClassNotFoundException e) { System. } } public static Connection getConnection() { Class. userid.JdbcOdbcDriver”).showMessageDialog (null.getMessage()). do{ choice = getChoice(). ? try { //Class. System. } if(choice==2){ createOrders(). Create Employees Table\n”+ “2.jdbc.showInputDialog(null. int choice = -1. System.forName (”sun.err. password). Exit\n\n”+ “Enter your choice”). } public static int getChoice() { String choice. } } while ( choice != 0).print(”ClassNotFoundException: “). ch = Integer.147 JAVA FOR BEGINNERS JOptionPane.parseInt(choice).exit(0). ame”). int ch.getMessage()). } return con.”JDBC Programming showing Creation of Table’s”).

String createString. } JOptionPane. } JOptionPane. } /*CREATE TABLE Orders ( Prod_ID INTEGER. Employee_ID INTEGER ).showMessageDialog(null.executeUpdate(createString). “+ “Employee_ID INTEGER )”. ” + “Name VARCHAR(30))”.getMessage()).println(”SQLException: ” + ex.close(). ” + “ProductName VARCHAR(20). try { stmt = con. } catch(SQLException ex) { System. try { stmt = con. } }//End of class JDBC Insert Inserting Data into SQL Tables . stmt.close(). createString = “create table Orders (” + “Prod_ID INTEGER.executeUpdate(createString).*/ public static void createOrders() { Connection con = getConnection(). stmt. stmt. con.*/ public static void createEmployees() { Connection con = getConnection(). createString = “create table Employees (” + “Employee_ID INTEGER. con.close().err.close().”Orders Table Created”).showMessageDialog(null. stmt. Name VARCHAR(30) ).148 JAVA FOR BEGINNERS /*CREATE TABLE Employees ( Employee_ID INTEGER.println(”SQLException: ” + ex.createStatement().createStatement(). String createString.err.getMessage()). } catch(SQLException ex) { System.”Employees Table Created”). ProductName VARCHAR(20).

Name VARCHAR(30) ). public class JDBCProgram{ //JDBC Insert Example static String userid=”scott”. Orders) as a part of the JDBC tutorial for insert in jdbc insert query.showMessageDialog (null.sql.JOptionPane.149 JAVA FOR BEGINNERS We will insert data into the table’s Employees and Orders as created in the previous tutorial. one row at a time. Employees: Employee_ID 6323 5768 1234 5678 Orders: CREATE TABLE Orders (Prod_ID INTEGER. CREATE TABLE Employees (Employee_ID INTEGER. The values to be inserted into the columns are listed in the same order that the columns were declared when the table was created.*. import java.ProductName VARCHAR(20). // String url = “jdbc:mySubprotocol:myDataSource”. Employee_ID INTEGER ). . For my website I am creating the following 2 tables (Employee. Employee_ID is the primary key which forms a relation between the 2 tables.swing. static Connection con. 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. static String url = “jdbc:odbc:bob”. password = “tiger”. supplying the information to be stored in each column of that row using a jdbc insert query statement. public static void main(String args[]){ JOptionPane. Below is a JDBC Program showing the use of executeUpdate() to create a table and insert row into using java jdbc insert data statement.”JDBC Programming showing Insertion of Table Data”). ? static Statement stmt.

} } while ( choice != 0). } if(choice==2){ createOrders(). ? } catch(java. do{ choice = getChoice(). “1.JdbcOdbcDriver”).ClassName”). } } public static Connection getConnection() { try { Class. } if(choice==4){ insertOrders(). Exit\n\n”+ “Enter your choice”).lang.forName(”my Driver.odbc. } public static void getSelected(int choice){ if(choice==1){ createEmployees(). ch = Integer.showInputDialog(null. Create Products Table\n”+ “3. //Class.ClassNotFoundException e) .jdbc.150 JAVA FOR BEGINNERS int choice = -1. } if(choice==3){ insertEmployees(). return ch. System.exit(0).parseInt(choice). } public static int getChoice() { String choice. Insert data into Products Table\n”+ “0. int ch.forName (”sun. choice = JOptionPane. if (choice != 0){ getSelected(choice). Create Employees Table\n”+ “2. Insert data into Employees Table\n”+ “4.

err.getConnection(url. Name VARCHAR(30) ). createString = “create table Employees (” +“Employee_ID INTEGER. ” + “Name VARCHAR(30))”. String createString. ProductName VARCHAR(20).close(). System.print(”ClassNotFoundException: “).err. } /*CREATE TABLE Employees ( Employee_ID INTEGER. userid.*/ public static void createEmployees() { Connection con = getConnection().close().showMessageDialog(null. } /*CREATE TABLE Orders ( Prod_ID INTEGER.getMessage()).err.println(e.err. } return con. String createString.println(”SQLException: ” + ex.createStatement(). try { stmt = con. stmt. } try { con = DriverManager. } catch(SQLException ex) { System.*/ public static void createOrders() { Connection con = getConnection(). stmt.getMessage()).”Employees Table Created”). ” +“ProductName . } catch(SQLException ex) { System. } JOptionPane. createString = “create table Orders (” + “Prod_ID INTEGER.151 JAVA FOR BEGINNERS { System.println(”SQLException: ” + ex. password).executeUpdate(createString). Employee_ID INTEGER ). con.getMessage()).

close(). ‘Shawn’)”. stmt. insertString3 = “insert into Employees values(1234.executeUpdate(insertString2). insertString4. stmt. “+“Employee_ID INTEGER )”.createStatement().executeUpdate(insertString4). } catch(SQLException ex) { System. ‘Hemanth’)”.close(). insertString2 = “insert into Employees values(5768. ‘Michaels’)”. stmt.showMessageDialog(null.executeUpdate(insertString1).println(”SQLException: ” + ex.”Orders Table Created”). insertString2. stmt. con.executeUpdate(insertString3).createStatement(). stmt.152 JAVA FOR BEGINNERS VARCHAR(20).getMessage()). ‘Bob’)”. insertString4 = “insert into Employees values(5678. } JOptionPane.”Data Inserted into Employees Table”). insertString1 = “insert into Employees values(6323. String insertString1.getMessage()). } .close(). try { stmt = con. } catch(SQLException ex) { System. stmt.executeUpdate(createString).close().println(”SQLException: ” + ex.showMessageDialog(null. } JOptionPane. try { stmt = con. stmt. insertString3. con. } /*Employee_ID Name 6323 Hemanth 5768 Bob 1234 Shawn 5678 Michaels */ public static void insertEmployees() { Connection con = getConnection().err.err.

6323)”. } catch(SQLException ex) { System.executeUpdate(insertString1). stmt.executeUpdate(insertString3).”Data Inserted into Orders Table”). stmt. } }//End of class JDBC Select Statement Retrieving Data using JDBC Select Query . ‘Belt’.executeUpdate(insertString2).showMessageDialog(null. ‘Ring’. insertString2.close(). insertString3 = “insert into Orders values(876. con. 1234)”. String insertString1. insertString3. stmt. ‘Bottle’. insertString1 = “insert into Orders values(543. insertString2 = “insert into Orders values(432.153 JAVA FOR BEGINNERS /* Prod_ID 543 432 876 ProductName Belt Bottle Ring Employee_ID 6323 1234 5678 */ public static void insertOrders() { Connection con = getConnection().createStatement(). stmt.getMessage()). try { stmt = con. insertString4.println(”SQLException: ” + ex.err.close(). 5678)”. } JOptionPane.

ProductName VARCHAR(20). For my website I am creating the following 2 tables (Employee. The tabular results of the query are captured in the ResultSet object. CREATE TABLE Employees (Employee_ID INTEGER. The return value for an executeQuery is a ResultSet object containing the results of the query sent to the DBMS. Orders) as a part of the JDBC tutorial. using the jdbc select data statement as the parameter. so we need to declare an instance of the class ResultSet to hold our results. we use the next() method. Employee_ID INTEGER ). To process each row in the ResultSet. results. Prod_ID 543 432 Product Name Belt Bottle Employee_ID 6323 1234 . Employee_ID is the primary key which forms a relation between the 2 tables.Name VARCHAR(30) ). 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. Select is the SQL keyword that performs a query. This method moves the pointer through the rows of data.154 JAVA FOR BEGINNERS We can use Java JDBC Select statement in a java program to retrieve the data and display it for the respective Tables. We invoke the jdbc select query (executequery) method. JDBC returns results in a ResultSet object. The ResultSet maintains a cursor pointing to the current row. Because this cursor is initially positioned before the first row. Note that executeQuery() always returns a ResultSet although it need not have any rows in it. Employees Table: Employee_ID 6323 5768 1234 5678 Name Hemanth Bob Shawn Michaels Orders Table: CREATE TABLE Orders (Prod_ID INTEGER.

static Connection con. Create Products Table\n”+ “3. Insert data into Orders Table\n”+ “5. System. Create Employees Table\n”+ “2. // String url = “jdbc:mySubprotocol:myDataSource”. } } while ( choice != 0). } if(choice==2){ createOrders(). return ch.showMessageDialog(null. public static void main(String args[]){ JOptionPane. int ch. choice = JOptionPane.155 JAVA FOR BEGINNERS 876 Ring 5678 JDBC SQL Select Example import javax.parseInt(choice). public class JDBCProgram{ static String userid=”scott”. ch = Integer. if (choice != 0){ getSelected(choice). Retrieve data for Employees Table\n”+ “6. } public static void getSelected(int choice){ if(choice==1){ createEmployees().swing.showInputDialog(null. import java.exit(0).*.”JDBC Programming showi ng Retrieval of Table Data”). do{ choice = getChoice(). } public static int getChoice() { String choice. Insert data into Employees Table\n”+ “4.JOptionPane. Exit\n\n”+ “Enter your choice”). Retrieve data for Orders Table\n”+ “0. “1. } if(choice==3){ . int choice = -1. static String url = “jdbc:odbc:bob”.sql. password = “tiger”. ? static Statement stmt.

156 JAVA FOR BEGINNERS

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 (

157 JAVA FOR BEGINNERS

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”);

158 JAVA FOR BEGINNERS

} /*

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’, 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();

showMessageDialog(null. con.getInt(”Prod_ID”). result =”Prod_ID\t\tProductName\t\tEmployee_ID\n”. } }//End of class Java JDBC Update JDBC Update Table Example . while (rs. } stmt. result +=pr_id+”\t\t”+ prodName+”\t\t”+id+”\n”.createStatement().159 JAVA FOR BEGINNERS String result = null.executeQuery(selectString). ResultSet rs = stmt. String prodName = rs.err.next()) { int pr_id = rs. result). int id = rs. try { stmt = con.getString(”ProductName”).getInt(”Employee_ID”). selectString = “select * from Orders”.close().getMessage()). } JOptionPane.println(”SQLException: ” + ex. } catch(SQLException ex) { System. String selectString.close().

executeUpdate().sql. static Connection con. // String url = “jdbc:mySubprotocol:myDataSource”. Orders) as a part of the JDBC update table statement.JOptionPane. ? static Statement stmt. Employee_ID is the primary key which forms a relation between the 2 tables. password = “tiger”. 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. Below is a program showing the use of jdbc executeupdate (uses jdbc update query) to update a table. For my website I am creating the following 2 tables (Employee. import java. .160 JAVA FOR BEGINNERS We can use java jdbc update statements in a java program to update the data for a Table.ProductName VARCHAR(20). The return value for a jdbc sql update is an int that indicates how many rows of a table were updated. Employee_ID INTEGER ).*. For instance in a statement like int n = stmt.swing.Name VARCHAR(30) ). static String url = “jdbc:odbc:bob”. public class JDBCProgram{ static String userid=”scott”. CREATE TABLE Employees (Employee_ID INTEGER. Employees: Employee_ID 6323 5768 1234 5678 Orders: CREATE TABLE Orders (Prod_ID INTEGER.

Insert data into Employees Table\n”+ “4. } if(choice==4){ insertOrders(). do{ choice = getChoice(). Retrieve data for Employees Table\n”+ “6.parseInt(choice). } public static int getChoice() { String choice.showInputDialog(null.exit(0). int ch. Create Products Table\n”+ “3. choice = JOptionPane. if (choice != 0){ getSelected(choice). int choice = -1. Exit\n\n”+ “Enter your choice”). Insert data into Orders Table\n”+ “5.161 JAVA FOR BEGINNERS public static void main(String args[]){ JOptionPane. } } while ( choice != 0). } if(choice==3){ insertEmployees(). “1.”JDBC Programming showing Updation of Table Data”). return ch. } if(choice==5){ . Create Employees Table\n”+ “2. Retrieve data for Orders Table\n”+ “7. } if(choice==2){ createOrders(). System. Update Employees Table\n”+ “0. } public static void getSelected(int choice){ if(choice==1){ createEmployees().showMessageDialog (null. ch = Integer.

ClassNotFoundException e) { System. } try { con = DriverManager. userid.162 JAVA FOR BEGINNERS retrieveEmployees(). //Uses JDBC Update Statement } } public static Connection getConnection() { try { Class.jdbc. System. ? } catch(java. } if(choice==7){ updateEmployees().ClassName”).getMessage()).err.odbc. } catch(SQLException ex) { System.forName(”myDriver.JdbcOdbcDriver”).println(e. ” + “Name . } /*CREATE TABLE Employees ( Employee_ID INTEGER. //Class. password).lang. Name VARCHAR(30) ).getMessage()).println(”SQLException: ” + ex.*/ public static void createEmployees() { Connection con = getConnection().print(”ClassNotFoundException: “).err.forName(”sun.getConnection(url. } return con. createString = “create table Employees (” + “Employee_ID INTEGER. } if(choice==6){ retrieveOrders(). String createString.err.

ProductName VARCHAR(20).err. try { stmt = con.close().getMessage()).executeUpdate(createString).close().createStatement().*/ public static void createOrders() { Connection con = getConnection().”Orders Table Created”). Employee_ID INTEGER ). stmt.println(”SQLException: ” + ex. stmt.err. } JOptionPane.createStatement(). con. } catch(SQLException ex) { System. ” + “ProductName VARCHAR(20). con.close(). stmt.println(”SQLException: ” + ex. try { stmt = con.getMessage()).showMessageDialog(null.163 JAVA FOR BEGINNERS VARCHAR(30))”.executeUpdate(createString). stmt. } /*Employee_ID 6323 Name Hemanth . } /*CREATE TABLE Orders ( Prod_ID INTEGER. “+ “Employee_ID INTEGER )”.”Employees Table Created”).close(). } catch(SQLException ex) { System.showMessageDialog(null. } JOptionPane. String createString. createString = “create table Orders (” + “Prod_ID INTEGER.

insertString2. try { stmt = con.createStatement(). ‘Shawn’)”. } JOptionPane. ‘Bottle’.”Data Inserted into Employees Table”). insertString2 = “insert into Orders values(432.showMessageDialog(null.executeUpdate(insertString4). stmt. insertString2. con.close(). } catch(SQLException ex) { System. ‘Bob’)”.164 JAVA FOR BEGINNERS 5768 Bob 1234 Shawn 5678 Michaels */ public static void insertEmployees() { Connection con = getConnection(). insertString2 = “insert into Employees values(5768. 6323)”.err. insertString3. .println(”SQLException: ” + ex. ‘Michaels’)”. String insertString1. } /* Prod_ID 543 432 876 ProductName Belt Bottle Ring Employee_ID 6323 1234 5678 */ public static void insertOrders() { Connection con = getConnection(). stmt.executeUpdate(insertString1). insertString4. stmt. insertString1 = “insert into Orders values(543.executeUpdate(insertString2). stmt. 1234)”. insertString4. ‘Belt’. insertString1 = “insert into Employees values(6323.getMessage()). insertString4 = “insert into Employees values(5678. ‘Hemanth’)”. stmt.close().executeUpdate(insertString3). insertString3. insertString3 = “insert into Employees values(1234. String insertString1.

} JOptionPane.println(”SQLException: ” + ex. stmt. String name = rs. try { stmt = con.executeQuery(selectString). stmt.getString(”Name”). String selectString.executeUpdate(insertString1).createStatement().println(”SQLException: ” + ex. } catch(SQLException ex) { System. selectString = “select * from Orders”.err. while (rs. result =”Employee_ID\t\tName\n”. } public static void retrieveOrders(){ Connection con = getConnection().err.getMessage()). } stmt.close(). } catch(SQLException ex) { System. stmt. ResultSet rs = stmt. } JOptionPane. ‘Ring’.next()) { int id = rs.getInt(”Employee_ID”).”Data Inserted into Orders Table”).createStatement(). String result = null.showMessageDialog(null. con.executeUpdate(insertString2). } public static void retrieveEmployees(){ Connection con = getConnection().close(). result).close(). result+=id+”\t\t”+ name+”\n”. stmt.getMessage()). String result = null. con. selectString = “select * from Employees”. String selectString.close().executeUpdate(insertString3). result . try { stmt = con.showMessageDialog(null. 5678)”.165 JAVA FOR BEGINNERS insertString3 = “insert into Orders values(876.

err.createStatement(). try { stmt = con.executeUpdate(updateString1). } }//End of class Using Prepared Statements .getString(”ProductName”).close(). stmt.executeQuery(selectString). stmt. result +=pr_id+”\t\t”+ prodName+”\t\t”+id+”\n”. con.createStatement().println(”SQLException: ” + ex. } stmt. String prodName = rs.getMessage()). con.showMessageDialog(null. } catch(SQLException ex) { System.close().next()) { int pr_id = rs. result). ResultSet rs = stmt.getMessage()). } public static void updateEmployees(){ Connection con = getConnection().close(). } JOptionPane. while (rs. String updateString1.getInt(”Prod_ID”).err. updateString1 = “update Employees set name = ‘hemanthbalaji’ where Employee_id = 6323″.close().166 JAVA FOR BEGINNERS =”Prod_ID\t\tProductName\t\tEmployee_ID\n”. } catch(SQLException ex) { System.”Data Updated into Employees Table”). try { stmt = con. int id = rs.showMessageDialog(null. } JOptionPane.println(”SQLException: ” + ex.getInt(”Employee_ID”).

This means that when the PreparedStatement is executed. Orders) as a part of the JDBC tutorial. Precompiled SQL is useful if the same SQL is to be executed repeatedly. but an SQL statement that has been precompiled. Every java sql prepared statement is compiled at some point.setString(1. the PreparedStatement object contains not just an SQL statement. This SQL statement is sent to the DBMS right away.Name VARCHAR(30) ).prepareStatement() method.executeUpdate(). in a loop. you probably use them most often for SQL statements that take parameters. JDBC PreparedStatements are useful especially in situations where you can use a for loop or while loop to set a parameter to a succession of values. objects can be used for SQL statements with no parameters. “Bob”). Employee_ID is the primary key which forms a relation between the 2 tables CREATE TABLE Employees (Employee_ID INTEGER.setInt(2. If you want to execute a Statement object many times. An important feature of a PreparedStatement object is that. the DBMS can just run the PreparedStatement SQL statement without having to compile it first. unlike a Statement object. you must first create a object by calling the Connection. pstmt. where it is compiled. it is given an SQL statement when it is created. An example of a PreparedStatement object is PreparedStatement pstmt = con. Prepared statements in java only save you time if you expect to execute the same SQL over again. it normally reduces execution time to use a PreparedStatement object instead. 100). You need to supply values to be used in place of the question mark placeholders (if there are any) before you can execute a PreparedStatement object. you need to call close() to make sure database resources are freed as soon as possible. For my website I am creating the following 2 tables (Employee. As a result. You do this by calling one of the setXXX methods defined in the PreparedStatement class. Below is a JDBC Program showing the use of jdbc prepared statements to insert data into tables using jdbc programming. Using Prepared Statements in jdbc.prepareStatement(”update Orders set pname = ? where Prod_Id = ?”). 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. pstmt. As with CallableStatements. To use a java reparedstatements. .167 JAVA FOR BEGINNERS Java Prepared Statements Java JDBC Prepared statements are pre-compiled SQL statements. The syntax is straightforward: just insert question marks for any parameters that you’ll be substituting before you send the SQL to the database. There is a setXXX method for each primitive type declared in the Java programming language. for example. pstmt.

Prod_ID 543 432 876 Product Name Belt Bottle Ring Employee_ID 6323 1234 5678 Java JDBC Prepared Statement Example import javax.ProductName VARCHAR(20).sql. static PreparedStatement pstmt.168 JAVA FOR BEGINNERS Employees: Employee_ID 6323 5768 1234 5678 Name Hemanth Bob Shawn Michaels Orders: CREATE TABLE Orders (Prod_ID INTEGER. } } . JOptionPane.JOptionPane. static Connection con.showMessageDial og(null. password = “tiger”. import java. int choice = -1. do{ choice = getChoice(). static String url = “jdbc:odbc:bob” // String url = “jdbc:mySubprotocol:myDataSource”. Employee_ID INTEGER ). public class JDBCProgram{ static String userid=”scott”. public static void main(String args[]){ .*.swing. if (choice != 0){ getSelected(choice). ? static Statement stmt.”JDBC Programming showing Updation of Table Data”).

Insert data into Employees Table\n”+ “4. Create Employees Table\n”+ “2. } public static void getSelected(int choice){ if(choice==1){ createEmployees(). } if(choice==7){ updateEmployees(). List the name of employees who bought CD’sn”+ “0. Update Employees Table\n”+ “8. return ch. Insert data into Orders Table\n”+ “5.parseInt(choice). Update Employees Table Using a Prepared Statement\n”+ “9. Create Products Table\n”+ “3. } if(choice==8){ . Exit\n\n”+ “Enter your choice”). “1. ch = Integer. } if(choice==5){ retrieveEmployees(). Retrieve data for Employees Table\n”+ “6. } if(choice==6){ retrieveOrders(). Update many records of Orders Table Using a Prepared Statement\n”+ “10. System.exit(0). int ch.169 JAVA FOR BEGINNERS while ( choice != 0). Retrieve data for Orders Table\n”+ “7. choice = JOptionPane.showInputDialog(null. } public static int getChoice() { String choice. } if(choice==3){ insertEmployees(). } if(choice==4){ insertOrders(). } if(choice==2){ createOrders().

} if(choice==9){ updateOrdersPrepared().print(”ClassNotFoundException: “).lang.getConnection(url.*/ public static void createEmployees() { Connection con = getConnection().JdbcOdbcDriver”). stmt.executeUpdate(createString). } } public static Connection getConnection() { try { Class. } /*CREATE TABLE Employees ( Employee_ID INTEGER.jdbc. } catch(SQLException ex) { System.err.println(”SQLException: ” + ex.ClassName”). . Name VARCHAR(30) ).println(e. createString = “create table Employees (” + “Employee_ID INTEGER.getMessage()).170 JAVA FOR BEGINNERS updateEmployeesPrepared().ClassNotFoundException e) { System. userid. System. } if(choice==10){ dynamicQuery(). password).odbc. try { stmt = con.forName(”myDriver. //Class. } try { con = DriverManager.err. String createString. } return con.err. ? } catch(java.forName(”sun.createStatement(). ” + “Name VARCHAR(30))”.getMessage()).

println(”SQLException: ” + ex.”Orders Table Created”).close().close(). stmt. ” + “ProductName VARCHAR(20). “+ “Employee_ID INTEGER )”.showMessageDialog(null. } JOptionPane. stmt. Employee_ID INTEGER ). } /*CREATE TABLE Orders ( Prod_ID INTEGER. createString = “create table Orders (” + “Prod_ID INTEGER. } catch(SQLException ex) { System. .close(). String createString. } JOptionPane.println(”SQLException: ” + ex. } catch(SQLException ex) { System.getMessage()).err.err.171 JAVA FOR BEGINNERS stmt. con. } /*Employee_ID Name 6323 Hemanth 5768 Bob 1234 Shawn 5678 Michaels */ public static void insertEmployees() { Connection con = getConnection().createStatement().getMessage()).executeUpdate(createString). con.”Employees Table Created”).close().*/ public static void createOrders() { Connection con = getConnection(). ProductName VARCHAR(20).showMessageDialog(null. try { stmt = con.

stmt. insertString2 = “insert into Orders values(432.”Data Inserted into Employees Table”). insertString1 = “insert into Orders values(543. ‘Bottle’. 5678)”. insertString2 = “insert into Employees values(5768. . ‘Bob’)”.172 JAVA FOR BEGINNERS String insertString1. String insertString1. stmt.executeUpdate(insertString1). } catch(SQLException ex) { System.executeUpdate(insertString2). insertString3. con. stmt. } /* Prod_ID 543 432 876 ProductName Belt Bottle Ring Employee_ID 6323 1234 5678 */ public static void insertOrders() { Connection con = getConnection().getMessage()).showMessageDialog(null. insertString4. insertString4 = “insert into Employees values(5678. ‘Shawn’)”.createStatement(). stmt.close(). ‘Michaels’)”. ‘Belt’.executeUpdate(insertString1). 6323)”. try { stmt = con.err. ‘Ring’. insertString1 = “insert into Employees values(6323. insertString4.createStatement().executeUpdate(insertString3). insertString2. ‘Hemanth’)”.executeUpdate(insertString4). try { stmt = con. insertString3 = “insert into Orders values(876.close(). insertString3.println(”SQLException: ” + ex. insertString3 = “insert into Employees values(1234. stmt. } JOptionPane. insertString2. stmt. 1234)”.

try { stmt = con. con.executeQuery(selectString).println(”SQLException: ” + ex.executeQuery(selectString).showMessageDialog(null.getMessage()). ResultSet rs = stmt.executeUpdate(insertString2). while (rs. } stmt. result =”Employee_ID\t\tName\n”. result+=id+”\t\t”+ name+”\n”.getString(”Name”). result =”Prod_ID\t\tProductName\t\tEmployee_ID\n”. selectString = “select * from Orders”. String result = null. String result = null. ResultSet rs = stmt. String selectString.getInt(”Employee_ID”).getMessage()). con.173 JAVA FOR BEGINNERS stmt. stmt.next()) { . } JOptionPane. } catch(SQLException ex) { System. result).close().close().err. stmt.next()) { int id = rs.close(). } public static void retrieveOrders(){ Connection con = getConnection(). } catch(SQLException ex) { System.createStatement(). String name = rs. selectString = “select * from Employees”.createStatement().println(”SQLException: ” + ex.showMessageDialog(null.”Data Inserted into Orders Table”).close(). String selectString. try { stmt = con.executeUpdate(insertString3). } JOptionPane.err. } public static void retrieveEmployees(){ Connection con = getConnection(). while (rs.

pstmt.close(). } JOptionPane. //Note index starts with 1 pstmt.174 JAVA FOR BEGINNERS int pr_id = rs. 6323). “hemanthbob”).executeUpdate(updateString1). pstmt.println(”SQLException: ” + ex. } stmt.err. } catch(SQLException ex) { System. result).executeUpdate(). int id = rs.showMessageDialog(null.getString(”ProductName”).close().getInt(”Prod_ID”).showMessageDialog(null. } public static void updateEmployeesPrepared(){ Connection con = getConnection(). stmt.setInt(2. try { stmt = con. con. updateString1 = “update Employees set name = ‘hemanthbalaji’ where Employee_id = 6323″. stmt. String updateString1. } public static void updateEmployees(){ Connection con = getConnection().getMessage()).getInt(”Employee_ID”). } JOptionPane. .close().”Data Updated into Employees Table”).err.createStatement(). con.prepareStatement (”update Employees set name = ? where Employee_Id = ?”).setString(1. result +=pr_id+”\t\t”+ prodName+”\t\t”+id+”\n”.close(). String prodName = rs.println(”SQLException: ” + ex.getMessage()). } catch(SQLException ex) { System. // create prepared statement try { pstmt = con.

432. selectString = “select Employees. productIds[i]). for(int i = 0. } public static void updateOrdersPrepared(){ int [] productIds = {543.”Data Updated into Orders Table”). Connection con = getConnection().close(). “dvds”. productNames[i]).employee_id “.println(”SQLException: ” + ex.name from Employees. String selectString.executeUpdate(). try { . Orders where productname = ‘cds’ ” + “and Employees.close().close().employee_id = Orders.length. result =”Name\n”. String [] productNames = {”cds”. pstmt.getMessage()).close().showMessageDialog(null.175 JAVA FOR BEGINNERS pstmt.prepareStatement (”update Orders set productname = ? where Prod_Id = ?”).setInt(2. } pstmt.println(”SQLException: ” + ex. con. } catch(SQLException ex) { System. con.err.”Data Updated into Employees Table”). } catch(SQLException ex) { System. } public static void dynamicQuery(){ Connection con = getConnection().setString(1. int len = productNames. } JOptionPane. String result = null.showMessageDialog(null. } JOptionPane. “Espresso”}. pstmt.getMessage()). i++) { pstmt. i < len.err. 876}. try { pstmt = con.

close().getMessage()).176 JAVA FOR BEGINNERS stmt = con. } }//End of class . while (rs. } stmt. result).next()) { String name = rs.createStatement(). ResultSet rs = stmt.println(”SQLException: ” + ex.getString(”Name”). con.err. } catch(SQLException ex) { System. result+=name+”\n”. } JOptionPane.showMessageDialog(null.executeQuery(selectString).close().

Sign up to vote on this title
UsefulNot useful