You are on page 1of 29

ADVANCED JAVA LAB FILE

(8th SEM, May 2012)

Submitted To: Mr.Vinod Jain Submitted By: Himanshi Lamba 08/IT/017 Group-4.1

08/IT/017

PROGRAM 1
INTRODUCTION TO JAVA
Java is a programming language originally developed by James Gosling at Sun Microsystems (which has since merged into Oracle Corporation) and released in 1995 as a core component of Sun Microsystems' Java platform. The language derives much of its syntax from C and C++ but has a simplerobject model and fewer low-level facilities. Java applications are typically compiled to bytecode (class file) that can run on any Java Virtual Machine (JVM) regardless of computer architecture. Java is a general-purpose, concurrent, class-based, object-oriented language that is specifically designed to have as few implementation dependencies as possible. All source code is written in plain text file ending with the .java extension.Source files are compiled into .class files by the javac compiler.A .class file does not contain code that is native to your processor: contains bytecodes.Bytecodes: the machine language of the JavaVirtual Machine (JVM) the java launcher tool then runs your application with an instance of the JVM

PRINCIPLES There were five primary goals in the creation of the Java language: 1. 2. 3. 4. 5. It should be "simple, object-oriented and familiar" It should be "robust and secure" It should be "architecture-neutral and portable" It should execute with "high performance" It should be "interpreted, threaded, and dynamic"

FEATURES OF JAVA Platform Independent The concept of Write-once-run-anywhere (known as the Platform independent) is one of the important key feature of java language that makes java as the most powerful language. Not even a

08/IT/017 single language is idle to this feature but java is more closer to this feature. The programs written on one platform can run on any platform provided the platform must have the JVM. Simple There are various features that makes the java as a simple language. Programs are easy to write and debug because java does not use the pointers explicitly. It is much harder to write the java programs that can crash the system but we can not say about the other programming languages. Java provides the bug free system due to the strong memory management. It also has the automatic memory allocation and deallocation system. Object Oriented To be an Object Oriented language, any language must follow at least the four characteristics.

Inheritance : It is the process of creating the new classes and using the behavior of the existing classes by extending them just to additional features as needed. reuse the existing code and adding the

Encapsulation: : It is the mechanism of combining the information and providing the abstraction. Polymorphism: : As the name suggest one name multiple form, Polymorphism is the way of providing the different functionality by the functions having the same name based on the signatures of the methods.

Dynamic binding : Sometimes we don't have the knowledge of objects about their specific types while writing our code. It is the way program about the specific type at runtime. of providing the maximum functionality to a

Robust Java has the strong memory allocation and automatic garbage collection mechanism. It provides the powerful exception handling and type checking mechanism as compare to other programming languages. Compiler checks the program whether there any error and interpreter checks any run time error and makes the system secure from crash. All of the above features makes the java language robust. Distributed The widely used protocols like HTTP and FTP are developed in java. Internet programmers can call functions on these protocols and can get access the files from any remote machine on the internet rather than writing codes on their local system.

08/IT/017 Portable The feature Write-once-run-anywhere makes the java language portable provided that the system must have interpreter for the JVM. Java also have the standard data size irrespective of operating system or the processor. These features makes the java as a portable language. Dynamic While executing the java program the user can get the required files dynamically from a local drive or from a computer thousands of miles away from the user just by connecting with the Internet. Secure Java does not use memory pointers explicitly. All the programs in java are run under an area known as the sand box. Security manager determines the accessibility options of a class like reading and writing a file to the local disk. Java uses the public key encryption system to allow the java applications to transmit over the internet in the secure encrypted form. The bytecode Verifier checks the classes after loading. Performance Java uses native code usage, and lightweight process called threads. In the beginning interpretation of bytecode resulted the performance slow but the advance version of JVM uses the adaptive and just in time compilation technique that improves the performance. Multithreaded Java is also a Multithreaded programming language. Multithreading means a single program having different threads executing independently at the same time. Multiple threads execute instructions according to the program code in a process or a program. Multithreading works the similar way as multiple processes run on one computer. Interpreted We all know that Java is an interpreted language as well. With an interpreted language such as Java, programs run directly from the source code. The interpreter program reads the source code and translates it on the fly into computations. Thus, Java as an interpreted language depends on an interpreter program.The versatility of being platform independent makes Java to outshine from other languages. The source code to be written and distributed is platform independent. Another advantage of Java as an interpreted language is its error debugging quality. Due to this any error occurring in the program gets traced. This is how it is different to work with Java.

