COLLEGE OF TECHNOLOGY, BHOPAL

DEPARTMENT OF INFORMATION TECHNOLOGY

LAB MANUAL

Programme : BE

Semester :III

Course Code : Civil-305

Subject Name : Computer programming(Java)

Prepared By: Approved By:


Index

S.No. Contents Page No.

1.  Syllabus

2.  List of Experiments /Methods

3.  Viva Questions

4.  Grading Sheet

Syllabus

CE- 306 Computer Programming

UNIT-I

Basic Java Features - C++ Vs JAVA, JAVA virtual machine, Constant & Variables, Data

Types, Class, Methods, Objects, Strings and Arrays, Type Casting, Operators, Precedence

relations, Control Statements, Exception Handling, File and Streams, Visibility, Constructors,

Operator and Methods Overloading, Static Members, Inheritance: Polymorphism, Abstract

methods and Classes

UNIT–II

Java Collective Frame Work - Data Structures: Introduction, Type-Wrapper Classes for

Primitive Types, Dynamic Memory Allocation, Linked List, Stack, Queues, Trees,

Generics: Introduction, Overloading Generic Methods, Generic Classes, Collections: Interface

Collection and Class Collections, Lists, Array List and Iterator, Linked List, Vector.

Collections Algorithms: Algorithm sorts, Algorithm shuffle, Algorithms reverse, fill, copy, max

and min Algorithm binary Search, Algorithms add All, Stack Class of Package java. Util, Class

Priority Queue and Interface Queue, Maps, Properties Class, Un-modifiable Collections.

UNIT–III

Advance Java Features - Multithreading: Thread States, Priorities and Thread

Scheduling, Life Cycle of a Thread, Thread Synchronization, Creating and Executing Threads,

Multithreading with GUI, Monitors and Monitor Locks. Networking: Manipulating URLs, Reading

a file on a Web Server, Socket programming, Security and the Network, RMI, Networking,

Accessing Databases with JDBC: Relational Database, SQL, MySQL, Oracle

UNIT–IV

Advance Java Technologies - Servlets: Overview and Architecture, Setting Up the

Apache Tomcat Server, Handling HTTP get Requests, Deploying a web Application, Multitier

Applications, Using JDBC from a Servlet, Java Server Pages (JSP): Overview, First JSP

Example, Implicit Objects, Scripting, Standard Actions, Directives, Multimedia: Applets and

Application: Loading, Displaying and Scaling Images, Animating a Series of Images, Loading

and playing Audio clips

UNIT–V

Advance Web/Internet Programming (Overview): J2ME, J2EE, EJB, XML.

References books

1. Deitel & Deitel, ”JAVA, How to Program”; PHI, Pearson.

2. E. Balaguruswamy, “Programming In Java”; TMH Publications

3. The Complete Reference: Herbert Schildt, TMH

4. Peter Norton, “Peter Norton Guide To Java Programming”, Techmedia.

5. Merlin Hughes, et al; Java Network Programming , Manning Publications/Prentice Hall

List of Program to be perform (Expandable)

1.  Write the importance of object oriented programming. Mention the features of JAVA

2.  Write a program to show Concept of CLASS in JAVA

3.  Write a program using if else. Statement

4.  Write a program showing use of constructor

5.  Write a program to show Type Casting in JAVA

6.  Write a program to show How Exception Handling is in JAVA

7.  Write a program to show Inheritance

8.  Write a program to show Polymorphism

9.  Write a program to show Interfacing between two classes

10. Write a program to Add a Class to a Package

11. Write a program to demonstrate AWT.

12. Write a program to Hide a Class

13. Write a program to show Data Base Connectivity Using JAVA

14. Write a program to show “HELLO JAVA ” in Explorer using Applet

15. Write a program to show Connectivity using JDBC

16. Write a program to demonstrate multithreading using Java.

17. Write a program to demonstrate applet life cycle.

1.Write the importance of object oriented programming. Mention the features of JAVA

Java is a programming language created by James Gosling from Sun Microsystems (Sun) in 1991. The first publicly available version of Java (Java 1.0) was released in 1995.

Sun Microsystems was acquired by the Oracle Corporation in 2010. Oracle has now the steermanship for Java.

