0% found this document useful (0 votes)
528 views

Java Lab Record PDF

This certificate certifies that Mr./Ms. [Name] with Registration No. [Number] is a student of B.Tech 2-1 Semester who has successfully completed [Number] experiments in [Lab Name] Lab during the academic year 2020-2021 as verified by the Faculty In Charge, Head of the Department, and External Examiner.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
528 views

Java Lab Record PDF

This certificate certifies that Mr./Ms. [Name] with Registration No. [Number] is a student of B.Tech 2-1 Semester who has successfully completed [Number] experiments in [Lab Name] Lab during the academic year 2020-2021 as verified by the Faculty In Charge, Head of the Department, and External Examiner.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 98

Department of

INFORMATION TECHNOLOGY

CERTIFICATE

This is to certify that Mr./Ms.______________________________________

bearing Regd. No. _____________________ is a student of B.Tech 2-1 Semester

has successfully completed ____________ experiments in

___________________________ Lab during the academic year 2020-2021.

Faculty In charge Head of the Department

External Examiner

Page 1 of 98
INDEX

Name of the Lab:

S. No Date Title of the Experiment Page No. Marks & Sign

Page 2 of 98
Page 3 of 98
Exercise-1

a. Write a Java program to print “Welcome”.


PROCEDURE:

CODE:

public class HelloWorld


{
public static void main(String []args)
{
//printing the message
System.out.println("Welcome!");
}
}

OUTPUT:

Page 4 of 98
b. Write a java program to read the different types of data from the user and display that data
using Scanner class.

PROCEDURE:

What is the use of Scanner Class?

Page 5 of 98
CODE:

Import java.util.Scanner;
class HelloWorld
{
public static void main(String args[])
{
// Using Scanner for Getting Input from User
Scanner in = new Scanner(System.in);

String s = in.nextLine();
System.out.println("You entered string "+s);

int a = in.nextInt();
System.out.println("You entered integer "+a);

float b = in.nextFloat();
System.out.println("You entered float "+b);
}
}

OUTPUT:

Page 6 of 98
c. Write a java program to read the different types of data from the user and display that data
using command line arguments.
PROCEDURE:

CODE:

class A
{
public static void main(String args[])
{
System.out.println("Your first argument is: "+args[0]);

System.out.println("Your Second argument is: "+args[1]);

System.out.println("Your third argument is: "+args[2]);


}
}

OUTPUT:

Page 7 of 98
d. Write a Java program to illustrate type conversions.
PROCEDURE:

Explain Widening Casting?

Page 8 of 98
CODE:

public class Test


{
public static void main(String[] args)
{
int i = 100;
long l = i; //no explicit type casting required
float f = l; //no explicit type casting required
System.out.println("Int value "+i);
System.out.println("Long value "+l);
System.out.println("Float value "+f);
}
}

OUTPUT:

Explain Narrowing Casting?

Page 9 of 98
CODE:

public class Test


{

public static void main(String[] args)


{

double d = 100.04;
long l = (long)d; //explicit type casting required
int i = (int)l; //explicit type casting required

System.out.println("Double value "+d);


System.out.println("Long value "+l);
System.out.println("Int value "+i);
}
}

OUTPUT:

Page 10 of 98
e. Write a java program to observe the effects of various bitwise operators.
PROCEDURE:

What are the various Operators available in Java?

Page 11 of 98
CODE:
public class operators {
public static void main(String[] args)
{
//Initial values
int a = 5;
int b = 7;

// bitwise and
// 0101 & 0111=0101 = 5
System.out.println("a&b = " + (a & b));

// bitwise or
// 0101 | 0111=0111 = 7
System.out.println("a|b = " + (a | b));

// bitwise xor
// 0101 ^ 0111=0010 = 2
System.out.println("a^b = " + (a ^ b));

// bitwise and
// ~0101=1010
// will give 2's complement of 1010 = -6
System.out.println("~a = " + ~a);

// can also be combined with assignment operator to provide shorthand assignment


a=a&b
a&= b;
System.out.println("a= " + a);
}
}

OUTPUT:

Page 12 of 98
Exercise-2

a. Write a Java program to find largest number out of 3 numbers using nested if.
PROCEDURE:

An IF-ELSE statement is also called _______________________________________.

An IF or ELSE IF statement accepts _____________________ as input before branching.

Every IF statement must be followed by an ELSE of ELSE-IF statement. (True/False)

Page 13 of 98
CODE:
public class LargestNestedIfDemo{
public static void main(String[] args)
{
int num1 = 36, num2 = 35, num3 = 56;
if(num1 >= num2)
{
if(num1 >= num3)
{
System.out.println(num1 + " is largest number.");
}
else
{
System.out.println(num3 + " is largest number.");
}
}
else
{
if(num2 >= num3)
{
System.out.println(num2 + " is largest number.");
}
else
{
System.out.println(num3 + " is largest number.");
}
}
}
}

OUTPUT:

