Java Programming
Java Programming
Java Solutions
Shishav jain
2012
Chapter 1 .
3.1 Packages
3.2 Concept of CLASSPATH
3.3 Access Modifier or Visibility control
3.4 Using other package in class
3.5 Interfaces
3.6 String Handling
3.7 Constructors defined in the String class
3.8 Special String Operations
3.9 String Buffer
4.1 Exceptions
4.2 Exception Hierarchy
6.1 Drivers
6.2 Steps for Connectivity between java program and database
6.3 Select Query Program
6.4 Insert Query Program
6.5 Delete Query Program
6.6 Update Query Program
Note : Don’t compare java with c++ . This freak question is always a
part of university exams , but there is no point while learning java to
compare it with c++.
1.1 Java byte code power : As java compiler internally convert the java
source code into byte code , and this byte code is platform independent
means byte code generated by java compiler can be accessible in every
platform that install java virtual machine.
What we will do in java – Programmer writes java source file using note pad
or some java editors and save this source file with .java extension. This .java
file is compiled using javac compiler which removes all the syntax errors in
your code and if it satisfied , it creates a file with .class extension which
contains the byte code as shown in below diagram.
1.Simple:
3. Dynamic
In java, All the user defined things are stored on heap memory , and heap
memory is dynamic memory . In java , we cant define user defined objects
on stack.All the user defined objects are created using the new operator,
which is used to allocate memory on heap.
java has got pointers, but pointers cannot misbehave in a freak way and in
all java, Becuase they can’t ptr++ or ptr--.Internally java compiler controls
the pointer working.
7. Multithreaded enviouement :
Java supports multithreading , through which we can do multitasking in
our program , so that we can utilize our processor more effectively.
Low level languages elements are called lexical tokens which are used to
constructs complex element of the language. Identifiers , keyword and
Identifiers
Note:
• Java is case sensitive languages e.g price and Price are different in
java
Keywords
Keywords are the reserved identifiers that are predefined in the languages
and cannot be used to denote other entities.
Keywords in Java
Const goto
MultiLine Comments
A multiline comments can span several lines . Such a comments starts with
/* and ends with */.Multiline comments are also called block comment.
/* A comment
On several lines
*/
Documentation Comment
A documentation comment is a special-purpose comment that when placed
before class or class member declarations can be extracted and used by the
javadoc tool to generate HTML documentation for the program.
Documentation comments are usually placed in front of classes, interfaces,
methods and field definitions. Groups of special tags can be used inside a
documentation comment to provide more specific information. Such a
comment starts with /** and ends with */:
• Boolean Type
Integer types : in java integers types are divided in four sub types
• Range of datatype specifies the range of value that a variable can hold.
For Example range of byte is -128 to 127 . so we can represent
number between -128 to 127 by using byte datatype. If value is
greater then 127 or less then -128 , then it is not possible with byte.
• Primitive data values are atomic values and are not objects. Atomic
means they can’t be further divided.
• Each Primitive data type has a corresponding wrapper class that can
be used to represent a primitive data type as an object.
Character type
Note : java supports Unicode character set to represent the characters and
other special symbols .
Floating points numbers are used to represents the numbers that have
fractional values like 10.10 .There are two ways to represent floating
number is java described in below table.
3.Booleans Datatypes
Boolean data types is used to represent logical values that can be either true
or false . Width is not applicable for Boolean types variables.
Note :
Default values of primitive data types are used when we are not initialize the
non local variables in java . Non local variables in java are initialized by its
default values. For Example , if we initialize the non local int variable , it its
initializes with 0. Variables for a function/methods are called local variables
, all other variables are called non local variables.
Default Values
Boolean false
Char '\u0000'
int a = 5+4*5;
it can be understand as (5+4) * 5 or 5 + (4*5). In both cases the value for the
variable a is different , so to avoid such type of undeterministic result , java
provides the Associativity and precedence (priority) rules on operators.
((1+2)-3)
(1+(2-3))
<variable>=<expression>
Note:
For Ex :
Ex : int i,j;
int b =10;
int c = a+b;
Arithmetic Operators
+ Addition - Subtraction
Note:
• All the arithmetic operators are binary operators. They require two
operands as shown in diagram.
Multiplication Operator: *
Multiplication operator * multiplies two numbers.
int sameSigns = -4 * -8; // result: 32
double oppositeSigns = 4.0 * -8.0; // result: -32.0
int zero = 0 * -0; // result: 0
Division Operator: /
The division operator / is overloaded. If its operands are integral, the
operation results in integer division.
int i1 = 4 / 5; // result: 0
int i2 = 8 / 8; // result: 1
double d1 = 12 / 8; // result: 1 by integer division. d1 gets the value 1.0.
Integer division always returns the quotient as an integer value, i.e. the
result is truncated toward zero. Note that the division performed is integer
division if the operands have integral values, even if the result will be stored
in a floating-point type.
If any of the operands is a floating-point type, the operation performs
floating-point division.
double d2 = 4.0 / 8; // result: 0.5
double d3 = 8 / 8.0; // result: 1.0
double d4 = 12.0F / 8; // result: 1.5F
Relational Operators
Equality Operators
a == b a and b are equal? That is, have the same primitive value?
(Equality)
a != b a and b are not equal? That is, do not have the same primitive
1.Equality operators have precedence less then the relational operators but
greater then the assignment operator.
Ex:
Logical AND x & y true if both operands are true; otherwise, false.
Note:
Conditional Operators
Conditional AND x && y true if both operands are true; otherwise, false.
Unlike their logical counterparts & and |, which can also be applied to
integral operands for bitwise operations, the conditional operators && and
|| can only be applied to boolean operands. Their evaluation results in a
boolean value. Truth-values for conditional operators are shown in Table.
Not surprisingly, they have the same truth-values as their counterpart
logical operators.
x y x && y x || y
Short-circuit Evaluation
In evaluation of boolean expressions involving conditional AND and OR, the
left-hand operand is evaluated before the right one, and the evaluation is
short-circuited (i.e., if the result of the boolean expression can be
Written by : Shishav Jain Mob:8290280309 Page Number :17
determined from the left-hand operand, the right-hand operand is not
evaluated). In other words, the right-hand operand is evaluated
conditionally.
The binary conditional operators have precedence lower than either
arithmetic, relational, or logical operators, but higher than assignment
operators. The following examples illustrate usage of conditional operators:
boolean b1 = 4 == 2 && 1 < 4; // false, short-circuit evaluated as
// (b1 = ((4 == 2) && (1 < 4)))
boolean b2 = !b1 || 2.5 > 8; // true, short-circuit evaluated as
// (b2 = ((!b1) || (2.5 > 8)))
boolean b3 = !(b1 && b2); // true
boolean b4 = b1 || !b3 && b2; // false, short-circuit evaluated as
// (b4 = (b1 || ((!b3) && b2)))
Postfix increment operator: post increment operator have the below syntax
i++ uses the current value of i as the value of expression first , then it is
incremented by 1.
Below diagram explains the postIncrement operator.
++i add 1 to i first , then uses the new value of i as the value for the
expression .
1.8 Arrays:
Or
When the [] notation follows the type, all variables in the declaration are
arrays. Otherwise the [] notation must follow each individual array name in
the declaration.
Constructing an Array
The minimum value of <array size> is 0 (i.e., arrays with zero elements can
be constructed in Java). If the array size is negative, a
NegativeArraySizeException is thrown.
However, here array type <element type2>[] must be assignable to array type
<element type1>[] .When the array is constructed, all its elements are
initialized to the default value for <element type2>. This is true for both
member and local arrays when they are constructed.
In all the examples below, the code constructs the array and the array
elements are implicitly initialized to their default value. For example, the
element at index 2 in array anIntArray gets the value 0, and the element at
index 3 in array mediumPizzas gets the value null when the arrays are
constructed.
The value of the field length in each array is set to the number of elements
specified during the construction of the array; for example, medium
Pizzas.length has the value 5.
Once an array has been constructed, its elements can also be explicitly
initialized individually; for example, in a loop. Examples in the rest of this
section make heavy use of a loop to traverse through the elements of an
array for various purposes.
Initializing an Array
The expressions in the <array initialize list> are evaluated from left to right,
and the array name obviously cannot occur in any of the expressions in the
list. In the examples above, the <array initialize list> is terminated by the
right curly bracket , }, of the block. The list can also be legally terminated by
a comma. The following array has length two, not three:
Using an Array
The whole array is referenced by the array name, but individual array
elements are accessed by specifying an index with the [] operator. The array
element access expression has the following syntax:
both creates the array and initializes the array elements to specific values
given in the array initializer block. However, the array initialization block is
not an expression.
Java has another array creation expression, called anonymous array, which
allows the concept of the array creation expression from (1) and the array
initializer block from (2) to be combined, to create and initialize an array
object:
In (1), an array initializer block is used to create and initialize the elements.
In (2), an anonymous array expression is used. It is tempting to use the
array initialization block as an expression; for example, in an assignment
statement as a short cut for assigning values to array elements in one go.
However, this is illegal—instead, an anonymous array expression should be
used.
int[] daysInMonth;
daysInMonth = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; // Not ok.
daysInMonth = new int[] {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; //
ok.
Since an array element can be an object reference and arrays are objects,
array elements can themselves reference other arrays. In Java, an array of
arrays can be defined as follows:
In fact, the sequence of square bracket pairs, [], indicating the number of
dimensions, can be distributed as a postfix to both the element type and the
array name. Arrays of arrays are also sometimes called multidimensional
arrays.
double[][] identityMatrix = {
{1.0, 0.0, 0.0, 0.0 }, // 1. row
{0.0, 1.0, 0.0, 0.0 }, // 2. row
{0.0, 0.0, 1.0, 0.0 }, // 3. row
{0.0, 0.0, 0.0, 1.0 } // 4. row
}; // 4 x 4 Floating-point matrix
simple if Statement
if-else Statement
switch Statement
Simple if Statement
The simple if statement has the following syntax:
if (<conditional expression>)
<statement>
Note that <statement> can be a block, and the block notation is necessary if
more that one statement is to be executed when the <conditional
expression> is true.
Note that the if block can be any valid statement. In particular, it can be the
empty statement (;) or the empty block ({}). A common programming error is
an inadvertent use of the empty statement.
if (<conditional expression>)
<statement1>
else
<statement2>
The rule for matching an else clause is that an else clause always refers to
the nearest if that is not already associated with another else clause. Block
notation and proper indentation can be used to make the meaning obvious.
switch Statement
Conceptually the switch statement can be used to choose one among many
alternative actions, based on the value of an expression. Its general form is
as follows:
All labels (including the default label) are optional and can be defined in any
order in the switch body. There can be at most one default label in a switch
statement. If it is left out and no valid case labels are found, the whole
switch statement is skipped.
while statement
These loops differ in the order in which they execute the loop body and test
the loop condition. The while and the for loops test the loop condition before
executing the loop body, while the do-while loop tests the loop condition
after execution of the loop body.
while Statement
The syntax of the while loop is
The loop condition is evaluated before executing the loop body. The while
statement executes the loop body as long as the loop condition is true. When
the loop condition becomes false, the loop is terminated and execution
continues with the statement immediately following the loop. If the loop
condition is false to begin with, the loop body is not executed at all. In other
words, a while loop can execute zero or more times. The loop condition must
be a boolean expression.
The while statement is normally used when the number of iterations is not
known a priori.
while (noSignOfLife())
keepLooking();
Since the loop body can be any valid statement, inadvertently terminating
each line with the empty statement (;) can give unintended results.
do
<loop body>
while (<loop condition>);
The loop condition is evaluated after executing the loop body. The do-while
statement executes the loop body until the loop condition becomes false.
When the loop condition becomes false, the loop is terminated and execution
continues with the statement immediately following the loop. Note that the
loop body is executed at least once.
do { // (2)
mice.play();
} while (cat.isAway());
for Statement
The for loop is the most general of all the loops. It is mostly used for
counter-controlled loops, that is, when the number of iterations is known
beforehand.
<initialization>
while (<loop condition>) {
<loop body>
<increment expression>
}
The following code creates an int array and sums the elements in the array.
int sum = 0;
int[] array = {12, 23, 5, 7, 19};
for (int index = 0; index < array.length; index++) // (1)
sum += array[index];
The loop at (1) showed how a declaration statement can be specified in the
<initialization> section. Such a declaration statement can also specify a
comma-separated list of variables.
The variables i, j, and k in the declaration statement all have type int. All
variables declared in the <initialization> section are local variables in the for
block and obey the scope rules for local blocks.
int a[]={2,5,6,,8,4,9,10};
then to sum all the elements in this array , we require to traverse each
element of the array and add it, so for this, we can used loops. Check the
below diagram
Note that Java does not have a goto statement, although goto is a reserved
word.
break Statement
The break statement comes in two forms: the unlabeled and the labeled
form.
The unlabeled break statement terminates loops (for, while, do-while) and
switch statements which contain the break statement, and transfers control
out of the current context (i.e., the closest enclosing block). The rest of the
statement body is skipped, terminating the enclosing statement, with
execution continuing after this statement.
Example also shows that the unlabeled break statement only terminates
the innermost loop or switch statement that contains the break statement.
The break statement at (3) terminates the inner for loop when j is equal to 2,
and execution continues in the outer switch statement at (4) after the for
loop.
class BreakOut {
int n = 2;
1 1.0
2 1.4142135623730951
3 1.7320508075688772
Inner for loop:
0
1
default: 2
out:
{ // (1) Labeled block
// ...
if (j == 10) break out; // (2) Terminate block. Control to (3).
System.out.println(j); // Rest of the block not executed if j == 10.
// ...
}
// (3) Continue here.
continue Statement
Like the break statement, the continue statement also comes in two forms:
the unlabeled and the labeled form.
The continue statement can only be used in a for, while, or do-while loop to
prematurely stop the current iteration of the loop body and proceed with the
next iteration, if possible. In the case of the while and do-while loops, the
1 1.0
2 1.4142135623730951
3 1.7320508075688772
5 2.23606797749979
return Statement
return Statement
2.4 Classes
Class syntax:
class [className]
{
class student
{
Private int std_id;
Private String std_name;
}
• Both class variables and methods constitutes the class Members.
• UML Notation
Here Student is a class that is used to denote the student entity and
st is the references of the student class .
2. Creating an Object:
Note: In general , Object provides a handlers for the class , handler is used
to access the variables and methods in a class .
Static Members :
1. Non static members are specific for the object , means its number of
copies is dependent on the number of objects .
2. Non static member is called(used) by using the object of the class
3. Non static members are initialize when the constructor of the class is
called.(when object is created)
4. ―this‖ is available.
Class members are access by using the object of the class with the dot
operator (.), followed by the variable or method name . Static variables and
methods can also be called without using object name . Static member can
Non static variable and functions can be access by object of the class
followed by the variable and method name concatenate with the dot
operator.
2.9 Constructors
The main purpose of constructor is to set the initial state of an object when
the object is created using the new operator
class Student
{
int studid;
Student() // constructor of student class
{
System.out.print(―This is constructor of student class‖);
}
}
3. Constructor is used to set the initial value of object with their defaults
values .
4. There are two types of constructor , default constructor and
parameterized constructor , constructor with no input arguments are
called default constructor , constructor with the input arguments are
called parameterized constructor.
5. By default , if we don’t write any constructor , then java provides us a
default constructor with empty body which initialize the state of object
with default vales.
In addition to the top-level classes and interfaces, there are four categories
of nested classes and one of nested interfaces, defined by the context these
classes and interfaces are declared in:
The last three categories are collectively known as inner classes. They differ
from non-inner classes in one important aspect: that an instance of an inner
class may be associated with an instance of the enclosing class. The
instance of the enclosing class is called the immediately enclosing instance.
An instance of an inner class can access the members of its immediately
enclosing instance by their simple name.
A nested class or interface cannot have the same name as any of its
enclosing classes or interfaces
2.11 Inheritance:
Inheritance.
1. Inheritance in English means you should get something from the other
person.
2 . In terms of Programming , It is not about only getting something from the
other person but also getting something exclusive to you. Meaning of you in
object oriented terminology is sub class object.
in inheritance, we should never talk about parent and child, because then
there is never ending story.
class A
class B extends A // we tell B is inheriting from A
class C extends B // C is inheriting from B
class D extends C // D is inheriting from C
What is Extensibility
1. when we add a new feature into the super class, without making any
changes in the Sub class ,the sub class object is able to access
the new feature added in the super class.
Example
One day, customer comes tells in Employee class you need to add deptid, we
will add deptid into employee class, provide the necessary functions. Then
without making any changes in the SE class, SE object, will access the
deptid feature of Employee this is called extensibility. we can access feature
when we talk about inheritance the day we forget subclass object, we are
dead in inheritance.
Substitutability
Substitute means you don’t get what you were actually told you will get.
in real life, we like generalizing things. about we have always deal with
specializations.
In above object creation , object of Sub class is created and this object are
handled by the Sub class reference . Class left to the = sign , shows the type
of reference and class afer the = shows the type of the object.
Arrow 2 in the diagram shows that display function of super class will call if
we create object as :
As object is of type super class it calls the super class display function .
Arrow 3 shows that display function of the sub class is called , because the
object is of type sub , which is handled by super class reference , thanks to
substitutability feature of inheritance , because a sub class object can be
assigned either super class reference or sub class reference.
A final variable of a primitive data type cannot change its value once it
has been initialized.
A final variable of a reference type cannot change its reference value
once it has been initialized, but the state of the object it denotes can
still be changed.
These variables are also known as blank final variables. Final static
variables are commonly used to define manifest constants (also called
named constants), for example Integer.MAX_VALUE, which is the maximum
int value. Variables defined in an interface are implicitly final . Note that a
final variable need not be initialized at its declaration, but it must be
initialized once before it is used.
Final variables ensure that values cannot be changed, and final methods
ensure that behavior cannot be changed.
2.15 Abstract :
Abstract method in a class means that it is not provided what the function
do in class , but the body of method is implemented in the sub class , so
declaring a method abstract means that overriding of such method is
compulsory.
3.1 Packages
package com.practice.demoprograms ;
6. All java inbuild packages names start with either java or javax.
So it is advisable not to start a package name with the java or
javax.
Where to look? The Java runtime system needs to know where to find
programs that you want to run and libraries that are needed. It knows
where the predefined Java packages are, but if you are using additional
packages, you must tell specify where they are located.
C:/>java Hello
Now the interpreter will search this file ―Hello‖ in directory D:/
Advantages of Classpath:-
3.3 Access Modifier or Visibility control :Java has four access levels and
three access modifiers. There are only three modifiers because the default
(what you get when you don't use any access modifier) is one of the four
access levels.
Access Levels (in order of how restrictive they are, from least to most
restrictive)
private
Use private for virtually all instance variables, and for methods that you
don't want outside code to call (in other words, methods used by the public
methods of your class). But although you might not use the other two
(protected and default), you still need to know what they do because you'll
see them in other code.
default
Both protected and default access levels are tied to packages. Default access
is simple-it means that only code within the samepackage can access code
with default access. So a default class, for example can be accessed by only
classes within the same package as the default class.
protected
Protected access is almost identical to default access, with one exception: it
allows subclasses to inherit the protected thing, even if those subclasses are
outside the package of the super-class they extend: That's it. That's all
protected buys you-the ability to let your subclasses be outside your
superclass package, yet still inherit pieces of the class, including methods
and constructors.
There are two ways to used different classes from different package in our
class .
import javax.swing.*;
for importing specific class
import javax.swing.JOptionPane;
3.5 Interfaces
Defining Interfaces
A top-level interface has the following general syntax:
constant declarations
method prototype declarations
An interface does not provide any implementation and is, therefore, abstract
by definition. This means that it cannot be instantiated, but classes can
implement it by providing implementations for its method prototypes.
Declaring an interface abstract is superfluous and seldom done.
The member declarations can appear in any order in the interface body.
Since interfaces are meant to be implemented by classes, interface members
implicitly have public accessibility and the public modifier is omitted.
Interfaces with empty bodies are often used as markers to tag classes as
having a certain property or behavior. Such interfaces are also called ability
interfaces. Java APIs provide several examples of such marker interfaces:
java.lang.Cloneable, java.io.Serializable, java.util.EventListener.
Implementing Interfaces
Extending Interfaces
An interface can extend other interfaces, using the extends clause. Unlike
extending classes, an interface can extend several interfaces. The interfaces
extended by an interface (directly or indirectly), are called superinterfaces.
Conversely, the interface is a subinterface of its superinterfaces. Since
interfaces define new reference types, superinterfaces and subinterfaces are
also supertypes and subtypes, respectively.
Constants in Interfaces
An interface can also define named constants. Such constants are defined
by field declarations and are considered to be public, static and final. These
modifiers are usually omitted from the declaration. Such a constant must be
initialized with an initializer expression .
The String class is defined in the java.lang package and hence is implicitly
available to all the programs in Java. The String class is declared as final,
which means that it cannot be subclassed. It extends the Object class and
implements the Serializable, Comparable, and CharSequence interfaces.
The String objects are immutable, i.e., once an object of the String class is
created, the string it contains cannot be changed. In other words, once a
String object is created, the characters that comprise the string cannot be
changed. Whenever any operation is performed on a String object, a new
String object will be created while the original contents of the object will
remain unchanged. However, at any time, a variable declared as a String
reference can be changed to point to some other String object.
The String class defines several constructors. The most common constructor
of the String class is the one given below:
This constructor constructs a new String object initialized with the same
sequence of the characters passed as the argument. In other words, the
newly created String object is the copy of the string passed as an argument
to the constructor.
This constructor creates an empty String object. However, the use of this
constructor is unnecessary because String objects are immutable.
This constructor creates a new String object initialized with the same
sequence of characters currently contained in the array that is passed as
the argument to it.
This constructor creates a new String object initialized with the same
sequence of characters currently contained in the subarray. This subarray is
derived from the character array and the two integer values that are passed
as arguments to the constructor. The int variable startindex represents the
index value of the starting character of the subarray, and the int variable len
represents the number of characters to be used to form the new String
object.
This constructor creates a new String object that contains the same
sequence of characters currently contained in the string buffer argument.
This constructor creates the String object after decoding the array of bytes
and by using the subarray of bytes.
The String class defines the length() method that determines the length of a
string. The length of a string is the number of characters contained in the
string. The signature of the length() method is given below:
System.out.println(s);
This code will display the string "Our daily sale is 500 dollars".
The + operator may also be used to concatenate a string with other data
types. For example,
System.out.println(s);
This code will display the string "Our daily sale is 500 dollars". In this case,
the variable sale is declared as int rather than String, but the output
produced is the same. This is because the int value
contained in the variable sale is automatically converted to String type, and
then the + operator concatenates the two strings.
charAt( )
Here, where is the index of the character that you want to obtain. The value
of where must be nonnegative and specify a location within the string.
charAt( ) returns the character at the specified location. For example,
getChars( )
If you need to extract more than one character at a time, you can use the
getChars( ) method. It has this general form:
Here, sourceStart specifies the index of the beginning of the substring, and
sourceEnd specifies an index that is one past the end of the desired
substring. Thus, the substring contains the characters from sourceStart
through sourceEnd–1. The array that will receive the characters is specified
by target. The index within target at which the substring will be copied is
passed in targetStart. Care must be taken to assure that the target array is
large enough to hold the number of characters in the specified substring.
The following program demonstrates getChars( ):
class getCharsDemo {
public static void main(String args[]) {
String s = "This is a demo of the getChars method.";
int start = 10;
int end = 14;
char buf[] = new char[end - start];
s.getChars(start, end, buf, 0);
System.out.println(buf);
}
}
demo
getBytes( )
byte[ ] getBytes( )
Other forms of getBytes( ) are also available. getBytes( ) is most useful when
you are exporting a String value into an environment that does not support
16-bit Unicode characters. For example, most Internet protocols and text file
formats use 8-bit ASCII for all text interchange.
If you want to convert all the characters in a String object into a character
array, the easiest way is to call toCharArray( ). It returns an array of
characters for the entire string. It has this general form:
char[ ] toCharArray( )
String Comparison
The String class defines various methods that are used to compare strings
or substrings within strings. Each of them is discussed in the following
sections:
equals()
The equals() method is used to check whether the Object that is passed as
the argument to the method is equal to the String object that invokes the
method. It returns true if and only if the argument is a String object that
represents the same sequence of characters as represented by the invoking
object. The signature of the equals() method is as follows:
equalsIgnoreCase()
compareTo()
Value Meaning
Less than zero The invoking string is less than the argument string.
Zero The invoking string and the argument string are same.
Greater than zero The invoking string is greater than the argument string.
The String class also has the compareToIgnoreCase() method that compares
two strings without taking into consideration their case difference. The
signature of the method is given below:
regionMatches()
There is also an overloaded version of the method that tests the equality of
the substring ignoring the case of characters in the substring. Its signature
is given below:
startsWith()
The startsWith() method is used to check whether the invoking string starts
with the same sequence of characters as the substring passed as an
argument to the method. The signature of the method is given below:
In both signatures of the method given above, the prefix denotes the
substring to be matched within the invoking string. However, in the second
version, the startindex denotes the starting index into the invoking string at
which the search operation will commence.
endsWith()
The endsWith() method is used to check whether the invoking string ends
with the same sequence of characters as the substring passed as an
argument to the method. The signature of the method is given below:
Modifying a String
The String objects are immutable. Therefore, it is not possible to change the
original contents of a string. However, the following String methods can be
used to create a new copy of the string with the required modification:
substring()
The substring() method creates a new string that is the substring of the
string that invokes the method. The method has two forms:
where, startindex specifies the index at which the substring will begin and
endindex specifies the index at which the substring will end. In the first
form where the endindex is not present, the substring begins at startindex
and runs till the end of the invoking string.
Concat()
The concat() method creates a new string after concatenating the argument
string to the end of the invoking string. The signature of the method is given
below:
The replace() method creates a new string after replacing all the occurrences
of a particular character in the string with another character. The string
that invokes this method remains unchanged. The general form of the
method is given below:
trim()
The trim() method creates a new copy of the string after removing any
leading and trailing whitespace. The signature of the method is given below:
toUpperCase()
The toUpperCase() method creates a new copy of a string after converting all
the lowercase letters in the invoking string to uppercase. The signature of
the method is given below:
toLowerCase()
The toLowerCase() method creates a new copy of a string after converting all
the uppercase letters in the invoking string to lowercase. The signature of
the method is given below:
Searching Strings
The String class defines two methods that facilitate in searching a particular
character or sequence of characters in a string. They are as follows:
IndexOf()
lastIndexOf()
String buffers are safe for use by multiple threads. The methods are
synchronized where necessary so that all the operations on any particular
instance behave as if they occur in some serial order that is consistent with
the order of the method calls made by each of the individual threads
involved.
String buffers are used by the compiler to implement the binary string
concatenation operator +. For example, the code:
x = "a" + 4 + "c"
x = new StringBuffer().append("a").append(4).append("c")
.toString()
which creates a new string buffer (initially empty), appends the string
representation of each operand to the string buffer in turn, and then
converts the contents of the string buffer to a string. Overall, this avoids
creating many temporary strings.
Every string buffer has a capacity. As long as the length of the character
sequence contained in the string buffer does not exceed the capacity, it is
not necessary to allocate a new internal buffer array. If the internal buffer
overflows, it is automatically made larger.
4.1 Exceptions :
An exception in Java is a signal that indicates the occurrence of some
important or unexpected condition during execution. For example, a
requested file cannot be found, or an array index is out of bounds, or a
network link failed. Explicit checks in the code for such conditions can
easily result in incomprehensible code. Java provides an exception handling
mechanism for systematically dealing with such error conditions.
The exception mechanism is built around the throw-and-catch paradigm. To
throw an exception is to signal that an unexpected error condition has
Exceptions in Java are objects. All exceptions are derived from the java.lang.
Throwable class. The two main subclasses Exception and Error constitute
the main categories of throwables, the term used to refer to both exceptions
and errors.
1. Compile time error : if we have any syntax error , then this errors are
rectified during compilation of code , and your code is aborted until all the
compile time errors are removed . for example , if during the code designing ,
instead of while(condition) , we make a spell mistake for while , then it is
compile time error.
2. Run Time Error : If error occurs while running your application code ,
then it is called run time error , all the exception are run time errors .
3. Logical Error : if we have some logic problem then such types of errors are
called logical errors.
try {
} finally {
// finally block<statements>
}
Exceptions thrown during execution of the try block can be caught and
handled in a catch block. A finally block is guaranteed to be executed,
regardless of the cause of exit from the try block, or whether any catch block
was executed.
A few aspects about the syntax of this construct should be noted. The block
notation is mandatory. For each try block there can be zero or more catch
blocks, but only one finally block. The catch blocks and finally block must
always appear in conjunction with a try block, and in the above order. A try
block must be followed by either at least one catch block or one finally
block. Each catch block defines an exception handler. The header of the
try Block
The try block establishes a context that wants its termination to be handled.
Termination occurs as a result of encountering an exception, or from
successful execution of the code in the try block.
For all exits from the try block, except those due to exceptions, the catch
blocks are skipped and control is transferred to the finally block, if one is
specified . For all exits from the try block resulting from exceptions, control
is transferred to the catch blocks—if any such blocks are specified—to find a
matching catch block .If no catch block matches the thrown exception,
control is transferred to the finally block, if one is specified .
catch Block
Only an exit from a try block resulting from an exception can transfer
control to a catch block. A catch block can only catch the thrown exception
if the exception is assignable to the parameter in the catch block .The code
of the first such catch block is executed and all other catch blocks are
ignored.
After a catch block has been executed, control is always transferred to the
finally block, if one is specified. This is always true as long as there is a
finally block, regardless of whether the catch block itself throws an
exception.
In Example the method printAverage() calls the method
computeAverage() in a try catch construct at (4). The catch block is declared
to catch exceptions of type ArithmeticException. The catch block handles
the exception by printing the stack trace and some additional information at
(7) and (8), respectively.
Computing average.
Average = 100 / 20 = 5
Exit printAverage().
Exit main().
Computing average.
java.lang.ArithmeticException: / by zero
at Average2.computeAverage(Average2.java:24)
at Average2.printAverage(Average2.java:11)
at Average2.main(Average2.java:5)
Exception handled in printAverage().
Exit printAverage().
Exit main().
Important note :
1. We can mention more then one catch for a try block . each catch can
handle exception .
2. We can mention super class reference in the catch block . Super reference
can handle any exception of its type or of its sub class type.
3. Any line of code in try block, if we get exception , then execution of try is
aborted at that place and control moves to the catch block.
4. If exception thrown by try is not matched with any reference in catch
block , then program will terminate due to exception in your code.
finally Block
// other actions
} finally {
if (sum >= 0) calculateAverage();
}
The code above guarantees that if the try block is entered sumNumbers() will
be executed first and then later calculateAverage() will be executed in the
finally block, regardless of how execution proceeds in the try block. As the
operation in calculateAverage() is dependent on the success of
sumNumbers(), this is checked by the value of the sum variable before
calling calculateAverage(). catch blocks can, of course, be included to handle
any exceptions.
Computing average.
Finally in printAverage().
java.lang.ArithmeticException: Integer division by 0
at Average7.computeAverage(Average7.java:35)
at Average7.printAverage(Average7.java:19)
at Average7.main(Average7.java:6)
Exception handled in main().
Finally in main().
Exit main().
... someMethod(...)
throws <ExceptionType1>, <ExceptionType2>,..., <ExceptionTypen> { ... }
Any method that can cause a checked exception to be thrown, either directly
by using the throw statement or indirectly by invoking other methods that
can throw such an exception, must deal with the exception in one of three
ways. It can
use a try block and catch the exception in a handler and deal with it
use a try block and catch the exception in a handler, but throw
another exception that is either unchecked or declared in its throws
clause
explicitly allow propagation of the exception to its caller by declaring it
in the throws clause of its method protoype
throws Clause
System.out.println("Computing average.");
if (number == 0) // (9)
throw new IntegerDivisionByZero("Integer Division By Zero");
return sum/number; // (10)
}
}
Computing average.
IntegerDivisionByZero: Integer Division By Zero
at Average8.computeAverage(Average8.java:33)
at Average8.printAverage(Average8.java:22)
at Average8.main(Average8.java:7)
Exception handled in main().
Finally done in main().
Exit main().
The exception type specified in the throws clause in the method protoype
can be a superclass type of the actual exceptions thrown, that is, the
exceptions thrown must be assignable to the type of the exceptions specified
in the throws clause. If a method can throw exceptions of the type A, B, and
1. Don’t know whether to put try and catch or throws then better put throws.
2. Throw is used to indicate the person who is using out function that some
trouble has occurred in our function, the person who is using it, can deal with
it programmatically.
3. In a single function we can put try and catch also and also throws.
4. What is most important thing a person who is using only try and catch
when they are supposed throws, this will create a lot of mess
finally:
It is a block associated with try catch the main objective of finally
block is to maintain cleanup code which should execute always.
finalize:
It is a method should be executed by the ―Garbage Collector‖ just before
destroying an object. The main objective of finalize method is to maintain
cleanup code.
Note:
when compared with finalize, finally is always recommended to
maintain cleanup code because there is no guarantee for the exact behavior
of ―Garbage Collector‖ it is Virtual Machine Dependent.
throw and throws are two Java keyword related to Exception feature of Java
programming language. If you are writing Java program and familiar with
What is Exception in Java, its good chance that you are aware of What is
throw and throws in Java. In this Session we will compare throw vs throws
and see some worth noting difference between throw and throws in Java.
Exception handling is an important part of Java programming language which
enables you to write robust programs. There are five keywords related to
Exception handling in Java e.g. try, catch, finally, throw and throws.
1) throw keyword is used to throw Exception from any method or static block
in Java while throws keyword, used in method declaration, denoted which
Exception can possible be thrown by this method.
3) throw keyword can be used in switch case in Java but throws keyword can
not be used anywhere except on method declaration line.
5) throw transfers control to caller, while throws is suggest for information and
compiler checking.
The java.io package can be categories along with its stream classes in a
hierarchy structure shown below:
The InputStream class is used for reading the data such as a byte and
array of bytes from an input source. An input source can be a file, a string,
or memory that may contain the data. It is an abstract class that defines
the programming interface for all input streams that are inherited from it.
An input stream is automatically opened when you create it. You cans
explicitly close a stream with the close( )method, or let it be closed implicitly
when the object is found as a garbage.
OutputStream:
OutputStream is also inherited from the Object class. Each class of the
OutputStreams provided by the java.io package is intended for a different
purpose.
Java uses streams to handle I/O operations through which the data is
flowed from one location to another. For example, an InputStream can flow
the data from a disk file to the internal memory and anOutputStream can
flow the data from the internal memory to a disk file. The disk-file may be a
text file or a binary file. When we work with a text file, we use
a character stream where one character is treated as per byte on disk.
When we work with a binary file, we use a binary stream.
The working process of the I/O streams can be shown in the given diagram.
Java is one of the most popular programming languages that people use. It
is so popular because it can be used so widely from application software to
web applications. As a language it is class-based, concurrent, general
purpose and object-orientated. This allows it to have as few implementation
dependencies as possible.
Filename handling
To write anything to a file first of all we need a file name we want to use.
The file name is a simple string like like this:
However if you define a path in your file name then you have to take care
the path separator. On windows system the '\' is used and you need to
backslash it so you need to write '\\', in Unix,Linux systems
the separator is a simple slash '/'.
To make your code OS independent you can get the separator character as
follows:
Open a file
To open a file for writing use the FileWriter class and create an instance
from it.
The file name is passed in the constructor like this:
This code opens the file in overwrite mode. If you want to append to the file
then
you need to use an other constructor like this:
Besides this the constructor can throw an IOException so we put all of the
code inside
a try-catch block.
Write to file
At this point we have a writer object and we can send real content to the
file. You can do this using the write() method, which has more variant but
the most commonly used requires a string as input parameter.
Calling the write() method doesn't mean that it immediately writes the data
into the file. The output is maybe cached so if you want to send your data
immediately to the file you need to call the flush() method.
As last step you should close the file with the close() method and you are
done.
However in a real world situation the FileWriter usually not used directly.
Instead of FileWriter the BufferedWriter or from Java 1.5 the PrintWriter are
used. These writer objects gives you more flexibility to handle your IO. Here
is a simple BufferedWriter example:
Code:
If everything is alright, you have successfully written some basic text into a
file. Now it's time to read the file content back. Not surprisingly reading from
a file is very similar to writing. We only need to use *Reader objects instead
of *Writer objects. It means that you can use FileReader or BufferedReader.
As a simple FileReader can handle only a single character or a character
array it is more convenient to use the BufferedReader which can read a
complete line from a file as a string. So using a BufferedReader we can read
Code:
import java.io.*;
class copypaste
{
public static void main(String args[])
{
FileReader fr= null;
BufferedReader br= null;
FileWriter fw= null;
BufferedWriter bw= null;
try
{
fr= new FileReader("arr.txt");
br= new BufferedReader(fr);
fw= new FileWriter("b.txt");
String text=null;
while((text=br.readLine())!=null)
{
bw.write(text);
bw.newLine();
System.out.println("pasting done");
}catch(FileNotFoundException e)
{
System.out.println("file name is not valid");
}catch(IOException e)
{
System.out.println("some probem occurs");
}
finally
{
bw.close();
br.close();
}
}
}
5.1 Multitasking :
Multiprocessing
MultiThreading
At the fine grain level , there is multithreading which allows part of the same
program to run concurrently on the computer , a separate path of execution
is used to run different parts of the same application , these separate path
of execution in process is called threads which are independent of each
others . For Example , in a word processor , during printing of some pages ,
printing and formatting are done simuntenouly.
5.2 Threads :
Threads is a path of execution within a program that shares code and data
among other threads , that’s why threads are called light weighted process
.In java , there are two types of threads
Threads which is created by the system is called daemon threads which are
used to create user defined threads means all the user defined threads are
spawned from Daemon threads . whenever all the user defined threads are
executing in a program , your program didn’t terminate .
Thread(Runnable threadTarget)
The first method returns the name of the thread. The second one sets the
thread's name to the argument.
try {
int val;
do {
val = counterA.getValue(); // (6) Access the counter value.
System.out.println("Counter value read by main thread: " + val);
Thread.sleep(1000); // (7) Current thread sleeps.
} while (val < 5);
} catch (InterruptedException e) {
System.out.println("main thread interrupted.");
}
Thread[Counter A,5,main]
Counter value read by main thread: 0
Counter A: 0
Counter A: 1
Counter A: 2
Counter A: 3
Counter value read by main thread: 4
Counter A: 4
Exit from thread: Counter A
Counter value read by main thread: 5
Exit from main() method.
The Client class uses the Counter class. It creates an object of class Counter
at (5) and retrieves its value in a loop at (6). After each retrieval, it sleeps for
1,000 milliseconds at (7), allowing other threads to run.
A class can also extend the Thread class to create a thread. A typical
procedure for doing this is as follows :
the Counter class from Example has been modified to illustrate extending
the Thread class. Note the call to the constructor of the superclass Thread at
(1) and the invocation of the inherited start() method at (2) in the
constructor of the Counter class. The program output shows that the Client
class creates two threads and exits, but the program continues running
until the child threads have completed. The two child threads are
independent, each having its own counter and executing its own run()
method.
When creating threads, there are two reasons why implementing the
Runnable interface may be preferable to extending the Thread class:
5.4 Synchronization :
Threads shares the same memory and resources . However, there are
situations where it is desirable that only one thread at a time to access the
shared resources. Foe Example, creditng and debiting a shared bank
account concurrently amongst several users without proper discipline will
endanger the integrity of data , so in that scenario , we are forcing that only
one thread have access the shared resources . This synchronization can be
achieved by using
1. Synchronized Methods
2. Synchronized Blocks
Synchronized Methods :
Synchronized blocks
Figure shows the states and the transitions in the life cycle of a thread.
Various methods from the Thread class are presented next. Examples of
their usage are presented in subsequent sections.
This method can be used to find out if a thread is alive or dead. A thread is
alive if it has been started but not yet terminated, that is, it is not in the
Dead state.
The first method returns the priority of the current thread. The second
method changes its priority. The priority set will be the minimum of the two
values: the specified newPriority and the maximum priority permitted for
this thread.
This method causes the current thread to temporarily pause its execution
and, thereby, allow other threads to execute.
The current thread sleeps for the specified time before it takes its turn at
running again.
A call to any of these two methods invoked on a thread will wait and not
return until either the thread has completed or it is timed out after the
specified time, respectively.
void interrupt()
Threads are assigned priorities that the thread scheduler can use to
determine how the threads will be scheduled. The thread scheduler can use
thread priorities to determine which thread gets to run. The thread
scheduler favors giving CPU time to the thread with the highest priority in
the Ready-to-run state. This is not necessarily the thread that has been the
longest time in the Ready-to-run state. Heavy reliance on thread priorities
for the behavior of a program can make the program unportable across
platforms, as thread scheduling is host platform–dependent.
Priorities are integer values from 1 (lowest priority given by the constant
Thread. MIN_PRIORITY) to 10 (highest priority given by the constant
Thread.MAX_PRIORITY). The default priority is 5 (Thread.NORM_PRIORITY).
A thread inherits the priority of its parent thread. Priority of a thread can be
set using the setPriority() method and read using the getPriority() method,
both of which are defined in the Thread class. The following code sets the
myThread.setPriority(Math.min(Thread.MAX_PRIORITY,
myThread.getPriority()+1));
Thread Scheduler
Preemptive scheduling.
After its start() method has been called, the thread starts life in the Ready-
to-run state. Once in the Ready-to-run state, the thread is eligible for
running, that is, it waits for its turn to get CPU time. The thread scheduler
decides which thread gets to run and for how long. Figure illustrates the
transitions between the Ready-to-Run and Running states. A call to the
static method yield(), defined in the Thread class, will cause the current
thread in the Running state to transit to the Ready-to-run state, this
relinquishing the CPU. The thread is
By calling the static method yield(), the running thread gives other threads
in the Ready-to-run state a chance to run. A typical example where this can
be useful is when a user has given some command to start a CPU-intensive
computation, and has the option of canceling it by clicking on a Cancel
button. If the computation thread hogs the CPU and the user clicks the
Cancel button, chances are that it might take a while before the thread
monitoring the user input gets a chance to run and take appropriate action
to stop the computation. A thread running such a computation should do
the computation in increments, yielding between increments to allow other
threads to run. This is illustrated by the following run() method:
A call to the static method sleep() in the Thread class will cause the
currently running thread to pause its execution and transit to the Sleeping
state. The method does not relinquish any lock that the thread might have.
The thread will sleep for at least the time specified in its argument, before
transitioning to the Ready-to-run state where it takes its turn to run again.
If a thread is interrupted while sleeping, it will throw an
InterruptedException when it awakes and gets to execute.
These methods can only be executed on an object whose lock the thread
holds, otherwise, the call will result in an IllegalMonitorStateException.
A thread invokes the wait() method on the object whose lock it holds. The
thread is added to the wait set of the object.
The first are those based directly on the applet class , use the Abstract
window toolkit components for graphical user interface
The second type of applets care based on the swing class called
JApplet . Swing applets uses the swing components for graphic user
interface .
JApplets inherits from Applets , All the features of Applet are also available
in JApplet.
Local Applet are written in local system and stored in the file structure of
the local system , when this applets are included in the java enabled
Applet runs in the browser and its lifecycle method are called by JVM when
it is loaded and destroyed. Here are the lifecycle methods of an Applet:
stop(): This method can be called multiple times in the life cycle of an
Applet.
destroy(): This method is called only once in the life cycle of the applet
when applet is destroyed.
init () method: The life cycle of an applet is begin on that time when the
applet is first loaded into the browser and called the init() method. The init()
method is called only one time in the life cycle on an applet. The init()
method is basically called to read the PARAM tag in the html file. The init ()
method retrieve the passed parameter through the PARAM tag of html file
using get Parameter() method All the initialization such as initialization of
variables and the objects like image, sound file are loaded in the init ()
method .After the initialization of the init() method user can interact with
the Applet and mostly applet contains the init() method.
Stop () method: The stop() method can be called multiple times in the life
cycle of applet like the start () method. Or should be called at least one time.
There is only miner difference between the start() method and stop ()
method. For example the stop() method is called by the web browser on that
time When the user leaves one applet to go another applet and the start()
method is called on that time when the user wants to go back into the first
program or Applet.
destroy() method: The destroy() method is called only one time in the life
cycle of Applet like init() method. This method is called only on that time
when the browser needs to Shut down.
import java.applet.Applet;
import java.awt.Graphics;
<Html>
<Head>
<Title>Java Example</Title>
<Body>
This is my page<br>
Below you see an applet<br>
<br>
<Applet Code="MyApplet.class" width=200 Height=100>
</Applet>
</Body>
</Html>
Two HTML tags are relevant according to applets: <Applet> and <Param>.
<Param Name=NameOfParameter
Value="ValueOfParameter">
6.1 Drivers : Drivers are used to connect database and the java application.
The Type 1 driver translates all JDBC calls into ODBC calls and sends them
to the ODBC driver. ODBC is a generic API. The JDBC-ODBC Bridge driver
Advantage
The JDBC-ODBC Bridge allows access to almost any database, since the
database's ODBC drivers are already available.
Disadvantages
1. Since the Bridge driver is not written fully in Java, Type 1 drivers are not
portable.
2. A performance issue is seen as a JDBC call goes through the bridge to the
ODBC driver, then to the database, and this applies even in the reverse
process. They are the slowest of all driver types.
3. The client system requires the ODBC Installation to use the driver.
4. Not good for the Web.
The distinctive characteristic of type 2 jdbc drivers are that Type 2 drivers
convert JDBC calls into database-specific calls i.e. this driver is specific to a
particular database. Some distinctive characteristic of type 2 jdbc drivers
are shown below. Example: Oracle will have oracle native api.
Advantage
The distinctive characteristic of type 2 jdbc drivers are that they are typically
offer better performance than the JDBC-ODBC Bridge as the layers of
communication (tiers) are less than that of Type
1 and also it uses Native api which is Database specific.
Disadvantage
1. Native API must be installed in the Client System and hence type 2
drivers cannot be used for the Internet.
2. Like Type 1 drivers, it’s not written in Java Language which forms a
portability issue.
3. If we change the Database we have to change the native api as it is
specific to a database
4. Mostly obsolete now
5. Usually not thread safe.
Type 3 database requests are passed through the network to the middle-tier
server. The middle-tier then translates the request to the database. If the
Advantage
Disadvantage
Advantage
1. The major benefit of using a type 4 jdbc drivers are that they are
completely written in Java to achieve platform independence and eliminate
deployment administration issues. It is most suitable for the web.
2. Number of translation layers is very less i.e. type 4 JDBC drivers don't
have to translate database requests to ODBC or a native connectivity
interface or to pass the request on to another server, performance is
typically quite good.
3. You don’t need to install special software on the client or server. Further,
these drivers can be downloaded dynamically.
Disadvantage
With type 4 drivers, the user needs a different driver for each database.
1. Importing required classes : The very first step that is required while
connecting java code to database is that we have to import the required
class for connection . As an example , for connection mysql , the required
classes are present inside java.sql package .
2. Load the JDBC driver: Once you import the required classes , next step
is to load the driver for connectivity to database. Java provides a class with
the name ―Class‖ which is used to load the driver by using its static method
forName . So we load the driver by calling Class.forName() method.
try {
Class.forName( "com.mysql.jdbc.Driver" );
}
catch (Exception e)
{
System.out.println( “Unable to establish the connection” );
}
Java provides Connection interface which hold the connection reference for
executing different queries .
• Once establish the connection with database server we can interact with
database using statement object.
The simplest way to handle the results is to process them one row at a time,
using the ResultSet’s next method to move through the table a row at a
time. Within a row, ResultSet provides various getXxx methods that take a
column index or column name as an argument and return the result as a
variety of different Java types. For instance, use getInt if the value should be
an integer, getString for a String, and so on for most other data types. If you
just want to display the results, you can use getString regardless of the
actual column type. However, if you use the version that takes a column
index, note that columns are indexed starting at 1 (following the SQL
convention), not at 0 as with arrays, vectors, and most other data structures
in the Java programming language.
Note that the first column in a ResultSet row has index 1, not 0. Here is an
example that prints the values of the first three columns in all rows of a
ResultSet.
while(resultSet.next()) {
System.out.println(results.getString(1) + " " +
results.getString(2) + " " +
results.getString(3));
}
connection.close();
This session is used to for selection the particular rows according to DBMS
select query .
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(url,"root","shishav");
String query="select * from login_table where username=?";
PreparedStatement ps = con.prepareStatement(query);
ps.setString(1, "adi");
if(rs.next())
{
// fetch the rows until the empty row , rs.next() returns false if row
//don’t have any data , else it returns true
do
{
// USERNAME and PASS are the column names in table of Database
// we can also used the number of column starting from 1.
}while(rs.next());
}
else
{
System.out.println("no row selected");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally
{
try {
//Close the connection
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
This session is used for learning the insertion of data from java program to
dbms table.
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(url,"root","shishav");
String query="insert into [table name] [columns name comma separated]
values (values for the columns in comma separated ) ";
PreparedStatement ps = con.prepareStatement(query);
// if we want to insert the values according to some class attributes or some
//variable , then we can add ? in the query and fill the ? like this , 1st ? in
// the query have 1 number as shown below
// insert into emp(empid) values(?);
// above query have single ? . so its value is filled by adi as shown in below
//line
ps.setString(1, "adi");
int rs = ps.executeUpdate();
if(rs >0)
{
System.out.println(―rows successfully inserted‖);
}
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally
{
try {
//Close the connection
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
This session is used for learning the deletion of data from Database table
using java program .
// Import the required Drivers
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(url,"root","shishav");
String query="delete from [tablename] where [condition] ";
PreparedStatement ps = con.prepareStatement(query);
// if we want to insert the values according to some class attributes or some
//variable , then we can add ? in the query and fill the ? like this , 1st ? in
// the query have 1 number as shown below
// delete from emp where empid=?
// above query have single ? . so its value is filled by adi as shown in below
//line
ps.setString(1, "adi");
int rs = ps.executeUpdate();
if(rs >0)
{
// in case of deletion , number of rows deleted is returned by
//executeUpdate(),if value is less then 0, then no deletion
System.out.println(―rows successfullydeleted‖);
}
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally
{
try {
//Close the connection
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Updation in the database table is similar like insertion and deletion , only
the query syntax is changed according to requirement . In case of updation ,
query will be
Summary :
Chapter 7: Collections
Collection is used to create group of object that can be treated like a single
unit. Objects can be stored , manipulated or deleted in the group of objects ,
Core Interfaces
The elements in a Set must be unique, that is, no two elements in the set
can be equal. The order of elements in a List is retained, and individual
elements can be accessed according to their position in the list.
The Map interface does not extend the Collection interface because
conceptually, a map is not a collection. A map does not contain elements. It
contains mappings (also called entries) from a set of key objects to a set of
value objects. A key can, at most, be associated with one value. As the name
implies, the SortedMap interface extends the Map interface to maintain its
mappings sorted in key order.
Sets
The HashSet class implements the Set interface. Since this implementation
uses a hash table, it offers near constant-time performance for most
operations. A HashSet does not guarantee any ordering of the elements.
However, the LinkedHashSet subclass of HashSet guarantees insertion-
order. The sorted counterpart is TreeSet, which implements the SortedSet
interface and has logarithmic time complexity .
HashSet()
HashSet(Collection c)
Constructs a new set containing the elements in the specified collection. The
new set will not contain any duplicates. This offers a convenient way to
remove duplicates from a collection.
HashSet(int initialCapacity)
Constructs a new, empty set with the specified initial capacity and the
specified load factor.
Lists
Lists are collections that maintain their elements in order, and can contain
duplicates. The elements in a list are ordered. Each element, therefore, has
a position in the list. A zero-based index can be used to access the element
at the position designated by the index value. The position of an element can
change as elements are inserted or deleted from the list.
Replaces the element at the specified index with the specified element. It
returns the previous element at the specified index.
Inserts the specified element at the specified index. If necessary, it shifts the
element previously at this index and any subsequent elements one position
toward the end of the list. The inherited method add(Object) from the
Collection interface will append the specified element to the end of the list.
Deletes and returns the element at the specified index, contracting the list
accordingly. The inherited method remove(Object) from the Collection
interface will remove the first occurrence of the element from the list.
Inserts the elements from the specified collection at the specified index,
using the iterator of the specified collection. The method returns true if any
elements were added.
In a non-empty list, the first element is at index 0 and the last element is at
size()-1. As might be expected, all methods throw an
IndexOutOfBoundsException if an illegal index is specified.
int indexOf(Object o)
int lastIndexOf(Object o)
These methods respectively return the index of the first and the last
occurrence of the element in the list if the element is found; otherwise, the
value –1 is returned.
// List Iterators
ListIterator listIterator()
ListIterator listIterator(int index)
The iterator from the first method traverses the elements consecutively,
starting with the first element of the list, whereas the iterator from the
second method starts traversing the list from the element indicated by the
specified index.
boolean hasNext();
boolean hasPrevious();
// Open Range-View
List subList(int fromIndex, int toIndex)
This method returns a view of the list, which consists of the sublist of the
elements from the index fromIndex to the index toIndex-1. A view allows the
range it represents in the underlying list to be manipulated. Any changes in
The ArrayList class implements the List interface. The Vector class is a
legacy class that has been retrofitted to implement the List interface. The
Vector and ArrayList classes are implemented using dynamically resizable
arrays, providing fast random access and fast list traversal—very much like
using an ordinary array. Unlike the ArrayList class, the Vector class is
thread-safe, meaning that concurrent calls to the vector will not compromise
its integrity.
The ArrayList and Vector classes offer comparable performance, but Vector
objects suffer a slight performance penalty due to synchronization. Position-
based access has constant-time performance for the ArrayList and Vector
classes. However, position-based access is in linear time for a LinkedList,
owing to traversal in a doubly-linked list. When frequent insertions and
deletions occur inside a list, a LinkedList can be worth considering. In most
cases, the ArrayList implementation is the over-all best choice for
implementing lists
Map :
Map is a two column data structure , advantage of a map if we give the key,
it tells us the value.
m.get(key) : it returns the value for the key , if key is not there , then it
returns null value , else it returns the value for the key.
m.remove(key) : this method is used to delete the key value pair if the key
passed is present in the Map ,
else it returns null . it returns Object type value.
Map.Entry x = null;
while(i.hasNext())
{
x = (Entry) i.next();
System.out.println(x.getKey() + " -- " + x.getValue());
}
Dump way to run thru the map
Map m =new HashMap();
m.put("pen",3);
m.put("pen",4);
m.put("abc", 1);
Set s = m.keySet();
Iterator i = s.iterator();
// good thing we are running thru the map
//but what is pathetic about it is
// we get the key from iterator
// and then run to the map to get the value
while(i.hasNext())
{
Object key = i.next();
Object value = m.get(key);
System.out.println(key + "---" + value);