Java Total Notes BSC V Sem Paper V
Java Total Notes BSC V Sem Paper V
Java Total Notes BSC V Sem Paper V
UNIT - I
PROGRAMMING IN JAVA
Java Essentials:
A High Level Language java is a high level language that looks very
similar to C and C++ but offers unique features of its own.
Java BytecodeBytecode in java is and intermediate code generated by the
compiler, such as Sun's javac, that is executed by the JVM.
Java virtual Machine (JVM) JVM acts as an interpreter for the byte code,
which takes bytecodes as input and executes it as if it was a physical
process executing machine code.
JAVA Runtime Environment (JRE) includes JVM, class libraries, and other
supporting files.
JVM:
All language compilers translate source code into machine code for specific
computer. Java compiler also does the same thing. Java compiler produces an
intermediate code known as byte code for a machine that does not exist. This
machine is called the Java Virtual Machine and it exists only inside the
computer memory. The process of compiling a java program into bytecode which
is also referred to as virtual machine code.
Process of Compilation
The Virtual machine code is not machine specific. The machine specific code is
generated by the java interpreter by acting as an intermediary between the
virtual machine and the real machine.
Real Machine
Java Features:
Compiled and Interpreted
Platform- Independent and portable
Object Oriented
Robust and Secure
Distributed
Familiar, Simple and Small
Multithreaded and Interactive
High performance
Dynamic and Extensible
Compiled and Interpreted: Usually a computer languages is either
compiled or Interpreted. Java combines both these approaches. First, java
compiler translates source code into byte code instructions. Byte code are
not machine instructions and therefore second stage, Java interpreter
generates machine code that can be directly executed by the machine.
Java is both a compiled and an interpreted language.
Platform Independent and Portal : The most significant contribution of
java over other languages is its portability. Java programs can be moved
from one computer to another, anywhere and anytime. Changes and
upgrades in operating systems, processors and system resources will not
force any change in java programs. If a program yields the same result on
every machine, then the programs is called portability.
Object Oriented: Java is a true Object -oriented language. Almost
everything in java is an object. All programs code and data reside within
objects and classes. The object model in java is simple and easy to extend.
Robust and Secure: Robust means string. Java programs are strong and
they don't crash easily like a C or C++ program. There are 2 reasons.
Firstly, Java has got excellent inbuilt exception handling features.
Secondly java is robust lies in its memory management features. User
need not to be allocate and deallocate memory in java, everything will be
taken care of by JVM.
Distributed: JAVA is designed as a distributed language for creating
applications on networks. It can ability to share both data and programs.
Java applications can open and access remote objects on Internet easily as
they can do in a local system.
Simple, Small and Familiar: Java is small and simple language. For
example Java does not use pointers, preprocessor header files, goto
statement and many others. Java uses many constructs of C and C++ and
therefore, Java code "looks like a C++ code. In fact, java is a simplified
version of C++.
Multithreaded and interactive: Multithreaded means handling multiple
tasks simultaneously. Java supports multithreaded programs. Example:
we can listen to an audio clip while scrolling a page and at the same time
download an applet from a instant computer.
High Performance: The problem with interpreter inside the JVM is that it
is slow. Because of this, Java programs used to run slow. To overcome this
problem, along with the interpreter, java soft people have introduced
JIT(Just in time) compiler, which enhances the speed of execution.
Dynamic and extensible: Java is a dynamic language. java is capable of
dynamic linking new class libraries, methods and objects.
JAVA Tokens:
Reserved words
identifiers
literals
operators
Separators.
Character set: Basic character set which include letters, punctuation marks,
digits, in normal English language.
Letters: A..Z, a..z
Numbers: 0..9
Special Characters: +, - . *, / ,%, @, #, $, ^, &, *, ( , ), {, } , [ , ], : , ; , ", ', ?,<, > , back space etc.
Keywords: keywords are the essential part of language definition. Java
language has50 keywords. It has some specific meaning in java, we cannot use
them as names for variables, classes, methods and so on. All keywords are to be
written in lower case letters.
Identifiers: Identifiers are programmed design tokens. They are used for
naming classes, methods, variables, objects, labels, packages and identifiers in
a program.
JAVA identifier follow the following rules:-
1. They can have alphabets, digits and the underscore and dollar sign
characters.
2. They must not begin with a digit.
3. Upper case and lower case are distinct.
4. They can be any of length.
Examples:
names of all public methods and instance of variables starts with lower
case letters.
Ex: average
sum
When more than one words are used in a name second subsequent word
are marked with the upper case letter.
Ex: dayTemp
firstDayOfMonth
totalMaks
All classes and interfaces starts with a upper case letters.
Ex: Student
Helloworld
Motorcycle
Variables represents uppercase, lowercase and underscore between the
words.
Integer Literals.
PROGRAMMING IN JAVA
S
l
e
R
a
t
s
o
C
g
n
i
r
Literals: Literals in java are a sequence of characters. [ Digits, letters and other
characters] . That represents constant values to be stored in variables.
Constants: Constants in java refers to fixed values that do not change during
the execution of the program. Java supports several types of constants.
double p1;
Giving values to a variable:
1. By using assignment statement.
2. By using Read Keyword.
Syntax:
variablename=value;
Ex:
initialvalue=0;
finalvalue=10;
a=90;
Syntax:
datatypevariablename=value;
Ex:
intinitialvalue=0;
intfinalvalue=10;
class Example
{
public static void main(String args[])
{
int i;
float x;
System.out.println("Enter any integer number ");
i=Integer.parseInt(in.readLine( ));
System.out.println("Enter any floating point number");
x= Float.valueOf(in.readLine()).floatValue( );
System.out.println("Integer i=" +i);
System.out.println("Float x=" +x);
}
}
Scope of variables:
1. Instance variables.
2. class/static variables.
3. Local variables.
Instance variables:Anon static variable that is declared with in the class but
not in the method is called instance variable. Instance variables are related to a
specific object; they can access class variables.
Class / Static variables: A variable that is declared with static keyword is a
class but not in the method is called static or class variable.
Local variable: A variable that is declared within the method that is called
local variables. It is defined in method or other statements, such as defined and
used within the cache block and outside the block or method, the variable
cannot be used.
Ex:
class A
{
int amount=100; // instance variable
static int pin=2315; // static variable
public static void main(String args[])
{
int age=35; // local variable
}
}
Short 2 bytes
-32768 to + 32767
Int 4 bytes
-2147483648 to + 2147483647
Long 8 bytes
-9223372036854775808to
+9223372036854775807
Float 4 bytes
-3.4e-38 to +3.4e+038.
Double 8 bytes
-1.7e-308 to 1.7e+308.
Char 2 bytes
0 to 65535
Boolean
true or false
finalint PASS_MARK=50;
int a = 100;
double b = a;
System.out.println(b);
Narrowing Conversion
double a = 100.7;
int b = (int) a;
System.out.println(b);
Type Casting:
We often encounter situations where there is a need to store a value of one type
into a variable of another type. The process of converting one data type to
another data type is called casting.
type variable1=(type) variable2;
there are instances when we want to force a type conversion in a way that is
different from the automatic conversion.
Ex:-ratio=female_no/male_no;
Since female_no&male_no are declared as integer, the decimal part of the result
of the division would be lost and ratio would not represent a correct result. This
can be solved by converting locally one of the variables to floating point.
Ex:- ratio=(float)female_no/male_no;
Examples:
Examples Action
X=(int) 7.5 7.5 is converted to
integer by truncation
A=(int)21.3/(int)4.5 Evaluated as 21/4 and
the result would be 5
B=(double) sum/n Division is done in
Conditional statements:
1. If statement.
2. If...else statement
3. Nested if statement.
4. If...else..if statement.
5. Switch statement
1. If Statement:
This is a control statement to execute a single statement or a block of
statements, when the given condition is true and if it is false then it
skips if block and rest code of program is executed .
Syntax:
if(test expression)
{
<statements>;
...;
...;
}
Example: If n%2 evaluates to 0 then the "if" block is executed. Here it evaluates
to 0 so if block is executed. Hence "This is even number" is printed on the
screen.
Class Simpleif
{
public static void main(String args[])
{
int n = 10;
if(n%2 = = 0)
{
System.out.println("This is even number");
}
}
}
2. If-else Statement:
Syntax:
if( test expression)
{
<statements>;
...;
...;
}
else
{
<statements>;
....;
....;
}
Example: If n%2 doesn't evaluate to 0 then else block is executed. Here n%2
evaluates to 1 that is not equal to 0 so else block is executed. So "This is not
even number" is printed on the screen.
class Ifelse
{
public static void main(String args[])
{
int n = 11;
if(n%2 = = 0)
{
System.out.println("Even number");
}
else{
System.out.println("Odd number");
}
}
}
statement -1;
}
else
{
statement-2;
}
else
{
statement-3;
}
if( condition 1)
statement 1;
else if( condition 2)
statement 2;
else if( condition 3)
statement 3;
:
:
else
statement n;
(OR)
if(condition 1)
block1;
else if(condition 2)
block 2;
else if(condition 3)
block 3;
:
:
else
block n;
5. Switch Statement:
General form is:
switch (expression)
{
case constant 1: statement;
break;
case constant2: statement;
break;
:
:
:
case constant n: statement;
break;
default: statement;
}
The switch statements is multi way conditional statement .where expression
is an integer expression or character type expression and constant1,
constant2….constant n are the constants or constant expression called case
labels.
If the switch statement is executed , the value of the expression is
successively compared against the values of constant1,constant2,…constant
n. If a case is found whose value matches with the constant of the expression
the block of statement that follows the ‘case ‘ are executed.
The break statement at the end of a particular case causes an exit
from the switch statement. The absence of break statement at each block
causes the sequential execution of all statements from the block to the end of
the switch structure.
The default statement is executed if no matches are found. The
default is optional and if not present, no actual takes place of all matches fail.
When a match is found, the statement associated with that case is executed
until the break statement is reached.
break;
}
While(condition)
{
Statement 1;
: body of the loop
:
Statement n;
}
While is an entry control looping statement. Here first the condition is tested,
if it is true the body of the loop will be executed as long as the condition is
true. When if the condition is false the control comes out of the loop.
int i = 1;
//print 1 to 10
while (i <= 10){
System.out.println("Num " + i);
i++;
}
2.do-while loop statements:
Do ..while statement is an exit control loop statement. Here first the body of
the loop is executed and then condition is tested. If the condition is true again
the body of the loop is executed. If the condition is false the statements of the
loop will be terminated. i.e. control transfers to the statement following do ..
while statement.
Example: Here first do block of code is executed and current value "1" is printed
then the condition i<=10 is checked. Here "1" is less than number "10" so the
control comes back to do block. This process continues till value of i becomes
greater than 10.
int i = 1;
do{
System.out.println("Num: " + i);
i++;
}while(i <= 10);
3. for loop statements:
For loop is another entry control loop . The general form of for statement is
Syntax:
for (initialization; condition; increment or decrement){
<statement>;
...;
...;
}
initialization: The loop is started with the value specified.
condition: It evaluates to either 'true' or 'false'. If it is false then the loop is
terminated.
increment or decrement: After each iteration, value increments or decrements.
The execution of for statements the initialization of control value is done first.
The value of control variable is tested by using test condition. If the condition is
true then the body of the loop will be executed then the value of control variable
is incremented. This new value again tested using the test condition if it is true
again the body of loop is executed. If the condition is false control comes out of
the loop.
Syntax:
break; // breaks the innermost loop or switch statement.
break label; // breaks the outermost loop in a series of nested loops.
Continue statements:
This is a branching statement that are used in the looping statements (while, do-
while and for) to skip the current iteration of the loop and resume the next
iteration .
Syntax:
continue;
Return statements:
Syntax:
return;
return values;
return; //This returns nothing. So this can be used when method is declared with
void return type.
return expression; //It returns the value evaluated from theexpression.
Chapter -2
Classes and Objects
Class: A class is a group of objects which have common properties. It is a
template or blueprint from which objects are created. It is a logical entity. A
class in java can contain:
Fields
methods
Constructors
blocks
nested class and interface.
Syntax of Class:
class <class_name>
{
field declaration;
method declaration;
}
A class definition starts with the keyword class followed by the class name.
Where class name is a valid identifier for the class. The body of the declaration
can contains members, that can be either fields or method declarations. The
class members are classified into 3 categories: Private, Public and Protected.
These are called member access specifiers.
1. Private members: Private members of a class are accessible only from
within .members of the same class. You cannot access it outside the class.
2. Protected members: Protected members of their same class and also from
members of their derived classes.
3. Public Members: Public members are accessible from anywhere the object is
visible.
Note: By default all members of the class declared with the class keyword have
private access for all its members.
Method Declaration: Methods that are necessary for manipulating the data
contained in the class. Methods are declared inside the body of the class. But
immediately after the declaration of instance variables.
General Form:
type methodname(parameterlist)
{
method body;
}
Method declaration have 4 basic parts:
I. The name of the method (methodname)
II. The type of value the method returns ( datatype)
III. A list of parameters (parameter_list)
IV. The body of the method.
The type specify the type of value the method would return. This could be a
simple datatype such as int as well as any class type. It could even be void
type, if the method does not return any value.
The method name is the valid identifier.
The parameter list is always enclosed in a parenthesis. The list of variables
can be separated by commas. In the case, where no input data are required
the declaration must return the empty parenthesis.
Creating Objects: An object in java is a block of memory that contains space to
store all the instance variables. Creating an object is also referred to as
"initiating" an object.
Objects in java are created using the new operator. The new operator
creates an object of the specified class and returns a reference to that object.
breadth=y;
}
int rectarea( )
{
int area=length*breadth;
return(area);
}
}
class Rectarea
{
public static void main(String args[])
{
int area1, area2;
Rectangle rect1=new Rectangle( );
Rectangle rect2= new Rectangle( );
rect1.length=15;
rect1.breadth=10;
area1= rect1.length* rect1.breadth;
rect2.getdata(20,10);
area2= rect2.rectarea( );
System.out.println("Area1=" +area1);
System.out.println("Area2=" +area2);
}
}
Method Overloading:
In Java, it is possible to create methods that have the same name, but different
parameter lists and different definitions. This is called method overloading.
Method overloading is used when objects are required to perform similar tasks
but using different input parameters. When we call a method in an object. Java
matches up the method name first and then the number and type of parameters
to decide which one of the definitions to execute. This process is known as
"Polymorphism".
To create an overloaded method, all we have to do is to provide several
different method definitions in the class, all with the same name, but with
different parameter lists. The difference may either be in the number or type of
arguments. That is each parameter list should be unique.
Example Program:
class Room
{
float length;
float breadth;
Room(float x, float y)
{
length=x;
breadth=y;
}
Room(float x)
{
length=breadth=x;
}
float area( )
{
return(length*breadth);
}
public static void main(String args[])
{
Room r1=new Room(10);
Room r2= new Room(10,20);
System.out.println("Area=" +r1.area( ) );
System.out.println("Area=" +r2.area( ) );
}
}
UNIT - 2
CONSTRUCTORS
Constructors & Types of constructors?
There are the constructor with parameter. Using this constructor you can
provide different values to data members of different objects. by passing the
appropriate values as argument.
Example Program:
class Rectangle
{
{
intlength;
int breadth;
Rectangle(int x, int y)
{
length=x;
breadth=y;
}
public static void main(String args[])
{
Rectangle r1=new Rectangle(10,20);
System.out.println("Length of the rectangle" +r1.length);
System.out.println("Breadth of the rectangle" r1.breadth);
}
}
Constructor Overloading:
Just like other member functions, constructor can also be overloaded. In fact
when you have both default and parameterized constructors defined in your
class you are having overloaded constructors, one with no parameters and other
with parameters.
Example Program:
class Student
{
introllno;
String name;
public static void main(String args[])
{
Student s1=new Student( );
Student s2=new Student( 102, "Spandhan");
}
Student( )
{
rollno=101;
name="Preetham";
System.out.println(rollno + " " + name);
}
Student(int x, String n)
{
rollno=x;
name=n;
System.out.println(rollno + " " + name);
}
}
Static Variables and Methods:
The static keyword in java is used for memory management. It makes
your program memory efficient[i.e. it saves memory].
It can apply for
variables
methods
blocks.
The static variable can be used to refer the common property of all
objects.
Static variables gets memory only once in class area at the time of class
loading.
The members that are declared static are called static members.
Class basically contains two sections. One declares variables and other
declares methods. These variables and methods are called instance
variables and instance methods. Every time class is initiated, a new
copy of each of them is created. They are accessed using the objects
( with dot operator).
we want to define member that is common to all objects and accessed
without using particular object. That is, the member belongs to the
class as a whole rather than the objects created from a class.
Example: static int x;
static int max(int x, int y);
with the help of static method we can change (or) assign value to the
static variable.
class Student
{
int rollno;
String name;
static String college="GDCBCM";
Student(int x, String n)
{
rollno=x;
name=n;
}
static void change( )
{
college="Govt. Degree & PG College";
}
void display( )
{
System.out.println(rollno + " " +name + " " + college);
}
public static void main( String args[])
{
Student s1=new Student (101,"Preetham");
Student s2=new Student(102,"Spandhan");
change( );
s1.display( );
s2.display( );
}
}
this Keyword:
this Keyword refers to current instance of a class.
Using this keyword we can access instance members [ variables&
members].
Optional:
If there is no confusion between instance variable and local variable this
keyword is optional. In such case we don't specify this keyword automatically
and access local variable.
Mandatory:
If there is a confusion between instance variable and local variable then
specifying the this keyword is mandatory. In such case we don't specify this
keyword the compiler will also not specify this keyword and instead access local
variable. If we want to access instance variable then the programmer has to
specify the this keyword.
Student(int x )
{
this.x=x;
{
void display( )
{
System.out.println(x);
}
public static void main(String args[ ] )
{
Student s=new Student( 50);
s.display( );
}
}
Here arr is one dimensional array is of integer type, array containing 5 elements
those are arr[0], arr[1], arr[2],arr[3], arr[4].
arr[1]=10;
arr[2]=15;
arr[3]=20;
arr[4]=25;
Array Length: All arrays store the allocated size in a variable named length. we
can obtain the length of array a using a.length.
Arraylength=Upper+lower +1
Ex:
class Arraydemo
{
public static void main(String args[ ])
intarr[ ]= new int[5];
arr[0]=5;
arr[1]=10;
arr[2]=15;
arr[3]=20;
arr[4]=25;
for(int i=0;i<arr.length;i++)
{
System.out.println(arr[i]);
}
}
3. Inputting the values: We can inputting or read the values to an array by
using for loop.
Ex:
int a[]= new int[20];
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the size of the array");
int n= Integer.parseInt(br.readLine( ));
System.out.println("enter the elementsinto the array");
for(int i=0;i<n;i++)
{
a[i]=Integer.parseInt(br.readLine( ));
}
importjava.util.Scanner;
public class Javaprogram
{
public static void main(String args[ ])
{
intsmall,size,i;
intarr[ ]= new int[20];
Scanner scan= new Scanner(System.in);
System.out.println("Enter the array size ");
size=scan.nextInt( );
System.out.println("Enter the elementsinto the array ");
for(i=0;i<size;i++)
{
arr[i]=scan.nextInt( );
}
System.out.println("Searching for the smallest element \n \n");
small=arr[0];
for(i=1;i<size;i++)
{
if(small>arr[i])
{
small=arr[i];
}
}
System.out.println("smallest Element " +small);
}
}
2. Two Dimensional Array: A list of items can be given one variable name
using two subscripts such a variable is called a two dimensional array.
Syntax: datatype arrayname[ ][ ]= new datatype[size][size];
Ex: int arr[ ] [ ]= new int[3][3];
}
}
}
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
System.out.print(m3[i][j]+ "\t");
}
System.out.println("\n");
}
}
}
n
o
y
u
a
ti
e
t
d
l
s
M
h
i
A
m
I
r
S
N
c
C
Non static Nested class (These are the non static members of the class).
Static Nested class ( These are the static members of a class).
Inner Class: Creating inner class is quite simple. You just need to write
class within a class. Unlike a class, an inner class can be private and
once you declare an inner class private , it cannot be accessed from an
object outside the class.
Ex:
class Outer
{
class Inner
{
void innermethod( )
{
System.out.println("This is an inner class method ");
}
}
void outermethod( )
{
System.out.println("this is Outer method");
Inner i=new Inner( );
i.innermethod( );
}
public static void main(String args[])
{
Outer outr= new Outer( );
outr.outermethod( );
}
}
OUTPUT:
This is Outer method
This is inner class method
Method Local Inner Class:
In Java we can write a class within a method and this will be a local type.
Like local variable, the scope of the inner class is restricted within the method.
A method local inner class can be instantiated only within the method where the
inner class is defined.
Ex:
class Outer
{
void outermethod( )
{
class MethodInner
{
void innermethod( )
{
System.out.println("inner class method");
}
}
MethodInner inn= new MethodInner( );
inn.innermethod( );
}
public static void main(String args[])
{
Outer outr=new Outer( );
outr.outermethod( );
}
}
Output: inner class method.
{
public void mymethod( )
{
------------;
------------;
}
};
class Outer
{
static class Inner
{
void innermethod()
{
System.out.println("static inner class method");
}
}
}
output:
static inner class method
Inheritance
A Process of acquiring the members ( Properties and methods) of one class
to another class is called inheritance.
Inheritance is a mechanism wherein a new class is derived from existing
class.
Using inheritance we can achieve reusability and thereby reduce the code
size and development time of the application.
Inheritance represents the is-a relationship, also known as parent -child
relationship.
Uses of Inheritance in java:
for method overloading ( so runtime polymorphism can achieved)
for code reusability.
The extends keyword indicates that you making a new class that derives
from an existing class. The meaning of extends is to increase the functionality.
Program:
class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}
On the basis of class, there can be three types of inheritance in java: single,
multilevel and hierarchical.
Single Inheritance: In this type of inheritance one derived class extends from
only one base class. It is the most simplest form of inheritance.
Multilevel Example:
class Add
{
int a=15,b=10;
void Add()
{
System.out.println(a+b);
}
}
Class Sub extends Add
{
void Sub()
{
System.out.println(a-b);
}
Class Mul extends Sub
{
void Mul()
{
System.out.println(a*b);
}
Class Div extends Mul
{
void Div()
{
System.out.println(a/b);
}
}
Class Multilevel
{
Public static void main( String args[])
{
Div d=new Div();
d.add();
d.Sub();
d.Mul();
d.Div();
}
}
Hierarchical Example:
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 Hierarchical
{
public static void main(String args[])
{
Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//C.T.Error
Dog d=new Dog();
d.bark();
d.eat();
}
}
{
Bike obj = new Bike();
obj.run();
}
}
OUTPUT:
Bike is running safely.
Example:
class Super1
{
int x;
Super1(int x)
{
this.x=x;
}
void display()
{
System.out.println(“Super x=” +x);
}
}
class Sub1 extends Super1
{
int y;
Sub1(int x, int y)
{
Super1(x);
this.y=y;
}
void display()
{
System.out.println(“Super x=” +x);
System.out.println(“Super y=” +y);
}
}
class Overridetest
{
Sub1 s1=new Sub(100,200);
s1.display();
}
}
1. Use of super with variables: This scenario occurs when a derived class and
base class has same data members. In that case there is a possibility of
ambiguity for the JVM. We can understand it more clearly using this code
Class Vehicle
{
int maxSpeed = 120;
}
Class Car extends Vehicle
{
int maxSpeed = 180;
Void display()
{
System.out.println("Maximum Speed: "+ super.maxSpeed);
}
}
Class Test
{
publicstaticvoidmain(String[] args)
{
Car c= newCar();
c.display();
}
}
Output:
Maximum Speed: 120
2. Use of super with methods: This is used when we want to call parent class
method. So whenever a parent and child class have same named methods then
to resolve ambiguity we use super keyword. This code snippet helps to
understand the said usage of super keyword.
classPerson
{
Void message()
{
System.out.println("This is person class");
}
}
Class Student extends Person
{
Void message()
{
System.out.println("This is student class");
}
Void display()
{
message();
super.message();
}
}
classTest
{
Public static void main(String args[])
{
Student s = newStudent();
s.display();
}
}
Output:
This is student class
This is person class
3. Use of super with constructors: super keyword can also be used to access
the parent class constructor.
Class Person
{
Person()
{
System.out.println("Person class Constructor");
}
}
Class Student extends Person
{
Student()
{
super();
System.out.println("Student class Constructor");
}
}
classTest
{
Public static void main(String[] args)
{
Student s = new Student();
}
}
Output:
Person class Constructor
Student class Constructor
Final Keyword:
Final keyword can be used along with variables, methods and classes.
1. Final variable -> to create the constant variable.
2. Final method -> prevent the overriding.
3. Final class -> prevent the inheritance.
1.Final Variable: If you make any variable final, you cannot change the value.
A final variable that have no value it is called blank final variable(or)
uninitialized final variable. It can be initialized constructor only. The blank
final variable can be static also which will be initialized in static block only.
Example:
class Bike
{
final int speedlimit=90;
void run( )
{
speedlimit=120;
}
public static void main(String args[])
{
Bike b=new Bike( );
b.run();
}
}
Output: compile time error.
Final Method : If you make any method as final you cannot be override it.
Example:
class Bike
{
final void run( )
{
System.out.println(“Running”);
}
}
class Honda extends Bike
{
void run( )
{
Final class: If you make class as final, you cannot extend it.
Example:
Syntax:-interface interfacename
{
Variable declaration;
Method declaration;
}
Here interface is the keyword and interface name is any valid java variable.
Note:- When on interface extends two or more interfaces, they are separated by
commas.
Syntax:-
Class classname implements interfacename
{
\\ body of the class
}
Here class classname“ implements” the interface.
*Packages *
Package:- A package represents a directory that contains related group of
classes and interfaces. In fact, packages acts as “containers” for classes.
By organizing our classes into packages we achieve following benefits;
The classes contained in the packages of other programs can be
easily reused.
In packages, classes can be unique. That is two classes in two
different packages can have the same name
Packages provide a away to “hide" classes preventing other
programs or packages from accessing classes that are meant for
internal use only.
Package Contents
name
java.lang Languages support classes. These are class that
java compiler itself uses and therefore they are
automatically imported. They include classes for
primitive types, strings, math functions, threads
and exceptions.
java.util language utility classes such as Vectors, hash
tables, random Numbers, date etc
java.io Input /output support classes. They provide
facilities for input & output data.
java.awt set of classes for implementing Graphical user
interface. They include classes for windows
Buttons, lists, menus and so on.
java.net classes for networking. They include classes for
communicating with local computers as well as
with internet servers
java.applet Classes for creating and implementing applets.
double Y=java.lang.Math.sqrt(x);
This statement uses a fully qualified class name math to invoke the method
sqrt( ).
Creating a packages;-
First declare the name of the package using the package keyword by
packagename.
Creating our own by package involves the following steps;
1. Declare the package at the beginning of a file.
Package packagename;
2. Define the class that is to be put in the package and declare it public.
3. Store the class name.java file in the directory created.
4. Compile the file this creates the .class file in the directory
Package firstpackage;
Public class Firstclass
{
\\ body of the class
}
Here package name is firstpackage .The class Firstclass is part of the
package. Now save the file Firstclass.java and located in directory name
firstpackage. When the source file is compiled, java will create a .class file and
store it in the same directory.
Syntax:-Package firstpackage.secondpackage
Accessing package:-
Accessing package approach through the import statement.
General form:-
1. Import package1[ .package2] [.package 3] .classname;
Ex:- import firstpackage.secondpackage.myclass;
2. Import packagename .*;
Using a package:-
Consider small simple programs that we use classes from other packages.
1. Consider package named package1 containing a single classA.
2. ClassA .java and stored in the sub directory package1
3. When compile ClassA. Class will be stored in the same subdirectory.
package package1;
public class ClassA
{
public void displayA( )
{
System.out.println( “Class A”);
}
}
Consider package named package2 containing a single classB.
ClassB .java and stored in the subdirectory package2.
When compile ClassB.class will be stored in the same subdirectory.
package package2;
public class ClassB
{
protected int m=10;
Public void display B( )
{
System.out.println(“class B”);
System.out.println(“m=” +m);
}
}
Importing classes from other packages:-
Import package1.classA;
Import package2.*
class packageTest2
{
public static void main(String args[ ])
{
classA objA=new classA( );
classB objB=new classB( );
objA.displayA( );
objB.displayB( );
}
}
Output:-
` classA
classB
m=10
}
public class Student
{
-----------
-----------
}
package pack2;
public class Courses
{
-----------
-----------
}
public class Student
{
-----------
-----------
}
Creating object for those classes:-
Pack1.Student stu1;
Pack2.Student stu2;
classes and subclasses in the same package But also to the subclasses in the
other packages.
Private Protected Access: visibility level between "protected" and "private"
Access. This modifier makes all fields visible in all subclasses regardless of
package.
Friendly Access: No Access modifier is specified the member defaults to friendly
level of access. friendly access makes fields visible only in the same package.
Wrapper classes:-
Vectors cannot handle the primitive datatypes like int, float, long, char
and double. Primitive datatypes may be converted into object types by using the
wrapper classes contained in the java.lang package.
String Class:
In java, strings are class objects and implemented using the two classes,
namely " String" and "String Buffer".
A JAVA string is initiated object of string class.
A JAVA string is not a character and is not Null terminated.
Syntax:
String stringname;
stringname= new String("string");
Example:
String firstname;
firstname= new String("Anil");
(or)
String firstname= new String("Anil");
String Arrays: we can also create & use arrays that contains strings.
Ex: String item[]= new String[3];
String Methods: The string class defines a number of methods that accomplish
a variety of string manipulation tasks.
Some most commonly used string methods
Method Call Task Performed
s2=s1.toLowerCase; Converts the string s1 to all lowercase
s2=s1.toUpperCase; Converts the string s1 to all Uppercase
s2=s1.replace('x','y'); Replace all appearances of x with y
s2=s1.trim( ); Remove white spaces at the begin and
end of the string s1.
s1.equals(s2) Returns 'true' if s1 is equals to s2.
s1.equalIgnoreCase(s2) Returns 'true' if s1=s2, ignoring the
case of characters
s1.length( ) Gives the length of s1
s1.charAt(n) Gives nth character of s1.
Unit - 3
Exception Handling
Q) Exception Handling and Types of Exception Handling?
Catch: Catch block holds the reference of the object which is thrown from the
try block and reference has been is holded by the reference variable declared
type of exception thrown by the exception class.
throws: It is use to ignore try and catch block within the function.
Types of Exceptions:
There are 2 types of exceptions
Predefined / built in exceptions
User-Defined Exceptions
Sometimes, the built-in exceptions in Java are not able to describe a certain
situation. In such cases, a user can also create exceptions which are called
‘User-Defined Exceptions’. These exceptions are deal with common problems.
Following steps are followed for the creation of User defined Exception:
To raise exception of user-defined type, we need to create an object to his exception class
and throw it using throw clause, as:
MyException me=new MyException("Exception details");
throw me;
(or)
throw new MyException("exception details");
}
}
output:
enter Roll no
123
Invalid rno
Output:
enter Roll no
1234567890
Syntax:
try
{
statement; // generator an exception
}
catch(Exceptiontype e)
{
Statement; // process the exception
}
A try block can be followed by one or more catch blocks. Each catch block
must contain a different exception handler. So, if you have to perform different
tasks at the occurrence of different exceptions, use java multi-catch block.
o At a time only one exception occurs and at a time only one catch block is
executed.
Syntax:
try
{
statement; // generates an exception
}
catch(Exception_Type1 e)
{
Statement; // process the exception Type1
}
catch(Exception_Type2 e)
{
Statement; // process the exception Type2
}
.
.
.
catch(Exception_TypeN e)
{
Statement; // process the exception TypeN
}
package Exceptionhandling;
import java.util.*;
public class Dexception
{
public static void main(String args[])
{
try
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter a value");
int x= sc.nextInt();
int k=44/x; //when x==0 exception is raised
System.out.println("The value k:" +k);
}
catch(ArithematicException ae)
{
System.out.println("only non zero value");
}
catch(InputMismatchException ie)
{
System.out.println("only integer value");
}
}
}
OUTPUT:
1) Enter a value
12
The value k: 3
2) Enter a value
0
Only non zero value
3) Enter a value
12.34
Only integer value.
try
{
int arr={5,0,1,2};
try
{
int x=a[3]/a[1];
}
catch( ArithematicExcception e)
{
System.out.println("divide by zero");
}
arr[4]=3;
}
catch(ArrayIndexOfBoundsException ae)
{
System.out.println(" Array Index out of bound ");
}
}
}
Output:
divide by zero
Array Index out of bound.
Finally clause:
A finally keyword is used to create block of code that follows a try block.
A finally block of code is always executed whether an exception has
occurred or not.
Finally statement that can be used to handle an exception that is not
caught any of the previous catch statements.
It may added immediately after the try block (or) after the last catch block.
Syntax:
try try
{ {
-----------; ----------;
-----------; ----------;
} }
finally catch( )
{ {
------------; ------------;
------------; -------------;
} }
catch( )
{
--------------;
--------------;
}
finally
{
------------;
------------;
}
Example:
import java.util.*;
public class FinallyException
{
public static void main(String args[])
{
try
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter a value");
int x=sc.nextInt( );
int k=44/x;
System.out.println("The val k:" +k);
}
catch(ArithematicException ae)
{
System.out.println("only non zero value");
}
catch(InputMismatch ie)
{
System.out.println("only integer value");
}
finally
{
System.out.println("finally always executed");
}
}
}
Throw Keyword:
Throw keyword is used to explicitly throw an exception from a
method of any block of code.
We can throw either checked or unchecked exception in java by
throw keyword.
The throw keyword is mainly used to throw custom exception.
We can define our own set of conditions or rules and throw an
exception explicitly using throw keyword.
Example Program
class Exceptiondemo
{
Throws Keyword:
throws is a keyword in java which is used in the signature of method to
indicate that this method might throw one of the listed type exceptions.
The caller to these methods has to handle the exception using a try-catch
block.
It is designed to transfer the responsibility of exception handling to its
caller.
Syntax:
type methodname(parameter list) throws exception_list
{
//definition of method
}
Example Program:
class ExceptionDemo
{
static void display( ) throws ArithmeticException
{
int a=3/0;
System.out.println(a);
}
public static void main(String args[])
{
try
{
display( );
}
catch(ArithmeticException ae)
{
System.out.println("cannot divide by zero");
}
System.out.println("Successfully Printed");
}
}
Output:
cannot divide by zero
successfully printed.
Multithreading
Methods Description
setName( ) To give thread a name
getName( ) Returns threads name
getPriority( ) Returns thread priority
isAlive( ) Checks if thread is still running or not
join( ) Wait for a thread to end
Example:
class Mythread extends Thread
{
public void run()
{
System.out.println("concurrent thread started running");
}
}
class MythreadDemo
{
public static void main(String args[])
{
Mythread athread= new Mythread( );
athread.start();
}
}
2) Implementing the Runnable interface:
I. Declare the class as implementing Runnable interface.
Syntax: class Mythread implements Runnable
{
--------------;
--------------;
}
II. Implement the run method this method required to implementing the
threads in our program.
Syntax: public void run( )
{
--------------;
--------------;
}
III. create a thread by defining object that is initiated from this runnable
class as a target of the thread.
syntax: Mythread mt= new Mythread( );
Thread t= new Thread(mt);
IV. Call the threads start( )method to run( ) the thread.
Syntax: t.start( );
Example:
class Mythread implements Runnable
{
public void run()
{
System.out.println("Concurrent thread started running");
}
}
class MythreadDemo
{
public static void main(String args[])
{
Mythread mt=new Mythread();
Thread t=new Thread(mt);
t.start();
}
}
NORM-PRIORITY=5
MAX-PRIORITY=10
The int Number may assume one of these constants (or) any value between
1 to 10. Default string is NORM-PRIORITY.
If thread is higher priority comes, the currently running thread will
be
preempted and move to the runnable state.
Example:
class A extends Thread
{
public void run( )
{
System.out.println(" thread A started");
for(int i=1;i<=4;i++)
{
System.out.println("\t from thread A: i=" +i);
}
System.out.println("Exit from A");
}
}
class B extends Thread
{
public void run( )
{
System.out.println(" thread B started");
for(int j=1;j<=4;j++)
{
System.out.println("\t from thread B: j=" +j);
}
System.out.println("Exit from B");
}
}
class C extends Thread
{
public void run( )
{
System.out.println(" thread C started");
for(int k=1;k<=4;k++)
{
System.out.println("\t from thread C: k=" +k);
}
System.out.println("Exit from C");
}
}
class Threadpriority
{
public static void main(String args[])
{
A threadA=new A( );
B threadB=new B( );
C threadC=new C( );
threadC.setPriority(Thread.MAX_PRIORITY);
threadB.setPriority(threadB.getPriority( ) +1);
threadA.setPriority(Thread.MIN_PRIORTY);
threadA.start();
threadB.start();
threadC.start();
System.out.println("end of the main thread");
}
}
During the life time of a thread, there are many states it can enter. They are
1. Newborn state
2. Runnable state
3. Running state
4. Blocked state
5. Dead state
Newborn state:
When we create a thread object, the thread is born and is said to be in
newborn state, the thread is not yet scheduled for running. At this state we
can do only one of the following things with in:
Runnable state:
The runnable state means that the thread is ready for execution and is
waiting for the availability of the processor. That is the thread has joined the
queue of threads that are waiting for execution. If all threads have equal
priority then they are given time slots for execution in round robin fashion
i.e first come, first serve manner. This process of assigning time to threads
is known as time slicing.
Running state:
Running means that the processor has given in time to the thread for an
execution. The thread runs until it relinquished control on its own or it is
accumulated by a higher priority thread. A running thread may relinquish in
control in one of the following situations.
2. It had been made to sleep. We can put a thread to sleep for a specified
time periods using the method sleep(time) where time is in milliseconds.
3. It has been told to wait until some event occurs. This is done using wait( )
method. The thread can be scheduled to run again using the notify( )
method.
Blocked state:
A thread is said to be blocked when it is prevented from entering into the
runnable state and subsequently the running state. This happens when the
thread is suspended, sleeping , or waiting in order to satisfy contain
requirements.
Dead state:
Every thread has a life cycle. A running thread ends in life when it has
completed executing its runs method. It is a natural death.
Q) Synchronization:
At times more than one thread try to access a shared resource, we need to
ensure that resource will be used only one thread at a time. The process by
which this is achieved is called Synchronization.
Syntax:
Synchronized(Object)
{
//statement tobesynchronized
}
class Table
{
synchronized void printtable(int n)
{
for(int i=1;i<=5;i++)
{
System.out.println(n*i);
try
{
Thread.sleep(400);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
class Mythread extends Thread{
Table t;
Mythread(Table t)
{
this.t=t;
}
public void run()
{
t.printtable(5);
}
}
class Mythread2 extends Thread
{
Table t;
Mythread(Table t)
{
this.t=t;
public void run()
{
t.printtable(100);
}
}
public class Synchronize
{
public static void main(String args[])
{
Table obj=new Table();
Mythread1 t1=new Mythread1(obj);
Mythread2 t2=new Mythread2(obj);
t1.start();
t2.start();
}
}
OUTPUT:
5
10
15
20
25
100
200
300
400
500
Q) Deadlock in JAVA:
Deadlock in java is a part of multithreading. Deadlock can occur in a situation
when a thread is waiting for an object lock, that is acquired by another thread
and second thread is waiting for an object lock that is acquiring by first thread.
Since both threads are waiting for each other to release the lock, this condition
is called deadlock.
Syntax:
ThreadA synchronized method2()
{
synchronized method1()
{
-----------------;
-----------------;
}
}
ThreadB synchronized method1()
{
-----------------;
-----------------;
}
}
APPLETS
An Applet is a Java program that runs in a web browser. An applet fully
functional Java application because it has the entire JAVA API at its disposal.
There are certain differences between Applet and JAVA Standalone Application
that are described below:
1. An applet is a Java class that extends the java.applet.Applet class.
2. 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 in web browser or a separate runtime
environment.
6. Applets have strict security rules that are enforced by the web browser.
Note: Both program must have the same name and both program must bein the
same folder.
import java.awt.*;
import java.applet.*;
public class Myfirstapplet extends Applet
{
public void paint(Graphics g)
{
g.drawString("MyFirstAppletProgram", 100, 100);
}
}
1. Save the above program:Myfirstapplet.java
2. Compile:> javac Myfirstapplet.java
//MyMyfirstapplet.html
<html>
<head> <title> Myfirstapplet</title> </head>
<body>
<applet code="Myfirstapplet.class" width="400" height="400"> </applet>
</body>
</html>
Example 2:
import java.applet.*;
import java.awt.*;
public class Myapplet extends Applet
{
{
System.out.println("start()called");
}
public void paint(Graphics g)
{
System.out.println("paint()called");
}
public void distroy()
{
System.out.println("distroy()called");
}
public void stop()
{
System.out.println("stop()called");
}
}
//Appletlifecycle.html
<body>
<applet code="Appletlifecycle.class" width="100" height="100"> </applet>
</body>
EVENT HANDLING
Event is the change in the state of the object or source. Events are
generated as result of user interaction with the graphical user
interaction components. For example, clicking on a button, moving
on a mouse, entering a character through keyboard, selecting an
item from list, scrolling the page are the activities that causes an
event to happen.
Event Handling is the mechanism that controls the event and decides
what should happen if an event occurs. This mechanism have the
code which is known as event handler that is executed when an
event occurs.
Types of events
Event Classes: Event Classes in java are the classes defined for
almost all the components that may generate events.
t wheel is moved r
WindowEvent Generated when window WindowListener
is activated, deactivated,
deiconified, iconified,
opened or closed
ComponentEvent Generated when ComponentEventLi
component is hidden, stener
moved, resized or set
visible
ContainerEvent Generated when ContainerListener
component is added or
removed from container
AdjustmentEvent Generated when AdjustmentListener
scrollbar is manipulated
FocusEvent Generated when FocusListener
component gains or
losses keyboard focus
msg="no pressed";
else
msg="You pressed undecided";
repaint();
}
public void paint(Graphics g)
{
g.drawString(msg,60,100);
}
}
Ex.html
<applet code="Ex.class" width=400 height=400>
</applet>
}
public void itemStateChanged(ItemEvent i)
{
repaint();
}
public void paint(Graphics g)
{
msg="Current state";
g.drawString(msg,6,80);
msg="banana:"+banana.getState();
g.drawString(msg,6,100);
msg="grape:"+grape.getState();
g.drawString(msg,6,120);
msg="apple:"+apple.getState();
g.drawString(msg,6,140);
}
}
Ex1.html
<applet code="Ex1.class" width=400 height=400>
</applet>
}
public void keyReleased(KeyEvent k)
{
showStatus("key released");
}
public void keyTyped(KeyEvent k)
{
msg=msg+k.getKeyChar();
repaint();
}
public void paint(Graphics g)
{
g.drawString(msg,20,40);
}
}
Ex3.html
<applet code="Ex3.class" height=300 width=300>
</applet>
How to handle the Mouse Events:
import java.awt.*;
import java.awt.event.*;
public class MouseEventex extends Frame implements
MouseListener
{
Label l;
MouseEvent()
{
addMouseListener(this);
l=new Label();
l.setBounds(20,50,100,20);
add(l);
setSize(300,300);
Smt. T. LalithaKumari Page 82
PROGRAMMING IN JAVA
setLayout(null);
setVisible(true);
}
public void mouseClicked(MouseEvent e)
{
l.setText("mouseclicked");
}
public void mouseEntered(MouseEvent e)
{
l.setText("mouse entered");
}
public void mouseReleased(MouseEvent e)
{
l.setText("mouseReleased");
}
public static void main(String args[])
{
new MouseEvent();
}
import java.awt.*;
class Frameex1
{
public static void main(String args[])
{
Frame f = new Frame("Layout");
f.setSize(400,600);
f.setVisible(true);
}
}
Components:
Following some components of Java AWT are explained:
Syntax:
Label label_name = new Label("This is the label text");
Syntax:
Button button_name = new Button("This is the label button");
Syntax:
Checkbox checkbox_name = new checkbox("Optional check box1,"
false);
You can also see and get the state of the checkbox using the set state
(boolean) and getState() method provided by the checkbox class.
Syntax:
CheckboxGroup chkgp = new CheckboxGroup();
add(new Checkbox("One", chkgp, false);
add(new Checkbox("Two", chkgp, false);
add(new Checkbox("Three",chkgp, false);
Text Field: This is also the text container component of Java AWT
package. This component contains single line and limited text
information.
Syntax:
TextField txtfield = new TextField(20);
Creation of panel
import java.awt.*;
class Ex2
{
public static void main(String args[])
{
Frame f;
Panel p;
f=new Frame("I am frame with panel");
p= new Panel();
f.add(p);
f.setSize(400,600);
f.setVisible(true);
}
}
import java.awt.*;
class Labeltext
{
import java.awt.*;
class Buttoncheck
{
public static void main(String args[])
{
Frame f=new Frame("ComponentsFrame");
Button b1=new Button("Hai");
Button b2=new Button("Hello");
Label lb1=new Label("What do you plays:");
Checkbox c1= new Checkbox("Cricket",false);
Checkbox c2= new Checkbox("Chess",false);
Checkbox c3= new Checkbox("Football",false);
f.setLayout(new FlowLayout());
f.add(b1);
Smt. T. LalithaKumari Page 87
PROGRAMMING IN JAVA
f.add(b2);
f.add(lb1);
f.add(c1);
f.add(c2);
f.add(c3);
f.setSize(500,500);
f.show();
}
}
import java.awt.*;
class Option
{
public static void main(String args[])
{
Frame f=new Frame("ComponentsFrame");
Label lb1=new Label("Select What is your Mother Tongue:");
CheckboxGroup cg=new CheckboxGroup();
Checkbox o1= new Checkbox("Telugu",cg,true);
Checkbox o2= new Checkbox("English",cg,false);
Checkbox o3= new Checkbox("Hindi",cg,false);
Checkbox o4= new Checkbox("Tamil",cg,false);
f.setLayout(new FlowLayout());
f.add(lb1);
f.add(o1);
f.add(o2);
f.add(o3);
f.add(o4);
f.setSize(500,500);
f.show();
}
Flow Layout:
This layout is used to arrange the GUI components in a
sequential flow(that means one after another in horizontal way).
Default layout manager.
You can also set flow layout of components like flow from left,
flow from right. Default alignment will be center.
Syntax:
Frame f = new Frame();
f.setLayout(new FlowLayout());
Program:
import java.awt.*;
class FlowLayoutex
{
public static void main(String args[])
{
Frame f = new Frame("Layout");
String s[] = {"1","2","3","4","5","6","7","8","9"};
Button b[] = new Button[s.length];
f.setLayout(new FlowLayout());
for(int i=0;i<s.length;i++)
{
b[i] = new Button(s[i]);
f.add(b[i]);
}
f.setSize(500,500);
f.show();
Smt. T. LalithaKumari Page 89
PROGRAMMING IN JAVA
}
}
OUTPUT
Border Layout:
This Layout is used to arrange the GUI components in S directions of
frame.
Used for placement of components in Geographical direction.
Takes two arguments:
position of component within layout
specifies the component
Syntax:
Frame f = new Frame();
f.setLayout(new BorderLayout());
Program:
import java.awt.*;
class BorderLayoutex
{
public static void main(String args[])
{
Frame f = new Frame("Layout");
Button b[];
String border[] = {"East","West","North","South","Center"};
String s[] = {"1","2","3","4","5"};
f.setLayout(new BorderLayout());
b= new Button[s.length];
for(int i=0;i<s.length;i++)
{
b[i] = new Button(s[i]);
f.add(border[i],b[i]);
}
f.setSize(500,500);
f.show();
}
}
output:
Grid Layout:
This layout is used to arrange the GUI components in the table
format. In Grid layout all elements are in same.
Syntax:
Frame f = new Frame();
f.setLayout(new GridLayout(n,n));
Gridbag Layout:
Card Layout:
This layout is used to arrange multiple cards within the same
frame. It used to produce slide show components. Different panels
can be added at a time only one can be displayed at a time.Few
buttons can be set to native b/w different cards.
native buttons different cards: show()
first()
last()
next()
JPanel – A panel is an instance of JPanel. A frame can have more than one
panels and each panel can have several components. You can also call them
parts of Frame. Panels are useful for grouping components and placing them to
appropriate locations in a frame.
JTextField – Used for capturing user inputs, these are the text boxes where
user enters the data.
JPasswordField – Similar to text fields but the entered data gets hidden and
displayed as dots on GUI.
Q)Components in Swings:
Container classes are classes that can have other components on it. So for
creating a GUI, we need at least one container object. There are 3 types of
containers.
import javax.swing.*;
class gui{
public static void main(String args[]){
JFrame frame = new JFrame("My First GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300,300);
JButton button = new JButton("Press");
frame.getContentPane().add(button); // Adds Button to content pane of
frame
frame.setVisible(true);
}
}
import javax.swing.*;
class gui{
public static void main(String args[]){
JFrame frame = new JFrame("My First GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300,300);
JButton button1 = new JButton("Press");
frame.getContentPane().add(button1);
frame.setVisible(true);
}
}
Step 5) How about adding two buttons? Copy the following code into an editor.
import javax.swing.*;
class gui{
public static void main(String args[]){
JFrame frame = new JFrame("My First GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300,300);
JButton button1 = new JButton("Button 1");
JButton button2 = new JButton("Button 2");
frame.getContentPane().add(button1);
frame.getContentPane().add(button2);
frame.setVisible(true);
}
}
The Layout manager is used to layout (or arrange) the GUI java components
inside a container.There are many layout managers, but the most frequently
used are-
Java BorderLayout
Java FlowLayout
FlowLayout is the default layout manager for every JPanel. It simply lays out
components in a single row one after the other.
Java GridBagLayout
12.DATABASE HANDLING
JAVA JDBC:
Java JDBC is a Java API to connect and execute query with the database. JDBC
API used JDBC drivers to connect with the database.
We can use JDBC API to access tabular data stored into any relational
database.
Before JDBC, ODBC API was the database API to connect and
execute query with the database. But, ODBC API used 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 JDBCAPI to database using Java program and can perform
following activities:
Note: 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:
o easy to use.
o can be easily connected to any database.
o It is a database independent driver
o No need to install separately (This driver software is built-in with JDK).
Disadvantages:
o Performance degraded because JDBC method call is converted into the
ODBC function calls.
o The ODBC driver needs to be installed on the client machine.
o It is slow driver so not used in real time applications.
Advantage:
o performance upgraded than JDBC-ODBC bridge driver.
Disadvantage:
o The Native driver needs to be installed on the each client machine.
o The Vendor client library needs to be installed on client machine.
The Network Protocol driver uses middleware (application server) that converts
JDBC calls directly or indirectly into the vendor-specific database protocol. It is
fully written in java.
Advantage:
o No client side library is required because of application server that can
perform many tasks like auditing, load balancing, logging etc.
Disadvantages:
o Network support is required on client machine.
4) Thin driver
The thin driver converts JDBC calls directly into the vendor-specific
database protocol. That is why it is known as thin driver. It is fully
written in Java language.
Advantage:
o Better performance than all other drivers.
o No software is required at client side or server side.
Disadvantage:
o Drivers depend on the Database.
JDBC CONNECTIVITY
There are 5 steps to connect any java application with the database using
JDBC. These steps are as follows:
o Register the Driver class
o Create connection
o Create statement
o Execute queries
o Close connection
Note: Since JDBC 4.0, explicitly registering the driver is optional. We just need to
put vender's Jar in the classpath, and then JDBC driver manager can detect and
load the driver automatically.
Example
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","password");
Syntax
public Statement createStatement()throws SQLException
Example
Statement stmt=con.createStatement();
Syntax
public ResultSet executeQuery(String sql)throws SQLException
Example
ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next()){
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}
Syntax
public void close()throws SQLException
Example
con.close();
Create a Table
create table emp(id number(10),name varchar2(40),age number(3));
import java.sql.*;
class OracleCon{
public static void main(String args[]){
try{
//step1 load the driver class
Class.forName("oracle.jdbc.driver.OracleDriver");
//step2 create the connection object
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
//step3 create the statement object
Statement stmt=con.createStatement();
//step4 execute query
ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));
//step5 close the connection object
con.close();
}catch(Exception e){ System.out.println(e);}
}
}