Page 14 of 98
b. Raju’s parents are celebrating their marriage anniversary. They have arranged a small party
tonight. They are expecting their colleagues and Raju’s friends to attend the party. They have
planned to serve ‘Coke’ and ‘Badam Milk’ to these guests. But they would like to serve
‘Badam Milk’ to teenagers and ‘Coke’ to adults. Please help them in finding teenagers and
adults based on age. Now, Write a Java program to find out the adults and teenagers based on
their age. Note: Teenagers are those whose age is between 13 and 19 (both inclusive).
PROCEDURE:

A BREAK statement inside a Loop like WHILE, FOR, DO WHILE and Enhanced-FOR causes
the program execution __________ Loop.

What is a loop in Java Programming?

Page 15 of 98
Code:
Import java.util.*;

public class Q1
{
public static void main(String[] args)
{
System.out.print("Enter number of Guests:");
Scanner sc = new Scanner(System.in);
Int n,i,age;
n = sc.nextInt();
for(i=1; i<=n; i++)
{
System.out.println("Welcome Guest "+i+", How old are you? ");
age = sc.nextInt();
if(age >= 13 & age <= 19)
System.out.println("Hey Teenager! Enjoy yor Badam
Milk..Nothing fancy for you\n");
else if(age > 19)
System.out.println("Hey your Adult! Here is your coke :P\n");
}
}
}

OUTPUT:

Page 16 of 98
c. There is a telecommunication company called “Powered Air” who have approached you to
build their Interactive Voice Response (IVR) system. You should write a Java program and
be able to provide the following menu (given below):
Welcome to Powered Air Service. Whatwould you like to do?
Know my balance
Know my validity date
Know number of free calls available
More
Prepaid Bill Request
Customer Preferences
GPRS activation
Special Message Offers
Special GPRS Offers
3G Activation
Go back to previous menu-If user types in 7 the first menu should be displayed. You are free to
display your own messages
in this IVR

PROCEDURE

Page 17 of 98
Code:

import java.util.*;

public class Q2
{
static Scanner sc = new Scanner(System.in);
static int option;

public static void main(String[] args)


{
System.out.println("Welcome to Powered Air Service. What would like to do?");

while(true)
{

System.out.println(" 1.Know my balance.\n 2.Know my validity date.\n


3.Know number of free calls available.\n 4.More\n 5.Exit");
option = sc.nextInt();
switch(option)
{
case 1: balance(); break;
case 2: validity(); break;
case 3: free_calls(); break;
case 4: more(); break;
case 5: exit(); break;
default: System.out.println("Invalid Option.");break;
}
}
}

public static void balance()


{
// code to check balance
System.out.println("Your current balance is \"Balance\".\n");
}
public static void validity()
{
// code to check validity
System.out.println("Your current package expires on \"Date\".\n");
}
public static void free_calls()
{
// code to check free calls
System.out.println("You have \"FreeCalls\" left.\n");
}

Page 18 of 98
public static void more()
{
more: while(true)//labeling the loop
{
System.out.println(" 1.Prepaid Bill Request.\n 2.Customer Preference.\n
3.GPRS activation.\n 4.Special Message Offer\n 5.Special GPRS offer.\n 6.3G Activation. \n
7.back <-");
option = sc.nextInt();
switch(option)
{
case 1: System.out.println("This is option 1 in more\n"); break;
case 2: System.out.println("This is option 2 in more\n"); break;
case 3: System.out.println("This is option 3 in more\n"); break;
case 4: System.out.println("This is option 4 in more\n"); break;
case 5: System.out.println("This is option 5 in more\n"); break;
case 6: System.out.println("This is option 6 in more\n"); break;
case 7: break more;
default: System.out.println("Invalid Option.");break;
}
}
}
public static void exit()
{
// code to know balance
System.out.println("Thank You!");
System.exit(0);
}
}

OUTPUT:

Page 19 of 98
Exercise-3 a
Java program that prompts the user for an integer and the
a. Write a Java program that prompts the user for an integer and then prints out all prime
numbers up to that integer.

PROCEDURE

Page 20 of 98
CODE:
import java.util.Scanner;
public class PrimeNumbers {
public static void main(String[] args)
{
int n;
int p;
Scanner s=new Scanner(System.in);
System.out.println("Enter a number: ");
n=s.nextInt();
for(int i=2;i<n;i++)
{
p=0;
for(int j=2;j<i;j++)
{
if(i%j==0)
p=1;
}
if(p==0)
System.out.println(i);
}
}
}

OUTPUT:

Page 21 of 98
b. Write a java program to find the sum of even numbers up to 100.
PROCEDURE

Page 22 of 98
CODE:
import java.util.Scanner;

public class SumofEven1 {


private static Scanner sc;
public static void main(String[] args)
{
int number, i, evenSum = 0;
sc = new Scanner(System.in);

System.out.print(" Please Enter any Number : ");


number = sc.nextInt();

for(i = 1; i <= number; i++)


{
if(i % 2 == 0)
{
evenSum = evenSum + i;
}
}
System.out.println("\n The Sum of Even Numbers upto " + number + " = " +
evenSum);
}
}

OUTPUT:

Page 23 of 98
c. Write a java program to print the following output.

1
23
456
7 8 9 10

PROCEDURE

Page 24 of 98
CODE:

import java.util.Scanner;

public class Pattern {


public static void main(String[] args) {
int i, j, k = 1;
for (i = 1; i <= 4; i++) {
for (j = 1; j< i + 1; j++) {
System.out.print(k++ + " ");
}

System.out.println();
}
}
}

OUTPUT:

Page 25 of 98
d. Write a program in Java to print the Floyd’s Triangle.

1
01
101
0101
10101

PROCEDURE

Page 26 of 98
CODE:
public class floyd
{
public static void main(String[] args)
{
int i,j,n,p,q;
System.out.print("Input number of rows : ");
Scanner in = new Scanner(System.in);
n = in.nextInt();
for(i=1;i<=n;i++)
{
if(i%2==0)
{
p=1;q=0;
}
else
{
p=0;q=1;
}
for(j=1;j<=i;j++)
if(j%2==0)
System.out.print(p);
else
System.out.print(q);
System.out.println("");
}
}

OUTPUT:

Page 27 of 98
e. Write a Java program to print Fibonacci series using for loop.
PROCEDURE

Page 28 of 98
CODE:
import java.util.*;

public class Q3a


{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number to print Fibonaciiupto.. ");
int n = sc.nextInt();
if ( n == 0)
System.out.print("0");
else if(n == 1)
System.out.print("0 1");
else
{
int k, k1=0, k2=1, i;
System.out.print("0 1 ");

// f(k) = f(k-1) + f(k-2)


for (i=2; i<n; i++)
{
k = k1 + k2;
System.out.print(k+" ");
k1 = k2;
k2 = k;
}
}
}
}

OUTPUT:

Page 29 of 98
f. Write a Java program to check whether given number is Armstrong or not using while
loop.
PROCEDURE

Page 30 of 98
CODE:

import java.util.Scanner;

public class Q3b


{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number to check if its Armstrong or not.. ");
int n = sc.nextInt();
int check = 0, dig, tmp = n;
while(n>0)
{
dig = n%10;
check += Math.pow(dig,3);
n /= 10;
}
if(tmp == check)
System.out.println("Armstrong");
else
System.out.println("Not Armstrong");
}
}

OUTPUT:

Page 31 of 98
Exercise-4

a. Write a Java program to read 10 numbers from user and store it in an array. Display the
maximum and minimum number in the array.
PROCEDURE

Page 32 of 98
CODE:
import java.util.*;

public class Q4a


{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int[] numbers = new int[10];
int min = Integer.MAX_VALUE, max = Integer.MIN_VALUE, num;

System.out.println("Enter 10 numbers:");
for(int i=0; i<10; i++)
{
num = sc.nextInt();
numbers[i] = num;
if(num< min) min = num;
if(num> max) max = num;
}

System.out.println("Maximum number in array:"+max);


System.out.println("Minimun number in array:"+min);
}
}

OUTPUT:

Page 33 of 98
b. Write a java program to sort the given list of elements in an array.
PROCEDURE

Page 34 of 98
CODE:
import java.util.*;

public class Q4b


{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter Number of elements in array:");
int n = sc.nextInt();
int[] numbers = new int[n];
int num;
System.out.println("Enter "+n+" numbers:");
for(int i=0; i<n; i++)
{
num = sc.nextInt();
numbers[i] = num;
}
for (int i = 0; i < n-1; i++)
for (int j = 0; j < n-i-1; j++)
if (numbers[j] > numbers[j+1])
{
int temp = numbers[j];
numbers[j] = numbers[j+1];
numbers[j+1] = temp;
}

System.out.println("sorted aray is:");


for(int number: numbers)
System.out.print(number+" ");
}

OUTPUT:

Page 35 of 98
c. Write a Java program to search a given element in the array.
PROCEDURE

Page 36 of 98
CODE:
import java.util.*;
public class Q4c
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter Number of elements in array:");
int n = sc.nextInt();
int[] numbers = new int[n];
int num,i;
System.out.println("Enter "+n+" numbers:");
for(i=0; i<n; i++)
{
num = sc.nextInt();
numbers[i] = num;
}
System.out.print("Enter Element to be searched:");
int x = sc.nextInt();
boolean found = false;
for (i = 0; i < n-1; i++)
if(numbers[i] == x)
{
found = true;
break;
}
if(found)
System.out.println(x+" Found at index "+i);
else
System.out.println(x+" not found.");

OUTPUT:

Page 37 of 98
d. Write a Java program to calculate multiplication of 2 matrices.
PROCEDURE

Page 38 of 98
CODE:
import java.util.Scanner;

class MatrixMultiplication
{
public static void main(String args[])
{
int m, n, p, q, sum = 0, c, d, k;

Scanner in = new Scanner(System.in);


System.out.println("Enter the number of rows and columns of first matrix");
m = in.nextInt();
n = in.nextInt();

int first[][] = new int[m][n];

System.out.println("Enter elements of first matrix");

for (c = 0; c < m; c++)


for (d = 0; d < n; d++)
first[c][d] = in.nextInt();

System.out.println("Enter the number of rows and columns of second matrix");


p = in.nextInt();
q = in.nextInt();

if (n != p)
System.out.println("The matrices can't be multiplied with each other.");
else
{
int second[][] = new int[p][q];
int multiply[][] = new int[m][q];

System.out.println("Enter elements of second matrix");

for (c = 0; c < p; c++)


for (d = 0; d < q; d++)
second[c][d] = in.nextInt();

for (c = 0; c < m; c++) {

Page 39 of 98
for (d = 0; d < q; d++) {
for (k = 0; k < p; k++)
sum = sum + first[c][k]*second[k][d];

multiply[c][d] = sum;
sum = 0;
}
}

System.out.println("Product of the matrices:");

for (c = 0; c < m; c++) {


for (d = 0; d < q; d++)
System.out.print(multiply[c][d]+"\t");

System.out.print("\n");
}
}
}
}

OUTPUT:

Page 40 of 98
Exercise-5
a. Write a java program to check weather given string is palindrome or not.
PROCEDURE

What is String Class in Java?

Page 41 of 98
CODEe a java program to check weather given string is palindrome or not.
import java.util.Scanner;

public class palindrome {


public static void main(String arg[])
{
int num,t,s,rem;
Scanner sc=new Scanner(System.in);
System.out.println("Enter any number ");
num=sc.nextInt();
t=num;
for(s=0;num>0;num/=10)
{
rem=num%10;
s=(s*10)+rem;
}
if(s==t)
System.out.println(t+" is a palindrome number ");
else
System.out.println(t+" is not a palindrome number ");
}

OUTPUT:

Page 42 of 98
b. Write a Java Program that reads a line of integers, and then displays each integer, andthe
sum of all the integers (use String Tokenizer class)
PROCEDURE

What is String Tokenizer class? What is its importance?

Page 43 of 98
CODE:
import java.util.*;

public class Q3c


{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);

System.out.println("Enter Numbers in a single line(seperated by space): ");


String numberLine = sc.nextLine();
StringTokenizer arr = new StringTokenizer(numberLine, " ");

System.out.println("Entered numbers are...");

int sum = 0, num;


while(arr.hasMoreTokens())
{
num = Integer.parseInt(arr.nextToken());
System.out.println(num);
sum += num;
}

System.out.println("Sum of all numbers:"+sum);


}
}

