Sei sulla pagina 1di 97

Practical File
Of

Programming in Java
Submitted by

Aakash Raj

in partial fulfillment for the award of the degree


of

Bachelor of technology
At

Guru Nanak Dev Engineering College


Ludhiana
NOVEMBER & 2017

Signature of the Internal Examiner: Signature of the External Examiner:

Date: Date:
INDEX

S.No Objective Page No Signature

1 Handling various data types 1

2 Type casting 6

3 Arrays – 1D and 2 D 8

4 Various control structures 10

5 Various decision structures 13

6 Recursion 15

7 Method Overloading by passing 16


objects as arguments
8 Constructor Overloading by passing 17
objects as arguments
9 Various access control and usage of 18
static, final and finalize ( )
10 Command line arguments 21

11 Various types of inheritance by 22


applying various access controls to
its data members and methods
12 Method overriding 26

13 Abstract class 29
14 Nested class 30

15 Constructor chaining 33

16 Importing classes from user defined 35


package and creating packages
using access protection

17 Interfaces, nested interfaces and use 37


of extending interfaces

18 Exception Handling - using 39


predefined exception

19 Exception Handling - creating user 40


defined exceptions

20 Multithreading by extending Thread 42


Class
21 Multithreading by implementing 43
Runnable Interface

22 Thread life cycle 44

23 Applet life cycle 46

24 Applet for configuring Applets by 48


passing parameters

25 Event Handling 49

26 Reading and writing from a particular 51


file
27 Database connectivity for various 53
DDL and DML operations

28 String class and its methods 62

29 StringBuffer class and its methods 64


30 Without using inbuilt features of Java 66
implement following concepts related
to Data Structures:
a Stack 66
b Queue 67
c LinkList 69
d Quicksort 70
31 Implement following concepts related 72
to Digital Electronics:
a Octal to Hexadecimal ,Decimal, 72
Binary
b Convert Gray code to Binary 74
c Half Adder 75
d Full Adder 77
32 Implement following concepts related 79
to Operating Systems:

a First come first serve scheduling 79


algorithm
b Shortest job first 80
c Condition for Occurrence of deadlock 82
d  Multithreading approach to do Matrix 84
multiplication
33 Implement following concepts related 86
to Computer Networks:

a Sliding window sender 86


b Sliding window receiver 87
c To create a program for the 88
implementation of ARP(Address
Resolution Protocol Protocol)
d To create a program for the 90
implementation of RARP (Reverse
Address Resolution Protocol)
University Roll No 1507884

1. Handling various data types


A. Byte
a. Byte data type is a 8-bit signed two's complement integer
b. Minimum value is : -128 (-2^7)
c. Maximum value is : 127 (inclusive)(2^7 -1)
d. Default value is : 0
e. Byte data type is used to save space in large arrays, mainly in place of integers, since
a byte is four times smaller than an int
Program
class DataType_Byte {

byte a = 50;
byte b = (byte) -80;

void add() {

byte c = (byte) (a + b);

System.out.println("The Byte Value is : " + c);


}
}

class MainClass {

public static void main(String args[]) {

DataType_Byte obj = new DataType_Byte();

obj.add();
}
}
output

B. Short
a. Short data type is a 16-bit signed two's complement integer
b. Minimum value is : -32,768 (-2^15)
c. Maximum value is : 32,767(inclusive) (2^15 -1)
d. Default value is : 0
e. Short data type can also be used to save memory as byte data type. A short is 2 times
smaller than an int
Program
class DataType_Short {
short a = 1000;
Page No 1
University Roll No 1507884
short b = -1500;
void add() {
short c = (short) (a + b);
System.out.println("The Short Value is : " + c);
}
}
class MainClass1 {
public static void main(String args[]) {
DataType_Short obj = new DataType_Short();
obj.add();
}
}
output

C. Int
a. Int data type is a 32-bit signed two's complement integer
b. Minimum value is : -2,147,483,648.(-2^31)
c. Maximum value is : 2,147,483,647(inclusive).(2^31 -1)
d. Default value is : 0
e. Int is generally used as the default data type for integral values unless there is a
concern about memory
Program
class DataType_Int {
int a = 15000;
int b = -20000;
void add() {
int c = a + b;
System.out.println("The int Value is : " + c);
}
}
class MainClass2 {
public static void main(String args[]) {
DataType_Int obj = new DataType_Int();
obj.add();
}
}
output

Page No 2
University Roll No 1507884
D. Long
a. Long data type is a 64-bit signed two's complement integer
b. Minimum value is : -9,223,372,036,854,775,808.(-2^63)
c. Maximum value is : 9,223,372,036,854,775,807 (inclusive). (2^63 -1)
d. Default value is : 0L
e. This type is used when a wider range than int is needed
Program
class DataType_Long {
long a = 1000L;
long b = -2000L;
void add() {
long c = a + b;
System.out.println("The Long Value is : " + c);
}
}
class MainClass3 {
public static void main(String args[]) {
DataType_Long obj = new DataType_Long();
obj.add();
}
}
output

E. Float
a. Float data type is a single-precision 32-bit IEEE 754 floating point
b. Default value is : 0.0f
c. Float data type is never used for precise values such as currency
d. Float is mainly used to save memory in large arrays of floating point numbers
Program
class DataType_Float {
float a = (float) 10.56;
float b = (float) -23.57;
void add() {
float c = a + b;
System.out.println("The Float Vaue is : " + c);
}
}
class MainClass4 {
public static void main(String args[]) {
DataType_Float obj = new DataType_Float();
obj.add();
}
}

Page No 3
University Roll No 1507884

output

F. Double
a. double data type is a double-precision 64-bit IEEE 754 floating point
b. Default value is : 0.0d
c. Double data type should never be used for precise values such as currency
d. This data type is generally used as the default data type for decimal values. generally
the default choice
Program
class DataType_Double {
double a = 123.456;
double b = -45.894;
void add() {
double c = a + b;
System.out.println("The Double Value is : " + c);
}
}
class MainClass5 {
public static void main(String args[]) {
DataType_Double obj = new DataType_Double();
obj.add();
}
}
output

G. Boolean
a. boolean data type represents one bit of information
b. There are only two possible values : true and false
c. This data type is used for simple flags that track true/false conditions
d. Default value is : false
Program
class DataType_Boolean {
boolean a = true;
void check() {
if(a == true) {
a = false;
System.out.println("The Boolean Value is : " + a);
Page No 4
University Roll No 1507884
}
}
}
class MainClass6 {
public static void main(String args[]) {
DataType_Boolean obj = new DataType_Boolean();
obj.check();
}
}
output

H. Char
a. char data type is a single 16-bit Unicode character
b. Minimum value is : '\u0000' (or 0)
c. Maximum value is : '\uffff' (or 65,535 inclusive)
d. Char data type is used to store any character
Program
class DataType_Char {
char a = 'J';
char b = 'A';
char c = 'V';
char d = 'A';
void join() {
System.out.println("The Characters Value is : " + a+b+c+d);
}
}
class MainClass7 {
public static void main(String args[]) {
DataType_Char obj = new DataType_Char();
obj.join();
}
}
output

Page No 5
University Roll No 1507884

2. Type casting
Type conversion is automatically done if the types are compatible and source type is smaller than
destination type. But when destination type is smaller than source type, then we need to explicitly
cast it. This is called as 'Type Casting'. This is also called narrowing conversion and truncation.
A cast is an explicit type conversion.
Int to Byte Conversion
Program
class IntToByteConversion
{
public static void main(String arg[])
{
int a = 350;
byte b;

b = (byte) a;

System.out.println("b = " + b );

}
}
output

DESCRIPTION
When a value of larger size in the 350 is casted into a byte whose range is -128 to 127, it is
narrowed down to fit into that range. So the value becomes 94 from 350. 

We need to be careful with this kind of conversion, since if the destination type range can not store
the source value it is shortened and possibly loses the data.
Data type casting
Program
class DatatypeCasting
{
public static void main(String arg[])
{
byte b;
int i = 81;
double d = 323.142;
float f = 72.38f;
char c = 'A';
c = (char) i;
System.out.println("i = " + i + " c = " + c);
i = (int) d; // LINE A
System.out.println("d = " + d + " i = " + i);
i = (int) f; // LINE C
System.out.println("f = " + f + " i = " + i);

Page No 6
University Roll No 1507884
b = (byte) d;
System.out.println("d = " + d + " b = " + b);

}
}
output

DESCRIPTION
When i is casted to c the value corresponding to the ascii code of 81 which is 'Q' is assigned. 

When d is casted to i the decimal part .142 is truncated and only 323 is assigned to i. 

Similarly when f is casted to i, the decimal part .38 is truncated and only 72 is assigned to i. 

When d is casted to b whose range is -128 to 127, not only the decimal part .142 is truncated but it
is also shortened from 323 to 67 so as to fit in byte range.

Page No 7
University Roll No 1507884

3. Arrays – 1D and 2 D
One Dimensional Array Program
To print one dimensional array in Java Programming you have to use only one for loop as shown in
the following program.
Java Programming Code on One Dimensional (1D) Array
Following Java Program ask to the user to enter the array size and then ask to enter the element of
the array to store the elements in the array, then finally display the array elements on the screen:
Program
import java.util.Scanner;
public class JavaProgram
{
public static void main(String args[])
{
int arr[] = new int[50];
int n, i;
Scanner scan = new Scanner(System.in);
System.out.print("How Many Element You Want to Store in Array ? ");
n = scan.nextInt();
System.out.print("Enter " + n + " Element to Store in Array : ");
for(i=0; i<n; i++)
{
arr[i] = scan.nextInt();
}
System.out.print("Elements in Array is :\n");
for(i=0; i<n; i++)
{
System.out.print(arr[i] + " ");
}

}
}
output

Two Dimensional Array Program


Two dimensional array can be made in Java Programming language by using the two loops, the first
one is outer loop and the second one is inner loop. Outer loop is responsible for rows and the inner
loop is responsible for columns. And both rows and columns combine to make two-dimensional
(2D) Arrays.
Page No 8
University Roll No 1507884
Java Programming Code for Two Dimensional (2D) Array
Following Java Program ask to the user to enter row and column size of the array then ask to the
user to enter the array elements, and the program will display the two dimensional array:
Program
import java.util.Scanner;
public class JavaProgram1
{
public static void main(String args[])
{
int row, col, i, j;
int arr[][] = new int[10][10];
Scanner scan = new Scanner(System.in);
System.out.print("Enter Number of Row for Array (max 10) : ");
row = scan.nextInt();
System.out.print("Enter Number of Column for Array (max 10) : ");
col = scan.nextInt();
System.out.print("Enter " +(row*col)+ " Array Elements : ");
for(i=0; i<row; i++)
{
for(j=0; j<col; j++)
{
arr[i][j] = scan.nextInt();
}
}
System.out.print("The Array is :\n");
for(i=0; i<row; i++)
{
for(j=0; j<col; j++)
{
System.out.print(arr[i][j]+ " ");
}
System.out.println();
}
}
}
output

Page No 9
University Roll No 1507884

4. Various control structures


Java Control Structure & Looping structure explained with examples.
• java if... else statement
• java switch case
• java while loop
• java for loop
• java do....while loop
• java break statement
• java continue statement.

If-else statement
The if-else statement tests the result of a condition, and perform appropriate action based on result.
Program
class CheckNumber{
public static void main(String args[]){
int num = 10;
if (num % 2 == 0){
System.out.println(num + " is even number" );
} else {
System.out.println(num + " is odd number" );
}
}
}
output

