Professional Documents
Culture Documents
ISL67 Java Android LabManual
ISL67 Java Android LabManual
LABORATORY MANUAL
Semester : 6
Prepared by:
Prof. Jyothi S,
Asst. Professor,
Dept. of ISE,
Dr.AIT, Bangalore
1
Sub Title : Java, J2EE and Android LAB
Course Objectives :
Design & Develop the fundamentals of Object-oriented programming in Java, including
defining classes, invoking methods, using class libraries.
Design & Develop exception handling and multithreading concepts
Develop efficient Java applets and applications using OOP concepts
Design & Develop basic understanding of Android application programs
1 Design and Develop a Java Program to demonstrate Constructor Overloading and Method
Overloading.
2 Design and Develop a Java Program to implement Exception Handling (Using Nested try
catch and finally).
3 Design and Develop a Java program using Synchronized Threads, which demonstrates
Producer Consumer concept.
4 Design and Develop a Java program to implement multithreading (three threads using single
run method).
5 Design and Develop a Java program of an applet that receives two numerical values as the
input from user and displays the sum of these two numbers.
6 Design and Develop a Java applet program, which handles keyboard event.
7 Design and Develop a Java program to implement JTabbedPane.
8 Design and Develop a Java program to implement the SQL –login ID commands using
JDBC
9 Design and Develop a Java program to implement SQL commands using insert, delete and
select query using JDBC.
10 Design and Develop a simple android application which displays a welcome message on
screen.
11 Design and Develop an android application to calculate unit conversions like temperature
from Celsius to other unit formats
2
12 Design and Develop an android application to calculate exact age and total number of days
of a person.
Note: In the examination each student picks one question from the lot of all 12 questions
Course outcomes:
3
1. Write a JAVA Program to demonstrate Constructor Overloading and
Method Overloading.
class pgm1a
{
int a,b; //data members declaration
pgm1a()
{ //default constructor initialized to zero
a=b=0;
}
pgm1a(int x, int y) //parameterized constructor
{
a=x; b=y;
}
void display() //method to display the value of variables
{
System.out.println("Value of A is "+ a + " and " + "Value of B is "+ b);
}
public static void main(String args[]) //main method
{
pgm1a s1=new pgm1a(); // call default constructor
pgm1a s2=new pgm1a(10,20); // call parameterized constructor
s1.display();
s2.display();
}
}
Output:
4
/* pgm1b.java - Method Overloading */
class pgm1b {
int x,y;
float p,q,result;
void add(int a, int b)
{
x=a;
y=b;
result=x+y;
System.out.println("Result is:" +result);
}
void add(float a, float b)
{
p=a;
q=b;
result=p+q;
System.out.println("Result is:" +result);
}
void add(int a,float b){
x=a;
p=b;
result=x+p;
System.out.println("Result is:" + result);
}
public static void main (String args[])
{
pgm1b obj=new pgm1b();
obj.add(15,24);
obj.add(2.3f,0.8f);
obj.add(56,76f);
} }
Output:
5
2. Write a JAVA Program to implement Exception Handling (Using Nested
try catch and finally).
//pgm2.java
class pgm2{
// Through an exception out of the method.
static void procA() {
try {
System.out.println("\n inside procA \n");
throw new RuntimeException("demo");
} finally {
System.out.println("\n procA's finally \n");
}
}
// Return from within a try block.
static void procB() {
try {
System.out.println("\n inside procB \n");
return;
} finally {
System.out.println("\n procB's finally \n");
}
}
// Execute a nested try block.
static void procC() {
try {
System.out.println("\n inside procC \n");
try{
System.out.println("Inside NESTED TRY BLOCK");
int b =45/0;
System.out.println(b);
}
catch(ArrayIndexOutOfBoundsException e2){
System.out.println("Exception: e2");
}
}
catch(ArithmeticException e3){
System.out.println("Arithmetic Exception Caught");
System.out.println("Inside parent try catch block");
6
}
finally {
System.out.println("\n procC's finally \n");
}
}
public static void main(String args[]) {
try {
procA();
} catch (Exception e) {
System.out.println("\n Exception caught \n");
}
procB();
procC();
}
}
Output:
7
3. Write a JAVA program using Synchronized Threads, which
demonstrates Producer Consumer concept.
// Implementation of a producer and consumer – pgm3.java
class Q {
int n;
boolean valueSet = false;
synchronized int get() {
while(!valueSet)
try {
wait();
} catch(InterruptedException e) {
System.out.println("InterruptedException caught");
}
System.out.println("Got: " + n);
valueSet = false;
notify();
return n;
}
synchronized void put(int n) {
while(valueSet)
try {
wait();
} catch(InterruptedException e) {
System.out.println("InterruptedException caught");
}
this.n = n;
valueSet = true;
System.out.println("Put: " + n);
notify();
}
}
class Producer implements Runnable {
Q q;
Producer(Q q) {
this.q = q;
new Thread(this, "Producer").start();
}
public void run() {
int i = 0;
while(true) {
q.put(i++);
}
}
}
class Consumer implements Runnable {
Q q;
Consumer(Q q) {
this.q = q;
new Thread(this, "Consumer").start();
}
public void run() {
while(true) {
q.get();
}
}
8
}
class pgm3 {
public static void main(String args[]) {
Q q = new Q();
new Producer(q);
new Consumer(q);
System.out.println("Press Control-C to stop.");
}
}
output:
H:\JavaLabPgms>javac pgm3.java
H:\JavaLabPgms>java pgm3
9
4. Write a JAVA program to implement multithreading (three threads
using single run method).
// Create multiple threads – pgm4.java
class NewThread implements Runnable {
String name; // name of thread
Thread t;
NewThread(String threadname) {
name = threadname;
t = new Thread(this, name);
System.out.println("New thread: " + t);
t.start(); // Start the thread
}
// This is the entry point for thread.
public void run() {
try {
for(int i = 5; i > 0; i--) {
System.out.println(name + ": " + i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println(name + "Interrupted");
}
System.out.println(name + " exiting.");
}
}
class pgm4 {
public static void main(String args[]) {
new NewThread("One"); // start threads
new NewThread("Two");
new NewThread("Three");
try {
// wait for other threads to end
Thread.sleep(10000);
} catch (InterruptedException e) {
System.out.println("Main thread Interrupted");
}
System.out.println("Main thread exiting.");
}
}
10
output:
11
5. Write a JAVA program of an applet that receives two numerical values
as the input from user and displays the sum of these two numbers.
// pgm5.html
<html>
<applet code=pgm5.class width=300 height=400>
</applet>
</html>
// pgm5.java
import java.awt.*;
import java.applet.*;
s1=text1.getText();
x=Integer.parseInt(s1);
s2=text2.getText();
y=Integer.parseInt(s2);
}
12
catch(Exception ex) {}
z=x+y;
s=String.valueOf(z);
g.drawString("The Sum is:\n", 10,20);
g.drawString(s,100,75);
}
OUTPUT:
13
6 Write a JAVA applet program, which handles keyboard event.
// pgm6.html
<html>
<applet code="pgm6.class" width=300 height=400>
</applet>
</html>
// pgm6.java
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
addKeyListener(this);
requestFocus();
setBackground(Color.green);
setForeground(Color.blue);
}
public void keyPressed(KeyEvent k)
{
showStatus("KeyDown");
int key=k.getKeyCode();
switch(key)
{
case KeyEvent.VK_UP:
showStatus("Move to Up");
break;
case KeyEvent.VK_DOWN:
showStatus("Move to Down");
break;
case KeyEvent.VK_LEFT:
showStatus("Move to Left");
break;
case KeyEvent.VK_RIGHT:
14
showStatus("Move to Right");
break;
}
repaint();
}
public void keyReleased(KeyEvent k)
{
showStatus("Key Up");
}
public void keyTyped(KeyEvent k)
{
msg+=k.getKeyChar();
repaint();
}
public void paint(Graphics g)
{
g.drawString(msg,X,Y);
}
}
output :
15
7. Write a JAVA program to implement JTabbedPane.
// pgm7.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
jtbExample.addTab("City", jplInnerPanel1);
jtbExample.setSelectedIndex(0);
16
public static void main(String[] args) {
JFrame frame = new JFrame("TabbedPaneDemo");
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);}
});
frame.getContentPane().add(new pgm7(),BorderLayout.CENTER);
frame.setSize(400, 400);
frame.setVisible(true);
}
}
OUTPUT:
17
8. Write a JAVA program to implement the SQL –login ID commands
using JDBC
// pgm8.java
//import required packages
import java.sql.*;
import java.util.Scanner;
// Database credentials
static String USER;
static String PASS;
try{
// Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
// Execute a query
System.out.println("Creating database...");
stmt = conn.createStatement();
try{
if(conn!=null)
conn.close();
}
catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
}//end main
}//end JDBCDemo
19
OUTPUT:
20
9. Write a Java program to implement SQL commands using insert ,
delete and select query using JDBC.
// pgm9.java
// Import required packages
import java.sql.*;
import java.util.Scanner;
// Database credentials
static final String USER = "root";
static final String PASS = "root";
try{
// Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
stmt.executeUpdate(sql);
System.out.println("Created table in given database...");
21
int op=1;
do {
switch (choice)
{
case 1:
System.out.println("Inserting records into the table...");
stmt = conn.createStatement();
while(rs.next()){
//Retrieve by column name
int id = rs.getInt("id");
int age = rs.getInt("age");
String first = rs.getString("first");
String last = rs.getString("last");
//Display values
System.out.print("ID: " + id);
System.out.print(", Age: " + age);
22
System.out.print(", First: " + first);
System.out.println(", Last: " + last);
}
rs.close();
break;
case 2:
System.out.println("Creating statement...");
stmt = conn.createStatement();
sql = "SELECT id, first, last, age FROM ISEDEPT WHERE id = 101";
rs = stmt.executeQuery(sql);
//STEP 5: Extract data from result set
while(rs.next()){
//Retrieve by column name
int id = rs.getInt("id");
int age = rs.getInt("age");
String first = rs.getString("first");
String last = rs.getString("last");
//Display values
System.out.print("ID: " + id);
System.out.print(", Age: " + age);
System.out.print(", First: " + first);
System.out.println(", Last: " + last);
}
rs.close();
break;
case 3:
System.out.println("Creating statement...");
stmt = conn.createStatement();
sql = "DELETE FROM ISEDEPT " +
"WHERE id = 101";
stmt.executeUpdate(sql);
23
while(rs.next()){
//Retrieve by column name
int id = rs.getInt("id");
int age = rs.getInt("age");
String first = rs.getString("first");
String last = rs.getString("last");
//Display values
System.out.print("ID: " + id);
System.out.print(", Age: " + age);
System.out.print(", First: " + first);
System.out.println(", Last: " + last);
}
rs.close();
break;
default:
System.out.println("INVALID SELECTION");
}
System.out.println("1: CONTINUE , 2: EXIT ");
op = in.nextInt();
}while(op==1);
}
catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}
catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}
finally{
//finally block used to close resources
try{
if(stmt!=null)
stmt.close();
}
catch(SQLException se2){
}// nothing we can do
24
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
}//end main
}//end JDBCDemo
OUTPUT:
25
26
10. Write a simple android application which displays a welcome
message on screen.
// StudappActivity.java
package com.studapp;
import android.app.Activity;
import android.os.Bundle;
}
}
// main.xml
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/msg1" />
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/msg2" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/msg3" />
</LinearLayout>
27
//string.xml
</resources>
Output:
28
11. Write an android application to calculate unit conversions like
temperature from Celsius to other unit formats.
/* TempConverActivity.java */
package com.tempConverter;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;
import android.app.Activity;
import android.graphics.Color;
//get value from edit text box and convert into double
double a=Double.parseDouble(String.valueOf(et1.getText()));
RadioButton cb=(RadioButton)findViewById(R.id.cb);
RadioButton fb=(RadioButton)findViewById(R.id.fb);
ll.setBackgroundColor(Color.YELLOW);
//display conversion
result.setText(f2c(a)+" degree C");
//cb.setChecked(false);
fb.setChecked(true);
}
29
else
{
ll.setBackgroundColor(Color.CYAN);
result.setText(c2f(a)+" degree F");
//fb.setChecked(false);
cb.setChecked(true);
}
}
//Celcius to Fahrenhiet method
private double c2f(double c)
{
return (c*9)/5+32;
}
//Fahrenhiet to Celcius method
private double f2c(double f)
{
return (f-32)*5/9;
}
}
// main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/ll"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<EditText
android:id="@+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="numberDecimal" >
</EditText>
<TextView
android:id="@+id/result"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="30sp" />
<RadioGroup
android:id="@+id/radioGroup1"
android:layout_width="wrap_content"
30
android:layout_height="wrap_content" >
<RadioButton
android:id="@+id/cb"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="Celcius" />
<RadioButton
android:id="@+id/fb"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Fahrenhiet" />
</RadioGroup>
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="add"
android:text="Convert"
android:textSize="30sp" />
</LinearLayout>
OUTPUT:
31
12. Write an android application to calculate exact age and total
number of days of a person.
/* AgeCalculationActivity.java */
package com.example.agecalculatorapp;
import java.util.Calendar;
import java.util.Timer;
import android.os.Bundle;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;
import android.widget.Toast;
32
result=(TextView) findViewById(R.id.textView3);
btnStart=(Button) findViewById(R.id.button1);
btnStart.setOnClickListener(this);
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DATE_START_DIALOG_ID:
return new DatePickerDialog(this,
mDateSetListener,
startYear, startMonth, startDay);
}
return null;
}
default:
break;
}
}
33
private void calculateAge()
{
age.calcualteYear();
age.calcualteMonth();
age.calcualteDay();
Toast.makeText(getBaseContext(), "click the resulted
button"+age.getResult() , Toast.LENGTH_SHORT).show();
result.setText("AGE (DD/MM/YY) :"+age.getResult());
}
}
/* AgeCalculation.java */
package com.example.agecalculatorapp;
import java.util.Calendar;
import java.util.Date;
34
startMonth=sMonth;
startMonth++;
startDay=sDay;
}
public void calcualteYear()
{
resYear=endYear-startYear;
}
public void calcualteDay()
{
if(endDay>=startDay)
{
resDay= endDay-startDay;
}
else
{
resDay=endDay-startDay;
resDay=30+resDay;
if(resMonth==0)
{
resMonth=11;
resYear--;
}
35
else
{
resMonth--;
}
}
}
36
OUTPUT:
37