A little bit more...

Monday, April 30, 2007

Java基础复习

Introduction

基本上是按照网上流传甚广的一套Java的面试题目来的,一个一个问题回答。

谈谈final、finally、finalize的区别

其实除了名字类似,是不沾边的三个东西。

final

Final is a keyword that can be used for classes, methods and data ( field / arguments ). It means what it modifies can’t be changed anymore. For final classes, they can’t be extended or derived; for final methods, the method’s behavior can’t be changed by overridden; for final data, they can only be initialized once and not be assigned values any more. But remember there’re two reasons for preventing change: design or efficiency.

> final methods

There’re two reasons why you make a method final: 1) quite small final method can be inlined when they’re called which is more efficiently; 2) you don’t want a method to be explicitly overridden.

Private methods are considered to be implicitly final, because in whatever cases, you can’t access or override a private method.

> final data

A misconception ( maybe it’s only mine : ) is that declaring data to be final doesn’t necessarily mean that its value is known at compile-time. The value can be run-time determinable. And data can also be declared to be final without any initialization value. In this case the final datum is called blank final field which has to be initialized in constructor or static initializer, or somewhere before use.

> final classes

Defining classes as final simply prevents inheritance — nothing more. Since a class declared to be final can’t be inherited, all its methods are implicitly final and the complier can opt to bring efficiency for you as with other explicitly final methods.

finally

Finally is to do with Exception handling which can introduce a piece of code that you want to execute whether or not an exception is thrown within a try blok or catched in a catch block.

finalize

Finalize which is the name of a method of Object is to do with garbage collection, that is to do with memory release. Garbage collection in java is a two-pass process. In the first pass in which case the object is eligible for garbage-collected, garbage collector will call finalize(), and in the second pass in which case the running programm may reach the point of runing out memory, garbage collector may physically release memeory of eligible objects. So the storage of a finalized object isn’t necessarily get released.

Anonymous Inner Class (匿名内部类) 是否可以extends(继承)其它类,是否可以implements(实现)interface(接口)

The answer is yes for both cases.

Inner class constructors get passed a hidden parameter, a reference to the outer class object that created them. static nested classes don’t have this hidden parameter. This is analogous to the way instance methods have hidden this parameter, where static methods do not.

Inner classes are not permitted to have static methods or fields. That is not quite true. They are allowed static final compile time constants, which are treated as if there were literals. If inner classes need statics, they have to get the outer class to hold them, or you have to use static nested classes or you have to inherit the static fields. Oddly, inner classes are permitted to extend classes that do have static methods and fields.

Anonymous inner class can’t define constructors. An anonymous inner class implements an interface, say, ITest, by:

new ITest() { .. }

and extends a class, say, Test, by:

new Test( name) { .. }

where Test( String name ) is an non-default constructor of Test, and default constructor can’t be used here!

For which kind of classes an anonymous class can extend / implement, refer to nested classes : Java Glossary.

Static Nested Class 和 Inner Class的不同

Differs in creating instance of them, and linking with the outter class /instance.

&和&&的区别

& is bitwise AND ( 位与) operator, while && is logical AND (逻辑与) operator.

Shift operators

The left-shift operator( << ) produces the operand to the left of the operator shifted to the left by the number of bits specified after the operator( inserting zeroes at the lower-order bits ). The signed right-shift operator( >> ) produces the operand to the left of the operator shifted to the right by the number of bits specified after the operator( inserting zeroes / ones at the higher-order bits ). There’s an unsigned right-shift operator( >>> ) will produces results inserting zeroes at the higher-order bits regardless of the sign.

Shift operators can be combined with equl sign, such as, <<=, >>=, and >>>=.

Talk about collection framwork in Java 2

Main interfaces: Collection, List, Set, Map. There’re actually only three collections List, Set and Map, and only two or three implementations of each one. And Map is not derived from Collection. The reason putting it the collection framwork is because a Map can produce collections from its key set and value list. Refer to chaper 9 of Thinking in Java 2nd version and Sun’s Java library for full details.