switch-case statement
switch-case can be used as an alternative for if-else condition. If the programmer has to make
number of decisions, and all the decisions depend on the value of variable, then switch-case is used
instead of if-else condition.
Example :
int month = 1;
String name;
switch (month) {
case 1:
name = “January”;
break;
case 2:
name=”February”;
break;
.
.
default:
name=”Invalid Month”;

Page No 10
University Roll No 1507884
}
While Loop
The while loop executes till condition is specified. It executes the steps mentioned in the loop only
if the condition is true. This is useful where programmer doesn't know in advance that how many
times the loop will be executed.
Example :
int i = 1;
while(i<=5){
i++;
System.out.println(“value of i is : “+i);
}
do-while loop
The do-while loops execute certain statements till the specified condition is true. This loop ensures
that the loop body is executed atleast once.
Example :
int j = 8;
do{
j = j+2;
System.out.println(“value of j is : “ +j);
}while(j>=10 && j<=50){
j = j+5;
System.out.println(“value of j is : “ +j);
}
for loop
All loops have some common feature: a counter variable that is initialized before the loop begins.
The for loop provides the feature that, initialized the variable before loop begins, a condition for
counter variable and counter upto which loop lasts.
Example :
for(int i=1;i<=10;i++){
System.out.println(“Value of i is “ +i);
}
break statement
The break statements are used to,
- Terminate a statement sequence in a switch statement
- Exit a loop
Example :
class BreakExample{
public static void main(String args[]){
for(int count=1;count<=100;count++;{
if(count==10){
break;
}
System.out.println(“The value of num is : “ +count);
}
System.out.println(“Outside loop“);
}
}

Page No 11
University Roll No 1507884

continue statement
Sometimes the programmer might want to continue a loop, but stop processing the remainder of the
code in its body for a particular iteration. The continue statement can be used for such a scenario. In
while and do-while loops, a continue statement can be used, as shown in below example.
Example :
class ContinueDemo{
public static void main(String args[]){
for(int count = 1; count <= 10; count++){
System.out.println(“Value of count before : +count);
if(count%2==0){
continue;
}
System.out.println(“Value of count after : “+count);
}
}
}

Page No 12
University Roll No 1507884

5. Various decision structures


All programming languages allow you to perform certain actions based on decisions that need to be
made. In Java we use If and Switchstatements to check conditions and decide what to do.

If Statements
If the Boolean expression evaluates to true then the block of code inside the if statement will be
executed. If not, the first set of code after the end of the if statement (after the closing curly brace)
will be executed.
Program
class Test {

public static void main(String args[]) {


int x = 10;

if( x < 20 ) {
System.out.print("This is if statement");
}
}
}
output

Switch Statements
A switch statement allows a variable to be tested for equality against a list of values. Each value is
called a case, and the variable being switched on is checked for each case.
Program
class Test1 {
public static void main(String args[]) {
// char grade = args[0].charAt(0);
char grade = 'C';
switch(grade) {
case 'A' :
System.out.println("Excellent!");
break;
case 'B' :
case 'C' :
System.out.println("Well done");
break;
case 'D' :
System.out.println("You passed");
case 'F' :
System.out.println("Better try again");

Page No 13
University Roll No 1507884
break;
default :
System.out.println("Invalid grade");
}
System.out.println("Your grade is " + grade);
}
}
output

Page No 14
University Roll No 1507884

6. Recursion
Recursion in java is a process in which a method calls itself continuously. A method in java that
calls itself is called recursive method.
Java Recursion Example 1: Factorial Number
Program
class RecursionExample3 {
static int factorial(int n){
if (n == 1)
return 1;
else
return(n * factorial(n-1));
}
public static void main(String[] args) {
System.out.println("Factorial of 5 is: "+factorial(5));
}
}
output

Java Recursion Example 2: Fibonacci Series


Program
class RecursionExample4 {
static int n1=0,n2=1,n3=0;
static void printFibo(int count){
if(count>0){
n3 = n1 + n2;
n1 = n2;
n2 = n3;
System.out.print(" "+n3);
printFibo(count-1);
}
}
public static void main(String[] args) {
int count=15;
System.out.print(n1+" "+n2);//printing 0 and 1
printFibo(count-2);//n-2 because 2 numbers are already printed
}
}
output

Page No 15
University Roll No 1507884

7. Method Overloading by passing objects as


arguments.
This example displays the way of overloading a method depending on type and number of
parameters.
Program
class MyClass {
int height;
MyClass() {
System.out.println("bricks");
height = 0;
}
MyClass(int i) {
System.out.println("Building new House that is " + i + " feet tall");
height = i;
}
void info() {
System.out.println("House is " + height + " feet tall");
}
void info(String s) {
System.out.println(s + ": House is " + height + " feet tall");
}
}
public class MainClass {
public static void main(String[] args) {
MyClass t = new MyClass(0);
t.info();
t.info("overloaded method");

//Overloaded constructor:
new MyClass();
}
}
output

Page No 16
University Roll No 1507884

8. Constructor Overloading by passing objects as


arguments
Program
class Rectangle {
int length ;
int breadth ;
Rectangle() {
System.out.println("Constructor with Zero Parameter Called ");
length = breadth = 0 ;
}
Rectangle(int side)
{
System.out.println("Constructor with One Parameter Called");
length = breadth = side ;
}
Rectangle(int l,int b)
{
System.out.println("Constructor with Two Parameters Called");
length = l ;
breadth = b ;
}
int area() {
return (length * breadth) ;
}
}
class ConstructorOverloading
{
public static void main(String[] args)
{
Rectangle r1 = new Rectangle(); //const. with 0-parameter called
Rectangle r2 = new Rectangle(5); //const with l parameter called
Rectangle r3 = new Rectangle(7,8); //const.with2 parameter called
System.out.println("Area of First Rectangle is : "+ r1.area( ));
System.out. println("Area of Square is : "+ r2.area( ));
System.out.println("Area of Second Rectangle is : "+ r3.area( ));
}
}

Page No 17
University Roll No 1507884
output
9. Various access control and usage of static, final and
finalize ( )
JAVA ACCESS CONTROL :
One can control what parts of a program can access the member of a class. By controlling access,
one can prevent misuse.For Example, allowing access to data only through a well-defined set of
methods, one can prevent misuse of that data. Thus, when correctly implemented, a class creates
“black box”.
How a member can be accessed is determined by the access specifier that modifies its declaration.
Java provides a set to access specifiers. Some aspects of access control are related to inheritance or
packages.
Java’s access specifiers are:
public:
1. When a member of a class is specified by the public specifier, then that member can be
accessed by any other code.
2. The public modifier makes a method or variable completely available to all classes.
3. Also when the class is defined as public, it can be accessed by any other class.
private:
1. To hide a method or variable from other classes, private modifier is used.
2. A private variable can be used by methods in it’s own class but not by objects of any other
class.
3. Neither private variables nor private methods are inherited by subclass.
4. The only place these variables and methods can be seen is from within their own class.
protected:
1. protected applies only when inheritance is involved.
2. If you want to allow an element to be seen outside your current package, but only to classes that
are inherited from your class directly, then declare that element as protected.
default:
1. We have seen that when no access control modifier is specified, it is called as default access.
2. Classes written like this are not accessible in other package.
3. Any variable declared without a modifier can be read or changed by any other class in the same
package.
4. Any method declared the same way can be called by any other class in the same package.
5. When a member does not have an explicit access specification,
6. it is visible to subclasses as well as to other classes in the same package.
The following table summarizes the levels of access control.
Access Public Protected Default Private
From the same class Yes Yes Yes Yes
From any class in the same package Yes Yes Yes No
From any class outside the package Yes No No No
From a sub –  class in the same package Yes Yes Yes No
From a sub –  class outside the same package Yes Yes Yes No

Page No 18
University Roll No 1507884

static
The static keyword in java is used for memory management mainly. We can apply java static
keyword with variables, methods, blocks and nested class. The static keyword belongs to the class
than instance of the class.

Program
class Test
{
// static method
static void m1()
{
System.out.println("from m1");
}

public static void main(String[] args)


{
// calling m1 without creating
// any object of class Test
m1();
}
}

output

final
Final is used to apply restrictions on class, method and variable. Final class can't be inherited, final
method can't be overridden and final variable value can't be changed.

Program
class FinalExample{
public static void main(String[] args){
final int x=100;
x=200;//Compile Time Error
}}
output

Page No 19
University Roll No 1507884
finalize ( )
Finalize is used to perform clean up processing just before object is garbage collected.

Program
class FinalizeExample
{
public void finalize(){System.out.println("finalize called”);
}
public static void main(String[] args)
{
FinalizeExample f1=new FinalizeExample();
FinalizeExample f2=new FinalizeExample();
f1=null;
f2=null;
System.gc();
}
}

output

Page No 20
University Roll No 1507884

10. Command line arguments


The command line argument is the argument passed to a program at the time when you run it. To
access the command-line argument inside a java program is quite easy, they are stored as string
in String array passed to the args parameter of main() method.

Program

class Cmd
{
public static void main(String[] args)
{
for(int i=0;i< args.length;i++)
{
System.out.println(args[i]);
}
}
}

output

Page No 21
University Roll No 1507884

11. Various types of inheritance by applying various


access controls to its data members and methods.
Inheritance in java is a mechanism in which one object acquires all the properties and behaviors of
parent object.
Types of inheritance
1. Single Inheritance
Single Inheritance is the simple inheritance of all, When a class extends another class(Only one
class) then we call it as Single inheritance. The below diagram represents the single inheritance in
java where Class B extends only one class Class A. Here Class B will be the Sub class and Class
A will be one and only Super class.

Single Inheritance Example


Program
class ClassA
{
public void dispA()
{
System.out.println("disp() method of ClassA");
}
}
public class ClassB extends ClassA
{
public void dispB()
{
System.out.println("disp() method of ClassB");
}
public static void main(String args[])
{
//Assigning ClassB object to ClassB reference
ClassB b = new ClassB();
//call dispA() method of ClassA
b.dispA();
//call dispB() method of ClassB
b.dispB();
}
}
output

Page No 22
University Roll No 1507884
2. Multilevel Inheritance
In Multilevel Inheritance a derived class will be inheriting a parent class and as well as the derived
class act as the parent class to other class. As seen in the below diagram. ClassB inherits the
property of ClassA and again ClassB act as a parent for ClassC. In Short ClassA parent
for ClassB and ClassB parent for ClassC.
MultiLevel Inheritance Example

Program
class ClassA
{
public void dispA()
{
System.out.println("disp() method of ClassA");
}
}
class ClassB extends ClassA
{
public void dispB()
{
System.out.println("disp() method of ClassB");
}
}
public class ClassC extends ClassB
{
public void dispC()
{
System.out.println("disp() method of ClassC");
}
public static void main(String args[])
{
//Assigning ClassC object to ClassC reference
ClassC c = new ClassC();
//call dispA() method of ClassA
c.dispA();
//call dispB() method of ClassB
c.dispB();
//call dispC() method of ClassC
c.dispC();
}
}

output

Page No 23
University Roll No 1507884
3. Hierarchical Inheritance
In Hierarchical inheritance one parent class will be inherited by many sub classes. As per the below
example ClassA will be inherited by ClassB, ClassC and ClassD. ClassA will be acting as a parent
class for ClassB, ClassC and ClassD.

Hierarchical Inheritance Example


Program
class ClassA
{
public void dispA()
{
System.out.println("disp() method of ClassA");
}
}
class ClassB extends ClassA
{
public void dispB()
{
System.out.println("disp() method of ClassB");
}
}
class ClassC extends ClassA
{
public void dispC()
{
System.out.println("disp() method of ClassC");
}
}
class ClassD extends ClassA
{
public void dispD()
{
System.out.println("disp() method of ClassD");
}
}
public class HierarchicalInheritanceTest
{
public static void main(String args[])
{
//Assigning ClassB object to ClassB reference

Page No 24
University Roll No 1507884
ClassB b = new ClassB();
//call dispB() method of ClassB
b.dispB();
//call dispA() method of ClassA
b.dispA();
//Assigning ClassC object to ClassC reference
ClassC c = new ClassC();
//call dispC() method of ClassC
c.dispC();
//call dispA() method of ClassA
c.dispA();
//Assigning ClassD object to ClassD reference
ClassD d = new ClassD();
//call dispD() method of ClassD
d.dispD();
//call dispA() method of ClassA
d.dispA();
}
}

output

Page No 25
University Roll No 1507884

12. Method overriding


If subclass (child class) has the same method as declared in the parent class, it is known as method
overriding in java.
Rules for Java Method Overriding
1. method must have same name as in the parent class
2. method must have same parameter as in the parent class.
3. must be IS-A relationship (inheritance).
Understanding the problem without method overriding
Let's understand the problem that we may face in the program if we don't use method overriding.

Program
class Vehicle{
void run(){System.out.println("Vehicle is running");}
}
class Bike extends Vehicle{

public static void main(String args[]){


Bike obj = new Bike();
obj.run();
}
}

output

Example of method overriding


In this example, we have defined the run method in the subclass as defined in the parent class but it
has some specific implementation. The name and parameter of the method is same and there is IS-A
relationship between the classes, so there is method overriding.

Program
class Vehicle1{
void run(){System.out.println("Vehicle is running");}
}
class Bike2 extends Vehicle1{
void run(){System.out.println("Bike is running safely");}

public static void main(String args[]){


Bike2 obj = new Bike2();
obj.run();
}
}

Page No 26
University Roll No 1507884

output

Real example of Java Method Overriding


Consider a scenario, Bank is a class that provides functionality to get rate of interest. But, rate of
interest varies according to banks. For example, SBI, ICICI and AXIS banks could provide 8%, 7%
and 9% rate of interest.

Program
class Bank{
int getRateOfInterest(){return 0;}
}
class SBI extends Bank{
int getRateOfInterest(){return 8;}
}
class ICICI extends Bank{
int getRateOfInterest(){return 7;}
}
class AXIS extends Bank{
int getRateOfInterest(){return 9;}
}
class Test2{
public static void main(String args[]){
SBI s=new SBI();
ICICI i=new ICICI();
AXIS a=new AXIS();
System.out.println("SBI Rate of Interest: "+s.getRateOfInterest());
System.out.println("ICICI Rate of Interest: "+i.getRateOfInterest());
System.out.println("AXIS Rate of Interest: "+a.getRateOfInterest());
}

Page No 27
University Roll No 1507884
}
output

Page No 28
University Roll No 1507884

13. Abstract class


A class that is declared with abstract keyword, is known as abstract class in java. It can have
abstract and non-abstract methods (method with body).
Before learning java abstract class, let's understand the abstraction in java first.
Abstraction is a process of hiding the implementation details and showing only functionality to the
user.
Another way, it shows only important things to the user and hides the internal details for example
sending sms, you just type the text and send the message. You don't know the internal processing
about the message delivery.
Abstraction lets you focus on what the object does instead of how it does it.

Example of abstract class in java


Program
abstract class Bank{
abstract int getRateOfInterest();
}
class SBI extends Bank{
int getRateOfInterest(){return 7;}
}
class PNB extends Bank{
int getRateOfInterest(){return 8;}
}
class TestBank{
public static void main(String args[]){
Bank b;
b=new SBI();
System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");
b=new PNB();
System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");
}
}

output

Page No 29
University Roll No 1507884

14. Nested class


A class defined within another class is known as Nested class. The scope of the nested class is
bounded by the scope of its enclosing class.

Static nested classes


As with class methods and variables, a static nested class is associated with its outer class. And like
static class methods, a static nested class cannot refer directly to instance variables or methods
defined in its enclosing class: it can use them only through an object reference.
For example, to create an object for the static nested class, use this syntax:
Program
class OuterClass
{
// static member
static int outer_x = 10;
// instance(non-static) member
int outer_y = 20;
// private member
private static int outer_private = 30;
// static nested class
static class StaticNestedClass
{
void display()
{
// can access static member of outer class
System.out.println("outer_x = " + outer_x);

// can access display private static member of outer class


System.out.println("outer_private = " + outer_private);

// The following statement will give compilation error


// as static nested class cannot directly access non-static membera
// System.out.println("outer_y = " + outer_y);

}
}
}
// Driver class
class StaticNestedClassDemo
{
public static void main(String[] args)

Page No 30
University Roll No 1507884
{
// accessing a static nested class
OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass();
nestedObject.display();
}
}
output

Inner classes
To instantiate an inner class, you must first instantiate the outer class. Then, create the inner object
within the outer object with this syntax:
Program
class OuterClass
{
// static member
static int outer_x = 10;
// instance(non-static) member
int outer_y = 20;
// private member
private int outer_private = 30;

// inner class
class InnerClass
{
void display()
{
// can access static member of outer class
System.out.println("outer_x = " + outer_x);

// can also access non-static member of outer class


System.out.println("outer_y = " + outer_y);

// can also access private member of outer class


System.out.println("outer_private = " + outer_private);

}
}
}
// Driver class
public class InnerClassDemo
{
Page No 31
University Roll No 1507884
public static void main(String[] args)
{
// accessing an inner class
OuterClass outerObject = new OuterClass();
OuterClass.InnerClass innerObject = outerObject.new InnerClass();
innerObject.display();
}
}
output

Page No 32
University Roll No 1507884

15. Constructor chaining


Constructor chaining is the process of calling one constructor from another constructor with respect
to current object.

Constructor chaining can be done in two ways:
1. Within same class: It can be done using this() keyword for constructors in same class
2. From base class: by using super() keyword to call constructor from the base class.
Constructor Chaining within same class using this() keyword :
Program
class Temp
{
// default constructor 1
// default constructor will call another constructor
// using this keyword from same class
Temp()
{
// calls constructor 2
this(5);
System.out.println("The Default constructor");
}
// parameterized constructor 2
Temp(int x)
{
// calls constructor 3
this(5, 15);
System.out.println(x);
}
// parameterized constructor 3
Temp(int x, int y)
{
System.out.println(x * y);
}
public static void main(String args[])
{
// invokes default constructor first
new Temp();
}
}
output

Page No 33
University Roll No 1507884

Constructor Chaining to other class using super() keyword :


Program
class Base{
String name;
// constructor 1
Base() {
this("");
System.out.println("No-argument constructor of" +
" base class");
}
// constructor 2
Base(String name)
{
this.name = name;
System.out.println("Calling parameterized constructor"
+ " of base");
}
}
class Derived extends Base
{
// constructor 3
Derived()
{
System.out.println("No-argument constructor " +
"of derived");
}
// parameterized constructor 4
Derived(String name)
{
// invokes base class constructor 2
super(name);
System.out.println("Calling parameterized " +
"constructor of derived");
}
public static void main(String args[])
{
// calls parameterized constructor 4
Derived obj = new Derived("test");
// Calls No-argument constructor
// Derived obj = new Derived();
}
}
output

Page No 34
University Roll No 1507884

16. Importing classes from user defined package and


creating packages using access protection.
Packages In Java
Package in Java is a mechanism to encapsulate a group of classes, sub packages and interfaces.
Packages are used for:
1. Preventing naming conflicts. For example there can be two classes with name Employee in two
packages, college.staff.cse.Employee and college.staff.ee.Employee
2. Making searching/locating and usage of classes, interfaces, enumerations and annotations easier
3. Providing controlled access: protected and default have package level access control. A
protected member is accessible by classes in the same package and its subclasses. A default
member (without any access specifier) is accessible by classes in the same package only.
4. Packages can be considered as data encapsulation (or data-hiding).
How packages work?
Package naming conventions : Packages are named in reverse order of domain names, i.e.,
org.geeksforgeeks.practice. For example, in a college, the recommended convention is
college.tech.cse, college.tech.ee, college.art.history, etc.
Adding a class to a Package : We can add more classes to an created package by using package
name at the top of the program and saving it in the package directory. We need a new java file to
define a public class, otherwise we can add the new class to an existing .java file and recompile it.
Subpackages: Packages that are inside another package are the subpackages. These are not
imported by default, they have to imported explicitly. Also, members of a subpackage have no
access privileges, i.e., they are considered as different package for protected and default access
specifiers.
Accessing classes inside a package
Program
import java.util.Vector;
public class ImportDemo
{
public ImportDemo()
{
// java.util.Vector is imported, hence we are
// able to access directly in our code.
Vector newVector = new Vector();

// java.util.ArrayList is not imported, hence


// we were referring to it using the complete
// package.
java.util.ArrayList newList = new java.util.ArrayList();
}
public static void main(String arg[])
{
new ImportDemo();
}
}

Page No 35
University Roll No 1507884
output

Types of packages:

Built-in Packages
These packages consist of a large number of classes which are a part of Java API.Some of the
commonly used built-in packages are:
1. java.lang: Contains language support classes(e.g classed which defines primitive data types,
math operations). This package is automatically imported.
2. java.io: Contains classed for supporting input / output operations.
3. java.util: Contains utility classes which implement data structures like Linked List, Dictionary
and support ; for Date / Time operations.
4. java.applet: Contains classes for creating Applets.
5. java.awt: Contain classes for implementing the components for graphical user interfaces (like
button , ;menus etc).
6. java.net: Contain classes for supporting networking operations.
Program
import static java.lang.System.*;
class StaticImportDemo
{
public static void main(String args[])
{
// We don't need to use 'System.out'
// as imported using static.
out.println("GeeksforGeeks");
}
}
output

Page No 36
University Roll No 1507884

17. Interfaces, nested interfaces and use of extending


interfaces.
Here is a simple Java interface example:
public interface MyInterface {

public String hello = "Hello";

public void sayHello();


}
As you can see, an interface is declared using the Java interface keyword. Just like with classes, a
Java interface can be declared public or package scope (no access modifier).
Nested Interface
A nested interface, as mentioned in Java language specification, is any regular interface whose
declaration occurs within the body of another class or interface. Nested interface is also called inner
interface. A top level interface is an interface that is not a nested interface. Regardless of top level or
nested interface, an interface declaration introduces a new hundred percent abstract reference type,
whose members are classes, interfaces, constants, and abstract methods. By creating an interface,
we define a contract for what a class can do if it implements the interface, without saying anything
about how the class will do it. An interface cannot be instantiated on its own; therefore, it must be
implemented by a class or extended by other interface to be used.
Rules for Declaring Nested Interface
To declare a nested interface there are certain rules. These rules apply depending upon where the
nested interface declaration occurs inside another interface or class.
1. Nested interfaces are implicitly static regardless of where they are declared (inside class or
another interface).
2. Nested interface declared inside another interface is implicitly public.
3. Nested interface declared inside a class can accept any access modifiers.
4. Nested interface can be implemented by any class (package level, nested or inner) if the access
modifiers permit visibility.
Program
class A
{
private interface NestedPA { void paMethod(); }
protected interface NestedA extends NestedPA { void aMethod(); }
public interface NestedAA { void aaMethod(); }
}
public class NestedInterfaceDemo implements A.NestedA, A.NestedAA
{
public static void main (String args[])
{
A.NestedA na = new NestedInterfaceDemo();
na.aMethod();
na.paMethod();
A.NestedAA naa = (A.NestedAA) na;
naa.aaMethod();
}
public void aMethod()
{

Page No 37
University Roll No 1507884
System.out.println("within from aMethod");
}
public void aaMethod()
{
System.out.println("within from aaMethod");
}
public void paMethod()
{
System.out.println("within from paMethod");
}
}
output

Page No 38
University Roll No 1507884

18. Exception Handling - using predefined exception.


The exception handling in java is one of the powerful mechanism to handle the runtime errors so
that normal flow of the application can be maintained.
In this page, we will learn about java exception, its type and the difference between checked and
unchecked exceptions.
Program
class Example1
{
public static void main(String args[])
{
try{
int num1=30, num2=0;
int output=num1/num2;
System.out.println ("Result: "+output);
}
catch(ArithmeticException e){
System.out.println ("You Shouldn't divide a number by zero");
}
}
}
output

Page No 39
University Roll No 1507884

19. Exception Handling - creating user defined


exceptions
You can create your own exceptions in Java. Keep the following points in mind when writing your
own exception classes −
1. All exceptions must be a child of Throwable.
2. If you want to write a checked exception that is automatically enforced by the Handle or
Declare Rule, you need to extend the Exception class.
3. If you want to write a runtime exception, you need to extend the RuntimeException class.
You just need to extend the predefined Exception class to create your own Exception. These are
considered to be checked exceptions. The following InsufficientFundsException class is a user-
defined exception that extends the Exception class, making it a checked exception. An exception
class is like any other class, containing useful fields and methods.
Program
// File Name InsufficientFundsException.java
import java.io.*;

public class InsufficientFundsException extends Exception {


private double amount;

public InsufficientFundsException(double amount) {


this.amount = amount;
}
public double getAmount() {
return amount;
}
}
To demonstrate using our user-defined exception, the following CheckingAccount class contains a
withdraw() method that throws an InsufficientFundsException.
// File Name CheckingAccount.java
import java.io.*;
public class CheckingAccount {
private double balance;
private int number;
public CheckingAccount(int number) {
this.number = number;
}
public void deposit(double amount) {
balance += amount;
}
public void withdraw(double amount) throws InsufficientFundsException {
if(amount <= balance) {
balance -= amount;
}else {
double needs = amount - balance;
throw new InsufficientFundsException(needs);
}
}
public double getBalance() {
return balance;

Page No 40
University Roll No 1507884
}
public int getNumber() {
return number;
}
}
The following BankDemo program demonstrates invoking the deposit() and withdraw() methods of
CheckingAccount.
// File Name BankDemo.java
public class BankDemo {
public static void main(String [] args) {
CheckingAccount c = new CheckingAccount(101);
System.out.println("Depositing $500...");
c.deposit(500.00);
try {
System.out.println("\nWithdrawing $100...");
c.withdraw(100.00);
System.out.println("\nWithdrawing $600...");
c.withdraw(600.00);
} catch (InsufficientFundsException e) {
System.out.println("Sorry, but you are short $" + e.getAmount());
e.printStackTrace();
}
}
}
Compile all the above three files and run BankDemo. This will produce the following result
output

Page No 41
University Roll No 1507884

20. Multithreading by extending Thread Class.


We create a class that extends the java.lang.Thread class. This class overrides the run() method
available in the Thread class. A thread begins its life inside run() method. We create an object of our
new class and call start() method to start the execution of a thread. Start() invokes the run() method
on the Thread object.
Program
// Java code for thread creation by extending
// the Thread class
class MultithreadingDemo extends Thread
{
public void run(){
try{
// Displaying the thread that is running
System.out.println ("Thread " +
Thread.currentThread().getId() +
" is running");
}
catch (Exception e){
// Throwing an exception
System.out.println ("Exception is caught");
}
}
}
// Main Class
public class Multithread{
public static void main(String[] args)
{
int n = 8; // Number of threads
for (int i=0; i<8; i++)
{
MultithreadingDemo object = new MultithreadingDemo();
object.start();
}
}
}

Page No 42
University Roll No 1507884
output


Page No 43
University Roll No 1507884

21. Multithreading by implementing Runnable Interface.


We create a new class which implements java.lang.Runnable interface and override run() method.
Then we instantiate a Thread object and call start() method on this object.
Program
// Java code for thread creation by implementing
// the Runnable Interface
class MultithreadingDemo implements Runnable
{
public void run(){
try
{
// Displaying the thread that is running
System.out.println ("Thread " +
Thread.currentThread().getId() +
" is running");
}
catch (Exception e) {
// Throwing an exception
System.out.println ("Exception is caught");
}
}
}
// Main Class
class Multithread
{
public static void main(String[] args)
{
int n = 8; // Number of threads
for (int i=0; i<8; i++)
{
Thread object = new Thread(new MultithreadingDemo());
object.start();
}
}
}

Page No 44
University Roll No 1507884
output
22. Thread life cycle.
A thread in Java at any point of time exists in any one of the following states. A thread lies only in
one of the shown states at any instant:
1. New
2. Runnable
3. Blocked
4. Waiting
5. Timed Waiting
6. Terminated
The diagram shown below represent various states of a thread at any instant of time.

Here is the preceding program rewritten to extend the Thread


Program
class ThreadDemo extends Thread {
private Thread t;
private String threadName;
ThreadDemo( String name) {
threadName = name;
System.out.println("Creating " + threadName );
}
public void run() {
System.out.println("Running " + threadName );
try {
for(int i = 4; i > 0; i--) {
System.out.println("Thread: " + threadName + ", " + i);
// Let the thread sleep for a while.
Thread.sleep(50);
}
} catch (InterruptedException e) {
System.out.println("Thread " + threadName + " interrupted.");
}

Page No 45
University Roll No 1507884
System.out.println("Thread " + threadName + " exiting.");
}
public void start () {
System.out.println("Starting " + threadName );
if (t == null) {
t = new Thread (this, threadName);
t.start ();
}
}
}
public class TestThread {
public static void main(String args[]) {
ThreadDemo T1 = new ThreadDemo( "Thread-1");
T1.start();
ThreadDemo T2 = new ThreadDemo( "Thread-2");
T2.start();
}
}
output

Page No 46
University Roll No 1507884

23. Applet life cycle.


Java applet inherits features from the class Applet. Thus, whenever an applet is created, it undergoes
a series of changes from initialization to destruction. Various stages of an applet life cycle are
depicted in the figure below:

Advantage of Applet
There are many advantages of applet. They are as follows:
1. It works at client side so less response time.
2. Secured
3. It can be executed by browsers running under many plateforms, including Linux, Windows,
Mac Os etc.
Lifecycle methods for Applet:
For creating any applet java.applet.Applet class must be inherited. It provides 4 life cycle methods
of applet.
1. public void init(): is used to initialized the Applet. It is invoked only once.
2. public void start(): is invoked after the init() method or browser is maximized. It is used to
start the Applet.
3. public void stop(): is used to stop the Applet. It is invoked when Applet is stop or browser is
minimized.
4. public void destroy(): is used to destroy the Applet. It is invoked only once.
Simple example of Applet by html file:
To execute the applet by html file, create an applet and compile it. After that create an html file and
place the applet code in html file. Now click the html file.
Program
//First.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet{
public void paint(Graphics g){
g.drawString("welcome",150,150);
}
} 


Page No 47
University Roll No 1507884
myapplet.html
<html>
<body>
<applet code="First.class" width="300" height="300">
</applet>
</body>
</html>
output

Page No 48
University Roll No 1507884

24. Applet for configuring Applets by passing


parameters.
Java applet has the feature of retrieving the parameter values passed from the html page. So, you
can pass the parameters from your html page to the applet embedded in your page.
The param tag(<parma name="" value=""></param>) is used to pass the parameters to an
applet. For the illustration about the concept of applet and passing parameter in applet.
Program
import java.applet.*;
import java.awt.*;
/*<APPLET code="hai" width="300" height="250">
<PARAM name="Message" value="Hai friend how are you ..?"></APPLET>*/
public class Hai extends Applet {
private String defaultMessage = "Hello!";
public void paint(Graphics g) {
String inputFromPage = this.getParameter("Message");
if (inputFromPage == null) inputFromPage = defaultMessage;
g.drawString(inputFromPage, 50, 55);
}
}
output

Page No 49
University Roll No 1507884

25. Event Handling.


Any program that uses GUI (graphical user interface) such as Java application written for windows,
is event driven. Event describes the change in state of any object. For Example : Pressing a button,
Entering a character in Textbox, Clicking or Dragging a mouse, etc.
Components of Event Handling
Event handling has three main components,
• Events : An event is a change in state of an object.
• Events Source : Event source is an object that generates an event.
• Listeners : A listener is an object that listens to the event. A listener gets notified when an event
occurs.
How Events are handled ?
A source generates an Event and send it to one or more listeners registered with the source. Once
event is received by the listener, they process the event and then return. Events are supported by a
number of Java packages, like java.util, java.awt and java.awt.event.
Example of Event Handling
Program
import java.awt.*;
import java.awt.event.*;
class AEvent extends Frame implements ActionListener{
TextField tf;
AEvent(){

//create components
tf=new TextField();
tf.setBounds(60,50,170,20);
Button b=new Button("click me");
b.setBounds(100,120,80,30);

//register listener
b.addActionListener(this);//passing current instance

//add components and set size, layout and visibility


add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e){
tf.setText("Welcome");
}
public static void main(String args[]){
new AEvent();
}
}

Page No 50
University Roll No 1507884
output

Page No 51
University Roll No 1507884

26. Reading and writing from a particular file.


Reading console input
In Java 1.0, the only way to perform the console input was to use a byte stream. Today, using a byte
stream to read console input is still acceptable. However, for the commercial applications, the
preferred method of reading console input is to use a character-oriented stream. This makes your
program easier to internationalize and maintain.
In Java, console input is accomplished by reading from System.in. To obtain a character-based
stream that is attached to the console, wrap System.in in a BufferedReader object.
BufferedReader supports a buffered input stream. A commonly used constructor is shown below :
BufferedReader(Reader inputReader)
Here, inputReader is the stream that is linked to the instance of BufferedReader that is being
created. Reader is an abstract class. One of its concrete subclasses is InputStreamReader, which
converts bytes to characters. To obtain an InputStreamReader object that is linked to System.in,
use the following constructor:
InputStreamReader(InputStream inputStream)
The following program demonstrates the read() by reading the characters from the console until the
user types a "q". Notice that any I/O exceptions that might be generated are simply thrown out of
the main(). Such an approach is common when reading from console in simple example programs,
but in more sophisticated applications, you can handle the exceptions explicitly.
Program
import java.io.*;
class ReadConsoleInput
{
public static void main(String args[]) throws IOException
{
char chr;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter a character (Press 'q' to quit) : ");
// read characters now
do
{
chr = (char) br.read();
System.out.println(chr);

} while(chr != 'q');

}
}
output

Page No 52
University Roll No 1507884

writing console output


Console output is most easily accomplished with print() and println() methods, as described
earlier. These methods are defined by the class PrintStream which is the type of object referenced
by System.in. Even though System.outis a byte stream, using it for a simple program output is still
acceptable.
Because the PrintStream is an output stream derived from the OutputStream, it also implements
the low-level method write(). Thus, write() can be used to write to the console. The simplest form
of write() defined by the PrintStream is shown below :
void write(int byteval)
This method writes the byte specified by byteval. Although byteval is declared as an integer, only
the low-order eight bits are written. Following is a short example that uses write() to output the
character 'X' followed by a newline to the screen:
Program
class WriteConsoleOutput
{
public static void main(String args[])
{
int y;
y = 'X';
System.out.write(y);
System.out.write('\n');
}
}
output

Page No 53
University Roll No 1507884

27. Database connectivity for various DDL and DML


operations.
DDL (Data Definition Language)
DDL statements are used to alter/modify a database or table structure and schema. These statements
handle the design and storage of database objects.
1. CREATE – create a new Table, database, schema
The following steps are required to create a new Database using JDBC application −
• Import the packages: Requires that you include the packages containing the JDBC classes needed
for database programming. Most often, using import java.sql.* will suffice.
• Register the JDBC driver: Requires that you initialize a driver so you can open a
communications channel with the database.
• Open a connection: Requires using the DriverManager.getConnection() method to create a
Connection object, which represents a physical connection with the database server.
• To create a new database, you need not give any database name while preparing database URL as
mentioned in the below example.
• Execute a query: Requires using an object of type Statement for building and submitting an SQL
statement to the database.
• Clean up the environment . Requires explicitly closing all database resources versus relying on
the JVM's garbage collection.
Program
//STEP 1. Import required packages
import java.sql.*;
public class JDBCExample {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/";
// Database credentials
static final String USER = "virus";
static final String PASS = "virus";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{
//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
//STEP 3: Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
//STEP 4: Execute a query
System.out.println("Creating database...");
stmt = conn.createStatement();
String sql = "CREATE DATABASE STUDENTS";
stmt.executeUpdate(sql);
System.out.println("Database created successfully...");
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
Page No 54
University Roll No 1507884
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
}// nothing we can do
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
}
}
2. ALTER – alter existing table, column description
The following steps are required to create a new Database using JDBC application −
• Import the packages: Requires that you include the packages containing the JDBC classes needed
for database programming. Most often, using import java.sql.* will suffice.
• Register the JDBC driver: Requires that you initialize a driver so, you can open a
communications channel with the database.
• Open a connection: Requires using the DriverManager.getConnection() method to create a
Connection object, which represents a physical connection with a database server.
• Execute a query: Requires using an object of type Statement for building and submitting an SQL
statement to drop a table in a seleted database.
• Clean up the environment: Requires explicitly closing all database resources versus relying on
the JVM's garbage collection.
Program
import java.sql.*;
public class JDBCExample6 {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/STUDENTS";
static final String USER = "username";
static final String PASS = "password";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Connecting to a selected database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println("Connected database successfully...");
System.out.println("Deleting table in given database...");
stmt = conn.createStatement();
String sql = "DROP TABLE REGISTRATION ";
stmt.executeUpdate(sql);
System.out.println("Table deleted in given database...");
}catch(SQLException se){
Page No 55
University Roll No 1507884
se.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}finally{
try{
if(stmt!=null)
conn.close();
}catch(SQLException se){
}
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}
}
System.out.println("Goodbye!");
}
}