08/IT/017

PROGRAM 2
INTRODUCTION TO NET BEANS
NetBeans refers to both a platform framework for Java desktop applications, and an integrated development environment (IDE) for developing with Java,JavaScript, PHP, Python(no longer supported after NetBeans 7), Groovy, C], C++, Scala, Clojure , and others. The NetBeans IDE 7.0 no longer supports Ruby and Ruby on Rails], but a third party has begun work on a separate plugin. The NetBeans IDE is written in Java and can run on Windows, Mac OS, Linux, Solaris and other platforms supporting a compatible JVM. A pre-existing JVM or a JDK is not required. The NetBeans platform allows applications to be developed from a set of modular software components called modules. Applications based on the NetBeans platform (including the NetBeans IDE) can be extended by third party developers. The NetBeans Platform is a reusable framework for simplifying the development of Java Swing desktop applications. The NetBeans IDE bundle for Java SE contains what is needed to start developing NetBeans plugins and NetBeans Platform based applications; no additional SDK is required. Applications can install modules dynamically. Any application can include the Update Center module to allow users of the application to download digitally-signedupgrades and new features directly into the running application. Reinstalling an upgrade or a new release does not force users to download the entire application again. The platform offers reusable services common to desktop applications, allowing developers to focus on the logic specific to their application. Among the features of the platform are:

User interface management (e.g. menus and toolbars) User settings management Storage management (saving and loading any kind of data) Window management Wizard framework (supports step-by-step dialogs) NetBeans Visual Library Integrated Development Tools

Netbeans IDE is a free, open-source, cross-platform IDE with built-in-support for Java Programming Language. Using an Integrated Development Environment (IDE) for developing applications saves you time by managing windows, settings, and data. In addition, an IDE can store repetitive tasks through macros and abbreviations. Drag-and-drop features make creating graphical user interface (GUI) components or accessing databases easy, and highlighted code and debugging features alert you to errors in your code. The NetBeans IDE is open source and is written in the Java programming language. It provides the services common to creating desktop applications -- such as window and menu management, settings storage -- and is also the first IDE to fully support JDK 6.0 features. The NetBeans

08/IT/017 platform and IDE are free for commercial and noncommercial use, and they are supported by Sun Microsystems. The NetBeans IDE has many features and tools for each of the Java platforms. Those in the following list are not limited to the Java SE platform but are useful for building, debugging, and deploying applications and applets: Source Code Editor

Syntax highlighting for Java, JavaScript, XML, HTML, CSS, JSP, IDL Customizable fonts, colors, and keyboard shortcuts Live parsing and error marking Pop-up Javadoc for quick access to documentation Advanced code completion Automatic indentation, which is customizable Word matching with the same initial prefixes Navigation of current class and commonly used features Macros and abbreviations Goto declaration and Goto class Matching brace highlighting JumpList allows you to return the cursor to previous modification

GUI Builder

Fully WYSIWYG (What-You-See-Is-What-You-Get) designer with Test Form feature Support for visual and nonvisual forms Extensible Component Palette with preinstalled Swing and AWT components Component Inspector showing a component's tree and properties Automatic one-way code generation, fully customizable Support for AWT/Swing layout managers, drag-and-drop layout customization Powerful visual editor Support for null layout In-place editing of text labels of components, such as labels, buttons, and text fields JavaBeans support, including installing, using, and customizing properties, events, and customizers Visual JavaBean customization -- ability to create forms from any JavaBean classes Connecting beans using Connection wizard Zoom view ability

Database Support

Database schema browsing to see the tables, views, and stored procedures defined in a database Database schema editing using wizards Data view to see data stored in tables SQL and DDL command execution to help you write and execute more complicated SQL or DDL commands Migration of table definitions across databases from different vendors Works with databases, such as MySQL, PostgreSQL, Oracle, IBM DB2, Microsoft SQL Server, PointBase, Sybase, Informix, Cloudscape, Derby, and more

08/IT/017 The NetBeans IDE also provides full-featured refactoring tools, which allow you to rename and move classes, fields, and methods, as well as change method parameters. In addition, you get a debugger and an Ant-based project system.

08/IT/017

