0% found this document useful (0 votes)
7 views31 pages

Java Programming Basics and Features

The document provides an overview of Java programming, covering its introduction, features, differences from C and C++, and the Java Virtual Machine (JVM). It explains key concepts such as classes, objects, method overloading, static members, constructors, and arrays, along with examples for better understanding. Additionally, it discusses Java's input-output mechanisms and the use of wrapper classes.

Uploaded by

jeyojo4691
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views31 pages

Java Programming Basics and Features

The document provides an overview of Java programming, covering its introduction, features, differences from C and C++, and the Java Virtual Machine (JVM). It explains key concepts such as classes, objects, method overloading, static members, constructors, and arrays, along with examples for better understanding. Additionally, it discusses Java's input-output mechanisms and the use of wrapper classes.

Uploaded by

jeyojo4691
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

NOTES

Java Programming

MODULE -1

1. Introduction to Java
Java programming language was originally developed by Sun Microsystems which was initiated by James Gosling and
released in 1995 as core component of Sun Microsystems' Java platform (Java 1.0 [J2SE]).
Java is general purpose language which is used for developing either Stand alone Programs or either you can develop Web
Programs or Web Applets. First of all program of java is Compiled then it is transferred into the byte codes For Executing
java programs java name of the compiler is used for Converting the java program into the byte code and then by using the
interpreter we converts the Bytes code into the machine language.
If we simply excute the programs on our Machine then it is called as the Stand Alone Programs but if we using the Applets
for Which includes Graphical Environment then it is called as Web Applets.

Features of Java
 Compiled and Interpreted
 Platform Independent
 Object-Oriented
 Robust and Secure
 Secure
 Distributed
 Simple Small and Familiar
 Multithreaded and Interactive
Garbage Collection : Garbage collection in Java is the process by which Java programs perform automatic memory
management. Java programs compile to bytecode that can be run on a Java Virtual Machine, or JVM for short. When
Java programs run on the JVM, objects are created on the heap, which is a portion of memory dedicated to the program.

How Java Differs from C and C++?


1. C Uses header Files but java uses Packages.
2. C Uses Pointers but java doesn't supports pointers.
3. Java doesn't supports storage classes like auto, external etc.
4. The Code of C Language is Converted into the Machine code after Compilation But in
Java Code First Converted into the Bytes Codes then after it is converted into the
Machine Code.
5. C++ supports Operator Overloading but java doesn't Supports Operator Overloading.

What is JVM?
Java Virtual Machine (JVM) is a engine that provides runtime environment to drive the Java Code or applications. It
converts Java bytecode into machines language. JVM is a part of Java Runtime Environment (JRE). In other programming
languages, the compiler produces machine code for a particular system. However, Java compiler produces code for a Virtual
Machine known as Java Virtual Machine.
First, Java code is compiled into bytecode. This bytecode gets interpreted on different machines. Between host system and
Java source, Bytecode is an intermediary [Link] in Java is responsible for allocating memory space.
Operators in Java
There are multiple types of operators in Java all are mentioned below:
1. Arithmetic Operators
2. Unary Operators
3. Assignment Operator
4. Relational Operators
5. Logical Operators
6. Ternary Operator
7. Bitwise Operators
8. Shift Operators
9. instance of operator
Java Type Casting :Type casting is when you assign a value of one primitive data type to another type.
In Java, there are two types of casting:

1
 Widening Casting (automatically) - converting a smaller type to a larger type size

byte -> short -> char -> int -> long -> float -> double
 Narrowing Casting (manually) - converting a larger type to a smaller size type
double -> float -> long -> int -> char -> short -> byte
Java command-line argument is an argument i.e. passed at the time of running the Java program. In Java, the command
line arguments passed from the console can be received in the Java program and they can be used as input. The users can
pass the arguments during the execution bypassing the command-line arguments inside the main() method.
Example :
Class Para
{
public static void main (String args[])
{
[Link](args[0]);
[Link](args[1]);
[Link](args[2]);
[Link](args[3]);
}
}
Java IO : Input-output
Java brings various Streams with its I/O package that helps the user to perform all the input-output operations. These
streams support all the types of objects, data-types, characters, files etc to fully execute the I/O operations.
1. [Link]: This is the standard input stream that is used to read characters from the keyboard or any other standard
input device.
2. [Link]: This is the standard output stream that is used to produce the result of a program on an output device
like the computer screen.
Here is a list of the various print functions that we use to output statements:
 print(): This method in Java is used to display a text on the console. This text is passed as the parameter to this
method in the form of String. This method prints the text on the console and the cursor remains at the end of the
text at the console. The next printing takes place from just here.

Wrapper Class :
Wrapper classes provide a way to use primitive data types (int, boolean, etc..) as objects contained in [Link] package.

For example, in a business application , we type details like Name, Credit card no, etc and send them to the server. The
server expects this data in the form of Objects and hence we are supposed to send objects . In our data “ Name” is a String
type object but Credit card No is int type which is not an Object . So, this primitive data type should also be converted in to
an Object. To do this conversion , we need Wrapper class.

Sometimes you must use wrapper classes, for example when working with Collection objects, such as ArrayList, where
primitive types cannot be used (the list can only store objects):

ArrayList<int> myNumbers =newArrayList<int>();// Invalid


ArrayList<Integer> myNumbers =newArrayList<Integer>();// Valid

The table below shows the primitive type and the equivalent wrapper class:
Primitive
Data Type Wrapper Class

byte Byte
short Short
int Integer
long Long
float Float
double Double
boolean Boolean
char Character

Introduction to OOPS
2
Class and Object in Java

In Java, classes and objects are basic concepts of Object Oriented Programming (OOPs) that are used to represent real-
world concepts and entities. The class represents a group of objects having similar properties and behavior. For example,
the animal type Dog is a class while a particular dog named Tommy is an object of the Dog class.
Class – A class can be defined as a template/ blueprint that describes the behaviour/ state that the object of its type
support. Classes are the building blocks for object oriented programming in Java. A class defines the data , how it is
accessed and the method that manipulates the data. A class is a user defined data type with a template that serves to
define its properties.
Java has defined the following types of classes : i.e public , private, final, abstract
A class can be assigned a type by including the type modifier just before the class keyword at the time of creating the
class.

public modifier specifies that other objects outside the current package can use the class. By default classes are public in
the same package and private if a class is accessed from another package. By default when no access modifier is
specified , classes can only be used within that package in which they arte declared.

The final modifier specifies a class that have no sub classes.


An abstract modifier specifies , a class that has at least one abstract method in it. An abstract method is one that has no
implementation and an abstract class can not be instantiated.

Java has three modifiers –


Public- the public access specifies that the variables of a class can be freely accessed from outside the class of the current
package.
To completely hide a method or a variable from being used by any other class , the private modifier is used.
Protected variable or methods can be freely accessed either in a subclass or any other class in the same package.
Properties of Java Classes
1. Class is not a real-world entity. It is just a template or blueprint or prototype from which objects are created.
2. Class does not occupy memory.
3. Class is a group of variables of different data types and a group of methods.
4. A Class in Java can contain:
 Data member
 Method
 Constructor
 Nested Class
 Interface

