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 is a true and complete object C++ is an extension of C with object
oriented language. oriented behaviour. C++ is not a
complete object oriented language as
that of Java.
Java does not provide template C++ offers Template classes.
classes.
Java supports multiple inheritance C++ achieves multiple inheritance by
using interface. permitting classes to inherit from
multiple classes.
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
{
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
Tokens are the smallest unit of Program There is Five Types of Tokens
1) Reserve Word or Keywords
2) Identifier
3) Literals
4) Operators (Topic 1.7)
5) Separators
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 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
Note:
• 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)
Right Associativity implies grouping from right to left.
(1+(2-3))
<variable>=<expression>
Note:
For Ex :
Ex : int i,j;
i=j=10; //(i=(j=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
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
value? (Inequality)
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 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
boolean b4 = b1 || !b3 && b2; // false, short-circuit evaluated as
// (b4 = (b1 || ((!b3) && b2)))
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.
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
n >> k. New ones are appended at the end.
Right-shifting is equivalent to dividing the number by 2k.
<< ( left-shift ) : The operator shifts the integer n, k-bits to the right and
returns that if it's used as
n << k. New zeros are appened at the end.
Left-shifting is equivalent to multiplying the number by 2k. Thus the
expression 1<<n represents 2n.
Example:
simple if Statement
if-else Statement
switch Statement
Simple if Statement
The simple if statement has the following syntax:
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-else Statement
if (<conditional expression>)
<statement1>
else
<statement2>
Ex 1: if (emergency)
operate();
else
joinQueue();
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.
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:
{
case label1: <statement1>
case label2: <statement2>
...
case labeln: <statementn>
default: <statement>
} // end switch
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.
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
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>);
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();
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.
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.
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
2 1.4142135623730951
3 1.7320508075688772
5 2.23606797749979
return Statement
return Statement
2.1 Classes
Class syntax:
class [className]
{
class student
{
private int std_id;
private String std_name;
}
• Both class variables and methods constitute the class Members.
• 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
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.6 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.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
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.12 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 Arrays:
Or
where <element type> can be a primitive data type or a reference type. The
array variable <array name> has the type <element type>[]. Note that the
array size is not specified. This means that the array variable <array name>
can be assigned an array of any length, as long as its elements have
<element type>.
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 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:
can be used to construct arrays using an array creation expression. The size
of the array is specified in the array creation expression, which creates the
array and initializes the array elements to their default values. On the other
hand, the following declaration statement
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
3.4 Packages
package com.practice.demoprograms ;
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:-
1. Using classpath variable largest path can be written once but can be
used multiple times.
2. Using classpath we can clearly specify where from to search the
required file in computer.
3. Classpath is much useful in Packages.
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)
public
Use public for classes, constants (static final variables) , and methods that
you're exposing to other code (for example getters and setters) and most
constructors.
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
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;
Defining Interfaces
A top-level interface has the following general syntax:
In the interface header, the name of the interface is preceded by the keyword
interface. In addition, the interface header can specify the following
information:
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 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.
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
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,
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:
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;
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.
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:
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.
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()
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:
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:
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()
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()
For example, if z refers to a string buffer object whose current contents are
"start", then the method call z.append("le") would cause the string buffer to
contain "startle", whereas z.insert(4, "le") would alter the string buffer to
contain "starlet".
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( )
The second form creates a vector whose initial capacity is specified by size:
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:
Vector(Collection c)
Inserts the specified element at the specified position in this Vector. If Index
value is not in the range of already added objects then it throws
IndexOutOfBoundException.
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.
Removes the first (lowest-indexed) occurrence of the argument from this vector.
void removeElementAt(int index)
removeElementAt(int index)
protected void removeRange(int fromIndex, int toIndex)
Removes from this List all of the elements whose index is between fromIndex,
inclusive and toIndex, exclusive.
boolean remove(Object o)
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.
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
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)
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 :
1. A class extending the Thread class overrides the run() method from
the Thread class to define the code executed by the thread.
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.
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 :