Java面试题目汇总/英文Java面试题(核心知识)

来源:互联网 发布:win7网络红叉不能上网 编辑:程序博客网 时间:2024/05/21 15:49

 一、面向对象的三个基本特征
   2、方法重载和方法重写的概念和区别
   3、接口和内部类、抽象类的特性
   4、文件读写的基本类
   **5、串行化的注意事项以及如何实现串行化
   6、线程的基本概念、线程的基本状态以及状态之间的关系
   7、线程的同步、如何实现线程的同步
   8、几种常用的数据结构及内部实现原理。
   9、Socket通信(TCP、UDP区别及Java实现方式)
  **10、Java的事件委托机制和垃圾回收机制
  11、JDBC调用数据库的基本步骤
  **12、解析XML文件的几种方式和区别
  13、Java四种基本权限的定义
  14、Java的国际化
二、JSP
   1、至少要能说出7个隐含对象以及他们的区别
  ** 2、forward 和redirect的区别
   3、JSP的常用指令
三、servlet
   1、什么情况下调用doGet()和doPost()?
   2、servlet的init()方法和service()方法的区别
   3、servlet的生命周期
   4、如何现实servlet的单线程模式
   5、servlet的配置
   6、四种会话跟踪技术
四、EJB
   **1、EJB容器提供的服务
 主要提供声明周期管理、代码产生、持续性管理、安全、事务管理、锁和并发行管理等服务。
   2、EJB的角色和三个对象
 EJB角色主要包括Bean开发者 应用组装者 部署者 系统管理员 EJB容器提供者 EJB服务器提供者
 三个对象是Remote(Local)接口、Home(LocalHome)接口,Bean类
   2、EJB的几种类型
 会话(Session)Bean ,实体(Entity)Bean 消息驱动的(Message Driven)Bean
 会话Bean又可分为有状态(Stateful)和无状态(Stateless)两种
 实体Bean可分为Bean管理的持续性(BMP)和容器管理的持续性(CMP)两种
   3、bean 实例的生命周期
 对于Stateless Session Bean、Entity Bean、Message Driven Bean一般存在缓冲池管理,而对于Entity Bean和Statefull Session Bean存在Cache管理,通常包含创建实例,设置上下文、创建EJB Object(create)、业务方法调用、remove等过程,对于存在缓冲池管理的Bean,在create之后实例并不从内存清除,而是采用缓冲池调度机制不断重用实例,而对于存在Cache管理的Bean则通过激活和去激活机制保持Bean的状态并限制内存中实例数量。
   4、激活机制
 以Statefull Session Bean 为例:其Cache大小决定了内存中可以同时存在的Bean实例的数量,根据MRU或NRU算法,实例在激活和去激活状态之间迁移,激活机制是当客户端调用某个EJB实例业务方法时,如果对应EJB Object发现自己没有绑定对应的Bean实例则从其去激活Bean存储中(通过序列化机制存储实例)回复(激活)此实例。状态变迁前会调用对应的ejbActive和ejbPassivate方法。
   5、remote接口和home接口主要作用
 remote接口定义了业务方法,用于EJB客户端调用业务方法
 home接口是EJB工厂用于创建和移除查找EJB实例
   6、客服端调用EJB对象的几个基本步骤
一、 设置JNDI服务工厂以及JNDI服务地址系统属性
二、 查找Home接口
三、 从Home接口调用Create方法创建Remote接口
四、 通过Remote接口调用其业务方法
五、数据库
   1、存储过程的编写
   2、基本的SQL语句
六、weblogic
1、 如何给weblogic指定大小的内存?
在启动Weblogic的脚本中(位于所在Domian对应服务器目录下的startServerName),增加set MEM_ARGS=-Xms32m -Xmx200m,可以调整最小内存为32M,最大200M
2、 如何设定的weblogic的热启动模式(开发模式)与产品发布模式?
可以在管理控制台中修改对应服务器的启动模式为开发或产品模式之一。或者修改服务的启动文件或者commenv文件,增加set PRODUCTION_MODE=true。
3、 如何启动时不需输入用户名与密码?
修改服务启动文件,增加 WLS_USER和WLS_PW项。也可以在boot.properties文件中增加加密过的用户名和密码.
4、 在weblogic管理制台中对一个应用域(或者说是一个网站,Domain)进行jms及ejb或连接池等相关信息进行配置后,实际保存在什么文件中?
保存在此Domain的config.xml文件中,它是服务器的核心配置文件。
5、 说说weblogic中一个Domain的缺省目录结构?比如要将一个简单的helloWorld.jsp放入何目录下,然的在浏览器上就可打入http://主机:端口号//helloword.jsp就可以看到运行结果了? 又比如这其中用到了一个自己写的javaBean该如何办?
Domain目录/服务器目录/applications,将应用目录放在此目录下将可以作为应用访问,如果是Web应用,应用目录需要满足Web应用目录要求,jsp文件可以直接放在应用目录中,Javabean需要放在应用目录的WEB-INF目录的classes目录中,设置服务器的缺省应用将可以实现在浏览器上无需输入应用名。
6、 如何查看在weblogic中已经发布的EJB?
可以使用管理控制台,在它的Deployment中可以查看所有已发布的EJB
7、 如何在weblogic中进行ssl配置与客户端的认证配置或说说j2ee(标准)进行ssl的配置
缺省安装中使用DemoIdentity.jks和DemoTrust.jks  KeyStore实现SSL,需要配置服务器使用Enable SSL,配置其端口,在产品模式下需要从CA获取私有密钥和数字证书,创建identity和trust keystore,装载获得的密钥和数字证书。可以配置此SSL连接是单向还是双向的。
   8、在weblogic中发布ejb需涉及到哪些配置文件
不同类型的EJB涉及的配置文件不同,都涉及到的配置文件包括ejb-jar.xml,weblogic-ejb-jar.xmlCMP实体Bean一般还需要weblogic-cmp-rdbms-jar.xml
   9、EJB需直接实现它的业务接口或Home接口吗,请简述理由.
远程接口和Home接口不需要直接实现,他们的实现代码是由服务器产生的,程序运行中对应实现类会作为对应接口类型的实例被使用。
  10、说说在weblogic中开发消息Bean时的persistent与non-persisten的差别
persistent方式的MDB可以保证消息传递的可靠性,也就是如果EJB容器出现问题而JMS服务器依然会将消息在此MDB可用的时候发送过来,而non-persistent方式的消息将被丢弃。
  11、说说你所熟悉或听说过的j2ee中的几种常用模式?及对设计模式的一些看法
   Session Facade Pattern:使用SessionBean访问EntityBean
Message Facade Pattern:实现异步调用
EJB Command Pattern:使用Command JavaBeans取代SessionBean,实现轻量级访问
Data Transfer Object Factory:通过DTO Factory简化EntityBean数据提供特性
Generic Attribute Access:通过AttibuteAccess接口简化EntityBean数据提供特性
Business Interface:通过远程(本地)接口和Bean类实现相同接口规范业务逻辑一致性
EJB架构的设计好坏将直接影响系统的性能、可扩展性、可维护性、组件可重用性及开发效率。项目越复杂,项目队伍越庞大则越能体现良好设计的重要性。


一般Singleton模式通常有几种种形式:

  第一种形式:定义一个类,它的构造函数为private的,它有一个static的private的该类变量,在类初始化时实例话,通过一个public的getInstance方法获取对它的引用,继而调用其中的方法。

public class Singleton {
  private Singleton(){}
  //在自己内部定义自己一个实例,是不是很奇怪?
  //注意这是private 只供内部调用
  private static Singleton instance = new Singleton();
  //这里提供了一个供外部访问本class的静态方法,可以直接访问  
  public static Singleton getInstance() {
    return instance;   
   }
}

  第二种形式:

public class Singleton {
  private static Singleton instance = null;
  public static synchronized Singleton getInstance() {
  //这个方法比上面有所改进,不用每次都进行生成对象,只是第一次     
  //使用时生成实例,提高了效率!
  if (instance==null)
    instance=new Singleton();
return instance;   }
}

其他形式:

定义一个类,它的构造函数为private的,所有方法为static的。

  一般认为第一种形式要更加安全些

  Hashtable和HashMap

  Hashtable继承自Dictionary类,而HashMap是Java1.2引进的Map interface的一个实现

  HashMap允许将null作为一个entry的key或者value,而Hashtable不允许

  还有就是,HashMap把Hashtable的contains方法去掉了,改成containsvalue和containsKey。因为contains方法容易让人引起误解。

  最大的不同是,Hashtable的方法是Synchronize的,而HashMap不是,在
多个线程访问Hashtable时,不需要自己为它的方法实现同步,而HashMap
就必须为之提供外同步。

  Hashtable和HashMap采用的hash/rehash算法都大概一样,所以性能不会有很大的差异。

121、内部类可以引用他包含类的成员吗?有没有什么限制?
一个内部类对象可以访问创建它的外部类对象的内容
122、WEB SERVICE名词解释。JSWDL开发包的介绍。JAXP、JAXM的解释。SOAP、UDDI,WSDL解释。
Web ServiceWeb Service是基于网络的、分布式的模块化组件,它执行特定的任务,遵守具体的技术规范,这些规范使得Web Service能与其他兼容的组件进行互操作。
JAXP(Java API for XML Parsing) 定义了在Java中使用DOM, SAX, XSLT的通用的接口。这样在你的程序中你只要使用这些通用的接口,当你需要改变具体的实现时候也不需要修改代码。
JAXM(Java API for XML Messaging) 是为SOAP通信提供访问方法和传输机制的API。
WSDL是一种 XML 格式,用于将网络服务描述为一组端点,这些端点对包含面向文档信息或面向过程信息的消息进行操作。这种格式首先对操作和消息进行抽象描述,然后将其绑定到具体的网络协议和消息格式上以定义端点。相关的具体端点即组合成为抽象端点(服务)。
SOAP即简单对象访问协议(Simple Object Access Protocol),它是用于交换XML编码信息的轻量级协议。
UDDI 的目的是为电子商务建立标准;UDDI是一套基于Web的、分布式的、为Web Service提供的、信息注册中心的实现标准规范,同时也包含一组使企业能将自身提供的Web Service注册,以使别的企业能够发现的访问协议的实现标准。