Object- Objects have states and behaviours. Adog has states- color, name and breed as well as behaviour like barking ,
eating , and wagging the tail. All these objects have a state and behaviour. State is represented by data while behaviour is
represented by methods.
Example :
class Student
{
// data member (also instance variable)
int id;
// data member (also instance variable)
String name;
public static void main(String args[])
{
// creating an object of
// Student
Student s1 = new Student();
[Link]([Link]);
[Link]([Link]);
}
}
A class can contain any of the following types of variables :
1. Local Variable : Variable defined inside methods , constructors or block are called Local
variables. The variable will be declared and initialized within the methods .

3
2. Instance variable : Instance variables are variables within a class .Instance variable is considered analogus to global
variable for each object of the class. Each object can have different values for for its variable.. These are called instance
variable. Instance variable is also called as Object variable.

So, instance variables are member variable of a class defined within the class itself for which a separate copy is present
of each object of the class. It means when a number of object s are created from the same class , same copy of the
instance variables provided to all.
3. Class variable : class variables are variables declared within a class , outside any methods, with the static
keyword.

Scanner class
Input through keyboard in Java

Scanner class : Scanner class in java is found in the [Link] package . Java provides various ways to read input from the
keyboard , the java .[Link] class is one of them. The java Scanner class provides methods nextInt(), nextByte(),
nextShort(), next(), nextLine(), nextdouble(),, nextFloat() etc. To get a single character from the scanner class , you can call
next().charAt(0) method which returns a single character.

Example :

// Input string //
import [Link].*;
class input
{
Public static void main(String args[])
{
Scanner in new Scanner ([Link]);
String name;
[Link] (“ Enter yr name “);
name =[Link]();
// number input //

int age= [Link]();


float sal= [Link]();
double da = in. newDouble():

// character input //
Char grade = [Link]().charat(0);
}
}

MODULE – 2

Method Overloading :
Method overloading in Java means having two or more methods (or functions) in a class with the same name and different
arguments (or parameters). It can be with a different number of arguments or different data types of arguments.
For instance:

void function1(double a) { ... }


void function1(int a, int b, double c) { ... }
float function1(float a) { ...}
double function1(int a, float b) { ... }

In the above example, function1() is overloaded using a different number of parameters and different data types of
parameters.
Example
class Demo
{
double figure(double l, int b) //two parameters with double type
{ return (l*b); }
4
float figure(int s) //one parameter with float return type
{
return (s*s);
}
public static void main(String[] args)
{
demo obj = new Method_Overloading();
[Link]("Area of Rectangle: " +[Link](5.55, 6));
[Link]("Area of Square: " +[Link](3));
} }
Example :
class Sum
{
Public int sum(int x,int y)
{
return(x+y);
}
Public int sum(int x,int y, int z)
{
return(x+y+z);
}
Public double sum( double x , double y)
{
return(x+y);
}
public static void main(String[] args)
{
Sum obj = new Sum();
[Link](obj. sum(10,20));
[Link]([Link](10,20,30));
[Link]([Link](10.5,20.5));
}
}

static in Java
When you declare a variable or a method as static, it belongs to the class, rather than a specific instance. This means that
only one instance of a static member exists, even if you create multiple objects of the class, or if you don't create any. It will
be shared by all objects.

A static variable is associated with a class. It is not necessary to create an instance of that class in order to read and write
such variables. It is accessed through the class name.
Syntax : classname . variable name

A static method is associated with a class . There fore , it is not necessary to create an instance of that class in order to
invoke such method. So, static method can be called without an instanceof a class.
Syntax : classname . method name
Example :
Class student
{
int roll;
static String name=” GIST”;
student(int r )
{
roll=r;
}
Void display ()
{
[Link](roll+ “ “+ [Link]);
}
Public static void main(String args[])
{
Student s1(10);
5
Student s2 (20);
Student s3(30);

[Link]();
[Link]();
[Link]();
}
}

Constructor in Java
A constructor is a special method that is used to initialize an object. Every class has a constructor either implicitly or
explicitly. A constructor has same name as the class name in which it is declared. Constructor must have no explicit return
type. Constructor in Java can not be abstract, static, final or synchronized. These modifiers are not allowed for constructor.

Example
Class car
{
String name ;
String model;
Car( ) //Constructor
{
name ="";
model="";
}
}
Types of Constructor

Java Supports two types of constructors:


 Default Constructor
 Parameterized constructor
Each time a new object is created at least one constructor will be invoked.A constructor that has no parameters is known as
default the constructor. A constructor that has parameters is known as parameterized constructor. If we want to initialize
fields of the class with our own values, then use a parameterized constructor.

Example :
class GFG
{
// Default Constructor
GFG()
{
[Link]("Default constructor");
}
// Driver function
public static void main(String[] args)
{
GFG hello = new GFG();
}
}

MODULE - 3
Array in Java

An array is a group of contiguous related data items that share a common name. Arrays in Java are commonly used to
store collections of data, such as a list of numbers, a set of strings, or a series of objects. By using arrays, we can access
and manipulate collections of data more efficiently than using individual variables.

To create an array using this approach, you first declare the array variable using the syntax datatype[] arrayName,
where datatype is the type of data the array will hold, and arrayName is the name of the array.

An array can be created as follows.


int x[];
float avg[];

6
int[] num;
After declaring an array , we need to create it in the memory using new with size.
i.e x= new int [10];
avg=new float[5];
int[] numbers = new int[5];
int[] numbers = {1, 2, 3, 4, 5};

String[] names = {"John", "Mary", "David", "Sarah"};


String[] names;
names = new String[]{"John", "Mary", "David", "Sarah"};
Example :
class sk2
{
public static void main(String args[])
{
int a[]={10,20,30,40,50,60,70,80,90,100};
int size=a. length;
[Link]("Data in Given Array...");
for(int i=0;i<size;i++)
{
[Link](a[i]);
} } }
Example :
class demo
{
public static void main(String[] args)
{
int[] age = {12, 4, 5, 2, 5};
[Link]("Accessing Elements of Array:");
[Link]("First Element: " + age[0]);
[Link]("Second Element: " + age[1]);
[Link]("Third Element: " + age[2]);
[Link]("Fourth Element: " + age[3]);
[Link]("Fifth Element: " + age[4]);
}
}
Example :
class GFG
{
public static void main (String[] args)
{
int [] arr=new int [4];
[Link]("Array Size:"+[Link]);
}
}
Example
class demo
{
public static void main(String[] args)
{
int[] arr;
arr = new int[5];
arr[0] = 10;
arr[1] = 20;
arr[2] = 30;
arr[3] = 40;
arr[4] = 50;
for (int i = 0; i < [Link]; i++)
{
[Link]("Element at index " + i+ " : " + arr[i]);
}

7
}
}
Example
class Student
{
public int roll_no;
public String name;

Student(int roll_no, String name)


{
this.roll_no = roll_no;
[Link] = name;
}
}
public class GFG
{
public static void main(String[] args)
{
Student[] arr;
arr = new Student[5];
arr[0] = new Student(1, "aman");
arr[1] = new Student(2, "vaibhav");
arr[2] = new Student(3, "shikar");
arr[3] = new Student(4, "dharmesh");
arr[4] = new Student(5, "mohit");
for (int i = 0; i < [Link]; i++)
[Link]("Element at " + i + " : " + arr[i].roll_no + " " + arr[i].name);
}
}
2D Array in Java
Multidimensional arrays are useful when you want to store data as a tabular form, like a table with rows and [Link]
create a two-dimensional array, add each array within its own set of curly braces:
Example :
int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
[Link](myNumbers[1][2]); // Outputs 7