PROGRAM 3
Write a program to implement and understand exception handling
import java.io.*; public class Error { public static void main(String[] args) { // TODO Auto-generated method stub int invalid=0; int num,count=0; DataInputStream ds = new DataInputStream(System.in); for(int i=0;i<4;i++) { try{ System.out.println("\n Enter a no : "); num= Integer.parseInt(ds.readLine()); } catch(NumberFormatException e) { invalid++;

System.out.println("\nException Caught : Invalid Incremented : invalid = " + invalid); continue; } catch(Exception e){} count++; System.out.println(" \n Valid Incremented : count = "+ count); } System.out.println("valid no: "+count); System.out.println("invalid no. : "+invalid); }}

08/IT/017

OUTPUT:
run: Enter a no : 8000 Valid Incremented : count = 1 Enter a no : hu Exception Caught : Invalid Incremented : invalid = 1 Enter a no : 2o Exception Caught : Invalid Incremented : invalid = 2 Enter a no : 12 Valid Incremented : count = 2 valid no: 2 invalid no. : 2 BUILD SUCCESSFUL (total time: 17 seconds)

08/IT/017

PROGRAM 4
Write a program to implement and understand Multithreading
class A extends Thread { public void run() { for(int i=1;i<=5;i++) { if(i==1) yield(); System.out.println("\t From Thread A:i="+i); } System.out.println("exit from A"); } } class B extends Thread { public void run() { for(int j=1;j<=5;j++) { System.out.println("\t From Thread B:j="+j); if(j==3) stop(); } System.out.println("exit from B"); }

08/IT/017 }

class C extends Thread { public void run() { for(int k=1;k<=5;k++) { System.out.println("\t From Thread C:k="+k); if(k==1) try { sleep(1000); } catch(Exception e) { }} System.out.println("exit from C"); }} class ThreadMwethods { public static void main(String args[]) { A threadA=new A(); B threadB=new B(); C threadC=new C(); System.out.println("start thread A");

08/IT/017 threadA.start(); System.out.println("start thread B"); threadB.start(); System.out.println("start thread C"); threadC.start(); System.out.println("end of main thread"); } }

08/IT/017

OUTPUT:
run: start thread A start thread B From Thread A:i=1 From Thread A:i=2 From Thread A:i=3 From Thread A:i=4 From Thread A:i=5 exit from A start thread C end of main thread From Thread B:j=1 From Thread B:j=2 From Thread B:j=3 From Thread C:k=1 From Thread C:k=2 From Thread C:k=3 From Thread C:k=4 From Thread C:k=5 exit from C BUILD SUCCESSFUL (total time: 2 seconds)

08/IT/017

PROGRAM 5
Write a program to create and run an applet
import java.awt.*; import java.applet.*; public class Sum extends Applet { TextField text1, text2; public void init() { text1=new TextField(8); text2=new TextField(8); add(text1); add(text2); text1.setText(""); text2.setText(""); } public void paint(Graphics g) { int x=0,y=0,z=0; String s1,s2,s; g.drawString("Input a number in each box",10,50); try { s1=text1.getText(); x=Integer.parseInt(s1); s2=text2.getText(); y=Integer.parseInt(s2);

08/IT/017 } catch(Exception ex) { } z=x+y; s=String.valueOf(z); g.drawString("The sum is:",10,75); g.drawString(s,100,75); } public boolean action(Event event,Object object) { repaint(); return true; } }

08/IT/017

OUTPUT:

08/IT/017

