Programming in Java Laboratory File
Programming in Java Laboratory File
Practical File
Of
Programming in Java
Submitted by
Aakash Raj
Bachelor of technology
At
Date: Date:
INDEX
2 Type casting 6
3 Arrays – 1D and 2 D 8
6 Recursion 15
13 Abstract class 29
14 Nested class 30
15 Constructor chaining 33
25 Event Handling 49
byte a = 50;
byte b = (byte) -80;
void add() {
class MainClass {
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
Page No 9
University Roll No 1507884
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
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
Page No 15
University Roll No 1507884
//Overloaded constructor:
new MyClass();
}
}
output
Page No 16
University Roll No 1507884
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");
}
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
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
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.
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
Program
class Vehicle{
void run(){System.out.println("Vehicle is running");}
}
class Bike extends Vehicle{
output
Program
class Vehicle1{
void run(){System.out.println("Vehicle is running");}
}
class Bike2 extends Vehicle1{
void run(){System.out.println("Bike is running safely");}
Page No 26
University Roll No 1507884
output
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
output
Page No 29
University Roll No 1507884
}
}
}
// 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);
}
}
}
// 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
Page No 33
University Roll No 1507884
Page No 34
University Roll No 1507884
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
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
Page No 39
University Roll No 1507884
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
Page No 42
University Roll No 1507884
output
Page No 43
University Roll No 1507884
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.
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
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
Page No 49
University Roll No 1507884
//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
Page No 50
University Roll No 1507884
output
Page No 51
University Roll No 1507884
} while(chr != 'q');
}
}
output
Page No 52
University Roll No 1507884
Page No 53
University Roll No 1507884
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
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
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.
Page No 65
University Roll No 1507884
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
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
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
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
Page No 74
University Roll No 1507884
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
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
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
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
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"};
Page No 92