int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };


myNumbers[1][2] = 9;
[Link](myNumbers[1][2]); // Outputs 9 instead of 7

Example :
public class Main
{
public static void main(String[] args)
{
int[][] myNumbers = {
{1, 2, 3, 4},
{5, 6, 7} };
for (int i = 0; i < [Link]; ++i)
{
for(int j = 0; j < myNumbers[i].length; ++j)
{
[Link](myNumbers[i][j]);
}
}
}
}

Strings
8
In Java a string is a sequence of characters, but unlike many other languages that implements strings as character arrays ,
java implements strings as objects of type String. The strings used in java are handled by two classes – String and
StringBuffer. String class deals with strings that are not altered after creation. StringBuffer class deals with strings that need
alteration after they are created . String type strings are rigid , where as StringBuffer srings are flexible for manipulation.
Both the classes are available in [Link] package .

The String class - The String class supports several constructors . To create an empty String, we call the default
constructor .

1. String s= new String ();


2. string str= new string (“welcome to you”);
3. String msg=”sunil kumar jha”;
4. String (char arr[])
Char arr[]={ ‘j’,’a’,’v’,’a’};
String s=new String (arr);
Example :
import [Link].*;
class string
{
public static void main(String args[])
{
String s1="sunil kumar jha";
[Link](s1);
String s2=s1;
[Link](s2);
char c[]={'J','A','V','A'};
String s3= new String (c);
[Link](s3);
int len=[Link]();
[Link]("lengthof tring =" + len);
// string length is obtained by length() //
}
}
Example :
class string
{
public static void main(string args[])
{
String arr[]={"sunil","anil","raja","rani","sunny"};
int i;
for(i=0;i<[Link];i++)
{
[Link](arr[i]);
}
[Link]("size of array= " + [Link]);
}
}
String Buffer
StringBuffer is a peer class of string .While String creates string of fixed length StringBuffer creates string of flexible
length that can be modified in terms of both length and content. We can insert characters and substrings in the middle of
a string or append another string in the end.
Example :
import [Link].*;
class sk3
{
public static void main(String args[])
{
String str="sunil";
StringBuffer str1= new StringBuffer("sunil");
[Link](str);
9
[Link]("kumar");
[Link]("jha");
[Link](str1);
[Link](0,"welcome");
[Link](str1);
int length=[Link]();
[Link]("Length :=" + length);
for(int i=0;i<length;i++)
{

int p=i+1;
[Link]("Character at position :" + p+"is" + " "+ [Link](i));
}
}
}
Vector
Vectors are grow able array. Vector is like the dynamic array which can grow or shrink its size. Unlike array, we can
store n-number of elements in it as there is no size limit. It is a part of Java Collection framework since Java 1.2. It is
found in the [Link] package and implements the List interface, so we can use all the methods of List interface
[Link] than being constrained to a specific number of elements, one can expand them when needed. A Vector is a
java class, which needs to be initialized before it can be used. In order to use Vector class ,the [Link] package must
be imported in to the program.

i.e Vector names=new Vector();


The size of vector is the number of elements currently stored in it. The capacity of vector indicates the amount of
memory allocated to hold elements and is always greater than or equal to the size.
i.e Vector name =new Vector(25);
This vector will allocate enough memory to support 25 elements.
i.e Vector name=new Vector (25,5);
This vector has an initial size of 25 elements and will expand in increments of 5 elements when more than 25 elements
are added to it.
addElement() method – Adds an element at the end of vector i.e [Link](“skjha”);
insertElementAt() – inserts an element at a specified position.
i.e [Link](“skjha”,0)
To retrieve the last string added to the vector , one can use the lastElement().
i.e – String s =(String )[Link]()
elementAt() – This method is used to retrieve a vector element using an index.
i.e String s1=(String ) [Link](0).
Elements of a vector can be deleted or removed by using the removeElementAt() method
i..e [Link](0)
[Link](“sunil”)
To determine the size of vector , the class provides the size() method.. The size() method determines the number of
elements in the vector.
i.e int size = [Link]()
[Link](10) - it sets the size of vector by 10.
Int capacity() – returns the capacity of the vector

StringBuilder :
StringBuilder is a Java Class used to create mutable or successors that can be modified with characters. The StringBuilder
class is similar to another class in java, StringBuffer, but is non-synchronized. The StringBuilder class doesn’t provide
synchronization, and this is why Java StringBuilder is more suitable to work with than StringBuffer, as it works with a
single thread.

Important Constructors of StringBuilder class


The StringBuilder class provides several types of constructors used for converting a sequence of characters, the format of
characters, and the configuration of some properties of StringBuilder such as size, etc. Here are the essential constructors of
the StringBuilder class discussed below:

1. StringBuilder: This constructor is used to create a blank string builder. Initially, the capacity of this builder is set to 16
characters.

10
2. StringBuilder(int capacity): This constructor also creates an empty builder, but you can specify the builder’s capacity.

3. StringBuilder(CharSequence): The characters in this builder are created with specified arguments. The CharSequence is
used for the sequence of characters in the StringBuilder.

4. StringBuilder(string): This constructor is used to construct a string builder with a given string.

Check out some of the important questions on StringBuilder in java interview questions.

Methods of StringBuilder class


The StringBuilder class uses various methods. These methods are used to perform different operations on the StringBuilder
class. In this section, we will discuss the methods of the StringBuilder class below:

1. append(): This method is used when we need to append a new sequence in the existing sequence of characters in the
StringBuilder class.
Syntax to use append() method:
[Link](datatype s)

2. reverse(): As the name suggests, the reverse method is used to reverse the sequence of characters of the StringBuilder
string.
Syntax for reverse() method:
public [Link] reverse( )

3. charAt(): This method is useful in the situation when we want a specific character at an index value. We need to give the
index value of the
character from the string, and it will return that character.

4. capacity(): To find the initial capacity of the StringBuilder object, the capacity() method is used. However, the default
capacity of the
StringBuilder class is 16 bytes.

5. isEmpty(): This method is used to check whether the StringBuilder object is empty.