All collection implementation requires type checking ( especially with generic feature in Java 5 ) or bounds checking, or both.

Vector is synchronized, which means it’s thread-safe.

ArrayList is much like an array except it is variant-sized which brings extra run-time overhead.

The List interface provides four methods for positional (indexed) access to list elements. Note that these operations may execute in time proportional to the index value for some implementations (the LinkedList class, for example). Thus, iterating over the elements in a list is typically preferable to indexing through it if the caller does not know the implementation.

For the Set interface, a speicial case of prohibition is that it is not permissible for a set to contain itself as an element.

Diff between Collection and Collections

First Collections is the name of a conceptual framework coined by the designers of Java to represent a collection of interfaces and / or classes that enables an object holding a group of objects and variaous operations on it. It is generally called the collections framework ( or container classes before Java 2 ).

Collection as a type name is the name of an interface which is the root of the collecitons framework hierarchy and is located at package java.util. While it is the root of the collection hierarchy, there’re some collection classes that aren’t rooted from it, such as Map.

While Collections is a class also located in the package java.util which consists of a variety of static methods that operate on or return collections. This is common technique used to organize a bunch of related PO paradigm interfaces* ( may be not types, but methods ) into one module supported by OOP paradigm to improve the modularity and/or accessability of such interfaces*. In some cases, this is called the facade design pattern. Similar classes examplifying this techinque are Arrays, Math, etc.

Diff between HashMap and HashTable

String, StringBuffer, and StringBuilder

String class represents character strings. All string literals ( e.g., “Kenyth” ) in Java program are implemented as instances of String class. Strings are constant, namely immutable, as opposed to mutable StringBuffers. Their values can’t be changed after they’re created, which makes they can be shared ( refer to a compiler theory book about handling of constants ). And any modification to a String will produce a new instance of String, explicitly or implicitly. Concatenation of String is implemented as operations on StringBuffer( see the class file bytecode ), and conversions from an object to String is facilitated by the toString() method defined in Object class.

StringBuffer class represents a sequence of characters. It is mutable. It allows for data being appended to and inserted into it. It is thread-safe.

StringBuilder is like StringBuffer, but is not intended to be used by multi threads, that is not synchronized, or not thread-safe. It is introduced as of Java 5.

When to use assert

( Actually I’ve never used this keyword in my programming ) For the full details refer to Sun’s official document Programming With Assertions.

Simply speaking, assert in Java provides you a debugging facility similar to macros in C/C++. You can enable/disable your assertions when starting your program by passing in JVM command-line arguments ea/da. However, by default assertions are disabled at run-time.

There’s one guideline for deciding where/when to use assert that you should never use it for what your programming code do, such as method contract enforcement. Because since it is just a helper tool for debugging / observing your program and can be disabled, you must not depend the functionalities of your program on it.

more are coming soon…