PROGRAM 6
Write a program to implement file handling
import java.io.*; class file3 { public static void main(String args[]) { FileInputStream infile = null; int temp; try { infile = new FileInputStream("city.dat"); while( (temp = infile.read() ) != -1) { System.out.print((char)temp); }} catch(IOException e) { } finally { try { infile.close(); } catch(IOException e) { }} }/// end main }// end class

08/IT/017

OUTPUT:
run: This is a program for file handling BUILD SUCCESSFUL (total time: 1 second)

08/IT/017

PROGRAM 7
Write a program to create client and server sockets
import java.io.*; import java.net.*; public class Client { public static void main(String args[]) { try { Socket server; String str=""; DataInputStream d=new DataInputStream(System.in); PrintStream toserver; BufferedReader fromserver; server=new Socket("192.168.0.204",1096); InputStreamReader isr=new InputStreamReader(server.getInputStream()); fromserver= new BufferedReader(isr); toserver=new PrintStream(server.getOutputStream()); while(true) { str=":"+d.readLine(); toserver.println(str); str=fromserver.readLine(); System.out.println(str); }} catch(Exception e)

08/IT/017 { System.out.println(e); }} import java.io.*; import java.net.*; public class Server { public static void main(String args[]) { ServerSocket sc; Socket client; DataInputStream d; PrintStream toClient; BufferedReader fromClient; String str=""; try { d=new DataInputStream(System.in); sc=new ServerSocket(1096); System.out.println("ServerStarted"); client=sc.accept(); InputStreamReader isr=new InputStreamReader(client.getInputStream()); fromClient=new BufferedReader(isr); toClient=new PrintStream(client.getOutputStream()); while(true) { str=fromClient.readLine();

08/IT/017 System.out.println(str); str=":"+d.readLine(); toClient.println(str); }} catch(Exception e) { System.out.println(e); } }

08/IT/017

OUTPUT:

08/IT/017

PROGRAM 8
Write a program to implement and understand data base connectivity using JDBC
package jdbc; import java.sql.*; import java.lang.*; public class Base { public static void main(String[] args) { // TODO Auto-generated method stub try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection con=DriverManager.getConnection("jdbc:odbc:Login1"); Statement stmt=con.createStatement(); String s="Select * from College where course Like '%e'"; ResultSet rs=stmt.executeQuery(s); while(rs.next()) { String st=rs.getString("course"); System.out.println(st); } con.close(); } catch(Exception ex) { System.out.println("there is an exception"+ex); } }// end main }// end class

08/IT/017

OUTPUT:
run:

100

ABC

84

103

DEF

54

105

GFH

77

106

NBV

45

BUILD SUCCESSFUL (total time: 1 second)

08/IT/017

PROGRAM 9
Write a program to create a Distributed Application Using Remote Method Invocation
Step 1:Create Interface import java.rmi.*; public interface HelloInterface extends Remote { public String say() throws RemoteException; } Step 2:Implement Interface import java.rmi.*; import java.rmi.server.*; public class Hello extends UnicastRemoteObject implements HelloInterface { private String message; public Hello (String msg) throws RemoteException { message = msg; } public String say() throws RemoteException { return message; } } Step 3: Compile Both the file Step 4: Generate the Stub & Skelton rmic Hello Step 5: Rebind the Server import java.rmi.Naming; public class HelloServer { public static void main (String[] argv) {

08/IT/017 try { Naming.rebind ("Hello", new Hello ("Hello,From BSAITM!")); System.out.println ("Server is connected and ready for operation."); } catch (Exception e) { System.out.println ("Server not connected: " + e); }}} Step 6:Look up the Client import java.rmi.Naming; public class HelloClient { public static void main (String[] argv) { try { HelloInterface hello =(HelloInterface) Naming.lookup ("//192.168.10.201/Hello"); System.out.println (hello.say()); } catch (Exception e){ System.out.println ("HelloClient exception: " + e);} }} Step 7: Complie both the source file Step 8: Start RMI Registry Start rmiregistry

Note: do not close the registry window minimize it.

08/IT/017 Step9: start Server

Step 10: start Client

08/IT/017

PROGRAM 10
Write a program to create a tree using swings
import javax.swing.*; import javax.swing.tree.*; public class TreeComponent{ public static void main(String[] args) { JFrame frame = new JFrame("Creating a JTree Component!"); DefaultMutableTreeNode parent = new DefaultMutableTreeNode("Color", true); DefaultMutableTreeNode black = new DefaultMutableTreeNode("Black"); DefaultMutableTreeNode blue = new DefaultMutableTreeNode("Blue"); DefaultMutableTreeNode nBlue = new DefaultMutableTreeNode("Navy Blue"); DefaultMutableTreeNode dBlue = new DefaultMutableTreeNode("Dark Blue"); DefaultMutableTreeNode green = new DefaultMutableTreeNode("Green"); DefaultMutableTreeNode white = new DefaultMutableTreeNode("White"); parent.add(black); parent.add(blue); blue.add(nBlue); blue.add(dBlue); parent.add(green ); parent.add(white); JTree tree = new JTree(parent); frame.add(tree); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //frame.setUnde0corated(true); frame.getRootPane().setWindowDecorationStyle(JRootPane.PLAIN_DIALOG); frame.setSize(200,200); frame.setVisible(true); } }

08/IT/017

OUTPUT:

You might also like