Over time new enhanced versions of Java have been released. The current version of Java is Java 1.7 which is also known as Java 7.

From the Java programming language the Java platform evolved. The Java platform allows software developers to write program code in other languages than the Java programming language which still runs on the Java virtual machine. The Java platform is usually associated with the Java virtual machine and the Java core libraries.

Java has the following properties:

·  Platform independent: Java programs use the Java virtual machine as abstraction and do not access the operating system directly. This makes Java programs highly portable. A Java program (which is standard complaint and follows certain rules) can run unmodified on all supported platforms, e.g., Windows or Linux.

·  Object-orientated programming language: Except the primitive data types, all elements in Java are objects.

·  Strongly-typed programming language: Java is strongly-typed, e.g., the types of the used variables must be pre-defined and conversion to other objects is relatively strict, e.g., must be done in most cases by the programmer.

·  Interpreted and compiled language: Java source code is transferred into the bytecode format which does not depend on the target platform. These bytecode instructions will be interpreted by the Java Virtual machine (JVM). The JVM contains a so called Hotspot-Compiler which translates performance critical bytecode instructions into native code instructions.

·  Automatic memory management: Java manages the memory allocation and de-allocation for creating new objects. The program does not have direct access to the memory. The so-called garbage collector automatically deletes objects to which no active pointer exists.


2. Write a program to show Concept of CLASS in JAVA

importjava.util.*;
publicclassDateDemo{
publicstaticvoidmain(String[]args){
Dated=newDate();
System.out.println("Todaydateis"+d);
}
}


3.Write a program using SWICTH Statement

importjava.io.*;
publicclassSwitchExample{
publicstaticvoidmain(String[]args)throwsException{
intx,y;
BufferedReaderobject=newBufferedReader
(newInputStreamReader(System.in));
System.out.println("Entertwonumbersforoperation:");
try{
x=Integer.parseInt(object.readLine());
y=Integer.parseInt(object.readLine());
System.out.println("1.Add");
System.out.println("2.Subtract");
System.out.println("3.Multiply");
System.out.println("4.Divide");
System.out.println("enteryourchoice:");
inta=Integer.parseInt(object.readLine());
switch(a){
case1:
System.out.println("Enterthenumberone="+(x+y));
break;
case2:
System.out.println("Enterthenumbertwo="+(x-y));
break;
case3:
System.out.println("Enetrthenumberthree="+(x*y));
break;
case4:
System.out.println("Enterthenumberfour="+(x/y));
break;
default:
System.out.println("Invalid Entry!");
}
}
catch(NumberFormatExceptionne){
System.out.println(ne.getMessage()+"isnotanumericvalue.");
System.exit(0);
}
}
}


4.Write a program showing use of constructor

classanother{
intx,y;
another(inta,intb){
x=a;
y=b;
}
another(){
}
intarea(){
intar=x*y;
return(ar);
}
}
publicclassConstruct{
publicstaticvoidmain(String[]args)
{
anotherb=newanother();
b.x=2;
b.y=3;
System.out.println("Areaofrectangle:"+b.area());
System.out.println("Valueofyinanotherclass:"+b.y);
anothera=newanother(1,1);
System.out.println("Areaofrectangle:"+a.area());
System.out.println("Valueofxinanotherclass:"+a.x);
}
}


5.Write a program to show Type Casting in JAVA

//Integer code1
public class CastExample
{
public static void main(String arg[])
{
String s=”27”;
int i=Integer.parseInt(s);
System.out.println(i);
Float f=99.7f;
int i1=Integer.parseInt(f);
}
}
//Integer code2
public class CastExample
{
public static void main(String arg[])
{
String s=”27”;
int i=(int)s;
System.out.println(i);
}
}
//Integer to String
int a=97;
String s=Integer.toString(a);
(or)
String s=””+a;
//Double to String
String s=Double.toString(doublevalue);
//Long to String
String s=Long.toString(longvalue);
//Float to String
String s=Float.toString(floatvalue);
//String to Integer
String s=”7”;
int i=Integer.valueOf(s).intValue();
(or)
int i = Integer.parseInt(s);
//String to Double
double a=Double.valueOf(s).doubleValue();
//String to Long
long lng=Long.valueOf(s).longValue();
(or)
long lng=Long.parseLong(s);
//String to Float
float f=Float.valueOf(s).floatValue();
//Character to Integer
char c=’9’;
int i=(char)c;
//String to Character
String s=”welcome”;
char c=(char)s;