6. substring(): substring() method is used to find the substring of the StringBuilder sequence.
The syntax of the substring() method is as follows:
public [Link](index_start, index_end+1)

7 length(): This method is used to find the length of the sequence of StringBuilder. The syntax to use the length() method is
as follows:

8. indexof(): This method is used when we need to find the first index of a given string in the StringBuilder sequence. In the
absence of a string, it returns -1.

[Link](): When we don’t need a particular sequence from the StringBuilder sequence, we will use the delete() method.
Example:
public class AppendExample{
public static void main(String args[]){
StringBuilder mystring = new StringBuilder(“Learn”);
[Link](“ Java StringBuilder”);
[Link](mystring);
[Link](“ from GLA”);
[Link](mystring);
}}
Example :
class InsertMethodEg
{
public static void main(String args[])
{
StringBuilder mystring = new StringBuilder(“Learn”);

11
[Link](2, “String”);
[Link](mystring);
}
}
Example :
class ReplaceMethodEg
{
public static void main(String args[]){
StringBuilder mystring = new StringBuilder(“GreatLearning”);
[Link](10,14,”StringBuilder”);
[Link](mystring);
}
}

MODULE-4
Inheritance

In Java, a class is created for carrying out a task. Properties of such a class can be inherited in to another class. In such
conditions , the existing class can be extended to have additional capabilities .Such a class derived from another class ,is
called a subclass. The parent class is called a super class. A subclass inherits all instance variables and methods from its
super class and also has its own instance variables and methods. It is called inheritance. To create a sub class the keyword
extends is used in the class definition. Java does not support multiple inheritance. However this concept is implemented
using a secondary inheritance path in the form of interfaces.
 A subclass constructor is used to construct the instance variables of both the subclass and superclass. The subclass
constructor uses the keyword super to invoke the constructor method of the super class. The keyword super is used
within a subclass constructor method. The call to super class constructor must appear as the first statement within
the subclass constructor. The parameters in the super call must match the order and type of the instance variable
declared in the super class.
 A superclass reference can refer to an object of its class or any object derived from that object derived from that
class. This is an important feature of java and is used extensively when implementing run time polymorphism.
Example
class E
{
int a;
}
class F extends E
{
String x;
}
class ex1
{
public static void main(String args[])
{
F f=new F();
f.a=100;
f.x="sunil kumar jha";
[Link]("A="+ f.a);
[Link]("x"+f.x);
} }
Example
class A
{
String sa="I am class A";
int a=200;
}
class B extends A
{
String sb="I am class B";
}
class C extends B
{
12
String sc="I am string C";
}
class ex1
{
public static void main(String args[])
{
C objc=new C();
[Link]([Link]);
[Link]([Link]);

[Link]([Link]);
B objb=new B();
[Link]([Link]);
[Link](objc.a);
}
}
}

Super keyword
 super is used to call a superclass constructor: When a subclass is created, its constructor must call the constructor
of its parent class. This is done using the super() keyword, which calls the constructor of the parent class.
 super is used to call a superclass method: A subclass can call a method defined in its parent class using the super
keyword. This is useful when the subclass wants to invoke the parent class’s implementation of the method in addition
to its own.
 super is used to access a superclass field: A subclass can access a field defined in its parent class using the super
keyword. This is useful when the subclass wants to reference the parent class’s version of a field.
 super must be the first statement in a constructor: When calling a superclass constructor, the super() statement
must be the first statement in the constructor of the subclass.
 super cannot be used in a static context: The super keyword cannot be used in a static context, such as in a static
method or a static variable initializer.
 super is not required to call a superclass method: While it is possible to use the super keyword to call a method in
the parent class, it is not required. If a method is not overridden in the subclass, then calling it without the super
keyword will invoke the parent class’s implementation.

Example
// super keyword in java Variable
class Vehicle
{
int maxSpeed = 120;
}

class Car extends Vehicle


{
int maxSpeed = 180;
void display()
{
// print maxSpeed of base class (vehicle)
[Link]("Maximum Speed: " + [Link]);
}
}
class Test
{
public static void main(String[] args)
{
Car small = new Car();
[Link]();
}
}

Method Overriding :

13
A method in the subclass having the same name and type signature in the super class is called overriding method.
Overriding method exhibits polymorphism. Overriding exhibits polymorphism property. In order to revoke overriding , we
can use super.
Example
class A
{
int a;
A() { a=10; }
void print()
{ [Link]("A="+a); } }
class B extends A
{ int b;

B()
{ b=20; }
void print()
{ [Link](); // super is used to revoke overriding //
[Link]("B="+b);
}
}
class over1
{ public static void main(String args[]) {
// A a1=new A();
// [Link]();
B b1=new B();
[Link](); } }

final method , final variable and final class in Java


final Variable :
final variables are nothing but constant . we can not change the value of a final variable.
Example :
class demo
{
public static void main(String[] args)
{
// create a final variable
final int AGE = 32;
// try to change the final variable
AGE = 45;
[Link]("Age: " + AGE);
}
}
final method :
In Java, the final method cannot be overridden by the child class.
Example :
class FinalDemo
{
// create a final method
public final void display()
{
[Link]("This is a final method.");
}
}

class Demo extends FinalDemo


{
// try to override final method
public final void display()
{
[Link]("The final method is overridden.");
14
}
public static void main(String[] args)
{
Demo obj = new Main();
[Link]();
}
}

final class
In Java, the final class cannot be inherited by another class.

Abstract class and Abstract method :-

A class which is declared abstract is known as abstract class. Abstract classes are very important in object oriented
programming . They are typically used to declare functionality that is implemented by one or more sub classes. It needs to
be extended and its method implemented. It can not be instantiated.

They are typically used to declare functionality that is implemented by one or more subclasses. The advantage of such a
design is that the abstract class , the abstract class specifies what functionality is provided but not how that functionality is
provided. Therefore , the subclass may use different implementation to achieve the same objective. Java allows defining of
abstract methods without body and such methods are called abstract methods. Abstract methods are defined with a keyword
abstract. Classes containing at least one abstract method is called abstract class. Since abstract classes do not have concrete
methods , object for abstract class can not be created. Further , when an abstract class is defined , a subclass of the abstract
class must give a concrete method , otherwise , the subclass also becomes an abstract class.
Example
abstract class A
{
abstract class A
abstract void m1();
void m2()
{
[Link] (“ It is a conceret method”):
}
}
class B extends A
{
Void m1()
{
[Link](“ I am in sublass B”):
}
}
class Demo
{
Public static void main (String args[])
{
B b1 = new B():
b1.m1():
b1.m2 ():
}
}
Interfaces and Multiple Inhertance
Interfaces are similar to abstract classes but differ in their functionality. Interfaces define methods without body. Interfaces
cannot have instance variables. But it can contain final variables which must be initialized with values. The methods can
have type signature. The interfaces help to implement multiple inheritance in java . An interface uses the extends clause to
inherit the methods and constants defined in the super interface. Only constants and abstract methods are allowed in the
interface .