Resources

  1. Thinking in java version 2.
  2. JAVA面试题目(去了两家公司,都是这样的题目) :一个很好的问题导向的复习提纲。
  3. 初识Java内部类:关于内部类的好处,静态内部类以及非静态内部类。
  4. `final’ variables and inner classes: explains why access from anonymous inner class to non-final outter variables is not allowed.
  5. nested classes : Java Glossary: contains very detailed explanation of the terms nested / inner class and their usages.
  6. Programming With Assertions

Technorati : , ,
Del.icio.us : , ,

Friday, April 20, 2007

The Architecture of Eclipse

Introduction

If explaining every bit in detail, you must be missed in the details and can’t see the architecture from a global perspective, nor will you be benifited in your practise. So I’m trying to explain the architecture based on senarios such as what will happen when you startup elipse, what will happen when an action that you contribute is fired, etc. I hope in such a way it will do help in your practice with Eclipse.

And, it is worthy to point out this is not an overview on the architecture of Eclipse for which there are tons of articles written about.

Startup of Eclipse

What will happen when the file eclipse.exe is executed.

Startup of Eclilpse begins by running a system specific executable binary file called eclilpse.exe which is located under the root directory of the eclipse installation. This executable will then lauches the org.eclipse.core.launcher.Main, located in startup.jar. After that the entry point of Main, that is static main method of Main is invoked. Below we will illustrate the calling path of important methods to demonstrate the post startup process of Eclipse.

Main.run( args )

Main.basicRun( args )

Main.getBootPath( .. ) : locate boot plugin ( in “plugin” directory of your eclispe installation ), within which Main.getDevPath( .. ) is called, within which Main.addBaseJars( .. ) is called, within which Main.readFrameworkExtensions( .. ) is called; invokeFramework( .. ): invoke EclipseStarter

the class EclipseStarter ( indicated by STARTER field ) is loaded by a URLClassLoader defined as an inner class with Main; EclipseStarter.run( .. ) is invoked in a reflective way

EclipseStarter.startup( .. ) : starts the platform and sets it up to run a single application

OSGi.new( .. ) : an instance of OSGi service platform is created

OSGi.launch() : start the OSGi framework

Framework.launch()

SystemBundle.resume() : SystemBundle subclasses Bundle to provide a system Bundle so that the framework can be represented as bundle

StartLevelManager.launch( .. ) : StartLevelManager is the startLevel service implementation for the OSGi spec

StartLevelManager.doSetStartLevel( .. )

StartLevelManager.incFWSL( .. )

StartLevelManager.getInstalledBundles( .. ) : Build an array of all installed bundles to be launch; StartLevelManager.loadInstalledBundles( .. ) : Load all bundles; StartLevelManager.resumeBundles( .. )

Framework.systemBundle.context.start() : Framework. :SystemBundle. :BundleContextImpl.start(), start the system bundle, BundleContextImpl.start() calls bundle’s BundleActivator.start()

BundleHost.loadBundleActivator() : Load and instantiate bundle’s BundleActivator class

BundleContextImpl.startActivator( .. ) : calls the start method of a BundleActivator which you have to extend when you create a plug-in.

Eclispe can also be started from with a client ( which is not part of the current Eclipse platform ), say, written in java, by using the EclispeStarter class located in org.eclipse.core.runtime.adaptor.

Action delegate and proxy

What will happen when your contributed action is fired.

Adding an action in a programatic way is different from adding it via contribution to an action extension point. For the former case, you have to implement some special API to create an action directly, while for the latter case you will have to only implement IActionDelegate+ which enables the lazy loading of the action.

At startup the registry is read and a PluginAction( extends Action, implements *Selection*Listener, IPluginContribution ) is created for each action extension point. The instance of PluginAction is an action proxy which directly represent an action in run time but doesn’t do the job a real action does. When the action that the action proxy represents is fired, the real action( the action delegate ) is created by the action proxy. After that point the action proxy delegate everything that is requested to the real action, the action delegate. This mechanism makes it possible to load the action extension lazily which is called lazy loading.

Following depicts the flow of action proxy and delegate:

read from registry ( IExtensionRegistry ) -> a PluginAction created for each action extension point ( while the action is fired -> an action delegate created -> action is delegated )

Contribute an Extension

to be continued…

Extension Pattern

Adapter pattern is extensively used in Eclipse to contribute extensions ( different from extensions to extension point ) to type or instance. This mechanism is enabled mainly by implementing IAdaptable and IAdapterFactory. For the detailed explanation with examples, please refer to Chapter 31 of the book Contributing to Eclipse: Principles, Patterns, and Plugins (Paperback).

Resources

  1. The Architecture of Eclipse. This article refers to and linked to a lot of valuable resources.
  2. A First Look at Eclipse Plug-In Programming. Contains a very detailed comparsion between Sun’s awt and swing and Eclipse’s SWT and JFace and anatomy of the process of Eclispe startup.
  3. About the OSGi Service Platform - Technical Whitepaper Revision 4.0
  4. org.eclipse.osgi_3.2.2.R32X_v20070118.jar : org.eclipse.core.runtime.adaptor.EclipseStarter.class source code, org.eclipse.osgi.framework.internal.core.AbstractBundle.class source code, org.eclipse.osgi.framework.internal.core.BundleContextImpl.class source code, org.eclipse.osgi.framework.internal.core.BundleHost.class source code, org.eclipse.osgi.framework.internal.core.Framework.class source code, org.eclipse.osgi.framework.internal.core.OSGi.class source code, org.eclipse.osgi.framework.internal.core.StartLevelManager.class source code, org.eclipse.osgi.framework.internal.core.SystemBundle.class source code, org.osgi.framework.BundleActivator.class source code.
  5. org.eclipse.ui.workbench_3.2.2.M20070119-0800.jar source code.
  6. eclipse 3.2.2 startup.jar : org.eclilpse.core.launcher.Main.class source code.
  7. Contributing to Eclipse: Principles, Patterns, and Plugins (Paperback)
  8. Eclipse Help

to be continued…

Technorati : , , , , , ,
Del.icio.us : , , , , , ,

Thursday, April 19, 2007

Knowledge on font size

声明:全部摘抄自网络资源,准确性和完整性不能保证,请读者自己辨别。

Introduction

一种字体(font)是一组字形(glyph)的集合,每一个字形代表了特定字样(typeface)的字符集(character set)里面的一个字符。

A font is a set of glyphs (images) representing the characters from a particular character set in a particular typeface. In professional typography the term typeface is not interchangeable with the word font, which is defined as a given alphabet and its associated characters in a single size. For example, 8-point Caslon is one font, and 10-point Caslon is another. Historically, fonts came in specific sizes determining the size of characters, and in quantities of sorts or number of each letter provided. The design of characters in a font took into account all these factors.

Measurement of font size

Point (pt, 磅)

在排版印刷中1pt是最小的测量单位, 12pt是1pica,具体是多长视情况而定。传统的排版印刷中1pt可能在0.18到0.4mm之间,这依赖于对foot的定义,现代的桌面出版中 (Desktop Publishing Point)1pt是1/72inch,也就是约0.3527mm,所以6pica是1inch。

Pixel(像素)

Inch(英寸)

millimeter(毫米)

Commonly used font size

9pt = 12px = 小五号

1pt = 4/3px

MS WORD中最大能定义1638pt大小的字体!

下表是字号与磅以及毫米之间的对应关系,并附以字样,以供大家在排版或调整布局时使用。

HTML和CSS中用的font size属性

Syntax: font-size: | | |
Possible Values:

*
o xx-small | x-small | small | medium | large | x-large | xx-large
*
o larger | smaller
*
* (in relation to parent element)

Both relative and absolute length units are supported in CSS1. Relative units give a length relative to another length property, and are preferred since they will better adjust to different media. The following relative units are available:

  • em (ems, the height of the element’s font)
  • ex (x-height, the height of the letter “x”)
  • px (pixels, relative to the canvas resolution)

Absolute length units are highly dependent on the output medium, and so are less useful than relative units. The following absolute units are available:

  • in (inches; 1in=2.54cm)
  • cm (centimeters; 1cm=10mm)
  • mm (millimeters)
  • pt (points; 1pt=1/72in)
  • pc (picas; 1pc=12pt)

要注意的是,相同大小的字体在不同的具体环境下显示出来的字体的真实大小可能不一样,差别比较小的可能是用px度量的大小。

关于x-height的定义可以看Typeface中的解释,简要的说是,对每一个字体都有一个假想的水平线叫baseline(想想小时候练习写英文字母的时候每一行都有三条或者四条横线那种作业本),x-height就是从baseline到字体最高处的高度。

Resources

  1. Font Size
  2. Point (typography)
  3. Typeface
  4. CSS改变字体大小而不影响网页
  5. 【知识】字体中“号”“磅”及“毫米”的关系
  6. Length Units

Technorati : , ,
Del.icio.us : , ,
Ice Rocket : , ,
Flickr : , ,
Zooomr : , ,
Buzznet : , ,

About Me

My photo
I'm finishing my master degree in Software Engineering, Computer Science. I believe and have been following what Forrest Gump's Mam said: you have to do the best with what god gave you.