JAVA-ALL
JAVA-ALL
Unit-1
Fundamentals of object oriented programming: -
Object oriented paradigm: -
OOP supports to inheritance, overloading of operator.
Emphasis on data rather than procedure.
Programs are divided into objects.
Functions that operate on the data of an object.
Data is hidden and can not be accessed by external functions.
Objects may pass the data to each other by using functions. It
is easy to add new data and function in the class.
It is use the bottom-top approach in the program.
7. Multithreading: JAVA can handle multiple tasks simultaneously. This future is known as
multithreading.
8. High performance: Java performance is impressive for an interpreted language, mainly due to
the use of intermediate byte-code.
9. Dynamic & Extensible: Java is capable of dynamic linking in new class libraries, method and
objects.
Application of JAVA: -
The programming areas of application of JAVA include:
1. Real time systems.
2. Simulation and modelling.
3. Object oriented database.
4. Hypertext and hypermedia.
5. AI and expert system.
6. Neural network and parallel programming.
7. Decision support and office automation system.
Tools Description
appletviewer (for Enables us to run Java applet (without actually using a java-
viewing java applet) compatible browser)
Java (java interpreter ) Java interpreter, which runs applet and application by reading
and interpreting byte code file.
Javac (java compiler ) The Java compiler, which translate Java source code to byte
code files that the interpreter understand.
Javadoc (for creating Create HTML – format documentation from java source code
HTML document) files.
Javah (for C header Produce header files for use with native methods.
files )
Jdb(java debugger) Java debugger, which helps us to fine errors in our program.
Documentation Section: -
1. The documentation section comprises a set of Comment lines giving the name of the program,
the author and other details, which the programmer would like to refer to at later stage.
2. Comments must explain why and what of classes & how of algorithms. This would greatly help
maintaining the program.
Package statement: -
1. The first statement allowed in java file is Package statement.
2. This statement declares a Package name and informs the compiler that the classes defined here
belong to this package.
package student;
3. The package statement optional means our classes do not have to be a part of package.
Import Statements: -
1. This is similar to the #include statement in C.
import student.test;
2. This statement instructs the interpreter to load the test classes contained on the package
student.
Interface statements: -
1. An interface is like a class but includes a group of method declarations.
2. This is also an optional section and is used only when we wish to implement the multiple
inheritance features in the program.
Class Definition: -
1. A java program may contain multiple class definition.
2. Classes are the primary and essential elements of a Java Program.
3. The number of classes used depends on the complexity of the program.
Main Method Class: -
1. Since every java Stand-alone program required a Main method as its starting point, this class is
the essential part of a Java program.
2. A simple java program may contain only this part.
3. The Main method creates objects of various & establishes communication between them.
4. Public: - Public is an access specifier that declares the main method as unprotected &
therefore making it accessible to all other classes.
5. Static: - Static is a keyword which can be called & executed without creating the object, so
when we want to call main() method without using an object, we should declare main() method
as Static.
6. Void: - A method can return some result. If we want the method to return the result in form of
an integer then we should write int before the method name.
o If a method is not meant to return any value, then we should write void before the
method’s name. Void means no value.
7. Main: - This is the starting point for interpreter to begin the execution of the program.
8. String args[]: - An args[] is the array name & it is of String type. This means that it can be
store a group of strings. This array can also store a group of number but in the form string only.
System.out.println (“Hello”)
System is the class name & out is a static variable in system class.
Out is called a field in system class. (Out is an object of system class).
When we call this field, a Printstream class object will be created internally, so we can call the
print() method.
Sample program: -
Following JAVA program find the area of circle.
class area
{
public static void main(String args[])
{
double pi, r, a;
pi = 3.1416;
r = 5;
a = pi * r * r;
System.out.println (“This is the area of Circle” +a);
}
}
JAVA tokens: -
Java program is basically a collection of class.
A class define by set of declaration statements and methods containing executable
statements. Most statements contain expression, which describe the action carried out on
data.
Smallest individual unit in a program are known as tokens.
The compiler recognizes them for building up expression and statement.
Java program has collection of Tokens.
o Reserved Keywords
o Identifiers
o Literals
o Operators
o Separation
Keywords: -
Keywords are an essential part of a language definition.
Java language has reserved 50 words as keywords.
These keywords combine with operators & separators according to syntax, form definition of the
java language.
Every JAVA word is classified as a keyword.
All keyword have fixed meanings.
These meaning cannot be changed.
All keywords are to be written in lower-case letters.
Identifiers: -
Identifier refers to the mane of variables, functions and array name, structure name.
These names are defined by user, so they are known as user-define names.
Identifier consists of letters and digits.
Both uppercase and lowercase are permitted.
Rules of Identifiers: -
1. First character must be an alphabet or underscore.
2. Must consist of only letters, digits and underscore.
3. The JAVA variable of any size.
4. We can not use keyword as identifiers.
5. White spaces are not allowed in identifiers.
Literals: -
Literals in java a sequence of character (digits, letters and other characters) that represent
constant values to be stored in variable.
Constants refer as fixed value in JAVA that does not change during the execution of a program.
Five major types of literals
1. Integer literals
2. Floating point Literals
3. Character literals
4. String literals
5. Boolean literals
Integer Constants refer to a sequence of digit like 1056.
Real (Float) constants refer a fractional (point) part like 17.76. Such numbers are called real or
floating point constants.
A single character constant contains only a single character. They are enclosed within single quote
mark. Ex. – ‘g’, K’, ‘l’ etc…
A string constant is sequence of character enclosed within double quote mark. Ex. – “Well Done”,
“Hello Word”, etc…
Separator: -
Separators are symbols used to indicate where groups of code are divided and arranged.
() Parentheses: - Used to enclose parameter in method definition and invocation also used for
defining precedence in expression.
{} Braces: - Used to contain the values of automatically initialize array and to define a block of
code classes, methods & local scopes.
[] Brackets: - Used to declare an array types.
; Semicolon: - Used to separate the statements.
, Comma: - Used to separate variables, in for loop etc…
. Period: - Used to separate package names, also used to separate variable or method from a
reference variable.
Variables: -
A variable is a data name that may be used to store a data value.
Variables may take different values at different time during execution.
A variable name can be chosen by the programmer.
Ex.- Average, height, Total, Counter_1, class_strenght etc….
Rules For Variable: -
1. They must begin with letter.
2. The JAVA variable of any size.
3. Uppercase and lowercase are significant.
4. It should not be a keyword.
5. White space is not allowed.
Some valid example of variable.
John, Value, T_raise, Delhi, x1, ph_value, mark, sum2, sum_5 etc….
Constants: -
Constants refer as fixed value in JAVA that does not change during the execution of a program.
JAVA supports several types of constants.
Constants
Character Type: - In order to store character constant in memory, JAVA provides a character data
type called char. The character type assumes a size of 2 bytes but, it can hold only a single
character.
Boolean type: - Boolean type is used when we want to test particular condition during the
execution of the program. There are only two values that a Boolean type can take: true or false.
Scope of variable: -
An area of the program where the variable is accessible is called Scope.
JAVA supports three types of variables.
1. Instance variables.
2. Class variables.
3. Local variable.
Instance variable: -
1. Instance variable declare in class.
2. Instance variable are created when the object are instantiated and therefore they are
associated with objects.
3. They take different value for each object.
Class variable: -
1. Class variable are global to a class and belong to entire set of objects that class created.
2. Only one memory location is created for each class variable.
Local variable: -
1. Local variable is declare and used in methods.
2. They are called so because they are not available for use outside the method definition.
3. Local variable is also declared in program blocks defined between an {open & close braces}.
4. This variable is visible only from the beginning of its program block to end of the program block.
Type casting: -
There is a need to store a value of one type in to variable of another type.
Syntax:
type variable1= (type) variable2;
int m = 50;
byte n = (byte) m;
long count= (long) m;
Casting is often necessary when a method returns a type different than the one we require.
Casting in to smaller type may result in a loss of data.
Like, he float & double can be cast to any other type expect Boolean.
Casts that Results in NO LOSS OF Information
From To
byte short, char, int, long, float, double
short int, long, float, double
char int, long, float, double
int Long, float, double
long Float, double
float Double
Automatic Conversion: -
1. It is possible to assign a value of one type to a variable of different type without a cast.
2. Java does the conversion of the assigned value automatically.
3. This is known as automatic type conversion.
byte b = 75;
int a = b;
5. The process of assigning a smaller type to large one is known as winding or Promotion.
6. Larger to smaller one is known as Narrowing.
Operators: -
JAVA supports several kinds of operators.
An operator is a symbol that tell to computer that to perform mathematical or logical operation.
An operator is used in program to perform the operation on variable or data values.
JAVA operator can be classified as under.
1. Arithmetic operator
2. Relational operator
3. Logical operator
4. Assignment operator
5. Increment and Decrement operator
6. Conditional operator
7. Special operator
8. Bitwise operator
Arithmetic operator: -
JAVA provides all the basic arithmetic operators.
The operators +, -, *, /, % all work the same way as they do in other language.
These can operate on any basic data type.
Operator Meaning
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulo Division
For example, here a and b are variable and known as a operand.
a + b : variable a is added to b
a - b : variable a is subtract from b
a * b : variable a is multiply by b
a / b : variable a is divided by b and integer division truncate the fractional part.
a % b : variable a is divided by b and produce the reminder of an integer division.
Note: - Modulo division (%) operator can not be used with floating point data.
Relational operator: -
JAVA provides all the basic relational operators.
These operators are used to compare two more values with each other to get relation.
These kinds of comparisons can be done with the help of relational operators.
The value of expression is either one or zero.
The value is one if the relational expression is true.
The value is zero if the relational expression is false.
JAVA supports six relational operators.
These operators and meaning are shown as under.
Logical operator: -
JAVA has following logical operators.
Assignment operator: -
Assignment operators are used to assign the result of an expression.
Also JAVA has short hand assignment operators.
Syntax is:
variable op = expression , where op is a operators.
The assignment statement
V op = exp;
Is equal to
V = v op (exp);
Ex:-
X + = y+1;
Is equal to
X = x+(y+1);
Some of common shorthand assignment operators are shown as under.
We use the increment and decrement operator in for loop, while loop and do while loop.
There are two types of increment and decrement operators. Prefix and postfix operators.
A prefix operator first adds 1 to the operand and then result is assign to the variable.
A postfix operator first assigns the value to the variable and then increments the operand.
X = a-b/3+c*2-1
When a = 9, b = 12, and c = 3 then the statement become
X=9-12/3+3*2-1
First pass:
Step-1: x=9-4+3*2-1
Step-2: x=9-4+6-1
Second Pass:
Step-3: x=5+6-1
Step-4: x=11-1
Step-5: x=10
Simple IF statement: -
The if statement is powerful decision making statement.
The if statement is used to control the flow of execution of statement.
It is two-way decision statements and is used to conjunction with expression.
General form of if statement is:
if(test condition)
{
block-statement;
}
statement-x;
if(category == sports)
if (test condition)
{
true block statement;
}
else
{
false block statement;
}
statement-x;
If the test condition is true, then the true block statement is executed. If
the test condition is false, then the false block statement is executed. In
either case, either true block or false block will be executed, not both. In
the both cases, the control is transferred subsequently to statement-x.
Let us consider an example of counting the number of boys and girls in class.
We use the code 1 for boys and code 2 for girls.
……..
if(code == 1)
{
boy = boy + 1;
}
else
{
girl = girl + 1;
}
……..
………
if(test condition-1)
{
if(test condition-2)
{
statement-1;
}
else
{
statement-2;
}
}
else
{
statement-3;
}
statement-x;
But if the condition-1 is false then control is transfer to the statement-3. In this case statement-1
and statement-2 is not executed.
if (condition-1)
statement-1;
else if (condition-2)
statement-2;
else if (condition-3)
statement-3;
else if (condition-n)
statement-n
else
default-statement;
statement-x;
switch (expression)
{
case value-1:
statement-1;
break;
case value-2:
statement-2;
break;
case value-3:
statement-3;
break;
………
……..
default :
default statement;
break;
}
statement-x;
The ? : operator: -
Conditional operator is also known as a ternary operator.
A conditional operator pair “ ? : “ is available in C.
A conditional operator is used to create conditional expression.
Syntax is :
exp1 ? exp2 : exp3;
In this syntax exp1 is evaluated first. If it is nonzero (true), then the expression exp2 is evaluated
and become the value of expression.
If exp1 is false, exp3 is evaluated and its value becomes the value of the expression.
Note that only one of the expressions either exp2 or exp3 is evaluated.
For example:
int a=10;
int b=15;
int x;
x = (a<b) ? a : b ;
In this example, x will be assigning the value of b.
Initialization;
while (test condition)
{
body of the loop;
}
sum =0;
n=1;
while(n<=10)
{
sum = sum + n * n ;
n = n + 1;
}
System.out.println(“Sum= “ + sum);
……………….
Initialization;
do
{
body of the loop;
}
while (test condition);
statement-x;
On reaching the do statement, the program proceeds to evaluate the body of the loop first.
At the end of loop, the test condition in the while statement is executed.
If the condition is true then control is further transfer to body of the loop.
But if the condition is false control is transfer to statement-x.
The do while loop create an exit control loop and therefore body of the loop is always executed at
least once.
A simple example of do while loop is :
number = 0;
do
{system.out.println (“input a number”);
number = number + 1 ;
} while (number>0 && number < 100);
…………
for (x=0; x<=10 ; x++)
{
System.out.println (“x = ” + x);
}
System.out.println (“\n”);
………….
Jumping in loops: -
Loops perform the set of operations repeatedly until the control variable fails to satisfy the test
condition.
But sometimes, when executing a loop it becomes desirable to skip a part of loop or to leave the
loop as soon as a certain condition is occurs.
At that time we have to use a break statement. When the break statement is encountered inside
the loop, the loop is immediately exited and the program continues with the statement immediately
following the loop.
while(test condition)
{………..
if( condition)
continue;
………….
}
Rough work
Unit-2
Class: -
Class is a collection of data and method to manipulate that data are combines together and
become user defined data type is known as class.
Class is a user-defined data type.
Class create an object and object use methods to communicate between them.
Classes provide a convenient method for packing together a group of logically related data items
and functions that work on them.
In JAVA the data items are called fields and functions are called methods.
Defining a class: -
Class that contain data, and code to manipulate that data. The entire set of data and code of an
object can be made a user-defined data type with the help of class.
A class specification has two parts. (1) Class declaration (2) Class method definition.
The general form of a class declaration is:
class class_name
{
[BY. VIPUL PRAJAPATI] Page 17
[CCMS VADU] BCA-501-JAVA PROGRAMMING
field declarations;
method declarations;
}
Once class has been defined, we can create an object of class type using declaration that is similar
to the basic type declaration.
In JAVA this objects are known as instance of a class.
Every thing in side braces is optional.
The field variables and methods are collectively called class members.
Field declaration: -
We can create a data field (variable) inside class body.
These variables are called instance variables because they are created whenever an object of the
class is created.
Example: -
class prog1
{
int length;
float width;
}
Remember that here both variables are only declared and therefore no storage space has been
created in the memory.
Instance variable is also known as member variable.
Method declaration: -
Without method, field variable has no life.
We must add methods that are necessary for manipulating the data.
Methods are declared inside the body of class after the declaration of field variables.
The general form of method declaration is: -
………………….
return_type method_name (argument list)
{
method body;
}
…………………
class access
{
int x;
void method1 ()
{
int y;
x = 10; // legal
y = 20; // legal
}
void method2 ()
{
int z;
x = 5; // legal
z = 20; // legal
Creating an object: -
An object in JAVA is essentially a block of memory that contains space to store all the instance
variables.
We can create an object in JAVA by using new operator.
The new operator creates an object for the particular class and returns a reference to that object.
We can create an object by using following statement.
For example: -
rectangular rect1 = new rectangular();
Whenever objects are created every time memory space is allocated to the field variables for
particular object.
rect1.length = 15;
rect1.width = 10;
rect2.length = 20;
Note that the two objects rect1 and rect2 store different values.
To access methods consider the following example.
Constructors: -
We know that all objects that are created must be given initial values.
We have earlier using two approaches.
1. Uses the dot operator (.) to access the instance variable & then assign values to them individually.
2. Use of the method to initialize each object.
Java allows objects to initialize themselves when they are created. This automatic initialization is
performed through the use of a constructor.
A constructor is a special method that initializes a newly instantiated object.
A constructor initializes an object immediately upon creation. It has the same name as the class in
which it resides and is syntactically similar to a method.
Once defined, the constructor is automatically called immediately after the object is created, before
the new operator completes.
Constructors look a little strange because they have no return type, not even void.
It is the constructor's job to initialize the internal state of an object so that the code creating an
instance will have a fully initialized, usable object immediately.
Simple Constructor: -
Parameterized Constructor: -
Method Overloading:-
Overloading a method means to use the same method name for more than one method.
In Java it is possible to define two or more methods within the same class that share the same name,
as long as their parameter declarations are different.
When this is the case, the methods are said to be overloaded, and the process is referred to as method
overloading.
Method overloading is one of the ways that Java implements polymorphism.
When an overloaded method is invoked, Java uses the type and/or number of arguments as its guide to
determine which version of the overloaded method to actually call.
Thus, overloaded methods must differ in the type and/or number of their parameters.
While overloaded methods may have different return types, the return type alone is insufficient to
distinguish two versions of a method.
When Java encounters a call to an overloaded method, it simply executes the version of the method
whose parameters match the arguments used in the call.
Example
/ Demonstrate method overloading.
class OverloadDemo {
void test() {
System.out.println("No parameters");
}
/ Overload test for one integer parameter.
void test(int a) {
System.out.println("a: " + a);
}
/ Overload test for two integer parameters.
void test(int a, int b) {
System.out.println("a and b: " + a + " " + b);
}
No parameters
a: 10
a and b: 10 20
double a: 123.2
Result of ob.test(123.2): 15178.2
System.out.println("No parameters");
}
// Overload test for two integer parameters.
void test(int a, int b) {
System.out.println("a and b: " + a + " " + b);
}
// overload test for a double parameter
void test(double a) {
System.out.println("Inside test(double) a: " + a);
}
}
class Overload {
public static void main(String args[]) {
OverloadDemo ob = new OverloadDemo();
int i = 88;
ob.test();
ob.test(10, 20);
ob.test(i); // this will invoke test(double)
ob.test(123.2); // this will invoke test(double)
}
}
Static Members:-
Normally a class member must be accessed only with an object of its class.
It is possible to create a class member that can be used by itself, without reference to a specific
instance or object.
To create such a member, precede its declaration with the keyword static.
When a member is declared static, it can be accessed before any objects of its class are created, and
without reference to any object.
You can declare both methods and variables to be static.
The most common example of a static member is main( ). main( ) is declared as static because it
must be called before any objects exist.
Methods declared as static have several restrictions:
• They can only call other static methods.
• They must only access static data.
• They cannot refer to this or super in any way.
Example
/ Demonstrate static variables, methods, and blocks.
class UseStatic {
static int a = 3;
static int b;
static void meth(int x)
{ System.out.println("x = " +
x); System.out.println("a = " +
a); System.out.println("b = " +
b);
}
static {
System.out.println("Static block initialized.");
b = a * 4;
}
public static void main(String args[])
{ meth(42);
}
}
Output:-
Static block initialized.
x = 42
a=3
b = 12
As soon as the UseStatic class is loaded, all of the static statements are run. First, a is set to 3, then
the static block executes (printing a message), and finally, b is initialized to a * 4 or 12. Then main( )
is called, which calls meth( ), passing 42 to x. The three println( ) statements refer to the two static
variables a and b, as well as to the local variable x.
Nesting of Methods:-
A method can be called by using only its name by another method of the same class. This is known as
Nesting of Methods
Inheritance:-
It is always nice if we could reuse something that already exists rather than creating the same all over
again.
This is basically done by creating new class, reusing the properties of existing one, the deriving a new
class from an old is called inheritance.
The old class is known as base class or super class or Parent class and the new one is called the
subclass or derived class or child class.
The inheritance allows subclasses to inherit all the variable and methods of their parent class.
Inheritance may take different form.
Single inheritance (only one super class)
Multiple inheritance (several super class)
Hierarchical inheritance (one super class, many subclasses)
Multilevel inheritance (derived from a derived classes)
Rules of inheritance: -
There are certain rules for inheritance which are define as under:
1. Private members of base class can not be inherited.
2. When a base class is privately inherited by derived class, “public members of base class
become private members of derived class.” And therefore they are only accessed by
members of derived class. They are not accessible to the object of derived class.
3. When a base class is publicly inherited by derived class, “public members of base class
become public members of derived class.” And therefore they are accessible to the object of
derived class.
Java dose not directly implement multiple inheritance. However, this concept is implemented using a
secondary inheritance path in the form of interface.
The keywords extends signifies that the properties of the superclassname are extended to the
subclassname.
The subclass will now contain its own variable and methods as well those of the superclass.
This kind of situation occurs when we want to add some more properties to an extending class without
actually modifying it.
Inheritance is one of the cornerstones of object-oriented programming because it allows the creation of
hierarchical classifications.
Single Inheritance: -
The derived class is derived from single base class that is known as single inheritance.
Multiple Inheritance: -
The derived class is derived from multiple base class is known as multiple inheritance.
Multiple inheritance allows us to combine a feature of several existing classes in single class.
subOb.showk();
System.out.println();
System.out.println("Sum of i, j and k in subOb:");
subOb.sum();
}
}
Super Keywords:-
A subclass constructor is used to construct the instance variables of both the subclass and the super
class.
The subclass constructor uses the keyword super to invoke the constructor method of the super class.
The super keyword is used subject to the following condition.
1. Super may only be used with in a sub class constructor method.
2. The call to super class constructor must appear as the first statement with in the subclass
constructor.
3. The parameters in the super call must match the order and type of the instance variable declared
in the superclass.
Method Overriding:-
When a method in a subclass has the same name and type signature as a method in its superclass,
then the method in the subclass is said to override the method in the superclass.
When an overridden method is called from within a subclass, it will always refer to the version of that
method defined by the subclass.
The version of the method defined by the superclass will be hidden.
Example
Garbage Collection:-
Since objects are dynamically allocated by using new operator, you might be wondering how such
objects are destroyed and their Memory released for later reallocation.
Java handles de-allocation for you automatically. The technique that accomplishes this is called
Garbage collection.
Finalize Method:-
We have seen that a Constructor method is used to initialize an object when it is declare. This process
is known as Initialization.
Similarly, Java support a concept called Finalization, which is just opposite to Initialization.
Java provides automatically free memory allocation used by object, but objects may hold other non-
object resources such as file handle or window character font.
The garbage collector can not free these resources. To free this kind of resource we can use finalize()
method.
The finalize() method has this general form:
Final keyword:-
All method & variable can be overridden by default in subclass.
If we wish to prevent the subclasses from overriding the members of the superclass, we can declare
them as final using the keyword final.
Sometimes we may like to prevent a class being further subclasses for security reason; a class that
cannot be subclassed is called a final class.
Abstract keywords:-
class dynamic_dispatch
{
public static void main(String args[])
Arrays: -
Definition: - “Array is sequence collection of related data item that share same name and same
data type, but store a different value.”
C supports a derived data type known as array that can be used for many applications.
Three type of array is available in C :
1. One dimensional array.
2. Two dimensional arrays.
3. Multidimensional arrays.
For example, if we want to represent a set of five number, say (35,40,20,57,19), by an array
variable number, then we may declare the variable number as follows:
number[0]
number[1]
number[2]
number[3]
number[4]
The values to the array elements can be assigned as follows:
number[0] = 35;
number[1] = 40;
number[2] = 20;
number[3] = 57;
number[4] = 19;
This would cause the array number to store the values as shown below:
35 number[0]
40 number[1]
20 number[2]
57 number[3]
19 number[4]
These elements may be used in programs just like any other C variable.
For example, the following are valid statements:
a = number[0] + 10;
number[4] = number[0] + number [2];
number[2] = x[8] + y [10];
Initialisation of array: -
Initialisation means to store the values to an array element.
An array can be initialized at two ways.
1. At compile time.
2. At run time.
2 num[0]
4 num[1]
5 num[2]
0 num[3]
0 num[4]
STRINGS: -
String manipulation is the most common part of many JAVA programs.
String represents a sequence of characters.
The easiest way to represent a sequence of characters in JAVA is by using a character array.
For example:
char chararray [ ] = new char [4];
chararray[0] = ‘ j ’ ;
chararray[1] = ‘ a ’ ;
chararray[2] = ‘ v ’ ;
chararray[3] = ‘ a ’ ;
In JAVA, strings are class objects and implements using String and StringBuffer class.
A JAVA string is an instantiated object of string class.
A JAVA string is not a character array and is not NULL terminated.
The string may be declared and created as follows.
String String_name;
String_name = new String (“string”);
[BY. VIPUL PRAJAPATI] Page 32
[CCMS VADU] BCA-501-JAVA PROGRAMMING
For example:
String first_name;
first_name = new String (“Anil”);
Like arrays, it is possible to get the length of string using length method of the string class.
int m = first_name.length( );
Note the use of parentheses here. JAVA string can be concatenated using the + operator.
String fullName = name1 + name2;
String city1 = “New” + “Delhi”;
String Methods: -
The string class defines a number of methods that allow us to accomplish a variety of string
manipulation task.
Some most commonly used string methods.
Vector Class:-
The Vector class is one of the most important in all of the Java Class
libraries. Recall that you can not expands the size of a static array.
You may think of a vector as a dynamic array that automatically expands as more elements are
added to it.
All vectors are created with some initial capacity.
When space is needed to accommodate more elements, the capacity is automatically increased
. It is for this reason that vector are commonly used in Java Programming.
The class supports the following constructor:-
[BY. VIPUL PRAJAPATI] Page 33
[CCMS VADU] BCA-501-JAVA PROGRAMMING
Vector()
Vector(int n)
Vector(int n,int delta)
The first form creates a vector with initial capacity of ten Element.
The second forms create a vector with an initial capacity of n element.
The third forms create a vector with an initial capacity of n elements that increase by Delta elements
each time it needs to expand.
The instance methods provided by this class.
SN Method_Name Description
1 Void addElement(Object Adds Obj to the vector.
obj)
2 int capacity() Returns the capacity.
3 Object clone() Returns a duplicated of the current Object.
4 Boolean contains(Object Returns True if Obj is contained by the vector.
obj) Otherwise returns False.
5 void copyInto(Object Copies the element s of the current object to array.
array[])
6 Object elementAt(int Returns the element at index.
index)
7 Enumeration elements() Returns an enumeration of the elements.
8 Void ensureCapacity(int Set the minimum capacity to minimum.
minimum)
9 Object firstElement() Returns the first element.
10 int indexOf(Object obj) Search for the first occurrence of Obj. Returns its
index or -1 if Obj is not in the vector.
11 int indexOf(Object obj,int Searches for the first occurrence of Obj beginning at
start) index start. Returns its index or -1 if Obj is not in the
vector.
12 Void Adds Obj to the vector at index.
insertElementAt(Object
obj,int index)
boolean hasMoreElements()
Object nextElement()
The first method returns true if more elements are available, otherwise, it returns false.
The second method returns the next available element.
This interface is implemented by Vector class.
System.out.println(vector);
}
}
Wrapper classes: -
As we know that vector class does not handle primitive data types like int, float, long, char and double.
Primitive data types may be converted into object types by using the wrapper class provided by JAVA.
Wrapper classes for converting simple types.
boolean Boolean
char Character
double Double
float Float
int Integer
long Long
The wrapper class have a number of unique methods for handling primitive data types and object.
Converting primitive numbers to object number using constructor methods.
Converting string objects to numeric objects using the static method ValueOf().
The parseInt() and parseLong() methods throw a Number Format Exception if the value of the str does
not represent an integer.
Interface: -
Interface defines only abstract methods & final fields.
This means that interface do no specify any code to implement these methods and data fields contains
only constants.
An interface contains only abstract methods which are all incomplete methods, so it is not possible to
create an object to an interface.
In this case, we can create separate classes where we can implement all the methods of the interface.
These classes are known as implementation classes will have all the methods with body.
It is possible to create object of implementation class.
interface is the keyword & interfacename is valid Java variable(just like class name)
Implementing Interface:-
Interfaces are used as “Superclass” whose properties are inherited by classes.
This shows that a class can extend another class while implementing interface.
When a class implementation more than one interfaces, they are separated by comma.
Example:-
interface Area // interface define
{
final static float pi=3.14F;
float compute (float x,float y);
}
class Rectangle implements Area //interface implemented
{
public float compute(float x,float y)
{
return (x*y);
}
}
class circle implements Area // interface implemented
{
Example:-
/ One interface can extend another.
interface A {
void meth1();
void meth2();
}
/ B now includes meth1() and meth2() — it adds meth3().
interface B extends A {
void meth3();
}
/ This class must implement all of A and B
class MyClass implements B {
public void meth1() {
System.out.println("Implement meth1().");
}
public void meth2() {
System.out.println("Implement meth2().");
}
public void meth3() {
System.out.println("Implement meth3().");
}
}
class IFExtend {
public static void main(String arg[]) {
MyClass ob = new MyClass();
ob.meth1();
ob.meth2();
ob.meth3();
}
}
interface A
{
float HT=6.2F;
void height();
}
interface B
{
float HT=5.8F;
void height();
}
class C implements A,B
{
public void height()
{
float ht=(A.HT+B.HT)/2;
System.out.println("C's height--->"+ht);
}
}
class multiple
{
public static void main(String args[])
{
C c=new C();
c.height();
}
}
Class Interface
The member of a class can be constants or The member of an interfaces are always
variable declare as constants, i.e their values are
final.
The class definition can contain the code The methods in an interface are abstract in
for each of its methods. That is the nature, i.e., there is no code associated
methods can be abstract or non-abstract. with them. It is later defined by the class
that implements the interface.
It can be instantiated by declaring objects. It cannot be used to declare object. It can
only be inherited by a class.
It can be various access specifier like It can only use the public access specifier.
public, private, or protected.
Benefits of packages: -
The classes contained in the packages of other programs can be easily reused.
In packages, classes can be unique compared with classes in other packages. That is, two classes
in two different packages can have the same name. They may be referred by their fully qualified
name, comprising the packages and the class name.
Packages provide a way to ‘hide’ classes thus preventing other programs or packages from
accessing classes that are meant for internal use only.
Packages Contents
Name
java.lang Language support classes. These are classes that JAVA compiler itself used and
therefore they are automatically imported. They include classes for primitive types,
string, math functions, thread and exceptions.
java.util Language utility classes such as vector, hash table, random number, date, etc…
java.io Input/output support classes. They provide facilities for the input and output of
data.
java.awt Set of classes for implementing graphical user interface. They include classes for
windows, buttons, list, menus, and so on.
java.net Classes for networking. They include classes for communicating with local
computers as well as with internet servers.
java.applet Classes for creating and implementing applets.
Naming conventions: -
Packages can be named using the standard JAVA naming rules.
By convention, however, packages begin with lowercase letters. This may make it easy for user to
distinguish packages name from class name.
Look at the following example.
This statement uses a fully qualified class name Math to invoke the method sqrt(). Note that
methods begin with lowercase letters.
Consider the following example.
java.awt.Point pts[]
This statement declares an array of Point type object using the fully qualified class name.
Every package name must be unique to make the best use of package. Duplicate name will create
run time errors.
Since multiple user work on internet, duplicate package names are unavoidable. JAVA designers
have recognised this problem and therefore suggested a package naming convention that ensures
uniqueness.
Creating package: -
We first declare the name of the package using the package keyword followed by the package
name.
This must be the first statement in the JAVA source file while creating a
package. Then we define the class.
Consider the following example.
package first_package ;
Here the package name is first_class. The first_class is now considered as a part of this
package.
This listing would be saved as a file called first_class.java, and located in a directory named
first_package.
When the source file is compiled, JAVA will create a .class file and store it in the same directory.
While creating our own package it involves the following steps.
1. Declare the package at the beginning of the file using the form package packagename:
2. Define the class that is to be put in the package and declare in public.
3. Create subdirectory under the directory where the main source files are stored.
4. Store the listing as the classname.java file in the subdirectory created.
5. Compile the file. This create .class file in the directory.
Accessing a package: -
The JAVA system packages can be accessed either using a fully qualified class name or using a
shortcut approach through the import statement.
We use the import statement when there many references to particular package or the package
name.
The same approaches can be used to access the further-defined packages as well.
The import statement can be used to search a list of packages for particular class.
Consider the following example.
Here package1 is the name of the top level package; package2 is the name of package that is
inside the package1 and so on.
Note that the statement must end with a semicolon (;). Multiple import statements are allowed.
We can also use another approach as follows;
import packagename.* ;
Using a package: -
Let us now consider the some simple programs that will use the classes from other package.
The listing below shows a package named package1 containing a single class Class1.
package package1 ;
public class ClassA
{
public void displayA()
{
System.out.printline(“Class A”);
}
}
This source file should be named ClassA.java and stored in the subdirectory package1.
Now compile this JAVA file. The resultant ClassA.class will be stored in the same subdirectory.
Now consider the following listing shown below.
inport package1.ClassA ;
class packagetest1
{
public static void main (String args[ ])
{
ClassA objA = new ClassA( );
objA.display( );
}
}
Above example shows a simple program that imports the class ClassA from the package
package1.
-------
JAVA util package classes: -
The Random Class:-
The Random Class allows you to generate random double, float, int or long numbers.
You may also generate numbers that have a Gaussian distribution.
This can be valuable if you are building a simulation of real-world system.
Input data frequently followed such a distribution.
This class provides the following Constructor
Random()
Random(long seed)
Here, seed is a value to initialize the random number generator. The first form uses the current time as
the seed.
Some instance Methods define by this class.
for(int i=0;i<10;i++)
{
System.out.println(generator.nextInt());
}
}
}
SN Method_Name Description
1 Boolean after(Date d) Returns true if d is after the current date.
Otherwise returns false.
2 Boolean before(Date d) Returns true if d is before the current date.
Otherwise return false.
3 Boolean equals(Date d) Returns true if d has the same value as the
current date. Otherwise return false.
4 long getTime() Return the number of milliseconds since the
epoch.
5 Void setTime(long msec) Set the date and time of the current object
to represent msec milliseconds since the
epoch.
6 String toString() Returns the string equivalent of the date.
------
Example:- Display current date with Date object with default constructor.
import java.util.*;
class dateDemo
{
public static void main(String args[])
System.out.println(epoch);
Method_Name Description
abstract boolean after(Object Returns true if the invoking Calendar object contains a date
calendarObj) later than the one specified by calendarObj, it returns false.
abstract boolean before(Object Returns true if the invoking Calendar object contains a date
calendarObj) earlier than the one specified by calendarObj, it returns false.
abstract boolean equals(Object Returns true if the invoking Calender object contains a date
calendarObj) equals to the one specified by calendarObj, it returns false.
final int get(int calendarField) Returns the value of one component of the invoking object.
The component is indicated by Calendar Field. Some Example
of the component that can be requested are
Calendar.YEAR,Calendar.MONTH,Calnender.MINUTE and
so forth
static Calender getInstance() Returns a Calender object for the default locale and time
zone.
final Date getTime() Returns a Date object equivalent to the time of the invoking
object.
final void set(int year,int month Set various date and time component of the invoking object.
Initialized to the current date and time. One of its forms is shown here:-
Calendar getInstance()
Some Instance methods provided by this class.
1. GregorianCalendar()
2. GregorianCalender(int year,int month,int date)
3. GregorianCalender(int year,int month,int date,int hour,int minute,int sec)
4. GregorianCalender(int year,int month,int date,int hour,int minute,int minute)
The first form creates an object initialize with the current date and time.
The other forms allow you to specify how various date and time component s are initialized.
The class provides all of the methods defined by Calendar and also adds the isLeapYear() method
shown here:
boolean isLeapYear()
This method returns true, if the current year is a leap year. Otherwise, it returns false.
Example: - This program illustrate how to use some methods provide by Calendar class.
import java.util.*;
class CalendarDemo
{
public static void main(String args[])
{
Calendar calendar=Calendar.getInstance();
System.out.println(calendar.get(Calendar.YEAR));
System.out.println(calendar.get(Calendar.HOUR));
System.out.println(calendar.get(Calendar.DATE));
System.out.println(calendar.get(Calendar.HOUR_OF_DAY));
System.out.println(calendar.get(Calendar.MINUTE));
}
}
Stack Class:-
The Stack Class extends Vector and provides a LIFO (last-in, First-out) stack.
Here is an excellent example of the power of object-oriented programming.
The Vector class provides the functionality of a dynamic array.
This capacity is also needed to implement the Stack class.
The stack class reuses this implementation and also provides methods to push, pop, and otherwise
manipulate the stack.
You will see that class inheritance is commonly used throughout the Java Class libraries to achieve
maximum code reuse.
SN Method_Name Description
1 Boolean empty() Returns True if the stack is empty. otherwise , returns
False.
2 Object peek() Returns the object at the top of the stack but dose not
throws remove it from the stack.
EmptyStackException
3 Object pop() throws Returns the object at the top of the stack and remove
EmptyStackException it from the stack.
4 Object push(Object Pushes Obj onto the stack and also return obj.
obj)
Hashtable()
Hashtable(int n)
Hashtable(int n,float lf)
Here, n is the initial capacity of hash table and if is its load factor.
The latter is a number between 0 & 1.
The size of Hash table is automatically increased when the number of entries in the hash table exceeds
the product of the capacity and load factor.
Instance method of this class
SN Method_Name Description
1 boolean contains(Object Returns TRUE if the hash table contains v as one of its
v)throws NullPointerException values. Otherwise, return FALSE. The method throws a
NullPointerException if v is null.
2 boolean containsKey(Object k) Returns true if the hash table contains k as one of its keys.
Otherwise, returns false.
3 boolean containsValue(Object Returns true if the hash table contains v as one of its
v) values. Otherwise returns false.
4 Enumeration elements() Returns an enumeration of the value.
5 Object get(Object k) Returns the value associated with the key k.
6 boolean isEmpty() Returns true if the hash table is empty. Otherwise, returns
false.
7 Enumeration keys() Returns an enumeration of the key.
8 Object put(Object k, Object v) Puts a key/value pair into the hash table. The key is k and
throws NullPointerException the value is v. The method throws a
[BY. VIPUL PRAJAPATI] Page 46
[CCMS VADU] BCA-501-JAVA PROGRAMMING
NullPointerException if k or v is null.
9 Object remove(Object k) Remove the key/value pair whose key is k.
10 Int size() Returns the number of key.
11 String toString() Returns the string equivalent of this hash table.
import java.util.*;
class HashTableDemo
{
public static void main(String args[])
{
//create hash table and populate it
Hashtable hash=new Hashtable();
hash.put("pen","red");
hash.put("pencil","blue");
hash.put("book","green");
hash.put("kit","yellow");
StringTokenizer(String str)
StringTokenizer(String str,String delimiter)
StringTokenizer(String str,String delimiter,Boolean delimiterAreTokens)
-------
Here, str is the String to be parsed & delimiters contains the character that separate tokens.
If delimitersAreTokens is true, the tokenizer returns the delimiters as tokens. Otherwise, the delimiters
are not returned from the tokenizer.
Instance method which are use by String Tokenizer
SN Method_Name Description
1 int countTokens() Returns the number of tokens in the string.
2 boolean hasMoreToken() Returns true if there are more tokens. Otherwise ,
returns false.
3 String nextToken() Returns the next token.
4 String nextToken(String Returns the next token and defines delimiters as
delimiters) the set of the delimiter characters.
Unit-3
Threads: -
Java provides built-in support for multithreaded programming. A multithreaded program contains
two or more parts that can run concurrently. Each part of such a program is called a thread, and
each thread defines a separate path of execution.
A multithreading is a specialized form of multitasking. Multitasking threads require less overhead
than multitasking processes.
There are two types of multitasking:
o Process-based multitasking: -
Process-based multitasking is the feature that allows your computer to run two or
more programs concurrently.
o Thread-based multitasking: -
Thread-based multitasking environment, the thread is the smallest unit of
dispatchable code. This means that a single program can perform two or more tasks
simultaneously.
Multithreading has several advantages over Multiprocessing such as:-
1. Threads are lightweight compared to processes.
2. Threads share the same address space and therefore can share both data and code.
3. Context switching between threads is usually less expensive than between processes.
4. Cost of thread intercommunication is relatively low that that of process intercommunication.
5. Threads allow different tasks to be performed concurrently.
New born state:- When we create a thread object, the thread is born and is said to be in newborn
state.
o The thread is not yet scheduled for running; at this state we can do only one of the Following
things.
Schedule it for running using start() method.
Kill it using stop() method.
o If we attempt to use any another method at this stage, an exception will be thrown.
Runnable state:- The runnable state means that the thread is ready for execution and is waiting
for the availability of the processor.
o The thread had joined the queue of threads that are waiting for execution.
o If all thread has equal priority, then they are given time slots for execution in First-come
First-serve manner.
o If we want a thread to give up control to another thread to equal priority before its turns
comes , we can do so by using the yield() method.
Running state:- Running means that the processor has given its time to the thread for its
execution.
o The thread runs until it give up control on its own or it is prevent by a higher priority thread.
o A running thread gives up its control in one of the following situation.
It has been suspended using suspend () method.
A suspended thread can be revived by using the resume () method.
This approach is useful when we want to suspend a thread for some times due to
creation reason, but do not want to kill it.
It has been made to sleep, we can put a thread to sleep for a specified time period
using the method sleep(time) where time is in milliseconds.
This means that the thread is out of the queue during this time period.
The thread re-enter the runnable state as soon as this time period is elapsed.
-------
Blocked state:- A thread is said be blocked when it is prevented from entering into the runnable
state and subsequently the running state.
o This happens when the thread is suspended, sleeping or waiting in order to satisfy certain
requirements.
o A blocked thread is considered “not runnable” but not dead and therefore fully qualified to
run again.
Dead State:- Every thread has a life cycle, A running thread ends its life when it has completed
executing its run() method.
o It is a natural dead, we can kill it by sending the stop message to it at any state thus causing
a premature death to it.
o A thread can be killed as soon it is born, or while it is running, or even when its in “not
runnable” (blocked) condition.
Creating a Thread: -
Java defines two ways in which this can be accomplished:
o You can implement the Runnable interface.
o You can extend the Thread class, itself.
You will define the code that constitutes the new thread inside run() method.
It is important to understand that run() can call other methods, use other classes, and declare
variables, just like the main thread can.
After you create a class that implements Runnable, you will instantiate an object of type Thread
from within that class. Thread defines several constructors. The one that we will use is shown here:
Thread(Runnable threadOb, String threadName);
Here threadOb is an instance of a class that implements the Runnable interface and the name of
the new thread is specified by threadName.
After the new thread is created, it will not start running until you call its start( ) method, which is
declared within Thread. The start( ) method is shown here:
void start( );
PROGRAM:-
class A extends Thread
{
public void run()
{
for(int i=1;i<=5;i++)
{
[BY. VIPUL PRAJAPATI] Page 51
[CCMS VADU] BCA-501-JAVA PROGRAMMING
-------
if(i==1) yield();
System.out.println("\tFrom Thread A :-i= "+i);
}
System.out.println("Exit from A");
}
}
catch(Exception e)
{
}
}
System.out.println("Exit from c");
}
}
class ThreadMethods
{
public static void main(String args[])
{
A threadA=new A();
B threadB=new B();
C threadC=new C();
OUTPUT:-
start Thread A
class ThreadDemo {
public static void main(String args[]) {
new NewThread(); // create a new thread
try {
for(int i = 5; i > 0; i--) {
System.out.println("Main Thread: " + i);
Thread.sleep(1000);
}
} catch (InterruptedException e)
{ System.out.println("Main thread
interrupted.");
}
System.out.println("Main thread exiting.");
}
}
Thread Methods: -
Following is the list of important methods available in the Thread class.
These methods are invoked on a particular Thread object. The following methods in the Thread
class are static.
SN Methods Description
1 public void start() Starts the thread in a separate path of execution, then invokes the
run() method on this Thread object.
2 public void run() If this Thread object was instantiated using a separate Runnable
target, the run() method is invoked on that Runnable object.
3 public final void Changes the name of the Thread object. There is also a getName()
setName(String name) method for retrieving the name.
4 public final void Sets the priority of this Thread object. The possible values are
setPriority(int priority) between 1 and 10.
5 public final void The current thread invokes this method on a second thread,
join(long millisec) causing the current thread to block until the second thread
terminates or the specified number of milliseconds passes.
6 public final boolean Returns true if the thread is alive, which is any time after the
isAlive() thread has been started but before it runs to completion.
Invoking one of the static methods performs the operation on the currently running thread
SN Methods Description
1 public static void yield() Causes the currently running thread to
yield to any other threads of the same
priority that are waiting to be scheduled
2 public static void sleep(long Causes the currently running thread to
millisec) block for at least the specified number of
milliseconds
3 public static Thread Returns a reference to the currently
currentThread() running thread, which is the thread that
invokes this method.
Thread priorities: -
Thread priorities are used by the thread scheduler to decide when each thread should be allowed
to run.
In theory, higher-priority threads get more CPU time than lower-priority threads.
When the thread are created and started, a ‘Thread scheduler’ program in JVM will load them into
memory and execute them.
This scheduler will allot more JVM time to those threads which are having higher priorities.
Java priorities are in the range between MIN_PRIORITY (a constant of 1) and MAX_PRIORITY (a
constant of 10). By default, every thread is given priority NORM_PRIORITY (a constant of 5).
The minimum priority (shows by Thread.MIN_PRIORITY) of a thread is 1,and the maximum priority
(Thread.MAX_PRIORITY) is 10,and normal priority of a thread (Thread.NORM_PRIORITY) is 5.
-------
PROGRAM:-//
Thread priorities
class myclass extends Thread
{
int count=0; //this count numbers
public void run()
{
for(int i=1;i<10;i--)
count++;//count number up to 10
/ display which thread has completed counting and its priority
System.out.println("CompleteThread:"+Thread.currentThread().getName());
System.out.println("Itspriority:"+Thread.currentThread().getPriority());
}
class prior
{
public static void main(String args[])
{
myclass obj=new myclass();
OUTPUT:-
Complete Thread: two
Its priority:5
Complete Thread: one
Its priority:2
synchronized (object)
{
// statements to be synchronized
}
Synchronized block ensures that a call to a method that is a member of object occurs only after the
current thread has successfully entered object's monitor.
-------
PROGRAM:-
//Thread Synchronization - Two Threads acting on same object
class reserve implements Runnable
{
/ available berths are 1
int available=1;
int wanted;
//accept wanted berths at run time
reserve(int i)
{
wanted=i;
}
public void run()
{
synchronized(this) // synchroniz current object
{
//display available berth
System.out.println("Available Berths="+available);
//if available berths are more than wanted berths
if(available>=wanted)
{
//get the name of passenger
String name=Thread.currentThread().getName();
//allot the berth to him
System.out.println(wanted+ "Berths reserved for" + name);
try
{
Thread. sleep (1500);//wait for printing the ticket
available=available-wanted;
//update the no. of avialable berths
} catch (InterruptedException ie){}
}
//if available berths are less,display sorry
else System.out.println("Sorry, No Berths");
}//end of synchronized block
}
}
class safe
{
public static void main(String args[])
{
//tell that 1 berth is needed
reserve obj=new reserve(1);
PROGRAM:-//
Thread DeadLock
class BookTicket extends Thread
{
//we assume train and compartment ad object
Object train,comp;
BookTicket(Object train,Object comp)
{
this.train=train;
this.comp=comp;
}
public void run()
{
//lock on train object
synchronized(train)
{
System.out.println("Book Ticket locked on train");
try
{
Thread.sleep(150);
}catch(InterruptedException e){}
System.out.println("BookTicket now waiting to lock on compartment");
synchronized(comp)
{
System.out.println("BookTicket locked on compartment");
}
}
}
}
-------
class DeadLock
{
public static void main(String args[])
{
//take train,compratment as object of object class
Object train=new Object();
Object compartment=new Object();
OUTPUT:-
Book Ticket locked on train
cancle Ticket locked on compartment
BookTicket now waiting to lock on compartment
cancleTicket now waiting to lock on train...
cancleTicket locked on train..
BookTicket locked on compartment
In this program, BookTicket thread & cancleTicket threads act in reverse direction creating a
deadlock situation.
Exception Handling:-
An exception is a condition that is caused by run-time error in the program.
An exception is an abnormal condition that arises in a code sequence at run time.
“Purpose of exception handling mechanism is to provide a means to detect and Report an
‘Exception circumstance ’so that appropriate action can be taken.”
The mechanism suggests incorporation of separate error handling code that perform the following
task:
o Find the problem(HIT the exception)
o Inform that an error has occurred (Throw the exception)
o Receive the error information(Catch the exception)
o Take corrective action(Handle the exception)
The error handling code basically consists of two segments, one to detect errors and to throw
exceptions & the other to catch exceptions & to take appropriate actions.
o Furthermore the errors can be propagated up the method call stack i.e. problems occurring
at the lower level in the chain can be handled by the methods higher up the call chain.
Try block
Statement that causes
an exception Exception object
Throws creator
exceptio
n object
Catch block
Statement that handles
the exception Exception handler
A method catches an exception using a combination of the try and catch keywords.
Java use a keyword try to preface a block of code that is likely to causes an error condition and
“throw” an exception.
A try/catch block is placed around the code that might generate an exception.
A Catch block defined by keyword catch ”catches” the exception “thrown” by the try block and
handles it appropriately.
Code within a try/catch block is referred to as protected code, and the syntax for using try/catch
looks like the following:
try
{
//Protected code
} catch (ExceptionName e1)
{
//Catch block
}
A catch statement involves declaring the type of exception you are trying to catch.
If an exception occurs in protected code, the catch block (or a block) that follows the try is checked.
If the type of exception that occurred is listed in a catch block, the exception is passed to the catch
block much as an argument is passed into a method parameter.
To illustrate how easily this can be done, the following program includes a try block and a catch
clause which processes the ArithmeticException generated by the division-by-zero error:
PROGRAM:-
class Exc2 {
public static void main(String args[])
{
int d, a;
try
{ // monitor a block of code.
d = 0;
a = 42 / d;
System.out.println("This will not be printed.");
}
catch (ArithmeticException e)
{ // catch divide-by-zero error
System.out.println("Division by zero.");
}
System.out.println("After catch statement.");
}
}
OUTPUT:-
Division by zero.
After catch statement.
{
//Catch block
}catch(ExceptionType2 e2)
{
//Catch block
}catch(ExceptionType3 e3)
{
//Catch block
}
The previous statements demonstrate three catch blocks, but you can have any number of them
after a single try
If an exception occurs in the protected code, the exception is thrown to the first catch block in the
list.
If the data type of the exception thrown matches ExceptionType1, it gets caught there.
If not, the exception passes down to the second catch statement.
This continues until the exception either is caught or falls through all catches, in which case the
current method stops execution and the exception is thrown down to the previous method on the
call stack.
PROGRAM:-
public class Multi_Catch
{
public static void main (String args[])
{
int array[]={20,10,30};
int num1=15,num2=0;
int res=0;
try
{
res = num1/num2;
System.out.println("The result is" +res);
for(int ct =2;ct >=0; ct--)
{
System.out.println("The value of array are" +array[ct]);
}
}
catch (ArrayIndexOutOfBoundsException e)
{
System.out.println("Error…. Array is out of Bounds");
}
catch (ArithmeticException e)
{
System.out.println ("Can't be divided by Zero");
}
}
}
OUTPUT:-
Can't be divided by Zero
-------
PROGRAM:-
public class ExcepTest{
public static void main(String args[]){
int a[] = new int[2];
try{
System.out.println("Access element three :" + a[3]);
}catch(ArrayIndexOutOfBoundsException e){
System.out.println("Exception thrown :" + e);
}
finally{
a[0] = 6;
System.out.println("First element value: " +a[0]);
System.out.println("The finally statement is
executed"); }
}
}
OUTPUT:-
Exception thrown :java.lang.ArrayIndexOutOfBoundsException
First element value: 6
The finally statement is executed
Example:-
PROGRAM:-
import java.lang.Exception;
class MyException extends Exception
{
MyException(String message)
{
super(message);
}
}
class TestMyException
{
public static void main(String args[])
{
int x=5,y=1000;
try
{
float z=(float)x/(float)y;
if(z<0.01)
{
throw new MyException("Number is two small");
}
}
catch(MyException e)
{
System.out.println("Caught my Exception");
System.out.println(e.getMessage());
}
finally
{
System.out.println("I m Always here");
}
}
}
OUTPUT:-
Caught my Exception
Number is two small
I m Always here
-------
Syntax
type method-name(parameter-list) throws exception-list
{
// body of method
}
PROGRAM:-
class ThrowsDemo
{
static void throwOne() throws IllegalAccessException {
System.out.println("Inside throwOne.");
throw new IllegalAccessException("demo");
}
OUTPUT:-
Inside throwOne
Caught java.lang.IllegalAccessException: demo
Event Handling:-
Event handling is at the core of successful applet programming.
Most events to which your applet will respond are generated by the user.
These events are passed to your applet in a variety of ways, with the specific method depending
upon the actual event.
The most commonly handled events are those generated by the mouse, the keyboard, and various
controls, such as a push button.
Events are supported by the java.awt.event package.
Events: -
[BY. VIPUL PRAJAPATI] Page 63
[CCMS VADU] BCA-501-JAVA PROGRAMMING
In the delegation model, an event is an object that describes a state change in a source.
It can be generated as a consequence of a person interacting with the elements in a graphical user
interface.
Some of the activities that cause events to be generated are pressing a button, entering a
character via the keyboard, selecting an item in a list, and clicking the mouse. Many other user
operations could also be cited as examples.
Events may also occur that are not directly caused by interactions with a user interface.
For example, an event may be generated when a timer expires, a counter exceeds a value, a
software or hardware failure occurs, or an operation is completed.
You are free to define events that are appropriate for your application.
Event Sources: -
A source is an object that generates an event.
This occurs when the internal state of that object changes in some way.
Sources may generate more than one type of event.
A source must register listeners in order for the listeners to receive notifications about a specific
type of event.
Each type of event has its own registration method.
Basic Syntax:-
Here, Type is the name of the event and el is a reference to the event listener.
For example, the method that registers a keyboard event listener is called addKeyListener().
The method that registers a mouse motion listener is called addMouseMotionListener( ).
This is known as multicasting the event. In all cases, notifications are sent only to listeners that
register to receive them.
Event Listeners: -
A listener is an object that is notified when an event occurs.
It has two major requirements.
First, it must have been registered with one or more sources to receive notifications about specific
types of events.
Second, it must implement methods toreceive and process these notifications.
The methods that receive and process events are defined in a set of interfaces found in
java.awt.event.
For example, the MouseMotionListener interface defines two methods to receive notifications
when the mouse is dragged or moved.
Any object may receive and process one or both of these events if it provides an implementation of
this interface.
Event Classes: -
The classes that represent events are at the core of Java's event handling mechanism.
At the root of the Java event class hierarchy is EventObject, which is in java.util.
It is the superclass for all events. Its one constructor is shown here:
EventObject(Object src)
SN Class Description
1 ActionEvent Generated when a button is pressed, a list item is double
clicked, or a menu item is selected.
2 ItemEvent Generated when a check box or list item is clicked; also
occurs when a choice selection is made or a checkable menu
item is selected or deselected.
3 AdjustmentEvent Generated when a scroll bar is manipulated.
4 TextEvent Generated when the value of a text area or text field is
changed.
5 ComponentEvent Generated when a component is hidden, moved, resized, or
becomes visible.
6 InputEvent Abstract super class for all component input event classes
7 KeyEvent Generated when input is received from the keyboard
8 MouseEvent Generated when the mouse is dragged, moved, clicked,
pressed, or released; also generated when the mouse-enters
or exits a component.
9 FocusEvent Generated when a component gains or loses keyboard focus.
10 ContainerEvent Generated when a component is added to or removed from a
container.
11 WindowEvent Generated when a window is activated, closed, deactivated,
deiconified, iconified, opened, or quit.
Here, src is a reference to the component that generated this event. For example, this might be a
list or choice element.
The type of the event is specified by type.
The specific item that generated the item event is passed in entry.
The current state of that item is in state.
Here, src is a reference to the object that generated this event. The type of the event is specified
by type.
ComponentEvent is the super-class either directly or indirectly of ContainerEvent, FocusEvent,
KeyEvent, MouseEvent, and WindowEvent.
ComponentEvent Method
boolean isAltDown( )
boolean isAltGraphDown( )
boolean isControlDown( )
boolean isMetaDown( )
boolean isShiftDown( )
InputEvent Method:
int getModifiers( )
Returns a value that contains all of the modifier flags for this event.
KeyEvent(Component src, int type, long when, int modifiers, int code)
KeyEvent(Component src, int type, long when, int modifiers, int code, char ch)
-------
MouseEvent is a subclass of InputEvent and has this constructor:
MouseEvent(Component src, int type, long when, int modifiers, int x, int y, int
clicks,boolean triggersPopup)
boolean isTemporary( )
src is a reference to the object that generated this event. The type of the event is type.
WindowEvent Method
Window getWindow( )
Returns the Window object that generated the event.
Sources of Events: -
SN Interface Description
1 ActionListener Defines one method to receive action events.
2 AdjustmentListener Defines one method to receive adjustment
events.
3 ComponentListener Defines four methods to recognize when a
component is hidden, moved, resized, or shown.
ROUGH WORK
Unit-4
What is applet?
“An applet represents Java byte code embedded in a web page.”
Initialization state:-
1 Applet enters the initialization state when it is first loaded.
2 The init( ) method is the first method to be called.
3 This method is the first method to be called by the browser and it is execute only once.
4 So, the programmer can use this method to initialize any variable, creating component, set up
colours and create objects needed by the applet.
5 When this method execution is completed, browser looks for the next method: start().
6 Syntax of initialization method:-
public void init()
{
……….
………..
}
Running state:-
1 Applet enters the running state when the system calls the start() method of Applet class.
2 This method may be called multiples time when the Applet needs to be started or restarted.
3 For example, the user has minimized the web page that contains the applet and moved to
another page then this method’s execution is stopped.
4 When the user comes back to view the web page again, start() method execution will resume.
5 start() method may be called more than once.
public void start()
{
……….
………..
}
/ An Applet
skeleton. import
java.awt.*; import
java.applet.*; /*
<applet code="AppletSkel" width=300
height=100> </applet>
*/
public class AppletSkel extends Applet
{
/ Called first.
public void init()
{
/ initialization
}
/* Called second, after init(). Also called whenever the applet is restarted. */
public void start()
{
/ start or resume execution
}
/ Called when the applet is
stopped. public void stop()
{
/ suspends execution
}
/* Called when applet is terminated. This is the last method executed. */
public void destroy()
{
// perform shutdown activities
}
// Called when an applet's window must be restored.
public void paint(Graphics g)
{
// redisplay contents of window
}
java.lang.Object
java.awt.Component
java.awt.Container
java.awt.Panel
java.applet.Applet
<APPLET
[CODEBASE =codebase_URL]
CODE =AppletFileName.class
[ALT=alternate_text]
[NAME=applet_instance_name]
WIDTH=pixels
HEIGHT=pixels
[ALIGN=alignment]
[VSPACE=pixels]
[HSPACE=pixels]
>
[<PARAM NAME=name1 VALUE=value1>]
[<PARAM NAME=name2 VALUE=value2>]
...........
...........
</APPLET>
Attribute Description
CODE =AppletFileName.class Name of the applet class file to be loaded.it must be
specified which execute java bytecode for the applet is
stored
[CODEBASE =codebase_URL] Specifies the URL of the directory in which the applet
(optional) resides.
WIDTH=pixles This defines width of applet.
HEIGHT=pixles This defines height of applet.
[NAME=applet_instance_name] Specified name of applet so that other applet on the
(optional) page may refer to this applet
[ALIGN=aligment] Specifies where on the page the applet will
appear[TOP,BOTTOM,LEFT,RIGHT,MIDDLE,ABSMIDDLE,
TEXTTOP,BASELINE]
[VSPACE=pixles] Specifies the amount of vertical blank space the
browser.
[HSPACE=pixles] Specifies the amount of horizontal blank space the
browser.
[ALT=alternate_text] Non-Java browsers will display this text where the
applet would normally go. This attribute is optional.
[<PARAM NAME=name2 Supply user-defined parameter to an applet.
VALUE=value2>] NAME indicates name of attribute.
VALLUE indicates value of that parameter.
}
public void start()
{
param=getParameter("fontSize");
fontSize = Integer.parseInt(param);
}
public void paint(Graphics g)
{
String msg;
URL url = getCodeBase();
msg = "Code base: " + url.toString();
g.drawString(msg, 10, 20);
g.drawString(str,10,100);
g.drawString("Font size: " + fontSize,20,150);
showStatus("This is shown in the status window.");
resize(300,300);
}
}
<html>
<head>
<title> welcome to java applet</title>
</head>
<body>
<applet code=hellojava.class width=200
height=200> <param name="string"
value="APPLET">
<param name=fontSize value=14>
</applet>
</body>
</html>
Component
1. Component class is the super class of all other classes.
2. It is responsible for affecting the display of a graphics object on the screen.
3. It is also handle the various keyboards and mouse events of the GUI applications.
Container
1. The container object contains the other awt components.
2. It manages the other layout and placement of the various awt components within the container.
3. A container object can contain others containers object as well; thus allowing nesting of
containers.
Window
1. The window object realizes a top level window but without any border or menu bar.
2. It just specifies the layout of the window.
3. A typical window that you want to create in your application is not normally derived from the
Window class but from its subclass.
Panel
1. The supper class of applet is panel.
2. The panel class represents a window space on which application’s output is displayed.
3. It is just like a normal window having no border, title bar, menu bar etc…
4. A panel can contain within itself other panel as well.
Frame
1. The frame object realizes a top level window complete with border and menu bar.
2. It supports common window related events such as close, open, activate, deactivate etc…
3. Almost all the programs that we created while discussing applets and graphics programming
used one or more classes of the awt package.
Graphics Class:-
“Graphics class includes methods for drawing many different types of shapes, from simple line to
polygon to text in a variety of fonts.”
Sn Method Description
1 Void drawRect(int top, int The upper-left corner of the rectangle is at top, left. The
left, int width, int height) dimensions of the rectangle are specified by width and height.
2 Void fillRect(int top, int Its draw rectangle fills with black colour.
left, int width, int height)
import java.awt.*;
import java.applet.*;
/*
<applet code=graph_ex width=600 height=600 >
</applet>
*/
public class graph_ex extends Applet
{
public void paint (Graphics g)
{
setBackground(Color.cyan);
Font f=new Font("Arial",Font.BOLD,20);
g.setFont(f);
g.drawString("Here are a selection of blank shapes.",20,40);
g.drawLine(20,40,200,40);
g.setColor(Color.blue);
g.drawLine(20,50,70,90);
g.setColor(Color.red);
g.drawRect(100,50,32,55);
g.setColor(Color.green);
g.drawOval(150,46,60,60);
g.setColor(Color.magenta);
g.drawArc(230,50,65,50,30,270);
g.setColor(Color.black);
g.drawString("Here are the filled equivalents.",20,140);
g.drawLine(20,140,200,140);
g.setColor(Color.yellow);
g.fillRect(100,150,32,55);
g.setColor(Color.pink);
g.fillOval(150,146,60,60);
g.setColor(Color.darkGray);
g.fillArc(230,150,65,50,30,270);
g.setColor(Color.orange);
int x[]={300,400,300,150};
int y[]={300,120,400,250};
int num=4;
g.fillPolygon(x,y,num);
}
}
JDBC-ODBC Connection:-
JDBC is Java application programming interface that allows the Java programmers to access
database management system from Java code.
Java Database Connectivity in short called as JDBC. It is a java API which enables the java
programs to execute SQL statements.
It is an application programming interface that defines how a java programmer can access the
database in tabular format from Java code using a set of standard interfaces and classes written in
the Java programming language.
JDBC has been developed under the Java Community Process that allows multiple implementations
to exist and be used by the same application.
JDBC provides methods for querying and updating the data in Relational Database Management
system such as SQL, Oracle etc.
The Java application programming interface provides a mechanism for dynamically loading the
correct Java packages and drivers and registering them with the JDBC Driver Manager that is
used as a connection factory for creating JDBC connections which supports creating and executing
statements such as SQL INSERT, UPDATE and DELETE. Driver Manager is the backbone of the JDBC
architecture.
Generally all Relational Database Management System supports SQL and we all know that Java is
platform independent, so JDBC makes it possible to write a single database application that can run
on different platforms and interact with different Database Management Systems.
Java Database Connectivity is similar to Open Database Connectivity (ODBC) which is used for
accessing and managing database, but the difference is that JDBC is designed specifically for Java
programs, whereas ODBC is not depended upon any language.
In short JDBC helps the programmers to write java applications that manage these three
programming activities:
1 It helps us to connect to a data source, like a database.
2 It helps us in sending queries and updating statements to the database and
3 Retrieving and processing the results received from the database in terms of answering to your
query.
ROUGH WORK
class area
{
public static void main(String args[])
{
double pi,r,a;
pi=3.1416;
r=5; a=pi*r*r;
System.out.println(“This is the area of Circle”+a);
}
}
Output
This is the area of Circle78.54
2) Write a Java Program that will display Factorial of the Given Number.
class factorial
{
public static void main(String args[])
Output
Factorial of given No::120
import java.io.*;
class factorial
{
public static void main(String args[]) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in);
String str;
Str=br.readLine();
int num=Integer.parseInt(str);
int result=1;
while(num>0)
{
result=result*num;
num--;
}
System.out.println(“Factorial of Given No::”+result);
}
}
Output
5
Factorial of given No::120
3) Write a Java Program that will display the sum of 1+1/2+1/3…+1/n. (Harmonic Series)
class pro3
{
public static void main(String args[])
{
double i,j; double
sum=0; double
num=3;
for(i=1;i<=num;i++)
{
j=1/i;
sum=sum+j;
}
System.out.println("\nSum of series is :-->"+sum);
}
}
Output
Sum of series is:1.8333333333333333
import java.io.*;
[BY. VIPUL PRAJAPATI] Page 86
[CCMS VADU] BCA-501-JAVA PROGRAMMING
class pro3
{
public static void main(String args[]) throws IOException
{
double i,j,num;
double sum=0;
for(i=1;i<=num;i++)
{
j=1/i;
sum=sum+j;
}
System.out.println("\nSum of series is :-->"+sum);
}
}
Output:-
3
Sum of series is: 1.8333333333333333
class primeno
{
public static void main(String args[])
{
int i, j, a = 0,k=1;
for (i = 1; i <= 100; i++)
{
a = 0;
for (j = 2; j <= i - 1; j++)
{
if (i % j == 0)
{
a = 1;
}
}
if (a != 1 && k<=25)
{
System.out.println("THis is the\t"+k+"\t primenumber-->" + i);
k=k+1;
}
}
}
}
Output:-
This is 1 prime number=1
This is 2 prime number=2
This is 3 prime number=3
This is 4 prime number=5
(same as Up to 25)
5) Write a Java Program that will accept Command-Line argument and Display the same.
import java.io.*;
class command
Output:-
ABCD
This is Your String :->ABCD
import java.io.*;
class ascending
{
public static void main(String args[]) throws IOException
{
//to accept command line argument
for(int i=0;i<n;i++)
{
Sysem.out.print("Enter Integer::->");
arr[i]=Integer.parseInt(br.readLine());
}
int limit=n-1;
for(int i=0;i<limit;i++)
{
for(int j=0;j<limit-i;j++)
{
if(arr[j]<arr[j+1])
{
int temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
}
Output:-
7) Write a Java Program which will read a text and count all occurrences of a particular word.
import java.util.*;
import java.io.*;
import java.lang.*;
public class StringCount
{
public static void main(String args[]) throws IOException
{
BufferedReader br1=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter String:----->");
String base = br1.readLine();
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter SubString which YOu want to count-->");
String searchFor = br.readLine();
int len = searchFor.length();
int result = 0;
if (len > 0)
{
int start = base.indexOf(searchFor);
while (start != -1)
{
result++;
start = base.indexOf(searchFor, start+len);
}
}
System.out.println(result);
}
}
8) Write a Java Program which will read a string and rewrite it in the alphabetical order eg.The
Word “STRING” should be written a “GINRST”.
import java.io.*;
class Aphabetic
{
public static void main(String args[]) throws IOException
{
String str;
char s[];
}
class BoxDemo7 {
public static void main(String args[]) {
/ declare, allocate, and initialize Box objects
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box(3, 6, 9);
double vol;
/ get volume of first box
vol = mybox1.volume();
System.out.println("Volume is " + vol);
/ get volume of second box vol =
mybox2.volume();
System.out.println("Volume is " + vol);
}
}
10) Write a java program which show the use of methods overloading .
// Demonstrate method overloading.
class OverloadDemo
{ void test() {
System.out.println("No parameters");
}
/ Overload test for one integer parameter.
void test(int a) {
System.out.println("a: " + a);
}
/ Overload test for two integer parameters.
void test(int a, int b) {
System.out.println("a and b: " + a + " " + b);
}
/ overload test for a double parameter
class Overload {
public static void main(String args[]) {
OverloadDemo ob = new OverloadDemo();
double result;
/ call all versions of test()
ob.test();
ob.test(10); ob.test(10,
20); result =
ob.test(123.2);
System.out.println("Result of ob.test(123.2): " + result);
}
}
11) Write a java program which show the use of static members.
// Demonstrate static variables, methods, and blocks.
class UseStatic { static
int a = 3; static
int b;
static void meth(int x)
{ System.out.println("x = " +
x); System.out.println("a = " +
a); System.out.println("b = " +
b);
}
static {
System.out.println("Static block initialized.");
b = a * 4;
}
class Nesting
{
int m,n;
Nesting(int x,int y) //Constructor method
{
m=x;
n=y;
}
int largest()
{
if(m>=n)
return m;
else
return n;
}
void display()
{
int large=largest(); // call method and store result in variable
System.out.println("Largest value is ==>"+large);
}
}
13) Write a java program which explaining the concept of single inheritance.
interface Callback
{
void callback(int param);
}
interface value
{
[BY. VIPUL PRAJAPATI] Page 93
[CCMS VADU] BCA-501-JAVA PROGRAMMING
float val=6;
void multi();
}
interface value1
{
float val=5;
void multi();
}
class multiplication implements value,value1
{
public void multi()
{
//multiplication of two numbers float
mul=(value.val*value1.val);
System.out.println("multiplication of two number="+mul);
}
}
class multiInterface
{
public static void main(String args[])
{
multiplication mu=new multiplication();
mu.multi();
}
}
18) Write a java program which shows importing of classes from other package.
19) Write a Java program which creates threads using the thread class.
for(int i=1;i<=10;i++)
{
System.out.println(i);
}
}
}
//another class
class demo
{
public static void main(String args[])
{
//create an object to mythread class
mythread obj=new mythread();
}
}
20) Write a Java program which shows the use of yield(),stop() and sleep() method.
{
}
}
System.out.println("Exit from c");
}
}
class ThreadMethods
{
public static void main(String args[])
{
A threadA=new A();
B threadB=new B();
C threadC=new C();
//Thread priorities
class myclass extends Thread
{
int count=0; //this count numbers
public void run()
{
for(int i=1;i<10;i--)
[BY. VIPUL PRAJAPATI] Page 96
[CCMS VADU] BCA-501-JAVA PROGRAMMING
count++;//count number up to 10
/ display which thread has completed counting and its priority
System.out.println("Complete Thread:"+Thread.currentThread().getName());
System.out.println("Its priority:"+Thread.currentThread().getPriority());
}
}
class prior
{
public static void main(String args[])
{
myclass obj=new myclass();
class PrintString
{
public static void main (String args [ ])
{
StringThread t = new StringThread ("Java",5);
new Thread(t). start ( );
}
}
class StringThread implements Runnable
{
String str;
int num;
StringThread(String s, int n)
{
str = new String (s);
num =n;
}
public void run ( )
{
for (int i=1; i<=num; i++)
System.out.print (str+" ");
}
}
23) Write a Java program which use try and catch for exception handling.
class Exc2 {
public static void main(String args[])
{
int d, a;
try
{ // monitor a block of code.
d = 0;
a = 42 / d;
System.out.println("This will not be printed.");
int res=0;
try
{
res = num1/num2;
System.out.println("The result is" +res);
for(int ct =2;ct >=0; ct--)
{
System.out.println("The value of array are"
+array[ct]); }
}
catch (ArrayIndexOutOfBoundsException e)
{
System.out.println("Error…. Array is out of Bounds");
}
catch (ArithmeticException e)
{
System.out.println ("Can't be divided by Zero");
}
}
}
25) Write a Java program which shows throwing our own exception.
import java.lang.Exception;
class MyException extends Exception
{
MyException(String message)
{
super(message);
26)Make a Applet that create two button named ”Red” and “Blue” when a button is pressed
the background color of the applets is set to the color named by the button’s label.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="ButtonDemo" width=500
height=500> </applet>
*/
public class ButtonDemo extends Applet implements ActionListener
{
}
public void actionPerformed(ActionEvent ae)
{
//Know the label of the button clicked by user
String str = ae.getActionCommand();
}
}
Javac ButtonDemo.java
appletviewer ButtonDemo.java
27) Write a Java Applet that create some text fields and text area to demonstrate features
of each.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="TextFieldDemo" width=400 height=400>
</applet>
*/
public class TextFieldDemo extends Applet implements ActionListener,TextListener
{
TextField name, pass;
TextArea area;
public void init()
{
Label namep = new Label("Name: ", Label.RIGHT);
Label passp = new Label("Password: ", Label.RIGHT);
name = new TextField(12);
pass = new TextField(8);
area = new TextArea(5,30);
pass.setEchoChar('?');
add(namep);
add(name);
add(passp);
add(pass);
add(area);
}
}
28) Create an applet with three textfield & two button add & subtract.User will enter two
values in the TextFields. When the add is pressed , the addition of the two values should be
displayed in the TextFields. Same the Subtract button should perform the subtraction
operation.
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/*
<applet code=EventDemo width=350 height=200>
</applet>
*/
public class EventDemo extends Applet implements ActionListener
{
TextField t1,t2,t3;
Button b1, b2;
Label l1,l2,l3;
public void init()
{
t1= new TextField(5);
t2= new TextField(5);
t3= new TextField(5);
l1= new Label("First number");
l2= new Label("Second number");
l3= new Label("The Final Result is");
b1=new Button("Addition");
b2=new Button("Subtraction");
b1.addActionListener(this);
b2.addActionListener(this);
add(l1);
add(t1);
add(l2);
add(t2);
add(l3);
add(t3);
add(b1);
add(b2);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==b1)
{
int n1= Integer.parseInt(t1.getText());
int n2= Integer.parseInt(t2.getText());
int n3=n1+n2;
t3.setText(Integer.toString(n3));
}
if(e.getSource()==b2)
{
int n1= Integer.parseInt(t1.getText());
int n2= Integer.parseInt(t2.getText());
int n3=n1-n2;
t3.setText(Integer.toString(n3));
[BY. VIPUL PRAJAPATI] Page 101
[CCMS VADU] BCA-501-JAVA PROGRAMMING
}
}
}
29) Create an applet to display the scrolling text. The text should move from right to left.
When it reaches to start of the applet border, it should stop moving and restart from the left.
When the applet is deactivated, it should stop moving. Its should restart moving from the
previous location when again activated.
import java.awt.*;
import java.applet.*;
/*
<applet code=scrolling_Text width=300
height=300> </applet>
*/
public class scrolling_Text extends Applet implements Runnable
{
int i=0,flag=0;
}
public void paint(Graphics g)
{
try
{
g.setColor(Color.red);
g.drawString("I.N.S.B. College,IDAR",i,50);
t.sleep(200);
if(i<280 && flag==0)
{
i=i+10;
}
else
{
if(i==0)
{
flag=0;
}
else
{
flag=1;
i=i-10;
}
}
repaint();
}
catch(Exception e){}
}
}
30) Write a program to create three scrollbar and a label. The background color of the
label should be changed according to the values of the scrollbars (The combination of the
values RGB)
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/*
<applet code=scrollbar_RGB width=600 height=300>
</applet>
*/
public class scrollbar_RGB extends Applet implements AdjustmentListener
add(l);
add(lred);
add(sred);
add(lblue);
add(sblue);
add(lgreen);
add(sgreen);
sred.addAdjustmentListener(this);
sblue.addAdjustmentListener(this);
sgreen.addAdjustmentListener(this);
}
public void adjustmentValueChanged(AdjustmentEvent ae)
{
if(ae.getSource()==sred||ae.getSource()==sblue||ae.getSource()==sgreen)
{
r=sred.getValue();
g=sgreen.getValue();
b=sblue.getValue();
Color c=new Color(r,g,b);
l.setBackground(c);
}
}
}
31) Write a java program which copying a characters from one file to another.
import java.io.*;
class CopyChar
{
public static void main(String args[]) throws IOException
{
File inFile=new File("input.dat");
File outFile=new File("output.dat");
FileReader ins=null;
FileWriter outs=null;
ins=new FileReader(inFile);
outs=new FileWriter(outFile);
int ch;
while((ch=ins.read())!=-1)
{
outs.write(ch);
}
ins.close();
outs.close();
}
}
32) Write a java program which shows reading and writing bytes to a file.
import java.io.*;
class write_readByte
{
public static void main(String args[]) throws IOException
{
byte cities []={'G','U','J','A','R','A','T','\n', 'B','O','M','B','A','Y'};
FileOutputStream outfile=null;
FileInputStream infile=null;
int b;
outfile=new FileOutputStream("city.txt");
outfile.write(cities);
outfile.close();
infile=new FileInputStream("city.txt");
while((b=infile.read())!=-1)
{
System.out.println((char)b);
}
infile.close();
}
}
33) Write a java program which shows the copying bytes from one file to another.
import java.io.*;
class copyByte
{
public static void main(String args[]) throws IOException
{
FileInputStream infile=null;
FileOutputStream outfile=null;
byte byteRead;
infile=new FileInputStream("in.dat");
outfile=new FileOutputStream("out.dat");
do
{
byteRead=(byte) infile.read();
outfile.write(byteRead);
}
while(byteRead!=-1);
infile.close();
outfile.close();
}
}
34) Write a java program which shows reading and writing primitive data.
import java.io.*;
class readwritePrimitive
{
dos.writeInt (1999);
dos.writeDouble (375.333);
dos.writeBoolean (false);
dos.writeChar ('R');
dos.close ();
fos.close ();
35) Write a java program which shows the single file for storing and retrieving.
import java.io.*;
class ReadWriteInteger
{
public static void main(String args[]) throws IOException
{
//Declare Data Stream
DataInputStream dis=null;
DataOutputStream dos=null;
//Construct a File
File intFile=new File("read.txt");
}
}
36) Write a java program which shows writing and reading with random access.
import java.io.*;
file=new RandomAccessFile("rand.dat","rw");
//writing to the file
file.writeChar('x');
file.writeInt(333);
file.writeDouble(322.33);
file.seek(4);
System.out.println(file.readBoolean());
file.close();
}
}
-: Questions of JAVA :-
Unit: - 1
1. What is object oriented Programming Language? How it’s Different from the procedure-oriented
Language?
2. What are the unique advantages of an object-Oriented Programming Paradigm?
3. Describe Common Features of Java. (Buzz words)
4. Explain Scope for member Variable & Function.
5. Explain java Magic Code, Compiler, interpreter with figure.
6. Explain Tools of Java.
7. What is relation between polymorphism, Function overloading and Operator Overloading.
8. Explain Control Structure of Java.
9. What is the Difference between C, C++ & Java?
10. Describe the Structure of Java Program.
11. What is Token? List the various types of token Supported by Java.
12. What is JVM? Explain Structure of JVM. How its Execute Java Program?
13. What is type casting? Why is it required in Java Program?
14. Explain Type Conversation in Java.
15. Explain Conditional Operator in Java With Example.
16. Explain Data Abstraction, Polymorphism & Encapsulation.
17. What is Garbage Collection?
Unit:-2
1. What is Constructor? What are its Special Properties?
2. Is Destructor support by Java? Explain with Reason.
3. Explain inheritance in java with Example.
4. Is multiple inheritances supported by Java? How its implements in Java?
5. Explain Method Overloading and Method Overriding.
What is the Difference between Method Overloading & Method Overriding? Define Each with
Example.
6. Explain Characteristic of abstract Class with Example.
7. What is Dynamic Method Dispatch?
8. Explain Difference between abstract class & Interface.
9. Explain Static Member with Example.
10. Explain Final Class with Example.
11. How we implement Nesting method in Java? Define with example.
12. Explain Random Class & String Tokenizer with example.
13. What is the Difference between Stack, Array & Vector? Explain Vector class With Example.
14. Explain Date & Calendar Class with example.
15. Explain Interface with Example. How Interface solve the problem of Inheritance? Explain with
example.
16. What is the use of wrapper Class in java? Explain it in brief.
Unit:-3
1. What is thread? What is the Difference between Multi-Threading and Muti-Tasking?
2. Difference between Process & Thread. Explain Thread Life Cycle.
3. Explain Thread Creation. Explain with Program.
4. Explain Methods Of Thread.
5. Explain Priorities of Thread with Example.
6. What is Synchronization (Monitors) in Thread? When so we use it? Explain It with Example.
7. What is Deadlock? How to implement Deadlock in Thread?
8. What is Exception? How many types are Exception in Java? What is Exception Handling? How its
implement in java?
9. What is the use of try, catch in Java? Explain nested try catch with Example.
10. What is the difference between throw & throws?
11. How we can create our own user define Exception in Java with Example?
12. What is difference between final, finalize and finally in Java.
13. Write short note on Event Delegation Model.
14. Explain Event handling process.
15. Explain Event classes.
16. Explain Different source of Event.
17. Explain Event Listener interface.
Unit:-4
1. Difference between Application & Applet.
2. Explain Applet Skeleton. (Explain Applet Life Cycle.)
3. Explain passing parameter in Java Applet.
4. Explain Different Methods in Applet.
5. Explain Advantages & Disadvantage of Applet.
6. Explain use of Thread in Applet with Example.
7. Explain AWT package & Its Hierarchy.
8. Explain Graphics class in Applet.
ROUGH WORK