Every interface is by default abstract. All methods declared in the interface are by default public and abstract. So, there is no
need to put the abstract or public modifiers before their declaration. Multiple inheritance can be implemented through
interfaces by creating a list of interfaces separated by comma .
15
The interface in java is a mechanism to achieve abstraction . There can be only abstract methods in the java interface , not
method body. It is used to achieve abstraction and multiple inheritance in java.

An interface uses the extends clause to inherit the methods and constants defined in the super interface. Only constants and
abstract methods are allowed in the interface. Every interface is by default abstract. All methods declared in the interface are
by default public and abstract. So, there is no need to put the abstract or public modifiers before their declaration. Multiple
inheritance can be implemented through interfaces by creating a list of interfaces separated by coma in the extends clause.
Example
interface event
{
Void start();
}

interface sports
{
Void play():
}
Class hockey implements event, sports
{
Public void start()
{
[Link](“ Events started “):
}
public void paly()
{
[Link](“ sports started”):
}
Public void show()
{
[Link](“ Hockey started”):
}
}

class multi
{
Public static void main(String args[])
{
Hockey h1 = new hockey();
h1. Start():
h1. play():
h1. show():
}
}

MODULE - 4
Exception Handling

Exceptions are abnormal condition occurring in a program during program execution which disrupts the normal flow of
execution. When such exceptions occur , the program aborts or hang without giving any information. It is usually due to the
logical [Link] such exceptions are not caught , the program aborts at the point of occurring of the [Link] unexpected
situations that may occur during program execution are :
 The size of array is less or mor than the index
 A number is divided by zero
 Mode of file is not valid
 File is not open to read or write
 Problem in network connectivity
In java Exception is predefined class present in [Link] package. In java Exception is handled by five keywords : try,
catch, finally, throw, and throws. The java code may produce an Exception is placed inside try block .catch block is used to
handle the Exception. If some necessor code is to be executed after try block then it is placed inside finally block. By the
16
help of throw keyword programmer generates the Execution . When an Exeption is thrown out of a method throws keyword
is used.

All Exception classes are subtypes of the [Link] class. The Exception class is basically a sub class of the
Throwable class. The Throwable class has two subclasses- [Link] and 2. Error
Exception has two subclasses namely : 1. IOException and 2. RuntimeException

The finaly block is optional.


Example
class exep1
{
public static void main(String args[])
{
int arr[]=new int[10];
try
{
arr[10]=20;
[Link](arr[10]);
}
catch(ArrayIndexOutOfBoundsException e)
{
[Link] ("Error in array:");
arr[9]=25;
}
[Link]("The last element "+ arr[9]);
}
}

Difference between throws and throw :


The throw keyword is used to throw an exception explicitly. It can throw only one exception at a time.
The throws keyword can be used to declare multiple exceptions, separated by a comma. Whichever exception occurs, if
matched with the declared ones, is thrown automatically then.

What is Thread ?
A thread is a light weight process. It means a threads are the poart of a process performing various tasks. A thread refers to a
single sequential flow of activities being executed in a process; it is also known as the thread of execution or the thread of
control. A process can have several threads. A Thread can be claaed as subprocess/ sub task a flow of controle.

Multithreading is a programming concept in which the application can createva small unitbof tasks to execute in parallel.
Multithreading improves the performance of the CPU through [Link] can be achievedin two ways :
1. Process based Multitasking (Multitprocessing)
2. Thread based Multitasking (Multithreading)

1. Multiprocessing :
 Each process has an address in memory.
 In other words , each process allocates a separate memory area.
 A process is a heavy weight.
 Cost of communication beween process is high.
 Switching from one process to another requires some time for saving and loading registers, memory maps,
updating lists etc.

2. Multithraeding :
 Here a program (process/ task/job) is devided into two or more subprogram(process), which can be implemented at
the same time in parallel.
 Threads are light weight since less resource is needed.
 Unlike the process , in threads address space is shared. Interprocess communication is cheap.
Creating a Thread: Java’s Thread class contained in [Link] supports the threading mechanism.A Java thread can be
created in two different ways :
They are
1) By extending Thread class and
2) 2) By implementing Runnable class
Example1
17
By Extending Thread class :
This example creates a Thread extending from Thread class. To create a thread , we create a new class that extends Thread
and then create an instance of that class. Then write a run() method and place all the statements all the statements that are to
be executed by the thread. Write a constructor for the class and create an instance of the Thread class by passing the run()
method as a parameter . Start the thread by calling the start() method.

Example 1 :
class ThreadExample extends Thread
{
public void run()
{
int i;
for(i=1;i<=10;i++)

{
[Link]("Welcome to Threading");
}
}
}
class example1
{
public static void main(String args[]) throws InterruptedException
{
ThreadExample te=new ThreadExample(); // creates constructor //
Thread th=new Thread(te); // Passing object of the class//
[Link](); // starts the thread //
[Link](1000); // sleeps the thread for 1000 millisec//
ThreadExample obj=new ThreadExample(); // another object created//
Thread ob=new Thread(obj,"Thread one");
[Link]("Name of Thread :" + [Link]()); // Displays the name of thread
[Link]();
}
}

In Example1 the statement Thread ob=new Thread(obj,"Thread one"); has thread name “thread one” that can be displays
by the method getname(); sleep() method makes the currently executing thread to sleep for millisecond.

Example 2
class sum extends Thread
{
Thread th;
sum()
{
th=new Thread(this); // Alternately we can use this keyword to call run()
[Link]();
}
public void run()
{
int i,s=0;
for(i=1;i<=100;i++)
{
s=s+i;
}
[Link]("Sum of 1 to 100 = "+ s);
}
}
class example2
{
public static void main(String args[])
{
new sum();

18
}
}
By Implementing Runnable interface :
Another way is to create a thread , is to create a class that implements the runnable interface . Runnable abstracts a unit of
executable code .
Example 3
class MyThread implements Runnable
{
public void run()
{ int i;
try
{
for(i=0;i<=10;i++)
{

[Link]("MY thread ");


[Link](1000);
}
}
catch(InterruptedException e)
{
}
}
}

class example
{
public static void main(String args[])
{
MyThread th= new MyThread();
Thread obj=new Thread(th,"Test");
[Link]();
[Link]("The name of the thread is :" + [Link]());
[Link]("The Thread is alive : " + [Link]());
}
}
Methods of Thread :
 start() : Used to start the Thread It immediately execute the run() method.
 stop() : Used to stop the Thread.
 suspend() :Used to temporarily stop the Thread
 resume() : Used to resume the suspended Thread
 Sleep() : It causes to sleep the thread for specified time period. The Exception InterruptedException is thrown
when sleep () is called.
 join() : It waits until the thread on which it is called terminates . It ensures that the thread has finished its
execution.
 yield() : It temporarily stops the called thread and puts it at the end of the queue to wait for another turn to be
