A little bit more...

Showing posts with label programming. Show all posts
Showing posts with label programming. Show all posts

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 : , ,

Monday, November 20, 2006

Basics of Javascript

Note:
My recent posts about basics or overview of something
mostly cite select matirials of sources listed in the Resources section of every
post. It only serves for personal study and learning. And if you like, you can
take any part or all of them as desired. It would be my pleasure.

Overview

Javascript is an html scripting language. In the official specification it is
called ECMAScript.

Built-in Features

Datatypes and Values

All numbers in JavaScript are represented as 64-bit floating-point values
(i.e., similar to double in java and C++).

Conversion between Strings and Numbers can be done in several ways in both
direction. Numbers are automatically converted to strings when needed, so are
strings converted to numbers.

Numbers to strings:

var n = 100;
var s = n + " bottles of beer.";

var n_as_string = n + "";

var string_value = String(number);

string_value = number.toString();

Strings to numbers:

var product = "21" * "2"; // get number 42

var number = string_value - 0;
(Note: adding zero to a string value
results in string concatenation)

var number = Number(string_value);

// And parseInt(), parseFloat.

In JavaScript, functions are values that can be manipulated
by JavaScript code. It means that functions can be stored in variables, arrays,
and objects, and it means that functions can be passed as arguments to other
functions.

Functions can be defined in three ways:

function square(x) { return x*x;}

var square = function(x) { return x*x; }
// function name here is
optional.

var square = new Function("x", "return x*x");
// awkward, less useful and
less efficient.

An object is a collection of named values. These named values are usually
referred to as properties of the object. Properties of objects are, in
many ways, just like JavaScript variables; they can contain any type of data,
including arrays, functions, and other objects. Objects in JavaScript can serve
as associative arrays (recall the same concept in Delphi/Pascal, if you
know that language); that is, they can associate arbitrary data values with
arbitrary strings.

image.width
image.height

image["width"]
image["height"]

Arrays may contain any type of JavaScript data, including references to other
arrays or to objects or functions. Also note that
JavaScript does not support multidimensional arrays,
except as arrays of arrays. Finally, because JavaScript is an untyped language,
the elements of an array do not all need to be
of the same type
, as they do in typed languages like Java.

A corresponding object class is defined for each of the three key
primitive datatypes
. That is, besides supporting the number, string,
and boolean datatypes, JavaScript also supports Number, String, and Boolean
classes. JavaScript can flexibly convert values from one type to another. When
you use a string in an object contexti.e., when you try to access a property or
method of the string, JavaScript internally creates a String wrapper
object for the string value
. Note that the String object created when
you use a string in an object context is a transient one.

Primitive types are manipulated by value, and reference types, as the
name suggests, are manipulated by reference
. Numbers and booleans are
easily manipulated at the low levels of the JavaScript interpreter. Objects, on
the other hand, are reference types. Arrays and functions, which are specialized
types of objects, are therefore also reference types.

Since strings (primitive type, not the wrapper) are immutable in JavaScript,
there is no way to tell whether strings are passed by value or by reference.

Variables

There's no fundamental difference in JavaScript between variables and
the properties of objects
.

When the JavaScript interpreter starts up, one of the first things it
does, before executing any JavaScript code, is create a global
object
. The properties of this object are the
global variables of JavaScript programs. When you declare a global JavaScript
variable, what you are actually doing is defining a property of the global
object.

The JavaScript interpreter initializes the global object with a number of
properties that refer to predefined values and functions. For example, the
Infinity, parseInt, and Math properties refer to the
number infinity, the predefined parseInt( ) function, and the
predefined Math object, respectively.

In top-level code (i.e., JavaScript code that is not part of a function), you
can use the JavaScript keyword this to refer to the global
object
.

In client-side JavaScript, the Window object
serves as the global object
for all JavaScript code contained in the
browser window it represents. This global Window object has a self-referential
window property that can be used instead of this to refer to
the global object. The Window object defines the core global properties, such as
parseInt and Math, and also global client-side properties,
such as navigator and screen.

For local variables, while the body of a function is executing, the function
arguments and local variables are stored as properties of another special
object. This object is known as the call object.

Each time the JavaScript interpreter begins to execute a function, it creates
a new execution context for that function. Thus,
JavaScript code that is not part of any function runs in an execution context
that uses the global object for variable definitions. A JavaScript
implementation may allow multiple "global" execution contexts
. The
obvious example is client-side JavaScript, in which each separate browser
window, or each frame within a window, defines a separate global execution
context.

Object Support

ECMAScript does not contain proper classes such as those in C++, Smalltalk,
or Java. An ECMAScript object is an unordered collection of properties each with
zero or more attributes.

It turns out that every JavaScript object includes an internal
reference to another object, known as its prototype
object. All
functions have a prototype property that is automatically created and
initialized when the function is defined. The initial value of the
prototype property is an object with a single property. This property
is named constructor and refers back to the constructor function with
which the prototype is associated.

Property inheritance occurs only when you read property values, not
when you write them
. If you set the property p in an
object o that inherits that property from its prototype, what
happens is that you create a new property p directly in
o. Now that o has its own property named
p, it no longer inherits the value of p from
its prototype.

Navigator Object

The JavaScript
navigator object
is the object representation of the client internet browser
or web navigator program that is being used. This object is the top level object
to all others.

DOM Object

Overview

The goal of the DOM group is to define a programmatic interface for XML and
HTML. It is platform- and language-neutral interface. The DOM is separated into
three parts: Core, HTML, and XML. The Core DOM provides a low-level set of
objects that can represent any structured document.

DOM is being designed at several levels:

  • "Level 1. This concentrates on the actual core, HTML, and XML document
    models. It contains functionality for document navigation and manipulation.

  • Level 2. Includes a style sheet object model, and defines functionality for
    manipulating the style information attached to a document. It also enables
    traversals on the document, defines an event model and provides support for XML
    namespaces.

  • Level 3. Will address document loading and saving, as well as content models
    (such as DTDs and schemas) with document validation support. In addition, it
    will also address document views and formatting, key events and event groups.
    First public working drafts are available.

  • Further Levels. These may specify some interface with the possibly
    underlying window system, including some ways to prompt the user. They may also
    contain a query language interface, and address multithreading and
    synchronization, security, and repository."

Resources

  1. ECMAScript
    Language Specification 3rd edition

  2. Ajax
    in Action

  3. The
    CTDP JavaScript Manual Version 0.6.0, December 31, 2000

  4. W3C Document Object Model
    (DOM)

  5. DOM
    objects and methods

  6. JavaScript - The Definitive Guide, 5th Edition


This is a rough draft and published temporarily.

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.