6. Write a program to show How Exception Handling is in JAVA

importjava.io.*;
publicclassexceptionHandle{
publicstaticvoidmain(String[]args)throwsException{
try{
inta,b;
BufferedReaderin=
newBufferedReader(newInputStreamReader(System.in));
a=Integer.parseInt(in.readLine());
b=Integer.parseInt(in.readLine());
}
catch(NumberFormatExceptionex){
System.out.println(ex.getMessage()
+"isnotanumericvalue.");
System.exit(0);
}
}

7. Program that illustrates inheritance in java using person class

class Person

{

String FirstName;

String LastName;

Person(String fName, String lName)

{

FirstName = fName;

LastName = lName;

}

void Display()

{

System.out.println("First Name : " + FirstName);

System.out.println("Last Name : " + LastName);

}}

class Student extends Person

{

int id;

String standard;

String instructor;

Student(String fName, String lName, int nId, String stnd, String instr)

{

super(fName,lName);

id = nId;

standard = stnd;

instructor = instr;

}

void Display()

{

super.Display();

System.out.println("ID : " + id);

System.out.println("Standard : " + standard);

System.out.println("Instructor : " + instructor);

}}

class Teacher extends Person

{

String mainSubject;

int salary;

String type; // Primary or Secondary School teacher

Teacher(String fName, String lName,String sub,int slry, String sType)

{

super(fName,lName);

mainSubject = sub;

salary = slry;

type = sType;

}

void Display()

{

super.Display();

System.out.println("Main Subject : " + mainSubject);

System.out.println("Salary : " + salary);

System.out.println("Type : " + type);

}}

class InheritanceDemo

{

public static void main(String args[])

{

Person pObj = new Person("Rayan","Miller");

Student sObj = new Student("Jacob","Smith",1,"1 - B","Roma");

Teacher tObj = new Teacher("Daniel","Martin","English","6000","Primary Teacher");

System.out.println("Person :");

pObj.Display();

System.out.println("");

System.out.println("Student :");

sObj.Display();

System.out.println("");

System.out.println("Teacher :"); tObj.Display();

}

}


8. Polymorpism In Java

class overLoading {

public static void main(String[] args)

{

functionOverload obj = new functionOverload();

obj.add(1,2);

obj.add(\"Life at \", \"?\");

obj.add(11.5, 22.5);

}

}

class functionOverload {

/*

* void add(int a, int b) // 1 - A method with two parameters {

*

* int sum = a + b; System.out.println(\"Sum of a+b is \"+sum);

*

* }

*/

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

int sum = a + b + c;

System.out.println(\"Sum of a+b+c is \"+sum);

}

void add(double a, double b) {

double sum = a + b;

System.out.println(\"Sum of a+b is \"+sum);

}

void add(String s1, String s2)

{

String s = s1 + s2;

System.out.println(s);

}

}


9.Write a program to show Interfacing between two classes

public interface First {
public void show_first();
}
public interface Second {
public void show_second();
}
public class One {
public void show_one()
{
System.out.println("Class One");
}
}
public class Two extends One implements First, Second{
public void show_first()
{
System.out.println("Interface first");
}
public void show_second()
{
System.out.println("Interface second");
}
public void show_two()
{
System.out.println("Class two");
}
}
public class DemoInterface {
public static void main(String a[])
{
Two t=new Two();
t.show_first();
t.show_second();
t.show_one();
t.show_two();
} }

10.  Write a program to Add a Class to a Package

  1. Package statment (optional).
  2. Imports (optional).
  3. Class or interface definitions.

// This source file must be Drawing.java in the illustration directory.

package illustration;

import java.awt.*;

public class Drawing {

. . .

}

Imports: three options

The JOptionPane class is in the swing package, which is located in the javax package. The wildcard character (*) is used to specify that all classes with that package are available to your program. This is the most common programming style.

import javax.swing.*; // Make all classes visible altho only one is used.

class ImportTest {

public static void main(String[] args) {

JOptionPane.showMessageDialog(null, "Hi");

System.exit(0);

}}Classes can be specified explicitly on import instead of using the wildcard character.

import javax.swing.JOptionPane; // Make a single class visible.

class ImportTest {

public static void main(String[] args) {

JOptionPane.showMessageDialog(null, "Hi");

System.exit(0);

}

}

Alternately we can the fully qualified class name without an import.

class ImportTest {

public static void main(String[] args) {

javax.swing.JOptionPane.showMessageDialog(null, "Hi");

System.exit(0);

}

}

11.  Write a program to demonstrate AWT.

Create AWT Button Example

This java example shows how to create a Button using AWT Button class.

*/

import java.applet.Applet;

import java.awt.Button;

/*

<applet code="CreateAWTButtonExample" width=200 height=200>

</applet>

*/

public class CreateAWTButtonExample extends Applet{

public void init(){

/*

* To create a button use

* Button() constructor.

*/

Button button1 = new Button();

/*

* Set button caption or label using

* void setLabel(String text)

* method of AWT Button class.

*/

button1.setLabel("My Button 1");

/*

* To create button with the caption use

* Button(String text) constructor of

* AWT Button class.

*/

Button button2 = new Button("My Button 2");

//add buttons using add method

add(button1);

add(button2);

}

}

12.  Write a program to Hide a file

Path path = FileSystems.getDefault().getPath("directory", "hidden.txt");
Boolean hidden = path.getAttribute("dos:hidden", LinkOption.NOFOLLOW_LINKS);
if (hidden != null & !hidden) {
path.setAttribute("dos:hidden", Boolean.TRUE, LinkOption.NOFOLLOW_LINKS);
}

13.  Write a program to show Data Base Connectivity Using JAVA

/STEP 1. Import required packages

import java.sql.*;

public class FirstExample {

// JDBC driver name and database URL

static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";

static final String DB_URL = "jdbc:mysql://localhost/EMP";

// Database credentials

static final String USER = "username";

static final String PASS = "password";

public static void main(String[] args) {

Connection conn = null;

Statement stmt = null;

try{

//STEP 2: Register JDBC driver

Class.forName("com.mysql.jdbc.Driver");

//STEP 3: Open a connection

System.out.println("Connecting to database...");

conn = DriverManager.getConnection(DB_URL,USER,PASS);

//STEP 4: Execute a query

System.out.println("Creating statement...");

stmt = conn.createStatement();

String sql;

sql = "SELECT id, first, last, age FROM Employees";

ResultSet 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);

}

//STEP 6: Clean-up environment

rs.close();

stmt.close();

conn.close();

}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

try{

if(conn!=null)

conn.close();

}catch(SQLException se){

se.printStackTrace();

}//end finally try

}//end try

System.out.println("Goodbye!");

}//end main

}//end FirstExample

