Posted by the original poster: 2008-06-17 15:26:20
lJBS
1. List 10 advantages of JAVA language
a: Free, open source, cross-platform (platform independence), easy to use, complete functions, object-oriented, robust, multi-threaded, structure neutral, mature platform for enterprise applications, wireless applications
2. List 10 object-oriented programming terms in JAVA
a: package, class, interface, object, attribute, method, constructor, inheritance, encapsulation, polymorphism, abstraction, paradigm
3. List 6 commonly used packages in JAVA
Java.lang;java.util;java.io;java.sql;java.awt;java.net;java.applet;javax.swing
4. What are the functions and characteristics of identifiers in JAVA? Function: Identifiers are used to name variables, classes and methods. Characteristics: In addition to starting with letters, underscores "_" and "$" characters, they can be followed by letters, Underscore "_" and "$" characters or numbers
Java is case-sensitive, and identifiers are no exception
5.What are the characteristics of keywords in JAVA? List at least 20 keywords
Some words in Java that are given specific meanings and used for special purposes are called keywords
All Java keywords are lowercase, TURE, FALSE, NULL, etc. are not Java keywords;
goto and const, although never used, are reserved as Java keywords;
There are a total of 51 keywords Java in •
abstract assert boolean break byte continue
case catch char class const double
default do extends else final float
for goto long if implements import
native new null instanceof int interface
package private protected public return short
static strictfp super switch synchronized this
while void throw throws transient try
volatile
6.How are data types classified in JAVA?
Can be divided into simple data types and reference data types:
Simple data types: numerical type (byte, short, int, long, float double), character type (char), Boolean type (boolean);
Reference data types: class, interface, array.
7. Classification and examples of operators in JAVA
• Separator:,,;,[],()
• Arithmetic operators: +, ―, *, /, %, ++, ――
• Relational operators: >, <, >=, <=, ==, !=
• Boolean logical operators: !, &, |, ^, &&, ||
• Bit operators: &, |, ^, ~, >>, < <, >>>
• Assignment operator: = Extended assignment operator: +=, ―=, *=, /=
• String concatenation operator: +
• Shape operator: ()
8.The function and usage of super and this keywords
• Use super in a Java class to refer to components of the parent class
– Can be used to access attributes super defined in the parent class
– Can be used to call the member method super defined in the parent class
– Can be used to call the super class constructor super in the subclass constructor
– Traceability is not limited to the direct parent class super
In order to solve the naming conflict and uncertainty problem of variables, the keyword "this" is introduced to represent the current object of the method in which it is located. Java
– The constructor refers to the new object created by the constructor
– The method refers to the object that calls the method
• Usage of keywordsthis
– Reference the instance variables and methods of the class in the method or constructor of the class itself
– Pass the current object as a parameter to other methods or constructors
– Used to call other overloaded constructors
9. What is an expression in JAVA? What does it do?
• An expression is a combination of operators and operands, and is a key component of any programming language
• Expressions allow programmers to perform mathematical calculations, comparison of values, logical operations and manipulation of objects in Java.
• Some examples of expressions:
–X
– X+10
– Y=x+10
–Arr[10]
– student.geName()
10. Make a table listing all modifiers in JAVA and their scope of application (can they modify constructors, properties, free blocks, etc.)
class attribute method builder free block inner class
public YYY Y Y
protected YY Y Y
(Default) YYYYYY
private YY Y Y
final YY Y Y
abstract Y Y Y
static Y YY
11. Write a method to print the multiplication table using a for loop
/**
*A for loop prints the multiplication table
*/
publicvoid nineNineMultiTable()
{
for (int i = 1,j = 1; j <= 9; i++) {
System.out.print(i+"*"+j+"="+i*j+" ");
if(i==j)
{
i=0;
j++;
System.out.println();
}
}
}
12. Given a java.util.Date object, how to convert it into a string in the format of "2007-3-22 20:23:22"
/**
*Convert a date into a string in a fixed format
*@paramdate
*@returnstr
*/
public String dateToStr(java.util.Date date)
{
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String str = sdf.format(date);
return str;
}
13. Write a method that can determine whether any integer is prime.
/**
* Determine whether any integer is prime
*@paramn
*@returnboolean
*/
publicboolean isPrimes(int n)
{
for (int i = 2; i <= Math.sqrt(n); i++) {
if(n%i==0)
{
returnfalse;
}
}
returntrue;
}
14. Write a method that inputs any integer and returns its factorial
/**
*Get the factorial of any integer
*@paramn
*@returnn !
*/
publicint factorial(int n)
{
//recursion
if(n==1)
{
return 1;
}
return n*factorial(n-1);
//non-recursive
// int multi = 1;
// for (int i = 2; i <= n; i++) {
// multi*=i;
// }
// return multi;
}
15. Write a method that uses binary search to determine whether any integer exists in any integer array. If it exists, return its index position in the array. If it does not exist, return -1.
/**
*Binary search for the position of a specific integer in the integer array (recursive)
*@paramdataset
*@paramdata
*@parambeginIndex
*@paramendIndex
*@returnindex
*/
publicint binarySearch(int[] dataset,int data,int beginIndex,int endIndex)
{
int midIndex = (beginIndex+endIndex)/2;
if(data <dataset[beginIndex]||data>dataset[endIndex]||beginIndex>endIndex)return -1;
if(data <dataset[midIndex])
{
return binarySearch(dataset,data,beginIndex,midIndex-1);
}elseif(data>dataset[midIndex])
{
return binarySearch(dataset,data,midIndex+1,endIndex);
}else
{
return midIndex;
}
}
/**
*Binary search for the position of a specific integer in the integer array (non-recursive)
*@paramdataset
*@paramdata
*@returnindex
*/
publicint binarySearch(int[] dataset,int data)
{
int beginIndex = 0;
int endIndex = dataset.length - 1;
int midIndex = -1;
if(data <dataset[beginIndex]||data>dataset[endIndex]||beginIndex>endIndex)return -1;
while(beginIndex <= endIndex) {
midIndex = (beginIndex+endIndex)/2;
if(data <dataset[midIndex]) {
endIndex = midIndex-1;
} elseif(data>dataset[midIndex]) {
beginIndex = midIndex+1;
}else
{
return midIndex;
}
}
return -1;
}
16. An example of a breeder feeding food to animals reflects the object-oriented thinking in JAVA and the usefulness of interfaces (abstract classes)
package com.softeem.demo;
/**
*@authorleno
*Animal interface
*/
interface Animal
{
publicvoid eat(Food food);
}
/**
*@authorleno
*an animal type: cat
*/
class Cat implements Animal
{
publicvoid eat(Food food)
{
System.out.println("Kitten eats"+food.getName());
}
}
/**
*@authorleno
*an animal type: dog
*/
class Dog implements Animal
{
publicvoid eat(Food food)
{
System.out.println("Puppy Chewing"+food.getName());
}
}
/**
*@authorleno
*Food abstract class
*/
abstractclassFood
{
protected String name;
public String getName() {
returnname;
}
publicvoid setName(String name) {
this.name = name;
}
}
/**
*@authorleno
*A food group: fish
*/
class Fish extends Food
{
public Fish(String name) {
this.name = name;
}
}
/**
*@authorleno
*A food group: bones
*/
class Bone extends Food
{
public Bone(String name) {
this.name = name;
}
}
/**
*@authorleno
*Breeder category
*
*/
classFeeder
{
/**
*The breeder feeds a certain kind of food to a certain kind of animal
*@paramanimal
*@paramfood
*/
publicvoid feed(Animal animal,Food food)
{
animal.eat(food);
}
}
/**
*@authorleno
*Test breeders feeding animals food
*/
publicclass TestFeeder {
publicstaticvoid main(String[] args) {
Feeder feeder=new Feeder();
Animal animal=new Dog();
Food food=new Bone("meat bone");
feeder.feed(animal,food); //Feed meat bones to the dog
animal=new Cat();
food=new Fish("fish");
feeder.feed(animal,food); //Feed fish to the cat
}
}
18. Make a single-mode class and only load the properties file once
package com.softeem.demo;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
/**
*@authorleno
*Single mode, ensuring that the configuration property file is only loaded once during the entire application
*/
publicclass Singleton {
privatestatic Singleton instance;
privatestaticfinal String CONFIG_FILE_PATH = "E:\config.properties";
private Properties config;
private Singleton()
{
config = new Properties();
InputStream is;
try {
is = new FileInputStream(CONFIG_FILE_PATH);
config.load(is);
is.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
publicstatic Singleton getInstance()
{
if(instance==null)
{
instance = new Singleton();
}
returninstance;
}
public Properties getConfig() {
returnconfig;
}
publicvoid setConfig(Properties config) {
this.config = config;
}
}
l J2SE
19. Copy a directory (file) to the specified path
/**
*Copy a directory or file to the specified path
*@paramsource
*@paramtarget
*/
publicvoid copy(File source,File target)
{
File tarpath = new File(target,source.getName());
if(source.isDirectory())
{
tarpath.mkdir();
File[] dir = source.listFiles();
for (int i = 0; i < dir.length; i++) {
copy(dir[i],tarpath);
}
}else
{
try {
InputStream is = new FileInputStream(source);
OutputStream os = new FileOutputStream(tarpath);
byte[] buf = newbyte[1024];
int len = 0;
while((len = is.read(buf))!=-1)
{
os.write(buf,0,len);
}
is.close();
os.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
20. Example of bank withdrawal problem using multi-threading in JAVA
packagecom.softeem.demo;
/**
*@authorleno
*Account type
*There is a balance by default and you can withdraw money
*/
class Account {
privatefloatbalance = 1000;
publicfloat getBalance() {
returnbalance;
}
publicvoid setBalance(float balance) {
this.balance = balance;
}
/**
*Withdrawal methods need to be synchronized
*@parammoney
*/
publicsynchronizedvoid withdrawals(float money)
{
if(balance>=money)
{
System.out.println("Taken"+money+"Yuan!");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
balance-=money;
}
else
{
System.out.println("Sorry, insufficient balance!");
}
}
}
/**
*@authorleno
*bank card
*/
class TestAccount1 extends Thread {
private Account account;
public TestAccount1(Account account) {
this.account = account;
}
@Override
publicvoid run() {
account.withdrawals(800);
System.out.println("The balance is:"+account.getBalance()+"Yuan!");
}
}
/**
*@authorleno
*Passbook
*/
class TestAccount2 extends Thread {
private Account account;
public TestAccount2(Account account) {
this.account = account;
}
@Override
publicvoid run() {
account.withdrawals(700);
System.out.println("The balance is:"+account.getBalance()+"Yuan!");
}
}
publicclass Test
{
publicstaticvoid main(String[] args) {
Account account = new Account();
TestAccount1 testAccount1 = new TestAccount1(account);
testAccount1.start();
TestAccount2 testAccount2 = new TestAccount2(account);
testAccount2.start();
}
}
21. Use multi-threading in JAVA to example train station ticket sales problem
package com.softeem.demo;
/**
*@authorleno
*Ticket sales
*/
class SaleTicket implements Runnable {
inttickets = 100;
publicvoid run() {
while (tickets > 0) {
sale();
//Or implement it like this
// synchronized (this) {
// if (tickets > 0) {
// System.out.println(Thread.currentThread().getName() + "Sell the first"
// + (100 - tickets + 1) + "tickets");
// tickets--;
// }
// }
}
}
publicsynchronizedvoid sale() {
if (tickets > 0) {
System.out.println(Thread.currentThread().getName() + "Sell first"
+ (100 - tickets + 1) + "tickets");
tickets--;
}
}
}
publicclass TestSaleTicket {
publicstaticvoid main(String[] args) {
SaleTicket st = new SaleTicket();
new Thread(st, "Window No. 1").start();
new Thread(st, "Window No. 2").start();
new Thread(st, "Window No. 3").start();
new Thread(st, "Window No. 4").start();
}
}
22. Example of producer and consumer issues using multi-threading in JAVA
package com.softeem.demo;
class Producer implements Runnable
{
private SyncStack stack;
public Producer(SyncStack stack) {
this.stack = stack;
}
publicvoid run() {
for (int i = 0; i < stack.getProducts().length; i++) {
String product = "product"+i;
stack.push(product);
System.out.println("Produced: "+product);
try
{
Thread.sleep(200);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
}
}
class Consumer implements Runnable
{
private SyncStack stack;
public Consumer(SyncStack stack) {
this.stack = stack;
}
publicvoid run() {
for(int i=0;i <stack.getProducts().length;i++)
{
String product =stack.pop();
System.out.println("Consumed: "+product);
try
{
Thread.sleep(1000);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
}
}
class SyncStack
{
private String[] products = new String[10];
privateintindex;
publicsynchronizedvoid push(String product)
{
if(index==product.length())
{
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
notify();
products[index]=product;
index++;
}
publicsynchronized String pop()
{
if(index==0)
{
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
notify();
index--;
String product = products[index];
return product;
}
public String[] getProducts() {
returnproducts;
}
}
publicclass TestProducerConsumer {
publicstaticvoid main(String[] args) {
SyncStack stack=new SyncStack();
Producer p=new Producer(stack);
Consumer c=new Consumer(stack);
new Thread(p).start();
new Thread(c).start();
}
}
23. Programming to realize the transmission of serialized Student (sno, sname) objects on the network
package com.softeem.demo;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.net.ServerSocket;
import java.net.Socket;
class Student implements Serializable {
private int sno;
private String sname;
public Student(int sno, String sname) {
this.sno = sno;
this.sname = sname;
}
public int getSno() {
return sno;
}
public void setSno(int sno) {
this.sno = sno;
}
public String getSname() {
return sname;
}
public void setSname(String sname) {
this.sname = sname;
}
@Override
public String toString() {
return "Student number:" + sno + ";Name:" + sname;
}
}
class MyClient extends Thread {
@Override
public void run() {
try {
Socket s = new Socket("localhost", 9999);
ObjectInputStream ois = new ObjectInputStream(s.getInputStream());
Student stu = (Student) ois.readObject();
System.out.println("The client program receives the student object transferred from the server program >> " + stu);
ois.close();
s.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class MyServer extends Thread {
@Override
public void run() {
try {
ServerSocket ss = new ServerSocket(9999);
Socket s = ss.accept();
ObjectOutputStream ops = new ObjectOutputStream(s.getOutputStream());
Student stu = new Student(1, "Zhao Benshan");
ops.writeObject(stu);
ops.close();
s.close();
ss.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public class TestTransfer {
public static void main(String[] args) {
new MyServer().start();
new MyClient().start();
}
}
l JDBC
24. Use the dom4j component to parse the following XML format files:
<?xml version="1.0" encoding="UTF-8"?>
<generator>
<table name="login" operation="1">
<column name="username" handle="0">aaa </column>
<column name="password" handle="0">123 </column>
</table>
<table name="login" operation="2">
<column name="id" handle="1">1 </column>
<column name="username" handle="0">bbb </column>
<column name="password" handle="0">444 </column>
</table>
<table name="login" operation="3">
<column name="id" handle="1">4 </column>
</table>
</generator>
Rules: <table>operation 1 table insert, table 2 update, table 3 delete.
<column>handle 1 table is used as where condition, 0 table is used as operation field.
Requirement: Generate three SQL statements according to the rules! (That is, make a method to parse the xml file to generate a string containing three SQL statements)
/**
*Parse the XML file to generate a string containing executable SQL statements
*@paramxmlFileName
*@returnSQL
*/
public String parseXmltoSQL(String xmlFileName) {
StringBuffer sbsql = new StringBuffer();
SAXReader reader = new SAXReader();
try {
Document document = reader.read(new File(xmlFileName));
Element element = document.getRootElement();
Iterator it = element.elementIterator("table");
while (it.hasNext()) {
element = (Element) it.next();
//Get operations on the table
String oper = element.attributeValue("operation");
//Get the table name
String tableName = element.attributeValue("name");
if ("1".equals(oper)) {
sbsql.append("insert into ").append(tableName);
Iterator it2 = element.elementIterator("column");
String columnName1 = null;
String columnValue1 = null;
String columnName2 = null;
String columnValue2 = null;
if (it2.hasNext()) {
element = (Element) it2.next();
columnName1 = element.attributeValue("name");
columnValue1 = element.getText();
}
if (it2.hasNext()) {
element = (Element) it2.next();
columnName2 = element.attributeValue("name");
columnValue2 = element.getText();
}
sbsql.append("("+columnName1+","+columnName2+")"+" values('"+columnValue1+"','"+columnValue2+"')n");
} elseif ("2".equals(oper)) {
sbsql.append("update ").append(tableName);
Iterator it2 = element.elementIterator("column");
String columnName1 = null;
String columnValue1 = null;
String columnName2 = null;
String columnValue2 = null;
String columnName3 = null;
String columnValue3 = null;
if (it2.hasNext()) {
element = (Element) it2.next();
columnName1 = element.attributeValue("name");
columnValue1 = element.getText();
}
if (it2.hasNext()) {
element = (Element) it2.next();
columnName2 = element.attributeValue("name");
columnValue2 = element.getText();
}
if (it2.hasNext()) {
element = (Element) it2.next();
columnName3 = element.attributeValue("name");
columnValue3 = element.getText();
}
sbsql.append(" set "+columnName2+"='"+columnValue2+"',"+columnName3+"='"+columnValue3+"' where "+columnName1+"="+columnValue1+"n");
}elseif ("3".equals(oper)) {
sbsql.append("delete from ").append(tableName);
Iterator it2 = element.elementIterator("column");
String columnName1 = null;
String columnValue1 = null;
if (it2.hasNext()) {
element = (Element) it2.next();
columnName1 = element.attributeValue("name");
columnValue1 = element.getText();
}
sbsql.append(" where "+columnName1+"="+columnValue1);
}
}
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return sbsql.toString();
}
lJSP/SERVLET
25. Write out the built-in objects of JSP and explain their functions
request:request represents the HttpServletRequest object. It contains information about the browser request and provides several useful methods for obtaining cookie and header data. response:response represents the HttpServletResponse object and provides several methods for setting the response sent back to the browser (such as cookies, header information, etc.) out:out object is an instance of javax.jsp.JspWriter and provides several Methods that you can use to send output back to the browser. pageContext: pageContext represents a javax.servlet.jsp.PageContext object. It is an API used to facilitate access to various scopes of namespaces and servlet-related objects, and it wraps methods of common servlet-related functions. session:session represents a requested javax.servlet.http.HttpSession object. Session can store user status information application:applicaton represents a javax.servle.ServletContext object. This helps in finding information about the servlet engine and servlet environment config:config represents a javax.servlet.ServletConfig object. This object is used to access the initialization parameters of the servlet instance. page:page represents a servlet instance generated from this page.
exception: The exception object is an exception object. When an exception occurs during the running of a page, this object is generated. If a JSP page wants to use this object, it must set isErrorPage to true, otherwise it cannot be compiled. It is actually the counterpart of java.lang.Throwable