Java:
Java:
The White Paper
The White Paper on Java uses the following eleven adjectives to describe the Java Language and Platform:
Simple
Object Oriented
Distributed
Robust
Secure
Architecture Neutral
Portable
Interpreted
High Performance
Multithreaded
Dynamic
Simple
15 Streamlined C++
16 No Header Files
17 No Pointer Arithmetic
18 No Structures, Unions, Operator Overloading, Virtual Base Classes, etc.
19 Small
20 Only 250K for the interpreter and base libraries
Distributed
22 import v. #include
23 networking
Robust
25 Java pointers
26 extensive error checking at both compile and run time
Secure
28 Java pointers
29 Class Loader
30 Byte Verifier
31 Security Manager
32 Applications v. Applets
Architecture Neutral
34 Byte Code is Byte Code
Portable
36 Fixed sizes primitive data types
37 32-bit Integers
38 Unicode
39 AWT to Swing
Interpreted
41 Faster than data stream
42 C++ simply waits longer
43 Recent optimized compilers get close to C++
44 JIT Compilers x10-x20
Multithreaded
46 Multiprocessing at the sub-process level
47 better interactive responsiveness and real time behavior
48 Extremely useful on Server side
Dynamic
50 Class Loader
51 Virtually All Objects Dynamically Allocated
52 . . . and Garbage Collected
53 Reflection and Introspection
JDK1.0.2
JDK1.1
56 JDK1.1.1
57 . . .
58 JDK1.1.8
JDK1.2 - Platform 2
60
61 add "C:\jdk1.x\bin" to path
Compiling and Running the Hello World Application
class HelloWorldApp {
public static void main(String[] args) {
System.out.println("Hello World!");
}
}
68 save as text file HelloWorldApp.java
69 at command line type>javac HelloWorldApp.java
70 execute program by typing>java HelloWorldApp
Compiling and Running the Hello World Applet
import java.applet.Applet;
import java.awt.Graphics;
class HelloWorldApplet extends Applet {
public void paint(Graphics g) {
g.drawString("Hello World!", 50, 25);
}
}
78 save as text file HelloWorldApplet.java
79 at command line type>javac HelloWorldApplet.java
80 execution is performed by viewer (browser)
Methods to override:
init();
start();
stop();
destroy();
paint();
Simple HTML
Texts:
90 Core Java by Horstmann and Cornell (Sun and Prentice Hall)
91 The Java Tutorial by Campione and Walrath (Sun and Prentice Hall)
Online:
93 The Java Tutorial -
94 JavaWorld Magazine -
95 Gamelan -
96 Excite, AltaVista, WebCrawler, etc.
97 A Beginner's Guide to HTML (NSCA)
Lecture 1b
Differences between C++ and Java
C++ is a superset of C while Java is a strictly Object Oriented Language.
C is procedural while C++ is object oriented
103 Many C++ programmers write non-OO code
104 Can't get away with that in Java
105 In Java, all classes descend from "Object"
C++ allows multiple inheritance while Java uses Interfaces.
107 Object Communication
108 An interface is a protocol by which two otherwise unrelated objects communicate
C++ runs on the hardware machine while Java runs on a Virtual machine.
110 Java Virtual Machine - Java Runtime Environment
C++ makes extensive use of pointers while Java has no specific pointer type.
In addition to the access specifiers of C++ (public, protected & private), Java adds a new one (package).
113 Individually tagged
C++ allows operator overloading; Java does not.
Java allows inner classes and anonymous inner classes; C++ does not.
Java is Garbage Collected; C++ is not.
117 new
118 no delete
In Java, arrays are objects.
120 out of bounds
121 length
class HelloWorldApp {
public static void main(String[] args) {
System.out.println("Hello World!");
}
}
// Not a GUI program.
GUI
For even the most basic GUI, one needs a working knowledge of :
Layout Managers
134 Interfaces
AWT (or Swing) widgets
136 1.1 Event Handling
import java.awt.*;
import java.awt.event.*;
public class CloseableFrame extends Frame
{
public CloseableFrame()
{ addWindowListener(new WindowAdapter()
{ public void windowClosing(WindowEvent e)
{ System.exit(0); } } );
setSize(300, 200);
setTitle(getClass().getName());
}
}
Resources
Texts:
147 Core Java by Horstmann and Cornell (Sun and Prentice Hall)
148 The Java Tutorial by Campione and Walrath (Sun and Prentice Hall)
Online:
150 The Java Tutorial -
151 JavaWorld Magazine -
152 Gamelan -
153 Excite, AltaVista, WebCrawler, etc.
Lecture #2
Reserved Words
abstract do implements private throws
boolean double import protected transient
break else inner public true
byte extends instanceof rest try
byvalue false int return var
case final interface short void
cast finally long static volatile
catch float native strictfp while
char for new super widefp
class future null switch
const generic operator synchronized
continue goto outer this
default if package throw
Reserved Words (Not Currently Used)
byvalue future inner rest
cast generic operator var
const goto outer
Non-Reserved Words (Examples)
delete include
define inline
friend using
ifdef virtual
Identifiers
o Theoretically may be made up from the Unicode character set but the tools only work with ASCII.
o The first character may only be a letter, a dollar sign or and underscore.
MyVariable $anotherName _yetAnotherName
o However, the convention is that method names start with a lower case letter:
public void myMethodThatDoesAmazingThings(){}
o While Variables and Class names start with an upper case letter:
public class MyClass {
public int MyVariable = 5;
}
Primitives
Type Contains Size Range
byte signed integer 8 bits -128 to 127
short signed integer 16 bits -32768 to 32767
char unsigned Unicode 16 bits \u0000 to \u FFFF
int signed integer 32 bits -231 to 231 – 1
float single precision 32 bits 1.4 x 10-45 to 3.4 x 1038
double double precision 64 bits 4.9 x 10-324 to 1.8 x 10308
boolean true or false --------- true or false
Primitives v. Reference Variables (Object Wrappers)
Primitive Object
byte Byte
short Short
char Char
int Integer
float Float
double Double
boolean Boolean
public class SimplePoint {
public int x = 0;
public int y = 0;
}
public class SimpleRectangle {
public int width = 0;
public int height = 0;
public SimplePoint origin = new SimplePoint();
}
public class Point {
public int x = 0;
public int y = 0;
// a constructor!
public Point(int x, int y) {
this.x = x;
this.y = y;
}
}
Passing Arguments
o In Java variables are passed by value.
The Class Declaration
o public
▪ By default, a class can be used only by other classes in the same package. The public modifier declares that the class can be used by any class regardless of its package.
o abstract
▪ Declares that the class cannot be instantiated.
o final
▪ Declares that the class cannot be subclasssed.
o class NameOfClass
▪ The class keyword indicates to the compiler that this is a class declaration and that the name of the class is NameOfClass.
o extends Super
▪ The extends clause identifies Super as the superclass of the class, thereby inserting the class within the class hierarchy.
o implements Interfaces
▪ To declare that your class implements one or more interfaces, use the keyword implements followed by a comma-delimited list of the names of the interfaces implemented by the class.
public final class MyClass extends Applet implements ItemListener, ActionListener {
. . .
}
Access Specifiers
o private
▪ Only accessible from within the class (not merely the instance).
o protected
▪ Also accessible from subclasses and package members.
o package
▪ Accessible from package members. (Friends, not family)
o public
o No restrictions. Accessible from anywhere.
Providing Constructors for Your Classes
Constructor Defined:
Default
public Stack() {
items = new Vector(10);
}
Overloaded
public Stack(int initialSize) {
items = new Vector(initialSize);
}
Constructor Called:
stack MyStack = new Stack(10);
stack MyOtherStack = new Stack();
This and Super
class AnimationThread extends Thread {
int framesPerSecond;
int numImages;
Image[] images;
AnimationThread(int fps, int num) {
super("AnimationThread");
this.framesPerSecond = fps;
this.numImages = num;
this.images = new Image[numImages];
for (int i = 0; i = 0) {
command += value.substring(from, to) + "''";
from = to + 1;
} // End of while()
command += value.substring(from) + "'";
} // End of if(columnType.start…)
else command += value;
} // End of for()
command += ")";
stmt.executeUpdate(command);
} // End of void insertInto();
private static void showTable(Statement stmt,
String tableName, int numCols) throws SQLException {
String query = "SELECT * FROM " + tableName;
ResultSet rs = stmt.executeQuery(query);
while (rs.next()){
for (int i = 1; i 1) System.out.print("|");
System.out.print(rs.getString(i));
} // End of for()
System.out.println("");
}// End of while(rs.next())
rs.close();
} // End of void showTable
}
Java Database Connectivity (JDBC)
Load the Driver:
. . .
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
// force loading of driver
. . .
Connect to the Database:
. . .
String url = "jdbc:odbc:corejava";
String user = "Cay";
String password = "password";
Connection con = DriverManager.getConnection(url,
user, password);
. . .
Issue Java-wrapped SQL statements:
. . .
Statement stmt = con.createStatement();
. . .
String command = "CREATE TABLE " + tableName + "(\n";
. . .
command += ")\n";
stmt.executeUpdate(command);
. . .
String command = "INSERT INTO " + tableName
+ " VALUES (";
. . .
command += ")";
stmt.executeUpdate(command);
Java Database Connectivity (JDBC)
Example Oracle Driver (in classes111.zip):
oracle.jdbc.driver.OracleDriver
Use the DriverManager to make the connection:
Connection conn =
DriverManager.getConnection ("jdbc:oracle:thin:@logic.njit.edu:1521:logic40",
"ted", "tln2880");
Java Database Connectivity (JDBC)
Simple Oracle Query:
import java.sql.*;
class Employee {
public static void main (String args []) throws SQLException, ClassNotFoundException
{
// Load the Oracle JDBC driver
Class.forName ("oracle.jdbc.driver.OracleDriver");
// Connect to the database
// You must put a database name after the @ sign in the connection URL.
// You can use either the fully specified SQL*net syntax or a short cut
// syntax as ::. The example uses the short cut syntax.
Connection conn = DriverManager.getConnection
("jdbc:oracle:thin:@logic.njit.edu:1521:logic40", "ted", "tln2880");
// Create a Statement
Statement stmt = conn.createStatement ();
// Select all columns from the "test" table
ResultSet rset = stmt.executeQuery ("select * from test");
// Iterate through the result and print the employee names
while (rset.next ()) System.out.println (rset.getString ("c"));
}
}
Java Database Connectivity (JDBC)
ResultSet executeQuery(String sql)
Executes a SQL statement that returns a single ResultSet.
rset.next()
moves cursor to next row (must be done initially)
rset.getString(1) or rset.getString("column name")
int executeUpdate(String sql)
Executes an SQL INSERT, UPDATE or DELETE statement.
Java Database Connectivity (JDBC)
import .*;
import java.sql.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import corejava.*;
public class QueryDB extends CloseableFrame implements ActionListener {
public QueryDB() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
authors = new Choice();
authors.addItem("Any");
publishers = new Choice();
publishers.addItem("Any");
result = new TextArea(4, 50);
result.setEditable(false);
priceChange = new TextField(8);
priceChange.setText("-5.00");
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
// force loading of driver
String url = "jdbc:odbc:corejava";
String user = "Cay";
String password = "password";
con = DriverManager.getConnection(url, user, password);
stmt = con.createStatement();
String query = "SELECT Name FROM Authors";
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) authors.addItem(rs.getString(1));
query = "SELECT Name FROM Publishers";
rs = stmt.executeQuery(query);
while (rs.next()) publishers.addItem(rs.getString(1));
} catch(Exception e) { result.setText("Error " + e);}
gbc.fill = GridBagConstraints.NONE;
gbc.weightx = 100;
gbc.weighty = 100;
add(authors, gbc, 0, 0, 2, 1);
add(publishers, gbc, 2, 0, 2, 1);
gbc.fill = GridBagConstraints.NONE;
Button queryButton = new Button("Query");
add(queryButton, gbc, 0, 1, 1, 1);
queryButton.addActionListener(this);
Button changeButton = new Button("Change prices");
add(changeButton, gbc, 2, 1, 1, 1);
changeButton.addActionListener(this);
add(priceChange, gbc, 3, 1, 1, 1);
gbc.fill = GridBagConstraints.BOTH;
add(result, gbc, 0, 2, 4, 1);
} // End of Constructor
private void add(Component c, GridBagConstraints gbc, int x, int y, int w, int h) {
gbc.gridx = x;
gbc.gridy = y;
gbc.gridwidth = w;
gbc.gridheight = h;
add(c, gbc);
} // End of void add()
public void actionPerformed(ActionEvent evt) {
String arg = evt.getActionCommand();
if (arg.equals("Query")) {
ResultSet rs = null;
try {
String author = authors.getSelectedItem();
String publisher = publishers.getSelectedItem();
if (!author.equals("Any")
&& !publisher.equals("Any")) {
if (authorPublisherQueryStmt == null) {
String authorPublisherQuery =
"SELECT Books.Price, Books.Title " +
"FROM Books, BooksAuthors, Authors, Publishers " +
"WHERE Authors.Author_Id = BooksAuthors.Author_Id AND " +
"BooksAuthors.ISBN = Books.ISBN AND " +
"Books.Publisher_Id = Publishers.Publisher_Id AND " +
"Authors.Name = ? AND " +
"Publishers.Name = ?";
authorPublisherQueryStmt
= con.prepareStatement(authorPublisherQuery);
} // End of if(authorPublichserQueryStmt…)
authorPublisherQueryStmt.setString(1, author);
authorPublisherQueryStmt.setString(2, publisher);
rs = authorPublisherQueryStmt.executeQuery();
} // End of if(!author.equals)
else if (!author.equals("Any") && publisher.equals("Any")) {
if (authorQueryStmt == null) {
String authorQuery =
"SELECT Books.Price, Books.Title " +
"FROM Books, BooksAuthors, Authors " +
"WHERE Authors.Author_Id = BooksAuthors.Author_Id AND " +
"BooksAuthors.ISBN = Books.ISBN AND " +
"Authors.Name = ?";
authorQueryStmt = con.prepareStatement(authorQuery);
} // End of if(authorQueryStmt…)
authorQueryStmt.setString(1, author);
rs = authorQueryStmt.executeQuery();
} // End of else if(!author.equals())
else if (author.equals("Any") && !publisher.equals("Any")) {
if (publisherQueryStmt == null) {
String publisherQuery =
"SELECT Books.Price, Books.Title " +
"FROM Books, Publishers " +
"WHERE Books.Publisher_Id = Publishers.Publisher_Id AND " +
"Publishers.Name = ?";
publisherQueryStmt = con.prepareStatement(publisherQuery);
} // End of if(publisherQueryStmt…)
publisherQueryStmt.setString(1, publisher);
rs = publisherQueryStmt.executeQuery();
} // End of else if (!author.equals())
else {
if (allQueryStmt == null) {
String allQuery = "SELECT Books.Price, Books.Title FROM Books";
allQueryStmt = con.prepareStatement(allQuery);
}
rs = allQueryStmt.executeQuery();
} // End of else
result.setText("");
while (rs.next())
result.append(rs.getString(1) + " | " + rs.getString(2) + "\n");
rs.close();
} // End of try
catch(Exception e) { result.setText("Error " + e);}
} // End of if(arg.equals(“Query”)
else if (arg.equals("Change prices")) {
String publisher = publishers.getSelectedItem();
if (publisher.equals("Any")) result.setText ("I am sorry, but I cannot do that.");
else
try {
String updateStatement =
"UPDATE Books " +
"SET Price = Price + " + priceChange.getText() +
" WHERE Books.Publisher_Id = " +
"(SELECT Publisher_Id FROM Publishers WHERE Name = '" + publisher + "')";
int r = stmt.executeUpdate(updateStatement);
result.setText(r + " records updated.");
} // End of try
catch(Exception e) { result.setText("Error " + e);}
} // End of else if(arg.equals(“Ch…”)
} // End of void actionPerformed()
public void dispose() {
try {
stmt.close();
con.close();
} catch(SQLException e) {}
}
public static void main (String args[]){
Frame f = new QueryDB();
f.setSize(400, 300);
f.show();
}
private Choice authors;
private Choice publishers;
private TextField priceChange;
private TextArea result;
private Connection con;
private Statement stmt;
private PreparedStatement authorQueryStmt;
private PreparedStatement authorPublisherQueryStmt;
private PreparedStatement publisherQueryStmt;
private PreparedStatement allQueryStmt;
}
Java Database Connectivity (JDBC)
Load the Driver:
. . .
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
. . .
Connect to the Database:
. . .
String url = "jdbc:odbc:corejava";
String user = "Cay";
String password = "password";
Connection con = DriverManager.getConnection(url,
user, password);
. . .
Issue Java-wrapped SQL statements:
. . .
Statement stmt = con.createStatement();
. . .
String query = "SELECT Name FROM Authors";
ResultSet rs = stmt.executeQuery(query);
while (rs.next())
authors.addItem(rs.getString(1));
query = "SELECT Name FROM Publishers";
rs = stmt.executeQuery(query);
while (rs.next())
publishers.addItem(rs.getString(1));
Java Database Connectivity (JDBC)
import .*;
import java.sql.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import corejava.*;
public class ViewDB extends CloseableFrame implements ActionListener, ItemListener {
public ViewDB() {
tableNames = new Choice();
tableNames.addItemListener(this);
dataPanel = new Panel();
add(dataPanel, "Center");
Panel p = new Panel();
Button nextButton = new Button("Next");
p.add(nextButton);
nextButton.addActionListener(this);
add(p, "South");
fields = new Vector();
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
// force loading of driver
String url = "jdbc:odbc:corejava";
String user = "Cay";
String password = "password";
con = DriverManager.getConnection(url, user, password);
stmt = con.createStatement();
md = con.getMetaData();
ResultSet mrs = md.getTables(null, null, null, new String[] { "TABLE" });
while (mrs.next()) tableNames.addItem(mrs.getString(3));
mrs.close();
} catch(Exception e) { System.out.println("Error " + e);}
add(tableNames, "North");
} // End of ViewDB
private void add(Container p, Component c, GridBagConstraints gbc, int x, int y, int w, int h)
{
gbc.gridx = x;
gbc.gridy = y;
gbc.gridwidth = w;
gbc.gridheight = h;
p.add(c, gbc);
}
public void itemStateChanged(ItemEvent evt) {
if (evt.getStateChange() == ItemEvent.SELECTED) {
remove(dataPanel);
dataPanel = new Panel();
fields.removeAllElements();
dataPanel.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.NONE;
gbc.anchor = GridBagConstraints.WEST;
gbc.weightx = 100;
gbc.weighty = 100;
try {
String tableName = (String)evt.getItem();
if (rs != null) rs.close();
rs = stmt.executeQuery("SELECT * FROM " + tableName);
ResultSetMetaData rsmd = rs.getMetaData();
for (int i = 1; i keytool -import -alias ted -file Nicholson.cer
Security policytool
Security
Here's a plugin applet that tries to read from a local file named "writetest".
Parsing an HTML page
import java.io.*;
import .*;
import javax.swing.text.*;
import javax.swing.text.html.*;
class GetLinks {
public static void main(String[] args) {
EditorKit kit = new HTMLEditorKit();
Document doc = kit.createDefaultDocument();
// The Document class does not yet
// handle charset's properly.
doc.putProperty("IgnoreCharsetDirective",
Boolean.TRUE);
try {
// Create a reader on the HTML content.
Reader rd = getReader(args[0]);
// Parse the HTML.
kit.read(rd, doc, 0);
// Iterate through the elements
// of the HTML document.
ElementIterator it = new ElementIterator(doc);
javax.swing.text.Element elem;
while ((elem = it.next()) != null) {
SimpleAttributeSet s = (SimpleAttributeSet)
elem.getAttributes().getAttribute(HTML.Tag.A);
if (s != null) {
System.out.println(s.getAttribute(HTML.Attribute.HREF));
}
}
} catch (Exception e) {e.printStackTrace();}
System.exit(1);
}
// Returns a reader on the HTML data. If 'uri' begins
// with "http:", it's treated as a URL; otherwise,
// it's assumed to be a local filename.
static Reader getReader(String uri) throws IOException {
if (uri.startsWith("http:")) {
// Retrieve from Internet.
URLConnection conn = new URL(uri).openConnection();
return new InputStreamReader(conn.getInputStream());
} else {
// Retrieve from file.
return new FileReader(uri);
}
}
}
................
................
In order to avoid copyright disputes, this page is only a partial summary.
To fulfill the demand for quickly locating and searching documents.
It is intelligent file search solution for home and business.
Related searches
- java sample code for beginners
- java this example
- this in java code
- all java codes
- sample java code
- java minecraft free download windows 10
- minecraft free download full version java edition
- minecraft java edition free download
- minecraft java edition full version
- basic java programming examples
- java collections tutorial with examples
- java sample programs