14.  Write a program to show “HELLO JAVA ” in Explorer using Applet

Create a Java Source File

Create a file named HelloWorld.java with the Java code shown here:

import java.applet.Applet;

import java.awt.Graphics;

public class HelloWorld extends Applet {

public void paint(Graphics g) {

g.drawString("Hello world!", 50, 25);

}

}

Compile the Source File

If the compilation succeeds, the compiler creates a file named HelloWorld.class in the same directory (folder) as the Java source file (HelloWorld.java). This class file contains Java bytecodes.

If the compilation fails, make sure you typed in and named the program exactly as shown above. If you can't find the problem, see Common Compiler and Interpreter Problems.

Create an HTML File that Includes the Applet

Using a text editor, create a file named Hello.html in the same directory that contains HelloWorld.class. This HTML file should contain the following text:

<HTML>

<HEAD>

<TITLE> A Simple Program </TITLE>

</HEAD>

<BODY>

Here is the output of my program:

<APPLET CODE="HelloWorld.class" WIDTH=150 HEIGHT=25>

</APPLET>

</BODY>

</HTML>

Run the Applet

To run the applet, you need to load the HTML file into an application that can run Java applets. This application might be a Java-compatible browser or another Java applet viewing program, such as the Applet Viewer provided in the JDK. To load the HTML file, you usually need to tell the application the URL of the HTML file you've created. For example, you might enter something like the following into a browser's URL or Location field:

file:/home/kwalrath/HTML/Hello.html

Once you've successfully completed these steps, you should see something like this in the browser window: