Java Lab Record PDF
Java Lab Record PDF
INFORMATION TECHNOLOGY
CERTIFICATE
External Examiner
Page 1 of 98
INDEX
Page 2 of 98
Page 3 of 98
Exercise-1
CODE:
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:
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]);
OUTPUT:
Page 7 of 98
d. Write a Java program to illustrate type conversions.
PROCEDURE:
Page 8 of 98
CODE:
OUTPUT:
Page 9 of 98
CODE:
double d = 100.04;
long l = (long)d; //explicit type casting required
int i = (int)l; //explicit type casting required
OUTPUT:
Page 10 of 98
e. Write a java program to observe the effects of various bitwise operators.
PROCEDURE:
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);
OUTPUT:
Page 12 of 98
Exercise-2
a. Write a Java program to find largest number out of 3 numbers using nested if.
PROCEDURE:
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.
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;
while(true)
{
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;
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;
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.*;
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;
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.*;
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;
}
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.*;
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;
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];
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.print("\n");
}
}
}
}
OUTPUT:
Page 40 of 98
Exercise-5
a. Write a java program to check weather given string is palindrome or not.
PROCEDURE
Page 41 of 98
CODEe a java program to check weather given string is palindrome or not.
import java.util.Scanner;
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
Page 43 of 98
CODE:
import java.util.*;
OUTPUT:
Page 44 of 98
c. Write a Java program for sorting a given list of names in ascending order.
PROCEDURE
Page 45 of 98
CODE:
import java.util.*;
intnum = sc.nextInt();
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
Page 47 of 98
CODE:
import java.util.*;
import java.io.*;
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
Page 49 of 98
CODE:
class Rectangle
{
private int Length=0;
private int Width=0;
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
Page 51 of 98
CODE:
import java.util.*;
class Company
{
private static int year;
private static double annualTurnover;
private static double annualSales;
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 {
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)
PROCEDURE:
What is 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 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?
Page 62 of 98
CODE:
AbstractMedia.java
public abstract class AbstractMedia {
AbstractDemo.java
Page 63 of 98
public static void main(String[] args) {
Book book = new Book(10001,"Tale of Two Cities",200);
book.printDetails();
cd.printDetails();
Book.java
/**
* @return the pageCount
*/
public int getPageCount() {
return pageCount;
}
/**
* @param pageCount the pageCount to set
*/
public void setPageCount(int pageCount) {
this.pageCount = pageCount;
}
CD.java
Page 64 of 98
private String playTime;
}
/**
* @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?
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?
Page 68 of 98
CODE:
interface Operations
{
public double area();
public double volume();
public double PI = 3.14;
}
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");
}
}
}
b. Accessing a package
package a;
import mypackage.*;
public class S implements MyInterface
{
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?
Page 72 of 98
CODE:
import java.util.*;
class Q7a
{
static int available = 75000;
static Scanner sc = new Scanner(System.in);
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:
Page 75 of 98
CODE:
import java.io.*;
public class finallyblock {
try{
int data=25/5;
System.out.println(data);
catch(NullPointerException e){System.out.println(e);}
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 Q7b
{
public static void main(String[] args)
{
System.out.println("Press Ctrl+c to exit.\n");
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;
}
}
}
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:
Page 82 of 98
CODE:
import java.util.*;
class Q8a
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
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:
Page 84 of 98
CODE:
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
int x=0,y=0;
String str="";
Page 85 of 98
public void mouseMoved(MouseEvent ae)
{
str="mouse moved";
repaint();
}
showStatus("Mouse Dragged");
}
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.*;
KeyBoard()
frame.setSize(300, 300);
frame.setVisible(true);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
text.setHorizontalAlignment(JLabel.CENTER);
text.setVerticalAlignment(JLabel.CENTER);
frame.add(text);
frame.addKeyListener(new KeyListener()
@Override
@Override
Page 87 of 98
public void keyReleased(KeyEvent e) {text.setText("keyReleased");}// for any key
released
@Override
});
//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?
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;
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
}
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.*;
Addition()
{
JFrame window = new JFrame();
window.setDefaultCloseOperation(EXIT_ON_CLOSE);
window.setLayout(null);
window.setSize(400, 400);
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:
Page 95 of 98
CODE:
import java.awt.event.*;
import javax.swing.*;
Form()
{
JFrame window = new JFrame("Registration Form");
window.setDefaultCloseOperation(EXIT_ON_CLOSE);
window.setLayout(null);
window.setSize(400, 650);
Page 96 of 98
window.add(female);
ButtonGroup BG = new ButtonGroup();
BG.add(male);
BG.add(female);
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