Java Programming (BCA 3rd Year)
Java Programming (BCA 3rd Year)
Java Solutions
Code in java
Shishav jain
3/10/2014
Indexing
Unit 1 : Introduction
2.1 Classes
2.2 Objects
2.3 Static and Non Static Members
2.4 Accessing Class members
2.5 Method Overloading
2.6 Constructors
2.7 Nested and Inner class
2.8 Inheritance
2.9 Method Overriding
2.10 Difference between Method overloading and overriding
2.11 Final with Inheritance
2.12 Abstract
3.1 Array
3.2 Anonymous Array
3.3 Multidimensional Array
3.4 Packages
3.5 Concept of CLASSPATH
3.6 Access Modifier or Visibility control
3.7 Using other package in class
3.8 Interfaces
3.9 String Handling
3.10 Constructors defined in the String class
3.11 Special String Operations
3.12 String Buffer
3.13 Vector
3.14 Wrapper Classes
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
Encapsulation
Abstraction
Inheritance
Polymorphism
Java C++
Java and Internet: Java is strongly associated with the Internet. Internet
users can use Java to create applet programs and run them locally using a
"Java-enabled browser" such as HotJava. They can also use a Java-enabled
browser to download an applet located on a computer anywhere in the
Internet and run it on his local computer. In fact, Java applets have made
the Internet a true extension of the storage system of the local computer.
Internet users can also setup their websites containing java applets that
could be used by other remote users of Internet. This feature made Java
most popular programming language for Internet.
Java and World Wide Web: World Wide Web (WWW) is an open-ended
information retrieval system designed to be used in the Internet's
distributed environment. This system contains Web pages that provide
both information and controls. Web system is open-ended and we can
navigate to a new document in any direction. This is made possible with
the help of a language called Hypertext Markup Language (HTML). Web
pages contain HTML tags that enable us to find, retrieve, manipulate and
display documents worldwide.
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 can’t 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, Because they can’t ptr++ or ptr--. Internally java compiler
controls the pointer working.
4. Robust
Memory leaks cannot happen, pointer cannot freak around in the memory.
This happens because java itself have the responsibly of garbage
collection , we can allocate memory using new operator in java , but java
itself collected back this memory when object are not reachable .And
exception handling is much more powerful in java as compared to
previous languages , that make the java robust.
7. Multithreaded enviouement :
Java supports multithreading , through which we can do multitasking in
our program , so that we can utilize our processor more effectively.
Tokens are the various Java program elements which are identified by the
compiler. A token is the smallest element of a program that is meaningful
to the compiler. Tokens supported in Java include keywords, variables,
constants, special characters, operations etc.
When you compile a program, the compiler scans the text in your source
code and extracts individual tokens. While tokenizing the source file, the
compiler recognizes and subsequently removes whitespaces (spaces,
tabs, newline and form feeds) and the text enclosed within comments.
Now let us consider a program
//Print Hello
{
Public static void main(String args[])
System.out.println(“Hello Java”);
The source code contains tokens such as public, class, Hello, {, public,
static, void, main, (, String, [], args, {, System, out, println, (, "Hello
Java", }, }. The resulting tokens· are compiled into Java bytecodes that is
capable of being run from within an interpreted java environment. Token
are useful for compiler to detect errors. When tokens are not arranged in
a particular sequence, the compiler generates an error message.
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
Separators
Separators in Java
1.4 Comments
MultiLine Comments
/* 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
Note:
• 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
Double 64 4.94065645841246544e-3241.79769313486231570e+308
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
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 :
int i=5; //fine
Ex : int i,j;
i=j=10; //(i=(j=10))
int b =10;
int c = a+b;
Arithmetic Operators
+ Addition - Subtraction
Note:
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
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
value? (Inequality)
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 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
i++ uses the current value of i as the value of expression first , then it is
incremented by 1.
Below diagram explains the post Increment operator.
++i add 1 to i first , then uses the new value of i as the value for the
expression .
& ( and ) : Do not confuse this with the && operator. This operator is
used to AND two integers. The ANDing is done bitwise, that is the i-th bit
of the left operand and i-th bit of the right operand are ANDed to give the
i-th bit of the result.
For e.g.
13 & 14 = 12
1101 // 13 in form of 0 and 1
& 1110 // 14 in form of 0 and 1
------
1100 // 12 in form of 0 and 1
| ( or ) : Do not confuse this with the || operator. This operator is used to
OR two integers. The XORing is done similar to that of the previous two
operators.
For e.g.
13 | 14 = 15
1101
| 1110
------
1111
^ ( xor ) : This operator is used to XOR two integers. The XORing is done
similar to that of the previous two operators.
For e.g.
13 ^ 14 = 3
1101
^ 1110
------
0011
~ (not): This unary operator returns the bitwise NOT of an integer. This is
not to be confused with the logical not (!) operator.
For example, (!1) returns 0 (false), but (~1) returns 0xfffffffe; the logical
value of both being true.
>> ( right-shift ) : The operator shifts the integer n, k-bits to the right
and returns that if it's used as
There is one more bit-shift operator for Java Programmers, that is the
unsigned right-shift operator
>>> ( unsigned right-shift ) : While the signed right-shift operator
( >> ) shifts the bits to the right and the left most bits depends on sign
extension, the unsigned right-shift operator ( >>> ) shifts zeros to the left
most bits. Note that this operator is not in C/C++, as there are unsigned
data types in C/C++ and not in Java.
Example:
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 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-else 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
{
case label1: <statement1>
case label2: <statement2>
...
case labeln: <statementn>
default: <statement>
} // end switch
The case labels are constant expressions whose values must be unique,
meaning no duplicate values are allowed. The case label values must be
assignable to the type of the switch expression . In particular, the case
label values must be in the range of the type of the switch expression.
Note that the type of the case label cannot be boolean, long, or floating-
point.
while statement
do-while statement
for 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
while(<loop condition>)
<loop body>
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-while Statement
do
<loop body>
while (<loop condition>);
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>
}
int sum = 0;
int[] array = {12, 23, 5, 7, 19};
for (int index = 0; index < array.length; index++) // (1)
sum += array[index];
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
break
continue
return
try-catch-finally
throw
assert.
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;
switch (n) {
case 1: System.out.println(n); break;
case 2: System.out.println("Inner for loop: ");
for (int j = 0; j < n; j++)
if (j == 2)
break; // (3) Terminate loop. Control to (4).
else
System.out.println(j);
default: System.out.println("default: " + n); // (4) Continue here.
}
}
}
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 rest of the loop body is skipped, that is, stopping the current
iteration, with execution continuing with the <loop condition>. In the case
of the for loop, the rest of the loop body is skipped, with execution
continuing with the <increment expression>.
1 1.0
return Statement
return Statement
2.1 Classes
Class syntax:
class [className]
{
class student
{
private int std_id;
private String std_name;
• UML Notation
2.2 Objects
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 access either object name or class name followed by the
variable name and method name , concatenated using dot operator .
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.
Note: Methods with same name and same argument ,but different return
type in a class are not overloaded methods.
2.6 Constructors
class Student
{
int studid;
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.8 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 of the super class directly by the subclass object.
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.
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.12 Abstract :
3.1 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.
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.
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
3.4 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.
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 .
String s = javax.swing.JOptionPane.showInputDialog(“enter
the string value”);
import javax.swing.*;
for importing specific class
import javax.swing.JOptionPane;
3.8 Interfaces
Defining Interfaces
A top-level interface has the following general syntax:
constant declarations
method prototype declarations
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 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.
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.
public String()
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
char ch;
String s=”java solutions”;
ch= s.charAt(3);
assigns the value "a" to ch.
getChars( )
If you need to extract more than one character at a time, you can use the
getChars( ) method. It has this general form:
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( )
toCharArray( )
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() :
public boolean equals(Object str)
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()
where, str is the String being compared to the invoking String. The
compareTo() method returns an int value as the result of String
comparison. The meaning of these values are given in the following table:
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.
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()
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
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()
replace()
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()
toLowerCase()
Searching Strings
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.
3.13 Vector
Vectors are dynamic arrays which can extend or shrink when objects are
added in the vector. Vector class is part of java.util package. Vector
proves to be very useful if you don't know the size of the array in advance
or you just need one that can change sizes over the lifetime of a program.
Vector comes under the collection of java. Vectors are synchronized
objects.
The Vector class supports four constructors. The first form creates a
default vector, which has an initial size of 10:
Vector( )
Vector(int size)
The third form creates a vector whose initial capacity is specified by size
and whose increment is specified by incr. The increment specifies the
number of elements to allocate each time that a vector is resized upward:
The fourth form creates a vector that contains the elements of collection
c:
Vector(Collection c)
boolean add(Object o)
boolean addAll(Collection c)
Appends all of the elements in the specified Collection to the end of this
Vector, in the order that they are returned by the specified Collection's
Iterator.
Inserts all of the elements in in the specified Collection into this Vector at
the specified position.
boolean removeAll(Collection c)
Removes from this Vector all of its elements that are contained in the
specified Collection.
void removeAllElements()
Removes all components from this vector and sets its size to zero.
boolean removeElement(Object obj)
removeElementAt(int index)
protected void removeRange(int fromIndex, int toIndex)
Removes the first occurrence of the specified element in this Vector If the
Vector does not contain the element, it is unchanged.
Searches for the first occurence of the given argument, testing for equality
using the equals method.
int indexOf(Object elem, int index)
Searches for the first occurence of the given argument, beginning the search
at index, and testing for equality using the equals method.
There is a wrapper class for every primitive date type in Java. This class
encapsulates a single value for the primitive data type. For instance the
wrapper class for int is Integer, for float is Float, and so on. Remember
that the primitive name is simply the lowercase name of the wrapper
except for char, which maps to Character, and int, which maps to Integer.
The wrapper classes in the Java API serve two primary purposes:
To provide a mechanism to “wrap” primitive values in an object so that
the primitives can be included in activities reserved for objects, like as
being added to Collections, or returned from a method with an object
return value.
4.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.
4.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
Thread(Runnable threadTarget)
Thread(Runnable threadTarget, String threadName)
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:
4.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.
Dead state : Once in this state, the thread cannot ever run again
Various methods from the Thread class are presented next. Examples of
their usage are presented in subsequent sections.
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).
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
browser , there is no requirement for the internet connectivity . Browser
search for the Applet in the local system path as defined in the HTML page
code.
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.
For Example if the user wants to return to the Applet, in this situation the
start Method() of an Applet will be called by the web browser and the user
will be back on the applet. In the start method user can interact within the
applet.
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
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>
</Head>
<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 is
recommended only for experimental use or when no other alternative is
available.
Advantage
The JDBC-ODBC Bridge allows access to almost any database, since the
database's ODBC drivers are already available.
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.
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 middle-tier server can in turn use Type1, Type 2 or Type 4 drivers.
Advantage
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” );
}
• 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
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");
ResultSet rs = ps.executeQuery();
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();
Written by : Shishav Jain Mob:8290280309 Page Number :95
} 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 java.sql.Connection;
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) {
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 :