432 Bcs3&Bca31 Java Programming
432 Bcs3&Bca31 Java Programming
UNIVERSITY
E-NOTES
PREPARED BY
SYLLABUS
Objectives:
To improve Object Oriented Programming gathered already through an independent
platform.
Unit – I: BASICS, ESSENTIALS, CONTROL STATEMENT AND CLASSES &
OBJECTS
Computer and its Languages – Stage, Origin and Features for Java - JDK–OOP;
JavaEssentials:Program – API - Variables& Literals - Data Types - String Class – Operators -
Type conversion - Constants - Scope – Comments - Keyboard Input; Control
Statements:Conditional Statements – Looping Statements - Break and Continue Statements;
Classesand Objects: Modifiers - Arguments - Constructors - Packages and import - Static
Class -Overloaded Methods and Constructors - Returning Objects – toString() - this reference
–Enumeration - Garbage Collection.
UNIT I
It can only understand and execute instructions given in the form of machine
languages i.e. the binary number 0 and 1.
Disadvantages
1. All operation codes have to be remembered
2. All memory addresses have to be remembered
3. It is hard to amend or find errors in a program written in the machine language
4. These languages are machine dependent i.e. a particular machine language can be
used on only one type of computer.
1.1.2 Assembly Languages
It was developed to overcome some of the many inconveniences of machine language. This
is another low level but a very important language in which operation codes and operands are
given in the form of alphanumeric symbols instead of 0’s and 1’s. These alphanumeric
symbols will be known as mnemonic codes and can have maximum up to 5 letter
combinations e.g. ADD for addition, SUB for subtraction, START LABEL etc. because of
this feature it is also known as “Symbolic Programming Language”. This language is very
difficult and needs a lot of practice to master it because very small English support is given.
This symbolic language helps in compiler orientations. The instructions of the assembly
language will also be converted to machine codes by language translator to be executed by
the computer
Advantages
1. It is easier to understand and use as compared to machine language
2. It is easy to locate and correct errors
3. It is modified easily
Disadvantages
1. Like machine language it is also machine dependent
2. Since it is machine dependent, there programmer should have the knowledge of he
hardware also.
The features of Java are also known as java buzzwords. Following is a list of most
important features of Java language.
The Java Features given below are simple and easy to understand.
Simple
Object-Oriented
Portable
Platform independent
Secured
Robust
Architecture neutral
Dynamic
Interpreted
High Performance
Multithreaded
Distributed
Simple
Java is very easy to learn and its syntax is simple, clean and easy to understand. According to
Sun, Java language is simple because:
syntax is based on C++ (so easier for programmers to learn it after C++).
Removed many confusing and/or rarely-used features e.g., explicit pointers, operator
overloading etc.
No need to remove unreferenced objects because there is Automatic Garbage
Collection in java.
Object-oriented
Object
Class
Inheritance
Polymorphism
Abstraction
Encapsulation
Platform Independent
Java is platform independent because it is different from other languages like C, C++
etc. which are compiled into platform specific machines while Java is a write once,
run anywhere language. A platform is the hardware or software environment in which
a program runs.
There are two types of platforms software-based and hardware-based. Java provides
software-based platform.
The Java platform differs from most other platforms in the sense that it is a software-
based platform that runs on the top of other hardware-based platforms.
It has two components:
Runtime Environment
API(Application Programming Interface)
Java code can be run on multiple platforms e.g. Windows, Linux, Sun Solaris,
Mac/OS etc. Java code is compiled by the compiler and converted into bytecode. This
bytecode is a platform-independent code because it can be run on multiple platforms
i.e. Write Once and Run Anywhere(WORA).
Secured
Java is best known for its security. With Java, we can develop virus-free systems. Java is
secured because:
No explicit pointer
Java Programs run inside virtual machine sandbox
Robust
Robust simply means strong. Java is robust because:
It uses strong memory management.
There are lack of pointers that avoids security problem.
There is automatic garbage collection in java.
There is exception handling and type checking mechanism in java. All these points
makes java robust.
Architecture-neutral
Java is architecture neutral because there is no implementation dependent features e.g.
size of primitive types is fixed.
In C programming, int data type occupies 2 bytes of memory for 32-bit architecture
and 4 bytes of memory for 64-bit architecture. But in java, it occupies 4 bytes of
memory for both 32 and 64 bit architectures.
Portable
Java is portable because it facilitates you to carry the java bytecode to any platform.
High-performance
Java is faster than traditional interpretation since bytecode is "close" to native code
still somewhat slower than a compiled language (e.g., C++). Java is an interpreted
language, so it is also a reason that why it is slower than compiled language C, C++.
Distributed
Java is distributed because it facilitates us to create distributed applications in java.
RMI and EJB are used for creating distributed applications. We may access files by
calling the methods from any machine on the internet.
Multi-threaded
A thread is like a separate program, executing concurrently. We can write Java
programs that deal with many tasks at once by defining multiple threads.
The main advantage of multi-threading is that it doesn't occupy memory for each
thread. It shares a common memory area. Threads are important for multi-media, Web
applications etc.
People new to Java may be confused about whether to use the JRE or the JDK. To run
Java applications and applets, simply download the JRE. However, to develop Java
applications and applets as well as run them, the JDK is needed.
Java developers are initially presented with two JDK tools, java and javac. Both are
run from the command prompt. Java source files are simple text files saved with an
extension of .java. After writing and saving Java source code, the javac compiler is
invoked to create .class files. Once the .class files are created, the 'java' command can
be used to run the java program.
There are different JDKs for various platforms. The supported platforms include
Windows, Linux and Solaris. Mac users need a different software development kit,
which includes adaptations of some tools found in the JDK.
Abstraction
Hiding internal details and showing functionality is known as abstraction. For
example: phone call, we don't know the internal processing.
In java, we use abstract class and interface to achieve abstraction.
Encapsulation
Binding (or wrapping) code and data together into a single unit is known as
encapsulation. For example: capsule, it is wrapped with different medicines.
A java class is the example of encapsulation. Java bean is the fully encapsulated class
because all the data members are private here.
Applets
Java is also used to create miniature, dynamic programs that run alongside or are
embedded within Web pages.
These programs are called applets and can be used to display maps, weather, games or
other interactive widgets or tools on a Web page.
Programming
Based on a C and C++-based syntax, Java is object-oriented and class-based.
Developers adopt and use Java because code can be run securely on nearly any other
platform, regardless of the operating system or architecture of the device, as long as
the device has a Java Runtime Environment (JRE) installed.
The JRE varies depending on the specific type of device, but essentially it runs a
“virtual” machine, or environment, that translates the code into an application or
program.
In Java, most basic programming tasks are performed by the API’s classes and packages,
which are helpful in minimizing the number of lines written within pieces of code.
Java compiler
Java Virtual Machine (JVM)
Java Application Programming Interface (API)
The Java API, included with the JDK, describes the function of each of its components. In
Java programming, many of these components are pre-created and commonly used. Thus, the
programmer is able to apply prewritten code via the Java API. After referring to the available
API classes and packages, the programmer easily invokes the necessary code classes and
packages for implementation.
1.7 Variables
A variable is the name given to a memory location. It is the basic unit of storage in a
program.
Declare variables
1.8 Literals
Literals in java are a sequence of characters(digits, letters and other characters) that
represent constant values to be stored in variables. Java language specifies five major types
of literals. They are
Interger literals
Character literals
String literals
Boolean literals
byte
Byte data type is an 8-bit signed two's complement integer
Default value is 0
Byte data type is used to save space in large arrays, mainly in place of integers, since
a byte is four times smaller than an integer.
short
Short data type is a 16-bit signed two's complement integer
Short data type can also be used to save memory as byte data type. A short is 2 times
smaller than an integer
Default value is 0.
int
Int data type is a 32-bit signed two's complement integer.
Integer is generally used as the default data type for integral values unless there is a
concern about memory.
long
Default value is 0L
float
Float data type is a single-precision 32-bit IEEE 754 floating point
Float is mainly used to save memory in large arrays of floating point numbers
Float data type is never used for precise values such as currency
double
double data type is a double-precision 64-bit IEEE 754 floating point
This data type is generally used as the default data type for decimal values, generally
the default choice
Double data type should never be used for precise values such as currency
boolean
This data type is used for simple flags that track true/false conditions
char
The java string toUpperCase() method converts this string into uppercase letter and string
toLowerCase() method into lowercase letter.
Program:
String s="Sachin";
System.out.println(s.toUpperCase());//SACHIN
System.out.println(s.toLowerCase());//sachin
System.out.println(s);//Sachin(no change in original)
Output
SACHIN
sachin
Sachin
1.11 Operators
Java provides a rich set of operators to manipulate variables. We can divide all the Java
operators into the following groups −
Arithmetic Operators
Relational Operators
Bitwise Operators
18 BCS 31/BCA 31 – JAVA PROGRAMMING
E-NOTES / B.SC CS /BCA
Logical Operators
Assignment Operators
Misc Operators
Show Examples
Show Examples
Bitwise operator works on bits and performs bit-by-bit operation. Assume if a = 60 and b =
13; now in binary format they will be as follows −
a = 0011 1100
b = 0000 1101
~a = 1100 0011
Show Examples
& (bitwise Binary AND Operator copies a bit to the (A & B) will give 12 which
and) result if it exists in both operands. is 0000 1100
^ (bitwise Binary XOR Operator copies the bit if it is (A ^ B) will give 49 which is
XOR) set in one operand but not both. 0011 0001
Assume Boolean variables A holds true and variable B holds false, then −
Show Examples
Show Examples
A + B
into C
%A
C <<= 2
is same as
<<= Left shift AND assignment operator.
C = C <<
2
C >>= 2
is same as
>>= Right shift AND assignment operator.
C = C >>
2
C &= 2 is
&= Bitwise AND assignment operator. same as C
=C&2
Conditional Operator ( ? : )
Conditional operator is also known as the ternary operator. This operator consists of three
operands and is used to evaluate Boolean expressions. The goal of the operator is to decide,
which value should be assigned to the variable.
Syntax:
Syntax:
Assigning a value of one type to a variable of another type is known as Type Casting.
Syntax:
int x = 10;
byte y = (byte)x;
Widening Casting(Implicit)
Example :
}
Output:
Int value 100
Long value 100
Float value 100.0
Example :
Output:
Double value 100.04
Long value 100
Int value 100
1.13 Constants
A constant is a variable whose value cannot change once it has been assigned.Java doesn't
have built-in support for constants, but the variable modifiers static and final can be used to
effectively create one. Constants can make your program more easily read and understood
by others.
The scope of a variable specifies the region of the source program where that variable
is known, accessible and can be used.
In Java, the declared variable has a definite scope. When a variable is defined within a
class, its scope determines whether it can be used only within the defined class or
outside of the class also.
Local variables can be used only within the block in which they are defined.
The scope of instance variables covers the entire class, so they can be used by any of
the methods within that class.
Variables that are declared in an outer scope can also be used in an inner scope.
The unique way in which Java checks for the scope of a given variable makes it
possible to create a variable in an inner scope such that a definition of that variable
hides its original value. Program makes this point clear.
The java comments are statements that are not executed by the compiler and interpreter. The
comments can be used to provide information or explanation about the variable, method,
class or any statement. It can also be used to hide program code for specific time.
Syntax:
Program:
Output:
10
Syntax:
/*
This
is
multi line
comment
*/
30 BCS 31/BCA 31 – JAVA PROGRAMMING
E-NOTES / B.SC CS /BCA
Program
public class CommentExample2
{ public static void main(String[] args)
{
/* Let's declare and
print variable in java. */
int i=10;
System.out.println(i);
}
}
Output
10
Syntax:
/**
This
is
documentation
comment
*/
1.16 Keyboard Input(JAVA Scanner class)
There are various ways to read input from the keyboard, the java.util.Scanner class is
one of them.
The Java Scanner class breaks the input into tokens using a delimiter that is
whitespace bydefault. It provides many methods to read and parse various primitive
values.
Java Scanner class is widely used to parse text for string and primitive types using
regular expression.
Java Scanner class extends Object class and implements Iterator and Closeable
interfaces.
public String next() It returns the next token from the scanner.
Java programming language provides following types of decision making statements. Click
the following links to check their detail.
1.17.1 If statement:
An if statement consists of a Boolean expression followed by one or more statements.
Syntax
if(Boolean_expression) {
// Statements will execute if the Boolean expression is true
}
Explanation:
If the Boolean expression evaluates to true then the block of code inside the if statement will
be executed. If not, the first set of code after the end of the if statement (after the closing
curly brace) will be executed.
Flow Diagram
Example
if( x < 20 ) {
System.out.print("This is if statement");
}
}
}
Output
This is if statement.
1.17.2 If…else
An if statement can be followed by an optional else statement, which executes when the
Boolean expression is false.
Syntax
if(Boolean_expression) {
// Executes when the Boolean expression is true
}else {
// Executes when the Boolean expression is false
}
Explanation:
If the boolean expression evaluates to true, then the if block of code will be executed,
otherwise else block of code will be executed.
Flow Diagram
Example
Live Demo
public class Test {
if( x < 20 ) {
System.out.print("This is if statement");
}else {
System.out.print("This is else statement");
}
}
}
Output
This is else statement
Example
switch(grade)
{ case 'A' :
System.out.println("Excellent!");
break;
case 'B' :
case 'C' :
System.out.println("Well done");
break;
case 'D' :
System.out.println("You passed");
case 'F' :
System.out.println("Better try
again"); break;
default :
System.out.println("Invalid grade");
}
System.out.println("Your grade is " + grade);
}
}
Output
Well done
Your grade is C
A loop statement allows us to execute a statement or group of statements multiple times and
following is the general form of a loop statement in most of the programming languages −
While loop
For loop
Do…while loop
A while loop statement in Java programming language repeatedly executes a target statement
as long as a given condition is true.
Syntax
while(Boolean_expression) {
// Statements
}
39 BCS 31/BCA 31 – JAVA PROGRAMMING
E-NOTES / B.SC CS /BCA
Explanation:
Here, statement(s) may be a single statement or a block of statements. The condition may be
any expression, and true is any non zero value.
When executing, if the boolean_expression result is true, then the actions inside the loop will
be executed. This will continue as long as the expression result is true.
When the condition becomes false, program control passes to the line immediately following
the loop.
Flow Diagram
Here, key point of the while loop is that the loop might not ever run. When the expression is
tested and the result is false, the loop body will be skipped and the first statement after the
while loop will be executed.
Example
while( x < 13 )
{ System.out.print("value of x : " +
x ); x++;
System.out.print("\n");
}
}
}
Output
value of x : 10
value of x : 11
value of x : 12
A for loop is a repetition control structure that allows you to efficiently write a loop
that needs to be executed a specific number of times.
A for loop is useful when you know how many times a task is to be repeated.
Syntax
Explanation:
The initialization step is executed first, and only once. This step allows you to
declare and initialize any loop control variables and this step ends with a semi colon
(;).
Next, the Boolean expression is evaluated. If it is true, the body of the loop is
executed. If it is false, the body of the loop will not be executed and control jumps to
the next statement past the for loop.
After the body of the for loop gets executed, the control jumps back up to the update
statement. This statement allows you to update any loop control variables. This
statement can be left blank with a semicolon at the end.
The Boolean expression is now evaluated again. If it is true, the loop executes and the
process repeats (body of loop, then update step, then Boolean expression). After the
Boolean expression is false, the for loop terminates.
Flow Diagram
Example
Live Demo
public class Test {
Output
value of x : 10
value of x : 11
value of x : 12
1.18.3 Do…while
A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to
execute at least one time.
Syntax
do {
// Statements
}while(Boolean_expression);
Explanation:
Notice that the Boolean expression appears at the end of the loop, so the statements in the
43 BCS 31/BCA 31 – JAVA PROGRAMMING
E-NOTES / B.SC CS /BCA
Example:
do {
System.out.print("value of x : " + x );
x++;
System.out.print("\n");
}while( x < 13 );
}
}
Output:
value of x : 10
value of x : 11
value of x : 12
1.19 Break statement
The break statement in Java programming language has the following two usages −
When the break statement is encountered inside a loop, the loop is immediately terminated
and the program control resumes at the next statement following the loop.
It can be used to terminate a case in the switch statement (covered in the next chapter).
Syntax
break;
Flow Diagram
Example
Live Demo
public class Test {
public static void main(String args[]) {
int [] numbers = {10, 20, 30, 40, 50};
for(int x : numbers ) {
if( x == 30 ) {
break;
}
System.out.print( x );
System.out.print("\n");
}
}
}
Output
10
20
Example
Live Demo
public class Test {
for(int x : numbers )
{ if( x == 30 ) {
continue;
}
System.out.print( x );
System.out.print("\n");
}
}
}
Output
10
20
40
50
1.20 Class and Objects:
Object − Objects have states and behaviors. Example: A dog has states - color, name,
breed as well as behaviors – wagging the tail, barking, eating. An object is an
instance of a class.
Objects in Java
If we consider the real-world, we can find many objects around us, cars, dogs,
humans, etc. All these objects have a state and a behavior.
47 BCS 31/BCA 31 – JAVA PROGRAMMING
E-NOTES / B.SC CS /BCA
If we consider a dog, then its state is - name, breed, color, and the behavior is -
barking, wagging the tail, running.
If you compare the software object with a real-world object, they have very similar
characteristics.
Software objects also have a state and a behavior. A software object's state is stored
in fields and behavior is shown via methods.
Classes in Java
A class is a blueprint from which individual objects are created..
Example:
public class Dog {
String breed;
int age;
String color;
void barking() {
}
void hungry() {
}
void sleeping() {
}
}
A class can contain any of the following variable types.
Local variables − Variables defined inside methods, constructors or blocks are called
local variables. The variable will be declared and initialized within the method and
the variable will be destroyed when the method has completed.
Instance variables − Instance variables are variables within a class but outside any
method. These variables are initialized when the class is instantiated. Instance
variables can be accessed from inside any method, constructor or blocks of that
particular class.
Java Modifiers are used to define access to various Java classes and objects, Java functions,
and Java constructors. They are also used to change the meaning of any keyword in Java.
Default
Private
Protected
Public
The default Java Modifier is used to define access when no other modifier is specified for the
class or function, with this modifier they are accessible only within the same package.
The keyword private Java Modifier is used to define access to a Java datatype or method,
with this it is only accessible in the same class, i.e. any other class of the same package won’t
be able to access it. The keyword used is ‘private’ classes cannot be defined with this access
type.
With this keyword, the Java methods or Java datatypes can be accessed within the same
package or subclass of a different package. The keyword used is ‘protected’.
In public modifier in java, there is no restriction, i.e. Java datatypes or methods can be
accessed from anywhere in the program. It has the widest scope amongst all the modifiers. It
uses the keyword ‘public’.
1.22 Arguments
The java command-line argument is an argument i.e. passed at the time of running the java
program.
The arguments passed from the console can be received in the java program and it can be
used as an input.
So, it provides a convenient way to check the behavior of the program for the different
values. You can pass N (1,2,3 and so on) numbers of arguments from the command prompt.
Program:
class sam{
"+args[0]);
}
1.22 Constructors
Constructors are used to initialize the object’s state. Like methods, a constructor also contains
collection of statements(i.e. instructions) that are executed at time of Object creation.
Each time an object is created using new() keyword at least one constructor (it could be
default constructor) is invoked to assign initial values to the data members of the same class.
Constructor is invoked at the time of object or instance creation. For Example:
class Geek
{
.......
// A Constructor
new Geek() {}
.......
}
// We can create an object of above class
// using below statement. This statement
// calls above constructor.
Geek obj = new Geek();
Rules for writing Constructor
Constructor(s) of a class must has same name as the class name in which it resides.
A constructor in Java can not be abstract, final, static and Synchronized.
Access modifiers can be used in constructor declaration to control its access i.e which other
class can call the constructor.
1.23 Package and imports
Package are used in Java, in-order to avoid name conflicts and to control access of class,
interface and enumeration etc. A package can be defined as a group of similar types of
classes, interface, enumeration or sub-package. Using package it becomes easier to locate the
related classes and it also provides a good structure for projects with hundreds of classes and
other files.
Built-in Package: Existing Java package for example java.lang, java.util etc.
User-defined-package: Java package created by user to categorize their project's classes and
interface.
Creating a package
Creating a package in java is quite easy. Simply include a package command followed by
name of the package as the first statement in java source file.
1.24 static class
Java allows us to define a class within another class. Such a class is called a nested
class. The class which enclosed nested class is known as Outer class. In java, we can’t
make Top level class static. Only nested classes can be static.
Following are major differences between static nested class and non-static nested
class. Non-static nested class is also called Inner Class.
Nested static class doesn’t need reference of Outer class, but Non-static nested class
or Inner class requires Outer class reference.
Inner class(or non-static nested class) can access both static and non-static members
of Outer class. A static class cannot access non-static members of the Outer class. It
can access only static members of Outer class.
An instance of Inner class cannot be created without an instance of outer class and an
Inner class can reference data and methods defined in Outer class in which it nests, so
we don’t need to pass reference of an object to the constructor of the Inner class. For
this reason Inner classes can make program simple and concise.
You can overload a method in the same way as a constructor. That is, multiple
methods can exist, each with the same name. Remember, though, that they can't have
the same number of arguments or the same type of arguments! Overloading isn't
cloning.
Program:
public double setRate(double c) {
conversionRate = 352.222;
return conversionRate;
}
public double setRate(double c, double m)
{ conversionRate = 352.22;
modifier = .0035;
double newRate = conversionRate * modifier;
return newRate;
}
1.26 Returning objects
When we pass a primitive type to a method, it is passed by value. But when we pass
an object to a method, the situation changes dramatically, because objects are passed
by what is effectively call-by-reference. Java does this interesting thing that’s sort of a
hybrid between pass-by-value and pass-by-reference. Basically, a parameter cannot be
changed by the function, but the function can ask the parameter to change itself via
calling some method within it.
While creating a variable of a class type, we only create a reference to an object.
Thus, when we pass this reference to a method, the parameter that receives it will
refer to the same object as that referred to by the argument.
53 BCS 31/BCA 31 – JAVA PROGRAMMING
E-NOTES / B.SC CS /BCA
This effectively means that objects act as if they are passed to methods by use of call-
by-reference.
Changes to the object inside the method do reflect in the object used as an argument.
1.27 to string()
The toString() method returns the string representation of the object.
If you print any object, java compiler internally invokes the toString() method on the
object. So overriding the toString() method, returns the desired output, it can be the
state of an object etc. depends on your implementation.
Advantage:
By overriding the toString() method of the Object class, we can return values of the
object, so we don't need to write much code.
Program:
class Student{
int rollno;
String name;
String city;
Student(int rollno, String name, String city)
{ this.rollno=rollno;
this.name=name;
this.city=city;
}
public static void main(String args[]){
Student s1=new Student(101,"Raj","lucknow");
Student s2=new Student(102,"Vijay","ghaziabad");
System.out.println(s1);//compiler writes here s1.toString()
System.out.println(s2);//compiler writes here s2.toString()
}
}
Output:
Student@1fee6fc
Student@1eed786
1.29 this reference
There can be a lot of usage of java this keyword. In java, this is a reference
variable that refers to the current object.
Usage of java this keyword
Here is given the 6 usage of java this keyword.
this can be used to refer current class instance variable.
this can be used to invoke current class method (implicitly)
this() can be used to invoke current class constructor.
this can be passed as an argument in the method call.
this can be passed as argument in the constructor call.
this can be used to return the current class instance from the method.
Suggestion: If you are beginner to java, lookup only three usage of this keyword.
name=name;
fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+fee);}
}
class TestThis1{
public static void main(String args[])
{ Student s1=new
Student(111,"ankit",5000f); Student s2=new
Student(112,"sumit",6000f); s1.display();
s2.display();
}}
Output:
0 null 0.0
0 null 0.0
1.30 Eumeration
It can be used for days of the week (SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY and SATURDAY) , directions (NORTH, SOUTH, EAST and
WEST) etc. The java enum constants are static and final implicitly. It is available from JDK
1.5.
Java Enums can be thought of as classes that have fixed set of constants.
enum may implement many interfaces but cannot extend any class because it
internally extends Enum clas
Program:
class EnumExample1{
public enum Season { WINTER, SPRING, SUMMER, FALL }
}}
Output:
WINTER
SPRING
SUMMER
FALL
1.31 Garbage Collection
In java, garbage means unreferenced objects.
Garbage Collection is process of reclaiming the runtime unused memory
automatically. In other words, it is a way to destroy the unused objects.
To do so, we were using free() function in C language and delete() in C++. But, in
java it is performed automatically. So, java provides better memory management.
Advantage of Garbage Collection
It makes java memory efficient because garbage collector removes the unreferenced
objects from heap memory.
It is automatically done by the garbage collector(a part of JVM) so we don't need to
make extra efforts.
UNIT I
QUESTION BANK
PART – A
(2 marks)
PART – C
(10 marks)
UNIT II
2.1 Arrays
Code Optimization: It makes the code optimized, we can retrieve or sort the data
easily.
Random access: We can get any data located at any index position.
Size Limit: We can store only fixed size of elements in the array. It doesn't grow its
size at runtime. To solve this problem, collection framework is used in java.
Syntax
dataType[] arr; (or)
dataType []arr; (or)
dataType arr[];
arrayRefVar=new datatype[size];
Example
class Testarray{
public static void main(String args[]){
int a[]=new int[5];//declaration and instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//printing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}}
Output:
10
20
70
40
50
Declaration, Instantiation and Initialization of Java Array
int a[]={33,3,4,5};//declaration, instantiation and initialization
Example to print this array.
class Testarray1{
public static void main(String args[]){
int a[]={33,3,4,5};//declaration, instantiation and initialization
//printing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}}
Output:
33
3
4
Passing Array to method
We can pass the java array to method so that we can reuse the same logic on any
array.
Example
class Testarray2{
static void min(int arr[]){
int min=arr[0];
for(int i=1;i<arr.length;i++)
if(min>arr[i])
min=arr[i];
System.out.println(min);
}
public static void main(String args[]){
int a[]={33,3,4,5};
min(a);//passing array to method
}}
Output:
3
Multidimensional array
Data is stored in row and column based index (also known as matrix form).
Syntax
Example
Example
arr[0][0]=1;
arr[0][1]=2;
arr[0][2]=3;
arr[1][0]=4;
arr[1][1]=5;
arr[1][2]=6;
arr[2][0]=7;
arr[2][1]=8;
arr[2][2]=9;
Example Program
class Testarray3{
public static void main(String args[]){
//declaring and initializing 2D array
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
//printing 2D array
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}}
Output:
123
245
445
Copying a array
Syntax
Output: caffeine
Multidimensional Arrays
It's also possible to create an array of arrays known as multidimensional array. For
example,
Here, a is a two-dimensional (2d) array. The array can hold maximum of 12 elements
of type int.
Remember, Java uses zero-based indexing, that is, indexing of arrays in Java starts
with 0 and not 1.
Example
{1, 2, 3},
{4, 5, 6, 9},
{7},
};
As mentioned, each component of array a is an array in itself, and length of each rows is also
different.
Let's write a program to prove it.
classMultidimensionalArray{ public
[] a ={
{1,2,3},
{4,5,6,9},
{7},
};
Length of row 1: 3
Length of row 2: 4
Length of row 3: 1
Since each component of a multidimensional array is also an array (a[0], a[1] and a[2]are also
arrays), you can use length attribute to find the length of each rows.
You can initialize 3d array in similar way like a 2d array. Here's an example:
// test is a 3d array
int[][][] test = {
{2, 3, 4}
},
{1},
{2, 3}
};
Basically, 3d array is an array of 2d arrays.Similar like 2d arrays, rows of 3d arrays can vary
in length.
class ThreeArray {
// test is a 3d array
int[][][] test = {
{2, 3, 4}
},
{1},
{2, 3}
};
System.out.println(item);
-2
Inheritance in java is a mechanism in which one object acquires all the properties and
behaviors of parent object. It is an important part of OPPs(Object Oriented programming
system).
The idea behind inheritance in java is that you can create new classes that are built upon
existing classes. When you inherit from an existing class, you can reuse methods and fields of
parent class, and you can add new methods and fields also.
As displayed in the above figure, Programmer is the subclass and Employee is the superclass.
Relationship between two classes is Programmer IS-A Employee.It means that Programmer
is a type of Employee.
class Employee{
float salary=40000;
}
71 BCS 31/BCA 31 – JAVA PROGRAMMING
E-NOTES / B.SC CS /BCA
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
d.bark();
72 BCS 31/BCA 31 – JAVA PROGRAMMING
E-NOTES / B.SC CS /BCA
d.eat();
}}
Output:
barking...
eating...
Multilevel Inheritance Example
File: TestInheritance2.java
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class BabyDog extends Dog{
void weep(){System.out.println("weeping...");}
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}}
Output:
weeping...
barking...
eating...
Hierarchical Inheritance Example
File: TestInheritance3.java
73 BCS 31/BCA 31 – JAVA PROGRAMMING
E-NOTES / B.SC CS /BCA
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class Cat extends Animal{
void meow(){System.out.println("meowing...");}
}
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//C.T.Error
}}
Output:
meowing...
eating...
Why multiple inheritance is not supported in java?
To reduce the complexity and simplify the language, multiple inheritance is not supported in
java.
Consider a scenario where A, B and C are three classes. The C class inherits A and B classes.
If A and B classes have same method and you call it from child class object, there will be
ambiguity to call method of A or B class.
Since compile time errors are better than runtime errors, java renders compile time error if
you inherit 2 classes. So whether you have same method or different, there will be compile
time error now.
class A{
void msg(){System.out.println("Hello");}
}
class B{
void msg(){System.out.println("Welcome");}
}
class C extends A,B{//suppose if it were
Address.java
public class Address
{ String
city,state,country;
}
Emp.java
public class Emp {
int id;
String name;
Address address;
void display()
{ System.out.println(id+"
"+name);
System.out.println(address.city+" "+address.state+" "+address.country);
}
e.display();
e2.display();
}
}
76 BCS 31/BCA 31 – JAVA PROGRAMMING
E-NOTES / B.SC CS /BCA
Output:111 varun
gzb UP india
112 arun
gno UP india
2.3 Super keyword in java
The super keyword in java is a reference variable which is used to refer immediate
parent class object.
Whenever you create the instance of subclass, an instance of parent class is created
implicitly which is referred by super reference variable.
class Animal{
String color="white";
}
class Dog extends Animal{
String color="black";
void printColor(){
System.out.println(color);//prints color of Dog class
System.out.println(super.color);//prints color of Animal class
}
}
class TestSuper1{
public static void main(String args[]){
Dog d=new Dog();
d.printColor();
77 BCS 31/BCA 31 – JAVA PROGRAMMING
E-NOTES / B.SC CS /BCA
}}
Output:
black
white
In the above example, Animal and Dog both classes have a common property color. If we
print color property, it will print the color of current class by default. To access the parent
property, we need to use super keyword.
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void eat(){System.out.println("eating bread...");}
void bark(){System.out.println("barking...");}
void work(){
super.eat();
bark();
}
}
class TestSuper2{
public static void main(String args[]){
Dog d=new Dog();
d.work();
}}
Output:
eating...
barking...
78 BCS 31/BCA 31 – JAVA PROGRAMMING
E-NOTES / B.SC CS /BCA
In the above example Animal and Dog both classes have eat() method if we call eat()
method from Dog class, it will call the eat() method of Dog class by default because
priority is given to local.
animal is created
dog is created
If a class inherits a method from its superclass, then there is a chance to override
the method provided that it is not marked final.
The benefit of overriding is: ability to define a behavior that's specific to the
subclass type, which means a subclass can implement a parent class method based
on its requirement.
Example
Let us look at an example.
Live Demo
class Animal {
Output
In the above example, you can see that even though b is a type of Animal it runs the move
method in the Dog class. The reason for this is: In compile time, the check is made on the
reference type.
The return type should be the same or a subtype of the return type declared in the
original overridden method in the superclass.
The access level cannot be more restrictive than the overridden method's access level.
Instance methods can be overridden only if they are inherited by the subclass.
A subclass within the same package as the instance's superclass can override any
superclass method that is not declared private or final.
A subclass in a different package can only override the non-final methods declared
public or protected.
An overriding method can throw any uncheck exceptions, regardless of whether the
overridden method throws exceptions or not
Inheritance can be defined as the process where one class acquires the properties
(methods and fields) of another. With the use of inheritance the information is made
manageable in a hierarchical order.
The class which inherits the properties of other is known as subclass (derived class,
child class) and the class whose properties are inherited is known as superclass (base
class, parent class).
extends Keyword
extends is the keyword used to inherit the properties of a class. Following is the syntax of
extends keyword.
Syntax
class Super {
.....
.....
}
class Sub extends Super {
.....
.....
}
Following is an example demonstrating Java inheritance. In this example, you can observe
two classes namely Calculation and My_Calculation.
Using extends keyword, the My_Calculation inherits the methods addition() and
Subtraction() of Calculation class.
2.6 Polymorphism
Polymorphism is the ability of an object to take on many forms. The most common use of
polymorphism in OOP occurs when a parent class reference is used to refer to a child class
object.
Any Java object that can pass more than one IS-A test is considered to be polymorphic. In
Java, all Java objects are polymorphic since any object will pass the IS-A test for their own
type and for the class Object.
It is important to know that the only possible way to access an object is through a reference
variable. A reference variable can be of only one type. Once declared, the type of a reference
variable cannot be changed.
The reference variable can be reassigned to other objects provided that it is not declared final.
The type of the reference variable would determine the methods that it can invoke on the
object.
A reference variable can refer to any object of its declared type or any subtype of its declared
type. A reference variable can be declared as a class or interface type.
Example
Let us look at an example.
public interface Vegetarian{}
public class Animal{}
public class Deer extends Animal implements Vegetarian{}
Now, the Deer class is considered to be polymorphic since this has multiple inheritance.
Following are true for the above examples −
A Deer IS-A Animal
A Deer IS-A Vegetarian
A Deer IS-A Deer
A Deer IS-A Object
When we apply the reference variable facts to a Deer object reference, the following
declarations are legal −
Example
Deer d = new Deer();
Animal a = d;
Vegetarian v = d;
Object o = d;
All the reference variables d, a, v, o refer to the same Deer object in the heap.
Virtual Methods
In this section, I will show you how the behavior of overridden methods in Java allows you to
take advantage of polymorphism when designing your classes.
We already have discussed method overriding, where a child class can override a method in
its parent. An overridden method is essentially hidden in the parent class, and is not invoked
unless the child class uses the super keyword within the overriding method.
A class that is declared with abstract keyword, is known as abstract class in java. It can have
abstract and non-abstract methods (method with body).
Before learning java abstract class, let's understand the abstraction in java first.
Abstraction in Java
Another way, it shows only important things to the user and hides the internal details
for example sending sms, you just type the text and send the message. You don't
know the internal processing about the message delivery.
Abstraction lets you focus on what the object does instead of how it does it.
A class that is declared as abstract is known as abstract class. It needs to be extended and its
method implemented. It cannot be instantiated.
abstract method
A method that is declared as abstract and does not have implementation is known as
abstract method.
Example abstract method
In this example, Bike the abstract class that contains only one abstract method run. It
implementation is provided by the Honda class.
Syntax:
interface <interface_name>{
interface Printable{
void print();
}
interface Showable{
void show();
}
class A7 implements Printable,Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}
interface Printable{
void print();
}
interface Showable extends Printable{
void show();
}
class TestInterface4 implements Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}
public static void main(String args[]){
TestInterface4 obj = new TestInterface4();
obj.print();
obj.show();
}
}
Hello
Welcome
Default Method in Interface
Since Java 8, we can have method body in interface. But we need to make it default method.
example:
File: TestInterfaceDefault.java
interface Drawable{
void draw();
default void msg(){System.out.println("default method");}
}
class Rectangle implements Drawable{
public void draw(){System.out.println("drawing rectangle");}
}
87 BCS 31/BCA 31 – JAVA PROGRAMMING
E-NOTES / B.SC CS /BCA
class TestInterfaceDefault{
public static void main(String args[]){
Drawable d=new Rectangle();
d.draw();
d.msg();
}}
drawing rectangle
default method
Static Method in Interface
Since Java 8, we can have static method in interface. Let's see an example:
File: TestInterfaceStatic.java
interface Drawable{
void draw();
static int cube(int x){return x*x*x;}
}
class Rectangle implements Drawable{
public void draw(){System.out.println("drawing rectangle");}
}
class TestInterfaceStatic{
public static void main(String args[]){
Drawable d=new Rectangle();
d.draw();
System.out.println(Drawable.cube(3));
}}
Output:
drawing rectangle
2.11 Java Package
A java package is a group of similar types of classes, interfaces and sub-packages.
Package in java can be categorized in two form, built-in package and user-defined
package.
There are many built-in packages such as java, lang, awt, javax, swing, net, io, util,
sql etc.
//save as Simple.java
package mypack;
public class Simple{
1. javac -d . Simple.java
The -d switch specifies the destination where to put the generated class file. You can use any
directory name like /home (in case of Linux), d:/abc (in case of windows) etc. If you want to
keep the package within the same directory, you can use . (dot).
1. import package.*;
2. import package.classname;
3. fully qualified name.
1) Using packagename.*
If you use package.* then all the classes and interfaces of this package will be accessible but
not subpackages.
The import keyword is used to make the classes and interface of another package accessible
to the current package.
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:Hello
2) Using packagename.classname
If you import package.classname then only declared class of this package will be accessible.
}
//save by B.java
package mypack;
import pack.A;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:Hello
3) Using fully qualified name
If you use fully qualified name then only declared class of this package will be accessible.
Now there is no need to import. But you need to use fully qualified name every time when
you are accessing the class or interface.
It is generally used when two packages have same class name e.g. java.util and java.sql
packages contain Date class.
}
}
Output:Hello
Subpackage in java
Package inside the package is called the subpackage. It should be created to categorize the
package further.
Example of Subpackage
package com.javatpoint.core;
class Simple{
public static void main(String args[])
{ System.out.println("Hello
subpackage");
}
}
Creating a Package
While creating a package, you should choose a name for the package and include
a package statement along with that name at the top of every source file that contains the
classes, interfaces, enumerations, and annotation types that you want to include in the
package.
To compile the Java programs with package statements, you have to use -d option as shown
below.
Example
package animals;
interfaceAnimal{ p
ublicvoid eat();
publicvoid travel();
Now, let us implement the above interface in the same package animals −
package animals;
{ System.out.println("Mammal
eats");
{ System.out.println("Mammal travels");
return 0;
m.eat();
m.travel();
$ javac -d . Animal.java
$ javac -d . MammalInt.java
Now a package/folder with the name animals will be created in the current directory and
these class files will be placed in it as shown below.
You can execute the class file within the package and get the result as shown below.
Mammal eats
Mammal travels
There are two types of modifiers in java: access modifiers and non-access modifiers.
The access modifiers in java specifies accessibility (scope) of a data member, method,
constructor or class.
1. private
2. default
3. protected
4. public
There are many non-access modifiers such as static, abstract, synchronized, native,
volatile, transient etc. Here, we will learn access modifiers. 1) private access modifier
The private access modifier is accessible only within class.
Simple example of private access modifier
In this example, we have created two classes A and Simple. A class contains private data
member and private method. We are accessing these private members from outside the
class, so there is compile time error.
class A{
private int data=40;
private void msg(){System.out.println("Hello java");}
}
A obj=new A();
System.out.println(obj.data);//Compile Time Error
obj.msg();//Compile Time Error
}
}
Role of Private Constructor
If you make any class constructor private, you cannot create the instance of that class
from outside the class. For example:
class A{
private A(){}//private constructor
void msg(){System.out.println("Hello java");}
}
public class Simple{
public static void main(String args[]){
A obj=new A();//Compile Time Error
}
}
class A{
void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();//Compile Time Error
obj.msg();//Compile Time Error
}
}
In the above example, the scope of class A and its method msg() is default so it cannot be
accessed from outside the package.
//save by A.java
package pack;
public class A{
protected void msg(){System.out.println("Hello");}
98 BCS 31/BCA 31 – JAVA PROGRAMMING
E-NOTES / B.SC CS /BCA
}
//save by B.java
package mypack;
import pack.*;
class B extends A{
public static void main(String args[]){
B obj = new B();
obj.msg();
}
}
Output:Hello
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
1.
Output:Hello
UNIT II
QUESTION BANK
PART – A
(2 marks)
PART – C
(10 marks)
1. Explain types of inheritance with example.
2. What is super class ? Give the limitation in its usage. Develop a program to
show its execution.
3. What is method overloading? Explain by giving a suitable example.
10 BCS 31/BCA 31 – JAVA PROGRAMMING
1
E-NOTES / B.SC CS /BCA
UNIT III
The Java platform provides the String class to create and manipulate strings.
Creating Strings
The most direct way to create a string is to write –
Whenever it encounters a string literal in your code, the compiler creates a String object with
its value in this case, "Hello world!'.
As with any other object, you can create String objects by using the new keyword and a
constructor. The String class has 11 constructors that allow you to provide the initial value
of the string using different sources, such as an array of characters.
Program
public class StringDemo {
'.' };
System.out.println( helloString );
Output
hello
Note − The String class is immutable, so that once it is created a String object cannot be
changed. If there is a necessity to make a lot of modifications to Strings of characters, then
String Length
Methods used to obtain information about an object are known as accessor methods. One
accessor method that you can use with strings is the length() method, which returns the
number of characters contained in the string object.
Program
public class StringDemo {
string1.concat(string2);
This returns a new string that is string1 with string2 added to it at the end. You can also use
the concat() method with string literals, as in −
which results in −
"Hello, world!"
Program:
Live Demo
public class StringDemo {
This method returns a String with the value of the String passed in to the method appended to
the end of the String used to invoke the method—for example,
String x = "book";
System.out.println( x.concat(" author") ); // output is "book author"
String x = "library";
System.out.println( x + " card"); // output is "library card"
String x = "United";
x += " States"
System.out.println( x ); // output is "United States"
10 BCS 31/BCA 31 – JAVA PROGRAMMING
4
E-NOTES / B.SC CS /BCA
This method returns a boolean value (true or false) depending on whether the value of the
String in the argument is the same as the value of the String used to invoke the method. This
method will return true even when characters in the String objects being compared have
differing cases—for example,
String x = "Exit";
System.out.println( x.equalsIgnoreCase("EXIT")); // is
"true" System.out.println( x.equalsIgnoreCase("tixe")); // is
"false"
This method returns the length of the String used to invoke the method—for example,
String x = "01234567";
System.out.println( x.length() ); // returns
This method returns a String whose value is that of the String used to invoke the method,
updated so that any occurrence of the char in the first argument is replaced by the char in the
second argument—for example,
String x = "oxoxoxox";
System.out.println( x.replace('x', 'X') ); // output is "oXoXoXoX"
public String substring(int begin)/ public String substring(int begin, int end)
The substring() method is used to return a part (or substring) of the String used to invoke the
method. The first argument represents the starting location (zero-based) of the substring. If
the call has only one argument, the substring returned will include the characters to the end of
the original String. If the call has two arguments, the substring returned will end with the
character located in the nth position of the original String where n is the second argument.
Unfortunately, the ending argument is not zero-based, so if the second argument is 7, the last
character in the returned String will be in the original String's 7 position, which is index 6.
Let's look at some examples:
String x = "0123456789"; // the value of each char is the same as its index!
System.out.println( x.substring(5) ); // output is "56789"
System.out.println( x.substring(5, 8)); // output is "567"
This method returns a String whose value is the String used to invoke the method, but with
any uppercase characters converted to lowercase—for example,
String x = "A New Java Book";
System.out.println( x.toLowerCase() ); // output is "a new java book"
This method returns a String whose value is the String used to invoke the method, but with
any lowercase characters converted touppercase—for example,
String x = "A New Java Book";
System.out.println( x.toUpperCase() ); // output is"A NEW JAVA BOOK"
This method returns a String whose value is the String used to invoke the method, but with
any leading or trailing blank spaces removed—for example,
String x = " hi ";
System.out.println( x + "x" ); // result is" hi x"
System.out.println(x.trim() + "x"); // result is "hix"
Program
public class StringMethodsDemo {
public static void main(String[] args) {
String targetString = "Java is fun to learn";
String s1= "JAVA";
String s2= "Java";
String s3 = " Hello Java ";
System.out.println("Char at index 2(third position): " +
targetString.charAt(2));
System.out.println("After Concat: "+ targetString.concat("-Enjoy-"));
System.out.println("Checking equals ignoring case: "
+s2.equalsIgnoreCase(s1));
System.out.println("Checking equals with case: " +s2.equals(s1));
System.out.println("Checking Length: "+ targetString.length());
System.out.println("Replace function: "+ targetString.replace("fun", "easy"));
System.out.println("SubString of targetString: "+ targetString.substring(8));
System.out.println("SubString of targetString: "+ targetString.substring(8,
12));
System.out.println("Converting to lower case: "+ targetString.toLowerCase());
System.out.println("Converting to upper case: "+ targetString.toUpperCase());
System.out.println("Triming string: " + s3.trim());
System.out.println("searching s1 in targetString: " + targetString.contains(s1));
System.out.println("searching s2 in targetString: " + targetString.contains(s2));
char [] charArray = s2.toCharArray();
System.out.println("Size of char array: " + charArray.length);
System.out.println("Printing last element of array: " + charArray[3]);
}
}
Output:
Note
String manipulation is one of the most widely performed activities in java programming
Java library is having various built-in methods like substring, concat, replace, converting to
uppercase or lowercase etc.,
3.4 STRING BUFFERED CLASS
Java StringBuffer class is used to create mutable (modifiable) string. The StringBuffer class
in java is same as String class except it is mutable i.e. it can be changed.
Mutable string
A string that can be modified or changed is known as mutable string. StringBuffer and
StringBuilder classes are used for creating mutable string.
StringBuffer append() method
The append() method concatenates the given argument with this string.
Program
10 BCS 31/BCA 31 – JAVA PROGRAMMING
7
E-NOTES / B.SC CS /BCA
class StringBufferExample{
public static void main(String args[])
{ StringBuffer sb=new StringBuffer("Hello ");
sb.append("Java");//now original string is changed
System.out.println(sb);//prints Hello Java
}}
StringBuffer insert() method
The insert() method inserts the given string with this string at the given position.
Program:
class StringBufferExample2{
public static void main(String args[])
{ StringBuffer sb=new StringBuffer("Hello ");
sb.insert(1,"Java");//now original string is changed
System.out.println(sb);//prints HJavaello
}}
StringBuffer replace() method
The replace() method replaces the given string from the specified beginIndex and endIndex.
Program:
class StringBufferExample3{
public static void main(String args[])
{ StringBuffer sb=new
StringBuffer("Hello"); sb.replace(1,3,"Java");
System.out.println(sb);//prints HJavalo
}}
StringBuffer delete() method
The delete() method of StringBuffer class deletes the string from the specified beginIndex to
endIndex.
Program:
class StringBufferExample4{
public static void main(String args[])
{ StringBuffer sb=new
StringBuffer("Hello"); sb.delete(1,3);
System.out.println(sb);//prints Hlo
}
}
StringBuffer reverse() method
The reverse() method of StringBuilder class reverses the current string.
Program:
class StringBufferExample5{
public static void main(String args[])
{ StringBuffer sb=new
StringBuffer("Hello"); sb.reverse();
System.out.println(sb);//prints olleH
}
}
StringBuffer capacity() method
The capacity() method of StringBuffer class returns the current capacity of the buffer. The
10 BCS 31/BCA 31 – JAVA PROGRAMMING
8
E-NOTES / B.SC CS /BCA
default capacity of the buffer is 16. If the number of character increases from its current
capacity, it increases the capacity by (oldcapacity*2)+2. For example if your current capacity
is 16, it will be (16*2)+2=34.
Program:
class StringBufferExample6{
public static void main(String args[])
{ StringBuffer sb=new StringBuffer();
System.out.println(sb.capacity());//default 16
sb.append("Hello");
System.out.println(sb.capacity());//now 16
sb.append("java is my favourite language");
System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
}}
Java StringBuilder class is used to create mutable (modifiable) string. The Java StringBuilder
class is same as StringBuffer class except that it is non-synchronized. It is available since
JDK 1.5.
Constructor Description
If you want to represent any object as a string, toString() method comes into existence.
If you print any object, java compiler internally invokes the toString() method on the object.
So overriding the toString() method, returns the desired output, it can be the state of an object
etc. depends on your implementation.
By overriding the toString() method of the Object class, we can return values of the object, so
we don't need to write much code.
Program:
class Student{
int rollno;
String name;
String city;
{ this.rollno=rollno;
this.name=name;
this.city=city;
} }
Output:
Student@1fee6fc
Student@1eed786
The java.util.StringTokenizer class allows you to break a string into tokens. It is simple way
to break string.
It doesn't provide the facility to differentiate numbers, quoted strings, identifiers etc. like
StreamTokenizer class. We will discuss about the StreamTokenizer class in I/O chapter.
Constructor Description
Program:
import java.util.StringTokenizer;
public class Simple{
public static void main(String args[]){
StringTokenizer st = new StringTokenizer("my name is khan"," ");
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}}}
Output:
my
name
is
11 BCS 31/BCA 31 – JAVA PROGRAMMING
1
E-NOTES / B.SC CS /BCA
khan
The exception handling in java is one of the powerful mechanism to handle the runtime errors
so that normal flow of the application can be maintained.
Java try block is used to enclose the code that might throw an exception. It
must be used within the method. Java try block must be followed by either
catch or finally block.
Syntax
try{
//code that may throw exception
}catch(Exception_class_Name ref){}
Catch Block
Java catch block is used to handle the Exception. It must be used after the try
block only.You can use multiple catch block with a single try.
If you have to perform different tasks at the occurrence of different Exceptions, use java
multi catch block.
Program:
public class
TestMultipleCatchBlock{ public static
void main(String args[]){ try{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e){System.out.println("task1 is completed");}
catch(ArrayIndexOutOfBoundsException e){System.out.println("task 2 completed");}
catch(Exception e){System.out.println("common task completed");}
System.out.println("rest of the code...");
}}
The try block within a try block is known as nested try block in java.
Syntax:
try
{
statement 1;
statement 2;
try
{
statement 1;
statement 2;
}
catch(Exception e)
{
}
}
catch(Exception e)
{
}
Program:
class Excep6{
public static void main(String args[])
{ try{
try{
System.out.println("going to divide");
int b =39/0;
}catch(ArithmeticException e){System.out.println(e);}
try{
int a[]=new int[5];
a[5]=4;
}catch(ArrayIndexOutOfBoundsException e){System.out.println(e);}
System.out.println("other statement);
11 BCS 31/BCA 31 – JAVA PROGRAMMING
3
E-NOTES / B.SC CS /BCA
}catch(Exception e){System.out.println("handeled");}
System.out.println("normal flow..");
}
}
We can throw either checked or uncheked exception in java by throw keyword. The throw
keyword is mainly used to throw custom exception. We will see custom exceptions later.
Syntax
throw exception;
Program:
public class
TestThrow1{ static void
validate(int age)
{ if(age<18)
throw new ArithmeticException("not valid");
else
System.out.println("welcome to vote");
}
public static void main(String args[])
{ validate(13);
System.out.println("rest of the code...");
}
}
There are many differences between throw and throws keywords. A list of differences
between throw and throws are given below:
There are many differences between final, finally and finalize. A list of differences between
final, finally and finalize are given below:
If subclass (child class) has the same method as declared in the parent class, it is known as
method overriding in java.
In other words, If subclass provides the specific implementation of the method that has been
provided by one of its parent class, it is known as method overriding.
Program
class Vehicle{
void run(){System.out.println("Vehicle is running");}
}
class Bike extends Vehicle{
Output:
Vehicle is running
If you are creating your own Exception that is known as custom exception or user-defined
exception. Java custom exceptions are used to customize the exception according to user
need.
By the help of custom exception, you can have your own exception and
message. Program:
class TestCustomException1{
3.17 Multithreading
It doesn't block the user because threads are independent and you can perform
multiple operations at same time.
Threads are independent so it doesn't affect other threads if exception occur in a single
thread.
Multitasking
Process-based Multitasking(Multiprocessing)
Thread-based Multitasking(Multithreading)
Threads are independent, if there occurs exception in one thread, it doesn't affect other
threads. It shares a common memory area.
A thread can be in one of the five states. According to sun, there is only 4 states in thread life
cycle in javanew, runnable, non-runnable and terminated. There is no running state.
But for better understanding the threads, we are explaining it in the 5 states.
The life cycle of the thread in java is controlled by JVM. The java thread states are as
follows:
New
Runnable
Running
Non-Runnable (Blocked)
Terminated
New
The thread is in new state if you create an instance of Thread class but before the invocation
of start() method.
Runnable
The thread is in runnable state after invocation of start() method, but the thread scheduler has
not selected it to be the running thread.
Running
The thread is in running state if the thread scheduler has selected it.
Non-Runnable (Blocked)
This is the state when the thread is still alive, but is currently not eligible to run.
Terminated
public void start(): starts the execution of the thread.JVM calls the run() method on the
thread.
public void sleep(long miliseconds): Causes the currently executing thread to sleep
(temporarily cease execution) for the specified number of milliseconds.
public void join(long miliseconds): waits for a thread to die for the specified miliseconds.
public void yield(): causes the currently executing thread object to temporarily pause and
allow other threads to execute.
public void setDaemon(boolean b): marks the thread as daemon or user thread.
public static boolean interrupted(): tests if the current thread has been interrupted.
The users are not blocked because threads are independent, and we can perform
multiple operations at times
As such the threads are independent, the other threads won't get affected if one thread
meets an exception.
Each thread have a priority. Priorities are represented by a number between 1 and 10. In most
cases, thread schedular schedules the threads according to their priority (known as
preemptive scheduling). But it is not guaranteed because it depends on JVM specification that
which scheduling it chooses.
Synchronization in java is the capability to control the access of multiple threads to any
shared resource.
Java Synchronization is better option where we want to allow only one thread to access the
shared resource.
Use of synchronization
Types of Synchronization
There are two types of synchronization
Process Synchronization
Thread Synchronization
Thread Synchronization
Program:
class Table{
void printTable(int n){//method not synchronized
for(int i=1;i<=5;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){System.out.println(e);}
}
}
}
class MyThread1 extends Thread{
Table t;
MyThread1(Table t){
this.t=t;
}
public void run()
{ t.printTable(5);
}
}
class MyThread2 extends
Thread{ Table t;
12 BCS 31/BCA 31 – JAVA PROGRAMMING
2
E-NOTES / B.SC CS /BCA
MyThread2(Table t){
this.t=t;
}
public void run()
{ t.printTable(100);
}
}
class TestSynchronization1{
public static void main(String args[])
{ Table obj = new Table();//only one
object MyThread1 t1=new
MyThread1(obj); MyThread2 t2=new
MyThread2(obj); t1.start();
t2.start();
}
}
Output
5
100
10
200
15
300
20
400
25
500
wait()
notify()
notifyAll()
wait() method
Causes current thread to release the lock and wait until either another thread invokes the
notify() method or the notifyAll() method for this object, or a specified amount of time has
elapsed.
12 BCS 31/BCA 31 – JAVA PROGRAMMING
3
E-NOTES / B.SC CS /BCA
The current thread must own this object's monitor, so it must be called from the synchronized
method only otherwise it will throw exception.
Method Description
notify() method
Wakes up a single thread that is waiting on this object's monitor. If any threads are waiting on
this object, one of them is chosen to be awakened. The choice is arbitrary and occurs at the
discretion of the implementation.
Syntax:
notifyAll() method
Syntax:
Core Java provides complete control over multithreaded program. You can develop a
multithreaded program which can be suspended, resumed, or stopped completely based on
your requirements. There are various static methods which you can use on thread objects to
control their behavior. Following table lists down those methods −
Sr.No. Method & Description
PART – A
(2 marks)
1. Define string.
2. Define an buffer
class.
3. Give the meaning for synchronization in java.(Nov 2012)
4. Define thread? Give example.(April 2011)
5. What is the use of thread class?(April 2013)
6. What are the events to be implemented to handle mouse events?(April 2013)
7. Define event sources.
8. What is meant by event listeners?
9. What is meant by event classes?
10. What is GUI?
PART – B
(5 marks)
PART – C
(10 marks)
1. APPLET FUNDAMENTALS
Applet is a special type of program that is embedded in the webpage to generate the
dynamic content. It runs inside the browser and works at client side.
Advantage of Applet
3. Secured
4. It can be executed by browsers running under many plateforms, including Linux, Windows,
Mac Os etc.
Drawback of Applet
Hierarchy of Applet
As displayed in the above diagram, Applet class extends Panel. Panel class extends Container which is the subclass
of Component.
9. Request information about the author, version, and copyright of the applet
10. Request a description of the parameters the applet recognizes
11. Initialize the applet
12. Destroy the applet
13. Start the applet's execution
14. Stop the applet's execution
The Applet class provides default implementations of each of these methods. Those
implementations may be overridden as necessary.
The "Hello, World" applet is complete as it stands. The only method overridden is the paint
method.
Lifecycle of Java Applet
6. Applet is initialized.
7. Applet is started.
8. Applet is painted.
9. Applet is stopped.
10. Applet is destroyed.
Lifecycle methods for Applet:
The java.applet.Applet class 4 life cycle methods and java.awt.Component class provides 1 life cycle
methods for an applet.
java.applet.Applet class
For creating any applet java.applet.Applet class must be inherited. It provides 4 life cycle methods of
applet.
1. public void init(): is used to initialized the Applet. It is invoked only once.
2. public void start(): is invoked after the init() method or browser is maximized. It is used to start the
Applet.
3. public void stop(): is used to stop the Applet. It is invoked when Applet is stop or browser is
minimized.
4. public void destroy(): is used to destroy the Applet. It is invoked only once.
5. paint − Invoked immediately after the start() method, and also any time the applet needs to repaint itself
in the browser. The paint() method is actually inherited from the java.awt.
An applet is a Java program that runs in a Web browser. An applet can be a fully functional
Java application because it has the entire Java API at its disposal.
There are some important differences between an applet and a standalone Java application,
including the following −
1. An applet is a Java class that extends the java.applet.Applet class.
2. A main() method is not invoked on an applet, and an applet class will not define
main().
3. Applets are designed to be embedded within an HTML page.
4. When a user views an HTML page that contains an applet, the code for the
applet is downloaded to the user's machine.
5. A JVM is required to view an applet. The JVM can be either a plug-in of the
Web browser or a separate runtime environment.
12 BCS 31/BCA 31 – JAVA PROGRAMMING
7
E-NOTES / B.SC CS /BCA
The JVM on the user's machine creates an instance of the applet class and invokes
various methods during the applet's lifetime.
Applets have strict security rules that are enforced by the Web browser. The security
of an applet is often referred to as sandbox security, comparing the applet to a child
playing in a sandbox with various rules that must be followed.
Other classes that the applet needs can be downloaded in a single Java Archive (JAR)
file.
}
These import statements bring the classes into the scope of our applet class −
java.applet.Applet
java.awt.Graphics
Without those import statements, the Java compiler would not recognize the classes Applet
and Graphics, which the applet class refers to.
1. Execution of applets is easy in a Web browser and does not require any
installation or deployment procedure in realtime programming (where as servlets
require).
2. Writing and displaying (just opening in a browser) graphics and animations is easier than
applications.
3. In GUI development, constructor, size of frame, window closing code etc. are not
required (but are required in applications).
1. By html file.
2. By appletViewer tool (for testing purpose).
1. //First.java
2. import java.applet.Applet;
3. import java.awt.Graphics;
4. public class First extends Applet{
5.
6. public void paint(Graphics g){
7. g.drawString("welcome",150,150);
8. }
9.
10. }
Note: class must be public because its object is created by Java Plugin software that resides on
the browser.
myapplet.html
1. <html>
2. <body>
3. <applet code="First.class" width="300" height="300">
4. </applet>
5. </body>
6. </html>
1. //First.java
2. import java.applet.Applet;
3. import java.awt.Graphics;
4. public class First extends Applet{
5.
6. public void paint(Graphics g){
7. g.drawString("welcome to applet",150,150);
8. }
9.
10. }
11. /*
12. <applet code="First.class" width="300" height="300">
13. </applet>
14. */
c:\>javac First.java
c:\>appletviewer First.java
Parameter in Applet
We can get any information from the HTML file as a parameter. For this purpose, Applet class
provides a method named getParameter(). Syntax:
1. public String getParameter(String parameterName)
Example of using parameter in Applet:
1. import java.applet.Applet;
2. import java.awt.Graphics;
3.
4. public class UseParam extends Applet{
5.
6. public void paint(Graphics g){
7. String str=getParameter("msg");
8. g.drawString(str,50, 50);
9. }
10.
11. }
myapplet.html
1. <html>
2. <body>
3. <applet code="UseParam.class" width="300" height="300">
4. <param name="msg" value="Welcome to applet">
5. </applet>
6. </body>
7. </html>
Graphics in Applet
public abstract void fillOval(int x, int y, int width, int height): is used to fill oval with
the default color and specified width and height.
public abstract void drawLine(int x1, int y1, int x2, int y2): is used to draw line
between the points(x1, y1) and (x2, y2).
public abstract boolean drawImage(Image img, int x, int y, ImageObserver observer):
is used draw the specified image.
public abstract void drawArc(int x, int y, int width, int height, int startAngle, int
arcAngle): is used draw a circular or elliptical arc.
public abstract void fillArc(int x, int y, int width, int height, int startAngle, int
arcAngle): is used to fill a circular or elliptical arc.
public abstract void setColor(Color c): is used to set the graphics current color to the
specified color.
public abstract void setFont(Font font): is used to set the graphics current font to the
specified font.
Example
import java.applet.Applet;
import java.awt.*;
public class GraphicsDemo extends Applet{
4.6 GUI
A program's graphical user interface presents an easy-to-use visual display to the user. It is
made up of graphical components (e.g., buttons, labels, windows) through which the user can
interact with the page or application. To make graphical user interfaces in Java, use either
Swing (older applications) or JavaFX.
Examples - Display text in different fonts
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Main extends JPanel
{ String[] type =
{ "Serif","SansSerif"};
int[] styles = { Font.PLAIN, Font.ITALIC, Font.BOLD, Font.ITALIC + Font.BOLD };
String[] stylenames = { "Plain", "Italic", "Bold", "Bold & Italic" };
public void paint(Graphics g) {
for (int f = 0; f < type.length; f++) {
for (int s = 0; s < styles.length; s++) {
Font font = new Font(type[f], styles[s], 18);
g.setFont(font);
String name = type[f] + " " + stylenames[s];
g.drawString(name, 20, (f * 4 + s + 1) * 20);
}
}
}
public static void main(String[] a)
{ JFrame f = new JFrame();
f.addWindowListener(new WindowAdapter()
{ public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
f.setContentPane(new Main());
f.setSize(400,400);
f.setVisible(true);
}
}
1. java.awt.BorderLayout
2. java.awt.FlowLayout
3. java.awt.GridLayout
4. java.awt.CardLayout
5. java.awt.GridBagLayout
6. javax.swing.BoxLayout
7. javax.swing.GroupLayout
8. javax.swing.ScrollPaneLayout
javax.swing.SpringLayout etc.
12 BCS 31/BCA 31 – JAVA PROGRAMMING
9
E-NOTES / B.SC CS /BCA
4.5 APPLICATION
Applications Vs. Applets
You have seen two main differences between applications and applets. Let us summarize
them.
main()
method Present Not present
1. Execution of applets is easy in a Web browser and does not require any installation or
deployment procedure in realtime programming (where as servlets require).
2. Writing and displaying (just opening in a browser) graphics and animations is easier than
applications.
3. In GUI development, constructor, size of frame, window closing code etc. are not
required (but are required in applications).
Java AWT components are platform-dependent i.e. components are displayed according to
the view of operating system. AWT is heavyweight i.e. its components are using the
resources of OS.
The java.awt package provides classes for AWT api such as TextField, Label, TextArea,
RadioButton, CheckBox, Choice, List etc.
Container
The Container is a component in AWT that can contain another components like buttons,
textfields, labels etc. The classes that extends Container class are known as container such as
Frame, Dialog and Panel.
Window
The window is the container that have no borders and menu bars. You must use frame, dialog
or another window for creating a window.
Panel
The Panel is the container that doesn't contain title bar and menu bars. It can have other
components like button, textfield etc.
Frame
The Frame is the container that contain title bar and can have menu bars. It can have other
components like button, textfield etc.
Method Description
public void setSize(int width,int height) sets the size (width and height) of the component.
public void setVisible(boolean status) changes the visibility of the component, by default
false.
To create simple awt example, you need a frame. There are two ways to create a frame in
AWT.
EventObject class
It is the root class from which all event state objects shall be derived. All Events are
constructed with a reference to the object, the source, that is logically deemed to be the
object upon which the Event in question initially occurred upon.This class is defined in
java.util package.
Class declaration
Following is the declaration for java.util.EventObject class:
extends Object
implements Serializable
Field
Following are the fields for java.util.EventObject class:
protected Object source -- The object on which the Event initially occurred.
Class constructors
1 EventObject(Object source)
Class methods
S.N. Method & Description
1
Object getSource()
2
String toString()
The AWT defines windows according to a class hierarchy that adds functionality and
specificity with each level.
The two most common windows are those derived from Panel, which is used by
applets, and those derived from Frame, which creates a standard window.
Much of the functionality of these windows is derived from their parent classes.
Component
At the top of the AWT hierarchy is the Component class.
Component is an abstract class that encapsulates all of the attributes of a visual
component.
All user interface elements that are displayed on the screen and that interact with the
user are subclasses of Component.
It defines over a hundred public methods that are responsible for managing events,
such as mouse and keyboard input, positioning and sizing the window, and repainting.
A Component object is responsible for remembering the current foreground and
background colors and the currently selected text font.
Container
The Container class is a subclass of Component.
It has additional methods that allow other Component objects to be nested within it.
Other Container objects can be stored inside of a Container (since they are themselves
instances of Component).
This makes for a multileveled containment system.
A container is responsible for laying out (that is, positioning) any components that it
contains.
Panel
The Panel class is a concrete subclass of Container. It doesn’t add any new methods;
it simply implements Container.
Panel is the superclass for Applet. When screen output is directed to an applet, it is
drawn on the surface of a Panel object.
A Panel is a window that does not contain a title bar, menu bar, or border.
When you run an applet using an applet viewer, the applet viewer provides the title
and border.
Other components can be added to a Panel object by its add( ) method inherited from
Container.
Once these components have been added, you can position and resize them manually
using the setLocation( ), setSize( ), or setBounds( ) methods defined by Component.
Window
The Window class creates a top-level window. A top-level window is not contained
within any other object; it sits directly on the desktop. Generally, we don’t create
Window objects directly. Instead, we use a subclass of Window called Frame.
Frame
Frame encapsulates what is commonly thought of as a “window.” It is a subclass of
Window and has a title bar, menu bar, borders, and resizing corners.
Canvas
It is not part of the hierarchy for applet or frame windows. Canvas encapsulates a
blank window upon which you can draw.
9.
Java BorderLayout
The BorderLayout is used to arrange the components in five regions: north, south, east, west
and center. Each region (area) may contain one component only. It is the default layout of
frame or window. The BorderLayout provides five constants for each region:
BorderLayout(): creates a border layout but with no gaps between the components.
JBorderLayout(int hgap, int vgap): creates a border layout with the given
horizontal and vertical gaps between the components.
4.13 BORDERS
As a practical matter, borders do not work with many JComponents other than JPanel.
Borders are drawn inside the graphics area of a JComponent, so subclassing JPanel for
13 BCS 31/BCA 31 – JAVA PROGRAMMING
9
E-NOTES / B.SC CS /BCA
drawing graphics must take this into account. This is one reason that subclassing JComponent
for graphics can be easier.
Good with JPanels, not good with other components, impossible with Containers
Method setBorder(). The setBorder() method is defined in the JComponent class, and is
therefore inherited by all child classes, which basically means all swing components, most
importantly JPanel.
Best on JPanels, not other JComponents. Borders are most often added to JPanels, and
somewhat less often to other JComponents, such as JLabels. Although you can add a border
to any JComponent, as a practical matter they often don't display well. If you need to add a
border to a component, put the component in a JPanel and add the border to that JPanel.
Creating borders
import javax.swing.border.*;
Reuse: A Border object describes how to draw the border. The same Border object may be
reused to set the border of many components.
Titled border -- Text on one of the other borders, usually a line border.
An empty border creates empty space around a component. Give the int number of pixels of
empty space on each side: top, left, bottom, right.
Java Swing is a part of Java Foundation Classes (JFC) that is used to create window-based
applications. It is built on the top of AWT (Abstract Windowing Toolkit) API and entirely
written in java.
The javax.swing package provides classes for java swing API such as JButton, JTextField,
JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.
UNIT IV
QUESTION BANK
PART – A (2 marks)
1. What is Applet?
2. Mention the two ways to create a Swing program.
3. Specify the use of AWT.
4. Mention the components in AWT. (Nov/Dec 2018)
5. Define the term-Panel.
6. What are the different controls provided by AWT?
7. What is Layout Manager?
8. What is the difference between local and remote applet?
9. What are Applet Classes?
10. Define Border.
14 BCS 31/BCA 31 – JAVA PROGRAMMING
1
E-NOTES / B.SC CS /BCA
PART – B (5 marks)
1. Describe the fundamentals of Applet.
2. Discuss on Border control component with example program.
3. Discuss about the Life Cycle of Applet.(Nov/Dec 2018)
4. How to create the Swing using Jpanel? Explain.
5. Write about the Advantages and Disadvantages of an Applet.
6. Explain drawRect() method in graphics class with example.
7. Write the difference between Swing and AWT.
8. What is the use of AWT Dialog box? Explain.
9. Discuss about the role of Swing in getting an interface.(Nov/Dec 2018)
UNIT V
5.1 JDBC
JDBC stands for Java Database Connectivity
JDBC is used to interact with various type of Database such as Oracle, MS Access,
My SQL and SQL Server.
The JDBC library includes APIs for each of the tasks mentioned below that are
commonly associated with database usage.
Use JDBC
Before JDBC, ODBC API was the database API to connect and execute query with the
database. But, ODBC API uses ODBC driver which is written in C language (i.e. platform
dependent and unsecured). That is why Java has defined its own API (JDBC API) that uses
JDBC drivers (written in Java language).
We can use JDBC API to handle database using Java program and can perform following
activities:
1. Connect to the database
2. Execute queries and update statements to the database
3. Retrieve the result received from the database.
The JDBC-ODBC bridge driver uses ODBC driver to connect to the database. The JDBC-
ODBC bridge driver converts JDBC method calls into the ODBC function calls. This is now
discouraged because of thin driver.
Oracle does not support the JDBC-ODBC Bridge from Java 8. Oracle recommends that you
use JDBC drivers provided by the vendor of your database instead of the JDBC-ODBC
Bridge.
Advantages:
Easy to use.
Can be easily connected to any database.
Disadvantages:
Performance degraded because JDBC method call is converted into the ODBC
function calls.
The ODBC driver needs to be installed on the client machine.
The Native API driver uses the client-side libraries of the database. The driver converts
JDBC method calls into native calls of the database API. It is not written entirely in java.
Advantage:
Performance upgraded than JDBC-ODBC bridge driver.
Disadvantage:
The Native driver needs to be installed on the each client machine.
The Vendor client library needs to be installed on client machine.
Advantage:
No client side library is required because of application server that can perform many
tasks like auditing, load balancing, logging etc.
Disadvantages:
14 BCS 31/BCA 31 – JAVA PROGRAMMING
5
E-NOTES / B.SC CS /BCA
Advantage:
Disadvantage:
JDBC API
Types of JDBC Drivers
This can be used in Java applications, applets, servlets or any other program where Java
codes used.
Java codes only interact with the JDBC Application-Program Interface (API). The
JDBC API is a simple SQL-Level interface, which allows execution of SQL
statements through Java.
The API consists of a set of interfaces and classes designed to perform actions on a
database.
The JDBC API class DriverManager, which is used to establish the connection to the
database, is responsible for managing the different JDBC drivers.
Other classes of JDBC API are useful when the programmer wishes to develop
specific drivers of her own.
The JDBC-ODBC bridge performs translations of JDBC calls to an ODBC-
compatible format.
This bridge is required to maintain compatibility with non-JDBC databases.
Some classes and interfaces which support connectivity between interface and database :-
DriverManager :-
14 BCS 31/BCA 31 – JAVA PROGRAMMING
7
E-NOTES / B.SC CS /BCA
“Driver Manger" Manages all the Drivers found in JDBC environment, load the most
appropriate driver for connectivity.
Connection:-
Connection class creates objects which represents connection and it's object also helps
in creating object of Statement, Prepared Statement and Callable Statement classes.
Statement:-
Statement object is used to execute query and also store it's value to
"Resultset" object.
PreparedStatement:-
It can be used in place of "Statement", Prepared Statement’s performance is high as
compared to "Statement" class, represents a precompiled SQL statement .
Callable Statement:-
Callable statement support stored procedure of RDBMS’, using it's object you can
execute stored procedure of database application.
ResultSet:-
Resultset object is used to store the result retrieve from database using "Statement" or
"PreparedStatement”, etc
SQLException:-
SqlException class is used to represent error or warning during access from database
or during connectivity.
Classes and interface
The JDBC API is comprised of two Java packages: java.sql and javax.sql. The following are
core JDBC classes, interfaces, and exceptions in the java.sql package:
DriverManager
DriverManager manages database drivers, load database specific drivers and select the most
appropriate database specific driver from the previously loaded drivers when a new
connection is established.
Managing, loading and selecting drivers are done automatically by the DriverManager from
JDBC 4.0, when a new connection is created.
The DriverManager can also be considered as a connection factory class as it uses database
specific drivers to create connection (java.sql.Connection) objects.
DriverManager consist of only one private constructor and hence it cannot be inherited or
initialized directly.
14 BCS 31/BCA 31 – JAVA PROGRAMMING
8
E-NOTES / B.SC CS /BCA
All other members of DriverManager are static. DriverManager maintains a list of DriverInfo
objects that hold one Driver object each.
Connection
Connection interface provides a standard abstraction to access the session established with a
database server. JDBC driver provider should implement the connection interface. We can
obtain a Connection object using the getConnection() method of the DriverManager as:
Before JDBC 4.0, we had to first load the Driver implementation before getting the
connection from the DriverManager as:
Class.forName(oracle.jdbc.driver.OracleDriver);
We can also use DataSource for creating a connection for better data source portability and is
the preferred way in production applications.
Statement
The Statement interface provides a standard abstraction to execute SQL statements and return
the results using the ResultSet objects.
A Statement object contains a single ResultSet object at a time. The execute method of a
Statement implicitly close its current ResultSet if it is already open. PreparedStatement and
CallableStatement are two specialized Statement interfaces. You can create a Statement
object by using the createStatement() method of the Connection interface as:
Statement st = con.createStatement();
You can then execute the statement, get the ResultSet and iterate over it:
while (rs.next())
{ System.out.println(rs.getString("empname"));
}
PreparedStatement
ps1.executeUpdate();
ResultSetMetaData
ResultSetMetaData is used to retrieve information about the count, types and the properties of
columns used in a ResultSet object. Consider an example where you are passed a ResultSet to
a method and you don’t know the number or type of columns in the ResultSet. You can use
ResultSetMetaData to get the column details and then find the corresponding row values
using the column details.
RowId
RowId maps a java object with a RowId. The RowId is a built-in datatype and is used as the
identification key of a row in a database table, especially when there are duplicate rows.
SQLException
This class is an exception class that provides information on a database access error or other
errors. JDBC 4.0 introduced following refined subclasses of SQLException:
java.sql.SQLClientInfoException
java.sql.SQLDataException
java.sql.SQLFeatureNotSupportedException
java.sql.SQLIntegrityConstraintViolationException
java.sql.SQLInvalidAuthorizationSpecException
java.sql.SQLSyntaxErrorException
java.sql.SQLTransactionRollbackException
java.sql.SQLTransientConnectionException
UNIT V
QUESTION BANK
PART – A (2 marks)
PART – B (5 marks)