OUTPUT:

Page 44 of 98
c. Write a Java program for sorting a given list of names in ascending order.
PROCEDURE

List any 5 String Class Methods with its use?

Page 45 of 98
CODE:
import java.util.*;

public class Q3d


{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);

System.out.print("Enter Number of Names... ");

intnum = sc.nextInt();

List<String> names = new ArrayList<String>();


for (; num>=0; num--)
{
names.add(sc.nextLine());
}

Collections.sort(names);
for(String name:names)
System.out.println(name);
}
}

OUTPUT:

Page 46 of 98
d. Write a Java program that displays the number of characters, lines and words in a text
file.
PROCEDURE

Explain Java File class?

What is the use of hasNextLine () method?

Page 47 of 98
CODE:
import java.util.*;
import java.io.*;

public class Q3e


{
public static void main(String[] args)
{
File fileObject = new File("Test.txt");
try
{
Scanner fileReader = new Scanner(fileObject);
intcharCount=0, wordCount=0, lineCount=0;
while(fileReader.hasNextLine())
{
String line = fileReader.nextLine();
String[] words = line.split(" ");

charCount += line.length();
wordCount += words.length;
lineCount++;
}
System.out.println("Number of
lines:"+lineCount+"\nNumber of words:"+wordCount+"\nNumber of
characters:"+charCount);
}
catch(FileNotFoundException e)
{
System.out.println("File Not Found");
}
}

OUTPUT:

Page 48 of 98
Exercise-6 (CLASS, OBJECTS AND METHODS)
a. Create a class Rectangle. The class has attributes length and width. It should
havemethods that calculate the perimeter and area of the rectangle. It should have
readAttributes method to read length and width from user.
PROCEDURE

What is a class, method and Object?

Page 49 of 98
CODE:

class Rectangle
{
private int Length=0;
private int Width=0;

public void setSize(int L, int W)


{
Length = L;
Width = W;
}
public int area()
{
return Length * Width;
}
public int perimeter()
{
return 2*(Length + Width);
}
}

public class Q5a


{
public static void main(String[] args)
{
Rectangle rec = new Rectangle();//default 0x0
rec.setSize(5,10);
System.out.println("Area:"+rec.area());
System.out.println("Perimeter:"+rec.perimeter());
}
}

OUTPUT:

Page 50 of 98
b. Design a class “Company” which has as attributes yearOfEstablishment,
AnnualTurnover, annualSales, etc. Moreover, these details need to be available to
theoutside world. Have appropriate methods for displaying these details.

You will also need to calculate the profitability of this company (if
annualTurnover/annualSales > 1 thenprofitability is high; <0.5 then profitability is low;
between 0.5 and 1 then profitability ismedium).

PROCEDURE

What is Encapsulation in Java?

Page 51 of 98
CODE:
import java.util.*;

class Company
{
private static int year;
private static double annualTurnover;
private static double annualSales;

protected static void setYear(int n){ year = n; }


protected static void setAnnualTurnover(double n){ annualTurnover = n;
}
protected static void setAnnualSales(double n){ annualSales = n; }

public static int getYear(){ return year; }


public static double getAnnualTurnover(){ return annualTurnover; }
public static double getAnnualSales(){ return annualSales; }

public static String getProfitability()


{
double ratio = annualTurnover/annualSales;
if (ratio > 1.0)
return "High";
if (ratio > 0.5)
return "Medium";
return "Low";
}

class Apple extends Company

Page 52 of 98
{
public Apple()
{
Company.setYear(1976);
Company.setAnnualTurnover(101839); //gross profit in Millions
(for google 77,270)
Company.setAnnualSales(163756); //goods sold in Millions (for
google 59,549)
}
}

class PUBLIC
{
public static void main(String[] args)
{
Apple apple = new Apple();
System.out.println(apple.getProfitability());
}
}

OUTPUT:

Page 53 of 98
c. Write a java program that implements method overloading.
PROCEDURE

What is method overloading? List all the cases where the method will overload?

Page 54 of 98
CODE:
public class Example {

public void add ( int a, int b)


{
System.out.println(a+b);
}

public void add ( int a, int b, int c)


{
System.out.println(a+b+c);
}

public void add ( int a, double b)


{
System.out.println(a+b);
}

public static void main(String args[]) {

Example e = new Example();

e.add(1, 2);
e.add(1,2,3);
e.add(1,2.5);

}
}

OUTPUT:

Page 55 of 98
Exercise-7 (INHERITANCE, POLYMORHISM AND INTERFACES)

a. Write a java program to implement various types of inheritance.


i. Single ii. Multi-Level iii. Hierarchical iv. Hybrid

PROCEDURE:

What is inheritance?

What is Single inheritance?

Page 56 of 98
SINGLE

class A
{
protected static void method_A()
{
System.out.println("Method A in class A");
}
}

class B extends A
{
public static void main(String[] args)
{
method_A(); // using objects from extended class without creating class
object
}
}

OUTPUT:

Page 57 of 98
What is Multi-level inheritance?

Multi-level (CODE)

class A
{
protected static void method_A()
{
System.out.println("Method A in class A");
}
}

class B extends A
{
protected static void method_B()
{
System.out.println("Method B in class B");
}
}

class C extends B
{
public static void main(String[] args)
{
method_B(); //direct or single inheritance
method_A(); //Multi-level inheritance
}
}

OUTPUT:

Page 58 of 98
What is hierarchical Inheritance?

What is the difference between Inheritance and Abstraction?

What is the use of Super Keyword?

What is a Constructor?

Page 59 of 98
Hierarchical (CODE)

class A
{
protected static void method_A()
{
System.out.println("Method A in class A");
}
}

class B extends A
{
protected static void method_B()
{
System.out.println("Method B in class B");
}
}
class C extends A
{
protected static void method_C()
{
System.out.println("Method C in class C");
}
}
class Q5a
{
public static void main(String[] args)
{
// method_B(); will throw an error

C a = new C();
a.method_A();
a.method_C();
}
}

OUTPUT:

Page 60 of 98
Hybrid

class A
{
protected static void method_A()
{
System.out.println("Method A in class A");
}
}

class B extends A
{
protected static void method_B()
{
System.out.println("Method B in class B");
}
}

class C extends A
{
protected static void method_C()
{
System.out.println("Method C in class C");
}

class D extends C
{
public static void main(String[] args)
{
method_A();
method_C();
}
}

OUTPUT:

Page 61 of 98
b. Create an abstract class Media (id, description). Derive classes Book (page count) and
CD (playtime). Define parameterized constructors. Create one object of Book and CD
each and display the details.
PROCEDURE:

What is Abstraction?

What is an Abstract class and Abstract Method?

Page 62 of 98
CODE:

AbstractMedia.java
public abstract class AbstractMedia {

public int id;


public String description;

public void SetValues(int id, String Description){


this.id = id;
this.description = Description;
}
abstract void printDetails();
/**
* @return the id
*/
public int getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(int id) {
this.id = id;
}
/**
* @return the description
*/
public String getDescription() {
return description;
}
/**
* @param description the description to set
*/
public void setDescription(String description) {
this.description = description;
}
}

AbstractDemo.java

public class AbstractDemo {

Page 63 of 98
public static void main(String[] args) {
Book book = new Book(10001,"Tale of Two Cities",200);
book.printDetails();

CD cd = new CD(10002, "Titanic","2hr30mins");

cd.printDetails();

Book.java

public class Book extends AbstractMedia{


private int pageCount;

public Book(int id, String Description, int pageCount){


this.pageCount = pageCount;
SetValues(id, Description);
}
public void printDetails() {
System.out.println("ID :"+getId());
System.out.println("Description :"+getDescription());
System.out.println("PageCount :"+pageCount);

/**
* @return the pageCount
*/
public int getPageCount() {
return pageCount;
}
/**
* @param pageCount the pageCount to set
*/
public void setPageCount(int pageCount) {
this.pageCount = pageCount;
}

CD.java

public class CD extends AbstractMedia {

Page 64 of 98
private String playTime;

public CD(int id, String Description, String playTime){


this.playTime = playTime;
SetValues(id, Description);
}
public void printDetails() {
System.out.println("ID :"+getId());
System.out.println("Description :"+getDescription());
System.out.println("PlayTime :"+getPlayTime());

}
/**
* @return the playTime
*/
public String getPlayTime() {
return playTime;
}
/**
* @param playTime the playTime to set
*/
public void setPlayTime(String playTime) {
this.playTime = playTime;
}

OUTPUT:

Page 65 of 98
c. Write a java program to implement runtime polymorphism
PROCEDURE

What is Polymorphism?

What is method overriding?

Page 66 of 98
CODE:
public class Shape {

void draw(){System.out.println("drawing...");
}
}
class Rectangle extends Shape{
void draw(){System.out.println("drawing rectangle...");}
}
class Circle extends Shape{
void draw(){System.out.println("drawing circle...");}
}
class Triangle extends Shape{
void draw(){System.out.println("drawing triangle...");}
}
class TestPolymorphism2
{
public static void main(String args[])
{
Shape s;
s=new Rectangle();
s.draw();
s=new Circle();
s.draw();
s=new Triangle();
s.draw();
}
}
OUTPUT:

Page 67 of 98
d. Define an interface, operations which has method area(), volume(). Define a constant
PIhaving value 3.14. Create class a Cylinder which implements this interface (member-
id,height). Create one object and calculate area and volume.
PROCEDURE

What is an Interface?

What is the difference between Abstract class and interface?

What is the difference between Interface and Class?

Page 68 of 98
CODE:

interface Operations
{
public double area();
public double volume();
public double PI = 3.14;
}

class Cylinder implements Operations


{
int ID;
double R;
double H;

public double area(){return (2*PI*R*H)+(2*PI*R*R);} // 2(pi)rh +


2(pi)r^2

public double volume(){return PI*R*R*H;} // (pi)hr^2


}

class Q6c
{
public static void main(String[] args)
{
Cylinder C1 = new Cylinder(1,15,3);
System.out.println(C1.area());
System.out.println(C1.volume());
}
}

OUTPUT:

Page 69 of 98
Exercise-8 (PACKAGES)
Write a java program to implement the following
a. Creation of simple package
PROCEDURE:

What is a Package? What are the two important ways to import a package?

Page 70 of 98
CODE:
package mypackage;
public class A
{
public void add()
{
System.out.println("Addition method in mypackage");
}

public static void main(String[] args) {

}
}

b. Accessing a package
package a;
import mypackage.*;
public class S implements MyInterface
{

public static void main(String[] args)


{

A a = new A();
a.add();
}

OUTPUT:

Page 71 of 98
Exercise-9 (EXCEPTION HANDLING)

a. Write a java program which accepts withdraw amount from the user and throws an
exception “In Sufficient Funds” when withdraw amount more than available amount.
PROCEDURE:

What is an Exception?

Why we need to handle Exception?

Page 72 of 98
CODE:
import java.util.*;

Class InsufficientFunds extends Exception


{
Public InsufficientFunds()
{
super("There is not enough money available in your bank account.");
}
}

class Q7a
{
static int available = 75000;
static Scanner sc = new Scanner(System.in);

public static void main(String[] args)


{
String ans;
while(true)
{
System.out.print("Continue to Withdraw money?[YES/NO]::");
ans = sc.nextLine().toLowerCase();
if (!ans.equals("yes"))
break;
withdraw();
}
}
public static void withdraw()
{
int amount;
System.out.print("Amount to Withdraw (multiples of 100):\t");
amount = Integer.parseInt(sc.nextLine());
if(!(amount%100 == 0))
{
System.out.println("Please enter amount in multiples of 100");
return;
}

try
{
available -= amount;

Page 73 of 98
if (available < 0)
throw new InsufficientFunds();
System.out.println("Available balance: "+available);
}
catch(Exception err)
{
available += amount;
System.out.println(err+"\nTry Withdrawing less ammount.");
}
}
}

OUTPUT:

Page 74 of 98
b. Write a java program to illustrate finally block.
PROCEDURE:

Explain the importance of try, catch and finally blocks?

Page 75 of 98
CODE:

import java.io.*;
public class finallyblock {

public static void main(String args[]){

try{

int data=25/5;

System.out.println(data);

catch(NullPointerException e){System.out.println(e);}

finally{System.out.println("finally block is always executed");}

System.out.println("rest of the code...");

OUTPUT:

Page 76 of 98
Exercise-10 (THREADS)

a. Write a java program to create three threads and that displays “good morning”, for
everyone second, “hello” for every 2 seconds and “welcome” for every 3 seconds by
using extending Thread class.
PROCEDURE:

What is a thread?

What is multithreading?

Page 77 of 98
List the Stages in thread Life cycle?

CODE:

class Message extends Thread


{
String msg;
int time;
Message(String msg, int time)
{
this.msg = msg;
this.time = time;
}

public void run()


{
while(true)
try
{
Thread.sleep(time);
System.out.println(msg);
}
catch (Exception err){}
Page 78 of 98
}
}

class Q7b
{
public static void main(String[] args)
{
System.out.println("Press Ctrl+c to exit.\n");

Message T1 = new Message("Good Morning", 1000);// 1000 milliseconds


Message T2 = new Message("Hello", 2000);
Message T3 = new Message("Welcome", 3000);

T1.start();
T2.start();
T3.start();

}
}

OUTPUT:

Page 79 of 98
b. Write a Java program that creates three threads. First thread displays “OOPS”, the second
thread displays “Through” and the third thread Displays “JAVA” by using Runnable
interface.
PROCEDURE:

What are the two ways to create a thread? Write the basic Syntax.

Page 80 of 98
CODE:
class Message implements Runnable
{
String msg;
Message(String msg)
{
this.msg = msg;
}

public void run()


{
System.out.println(msg);
}
}
class Q7c
{
public static void main(String[] args)
{
Thread T1 = new Thread(new Message("OOPS")); // 1000 milliseconds
Thread T2 = new Thread(new Message("Through"));
Thread T3 = new Thread(new Message("JAVA"));

//to print one message after another use Thread.join()


T1.start();
T2.start();
T3.start();

}
}

OUTPUT:

Page 81 of 98
Exercise -11

a. Write a Java program to create a new array list, add some colors (string) and print out the
collection

PROCEDURE:

Why Array List is better than Array?

Page 82 of 98
CODE:
import java.util.*;

class Q8a
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);

System.out.print("Enter Number of Colors... ");


intnum = sc.nextInt();

List<String> colors = new ArrayList<String>();

for (int i=num; i>=0; i--)


{
colors.add(sc.nextLine());
}

for(String color:colors)
System.out.print(color+" ");
}
}

OUTPUT:

Page 83 of 98
Exercise-12 (EVENT HANDLING)

a. Implement a java program for handling mouse events when the mouse entered, exited,
clicked, pressed, released, dragged and moved in the client area.
PROCEDURE:

What is Event Source, Event and Event Listener?

Page 84 of 98
CODE:
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;

public class NewApplet extends Applet implements


MouseListener,MouseMotionListener {

int x=0,y=0;
String str="";

public void init() {


addMouseListener(this);
addMouseMotionListener(this);
}

public void paint(Graphics g)


{
g.drawString(str,100,100);
}

public void mouseEntered(MouseEvent ae)


{
showStatus("Mouse Entered");
}

public void mouseExited(MouseEvent ae)


{
showStatus("Mouse Exited");
}

public void mousePressed(MouseEvent ae)


{
showStatus("Mouse Pressed");
}

public void mouseReleased(MouseEvent ae)


{
showStatus("Mouse Released");
}

Page 85 of 98
public void mouseMoved(MouseEvent ae)
{
str="mouse moved";
repaint();
}

public void mouseDragged(MouseEvent ae)


{
//str="mouse dragged";
//repaint();

showStatus("Mouse Dragged");
}

public void mouseClicked(MouseEvent ae)


{

showStatus("Mouse Clicked");
}

OUTPUT:

Page 86 of 98
b. Implement a Java program for handling key events when the key board is pressed,
released, typed.

CODE:
import java.awt.event.*;
import javax.swing.*;

public class KeyBoard extends JFrame

KeyBoard()

JFrame frame = new JFrame();

frame.setSize(300, 300);

frame.setVisible(true);

frame.setDefaultCloseOperation(EXIT_ON_CLOSE);

JLabel text = new JLabel();

text.setHorizontalAlignment(JLabel.CENTER);

text.setVerticalAlignment(JLabel.CENTER);

frame.add(text);

frame.addKeyListener(new KeyListener()

@Override

public void keyTyped(KeyEvent e){text.setText("keyTyped");} // for printable keys

@Override

Page 87 of 98
public void keyReleased(KeyEvent e) {text.setText("keyReleased");}// for any key

released

@Override

public void keyPressed(KeyEvent e) {text.setText("keyPressed");}// for non printable

keys [shift,alt,ctrl,arrow keys...etc]

});

//etLayout(new GridLayout(3,2));

}
public static void main(String[] args)
{
newKeyBoard();
}

OUTPUT:

Page 88 of 98
Exercise-13 (APPLETS AND SWINGS)

a. Develop an Applet program to accept two numbers from user and output the sum,
difference in the respective text boxes.
PROCEDURE:

What is an Applet?

What are the stages in Applet Life Cycle?

Page 89 of 98
CODE:
import java.applet.Applet;
import java.awt.Button;
import java.awt.Label;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class NewApplet extends Applet implements ActionListener{

Label l1=new Label("Number :1 ");


Label l2=new Label("Number :2 ");
Label l3=new Label("Add Result: ");
Label l4=new Label("Difference: ");
TextField t1=new TextField();
TextField t2=new TextField();
TextField t3=new TextField();
TextField t4=new TextField();
Button b=new Button("Calculate");

public void init()


{
add(l1);
add(t1);
add(l2);
add(t2);
add(l3);
add(t3);
add(l4);
add(t4);
add(b);

l1.setBounds(20,45,70,20);
t1.setBounds(180,45,200,20);
l2.setBounds(20,95,70,20);
t2.setBounds(180,95,200,20);
l3.setBounds(20,145,70,20);
t3.setBounds(180,145,200,20);
l4.setBounds(20,195,70,20);
t4.setBounds(180,195,200,20);
b.setBounds(180,250,200,20);
b.addActionListener(this);

Page 90 of 98
}

public void actionPerformed(ActionEvent e)


{
t3.setText(Integer.parseInt(t1.getText()) + Integer.parseInt(t2.getText())+"");
t4.setText(Integer.parseInt(t1.getText()) - Integer.parseInt(t2.getText())+"");

OUTPUT:

Page 91 of 98
b. Write a java swing program that reads two numbers from two separate text fields and
display sum of two numbers in third text field when button “add” is pressed.

PROCEDURE:

What is a Swing?

Page 92 of 98
CODE:
import java.awt.event.*;
import javax.swing.*;

public class Addition extends JFrame


{

Addition()
{
JFrame window = new JFrame();
window.setDefaultCloseOperation(EXIT_ON_CLOSE);
window.setLayout(null);
window.setSize(400, 400);

JTextField A = new JTextField();


A.setBounds(90, 50, 150, 30);
window.add(A);

JTextField B = new JTextField();


B.setBounds(90, 80, 150, 30);
window.add(B);

JButton Add = new JButton("ADD");


Add.setBounds(90, 140, 150, 30);
window.add(Add);

JTextField C = new JTextField();


C.setBounds(90, 200, 100, 30);
window.add(C);

Add.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{

Page 93 of 98
int a = Integer.parseInt(A.getText());

int b = Integer.parseInt(B.getText());

C.setText(Integer.toString(a+b));
}
});

window.setVisible(true);
}
public static void main(String args[]) {

new Addition();

}
}

OUTPUT:

Page 94 of 98
c. Write a JAVA program to design student registration form using Swing Controls. The
formwhich having the following fields and button SAVE
Form Fields are: Name, RNO, Mailid, Gender, Branch, and Address
PROCEDURE:

What is the difference between Applet and Swing?

Page 95 of 98
CODE:
import java.awt.event.*;
import javax.swing.*;

public class Form extends JFrame


{

Form()
{
JFrame window = new JFrame("Registration Form");
window.setDefaultCloseOperation(EXIT_ON_CLOSE);
window.setLayout(null);
window.setSize(400, 650);

JLabel nameL = new JLabel("Name:");


nameL.setBounds(40, 50, 80, 30);
window.add(nameL);

JTextField name = new JTextField();


name.setBounds(100, 50, 150, 30);
window.add(name);
JLabel rollL = new JLabel("Roll No:");
rollL.setBounds(40, 100, 80, 30);
window.add(rollL);

JTextField roll = new JTextField();


roll.setBounds(100, 100, 150, 30);
window.add(roll);
JLabel mailL = new JLabel("Mail Id:");
mailL.setBounds(40, 150, 80, 30);
window.add(mailL);

JTextField mail = new JTextField();


mail.setBounds(100, 150, 150, 30);
window.add(mail);

JLabel genderL = new JLabel("Gender:");


genderL.setBounds(40, 200, 80, 30);
window.add(genderL);

JRadioButton male = new JRadioButton("Male");


male.setBounds(100, 200, 60, 30);
window.add(male);

JRadioButton female = new JRadioButton("Female");


female.setBounds(170, 200, 80, 30);

Page 96 of 98
window.add(female);
ButtonGroup BG = new ButtonGroup();
BG.add(male);
BG.add(female);

JLabel branchL = new JLabel("Branch:");


branchL.setBounds(40, 250, 80, 30);
window.add(branchL);
String[] branches = {"IT", "ECE", "CSE"};
JComboBox branch = new JComboBox(branches);
branch.setBounds(100, 250, 150, 30);
window.add(branch);

JLabel addrL = new JLabel("Address:");


addrL.setBounds(40, 300, 80, 30);
window.add(addrL);

JTextAreaaddr = new JTextArea(30,30);


addr.setBounds(100, 300, 150, 150);
window.add(addr);

JButton save = new JButton("Save");


save.setBounds(100, 500, 150, 30);
window.add(save);

save.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
String gender = (male.isSelected())? "Male":"Female";
JOptionPane.showMessageDialog(window, "Name:
"+name.getText()+"\nRoll: "+roll.getText()+"\nMail: "+mail.getText()+"\nGender:
"+gender+"\nAddr :\n"+addr.getText()+"\n\nDetails Save.");
name.setText("");
roll.setText("");
mail.setText("");
addr.setText("");
BG.clearSelection();
branch.setSelectedIndex(0);
}
});

window.setVisible(true);
}

Page 97 of 98
public static void main(String args[])
{
new Form();
}

OUTPUT:

Page 98 of 98

You might also like