3. DROP – delete existing objects from database


The following steps are required to create a new Database using JDBC application −
• Import the packages: Requires that you include the packages containing the JDBC classes needed
for database programming. Most often, using import java.sql.* will suffice.
• Register the JDBC driver: Requires that you initialize a driver so you can open a
communications channel with the database.
• Open a connection: Requires using the DriverManager.getConnection() method to create a
Connection object, which represents a physical connection with a database server.
• Deleting a database does not require database name to be in your database URL. Following
example would delete STUDENTS database.
• Execute a query: Requires using an object of type Statement for building and submitting an SQL
statement to delete the database.
• Clean up the environment: Requires explicitly closing all database resources versus relying on
the JVM's garbage collection.
Program
import java.sql.*;
public class JDBCExample1 {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/";

static final String USER = "username";


static final String PASS = "password";

public static void main(String[] args) {


Connection conn = null;
Statement stmt = null;
try{
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Connecting to a selected database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);

Page No 56
University Roll No 1507884
System.out.println("Connected database successfully...");
System.out.println("Deleting database...");
stmt = conn.createStatement();
String sql = "DROP DATABASE STUDENTS";
stmt.executeUpdate(sql);
System.out.println("Database deleted successfully...");
}catch(SQLException se){
se.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}finally{
try{
if(stmt!=null)
conn.close();
}catch(SQLException se){
}// do nothing
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}
}
System.out.println("Goodbye!");
}
}
DML (Data Manipulation Language)
DML statements affect records in a table. These are basic operations we perform on data such as
selecting a few records from a table, inserting new records, deleting unnecessary records, and
updating/modifying existing records.
SELECT – select records from a table
The following steps are required to create a new Database using JDBC application −
• Import the packages: Requires that you include the packages containing the JDBC classes needed
for the database programming. Most often, using import java.sql.* will suffice.
• Register the JDBC driver: Requires that you initialize a driver so you can open a
communications channel with the database.
• Open a connection: Requires using the DriverManager.getConnection() method to create a
Connection object, which represents a physical connection with a selected database.
• Selection of database is made while you prepare database URL. Following example would make
connection with STUDENTS database.
• Clean up the environment: Requires explicitly closing all the database resources versus relying
on the JVM's garbage collection.
Program
import java.sql.*;
public class JDBCExample2 {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/STUDENTS";
static final String USER = "username";
static final String PASS = "password";
public static void main(String[] args) {
Page No 57
University Roll No 1507884
Connection conn = null;
try{
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Connecting to a selected database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println("Connected database successfully...");
}catch(SQLException se){
se.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}finally{
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}
}
System.out.println("Goodbye!");
}}