JAVA代码查错
1.
abstract class Name {
   private String name;
   public abstract boolean isStupidName(String name) {}
}
大侠们,这有何错误?
答案: 错。abstract method必须以分号结尾,且不带花括号。
2.
public class Something {
   void doSomething () {
       private String s = "";
       int l = s.length();
   }
}
有错吗?
答案: 错。局部变量前不能放置任何访问修饰符 (private,public,和protected)。final可以用来修饰局部变量
(final如同abstract和strictfp,都是非访问修饰符,strictfp只能修饰class和method而非variable)。
3.
abstract class Something {
   private abstract String doSomething ();
}
这好像没什么错吧?
答案: 错。abstract的methods不能以private修饰。abstract的methods就是让子类implement(实现)具体细节的,怎么可以用private把abstract
method封锁起来呢? (同理,abstract method前不能加final)。
4.
public class Something {
   public int addOne(final int x) {
       return ++x;
   }
}
这个比较明显。
答案: 错。int x被修饰成final,意味着x不能在addOne method中被修改。
5.
public class Something {
   public static void main(String[] args) {
       Other o = new Other();
       new Something().addOne(o);
   }
   public void addOne(final Other o) {
       o.i++;
   }
}
class Other {
   public int i;
}
和上面的很相似,都是关于final的问题,这有错吗?
答案: 正确。在addOne method中,参数o被修饰成final。如果在addOne method里我们修改了o的reference
(比如: o = new Other();),那么如同上例这题也是错的。但这里修改的是o的member vairable
(成员变量),而o的reference并没有改变。
6.
class Something {
    int i;
    public void doSomething() {
        System.out.println("i = " + i);
    }
}
有什么错呢? 看不出来啊。
答案: 正确。输出的是"i = 0"。int i属於instant variable (实例变量,或叫成员变量)。instant variable有default value。int的default value是0。
7.
class Something {
    final int i;
    public void doSomething() {
        System.out.println("i = " + i);
    }
}
和上面一题只有一个地方不同,就是多了一个final。这难道就错了吗?
答案: 错。final int i是个final的instant variable (实例变量,或叫成员变量)。final的instant variable没有default value,必须在constructor (构造器)结束之前被赋予一个明确的值。可以修改为"final int i = 0;"。
8.
public class Something {
     public static void main(String[] args) {
        Something s = new Something();
        System.out.println("s.doSomething() returns " + doSomething());
    }
    public String doSomething() {
        return "Do something ...";
    }
}
 看上去很完美。
答案: 错。看上去在main里call doSomething没有什么问题,毕竟两个methods都在同一个class里。但仔细看,main是static的。static method不能直接call non-static methods。可改成"System.out.println("s.doSomething() returns " + s.doSomething());"。同理,static method不能访问non-static instant variable。
9.
此处,Something类的文件名叫OtherThing.java
class Something {
    private static void main(String[] something_to_do) {       
        System.out.println("Do something ...");
    }
}
 这个好像很明显。
