41
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:

Lab Manual Java Civil

Embed Size (px)

DESCRIPTION

lab manual

Citation preview

FILE NO: TCT/MCA

COLLEGE OF TECHNOLOGY, BHOPALDEPARTMENT OF INFORMATION TECHNOLOGYLAB MANUAL Programme : BESemester

:IIICourse Code : Civil-305Subject 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 SheetSyllabusCE- 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

UNITII

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.

UNITIII

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

UNITIV

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

UNITV

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

References books1. 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 JAVA7. 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 code1public 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 code2public class CastExample{public static void main(String arg[]){String s=27;int i=(int)s;System.out.println(i);}}

//Integer to Stringint a=97;String s=Integer.toString(a);

(or)String s=+a;

//Double to StringString s=Double.toString(doublevalue);

//Long to StringString s=Long.toString(longvalue);

//Float to StringString s=Float.toString(floatvalue);

//String to IntegerString s=7;int i=Integer.valueOf(s).intValue();

(or)int i = Integer.parseInt(s);

//String to Doubledouble a=Double.valueOf(s).doubleValue();

//String to Longlong lng=Long.valueOf(s).longValue();

(or)long lng=Long.parseLong(s);

//String to Floatfloat f=Float.valueOf(s).floatValue();

//Character to Integerchar c=9;int i=(char)c;

//String to CharacterString 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 Javaclass 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;

/* */

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 filePath 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 packagesimport 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 FirstExample14. 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:

A Simple Program

Here is the output of my program:

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:

15. Write a program to show Connectivity using JDBC

package com.java2novice.jdbc;

import java.sql.Connection;import java.sql.DriverManager;import java.sql.SQLException;import java.sql.Statement;

public class JdbcConnection {

public static void main(String a[]){

try {Class.forName("oracle.jdbc.driver.OracleDriver");Connection con = DriverManager.getConnection("jdbc:oracle:thin:@::","user","password");Statement stmt = con.createStatement();System.out.println("Created DB Connection....");} catch (ClassNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}16. Write a program to demonstrate multithreading using Java.

class MyThread extends Thread{public MyThread(){ super("Using Thread Class");System.out.println("Child thread : " + this);start();}public void run(){try{for(int i = 5; i > 0 ; i--){System.out.println("Child Thread " + i );Thread.sleep(500);}}catch(InterruptedException ie){}System.out.println("Exiting Child Thread...");}}

class TestMyThread{public static void main(String args[]){MyThread a = new MyThread();try{for(int k=5; k > 0 ; k--){System.out.println("Main Thread " + k);Thread.sleep(1000);}}catch(InterruptedException ie1){}System.out.println("Exiting Main Thread...");}

}17. Write a program to demonstrate applet life cycle.Introduction: Applet is java program that can be embedded into HTML pages. Java applets runs on the java enables web browsers such as mozila and internet explorer. Applet is designed to run remotely on the client browser, so there are some restrictions on it. Applet can't access system resources on the local computer. Applets are used to make the web site more dynamic and entertaining.

Advantages of Applet: Applets are cross platform and can run on Windows, Mac OS and Linux platform

Applets can work all the version of Java Plugin

Applets runs in a sandbox, so the user does not need to trust the code, so it can work without security approval

Applets are supported by most web browsers

Applets are cached in most web browsers, so will be quick to load when returning to a web page User can also have full access to the machine if user allows

Disadvantages of Java Applet: Java plug-in is required to run applet

Java applet requires JVM so first time it takes significant startup time

If applet is not already cached in the machine, it will be downloaded from internet and will take time

Its difficult to desing and build good user interface in applets compared to HTML technology All these methods are optional

Life cycle of applet is governed by browser. There are 5 methods in the life cycle of an applet All these methods are optional

init( ) : Called when the applet is first created, to perform first-timeinitialization of the appletstart( ): Called every time the applet moves into sight on the Web browser, to allow the applet to start up its normal operations (especially those that are shut off by stop( )). Also called after init( ).paint( ) : Part of the base class Component (three levels of inheritance up). Called as part of an update( ) to perform special painting on the canvas of an applet.stop( ) : Called every time the applet moves out of sight on the Web browser, to allow the applet to shut off expensive operations. Also called right before destroy( ).destroy( ): Called when the applet is being unloaded from the page, to perform final release of resources when the applet is no longer used

Detailed Explanation:init () method: The life cycle of an applet is begin on that time when the applet is first loaded into the browser and called the init() method. The init() method is called only one time in the life cycle on an applet. The init() method is basically called to read the PARAM tag in the html file. The init () method retrieve the passed parameter through the PARAM tag of html file using get Parameter() method All the initialization such as initialization of variables and the objects like image, sound file are loaded in the init () method .After the initialization of the init() method user can interact with the Applet and mostly applet contains the init() method.

Start () method: The start method of an applet is called after the initialization method init(). This method may be called multiples time when the Applet needs to be started or restarted. For Example if the user wants to return to the Applet, in this situation the start Method() of an Applet will be called by the web browser and the user will be back on the applet. In the start method user can interact within the applet.

Stop () method: The stop() method can be called multiple times in the life cycle of applet like the start () method. Or should be called at least one time. There is only miner difference between the start() method and stop () method. For example the stop() method is called by the web browser on that time When the user leaves one applet to go another applet and the start() method is called on that time when the user wants to go back into the first program or Applet.

destroy() method: The destroy() method is called only one time in the life cycle of Applet like init() method. This method is called only on that time when the browser needs to Shut down.

Run this applet and view the messages in the console window.import java.awt.*;import java.applet.Applet;public class LifeCycle extends Applet{public void init(){showStatus("This is Init");for(int i=0;i