INSERT – insert new records
The following steps are required to create a new Database using JDBC application −
• Import the packages: Requires that you include the packages containing the JDBC classes needed
for database programming. Most often, using import java.sql.* will suffice.
• Register the JDBC driver: Requires that you initialize a driver so you can open a
communications channel with the database.
• Open a connection: Requires using the DriverManager.getConnection() method to create a
Connection object, which represents a physical connection with a database server.
• Execute a query: Requires using an object of type Statement for building and submitting an SQL
statement to insert records into a table.
• Clean up the environment: Requires explicitly closing all database resources versus relying on
the JVM's garbage collection.
Program
import java.sql.*;
public class JDBCExample3 {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/STUDENTS";
static final String USER = "username";
static final String PASS = "password";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Connecting to a selected database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println("Connected database successfully...");
System.out.println("Inserting records into the table...");
stmt = conn.createStatement();
Page No 58
University Roll No 1507884
String sql = "INSERT INTO Registration " +
"VALUES (100, 'Zara', 'Ali', 18)";
stmt.executeUpdate(sql);
sql = "INSERT INTO Registration " +
"VALUES (101, 'Mahnaz', 'Fatma', 25)";
stmt.executeUpdate(sql);
sql = "INSERT INTO Registration " +
"VALUES (102, 'Zaid', 'Khan', 30)";
stmt.executeUpdate(sql);
sql = "INSERT INTO Registration " +
"VALUES(103, 'Sumit', 'Mittal', 28)";
stmt.executeUpdate(sql);
System.out.println("Inserted records into the table...");
}catch(SQLException se){
se.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}finally{
try{
if(stmt!=null)
conn.close();
}catch(SQLException se){
}// do nothing
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}
}
System.out.println("Goodbye!");
}}

UPDATE – update/Modify existing records
The following steps are required to create a new Database using JDBC application −
• Import the packages: Requires that you include the packages containing the JDBC classes needed
for database programming. Most often, using import java.sql.* will suffice.
• Register the JDBC driver: Requires that you initialize a driver so you can open a
communications channel with the database.
• Open a connection: Requires using the DriverManager.getConnection() method to create a
Connection object, which represents a physical connection with a database server.
• Execute a query: Requires using an object of type Statement for building and submitting an SQL
statement to update records in a table. This Query makes use of IN and WHERE clause to update
conditional records.
• Clean up the environment: Requires explicitly closing all database resources versus relying on
the JVM's garbage collection.

Page No 59
University Roll No 1507884
Program
import java.sql.*;
public class JDBCExample4 {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/STUDENTS";
static final String USER = "username";
static final String PASS = "password";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Connecting to a selected database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println("Connected database successfully...");
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql = "UPDATE Registration " +
"SET age = 30 WHERE id in (100, 101)";
stmt.executeUpdate(sql);
sql = "SELECT id, first, last, age FROM Registration";
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()){
int id = rs.getInt("id");
int age = rs.getInt("age");
String first = rs.getString("first");
String last = rs.getString("last");
System.out.print("ID: " + id);
System.out.print(", Age: " + age);
System.out.print(", First: " + first);
System.out.println(", Last: " + last);
}
rs.close();
}catch(SQLException se){
se.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}finally{
try{
if(stmt!=null)
conn.close();
}catch(SQLException se){
}
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}
} System.out.println("Goodbye!");
}}

Page No 60
University Roll No 1507884
DELETE – delete existing records
The following steps are required to create a new Database using JDBC application −
• Import the packages: Requires that you include the packages containing the JDBC classes needed
for database programming. Most often, using import java.sql.* will suffice.
• Register the JDBC driver: Requires that you initialize a driver so you can open a
communications channel with the database.
• Open a connection: Requires using the DriverManager.getConnection() method to create a
Connection object, which represents a physical connection with a database server.
• Execute a query: Requires using an object of type Statement for building and submitting an SQL
statement to delete records from a table. This Query makes use of the WHERE clause to delete
conditional records.
• Clean up the environment: Requires explicitly closing all database resources versus relying on
the JVM's garbage collection.
Program
import java.sql.*;
public class JDBCExample5 {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/STUDENTS";
static final String USER = "username";
static final String PASS = "password";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Connecting to a selected database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println("Connected database successfully...");
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql = "DELETE FROM Registration " +
"WHERE id = 101";
stmt.executeUpdate(sql);
sql = "SELECT id, first, last, age FROM Registration";
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()){
int id = rs.getInt("id");
int age = rs.getInt("age");
String first = rs.getString("first");
String last = rs.getString("last");
System.out.print("ID: " + id);
System.out.print(", Age: " + age);
System.out.print(", First: " + first);
System.out.println(", Last: " + last);
}
rs.close();
}catch(SQLException se){
se.printStackTrace();
Page No 61
University Roll No 1507884
}catch(Exception e){
e.printStackTrace();
}finally{
try{
if(stmt!=null)
conn.close();
}catch(SQLException se){
} try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}
}
System.out.println("Goodbye!");
}
}


Page No 62
University Roll No 1507884

28. String class and its methods.


String is a sequence of characters, for e.g. “Hello” is a string of 5 characters. In java, string is an
immutable object which means it is constant and can cannot be changed once it has been created. In
this tutorial we will learn about String class and String methods in detail along with many other
Java String tutorials.
Creating a String
There are two ways to create a String in Java
1. String literal
2. Using new keyword
A Simple Java String Example
Program
public class Example{
public static void main(String args[]){
//creating a string by java string literal
String str = "Beginnersbook";
char arrch[]={'h','e','l','l','o'};
//converting char array arrch[] to string str2
String str2 = new String(arrch);

//creating another java string str3 by using new keyword


String str3 = new String("Java String Example");

//Displaying all the three strings


System.out.println(str);
System.out.println(str2);
System.out.println(str3);
}
}
output

Java String Methods


Here are the list of the methods available in the Java String class. These methods are explained in
the separate tutorials with the help of examples. Links to the tutorials are provided below:
1. char charAt(int index): It returns the character at the specified index. Specified index value
should be between 0 to length() -1 both inclusive. It throws IndexOutOfBoundsException if
index<0||>= length of String.
2. boolean equals(Object obj): Compares the string with the specified string and returns true if
both matches else false.

Page No 63
University Roll No 1507884
3. boolean equalsIgnoreCase(String string): It works same as equals method but it doesn’t
consider the case while comparing strings. It does a case insensitive comparison.
4. int compareTo(String string): This method compares the two strings based on the Unicode value
of each character in the strings.
5. int compareToIgnoreCase(String string): Same as CompareTo method however it ignores the
case during comparison.
6. boolean startsWith(String prefix, int offset): It checks whether the substring (starting from the
specified offset index) is having the specified prefix or not.
7. boolean startsWith(String prefix): It tests whether the string is having specified prefix, if yes
then it returns true else false.
8. boolean endsWith(String suffix): Checks whether the string ends with the specified suffix.
9. int hashCode(): It returns the hash code of the string.
10. int indexOf(int ch): Returns the index of first occurrence of the specified character ch in the
string.
11. int indexOf(int ch, int fromIndex): Same as indexOf method however it starts searching in the
string from the specified fromIndex.
12. int lastIndexOf(int ch): It returns the last occurrence of the character ch in the string.
13. int lastIndexOf(int ch, int fromIndex): Same as lastIndexOf(int ch) method, it starts search from
fromIndex.
14. int indexOf(String str): This method returns the index of first occurrence of specified substring
str.
15. int lastindexOf(String str): Returns the index of last occurrence of string str.

Page No 64
University Roll No 1507884

29. StringBuffer class and its methods.


Java StringBuffer class is used to create mutable (modifiable) string. The StringBuffer class in java
is same as String class except it is mutable i.e. it can be changed.
A string that can be modified or changed is known as mutable string. StringBuffer and
StringBuilder classes are used for creating mutable string.
The append() method concatenates the given argument with this string.
Program
class StringBufferExample{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello ");
sb.append("Java");//now original string is changed
System.out.println(sb);//prints Hello Java
}
}
output

Important methods of StringBuffer class

Modifier and Method Description


Type

public append(String s) is used to append the specified string with this string.
synchronized The append() method is overloaded like append(char),
StringBuffer append(boolean), append(int), append(float),
append(double) etc.

public insert(int offset, is used to insert the specified string with this string at
synchronized String s) the specified position. The insert() method is
StringBuffer overloaded like insert(int, char), insert(int, boolean),
insert(int, int), insert(int, float), insert(int, double) etc.

public replace(int is used to replace the string from specified startIndex


synchronized startIndex, int and endIndex.
StringBuffer endIndex, String
str)

public delete(int is used to delete the string from specified startIndex


synchronized startIndex, int and endIndex.
StringBuffer endIndex)

Page No 65
University Roll No 1507884

public reverse() is used to reverse the string.


synchronized
StringBuffer

public int capacity() is used to return the current capacity.

public void ensureCapacity( is used to ensure the capacity at least equal to the
int given minimum.
minimumCapaci
ty)

public char charAt(int is used to return the character at the specified position.
index)

public int length() is used to return the length of the string i.e. total
number of characters.

public String substring(int is used to return the substring from the specified
beginIndex) beginIndex.

public String substring(int is used to return the substring from the specified
beginIndex, int beginIndex and endIndex.
endIndex)

Page No 66
University Roll No 1507884

30. Without using inbuilt features of Java implement


following concepts related to Data Structures:
a) Stack
Java provides an inbuilt object type called Stack. It is a collection that is based on the last in first
out (LIFO) principle. On Creation, a stack is empty.
It extends Vector class with five methods that allow a vector to be treated as a stack. The five
methods are:
1. Object push(Object element) : Pushes an element on the top of the stack.
2. Object pop() : Removes and returns the top element of the stack. An ‘EmptyStackException’
exception is thrown if we call pop() when the invoking stack is empty.
3. Object peek( ) : Returns the element on the top of the stack, but does not remove it.
4. boolean empty() : It returns true if nothing is on the top of the stack. Else, returns false.
5. int search(Object element) : It determines whether an object exists in the stack. If the element
is found, it returns the position of the element from the top of the stack. Else, it returns -1.
Program
// Java code for stack implementation
import java.io.*;
import java.util.*;
class Test
{
// Pushing element on the top of the stack
static void stack_push(Stack<Integer> stack)
{
for(int i = 0; i < 5; i++)
{
stack.push(i);
}
}
// Popping element from the top of the stack
static void stack_pop(Stack<Integer> stack)
{
System.out.println("Pop :");

for(int i = 0; i < 5; i++)


{
Integer y = (Integer) stack.pop();
System.out.println(y);
}
}
// Displaying element on the top of the stack
static void stack_peek(Stack<Integer> stack)
{
Integer element = (Integer) stack.peek();
System.out.println("Element on stack top : " + element);
}
// Searching element in the stack
static void stack_search(Stack<Integer> stack, int element)
{
Integer pos = (Integer) stack.search(element);
Page No 67
University Roll No 1507884
if(pos == -1)
System.out.println("Element not found");
else
System.out.println("Element is found at position " + pos);
}
public static void main (String[] args)
{
Stack<Integer> stack = new Stack<Integer>();
stack_push(stack);
stack_pop(stack);
stack_push(stack);
stack_peek(stack);
stack_search(stack, 2);
stack_search(stack, 6);
}
}
output

b) Queue
The java.util.Queue is a subtype of java.util.Collection interface. It is an ordered list of objects with
its use limited to inserting elements at the end of list and deleting elements from the start of list i.e.
it follows FIFO principle.

Since it is an interface, we need a concrete class during its declaration. There are many ways to
initialize a Queue object, most common being-
1. As a Priority Queue
2. As a LinkedList
Please note that both the implementations are not thread safe. PriorityBlockingQueue is one
alternative implementation if you need a thread safe implementation.
Operations on Queue :
• Add()-Adds an element at the tail of queue. More specifically, at the last of linkedlist if it is used,
or according to the priority in case of priority queue implementation.
Page No 68
University Roll No 1507884
• peek()-To view the head of queue without removing it. Returns null if queue is empty.
• element()-Similar to peek(). Throws NoSuchElementException if queue is empty.
• remove()-Removes and returns the head of the queue. Throws NoSuchElementException when
queue is impty.
• poll()-Removes and returns the head of the queue. Returns null if queue is empty.
Since it is a subtype of Collections class, it inherits all the methods of it namely size(), isEmpty(),
contains() etc.
A simple Java program to demonstrate these methods
Program
// Java orogram to demonstrate working of Queue
// interface in Java
import java.util.LinkedList;
import java.util.Queue;
public class QueueExample
{
public static void main(String[] args)
{
Queue<Integer> q = new LinkedList<>();
// Adds elements {0, 1, 2, 3, 4} to queue
for (int i=0; i<5; i++)
q.add(i);
// Display contents of the queue.
System.out.println("Elements of queue-"+q);
// To remove the head of queue.
int removedele = q.remove();
System.out.println("removed element-" + removedele);
System.out.println(q);
// To view the head of queue
int head = q.peek();
System.out.println("head of queue-" + head);
// Rest all methods of collection interface,
// Like size and contains can be used with this
// implementation.
int size = q.size();
System.out.println("Size of queue-" + size);
}
}
output

Page No 69
University Roll No 1507884

c) LinkList
In Java, LinkedList class implements the list interface.
This class consists of the following methods :
1. boolean add(Object element) : It appends the element to the end of the list.
2. void add(int index, Object element): It inserts the element at the position ‘index’ in the list.
3. void addFirst(Object element) : It inserts the element at the beginning of the list.
4. void addLast(Object element) : It appends the element at the end of the list.
5. boolean contains(Object element) : It returns true if the element is present in the list.
6. Object get(int index) : It returns the element at the position ‘index’ in the list. It throws
‘IndexOutOfBoundsException’ if the index is out of range of the list.
7. int indexOf(Object element) : If element is found, it returns the index of the first occurrence of
the element. Else, it returns -1.
8. Object remove(int index) : It removes the element at the position ‘index’ in this list. It throws
‘NoSuchElementException’ if the list is empty.
9. int size() : It returns the number of elements in this list.
10. void clear() : It removes all of the elements from the list.
Program
// Java code for Linked List implementation
import java.util.*;
public class Test1
{
public static void main(String args[])
{
// Creating object of class linked list
LinkedList<String> object = new LinkedList<String>();
// Adding elements to the linked list
object.add("A");
object.add("B");
object.addLast("C");
object.addFirst("D");
object.add(2, "E");
object.add("F");
object.add("G");
System.out.println("Linked list : " + object);
// Removing elements from the linked list
object.remove("B");
object.remove(3);
object.removeFirst();
object.removeLast();
System.out.println("Linked list after deletion: " + object);
// Finding elements in the linked list
boolean status = object.contains("E");
if(status)
System.out.println("List contains the element 'E' ");
else
System.out.println("List doesn't contain the element 'E'");
// Number of elements in the linked list
int size = object.size();
System.out.println("Size of linked list = " + size);
Page No 70
University Roll No 1507884

// Get and set elements from linked list


Object element = object.get(2);
System.out.println("Element returned by get() : " + element);
object.set(2, "Y");
System.out.println("Linked list after change : " + object);
}
}
output

d) Quicksort
This is a Java Program to implement Quick Sort Algorithm. This program is to sort a list of
numbers.
Here is the source code of the Java program to implement Quick Sort Algorithm. The Java program
is successfully compiled and run on a Windows system. The program output is also shown below.
Program
import java.util.Scanner;
public class QuickSort
{
public static void sort(int[] arr)
{
quickSort(arr, 0, arr.length - 1);
}
public static void quickSort(int arr[], int low, int high)
{
int i = low, j = high;
int temp;
int pivot = arr[(low + high) / 2];
while (i <= j)
{
while (arr[i] < pivot)
i++;
while (arr[j] > pivot)
j--;
if (i <= j)
{
/** swap **/
Page No 71
University Roll No 1507884
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
i++;
j--;
}
}
if (low < j)
quickSort(arr, low, j);
/** recursively sort upper half **/
if (i < high)
quickSort(arr, i, high);
}
public static void main(String[] args)
{
Scanner scan = new Scanner( System.in );
System.out.println("Quick Sort Test\n");
int n, i;
/** Accept number of elements **/
System.out.println("Enter number of integer elements");
n = scan.nextInt();
int arr[] = new int[ n ];
System.out.println("\nEnter "+ n +" integer elements");
for (i = 0; i < n; i++)
arr[i] = scan.nextInt();
sort(arr);
System.out.println("\nElements after sorting ");
for (i = 0; i < n; i++)
System.out.print(arr[i]+" ");
System.out.println();
}
}
output


Page No 72
University Roll No 1507884

31. Implement following concepts related to Digital


Electronics:
a) Octal to Hexadecimal ,Decimal, Binary
Convert Octal to Hexadecimal
To convert octal to hexadecimal in Java Programming, you have to ask to the user to enter any
number in octal number format to convert it into equivalent hexadecimal format to display the
equivalent value in hexadecimal as shown in the following program.
Java Programming Code to Convert Octal to Hexadecimal
Following Java program ask to the user to enter any octal number to convert it into hexadecimal,
then display the result on the screen:
Following are the two steps to convert any octal number to hexadecimal number:
1. First, convert the octal number to decimal number :

int decnum = Integer.parseInt(octnum, 8);
2. Second, convert the decimal number to hexadecimal number :

String hexnum = Integer.toHexString(decnum);
Program
/* Java Program Example - Convert Octal to Hexadecimal */
import java.util.Scanner;
public class JavaProgram
{
public static void main(String args[])
{
String octnum, hexnum;
int decnum;
Scanner scan = new Scanner(System.in);
System.out.print("Enter Octal Number : ");
octnum = scan.nextLine();
decnum = Integer.parseInt(octnum, 8);
hexnum = Integer.toHexString(decnum);
System.out.print("Equivalent Hexadecimal Value of " + octnum + " is :\n");
System.out.print(hexnum);
}
}
output

Convert Octal to Decimal


To convert octal to decimal in Java Programming, you have to ask to the user to enter any number
in octal number format to convert it into equivalent decimal number format to display the
equivalent value in decimal number system as shown in the following program.
Java Programming Code to Convert Octal to Decimal

Page No 73
University Roll No 1507884
Following Java program ask to the user to enter any octal number to convert it into decimal, then
display the result on the screen :
Program
/* Java Program Example - Convert Octal to Decimal */
import java.util.Scanner;
public class JavaProgram1
{
public static void main(String args[])
{
int octnum, decnum=0, i=0, orig;
Scanner scan = new Scanner(System.in);
System.out.print("Enter Octal Number : ");
octnum = scan.nextInt();
orig = octnum;
while(octnum != 0)
{
decnum = decnum + (octnum%10) * (int) Math.pow(8, i);
i++;
octnum = octnum/10;
}
System.out.print("Equivalent Decimal Value of " + orig + " is :\n");
System.out.print(decnum);
}
}
output

Convert Octal to Binary


To convert octal to binary in Java Programming, you have to ask to the user to enter any number in
octal number format to convert it into equivalent binary number format to display the equivalent
value in binary number system as shown in the following program.
Java Programming Code to Convert Octal to Binary
Following Java Program ask to the user to enter any Octal Number to convert it into binary, then
display the result on the screen:
Program
/* Java Program Example - Convert Octal to Binary */
import java.util.Scanner;
public class JavaProgram2
{
public static void main(String args[])
{
int octnum, rem, quot, i=1, j;
int binnum[] = new int[100];
Scanner scan = new Scanner(System.in);

Page No 74
University Roll No 1507884

System.out.print("Enter Octal Number : ");


octnum = scan.nextInt();
quot = octnum;
while(quot != 0)
{
binnum[i++] = quot%2;
quot = quot/2;
}
System.out.print("Equivalent Binary Value of " +octnum+ " is :\n");
for(j=i-1; j>0; j--)
{
System.out.print(binnum[j]);
}
}
}
output

b) Convert Gray code to Binary


This is a Java Program to Convert Binary Code of a Number into its Equivalent Gray’s Code
Without Using Recursion. Gray code is a binary numeral system where two successive values differ
in only one bit.
Enter any binary number as an input. After that we perform operations like modulo and divsion to
convert it into gray code.
Here is the source code of the Java Program to Convert Binary Code of a Number into its
Equivalent Gray’s Code Without Using Recursion. The Java program is successfully compiled and
run on a Windows system. The program output is also shown below.
Program
import static java.lang.StrictMath.pow;
import java.util.Scanner;
public class Binary_Gray
{
public static void main(String[] args)
{
int a, b, x, result = 0, i = 0;
Scanner s = new Scanner(System.in);
System.out.print("Enter Binary number:");
x = s.nextInt();
while(x != 0)
{
a = x % 10;
x = x / 10;
b = x % 10;

Page No 75
University Roll No 1507884
if((a & ~ b) == 1 || (~ a & b) == 1)
{
result = (int) (result + pow(10,i));
}
i++;
}
System.out.println("Gray Code:"+result);
}
}
output

c) Half Adder
The half adder adds two one-bit binary numbers A and B. It has two outputs, S and C (the value
theoretically carried on to the next addition); the final sum is 2C + S. The simplest half-adder
design, pictured on the right, incorporates an XOR gate for S and an AND gate for C. With the
addition of an OR gate to combine their carry outputs, two half adders can be combined to make a
full adder.
Program
public class TruthTable
{
public void fullAdderTable()
{
boolean a,b,c,s,cr;
int x,y,z,sum,carry;
System.out.println(" x | y | z | c | s "); System.out.println("---|---|---|---|---"); // TRUTH
TABLE HEADER
for(x=0;x<2;x++){
for(y=0;y<2;y++){
for(z=0;z<2;z++){
a=(x==0)?false:true; b=(y==0)?false:true; c=(z==0)?false:true; //
INITIALIZING BOOLEAN VALUES IN BINARY FORM
s=!a&&!b&&c||a&&!b&&!c||!a&&b&&!c||a&&b&&c; cr=a&&b||b&&c||a&&c; //
FULL ADDER SUM AND CARRY CHECK OPERATION
sum=(s==false)?0:1; carry=(cr==false)?0:1; // CONVERTING BOOLEAN
SUM AND CARRY TO INTEGERS
System.out.println(" "+x+" | "+y+" | "+z+" | "+carry+" | "+sum); // PRINTING
EACH LINE OF TRUTH TABLE
}
}
}
}
public void halfAdderTable()
{
Page No 76
University Roll No 1507884
boolean a,b,s,cr;
int x,y,sum,carry;
System.out.println(" x | y | c | s "); System.out.println("---|---|---|---"); // TRUTH TABLE
HEADER
for(x=0;x<2;x++){
for(y=0;y<2;y++){
a=(x==0)?false:true; b=(y==0)?false:true; // INITIALIZING BOOLEAN VALUES
IN BINARY FORM
s=!a&&b||a&&!b; cr=a&&b; // FULL ADDER SUM AND CARRY CHECK
OPERATION
sum=(s==false)?0:1; carry=(cr==false)?0:1; // CONVERTING BOOLEAN
SUM AND CARRY TO INTEGERS
System.out.println(" "+x+" | "+y+" | "+carry+" | "+sum); // PRINTING EACH LINE
OF TRUTH TABLE
}
}
}
public static void main(String args[])
{
TruthTable obj=new TruthTable();
System.out.println("\nFull Adder Truth Table\n"); obj.fullAdderTable();
System.out.println("\nHalf Adder Truth Table\n"); obj.halfAdderTable();
}
}

output

Page No 77
University Roll No 1507884

d) Full Adder
A full adder adds binary numbers and accounts for values carried in as well as out. A one-bit full
adder adds three one-bit numbers, often written as A, B, and Cin; A and B are the operands, and Cin
is a bit carried in from the next less significant stage.[2] The full-adder is usually a component in a
cascade of adders, which add 8, 16, 32, etc. binary numbers. The circuit produces a two-bit output
sum typically represented by the signals Cout and S, where . The one-bit full adder's truth table is:
Program
import java.util.*;
class FULLADDER
{
public static void main(String args[])
{
int a[],b[];
Scanner sc=new Scanner(System.in);
System.out.println("ENTER NUMBER OF BITS : ");
int n=sc.nextInt();
a=new int[n];
b=new int[n];
System.out.println("ENTER ELEMENTS : \nA CONTAINS:");
for(int i=0;i<n;i++)
{
a[i]=sc.nextInt();
}
System.out.println("B CONTAINS ");
for(int i=0;i<n;i++)
{
b[i]=sc.nextInt();
}
int carry=0;
int sum[]=new int[n];
for(int i=n-1;i>=0;i++)
{
sum[i]=(a[i]+b[i]+carry)%2;
carry=(a[i]+b[i]+carry)/2;
}
System.out.print("FIRST BINARY NUMBER: ");
for(int i=0;i<n;i++)
{
System.out.print(a[i]);
}
System.out.println("");
System.out.print("SECOND BINARY NUMBER: ");
for(int i=0;i<n;i++)
{
System.out.print(b[i]);
}
System.out.println("");

System.out.print("SUM: ");
for(int i=0;i<n;i++)
Page No 78
University Roll No 1507884
{
System.out.print(sum[i]);
}
System.out.println("");
System.out.println("CARRY: "+carry);
}
}
output

Page No 79
University Roll No 1507884

32. Implement following concepts related to Operating


Systems:
a)  First come first serve scheduling algorithm
FCFS have a simple working rule the process which comes first will be executed first and then the
second and the third, this algorithm is easy to understand and implement.
Formulas for calculating Waiting time total time and turnaround time
turnaroundTime = completionTime - arrivalTime

waitingTime = turnaroundTime - bursts
Java Program for FCFS
Program
import java.util.Scanner;
class Process{
int wait;
int submission;
int bursts;
int turnAround;
int completionTime = 0;
Process(int sub,int bur){
submission = sub;
bursts = bur;
}
}
class Processmain{
public static void main(String[] args){
int wait = 0,x=0;
Scanner s = new Scanner(System.in);
System.out.println("Enter the number of processes:");
int n = s.nextInt();
Process[] myProcess = new Process[n];
for(int i=0;i<n;i++){
System.out.println("Enter Arrival time and bursts: ");
int sub = s.nextInt();
int bur = s.nextInt();
myProcess[i] = new Process(sub,bur);
}
for(int i=0;i<myProcess.length;i++){
x = x+myProcess[i].bursts;
myProcess[i].completionTime = x;
myProcess[i].turnAround = myProcess[i].completionTime -
myProcess[i].submission;
myProcess[i].wait = myProcess[i].turnAround - myProcess[i].bursts;
System.out.println("Process "+i+":");
System.out.println("Turnaround\tCompletion\twaiting");

System.out.println(myProcess[i].turnAround+"\t\t\t"+myProcess[i].completionTime+"\t\t\t"+
myProcess[i].wait);
}
}
}
Page No 80
University Roll No 1507884
output

b)  Shortest job first


A different approach to CPU scheduling is SJF shortest job first scheduling algorithm.This
associates with each process the length of the latter next CPU burst.When the CPU is available it is
assigned to the process that has the smallest next CPU burst.if two processes have same length next
CPU burst,FCFS scheduling is used to break the tie.Note that a more appropriate term would be the
shortest next CPU burst ,because the scheduling is done by examining the length of the next CPU
burst because the scheduling is done by examining the length of the next CPU burst of a
process,rather than its total length.The real difficulty in SJF shortest job first scheduling algorithm
is knowing the length of the next process.SJF shortest job first scheduling algorithm scheduling
algorithm is provably optimal.in that it gives the minimum average waiting time for a given set of
processes.