executed.
 currentThread() : It displays the name of the thread, its priority and name of its group. BY default, the name of
the thread is main and priority is 5 and group name is main.
 getName() : returns the name of the invoking thread object.
 isAlive() : Returns true if the thread has started and not yet terminated.
 wait() : This method makes the calling thread to give up monitor and go to sleep until some other thread wakes it
up.
 notify() : This method wakes up the first thread which called wait on the same object.
class example
{
public static void main(String args[]) throws InterruptedException
{
OldEvenThread oev=new OldEvenThread();
SumThread st=new SumThread();

19
FactThread ft=new FactThread();
Thread t1=new Thread(oev,"Old Even Thread");
Thread t2=new Thread(st,"Sum Thread");
Thread t3=new Thread(ft,"Factorial Threda");
[Link]();
[Link](2000);
[Link]();
[Link](2000);
[Link]();
Thread ct=[Link]();
[Link]("\nThe main thread is :" + [Link]());
[Link]("\nThe thread created is :" + [Link]());
[Link]("\nThe thread created is :" + [Link]());
[Link]("\nThe thread created is :" + [Link]());
[Link]("The priority value of " +[Link]()+"is " + [Link]());

[Link]("The priority value of " +[Link]()+"is " + [Link]());


[Link]("The priority value of " +[Link]()+"is " + [Link]());
}
}
By default the priority is NORMAL with value 5.

Life Cycle of Thread :


Following are the states of Thread after creation till destruction :
1 . new : When Thread is created , it is a new state. In this state the thread is not executed.
2. runnable : When the start() method is called on the thread object, the thread is in runnable state and can now be in one of
two states, - running or queued.
When the thread is in the running state , it is assigned CPU cycle and is actually running. When a thread is in the queue state
, it is waiting in the queue and completing for its turn to spend CPU cycles. A run time scheduler controls the transition
between these two sub
states. However , thread can call its yield() method to voluntarily move itself to the queued state from a running state.
3. blocked state : A running thread may go to a blocked state due to the following reason .
 wait() method is called by the thread
 sleep() method is called by the thread
 The thread is waiting for some I/O operations to complete.
When a blocked thread is unblocked , it goes to a runnable state and not to a running state. It will go back to the
runnable state competing for CPU cycle when another thread calls the suspended thread’s resume() method. Also by
the sleeping time is elapsed.
4. dead state : The dead state is entered when a thread finishes its execution or is stopped by another thread calling its
stop() method.
To find out whether a thread is alive , the isAlive() method is invoked.

Thread Priority:
Threads can be assigned priority . The priorities are used by the operating system to find out which runnable thread is to be
given the CPU time. Priorities are given by priority numbers ranging from 1 to 10.A thread with higher priority are given
preference than the lower one. There are three pre defined priorities
MIN_PRIORITY with value 1
NORM_PRIORITY with value 5
MAX_PRIORITY with value 10
To obtain the priority of the thread getPriority() method is used
join() – It may be required to wait for a particular thread to complete its task before another thread to proceed with. In such
situations the join() method of Thread class is used. When join() method is called on a thread object, the control waits for
the thread to completes its task and becomes a dead thread. Then the control proceeds with the normal course of execution.

MODULE-5
What Is Applet In Java?

20
Applets are second kind of programs supported by Java. Applets are programs that travel across the network in the form of
bytecode, load automatically in the local machine and are executed by web browsers. Applets can not be executed directly.
An applet can only be an element of an HTML page.

The applet elements of an html page can be executed by appletviewer provided by JDK . Applets do not use main() method
and [Link] for output. It supports only graphics methods for output. They generate window-based output.

They support AWT to draw and interactive i/o. Applets are defined in Applet class.
So we write import java. Applet. *;

Class hierarchy of Applet class is as follows :


Object->Component->Container->Panel->Applet->Japplet

Applets are created, executed, stopped and destroyed by methods provided by Applet class. All the activities are carried out
by the following methods –

(1) init () – This method is used only once and initializes the variable of the applet.
(2) Start() – This method is called automatically after the init() method. Start() method is called repeatedly while init()
method is called only once when applet is loaded.
(3) Paint() – This method is called automatically after the start() method. The user screen is drawn using the paint()
method. This method has an argument of type Graphics defined in AWT. The paint method() is called when the
applet begins execution.
(4) Stop() – This method is called automatically when a user leaves the page containing the applet.
(5) Destroy() – This method is called automatically when the browser ends the activity. This method helps to release
the resources used by the applet.

A Java application that is integrated into a webpage is called an applet. It functions as a front-end and is run within the web
computer. It makes a page more interactive and dynamic by operating inside the web browser. Applets are hosted on web
servers and inserted into HTML pages via the OBJECT or APPLET tags.
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 sid

The Life Cycle Of An Applet


The process by which an object is developed, launched, halted, and demolished throughout an application's implementation
is known as the applet life cycle in Java. In essence, it has five main methods: paint(), destroy(), stop(), init(), and start().The
browser calls these methods in order to perform their actions.

1. Init()- The init() function is the first to be executed and is responsible for initializing the applet. It can only be called once
throughout the startup process. The initialized objects are created by the web browser, which executes the init() function
located inside the applet after confirming the authentication setting.

2. Start()- This function launches the applet and includes the applet's real code. It begins directly following the call to the
init() function. The start() function is called each time the browser loads or refreshes. Additionally, it is triggered when the
applet is relaunched, improved, or switched across tabs in the web interface. Until the init() function is used, it is in an idle
state.

3. Stop()- The applet's execution is terminated by using the stop() function. Every time the applet is minimized, paused, or
switched between tabs on the web page, the stop() function is triggered. Again, the start() function is called when we return
to that page.

4. Destroy()- Once the applet completes its task, the destroy() function terminates it. When the webpage-containing tab
closes, or the applet window closes, it is triggered. It is performed just once and expunges the applet data from RAM. We
can't restart the applet after it's been deleted.

5. Paint()- The Java Graphics class contains the paint() function. It is employed in the applet to draw forms like squares,
circles, trapeziums, and so on. It runs following the call to the start() function and whenever the web page or applet display
resizes.

Sequence of method execution when an applet is executed:


1. init()
21
2. start()
3. paint()
Sequence of method execution when an applet is executed:
1. stop()
2. destroy()

Syntax of entire Applet Life Cycle in Java

class TestAppletLifeCycle extends Applet


{
public void init()
{
// initialized objects
}
public void start()
{
// code to start the applet
}
public void paint(Graphics graphics)
{

22
// draw the shapes
}

public void stop()


{
// code to stop the applet
}
public void destroy()
{
// code to destroy the applet
}
}
Example
import [Link].*;
import [Link].*;