答案: 正确。从来没有人说过Java的Class名字必须和其文件名相同。但public class的名字必须和文件名相同。
10.
interface  A{
   int x = 0;
}
class B{
   int x =1;
}
class C extends B implements A {
   public void pX(){
      System.out.println(x);
   }
   public static void main(String[] args) {
      new C().pX();
   }
}
答案:错误。在编译时会发生错误(错误描述不同的JVM有不同的信息,意思就是未明确的x调用,两个x都匹配(就象在同时import java.util和java.sql两个包时直接声明Date一样)。对于父类的变量,可以用super.x来明确,而接口的属性默认隐含为 public static final.所以可以通过A.x来明确。
11.
interface Playable {
    void play();
}
interface Bounceable {
    void play();
}
interface Rollable extends Playable, Bounceable {
    Ball ball = new Ball("PingPang");
}
class Ball implements Rollable {
    private String name;
    public String getName() {
        return name;
    }
    public Ball(String name) {
        this.name = name;       
    }
   public void play() {
        ball = new Ball("Football");
        System.out.println(ball.getName());
    }
}
这个错误不容易发现。
答案: 错。"interface Rollable extends Playable, Bounceable"没有问题。interface可继承多个interfaces,所以这里没错。问题出在interface Rollable里的"Ball ball = new Ball("PingPang");"。任何在interface里声明的interface variable (接口变量,也可称成员变量),默认为public static final。也就是说"Ball ball = new Ball("PingPang");"实际上是"public static final Ball ball = new Ball("PingPang");"。在Ball类的Play()方法中,"ball = new Ball("Football");"改变了ball的reference,而这里的ball来自Rollable interface,Rollable interface里的ball是public static final的,final的object是不能被改变reference的。因此编译器将在"ball = new Ball("Football");"这里显示有错。


JAVA编程题
1.现在输入n个数字,以逗号,分开;然后可选择升或者降序排序;按提交键就在另一页面显示按什么排序,结果为,提供reset
import java.util.*;
public class bycomma{
 public static String[] splitStringByComma(String source){
   if(source==null||source.trim().equals(""))
    return null;
   StringTokenizer commaToker = new StringTokenizer(source,",");
   String[] result = new String[commaToker.countTokens()];
   int i=0;
   while(commaToker.hasMoreTokens()){
    result[i] = commaToker.nextToken();
    i++;
   }
   return result;
 }
 public static void main(String args[]){
 String[] s = splitStringByComma("5,8,7,4,3,9,1");
 int[] ii = new int[s.length];
 for(int i = 0;i<s.length;i++){
 ii[i] =Integer.parseInt(s[i]);
 }
    Arrays.sort(ii);
    //asc
    for(int i=0;i<s.length;i++){
    System.out.println(ii[i]);
    }
    //desc
    for(int i=(s.length-1);i>=0;i--){
    System.out.println(ii[i]);
    }
 }
}
2.金额转换,阿拉伯数字的金额转换成中国传统的形式如:(¥1011)->(一千零一拾一元整)输出。
package test.format;
import java.text.NumberFormat;
import java.util.HashMap;
public class SimpleMoneyFormat {
  public static final String EMPTY = "";
  public static final String ZERO = "零";
  public static final String ONE = "壹";
  public static final String TWO = "贰";
  public static final String THREE = "叁";
  public static final String FOUR = "肆";
  public static final String FIVE = "伍";
  public static final String SIX = "陆";
  public static final String SEVEN = "柒";
  public static final String EIGHT = "捌";
  public static final String NINE = "玖";
  public static final String TEN = "拾";
  public static final String HUNDRED = "佰";
  public static final String THOUSAND = "仟";
  public static final String TEN_THOUSAND = "万";
  public static final String HUNDRED_MILLION = "亿";
  public static final String YUAN = "元";
  public static final String JIAO = "角";
  public static final String FEN = "分";
  public static final String DOT = ".";

  private static SimpleMoneyFormat formatter = null;
  private HashMap chineseNumberMap = new HashMap();
  private HashMap chineseMoneyPattern = new HashMap();
  private NumberFormat numberFormat = NumberFormat.getInstance();

  private SimpleMoneyFormat() {
    numberFormat.setMaximumFractionDigits(4);
    numberFormat.setMinimumFractionDigits(2);
    numberFormat.setGroupingUsed(false);

    chineseNumberMap.put("0", ZERO);
    chineseNumberMap.put("1", ONE);
    chineseNumberMap.put("2", TWO);
    chineseNumberMap.put("3", THREE);
    chineseNumberMap.put("4", FOUR);
    chineseNumberMap.put("5", FIVE);
    chineseNumberMap.put("6", SIX);
    chineseNumberMap.put("7", SEVEN);
    chineseNumberMap.put("8", EIGHT);
    chineseNumberMap.put("9", NINE);
    chineseNumberMap.put(DOT, DOT);

    chineseMoneyPattern.put("1", TEN);
    chineseMoneyPattern.put("2", HUNDRED);
    chineseMoneyPattern.put("3", THOUSAND);
    chineseMoneyPattern.put("4", TEN_THOUSAND);
    chineseMoneyPattern.put("5", TEN);
    chineseMoneyPattern.put("6", HUNDRED);
    chineseMoneyPattern.put("7", THOUSAND);
    chineseMoneyPattern.put("8", HUNDRED_MILLION);
  }

  public static SimpleMoneyFormat getInstance() {
    if (formatter == null)
      formatter = new SimpleMoneyFormat();
    return formatter;
  }

  public String format(String moneyStr) {
    checkPrecision(moneyStr);
    String result;
    result = convertToChineseNumber(moneyStr);
    result = addUnitsToChineseMoneyString(result);
    return result;
  }

  public String format(double moneyDouble) {
    return format(numberFormat.format(moneyDouble));
  }

  public String format(int moneyInt) {
    return format(numberFormat.format(moneyInt));
  }

  public String format(long moneyLong) {
    return format(numberFormat.format(moneyLong));
  }

  public String format(Number moneyNum) {
    return format(numberFormat.format(moneyNum));
  }

  private String convertToChineseNumber(String moneyStr) {
    String result;
    StringBuffer cMoneyStringBuffer = new StringBuffer();
    for (int i = 0; i < moneyStr.length(); i++) {
      cMoneyStringBuffer.append(chineseNumberMap.get(moneyStr.substring(i, i + 1)));
    }
    //拾佰仟万亿等都是汉字里面才有的单位,加上它们
    int indexOfDot = cMoneyStringBuffer.indexOf(DOT);
    int moneyPatternCursor = 1;
    for (int i = indexOfDot - 1; i > 0; i--) {
      cMoneyStringBuffer.insert(i, chineseMoneyPattern.get(EMPTY + moneyPatternCursor));
      moneyPatternCursor = moneyPatternCursor == 8 ? 1 : moneyPatternCursor + 1;
    }

    String fractionPart = cMoneyStringBuffer.substring(cMoneyStringBuffer.indexOf("."));
    cMoneyStringBuffer.delete(cMoneyStringBuffer.indexOf("."), cMoneyStringBuffer.length());
    while (cMoneyStringBuffer.indexOf("零拾") != -1) {
      cMoneyStringBuffer.replace(cMoneyStringBuffer.indexOf("零拾"), cMoneyStringBuffer.indexOf("零拾") + 2, ZERO);
    }
    while (cMoneyStringBuffer.indexOf("零佰") != -1) {
      cMoneyStringBuffer.replace(cMoneyStringBuffer.indexOf("零佰"), cMoneyStringBuffer.indexOf("零佰") + 2, ZERO);
    }
    while (cMoneyStringBuffer.indexOf("零仟") != -1) {
      cMoneyStringBuffer.replace(cMoneyStringBuffer.indexOf("零仟"), cMoneyStringBuffer.indexOf("零仟") + 2, ZERO);
    }
    while (cMoneyStringBuffer.indexOf("零万") != -1) {
      cMoneyStringBuffer.replace(cMoneyStringBuffer.indexOf("零万"), cMoneyStringBuffer.indexOf("零万") + 2, TEN_THOUSAND);
    }
    while (cMoneyStringBuffer.indexOf("零亿") != -1) {
      cMoneyStringBuffer.replace(cMoneyStringBuffer.indexOf("零亿"), cMoneyStringBuffer.indexOf("零亿") + 2, HUNDRED_MILLION);
    }
    while (cMoneyStringBuffer.indexOf("零零") != -1) {
      cMoneyStringBuffer.replace(cMoneyStringBuffer.indexOf("零零"), cMoneyStringBuffer.indexOf("零零") + 2, ZERO);
    }
    if (cMoneyStringBuffer.lastIndexOf(ZERO) == cMoneyStringBuffer.length() - 1)
      cMoneyStringBuffer.delete(cMoneyStringBuffer.length() - 1, cMoneyStringBuffer.length());
    cMoneyStringBuffer.append(fractionPart);

    result = cMoneyStringBuffer.toString();
    return result;
  }


  private String addUnitsToChineseMoneyString(String moneyStr) {
    String result;
    StringBuffer cMoneyStringBuffer = new StringBuffer(moneyStr);
    int indexOfDot = cMoneyStringBuffer.indexOf(DOT);
    cMoneyStringBuffer.replace(indexOfDot, indexOfDot + 1, YUAN);
}

 


- 作者: tianhb 2005年03月13日, 星期日 02:06  回复(0) |  引用(0) 加入博采

JAVA相关基础知识(6)

101、java中会存在内存泄漏吗,请简单描述。
会。如:int i,i2;  return (i-i2);   //when i为足够大的正数,i2为足够大的负数。结果会造成溢位,导致错误。
102、java中实现多态的机制是什么?
方法的重写Overriding和重载Overloading是Java多态性的不同表现。重写Overriding是父类与子类之间多态性的一种表现,重载Overloading是一个类中多态性的一种表现。
103、垃圾回收器的基本原理是什么?垃圾回收器可以马上回收内存吗?有什么办法主动通知虚拟机进行垃圾回收?
对于GC来说,当程序员创建对象时,GC就开始监控这个对象的地址、大小以及使用情况。通常,GC采用有向图的方式记录和管理堆(heap)中的所有对象。通过这种方式确定哪些对象是"可达的",哪些对象是"不可达的"。当GC确定一些对象为"不可达"时,GC就有责任回收这些内存空间。可以。程序员可以手动执行System.gc(),通知GC运行,但是Java语言规范并不保证GC一定会执行。
104、静态变量和实例变量的区别?
static i = 10; //常量
   class A a;  a.i =10;//可变
105、什么是java序列化,如何实现java序列化?
序列化就是一种用来处理对象流的机制,所谓对象流也就是将对象的内容进行流化。可以对流化后的对象进行读写操作,也可将流化后的对象传输于网络之间。序列化是为了解决在对对象流进行读写操作时所引发的问题。
序列化的实现:将需要被序列化的类实现Serializable接口,该接口没有需要实现的方法,implements Serializable只是为了标注该对象是可被序列化的,然后使用一个输出流(如:FileOutputStream)来构造一个ObjectOutputStream(对象流)对象,接着,使用ObjectOutputStream对象的writeObject(Object obj)方法就可以将参数为obj的对象写出(即保存其状态),要恢复的话则用输入流。
106、是否可以从一个static方法内部发出对非static方法的调用?
不可以,如果其中包含对象的method();不能保证对象初始化.
107、写clone()方法时,通常都有一行代码,是什么?
Clone 有缺省行为,super.clone();他负责产生正确大小的空间,并逐位复制。
108、在JAVA中,如何跳出当前的多重嵌套循环?
用break; return 方法。
109、List、Map、Set三个接口,存取元素时,各有什么特点?
List 以特定次序来持有元素,可有重复元素。Set 无法拥有重复元素,内部排序。Map 保存key-value值,value可多值。
110、J2EE是什么?
J2EE是Sun公司提出的多层(multi-diered),分布式(distributed),基于组件(component-base)的企业级应用模型(enterpriese application model).在这样的一个应用系统中,可按照功能划分为不同的组件,这些组件又可在不同计算机上,并且处于相应的层次(tier)中。所属层次包括客户层(clietn tier)组件,web层和组件,Business层和组件,企业信息系统(EIS)层。
111、UML方面
标准建模语言UML。用例图,静态图(包括类图、对象图和包图),行为图,交互图(顺序图,合作图),实现图。
112、说出一些常用的类,包,接口,请各举10个
常用的类:BufferedReader  BufferedWriter  FileReader  FileWirter  String  Integer  ActionMapping

Thread,Throwable类,System类,StringBuffer可变字符串类

常用的包:java.lang  java.awt  java.io  java.util  java.sql,javax.swing.* javax.mail,javax.xml,org.w3c.dom

常用的接口:Remote  List  Map  Document  NodeList ,ServletRequest,ServletResponse
113、开发中都用到了那些设计模式?用在什么场合?
每个模式都描述了一个在我们的环境中不断出现的问题,然后描述了该问题的解决方案的核心。通过这种方式,你可以无数次地使用那些已有的解决方案,无需在重复相同的工作。主要用到了MVC的设计模式。用来开发JSP/Servlet或者J2EE的相关应用。简单工厂模式等。
114、jsp有哪些动作?作用分别是什么?
JSP共有以下6种基本动作 jsp:include:在页面被请求的时候引入一个文件。 jsp:useBean:寻找或者实例化一个JavaBean。 jsp:setProperty:设置JavaBean的属性。 jsp:getProperty:输出某个JavaBean的属性。 jsp:forward:把请求转到一个新的页面。 jsp:plugin:根据浏览器类型为Java插件生成OBJECT或EMBED标记。
115、Anonymous Inner Class (匿名内部类) 是否可以extends(继承)其它类,是否可以implements(实现)interface(接口)?
可以继承其他类或完成其他接口,在swing编程中常用此方式。
116、应用服务器与WEB SERVER的区别?
应用服务器:Weblogic、Tomcat、Jboss
WEB SERVER:IIS、 Apache
117、BS与CS的联系与区别。
C/S是Client/Server的缩写。服务器通常采用高性能的PC、工作站或小型机,并采用大型数据库系统,如Oracle、Sybase、Informix或 SQL Server。客户端需要安装专用的客户端软件。
B/S是Brower/Server的缩写,客户机上只要安装一个浏览器(Browser),如Netscape Navigator或Internet Explorer,服务器安装Oracle、Sybase、Informix或 SQL Server等数据库。在这种结构下,用户界面完全通过WWW浏览器实现,一部分事务逻辑在前端实现,但是主要事务逻辑在服务器端实现。浏览器通过Web Server 同数据库进行数据交互。
C/S 与 B/S 区别:
1.硬件环境不同:
  C/S 一般建立在专用的网络上, 小范围里的网络环境, 局域网之间再通过专门服务器提供连接和数据交换服务.
  B/S 建立在广域网之上的, 不必是专门的网络硬件环境,例与电话上网, 租用设备. 信息自己管理. 有比C/S更强的适应范围, 一般只要有操作系统和浏览器就行
2.对安全要求不同
  C/S 一般面向相对固定的用户群, 对信息安全的控制能力很强. 一般高度机密的信息系统采用C/S 结构适宜. 可以通过B/S发布部分可公开信息.
  B/S 建立在广域网之上, 对安全的控制能力相对弱, 可能面向不可知的用户。
3.对程序架构不同
  C/S 程序可以更加注重流程, 可以对权限多层次校验, 对系统运行速度可以较少考虑.
  B/S 对安全以及访问速度的多重的考虑, 建立在需要更加优化的基础之上. 比C/S有更高的要求 B/S结构的程序架构是发展的趋势, 从MS的.Net系列的BizTalk 2000 Exchange 2000等, 全面支持网络的构件搭建的系统. SUN 和IBM推的JavaBean 构件技术等,使 B/S更加成熟.
4.软件重用不同
  C/S 程序可以不可避免的整体性考虑, 构件的重用性不如在B/S要求下的构件的重用性好.
  B/S 对的多重结构,要求构件相对独立的功能. 能够相对较好的重用.就入买来的餐桌可以再利用,而不是做在墙上的石头桌子
5.系统维护不同 
  C/S 程序由于整体性, 必须整体考察, 处理出现的问题以及系统升级. 升级难. 可能是再做一个全新的系统
  B/S 构件组成,方面构件个别的更换,实现系统的无缝升级. 系统维护开销减到最小.用户从网上自己下载安装就可以实现升级.
6.处理问题不同
  C/S 程序可以处理用户面固定, 并且在相同区域, 安全要求高需求, 与操作系统相关. 应该都是相同的系统
  B/S 建立在广域网上, 面向不同的用户群, 分散地域, 这是C/S无法作到的. 与操作系统平台关系最小.
7.用户接口不同
  C/S 多是建立的Window平台上,表现方法有限,对程序员普遍要求较高
  B/S 建立在浏览器上, 有更加丰富和生动的表现方式与用户交流. 并且大部分难度减低,减低开发成本.
8.信息流不同
  C/S 程序一般是典型的中央集权的机械式处理, 交互性相对低
  B/S 信息流向可变化, B-B B-C B-G等信息、流向的变化, 更像交易中心。
118、LINUX下线程,GDI类的解释。
LINUX实现的就是基于核心轻量级进程的"一对一"线程模型,一个线程实体对应一个核心轻量级进程,而线程之间的管理在核外函数库中实现。
GDI类为图像设备编程接口类库。
119、STRUTS的应用(如STRUTS架构)
Struts是采用Java Servlet/JavaServer Pages技术,开发Web应用程序的开放源码的framework。 采用Struts能开发出基于MVC(Model-View-Controller)设计模式的应用构架。 Struts有如下的主要功能: 一.包含一个controller servlet,能将用户的请求发送到相应的Action对象。 二.JSP自由tag库,并且在controller servlet中提供关联支持,帮助开发员创建交互式表单应用。 三.提供了一系列实用对象:XML处理、通过Java reflection APIs自动处理JavaBeans属性、国际化的提示和消息。
120、Jdo是什么?
JDO是Java对象持久化的新的规范,为java data object的简称,也是一个用于存取某种数据仓库中的对象的标准化API。JDO提供了透明的对象存储,因此对开发人员来说,存储数据对象完全不需要额外的代码(如JDBC API的使用)。这些繁琐的例行工作已经转移到JDO产品提供商身上,使开发人员解脱出来,从而集中时间和精力在业务逻辑上。另外,JDO很灵活,因为它可以在任何数据底层上运行。JDBC只是面向关系数据库(RDBMS)JDO更通用,提供到任何数据底层的存储功能,比如关系数据库、文件、XML以及对象数据库(ODBMS)等等,使得应用可移植性更强。


- 作者: tianhb 2005年03月13日, 星期日 02:05  回复(0) |  引用(0) 加入博采

JAVA相关基础知识(5)

81、如何设定的weblogic的热启动模式(开发模式)与产品发布模式?
可以在管理控制台中修改对应服务器的启动模式为开发或产品模式之一。或者修改服务的启动文件或者commenv文件,增加set PRODUCTION_MODE=true。
82、如何启动时不需输入用户名与密码?
修改服务启动文件,增加 WLS_USER和WLS_PW项。也可以在boot.properties文件中增加加密过的用户名和密码.
83、在weblogic管理制台中对一个应用域(或者说是一个网站,Domain)进行jms及ejb或连接池等相关信息进行配置后,实际保存在什么文件中?
保存在此Domain的config.xml文件中,它是服务器的核心配置文件。
84、说说weblogic中一个Domain的缺省目录结构?比如要将一个简单的helloWorld.jsp放入何目录下,然的在浏览器上就可打入http://主机:端口号//helloword.jsp就可以看到运行结果了? 又比如这其中用到了一个自己写的javaBean该如何办?
Domain目录/服务器目录/applications,将应用目录放在此目录下将可以作为应用访问,如果是Web应用,应用目录需要满足Web应用目录要求,jsp文件可以直接放在应用目录中,Javabean需要放在应用目录的WEB-INF目录的classes目录中,设置服务器的缺省应用将可以实现在浏览器上无需输入应用名。
85、在weblogic中发布ejb需涉及到哪些配置文件
不同类型的EJB涉及的配置文件不同,都涉及到的配置文件包括ejb-jar.xml,weblogic-ejb-jar.xmlCMP实体Bean一般还需要weblogic-cmp-rdbms-jar.xml
86、如何在weblogic中进行ssl配置与客户端的认证配置或说说j2ee(标准)进行ssl的配置
缺省安装中使用DemoIdentity.jks和DemoTrust.jks  KeyStore实现SSL,需要配置服务器使用Enable SSL,配置其端口,在产品模式下需要从CA获取私有密钥和数字证书,创建identity和trust keystore,装载获得的密钥和数字证书。可以配置此SSL连接是单向还是双向的。
87、如何查看在weblogic中已经发布的EJB?
可以使用管理控制台,在它的Deployment中可以查看所有已发布的EJB
88、CORBA是什么?用途是什么?
CORBA 标准是公共对象请求代理结构(Common Object Request Broker Architecture),由对象管理组织 (Object Management Group,缩写为 OMG)标准化。它的组成是接口定义语言(IDL), 语言绑定(binding:也译为联编)和允许应用程序间互操作的协议。 其目的为:用不同的程序设计语言书写在不同的进程中运行,为不同的操作系统开发。
89、说说你所熟悉或听说过的j2ee中的几种常用模式?及对设计模式的一些看法
  Session Facade Pattern:使用SessionBean访问EntityBean
Message Facade Pattern:实现异步调用
EJB Command Pattern:使用Command JavaBeans取代SessionBean,实现轻量级访问
Data Transfer Object Factory:通过DTO Factory简化EntityBean数据提供特性
Generic Attribute Access:通过AttibuteAccess接口简化EntityBean数据提供特性
Business Interface:通过远程(本地)接口和Bean类实现相同接口规范业务逻辑一致性
EJB架构的设计好坏将直接影响系统的性能、可扩展性、可维护性、组件可重用性及开发效率。项目越复杂,项目队伍越庞大则越能体现良好设计的重要性。
90、说说在weblogic中开发消息Bean时的persistent与non-persisten的差别
persistent方式的MDB可以保证消息传递的可靠性,也就是如果EJB容器出现问题而JMS服务器依然会将消息在此MDB可用的时候发送过来,而non-persistent方式的消息将被丢弃。
91、Servlet执行时一般实现哪几个方法?
public void init(ServletConfig config)
public ServletConfig getServletConfig()
public String getServletInfo()
public void service(ServletRequest request,ServletResponse response)
public void destroy()
92、j2ee常用的设计模式?说明工厂模式。
    Java中的23种设计模式:
Factory(工厂模式),      Builder(建造模式),       Factory Method(工厂方法模式),
Prototype(原始模型模式),Singleton(单例模式),    Facade(门面模式),
Adapter(适配器模式),    Bridge(桥梁模式),        Composite(合成模式),
Decorator(装饰模式),    Flyweight(享元模式),     Proxy(代理模式),
Command(命令模式),      Interpreter(解释器模式), Visitor(访问者模式),
Iterator(迭代子模式),   Mediator(调停者模式),    Memento(备忘录模式),
Observer(观察者模式),   State(状态模式),         Strategy(策略模式),
Template Method(模板方法模式), Chain Of Responsibleity(责任链模式)
工厂模式:工厂模式是一种经常被使用到的模式,根据工厂模式实现的类可以根据提供的数据生成一组类中某一个类的实例,通常这一组类有一个公共的抽象父类并且实现了相同的方法,但是这些方法针对不同的数据进行了不同的操作。首先需要定义一个基类,该类的子类通过不同的方法实现了基类中的方法。然后需要定义一个工厂类,工厂类可以根据条件生成不同的子类实例。当得到子类的实例后,开发人员可以调用基类中的方法而不必考虑到底返回的是哪一个子类的实例。
93、EJB需直接实现它的业务接口或Home接口吗,请简述理由。
远程接口和Home接口不需要直接实现,他们的实现代码是由服务器产生的,程序运行中对应实现类会作为对应接口类型的实例被使用。
94、排序都有哪几种方法?请列举。用JAVA实现一个快速排序。
    排序的方法有:插入排序(直接插入排序、希尔排序),交换排序(冒泡排序、快速排序),选择排序(直接选择排序、堆排序),归并排序,分配排序(箱排序、基数排序)
快速排序的伪代码。
/ /使用快速排序方法对a[ 0 :n- 1 ]排序
从a[ 0 :n- 1 ]中选择一个元素作为m i d d l e,该元素为支点
把余下的元素分割为两段left 和r i g h t,使得l e f t中的元素都小于等于支点,而right 中的元素都大于等于支点
递归地使用快速排序方法对left 进行排序
递归地使用快速排序方法对right 进行排序
所得结果为l e f t + m i d d l e + r i g h t
95、请对以下在J2EE中常用的名词进行解释(或简单描述)
web容器:给处于其中的应用程序组件(JSP,SERVLET)提供一个环境,使JSP,SERVLET直接更容器中的环境变量接口交互,不必关注其它系统问题。主要有WEB服务器来实现。例如:TOMCAT,WEBLOGIC,WEBSPHERE等。该容器提供的接口严格遵守J2EE规范中的WEB APPLICATION 标准。我们把遵守以上标准的WEB服务器就叫做J2EE中的WEB容器。
EJB容器:Enterprise java bean 容器。更具有行业领域特色。他提供给运行在其中的组件EJB各种管理功能。只要满足J2EE规范的EJB放入该容器,马上就会被容器进行高效率的管理。并且可以通过现成的接口来获得系统级别的服务。例如邮件服务、事务管理。
JNDI:(Java Naming & Directory Interface)JAVA命名目录服务。主要提供的功能是:提供一个目录系统,让其它各地的应用程序在其上面留下自己的索引,从而满足快速查找和定位分布式应用程序的功能。
JMS:(Java Message Service)JAVA消息服务。主要实现各个应用程序之间的通讯。包括点对点和广播。
JTA:(Java Transaction API)JAVA事务服务。提供各种分布式事务服务。应用程序只需调用其提供的接口即可。
JAF:(Java Action FrameWork)JAVA安全认证框架。提供一些安全控制方面的框架。让开发者通过各种部署和自定义实现自己的个性安全控制策略。
RMI/IIOP:(Remote Method Invocation /internet对象请求中介协议)他们主要用于通过远程调用服务。例如,远程有一台计算机上运行一个程序,它提供股票分析服务,我们可以在本地计算机上实现对其直接调用。当然这是要通过一定的规范才能在异构的系统之间进行通信。RMI是JAVA特有的。
96、JAVA语言如何进行异常处理,关键字:throws,throw,try,catch,finally分别代表什么意义?在try块中可以抛出异常吗?
Java通过面向对象的方法进行异常处理,把各种不同的异常进行分类,并提供了良好的接口。在Java中,每个异常都是一个对象,它是Throwable类或其它子类的实例。当一个方法出现异常后便抛出一个异常对象,该对象中包含有异常信息,调用这个对象的方法可以捕获到这个异常并进行处理。Java的异常处理是通过5个关键词来实现的:try、catch、throw、throws和finally。一般情况下是用try来执行一段程序,如果出现异常,系统会抛出(throws)一个异常,这时候你可以通过它的类型来捕捉(catch)它,或最后(finally)由缺省处理器来处理。
用try来指定一块预防所有"异常"的程序。紧跟在try程序后面,应包含一个catch子句来指定你想要捕捉的"异常"的类型。
throw语句用来明确地抛出一个"异常"。
throws用来标明一个成员函数可能抛出的各种"异常"。
Finally为确保一段代码不管发生什么"异常"都被执行一段代码。
可以在一个成员函数调用的外面写一个try语句,在这个成员函数内部写另一个try语句保护其他代码。每当遇到一个try语句,"异常"的框架就放到堆栈上面,直到所有的try语句都完成。如果下一级的try语句没有对某种"异常"进行处理,堆栈就会展开,直到遇到有处理这种"异常"的try语句。
97、一个".java"源文件中是否可以包括多个类(不是内部类)?有什么限制?
可以。必须只有一个类名与文件名相同。
98、MVC的各个部分都有那些技术来实现?如何实现?
MVC是Model-View-Controller的简写。"Model" 代表的是应用的业务逻辑(通过JavaBean,EJB组件实现), "View" 是应用的表示面(由JSP页面产生),"Controller" 是提供应用的处理过程控制(一般是一个Servlet),通过这种设计模型把应用逻辑,处理过程和显示逻辑分成不同的组件实现。这些组件可以进行交互和重用。
99、java中有几种方法可以实现一个线程?用什么关键字修饰同步方法? stop()和suspend()方法为何不推荐使用?
有两种实现方法,分别是继承Thread类与实现Runnable接口
用synchronized关键字修饰同步方法
反对使用stop(),是因为它不安全。它会解除由线程获取的所有锁定,而且如果对象处于一种不连贯状态,那么其他线程能在那种状态下检查和修改它们。结果很难检查出真正的问题所在。suspend()方法容易发生死锁。调用suspend()的时候,目标线程会停下来,但却仍然持有在这之前获得的锁定。此时,其他任何线程都不能访问锁定的资源,除非被"挂起"的线程恢复运行。对任何线程来说,如果它们想恢复目标线程,同时又试图使用任何一个锁定的资源,就会造成死锁。所以不应该使用suspend(),而应在自己的Thread类中置入一个标志,指出线程应该活动还是挂起。若标志指出线程应该挂起,便用wait()命其进入等待状态。若标志指出线程应当恢复,则用一个notify()重新启动线程。
100、java中有几种类型的流?JDK为每种类型的流提供了一些抽象类以供继承,请说出他们分别是哪些类?
字节流,字符流。字节流继承于InputStream / OutputStream,字符流继承于InputStreamReader / OutputStreamWriter。在java.io包中还有许多其他的流,主要是为了提高性能和使用方便。


- 作者: tianhb 2005年03月13日, 星期日 02:04  回复(0) |  引用(0) 加入博采

JAVA相关基础知识(4)

61、servlet的生命周期
web容器加载servlet,生命周期开始。通过调用servlet的init()方法进行servlet的初始化。通过调用service()方法实现,根据请求的不同调用不同的do***()方法。结束服务,web容器调用servlet的destroy()方法。
62、如何现实servlet的单线程模式
<%@ page isThreadSafe="false"%>
63、页面间对象传递的方法
request,session,application,cookie等
64、JSP和Servlet有哪些相同点和不同点,他们之间的联系是什么?
JSP是Servlet技术的扩展,本质上是Servlet的简易方式,更强调应用的外表表达。JSP编译后是"类servlet"。Servlet和JSP最主要的不同点在于,Servlet的应用逻辑是在Java文件中,并且完全从表示层中的HTML里分离开来。而JSP的情况是Java和HTML可以组合成一个扩展名为.jsp的文件。JSP侧重于视图,Servlet主要用于控制逻辑。
65、四种会话跟踪技术
会话作用域ServletsJSP 页面描述
page否是代表与一个页面相关的对象和属性。一个页面由一个编译好的 Java servlet 类(可以带有任何的 include 指令,但是没有 include 动作)表示。这既包括 servlet 又包括被编译成 servlet 的 JSP 页面
request是是代表与 Web 客户机发出的一个请求相关的对象和属性。一个请求可能跨越多个页面,涉及多个 Web 组件(由于 forward 指令和 include 动作的关系)
session是是代表与用于某个 Web 客户机的一个用户体验相关的对象和属性。一个 Web 会话可以也经常会跨越多个客户机请求
application是是代表与整个 Web 应用程序相关的对象和属性。这实质上是跨越整个 Web 应用程序,包括多个页面、请求和会话的一个全局作用域
66、Request对象的主要方法:
setAttribute(String name,Object):设置名字为name的request的参数值
getAttribute(String name):返回由name指定的属性值
getAttributeNames():返回request对象所有属性的名字集合,结果是一个枚举的实例
getCookies():返回客户端的所有Cookie对象,结果是一个Cookie数组
getCharacterEncoding():返回请求中的字符编码方式
getContentLength():返回请求的Body的长度
getHeader(String name):获得HTTP协议定义的文件头信息
getHeaders(String name):返回指定名字的request Header的所有值,结果是一个枚举的实例
getHeaderNames():返回所以request Header的名字,结果是一个枚举的实例
getInputStream():返回请求的输入流,用于获得请求中的数据
getMethod():获得客户端向服务器端传送数据的方法
getParameter(String name):获得客户端传送给服务器端的有name指定的参数值
getParameterNames():获得客户端传送给服务器端的所有参数的名字,结果是一个枚举的实例
getParameterValues(String name):获得有name指定的参数的所有值
getProtocol():获取客户端向服务器端传送数据所依据的协议名称
getQueryString():获得查询字符串
getRequestURI():获取发出请求字符串的客户端地址
getRemoteAddr():获取客户端的IP地址
getRemoteHost():获取客户端的名字
getSession([Boolean create]):返回和请求相关Session
getServerName():获取服务器的名字
getServletPath():获取客户端所请求的脚本文件的路径
getServerPort():获取服务器的端口号
removeAttribute(String name):删除请求中的一个属性
67、J2EE是技术还是平台还是框架?
    J2EE本身是一个标准,一个为企业分布式应用的开发提供的标准平台。
    J2EE也是一个框架,包括JDBC、JNDI、RMI、JMS、EJB、JTA等技术。
68、我们在web应用开发过程中经常遇到输出某种编码的字符,如iso8859-1等,如何输出一个某种编码的字符串?
  Public String translate (String str) {
    String tempStr = "";
    try {
      tempStr = new String(str.getBytes("ISO-8859-1"), "GBK");
      tempStr = tempStr.trim();
    }
    catch (Exception e) {
      System.err.println(e.getMessage());
    }
    return tempStr;
  }
69、简述逻辑操作(&,|,^)与条件操作(&&,||)的区别。
区别主要答两点:a.条件操作只能操作布尔型的,而逻辑操作不仅可以操作布尔型,而且可以操作数值型
b.逻辑操作不会产生短路
70、XML文档定义有几种形式?它们之间有何本质区别?解析XML文档有哪几种方式?
a: 两种形式 dtd  schema,b: 本质区别:schema本身是xml的,可以被XML解析器解析(这也是从DTD上发展schema的根本目的),c:有DOM,SAX,STAX等
    DOM:处理大型文件时其性能下降的非常厉害。这个问题是由DOM的树结构所造成的,这种结构占用的内存较多,而且DOM必须在解析文件之前把整个文档装入内存,适合对XML的随机访问
SAX:不现于DOM,SAX是事件驱动型的XML解析方式。它顺序读取XML文件,不需要一次全部装载整个文件。当遇到像文件开头,文档结束,或者标签开头与标签结束时,它会触发一个事件,用户通过在其回调事件中写入处理代码来处理XML文件,适合对XML的顺序访问
    STAX:Streaming API for XML (StAX)
71、简述synchronized和java.util.concurrent.locks.Lock的异同 ?
主要相同点:Lock能完成synchronized所实现的所有功能
主要不同点:Lock有比synchronized更精确的线程语义和更好的性能。synchronized会自动释放锁,而Lock一定要求程序员手工释放,并且必须在finally从句中释放。
72、EJB的角色和三个对象
一个完整的基于EJB的分布式计算结构由六个角色组成,这六个角色可以由不同的开发商提供,每个角色所作的工作必须遵循Sun公司提供的EJB规范,以保证彼此之间的兼容性。这六个角色分别是EJB组件开发者(Enterprise Bean Provider) 、应用组合者(Application Assembler)、部署者(Deployer)、EJB 服务器提供者(EJB Server Provider)、EJB 容器提供者(EJB Container Provider)、系统管理员(System Administrator)
三个对象是Remote(Local)接口、Home(LocalHome)接口,Bean类
73、EJB容器提供的服务
主要提供声明周期管理、代码产生、持续性管理、安全、事务管理、锁和并发行管理等服务。
74、EJB规范规定EJB中禁止的操作有哪些?
    1.不能操作线程和线程API(线程API指非线程对象的方法如notify,wait等),2.不能操作awt,3.不能实现服务器功能,4.不能对静态属生存取,5.不能使用IO操作直接存取文件系统,6.不能加载本地库.,7.不能将this作为变量和返回,8.不能循环调用。
75、remote接口和home接口主要作用
remote接口定义了业务方法,用于EJB客户端调用业务方法。
home接口是EJB工厂用于创建和移除查找EJB实例
76、bean 实例的生命周期
对于Stateless Session Bean、Entity Bean、Message Driven Bean一般存在缓冲池管理,而对于Entity Bean和Statefull Session Bean存在Cache管理,通常包含创建实例,设置上下文、创建EJB Object(create)、业务方法调用、remove等过程,对于存在缓冲池管理的Bean,在create之后实例并不从内存清除,而是采用缓冲池调度机制不断重用实例,而对于存在Cache管理的Bean则通过激活和去激活机制保持Bean的状态并限制内存中实例数量。
77、EJB的激活机制
以Stateful Session Bean 为例:其Cache大小决定了内存中可以同时存在的Bean实例的数量,根据MRU或NRU算法,实例在激活和去激活状态之间迁移,激活机制是当客户端调用某个EJB实例业务方法时,如果对应EJB Object发现自己没有绑定对应的Bean实例则从其去激活Bean存储中(通过序列化机制存储实例)回复(激活)此实例。状态变迁前会调用对应的ejbActive和ejbPassivate方法。
78、EJB的几种类型
会话(Session)Bean ,实体(Entity)Bean 消息驱动的(Message Driven)Bean
会话Bean又可分为有状态(Stateful)和无状态(Stateless)两种
实体Bean可分为Bean管理的持续性(BMP)和容器管理的持续性(CMP)两种
79、客服端调用EJB对象的几个基本步骤
设置JNDI服务工厂以及JNDI服务地址系统属性,查找Home接口,从Home接口调用Create方法创建Remote接口,通过Remote接口调用其业务方法。
80、如何给weblogic指定大小的内存?
在启动Weblogic的脚本中(位于所在Domian对应服务器目录下的startServerName),增加set MEM_ARGS=-Xms32m -Xmx200m,可以调整最小内存为32M,最大200M

英文Java面试题(核心知识)
Question: What is transient variable?
Answer: Transient variable can't be serialize. For example if a variable is declared as transient in a Serializable class and the class is written to an ObjectStream, the value of the variable can't be written to the stream instead when the class is retrieved from the ObjectStream the value of the variable becomes null.

Question: Name the containers which uses Border Layout as their default layout?
Answer: Containers which uses Border Layout as their default are: window, Frame and Dialog classes.
    

Question: What do you understand by Synchronization?
Answer: Synchronization is a process of controlling the access of shared resources by the multiple threads in such a manner that only one thread can access one resource at a time. In non synchronized multithreaded application, it is possible for one thread to modify a shared object while another thread is in the process of using or updating the object's value. Synchronization prevents such type of data corruption.
E.g. Synchronizing a function:
public synchronized void Method1 () {
     // Appropriate method-related code. 
}
E.g. Synchronizing a block of code inside a function:
public myFunction (){
    synchronized (this) { 
            // Synchronized code here.
         }
}
  

Question: What is Collection API?
Answer: The Collection API is a set of classes and interfaces that support operation on collections of objects. These classes and interfaces are more flexible, more powerful, and more regular than the vectors, arrays, and hashtables if effectively replaces. 
Example of classes: HashSet, HashMap, ArrayList, LinkedList, TreeSet and TreeMap.
Example of interfaces: Collection, Set, List and Map.

Question: Is Iterator a Class or Interface? What is its use?
Answer: Iterator is an interface which is used to step through the elements of a Collection. 
   

Question: What is similarities/difference between an Abstract class and Interface?
Answer:  Differences are as follows:

  • Interfaces provide a form of multiple inheritance. A class can extend only one other class.
  • Interfaces are limited to public methods and constants with no implementation. Abstract classes can have a partial implementation, protected parts, static methods, etc.
  • A Class may implement several interfaces. But in case of abstract class, a class may extend only one abstract class.
  • Interfaces are slow as it requires extra indirection to to find corresponding method in in the actual class. Abstract classes are fast. 

Similarities:

  • Neither Abstract classes or Interface can be instantiated.
      

Question: How to define an Abstract class?
Answer: A class containing abstract method is called Abstract class. An Abstract class can't be instantiated. 
Example of Abstract class:
abstract class testAbstractClass { 
    protected String myString; 
    public String getMyString() { 
        return myString; 
        } 
    public abstract string anyAbstractFunction();
}
     

Question: How to define an Interface?
Answer: In Java Interface defines the methods but does not implement them. Interface can include constants. A class that implements the interfaces is bound to implement all the methods defined in Interface.
Emaple of Interface:

public interface sampleInterface {
    public void functionOne();

    public long CONSTANT_ONE = 1000;
}
   

Question: Explain the user defined Exceptions?
Answer: User defined Exceptions are the separate Exception classes defined by the user for specific purposed. An user defined can created by simply sub-classing it to the Exception class. This allows custom exceptions to be generated (using throw) and caught in the same way as normal exceptions.
Example:
class myCustomException extends Exception {
     // The class simply has to exist to be an exception
}
  

Question: Explain the new Features of JDBC 2.0 Core API?
Answer: The JDBC 2.0 API includes the complete JDBC API, which includes both core and Optional Package API, and provides inductrial-strength database computing capabilities.
New Features in JDBC 2.0 Core API:

  • Scrollable result sets- using new methods in the ResultSet interface allows programmatically move the to particular row or to a position relative to its current position
  • JDBC 2.0 Core API provides the Batch Updates functionality to the java applications.
  • Java applications can now use the ResultSet.updateXXX methods.
  • New data types - interfaces mapping the SQL3 data types
  • Custom  mapping of user-defined types (UTDs)
  • Miscellaneous features, including performance hints, the use of character streams, full precision for java.math.BigDecimal values, additional security, and support for time zones in date, time, and timestamp values. 

    

Question: Explain garbage collection?
Answer: Garbage collection is one of the most important feature of Java. Garbage collection is also called automatic memory management as JVM automatically removes the unused variables/objects (value is null) from the memory. User program cann't directly free the object from memory, instead it is the job of the garbage collector to automatically free the objects that are no longer referenced by a program. Every class inherits finalize() method from java.lang.Object, the finalize() method is called by garbage collector when it determines no more references to the object exists. In Java, it is good idea to explicitly assign null into a variable when no more in use. I Java on calling System.gc() and Runtime.gc(),  JVM tries to recycle the unused objects, but there is no guarantee when all the objects will garbage collected. 
   

Question: How you can force the garbage collection?
Answer: Garbage collection automatic process and can't be forced.  
 

Question: What is OOPS?
Answer: OOP is the common abbreviation for Object-Oriented Programming.  
 

Question: Describe the principles of OOPS.
Answer: There are three main principals of oops which are called Polymorphism, Inheritance and Encapsulation.  
 

Question: Explain the Encapsulation principle.
Answer: Encapsulation is a process of binding or wrapping the data and the codes that operates on the data into a single entity. This keeps the data safe from outside interface and misuse. One way to think about encapsulation is as a protective wrapper that prevents code and data from being arbitrarily accessed by other code defined outside the wrapper.  
 

Question: Explain the Inheritance principle.
Answer: Inheritance is the process by which one object acquires the properties of another object.  
 

Question: Explain the Polymorphism principle.
Answer: The meaning of Polymorphism is something like one name many forms. Polymorphism enables one entity to be used as as general category for different types of actions. The specific action is determined by the exact nature of the situation. The concept of polymorphism can be explained as "one interface, multiple methods".  
 

Question: Explain the different forms of Polymorphism.
Answer: From a practical programming viewpoint, polymorphism exists in three distinct forms in Java:

  • Method overloading
  • Method overriding through inheritance
  • Method overriding through the Java interface

 
 

Question: What are Access Specifiers available in Java?
Answer: Access specifiers are keywords that determines the type of access to the member of a class. These are:

  • Public
  • Protected
  • Private
  • Defaults

 
 

Question: Describe the wrapper classes in Java.
Answer: Wrapper class is wrapper around a primitive data type. An instance of a wrapper class contains, or wraps, a primitive value of the corresponding type.

Following table lists the primitive types and the corresponding wrapper classes:

Primitive Wrapper boolean   java.lang.Boolean byte   java.lang.Byte char   java.lang.Character double   java.lang.Double float   java.lang.Float int   java.lang.Integer long   java.lang.Long short   java.lang.Short void   java.lang.Void  
 

Question: Read the following program:

public class test {
public static void main(String [] args) {
    int x = 3;
    int y = 1;
   if (x = y)
     System.out.println("Not equal");
  else
    System.out.println("Equal");
 }
}

What is the result?
   A. The output is equal?br>    B. The output in not Equal?br>    C. An error at " if (x = y)" causes compilation to fall.
   D. The program executes but no output is show on console.
Answer: C

Question:
what is the class variables ?
Answer: When we create a number of objects of the same class, then each object will share a common copy of variables. That means that there is only one copy per class, no matter how many objects are created from it. Class variables or static variables are declared with the static keyword in a class, but mind it that it should be declared outside outside a class. These variables are stored in static memory. Class variables are mostly used for constants, variable that never change its initial value. Static variables are always called by the class name. This variable is created when the program starts i.e. it is created before the instance is created of class by using new operator and gets destroyed when the programs stops. The scope of the class variable is same a instance variable. The class variable can be defined anywhere at class level with the keyword static. It initial value is same as instance variable. When the class variable is defined as int then it's initial value is by default zero, when declared boolean its default value is false and null for object references. Class variables are associated with the class, rather than with any object. 

Question: What is the difference between the instanceof and getclass, these two are same or not ?
Answer: instanceof is a operator, not a function while getClass is a method of java.lang.Object class. Consider a condition where we use 
if(o.getClass().getName().equals("java.lang.Math")){ }
This method only checks if the classname we have passed is equal to java.lang.Math. The class java.lang.Math is loaded by the bootstrap ClassLoader. This class is an abstract class.This class loader is responsible for loading classes. Every Class object contains a reference to the ClassLoader that defines. getClass() method returns the runtime class of an object. It fetches the java instance of the given fully qualified type name. The code we have written is not necessary, because we should not compare getClass.getName(). The reason behind it is that if the two different class loaders load the same class but for the JVM, it will consider both classes as different classes so, we can't compare their names. It can only gives the implementing class but can't compare a interface, but instanceof operator can. 
The instanceof operator compares an object to a specified type. We can use it to test if an object is an instance of a class, an instance of a subclass, or an instance of a class that implements a particular interface. We should try to use instanceof operator in place of getClass() method. Remember instanceof opeator and getClass are not same. Try this example, it will help you to better understand the difference between the two. 
Interface one{
}

Class Two implements one {
}
Class Three implements one {
}

public class Test {
public static void main(String args[]) {
one test1 = new Two();
one test2 = new Three();
System.out.println(test1 instanceof one); //true
System.out.println(test2 instanceof one); //true
System.out.println(Test.getClass().equals(test2.getClass())); //false
}

Q: What is the difference between an Interface and an Abstract class?
A: An abstract class can have instance methods that implement a default behavior. An Interface can only declare constants and instance methods, but cannot implement default behavior and all methods are implicitly abstract. An interface has all public members and no implementation. An abstract class is a class which may have the usual flavors of class members (private, protected, etc.), but has some abstract methods.

Q: What is the purpose of garbage collection in Java, and when is it used?
A: The purpose of garbage collection is to identify and discard objects that are no longer needed by a program so that their resources can be reclaimed and reused. A Java object is subject to garbage collection when it becomes unreachable to the program in which it is used.

Q: Describe synchronization in respect to multithreading.
A: With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchonization, it is possible for one thread to modify a shared variable while another thread is in the process of using or updating same shared variable. This usually leads to significant errors.

Q: Explain different way of using thread?
A: The thread could be implemented by using runnable interface or by inheriting from the Thread class. The former is more advantageous, 'cause when you are going for multiple inheritance..the only interface can help.


Q: What are pass by reference and passby value?
A: Pass By Reference means the passing the address itself rather than passing the value. Passby Value means passing a copy of the value to be passed.


Q: What is HashMap and Map?
A: Map is Interface and Hashmap is class that implements that.


Q: Difference between HashMap and HashTable?
A: The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls. (HashMap allows null values as key and value whereas Hashtable doesnt allow). HashMap does not guarantee that the order of the map will remain constant over time. HashMap is unsynchronized and Hashtable is synchronized.


Q: Difference between Vector and ArrayList?
A: Vector is synchronized whereas arraylist is not.


Q: Difference between Swing and Awt?
A: AWT are heavy-weight componenets. Swings are light-weight components. Hence swing works faster than AWT.


Q: What is the difference between a constructor and a method?
A: A constructor is a member function of a class that is used to create objects of that class. It has the same name as the class itself, has no return type, and is invoked using the new operator.
A method is an ordinary member function of a class. It has its own name, a return type (which may be void), and is invoked using the dot operator.


Q: What is an Iterator?
A: Some of the collection classes provide traversal of their contents via a java.util.Iterator interface. This interface allows you to walk through a collection of objects, operating on each object in turn. Remember when using Iterators that they contain a snapshot of the collection at the time the Iterator was obtained; generally it is not advisable to modify the collection itself while traversing an Iterator.


Q: State the significance of public, private, protected, default modifiers both singly and in combination and state the effect of package relationships on declared items qualified by these modifiers.
A: public : Public class is visible in other packages, field is visible everywhere (class must be public too)
private : Private variables or methods may be used only by an instance of the same class that declares the variable or method, A private feature may only be accessed by the class that owns the feature.
protected : Is available to all classes in the same package and also available to all subclasses of the class that owns the protected feature.This access is provided even to subclasses that reside in a different package from the class that owns the protected feature.
default :What you get by default ie, without any access modifier (ie, public private or protected).It means that it is visible to all within a particular package.


Q: What is an abstract class?
A: Abstract class must be extended/subclassed (to be useful). It serves as a template. A class that is abstract may not be instantiated (ie, you may not call its constructor), abstract class may contain static data. Any class with an abstract method is automatically abstract itself, and must be declared as such.
A class may be declared abstract even if it has no abstract methods. This prevents it from being instantiated.


Q: What is static in java?
A: Static means one per class, not one for each object no matter how many instance of a class might exist. This means that you can use them without creating an instance of a class.Static methods are implicitly final, because overriding is done based on the type of the object, and static methods are attached to a class, not an object. A static method in a superclass can be shadowed by another static method in a subclass, as long as the original method was not declared final. However, you can't override a static method with a nonstatic method. In other words, you can't change a static method into an instance method in a subclass.


Q: What is final?
A: A final class can't be extended ie., final class may not be subclassed. A final method can't be overridden when its class is inherited. You can't change value of a final variable (is a constant).

Q: What if the main method is declared as private?

A: The program compiles properly but at runtime it will give "Main method not public." message.
[ Received from Sandesh Sadhale]

Q: What if the static modifier is removed from the signature of the main method?

A: Program compiles. But at runtime throws an error "NoSuchMethodError".
[ Received from Sandesh Sadhale]

Q: What if I write static public void instead of public static void?

A: Program compiles and runs properly.
[ Received from Sandesh Sadhale]

Q: What if I do not provide the String array as the argument to the method?

A: Program compiles but throws a runtime error "NoSuchMethodError".
[ Received from Sandesh Sadhale]

Q: What is the first argument of the String array in main method?

A: The String array is empty. It does not have any element. This is unlike C/C++ where the first element by default is the program name.
[ Received from Sandesh Sadhale]

Q: If I do not provide any arguments on the command line, then the String array of Main method will be empty or null?

A: It is empty. But not null.
[ Received from Sandesh Sadhale]

Q: How can one prove that the array is not null but empty using one line of code?

A: Print args.length. It will print 0. That means it is empty. But if it would have been null then it would have thrown a NullPointerException on attempting to print args.length.
[ Received from Sandesh Sadhale]

Q: What environment variables do I need to set on my machine in order to be able to run Java programs?

A: CLASSPATH and PATH are the two variables.
[ Received from Sandesh Sadhale]

Q: Can an application have multiple classes having main method?

A: Yes it is possible. While starting the application we mention the class name to be run. The JVM will look for the Main method only in the class whose name you have mentioned. Hence there is not conflict amongst the multiple classes having main method.
[ Received from Sandesh Sadhale]

Q: Can I have multiple main methods in the same class?

A: No the program fails to compile. The compiler says that the main method is already defined in the class.
[ Received from Sandesh Sadhale]

Q: Do I need to import java.lang package any time? Why ?

A: No. It is by default loaded internally by the JVM.
[ Received from Sandesh Sadhale]

Q: Can I import same package/class twice? Will the JVM load the package twice at runtime?

A: One can import the same package or same class multiple times. Neither compiler nor JVM complains abt it. And the JVM will internally load the class only once no matter how many times you import the same class.
[ Received from Sandesh Sadhale]

Q: What are Checked and UnChecked Exception?

A: A checked exception is some subclass of Exception (or Exception itself), excluding class RuntimeException and its subclasses.
Making an exception checked forces client programmers to deal with the possibility that the exception will be thrown. eg, IOException thrown by java.io.FileInputStream's read() method·
Unchecked exceptions are RuntimeException and any of its subclasses. Class Error and its subclasses also are unchecked. With an unchecked exception, however, the compiler doesn't force client programmers either to catch the
exception or declare it in a throws clause. In fact, client programmers may not even know that the exception could be thrown. eg, StringIndexOutOfBoundsException thrown by String's charAt() method· Checked exceptions must be caught at compile time. Runtime exceptions do not need to be. Errors often cannot be.


Q: What is Overriding?

A: When a class defines a method using the same name, return type, and arguments as a method in its superclass, the method in the class overrides the method in the superclass.
When the method is invoked for an object of the class, it is the new definition of the method that is called, and not the method definition from superclass. Methods may be overridden to be more public, not more private.


Q: What are different types of inner classes?

A: Nested top-level classes, Member classes, Local classes, Anonymous classes

Nested top-level classes- If you declare a class within a class and specify the static modifier, the compiler treats the class just like any other top-level class.
Any class outside the declaring class accesses the nested class with the declaring class name acting similarly to a package. eg, outer.inner. Top-level inner classes implicitly have access only to static variables.There can also be inner interfaces. All of these are of the nested top-level variety.

Member classes - Member inner classes are just like other member methods and member variables and access to the member class is restricted, just like methods and variables. This means a public member class acts similarly to a nested top-level class. The primary difference between member classes and nested top-level classes is that member classes have access to the specific instance of the enclosing class.

Local classes - Local classes are like local variables, specific to a block of code. Their visibility is only within the block of their declaration. In order for the class to be useful beyond the declaration block, it would need to implement a
more publicly available interface.Because local classes are not members, the modifiers public, protected, private, and static are not usable.

Anonymous classes - Anonymous inner classes extend local inner classes one level further. As anonymous classes have no name, you cannot provide a constructor.
Q: Are the imports checked for validity at compile time? e.g. will the code containing an import such as java.lang.ABCD compile?

A: Yes the imports are checked for the semantic validity at compile time. The code containing above line of import will not compile. It will throw an error saying,can not resolve symbol
symbol : class ABCD
location: package io
import java.io.ABCD;
[ Received from Sandesh Sadhale]

Q: Does importing a package imports the subpackages as well? e.g. Does importing com.MyTest.* also import com.MyTest.UnitTests.*?

A: No you will have to import the subpackages explicitly. Importing com.MyTest.* will import classes in the package MyTest only. It will not import any class in any of it's subpackage.
[ Received from Sandesh Sadhale]

Q: What is the difference between declaring a variable and defining a variable?

A: In declaration we just mention the type of the variable and it's name. We do not initialize it. But defining means declaration + initialization.
e.g String s; is just a declaration while String s = new String ("abcd"); Or String s = "abcd"; are both definitions.
[ Received from Sandesh Sadhale]

Q: What is the default value of an object reference declared as an instance variable?

A: null unless we define it explicitly.
[ Received from Sandesh Sadhale]

Q: Can a top level class be private or protected?

A: No. A top level class can not be private or protected. It can have either "public" or no modifier. If it does not have a modifier it is supposed to have a default access.If a top level class is declared as private the compiler will complain that the "modifier private is not allowed here". This means that a top level class can not be private. Same is the case with protected.
[ Received from Sandesh Sadhale]

Q: What type of parameter passing does Java support?

A: In Java the arguments are always passed by value .
[ Update from Eki and Jyothish Venu]

Q: Primitive data types are passed by reference or pass by value?

A: Primitive data types are passed by value.
[ Received from Sandesh Sadhale]

Q: Objects are passed by value or by reference?

A: Java only supports pass by value. With objects, the object reference itself is passed by value and so both the original reference and parameter copy both refer to the same object .
[ Update from Eki and Jyothish Venu]

Q: What is serialization?

A: Serialization is a mechanism by which you can save the state of an object by converting it to a byte stream.
[ Received from Sandesh Sadhale]

Q: How do I serialize an object to a file?

A: The class whose instances are to be serialized should implement an interface Serializable. Then you pass the instance to the ObjectOutputStream which is connected to a fileoutputstream. This will save the object to a file.
[ Received from Sandesh Sadhale]

Q: Which methods of Serializable interface should I implement?

A: The serializable interface is an empty interface, it does not contain any methods. So we do not implement any methods.
[ Received from Sandesh Sadhale]

Q: How can I customize the seralization process? i.e. how can one have a control over the serialization process?

A: Yes it is possible to have control over serialization process. The class should implement Externalizable interface. This interface contains two methods namely readExternal and writeExternal. You should implement these methods and write the logic for customizing the serialization process.
[ Received from Sandesh Sadhale]

Q: What is the common usage of serialization?

A: Whenever an object is to be sent over the network, objects need to be serialized. Moreover if the state of an object is to be saved, objects need to be serilazed.
[ Received from Sandesh Sadhale]

Q: What is Externalizable interface?

A: Externalizable is an interface which contains two methods readExternal and writeExternal. These methods give you a control over the serialization mechanism. Thus if your class implements this interface, you can customize the serialization process by implementing these methods.
[ Received from Sandesh Sadhale]

Q: When you serialize an object, what happens to the object references included in the object?

A: The serialization mechanism generates an object graph for serialization. Thus it determines whether the included object references are serializable or not. This is a recursive process. Thus when an object is serialized, all the included objects are also serialized alongwith the original obect.
[ Received from Sandesh Sadhale]

Q: What one should take care of while serializing the object?

A: One should make sure that all the included objects are also serializable. If any of the objects is not serializable then it throws a NotSerializableException.
[ Received from Sandesh Sadhale]

Q: What happens to the static fields of a class during serialization?

A: There are three exceptions in which serialization doesnot necessarily read and write to the stream. These are
1. Serialization ignores static fields, because they are not part of ay particular state state.
2. Base class fields are only hendled if the base class itself is serializable.
3. Transient fields.
Q: Does Java provide any construct to find out the size of an object?

A: No there is not sizeof operator in Java. So there is not direct way to determine the size of an object directly in Java.
[ Received from Sandesh Sadhale] TOP

Q: Give a simplest way to find out the time a method takes for execution without using any profiling tool?

A: Read the system time just before the method is invoked and immediately after method returns. Take the time difference, which will give you the time taken by a method for execution.
To put it in code...

long start = System.currentTimeMillis ();
method ();
long end = System.currentTimeMillis ();

System.out.println ("Time taken for execution is " + (end - start));

Remember that if the time taken for execution is too small, it might show that it is taking zero milliseconds for execution. Try it on a method which is big enough, in the sense the one which is doing considerable amout of processing.

[ Received from Sandesh Sadhale] TOP

Q: What are wrapper classes?

A: Java provides specialized classes corresponding to each of the primitive data types. These are called wrapper classes. They are e.g. Integer, Character, Double etc.
[ Received from Sandesh Sadhale] TOP

Q: Why do we need wrapper classes?

A: It is sometimes easier to deal with primitives as objects. Moreover most of the collection classes store objects and not primitive data types. And also the wrapper classes provide many utility methods also. Because of these resons we need wrapper classes. And since we create instances of these classes we can store them in any of the collection classes and pass them around as a collection. Also we can pass them around as method parameters where a method expects an object.
[ Received from Sandesh Sadhale] TOP

Q: What are checked exceptions?

A: Checked exception are those which the Java compiler forces you to catch. e.g. IOException are checked Exceptions.
[ Received from Sandesh Sadhale] TOP

Q: What are runtime exceptions?

A: Runtime exceptions are those exceptions that are thrown at runtime because of either wrong input data or because of wrong business logic etc. These are not checked by the compiler at compile time.
[ Received from Sandesh Sadhale] TOP

Q: What is the difference between error and an exception?

A: An error is an irrecoverable condition occurring at runtime. Such as OutOfMemory error. These JVM errors and you can not repair them at runtime. While exceptions are conditions that occur because of bad input etc. e.g. FileNotFoundException will be thrown if the specified file does not exist. Or a NullPointerException will take place if you try using a null reference. In most of the cases it is possible to recover from an exception (probably by giving user a feedback for entering proper values etc.).
[ Received from Sandesh Sadhale] TOP

Q: How to create custom exceptions?

A: Your class should extend class Exception, or some more specific type thereof.
[ Received from Sandesh Sadhale] TOP

Q: If I want an object of my class to be thrown as an exception object, what should I do?

A: The class should extend from Exception class. Or you can extend your class from some more precise exception type also.
[ Received from Sandesh Sadhale] TOP

Q: If my class already extends from some other class what should I do if I want an instance of my class to be thrown as an exception object?

A: One can not do anytihng in this scenarion. Because Java does not allow multiple inheritance and does not provide any exception interface as well.
[ Received from Sandesh Sadhale] TOP

Q: How does an exception permeate through the code?

A: An unhandled exception moves up the method stack in search of a matching When an exception is thrown from a code which is wrapped in a try block followed by one or more catch blocks, a search is made for matching catch block. If a matching type is found then that block will be invoked. If a matching type is not found then the exception moves up the method stack and reaches the caller method. Same procedure is repeated if the caller method is included in a try catch block. This process continues until a catch block handling the appropriate type of exception is found. If it does not find such a block then finally the program terminates.
[ Received from Sandesh Sadhale] TOP

Q: What are the different ways to handle exceptions?

A: There are two ways to handle exceptions,
1. By wrapping the desired code in a try block followed by a catch block to catch the exceptions. and
2. List the desired exceptions in the throws clause of the method and let the caller of the method hadle those exceptions.
[ Received from Sandesh Sadhale] TOP

Q: What is the basic difference between the 2 approaches to exception handling.
1> try catch block and
2> specifying the candidate exceptions in the throws clause?
When should you use which approach?

A: In the first approach as a programmer of the method, you urself are dealing with the exception. This is fine if you are in a best position to decide should be done in case of an exception. Whereas if it is not the responsibility of the method to deal with it's own exceptions, then do not use this approach. In this case use the second approach. In the second approach we are forcing the caller of the method to catch the exceptions, that the method is likely to throw. This is often the approach library creators use. They list the exception in the throws clause and we must catch them. You will find the same approach throughout the java libraries we use.
[ Received from Sandesh Sadhale] TOP

Q: Is it necessary that each try block must be followed by a catch block?

A: It is not necessary that each try block must be followed by a catch block. It should be followed by either a catch block OR a finally block. And whatever exceptions are likely to be thrown should be declared in the throws clause of the method.
[ Received from Sandesh Sadhale] TOP

Q: If I write return at the end of the try block, will the finally block still execute?

A: Yes even if you write return as the last statement in the try block and no exception occurs, the finally block will execute. The finally block will execute and then the control return.
[ Received from Sandesh Sadhale] TOP

Q: If I write System.exit (0); at the end of the try block, will the finally block still execute?

A: No in this case the finally block will not execute because when you say System.exit (0); the control immediately goes out of the program, and thus finally never executes.
[ Received from Sandesh Sadhale]
Q: How are Observer and Observable used?

A: Objects that subclass the Observable class maintain a list of observers. When an Observable object is updated it invokes the update() method of each of its observers to notify the observers that it has changed state. The Observer interface is implemented by objects that observe Observable objects.
[Received from Venkateswara Manam] TOP

Q: What is synchronization and why is it important?

A: With respect to multithreading, synchronization is the capability to control
the access of multiple threads to shared resources. Without synchronization, it is possible for one thread to modify a shared object while another thread is in the process of using or updating that object's value. This often leads to significant errors.
[ Received from Venkateswara Manam] TOP

Q: How does Java handle integer overflows and underflows?

A: It uses those low order bytes of the result that can fit into the size of the type allowed by the operation.
[ Received from Venkateswara Manam] TOP

Q: Does garbage collection guarantee that a program will not run out of memory?

A: Garbage collection does not guarantee that a program will not run out of memory. It is possible for programs to use up memory resources faster than they are garbage collected. It is also possible for programs to create objects that are not subject to garbage collection
.
[ Received from Venkateswara Manam] TOP

Q: What is the difference between preemptive scheduling and time slicing?

A: Under preemptive scheduling, the highest priority task executes until it enters the waiting or dead states or a higher priority task comes into existence. Under time slicing, a task executes for a predefined slice of time and then reenters the pool of ready tasks. The scheduler then determines which task should execute next, based on priority and other factors.
[ Received from Venkateswara Manam] TOP

Q: When a thread is created and started, what is its initial state?

A: A thread is in the ready state after it has been created and started.
[ Received from Venkateswara Manam] TOP

Q: What is the purpose of finalization?

A: The purpose of finalization is to give an unreachable object the opportunity to perform any cleanup processing before the object is garbage collected.
[ Received from Venkateswara Manam] TOP

Q: What is the Locale class?

A: The Locale class is used to tailor program output to the conventions of a particular geographic, political, or cultural region.
[ Received from Venkateswara Manam] TOP

Q: What is the difference between a while statement and a do statement?

A: A while statement checks at the beginning of a loop to see whether the next loop iteration should occur. A do statement checks at the end of a loop to see whether the next iteration of a loop should occur. The do statement will always execute the body of a loop at least once.
[ Received from Venkateswara Manam] TOP

Q: What is the difference between static and non-static variables?

A: A static variable is associated with the class as a whole rather than with specific instances of a class. Non-static variables take on unique values with each object instance.
[ Received from Venkateswara Manam] TOP

Q: How are this() and super() used with constructors?

A: This() is used to invoke a constructor of the same class. super() is used to invoke a superclass constructor.
[ Received from Venkateswara Manam] TOP

Q: What are synchronized methods and synchronized statements?

A: Synchronized methods are methods that are used to control access to an object. A thread only executes a synchronized method after it has acquired the lock for the method's object or class. Synchronized statements are similar to synchronized methods. A synchronized statement can only be executed after a thread has acquired the lock for the object or class referenced in the synchronized statement.
[ Received from Venkateswara Manam] TOP

Q: What is daemon thread and which method is used to create the daemon thread?

A: Daemon thread is a low priority thread which runs intermittently in the back ground doing the garbage collection operation for the java runtime system. setDaemon method is used to create a daemon thread.
[ Received from Shipra Kamra] TOP

Q: Can applets communicate with each other?

A: At this point in time applets may communicate with other applets running in the same virtual machine. If the applets are of the same class, they can communicate via shared static variables. If the applets are of different classes, then each will need a reference to the same class with static variables. In any case the basic idea is to pass the information back and forth through a static variable.

An applet can also get references to all other applets on the same page using the getApplets() method of java.applet.AppletContext. Once you get the reference to an applet, you can communicate with it by using its public members.

It is conceivable to have applets in different virtual machines that talk to a server somewhere on the Internet and store any data that needs to be serialized there. Then, when another applet needs this data, it could connect to this same server. Implementing this is non-trivial.
[ Received from Krishna Kumar ] TOP

Q: What are the steps in the JDBC connection?

A: While making a JDBC connection we go through the following steps :

Step 1 : Register the database driver by using :
Class.forName(/" driver classs for that specific database/" );

Step 2 : Now create a database connection using :

Connection con = DriverManager.getConnection(url,username,password);

Step 3: Now Create a query using :

Statement stmt = Connection.Statement(/"select * from TABLE NAME/");

Step 4 : Exceute the query :

stmt.exceuteUpdate();



[ Received from Shri Prakash Kunwar] TOP

Q: How does a try statement determine which catch clause should be used to handle an exception?

A: When an exception is thrown within the body of a try statement, the catch clauses of the try statement are examined in the order in which they appear. The first catch clause that is capable of handling the exceptionis executed. The remaining catch clauses are ignored.

原创粉丝点击