Page No 81
University Roll No 1507884
SJF shortest job first scheduling algorithm Program :
Program
import java.util.*;
class SJF {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int n, BT[], WT[], TAT[];
System.out.println("Enter no of process");
n = sc.nextInt();
BT = new int[n + 1];
WT = new int[n + 1];
TAT = new int[n + 1];
float AWT = 0;
System.out.println("Enter Burst time for each process");
for (int i = 0; i < n; i++) {
System.out.println("Enter BT for process " + (i + 1));
BT[i] = sc.nextInt();
}
for (int i = 0; i < n; i++) {
WT[i] = 0;
TAT[i] = 0;
}
int temp;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n - 1; j++) {
if (BT[j] > BT[j + 1]) {
temp = BT[j];
BT[j] = BT[j + 1];
BT[j + 1] = temp;
temp = WT[j];
WT[j] = WT[j + 1];
WT[j + 1] = temp;
}
}
}
for (int i = 0; i < n; i++) {
TAT[i] = BT[i] + WT[i];
WT[i + 1] = TAT[i];
}
TAT[n] = WT[n] + BT[n];
System.out.println(" PROCESS BT WT TAT ");
for (int i = 0; i < n; i++)
System.out.println(" " + i + " " + BT[i] + " " + WT[i] + " " + TAT[i]);
for (int j = 0; j < n; j++)
AWT += WT[j];
AWT = AWT / n;
System.out.println("***********************************************");
System.out.println("Avg waiting time=" + AWT +
"\n***********************************************");
}
}

Page No 82
University Roll No 1507884
output

c)  Condition for Occurrence of deadlock


Deadlock in java is a programming situation where two or more threads are blocked forever. Java
deadlock situation arises with at least two threads and two or more resources. Here I have written a
simple program that will cause java deadlock scenario and then we will see how to analyze it.
Let’s have a look at a simple program where I will create deadlock in java threads.
Program
// Java program to illustrate Deadlock
// in multithreading.
class Util
{
static void sleep(long millis)
{
try
{
Thread.sleep(millis);
}
Page No 83
University Roll No 1507884
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
class Shared
{
synchronized void test1(Shared s2)
{
System.out.println("test1-begin");
Util.sleep(1000);
s2.test2(this);
System.out.println("test1-end");
}
synchronized void test2(Shared s1)
{
System.out.println("test2-begin");
Util.sleep(1000);
s1.test1(this);
System.out.println("test2-end");
}
}
class Thread1 extends Thread
{
private Shared s1;
private Shared s2;
public Thread1(Shared s1, Shared s2)
{
this.s1 = s1;
this.s2 = s2;
}
@Override
public void run()
{
// taking object lock of s1 enters
// into test1 method
s1.test1(s2);
}
}
class Thread2 extends Thread
{
private Shared s1;
private Shared s2;
public Thread2(Shared s1, Shared s2)
{
this.s1 = s1;
this.s2 = s2;
}
@Override
public void run()
{
Page No 84
University Roll No 1507884
s2.test2(s1);
}
}
public class GFG
{
public static void main(String[] args)
{
Shared s1 = new Shared();
Shared s2 = new Shared();
Thread1 t1 = new Thread1(s1, s2);
t1.start();
Thread2 t2 = new Thread2(s1, s2);
t2.start();
Util.sleep(2000);
}
}
output

d)  Multithreading approach to do Matrix multiplication


Program
import java.lang.*;
import java.io.*;
class MatMulti extends Thread{
static int in1[][];
static int in2[][];
static int out[][];
static int n=2;
int row;
MatMulti(int i){
row=i;
this.start();
}
public void run(){
int i,j;
for(i=0;i<n;i++)
{
out[row][i]=0;
for(j=0;j<n;j++)
out[row][i]=out[row][i]+in1[row][j]*in2[j][i];
}
}
public static void main(String args[]){
int i,j;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
Page No 85
University Roll No 1507884
System.out.print("Enter the order of Matrix : ");
try{
n=Integer.parseInt(br.readLine());
}catch(Exception e){}
in1=new int[n][n];
in2=new int[n][n];
out=new int[n][n];
System.out.println("Enter the First Matrix : ");
for(i=0;i<n;i++){
for(j=0;j<n;j++){
try{
in1[i][j]=Integer.parseInt(br.readLine());
}catch(Exception e){}
}
}
System.out.println("Enter the Second Matrix : ");
for(i=0;i<n;i++){
for(j=0;j<n;j++){
try
{
in2[i][j]=Integer.parseInt(br.readLine());
}catch(Exception e){}
}
}
MatMulti mat[]=new MatMulti[n];
for(i=0;i<n;i++)
mat[i]=new MatMulti(i);
try{
for(i=0;i<n;i++)
mat[i].join();
}catch(Exception e){}
System.out.println("OUTPUT :");
for(i=0;i<n;i++)
for(j=0;j<n;j++)
System.out.println(out[i][j]);
}
}
output


Page No 86
University Roll No 1507884


33. Implement following concepts related to Computer
Networks:
a)  Sliding window sender
The Stop and Wait ARQ offers error and flow control, but may cause big performance issues as
sender always waits for acknowledgement even if it has next packet ready to send. Consider a
situation where you have a high bandwidth connection and propagation delay is also high (you are
connected to some server in some other country though a high speed connection), you can’t use this
full speed due to limitations of stop and wait.
Program
import java.io.DataInputStream;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
public class slidsender
{
public static void main(String a[])throws Exception
{
ServerSocket ser=new ServerSocket(7870);
Socket s=ser.accept();
DataInputStream in=new DataInputStream(System.in);
DataInputStream in1=new DataInputStream(s.getInputStream());
String sbuff[]=new String[8];
PrintStream p;
int sptr=0,sws=8,nf,ano,i;
String ch;
do
{
p=new PrintStream(s.getOutputStream());
System.out.print("Enter the no. of frames : ");
nf=Integer.parseInt(in.readLine());
p.println(nf);
if(nf<=sws-1)
{
System.out.println("Enter "+nf+" Messages to be send\n");
for(i=1;i<=nf;i++)
{
sbuff[sptr]=in.readLine();
p.println(sbuff[sptr]);
sptr=++sptr%8;
}
sws-=nf;
System.out.print("Acknowledgment received");
ano=Integer.parseInt(in1.readLine());
System.out.println(" for "+ano+" frames");
sws+=nf;
}
else
{
Page No 87
University Roll No 1507884
System.out.println("The no. of frames exceeds window size");
break;
}
System.out.print("\nDo you wants to send some more frames : ");
ch=in.readLine(); p.println(ch);
}
while(ch.equals("yes"));
s.close();
}
}
output
//SENDER OUTPUT
Enter the no. of frames : 4
Enter 4 Messages to be send
hi
how r u
i am fine
how is everyone
Acknowledgment received for 4 frames
Do you wants to send some more frames : no
b)  Sliding window receiver
Sliding Window Protocol is actually a theoretical concept in which we have only talked about what
should be the sender window size (1+2a) in order to increase the efficiency of stop and wait arq.
Now we will talk about the practical implementations in which we take care of what should be the
size of receiver window. Practically it is implemented in two protocols namely :
1. Go Back N (GBN)
2. Selective Repeat (SR)
In this article, we will explain you about the first protocol which is GBN in terms of three main
characteristic features and in the last part we will be discussing SR as well as comparison of both
these protocols
Program
import java.net.*;
import java.io.*;
class slidreceiver
{
public static void main(String a[])throws Exception
{
Socket s=new Socket(InetAddress.getLocalHost(),10);
DataInputStream in=new DataInputStream(s.getInputStream());
PrintStream p=new PrintStream(s.getOutputStream());
int i=0,rptr=-1,nf,rws=8;
String rbuf[]=new String[8];
String ch; System.out.println();
do
{
nf=Integer.parseInt(in.readLine());
if(nf<=rws-1)
{

Page No 88
University Roll No 1507884
for(i=1;i<=nf;i++)
{
rptr=++rptr%8;
rbuf[rptr]=in.readLine();
System.out.println("The received Frame " +rptr+" is : "+rbuf[rptr]);
}
rws-=nf;
System.out.println("\nAcknowledgment sent\n");
p.println(rptr+1); rws+=nf; }
else
break;
ch=in.readLine();
}
while(ch.equals("yes"));
}
}
output
//RECEIVER OUTPUT
The received Frame 0 is : hi
The received Frame 1 is : how r u
The received Frame 2 is : i am fine
The received Frame 3 is : how is everyone
Acknowledgment sent
c)  To create a program for the implementation of
ARP(Address Resolution Protocol)
When the router and every other host on the local network receives the frame, they will look at the
destination MAC address to determine if they should pay attention to the frame. They will all see
the broadcast MAC address as the destination so all will open the message and read it. Once the
other hosts see the message is an ARP request for an IP address other than their own, they will
discard the frame and do nothing. The router will read the message, compare the IP address (the
default gateway) to its own, and discover someone has sent it an ARP request. It is now required to
send an ARP response.

Program
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Scanner;
public class MacAddress {
public static void main(String[] args)
{
try
{
Scanner console = new Scanner(System.in);
System.out.println("Enter System Name: ");
String ipaddr = console.nextLine();
InetAddress address = InetAddress.getByName(ipaddr);
Page No 89
University Roll No 1507884
System.out.println("address = "+address);
NetworkInterface ni = NetworkInterface.getByInetAddress(address);
if (ni!=null)
{
byte[] mac = ni.getHardwareAddress();
if (mac != null)
{
System.out.print("MAC Address : ");
for (int i=0; i<mac.length; i++)
{
System.out.format("%02X%s", mac[i], (i<mac.length - 1) ? "-" :"");
}
}
else
{
System.out.println("Address doesn't exist or is not accessible/");

}
}
else
{
System.out.println("Network Interface for the specified address is not found");
}
}
catch(UnknownHostException | SocketException e)
{
}
}
}
output

Page No 90
University Roll No 1507884

d)  To create a program for the implementation of RARP


(Reverse Address Resolution Protocol)
Reverse Address Resolution Protocol (RARP) is a protocol used by a client computer in demanding
for its IP address from another network. It is an obsolete protocol used in computer networking and
usually has its hardware address and the link layer.
Program
// RARP.java - Client
import java.io.*;
import java.net.*;
import java.util.*;
public class RARP {
public static void main(String args[]){
try{
DatagramSocket client = new DatagramSocket();
InetAddress addr = InetAddress.getByName("127.0.0.1");
byte[] sendByte = new byte[1204];
byte[] receiveByte = new byte[1024];
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the Physical Address ");
String str = in.readLine();
sendByte = str.getBytes();
DatagramPacket sender = new DatagramPacket(sendByte,sendByte.length,addr,
1309);
client.send(sender);
DatagramPacket receiver = new DatagramPacket(receiveByte,receiveByte.length);
client.receive(receiver);
String s = new String(receiver.getData());
System.out.println("The Logical Address is :" + s.trim());
client.close();
}
catch(Exception e){
System.out.println(e);
}
}
}
// RARPServer.java - Server
import java.io.*;
import java.net.*;
import java.util.*;

public class RARPServer{

public static void main(String args[]) {


try{

DatagramSocket server = new DatagramSocket(1309);


while(true){
byte[] sendByte = new byte[1204];
byte[] receiveByte = new byte[1204];

Page No 91
University Roll No 1507884
DatagramPacket receiver = new
DatagramPacket(receiveByte,receiveByte.length);
server.receive(receiver);
String str = new String(receiver.getData());
String s = str.trim();
InetAddress addr = receiver.getAddress();
int port = receiver.getPort();
String ip[] = {"10.0.3.186"};
String mac[] = {"D4:3D:7E:12:A3:D9"};

for (int i = 0; i < ip.length; i++) {


if(s.equals(mac[i]))
{
sendByte = ip[i].getBytes();
DatagramPacket sender = new
DatagramPacket(sendByte,sendByte.length,addr,port);
server.send(sender);
break;
}
}
break;
}
}catch(Exception e)
{
System.out.println(e);
}
}
}
output

Page No 92

Potrebbero piacerti anche