import [Link].*;
/*
<applet code=app5 height=300 width=300>
</applet>
*/
public class app5 extends Applet
{
int arr[]={12,44,55,66,7,22,1,45,68,90};
int xpos=20;
public void paint(Graphics g)
{
[Link]("The Original Series :", + 25,25);
for(int i=0;i<[Link];i++)
{
xpos+=35;
[Link](arr[i]+" ",xpos,40);
}
sort(arr,g);
}
public void sort(int x[],Graphics g)
{
int temp;
int xpos=50;
for(int i=0;i<[Link];i++)
{
for(int j=0;j<[Link];j++)
{
if(x[i]>x[j])
{
temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
}
[Link]("The Sorted array :", + 10,10);
for(int i=0;i<[Link];i++)
{
xpos+=20;
[Link](arr[i]+" ",xpos,40);
}
}
23
}
Example
import [Link].*;
import [Link].*;
/*<applet code=app3 height=300 width=300></applet> */
public class app3 extends Applet
{
Button b0,b1,b2,b3,b4,b5,b6,b7,b8,b9,b10;
public void init()
{
b0=new Button("ZERO");
b1=new Button("ONE");
b2=new Button("TWO");
b3=new Button("THREE");
b4=new Button("FOUR");
b5=new Button("FIVE");
b6=new Button("SIX");
b7=new Button("SEVEN");
b8=new Button("EIGHT");
b9=new Button("NINE");
b10=new Button("TEN");
add(b0);
add(b1);add(b2);add(b3);add(b4);add(b5);
add(b6);add(b7);add(b8);add(b9);add(b10);
}
}
Example :
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;

/*<applet code="app2" height=500 width=500></applet> */

public class app2 extends Applet implements ActionListener


{
Label l1 = new Label("Enter a number :");
Label l2 = new Label("Square : ");
TextField tf = new TextField(5);
TextField tff = new TextField(5);
Button b1 = new Button("Calculate");
public void init()
{
add(l1); add(tf); add(l2);add(tff); add(b1);
[Link](this);
}
public void actionPerformed(ActionEvent e)
{
if([Link]()==b1)
{
int num = [Link]([Link]());
int s = num * num;
//[Link]([Link](s));
[Link](" " +s);
}
}
}

MODULE - 6

24
Java AWT : User Interface

Java introduced a package called Abstract window Tool Kit(AWT). This package contains larger number of classes and
interfaces that supported the creation of Graphical User Interfaces (GUI) components on user interface screens. In order to
display data within a GUI , an applet must use java classes specially designed for displaying information in a GUI
environment.
The GUI classes are contained in the [Link] package Java’s GUI provides user interface tools, User interface containers,
event system and lay out components. Components can include elements one can actually see on the screen., such as
windows, menu bars, buttons, and text fields or they can include other containers , which in turn can hold other components.

The hierarchy of the classes are as follows –


Component -> Container -> window -> panel \ Frame

Component class is the top class of AWT . Component is an abstract class that encapsulates all of the attributes of a visual
components. All the user interfaces are the subclasses of Component..

The Container class is a sub class of Component that can contain other components, including other containers . The most
common form of container is the panel. Which represents a container that can be displayed on the screen.

Canvase : It ia s simple drawing surface

The Panel class as a concrete subclass of Container. Panel is the superclass of Applet. When screen output is is directed to
an applet, it is drawn on the panel object A panel is a window that does not contain a title bar , menu bar or border
.
The Window classcreates a top level window . A top level window is not contained within any other objects. It sits directly
on the desktop. Generally object window is not created directly . Instead a sub class of window called Frame is used.

Frame is a subclass of window and has a title bar, menu bar, border, and resizing corner. Some of the basic User Interface
are as follows – Labels, Buttons, Check boxes, radio Buttons, choice Menu, Text field , Text area and scroll bars..

For creating any of the above component first create the component , and then add it to the [Link] applet.. To add a
component to a panel, the add() method or the container class is used.
i.e public void init()
{
Button b=new Button(“OK”);
Add(b);
}
Label – A text string that can be used to label other User Interface components.
To create a label , following constructors are used.
Public void init()
{
Label()- creates empty label
Label(String) – creates a label with string aligned left
Label(string , Label. RIGHT) – set right aligned label. Similarly Label. LEFT,
Label. CENTER
}
One can change the label by setFont() method
i.e setFont(new Font(“verdana”,Font>BOLD,15);
Label l1=new Label(“label name”, [Link]);
add(l1);
Buttons : - Buttons are simple user interface components that initiates some action when pressed.
To create a button following constructors are used-
Button() – creates an empty Button
Button (String) – creates a Button with a given string as alabel

Example : Button b=new Button(“PRESS ME”);


add(b);
Check Boxes :- Check boxes are user interface components that are that have two states namely checked or unchecked . It
might be Nonexclusive and Exclusive.

25
Nonexclusive check boxes can be checked or unchecked independently of others. While in exclusive check boxes only one
can be selected. Non exclusive checkboxes are created by Checkbox class while exclusive check boxes can be created using
Radio group and then assigning to radio group.
To create a check box following constructors are used-
Checkbox() - creates an empty check box
Checkbox(String) – creates a check box with the given string label.
Check box(String , Boolean) – creates a checkbox that is either selected or not selected depending on true or
false argument

Radio Button :- Radio buttons are created from the Checkbox class. In case of radio buttons where only one can be
selected at a time , an instance of CheckboxGroup must be selected. After that create and add individual radio button from
the checkbox class.
Ie.
Public void init()
{
CheckboxGroup ch=new CheckboxGroup();
Checkbox chk=new Checkbox(“Sex”,ch,true);
Add(chk);
}

Choice Menu : Choice menu are pull down list of items from which one can select an item. Choice menu can have only
one item selected at a time. To create choice menu , first create an instance of the Choice class the add individual item to it.
i.e public void init()
{ Choice ch=new Choice();
[Link](“India”);
[Link](“usa”);
[Link](“ uk”);
[Link](“japan”);
[Link](“France”);
}
Following are the methods of Choice object
GetItem(int) - Returns the dtring item at the given position (similar to array begins from 0)
GetSelectedItem() - Returns the currently selected item as a string
Select(int) – Selects the Item at the given position
Select(String) – Selects the item with the given string

Text Fields :
Text fields provides an area where one can enter and edit single line of text.. We use TextField class to create text field by
following constructor :-
TextField() – creates an empty text field that can be resized
TextField(int) – creates a text field that can hold specified number of character as in the argument
TextField(String) – creates a text field with initialized by the given string as in the argument

Example : TextField txt = new TextField();


TextField txt=new TextField(10);
TextField txt= new TextFeild(“name”);
add(txt);
 The setEchoChar () method is used to illustrate the creation of the text field that could be used to accept password.
Example : TextField txtpass= new TextField(10);
[Link](“*”);
add(txtpass);
 getText() : Returns the text that the text field contain
 setText() : Puts the given text string into the field.
 selectAll() : Selects all the text in the field
 select(int,int) : Selects the text between the two integer position

Text Area :
Text area are editable text field that can handle more than one line of text input. It is created from TextArea class.
Following are the constructors to create Text Area :
TextArea(int , int ) : Creates a text area of specified row and col.

26
 We can use setText(), getText() , setEditable(), and isEditable() methods with textarea also.
 insertText(String,int) – inserts string at the character index as indicated by the integer
 repalceText(String,int,int) – Replaces the text between the given integer position

Scrolling List :
Scrolling list is created from the List class Scrolling Lists do not pop up when selected , rather displays multiple items at a
time.
Constructors are as follows to create Scrolling List
 List() : creates an empty List
List(int, boolean) : list with indicated number of items and whether multiple lines are selected or not
Example : List l1=new List(5,true);
Void init()
{
[Link](“delhi”);
[Link](“patnai”);
[Link](“bombay”);
[Link](“Calcutta”);
[Link](“goa”);
}
Scrollbars :
Scroll bars can be horizontal or vertical . It is created by the class Scrollbar.

Example :
Scrollbar b1= new Scrollbar ([Link],10,0,1,100);
Example :
import [Link].*;
import [Link].*;
/* <applet code=example1 width=300 height=300>.
</applet>
*/
public class example1 extends Applet
{
public void init()
{
setFont(new Font ("Helvetica", [Link],15));
Label l1=new Label("Name :",[Link]);
add(l1);
TextField f1=new TextField(20);
add(f1);
Button b1= new Button("click here");
add(b1);
TextArea a1= new TextArea("enter name",10,10);
add(a1);
}
}
Example :
import [Link].*;
import [Link].*;
/* <applet code=example1 width=300 height=300>
</applet>
*/
public class example1 extends Applet
{
public void init()
{
setFont(new Font ("Helvetica", [Link],15));
Label l1=new Label("Name :",[Link]);
add(l1);
TextField f1=new TextField(20);
add(f1);
Button b1= new Button("click here");

27
add(b1);
TextArea a1= new TextArea("enter name",10,10);
add(a1);
}
}
Example
import [Link].*;
import [Link].*;
/*<applet code=example2 height=400 width=400>
</applet>
*/
public class example2 extends Applet
{
FlowLayout flow=new FlowLayout([Link],30,10);
public void init()
{
setLayout(flow);
Label l1= new Label("Name");
add(l1);
Button b1= new Button("CLICK ME ");
add(b1);
Button b2= new Button("CANCEL");

add(b2);
}
}
Example
import [Link].*;
import [Link].*;
/*<applet code=example3 height=400 width=400>
</applet>
*/
public class example3 extends Applet
{
Button b1= new Button("Sunday");
Button b2= new Button("Monday");
Button b3= new Button("Tuesday");
Button b4= new Button("Wednesday");
Button b5= new Button("Thurseday");
Button b6= new Button("Friday");
Button b7= new Button("Saturday");
FlowLayout flow=new FlowLayout([Link],30,10);
GridLayout grid= new GridLayout(3,3,10,10);
public void init()
{
setLayout(flow);
setLayout(grid);
add(b1); add(b2); add(b3); add(b4); add(b5); add(b6); add(b7);
}
}

MODULE - 6

JDBC
Java Database Connectivity (JDBC) is an application programming interface (API) for the Java programming language
which defines how a client may access a database. JDBC is a Java API to connect and execute the query with the database.
It is a part of JavaSE (Java Standard Edition). JDBC API uses JDBC drivers to connect with the database.
There are four types of JDBC drivers:

28
o DBC-ODBC Bridge Driver,
o Native Driver,
o Network Protocol Driver, and
o Thin Driver

The [Link] package contains classes and interfaces for JDBC API. A list of popular interfaces of JDBC API are given
below: Driver interface

o Connection interface
o Statement interface
o PreparedStatement interface
o CallableStatement interface
o ResultSet interface
o ResultSetMetaData interface
o DatabaseMetaData interface
o RowSet interface

A list of popular classes of JDBC API are given below:


o DriverManager class
o Blob class
o Clob class
o Types class

Anatomy of a JDBC :
Anatomy of a JDBC :
1. Create data source in database

2. The next step is to load the driver that will connect the Data Source by using
[Link](String) [Link] can be by registering Driver Manager also This
method loads the given class into the Java Interpreter If the given class does not exit in
the System, then a lassNotFoundException will be thrown.

3. After loading the driver, we establish a connection to the data source using the
getConnection(String,String,String)method of the DriverManager class. This method
takes three arguments. Username and Password is optional.

4. Next we use createStatement() method of the connection [Link] [Link] package


contains an interface Connection. A Connection object represents an SQL session with
[Link] interface contains methods, which can be used to prepare Statement. Here
statements provide a via medium to send SQL Statements to the Database.

A Statement is used to execute static SQL statements. There are no IN or OUT parameters. When an SQL statement is
executed, Only one result is returned. Using this Statement Object we now construct and execute SQL statement to perform
required Transactions.

A PreparedStatement object is used to execute dynamic SQL statements with IN parameter. When we need to perform
he same operation several
times we can use PreparedStatement for runtime [Link] execution of
PreparedStatement object is faster than that of Statement objects as they are precompiled A CollableStatement
object is used for executing a stored procedure that can be used in an application.

Example : 1
import [Link].*;
import [Link].*;
class jdbc1
{
public static void main(String args[])

29
{
try
{
[Link]("[Link]");

// or Register the Driver as below//


// [Link](new [Link]());
}
catch(ClassNotFoundException ce)
{
[Link](ce);
}
try
{
Connection con=[Link]("jdbc:odbc:empdata");
// empdata is the name of Data Source created in DSN //
Statement s= [Link]();
ResultSet rs=[Link]("select * from emp1");
/* while([Link]())
{
[Link]([Link](1) +"\t");
[Link]([Link](2) +"\t");
[Link]([Link](3) +"\t");
[Link]([Link](4) +"\t");
}*/

/*while([Link]())
{
[Link]([Link](1) +"\t"+
[Link](2) +"\t" +
[Link](3) +"\t"+
[Link](4));
} */
while([Link]())
{
[Link]([Link]("empno") +"\t"+
[Link]("empname") +"\t\t" +
[Link]("salary") +"\t"+
[Link]("dept"));
}
[Link]();
[Link]();
}
catch(SQLException ce)
{
[Link]("SQL Error");
}
}
}

Example : 2
import [Link].*;
import [Link].*;
import [Link].*;
class jdbc2
{
public static void main(String args[])
{
try
{

30
// [Link]("[Link]");
// or Register the Driver //
[Link](new [Link]());
Connection con=[Link]("jdbc:odbc:empdata");
Statement s= [Link]();
ResultSet rs=[Link]("select * from emp1");
while([Link]())
{
[Link]([Link]("empno") +"\t"+
[Link]("empname") +"\t\t" +
[Link]("salary") +"\t"+
[Link]("dept"));
}
[Link]();
[Link]();
}
catch(SQLException ce)
{
[Link]("SQL Error");
}
}
}

Signature of Faculty
Signature of HOD

31

You might also like