Wednesday, 22 December 2010
Getting java run time memory statistics
{
System.out.println("JVM Statistics -- Max : " + Runtime.getRuntime().maxMemory() + "; " +
"Free: " + Runtime.getRuntime().freeMemory() + "; " +
"Total: " + Runtime.getRuntime().totalMemory());
}
Wednesday, 27 October 2010
Generics and Subtyping
Let’s test our understanding of generics. Is the following code snippet legal?
List<String> ls = new ArrayList<String>(); //1List<Object> lo = ls; //2
Line 1 is certainly legal. The trickier part of the question is line 2. This boils down
to the question: is a List of String a List of Object. Most people’s instinct is to answer:
“sure!”.
Well, take a look at the next few lines:
lo.add(new Object()); // 3String s = ls.get(0); // 4: attempts to assign an Object to a String!
Here we’ve aliased ls and lo. Accessing ls, a list of String, through the alias lo, we
can insert arbitrary objects into it. As a result ls does not hold just Strings anymore,
and when we try and get something out of it, we get a rude surprise.
The Java compiler will prevent this from happening of course. Line 2 will cause a
compile time error.
In general, if Foo is a subtype (subclass or subinterface) of Bar, and G is some
generic type declaration, it is not the case that G<Foo> is a subtype of G<Bar>.
This is probably the hardest thing you need to learn about generics, because it goes
against our deeply held intuitions.
So we had list of String not subtype of list of Objects.
The problem with that intuition is that it assumes that collections don’t change.
Our instinct takes these things to be immutable.
For example, if the department of motor vehicles supplies a list of drivers to the census
bureau, this seems reasonable. We think that a List<Driver> is a List<Person>,
assuming that Driver is a subtype of Person. In fact, what is being passed is a copy
of the registry of drivers. Otherwise, the census bureau could add new people who are
not drivers into the list, corrupting the DMV’s records.
In order to cope with this sort of situation, it’s useful to consider more flexible
generic types. The rules we’ve seen so far are quite restrictive.
Generic classes in java vs templates in C++
java.util:
public interface List<E> {
void add(E x);
Iterator<E> iterator();
}
public interface Iterator<E> {
E next();
boolean hasNext();
}
This should all be familiar, except for the stuff in angle brackets. Those are the
declarations of the formal type parameters of the interfaces List and Iterator.
Type parameters can be used throughout the generic declaration, pretty much where
you would use ordinary types (though there are some important restrictions.
In the introduction, we saw invocations of the generic type declaration List, such
as List<Integer>. In the invocation (usually called a parameterized type), all occurrences of the formal type parameter (E in this case) are replaced by the actual type argument (in this case, Integer).
You might imagine that List<Integer> stands for a version of List where E has been uniformly replaced by Integer:
public interface IntegerList {
void add(Integer x);
Iterator<Integer> iterator();
}
This intuition can be helpful, but it’s also misleading.
It is helpful, because the parameterized type List<Integer> does indeed have methods that look just like this expansion.
It is misleading, because the declaration of a generic is never actually expanded in this way. There aren’t multiple copies of the code: not in source, not in binary, not on disk and not in memory. If you are a C++ programmer, you’ll understand that this is very different than a C++ template.
A generic type declaration is compiled once and for all, and turned into a single class file, just like an ordinary class or interface declaration. Type parameters are analogous to the ordinary parameters used in methods or constructors. Much like a method has formal value parameters that describe the kinds of values it operates on, a generic declaration has formal type parameters. When a method is invoked, actual arguments are substituted for the formal parameters, and the method body is evaluated.
When a generic declaration is invoked, the actual type arguments are substituted for the formal type parameters.
The Motivation for Generics : dealing with casting of objects
List myIntList = new LinkedList(); // line no. 1
myIntList.add(new Integer(0)); // line no. 2
Integer x = (Integer) myIntList.iterator().next(); //line no. 3
The cast on line 3 is slightly annoying. Typically, the programmer knows what kind of data has been placed into a particular list. However, the cast is essential. The compiler can only guarantee that an Object will be returned by the iterator.
To ensure the assignment to a variable of type Integer is type safe, the cast is required.
Of course, the cast not only introduces clutter, it also introduces the possibility of a run time error, since the programmer might be mistaken.
Removing the cast
What if programmers could actually express their intent, and mark a list as being restricted to contain a particular data type?
This is the core idea behind generics.
Here is a version of the program fragment given above using generics:
List<Integer> myIntList = new LinkedList<Integer>(); // 1’
//OR
List<Integer> myIntList = new LinkedList(); // 1’
myIntList.add(new Integer(0)); //2’
Integer x = myIntList.iterator().next(); // 3’
Now, you might think that all we’ve accomplished is to move the clutter around.
Instead of a cast to Integer on line 3, we have Integer as a type parameter on line 1’. However, there is a very big difference here. The compiler can now check the type correctness of the program at compile-time. When we say that myIntList is declared with type List<Integer>, this tells us something about the variable myIntList, which holds true wherever and whenever it is used, and the compiler will guarantee it. In contrast, the cast tells us something the programmer thinks is true at a single point in the code.
The net effect, especially in large programs, is improved readability and robustness.
A big big note on Generics
Generics provides a sort of a syntactic sugar that might spare you some casting operation. But behind the scenes, after compilation the byte code is same. See Type Erasure with Generics to see how.
Enum and their super-class
java.lang.Enum
. Since java doesn't allow multiple inheritance, enum types can't have superclass. They can't even extend from java.lang.Enum
, nor java.lang.Object
. It also means enum A can't inherit or extend enum B.For example, the following is an invalid enum declaration:
public enum MyType extends Object {
ONE, TWO
}
Compiler error:MyType.java:3: '{' expected
public enum MyType extends Object {
MyType.java:6: expected
2 errors
The correct form should be:public enum MyType {
ONE, TWO
}
Enum that implements interfaces
java.io.Serializable
, and java.lang.Comparable
.public enum Color implements Runnable {A sample test program to invoke this run() method:
WHITE, BLACK, RED, YELLOW, BLUE;
public void run() {
System.out.println("name()=" + name() +
", toString()=" + toString());
}
}
for(Color c : Color.values()) {Or,
c.run();
}
for(Runnable r : Color.values()) {
r.run();
}
Enum with additional fields and custom constructor
public enum Color { //Color is of type enum
WHITE(21), BLACK(22), RED(23), YELLOW(24), BLUE(25);
private int code;
private Color(int c) {
code = c;
}
public int getCode() {
return code;
}
Switch statement on enums
public enum Shape { RECTANGLE, CIRCLE, LINE }
The
switch
statement was enhanced to allow a convenient use of enums. Note that the case values don't have to be qualified with the enum class name, which can be determined from the switch
control value. switch (drawing) {
case RECTANGLE: g.drawRect(x, y, width, height);
break;
case CIRCLE : g.drawOval(x, y, width, height);
break;
case LINE : g.drawLine(x, y, x + width, y + height);
break;
}
Tuesday, 26 October 2010
Bitwise Operators Summary
(a & b)
- Result is 1 in every bit position where both operands have a 1. (a | b)
- Result is 1 only in positions where one or both operands have a 1. (a ^ b)
- Result is 1 in positions where the two corresponding bits are different. (~a)
- Unary operator. Result is each bit of operand inverted. (a << n)
- Shifts bits n positions left. Zeros added on right. (a >> n)
- Shifts bits n positions right. High-order bit inserted on left. (a >>> n)
- Shifts bits n positions right. Zeros inserted at left.Operator Precedence
Precedence determines order of evaluation
Mathematical tradition, which programming languages generally try to match, dictates that some operations are done before others (for example, multiplication and division are done before addition and subtraction).
a+b*c
is the same as a+(b*c)
, not (a+b)*c
.
Ever operator has a precedence (a number) associated with it. The precedence determines which operations will be performed first. Multiplication has higher precedence than addition, as illustrated in the previous example..
Equal precedence operations generally performed left-to-right
In addition to the precedence of each operator, the compiler also knows whether equal-precedence operators should be performed left-to-right (almost all) or right-to-left (basically only assignment).
Parentheses can be used to control the order of evaluation
If you have any doubt about the order of evaluation, or have a potentially confusing expression, use parentheses. Remember that one of your goals should be to make your programs as readable as possible. Use parentheses when it makes an expression easier to read, not must when they are absolutely required. Few programmers know the precedence of all operators, so it's common for extra parentheses to be used.
Unary (one operand) versus binary (two operand) operators
Unary operators have only one operand, for example, in
a = -b;
The "-" operator is the unary (one operand) operator which changes the sign of its operand.
a = b - c
The "-" operator is a binary (two operand) operator which subtracts c from b.
Most unary operators are performed before binary operators (exceptions "." (qualification), "[]" (subscription), and "()" (method call).
Example - Parentheses
When you can work out the precedence, it's often useful to use parentheses to figure out the order of evaluation. For example, let's say you're evaluating the following expression.
1 + 2 - 3 * 4 / 5
Addition and subtraction are equal in precedence and lower than multiplication and division, which are equal. Form the parenthesized form and work out the values in steps.
1 + 2 - 3 * 4 / 5
= (1 + 2) - ((3 * 4) / 5)
= 3 - (12/5)
= 3 - 2
The result of the integer division, 12/5, is 2 .= 1
Precedence table
This table gives the precedence of all operators. You may not be familiar with all operators, but take the advice on the right side and only learn a few precedences.
Operator Precedence
. [] (args) post ++ --
! ~ unary + - pre ++ --
(type) new
* / %
+ -
<< >> >>>
< <= > >= instanceof
== !=
&
^
|
&&
||
?:
= += -= etc
Remember only
- unary operators
- * / %
- + -
- comparisons
- && ||
- = assignments
Alternative notation - Dataflow diagram
Let's look at the expression x = a+b-c*d/e
, which can be parenthesized as x = ((a+b) - ((c*d)/e))
. Instead of parentheses, we can draw a diagram.
This dataflow diagram shows another way to think about expression evaluation.
Boxes represent values in memory, ovals represent operations, and arrows show the direction of data flow. The assignment operator ("=") is treated as an operator with low precedence by the compiler, but from a dataflow point of view it only moves data so it's represented as an arrow, not an operation.
Dataflow diagrams show which operations must necessarily be performed before others, but doesn't show which are actually performed first. Java performs most operations left-to-right, so the addition would, in principle, be performed before the multiplication. I believe reordering of operations that can have no side effects is allowed, however.
Alternative notation - Postfix - RPN
Postfix. Altho it's not directly relevant to learning Java, there are other systems for writing expressions that don't need parentheses or precedence. Normal mathematical notation is called infix notation because the operators occur in between the operands. A common alternative is called postfix notation where the operator is written after its two operands.
Example. For example, a+b
would be written as ab+
, and x = a+b-c*d/e
would be written as xab+cd*e/-=
.
RPN. This is often called Reverse Polish Notation in honor of the Polish mathematician Jan Lukasiewicz.
Postfix notation is used in the following, among others.
- Hewlett-Packard makes RPN calculators.
- The Postscript printer control language is postfix.
- The Forth programming language is RPN.
- Java source code is translated into postfix notation!
Saturday, 23 October 2010
Design Hints for Inheritance
- Place common operations and fields in the superclass.This is why we put the name field into the Person class rather than replicating it in the Employee and Student classes.
- Some programmers think it is a good idea to define most instance fields as protected, "just in case," so that subclasses can access these fields if they need to. However, the protected mechanism doesn't give much protection, for two reasons. First, the set of subclasses is unbounded—anyone can form a subclass of your classes and then write code that directly accesses protected instance fields, thereby breaking encapsulation. And second, in the Java programming language, all classes in the same package have access to protected fields, whether or not they are subclasses.However, protected methods can be useful to indicate methods that are not ready for general use and should be redefined in subclasses. The clone method is a good example.
- Use inheritance to model the "is–a" relationship.Inheritance is a handy code-saver, and sometimes people overuse it. For example, suppose we need a Contractor class. Contractors have names and hire dates, but they do not have salaries. Instead, they are paid by the hour, and they do not stay around long enough to get a raise. There is the temptation to form a subclass Contractor from Employee and add an hourlyWage field.
class Contractor extends Employee
{ . . .
private double hourlyWage;
}This is not a good idea, however, because now each contractor object has both a salary and hourly wage field. It will cause you no end of grief when you implement methods for printing paychecks or tax forms. You will end up writing more code than you would have by not inheriting in the first place.The contractor/employee relationship fails the "is–a" test. A contractor is not a special case of an employee. - Don't use inheritance unless all inherited methods make sense.Suppose we want to write a Holiday class. Surely every holiday is a day, and days can be expressed as instances of the GregorianCalendar class, so we can use inheritance.
class Holiday extends GregorianCalendar { . . . }
Unfortunately, the set of holidays is not closed under the inherited operations. One of the public methods of GregorianCalendar is add. And add can turn holidays into nonholidays:Holiday christmas;
christmas.add(Calendar.DAY_OF_MONTH, 12);Therefore, inheritance is not appropriate in this example. - Don't change the expected behavior when you override a method.The substitution principle applies not just to syntax but, more important, to behavior. When you override a method, you should not unreasonably change its behavior. The compiler can't help you—it cannot check whether your redefinitions make sense. For example, you can "fix" the issue of the add method in the Holiday class by redefining add, perhaps to do nothing, or to throw an exception, or to move on to the next holiday.However, such a fix violates the substitution principle. The sequence of statements
int d1 = x.get(Calendar.DAY_OF_MONTH);
x.add(Calendar.DAY_OF_MONTH, 1);
int d2 = x.get(Calendar.DAY_OF_MONTH);
System.out.println(d2 - d1);should have the expected behavior, no matter whether x is of type GregorianCalendar or Holiday.Of course, therein lies the rub. Reasonable and unreasonable people can argue at length what the expected behavior is. For example, some authors argue that the substitution principle requires Manager.equals to ignore the bonus field because Employee.equals ignores it. These discussions are always pointless if they occur in a vacuum. Ultimately, what matters is that you do not circumvent the intent of the original design when you override methods in subclasses. - Use polymorphism, not type information.
if (x is of type 1)
action1(x);
else if (x is of type 2)
action2(x);think polymorphism.Do action1 and action2 represent a common concept? If so, make the concept a method of a common superclass or interface of both types. Then, you can simply callx.action();
and have the dynamic dispatch mechanism inherent in polymorphism launch the correct action.Code using polymorphic methods or interface implementations is much easier to maintain and extend than code that uses multiple type tests. - Don't overuse reflection.The reflection mechanism lets you write programs with amazing generality, by detecting fields and methods at run time. This capability can be extremely useful for systems programming, but it is usually not appropriate in applications. Reflection is fragile—the compiler cannot help you find programming errors. Any errors are found at run time and result in exceptions.
Thursday, 21 October 2010
Setting Program Attributes in java
System attributes are maintained by the
System
class and are covered later in System Properties. Java programs can set their own set of program attributes through three mechanisms: properties, command-line arguments, and applet parameters. Setting Up and Using Properties
A property defines attributes on a persistent basis. That is, you use properties when attribute values need to persist between invocations of a program. This section shows you how to do this in your programs.
Command-Line Arguments
A command-line argument defines attributes for Java applications on a nonpersistent basis. You use command-line arguments to set one or more attributes for a single invocation of an application. This section shows how to accept and process command-line arguments in a Java program.
Applet Parameters
An applet parameter is similar to a command-line argument, except that it is used with applets, not applications. Use applet parameters to set one or more attributes for a single invocation of an applet.Using Properties to Manage Program Attributes
os.name
" is the name for one of the Java platform's system attributes; its value contains the name of the current operating system, such as "Solaris
". The
Properties
class in the java.util
package manages a set of key/value pairs. A key/value pair is like a dictionary entry: The key is the word, and the value is the definition. This is a perfect match for managing the names and values of attributes. Each Properties
key contains the name of a system attribute, and its corresponding Properties
value is the current value of that attribute. The
System
class uses a Properties
object for managing system properties. Any Java program can use a Properties
object to manage its program attributes. The Properties
class itself provides methods for the following: - Loading key/value pairs into a
Properties
object from a stream - Retrieving a value from its key
- Listing the keys and their values
- Enumerating over the keys
- Saving the properties to a stream
Properties
extends the HashtableProperties
class and inherits methods from it for doing the following: - Testing to see if a particular key or value is in the
Properties
object - Getting the current number of key/value pairs
- Removing a key and its value
- Adding a key/value pair to the
Properties
list - Enumerating over the values or the keys
- Retrieving a value by its key
- Finding out if the
Properties
object is empty
The Life Cycle of a Program's Properties
There are 3 phases in program's properties life cycle :- Starting up - where properties are loaded
- Running - where properties are get and set
- Exiting - saving the properties
Starting Up
The actions given in the first three boxes occur when the program is starting up. First, the program loads the default properties from a well-known location into a
Properties
object. Normally, the default properties are stored in a file on disk along with the .class
and other resource files for the program. Next, the program creates another Properties
object and loads the properties that were saved from the last time the program was run. Many applications store properties on a per-user basis, so the properties loaded in this step are usually in a specific file in a particular directory maintained by this application in the user's home directory. Finally, the program uses the default and remembered properties to initialize itself. The key here is consistency. The application must always load and save properties to the same location so that it can find them the next time it's executed.Running
During the execution of the program, the user may change some settings, perhaps in a Preferences window, and the
Properties
object is updated to reflect these changes. For them to have a permanent effect, they must be saved.Exiting
Upon exiting, the program saves the properties to its well-known location, to be loaded again when the program is next started up.
Setting Up Your Properties
Object
The following Java code performs the first two steps described in the previous section: loading the default properties and loading the remembered properties:First, the application sets up a default. . .
// create and load default properties
Properties defaultProps = new Properties();
FileInputStream in = new FileInputStream("defaultProperties");
defaultProps.load(in);
in.close();
// create program properties with default
Properties applicationProps = new Properties(defaultProps);
// now load properties from last invocation
in = new FileInputStream("appProperties");
applicationProps.load(in);
in.close();
. . .Properties
object. This object contains the set of properties to use if values are not explicitly set elsewhere. Then the load method reads the default values from a file on disk nameddefaultProperties
. Next, the application uses a different constructor to create a secondProperties
object,applicationProps
, whose default values are contained indefaultProps
. The defaults come into play when a property is being retrieved. If the property can't be found inapplicationProps
, then its default list is searched.
Finally, the code loads a set of properties intoapplicationProps
from a file namedappProperties
. The properties in this file are those that were saved from the program the last time it was invoked (the next section shows you how this was done).
Saving Properties
The following example writes out the application properties from the previous example usingProperties
'ssave
method. The default properties don't need to be saved each time because they never change.TheFileOutputStream out = new FileOutputStream("appProperties");
applicationProps.save(out, "---No Comment---");
out.close();save
method needs a stream to write to, as well as a string that it uses as a comment at the top of the output.
Getting Property Information
Once you've set up yourProperties
object, you can query it for information about various keys/values that it contains. An application gets information from a Properties
object after start up so that it can initialize itself based on choices made by the user. The Properties
class has several methods for getting property information:- contains(Object value)
containsKey(Object key)
Returnstrue
if the value or the key is in theProperties
object.Properties
inherits these methods fromHashtable
. Thus they acceptObject
arguments. - You should pass in
String
s to get property.
getProperty(String key)
getProperty(String key, String default)
Returns the value for the specified property. The second version allows you to provide a default value. If the key is not found, the default is returned. - list(PrintStream s)
list(PrintWriter w)
Writes all of the properties to the specified stream or writer. This is useful for debugging. - elements()
keys()
propertyNames()
Returns anEnumeration
containing the keys or values (as indicated by the method name) contained in theProperties
object. - size()
Returns the current number of key/value pairs. - Setting
Properties
A user's interaction with a program during its execution may impact property settings. These changes should be reflected in theProperties
object so that they are saved when the program exits (and calls the save method). You can use the following methods to change the properties in aProperties
object:
put(Object key, Object value)
Puts the key/value pair in theProperties
object. - remove(Object key)
Removes the key/value pair associated with key.
Both put and remove come fromHashtable
and thus takeObjects
. You should pass inStrings
.
Tuesday, 19 October 2010
Stack in java using link list
push() - push elements into a stack. We will use the insertAtFirst() method of LinkedList. Throws StackOverflowException when the stack is full.
pop() - remove and returns the top element from a stack. We will use the removeAtFirst() method of LinkedList. Throws StackEmptyException when the stack is empty.
peek() - return the top element from the stack without removing it. We will use the getFirst() method of LinkedList. Throws StackEmptyException when the stack is empty.
The java code for this looks very simpler. We will make use of the existing SinglyLinkedList class that we have used before.
package dsa.stack;
import dsa.linkedlist.SinglyLinkedList;
public class Stack<E> extends SinglyLinkedList<E>{
public static final int MAX_STACK_SIZE = 100;
public E pop() throws StackEmptyException{
if(this.size()==0){
throw new StackEmptyException();
}
return this.removeAtFirst();
}
public E peek() throws StackEmptyException{
if(this.size()==0){
throw new StackEmptyException();
}
return this.getFirst().data;
}
public void push(E data) throws StackOverflowException{
if(this.size()>MAX_STACK_SIZE){
throw new StackOverflowException();
}
this.insertAtFirst(data);
}
public static void main(String args[]){
Stack<Integer> stack = new Stack<Integer>();
try{
System.out.println("Pushing 1, 2, 3, 4, 5");
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
stack.push(5);
System.out.println("Pop once : "+stack.pop());
System.out.println("Peek once : "+stack.peek());
System.out.println("Pop once : "+stack.pop());
System.out.println("Pop once : "+stack.pop());
System.out.println("Pop once : "+stack.pop());
System.out.println("Pop once : "+stack.pop());
System.out.println("Pop once : "+stack.pop());
}catch(StackEmptyException e){
System.out.println(e.getMessage());
}catch(StackOverflowException e){
System.out.println(e.getMessage());
}
}
}
/*
SAMPLE OUTPUT:
Pushing 1, 2, 3, 4, 5
Pop once : 5
Peek once : 4
Pop once : 4
Pop once : 3
Pop once : 2
Pop once : 1
Stack is empty!
*/
package dsa.stack;
public class StackEmptyException extends Exception{
public StackEmptyException(){
super("Stack is empty!");
}
}
package dsa.stack;
public class StackOverflowException extends Exception{
public StackOverflowException(){
super("Stack Overflown");
}
}
Parsing Strings with split
- parsing
- dividing a string into tokens based on the given delimiters
- token
- one piece of information, a "word"
- delimiter
- one (or more) characters used to separate tokens
When there is just one character used as a delimiter
Example 1
We want to divide up a phrase into words where spaces are used to separate words. For examplethe music made it hard to concentrate
String phrase = "the music made it hard to concentrate";
String delims = "[ ]+";
String[] tokens = phrase.split(delims);
- the general form for specifying the delimiters that we will use is "[delim_characters]+" . (This form is a kind of regular expression. You don't need to know about regular expressions - just use the template shown here.) The plus sign (+) is used to indicate that consecutive delimiters should be treated as one.
- the split method returns an array containing the tokens (as strings). To see what the tokens are, just use a for loop:
You should find that there are seven tokens: the, music, made, it, hard, to, concentratefor (int i = 0; i < tokens.length; i++)
System.out.println(tokens[i]);
Example 2
Suppose each string contains an employee's last name, first name, employee ID#, and the number of hours worked for each day of the week, separated by commas. SoSmith,Katie,3014,,8.25,6.5,,,10.75,8.5
String employee = "Smith,Katie,3014,,8.25,6.5,,,10.75,8.5";
String delims = "[,]";
String[] tokens = employee.split(delims);
There is one small wrinkle to be aware of (regardless of how consecutive delimiters are handled): if the string starts with one (or more) delimiters, then the first token will be the empty string ("").
When there are several characters being used as delimiters
Example 3
Suppose we have a string containing several English sentences that uses only commas, periods, question marks, and exclamation points as punctuation. We wish to extract the individual words in the string (excluding the punctuation). In this situation we have several delimiters (the punctuation marks as well as spaces) and we want to treat consecutive delimiters as oneString str = "This is a sentence. This is a question, right? Yes! It is.";
String delims = "[ .,?!]+";
String[] tokens = str.split(delims);
Example 4
Suppose we are representing arithmetic expressions using strings and wish to parse out the operands (that is, use the arithmetic operators as delimiters). The arithmetic operators that we will allow are addition (+), subtraction (-), multiplication (*), division (/), and exponentiation (^) and we will not allow parentheses (to make it a little simpler). This situation is not as straight-forward as it might seem. There are several characters that have a special meaning when they appear inside [ ]. The characters are ^ - [ and two &s in a row(&&). In order to use one of these characters, we need to put \\ in front of the character:String expr = "2*x^3 - 4/5*y + z^2";
String delims = "[+\\-*/\\^ ]+"; // so the delimiters are: + - * / ^ space
String[] tokens = expr.split(delims);
General template for using split
String s = string_to_parse;
String delims = "[delimiters]+"; // use + to treat consecutive delims as one;
// omit to treat consecutive delims separately
String[] tokens = s.split(delims);
java.util.StringTokenizer
java.util.StringTokenizer
class is used to break strings into tokens (words, numbers, operators, or whatever). Has been replaced by regular expression tools. A more powerful solution is to use regular expressions, and the easiest way to do that is use the
java.util.Scaner
class, the String split(..)
method, or the Pattern
and Matcher
classes. A StringTokenizer constructor takes a string to break into tokens and returns a StringTokenizer object for that string. Each time its
nextToken()
method is called, it returns the next token in that string. If you don't specify the delimiters (separator characters), blanks are the default. Constructors
StringTokenizer st = new StringTokenizer(s);
- Creates a StringTokenizer for the String s that uses whitespace (blanks, tabs, newlines, returns, form feeds) as delimiters.
StringTokenizer st = new StringTokenizer(s, d);
- Creates a StringTokenizer for the String s using delimiters from the String d.
StringTokenizer st = new StringTokenizer(s, d, f);
- Creates a StringTokenizer for the String s using delimiters from the String d. If the boolean f is
true
, each delimiter character will also be returned as a token.
Common Methods
Assume thatst
is a StringTokenizer. st.hasMoreTokens()
-- Returnstrue
if there are more tokens.st.nextToken()
-- Returns the next token as a String.st.countTokens()
-- Returns the int number of tokens. This can be used to allocate an array before starting, altho it can be inefficient for long strings because it has to scan the string once just to get this number. Using a Vector and converting it to an array at the end may be a better choice.
Example: Find the longest word in a String
This code finds the longest word (characters separated by delimiter characters) in the Strings
, using blanks, commas, and tabs as delimiters. // Assume s contains a string of words
String longestWord = "";
StringTokenizer st = new StringTokenizer(s, " ,\t");
while (st.hasMoreTokens()) {
String w = st.nextToken();
if (w.length() > longestWord.length()) {
longestWord = w;
}
}
Method overriding in java
public abstract class BaseClass {
public void insert(Object object) {
// Do something
}
}
public class SampleClass extends BaseClass {
public void insert(Object object, Long param){
// Do Something
}
}
SampleClass sampleClass = new SampleClass();
sampleClass.insert(Object object);
sampleClass.insert(Object object, Long param);
SampleClass sampleClass = new SampleClass();
sampleClass.insert(Object object, Long param);
here is no way of hiding the method. You can do this:but that's it.@Override
public void insert(Object ob) {
throw new UnsupportedOperationException("not supported");
}
The base class creates a contract. All subclasses are bound by that contract. Think about it this way:
BaseObject b = new SomeObjectWithoutInsert();
b.insert(...);
How is that code meant to know that it doesn't have an insert(Object)
method? It can't.Your problem sounds like a design problem. Either the classes in question shouldn't be inheriting from the base class in question or that base class shouldn't have that method. Perhaps you can take
insert()
out of that class, move it to a subclass and have classes that need insert(Object)
extend it and those that need insert(Object, Object)
extend a different subclass of the base object.here is no way of hiding the method. You can do this:
@Override
public void insert(Object ob) {
throw new UnsupportedOperationException("not supported");
}
but that's it.The base class creates a contract. All subclasses are bound by that contract. Think about it this way:
BaseObject b = new SomeObjectWithoutInsert();
b.insert(...);
How is that code meant to know that it doesn't have an insert(Object)
method? It can't.Your problem sounds like a design problem. Either the classes in question shouldn't be inheriting from the base class in question or that base class shouldn't have that method. Perhaps you can take
insert()
out of that class, move it to a subclass and have classes that need insert(Object)
extend it and those that need insert(Object, Object)
extend a different subclass of the base object.Static Methods
class Foo {
public static void method() {
System.out.println("in Foo");
}
}
class Bar extends Foo {
public static void method() {
System.out.println("in Bar");
}
}
This compiles and runs just fine. Isn't it an example of a static method overriding another static method? The answer is no - it's an example of a static method hiding another static method. If you try to override a static method, the compiler doesn't actually stop you - it just doesn't do what you think it does. So what's the difference?
Briefly, when you override a method, you still get the benefits of run-time polymorphism, and when you hide, you don't. So what does that mean? Take a look at this code:
class Foo {
public static void classMethod() {
System.out.println("classMethod() in Foo");
}
public void instanceMethod() {
System.out.println("instanceMethod() in Foo");
}
}
class Bar extends Foo {
public static void classMethod() {
System.out.println("classMethod() in Bar");
}
public void instanceMethod() {
System.out.println("instanceMethod() in Bar");
}
}
class Test {
public static void main(String[] args) {
Foo f = new Bar();
f.instanceMethod();
f.classMethod();
}
}
If you run this, the output isinstanceMethod() in BarWhy do we get instanceMethod from Bar, but classMethod() from Foo? Aren't we using the same instance f to access both of these? Yes we are - but since one is overriding and the other is hiding, we see different behavior. Since instanceMethod() is an instance method, in which Bar overrides the method from Foo, at run time the JVM uses the actual class of the instance f to determine which method to run. Although f was declared as a Foo, the actual instance we created was a new Bar(). So at runtime, the JVM finds that f is a Bar instance, and so it calls instanceMethod() in Bar rather than the one in Foo. That's how Java normally works for instance methods.
classMethod() in Foo
With classMethod() though. since it's a class method, the compiler and JVM don't expect to need an actual instance to invoke the method. And even if you provide one (which we did: the instance referred to by f) the JVM will never look at it. The compiler will only look at the declared type of the reference, and use that declared type to determine, at compile time, which method to call. Since f is declared as type Foo, the compiler looks at f.classMethod() and decides it means Foo.classMethod. It doesn't matter that the instance reffered to by f is actually a Bar - for static methods, the compiler only uses the declared type of the reference. That's what we mean when we say a static method does not have run-time polymorphism.
Because instance methods and class methods have this important difference in behavior, we use different terms - "overriding" for instance methods and "hiding" for class methods - to distinguish between the two cases. And when we say you can't override a static method, what that means is that even if you write code that looks like it's overriding a static method (like the first Foo and Bar at the top of this page) - it won't behave like an overridden method.
So what about accessing a static method using an instance?
It's possible in Java to write something like:
f.classMethod();where f is an instance of some class, and classMethod() is a class method (i.e. a static method) of that class. This is legal, but it's a bad idea because it creates confusion. The actual instance f is not really important here. Only the declared type of f matters. That is, what class is f declared to be? Since classMethod() is static, the class of f (as determined by the compiler at compile time) is all we need.
Rather than writing:
f.classMethod();It would be better coding style to write either:
Foo.classMethod();or
Bar.classMethod();That way, it is crystal clear which class method you would like to call. It is also clear that the method you are calling is indeed a class method. o;'oi;'i Barring that, you could always come up with this monstrosity:
f.getClass().getMethod("classMethod", new Class[]).invoke(null, new Object[]);But all this could be avoided by simply not trying to override your static (class) methods. :-)
Why does the compiler sometimes talk about overriding static methods?
Sometimes you will see error messages from the compiler that talk about overriding static methods. Apparently, whoever writes these particular messages has not read the Java Language Specification and does not know the difference between overriding and hiding. So they use incorrect and misleading terminology. Just ignore it. The Java Language Specification is very clear about the difference between overriding and hiding, even if the compiler messages are not. Just pretend that the compiler said "hide" rather than "override"..
Java exceptions and function overriding.
Monday, 18 October 2010
Immutable objects
final
, its use makes that purpose explicit, to the human (the software developer) and the machine (the compiler). Immutable objects carry some very desirable characteristics:
- they are simple to understand and easy to use
- they are inherently thread-safe: they require no synchronization
- they make great building blocks for other objects
final
is going to help us define immutable objects. First in labelling our object as immutable, which makes it simple to use and understand by other programmers. Second in guaranteeing that the object's state never changes, which enable the thread-safe property: thread concurrency issues are relevant when one thread can change data while another thread is reading the same data. Because an immutable object never changes its data, synchronizing access to it is not needed. Create an immutable class by meeting all of the following conditions: - Declare all fields
private final
. - Set all fields in the constructor.
- Don't provide any methods that modify the state of the object; provide only getter methods (no setters).
- Declare the class final, so that no methods may be overridden.
- Ensure exclusive access to any mutable components, e.g. by returning copies.
Sunday, 17 October 2010
Arrays tip : Ignoring the zeroth row
Sometimes you want to use natural input values as an index, the real values that that data has instead of starting with zero. Let's take the case of data that starts with the value 1, like the day of the month. The standard approach is to subtract one from every day value that's used as an index. This is annoying and error prone. Another way to do handle this case is to declare the array with an extra element, eg, 32 if dealing with the days in the month, then ignoring the zeroth element. If you're dealing with a two dimensional array, for example the
accidents
array from the previous page, you can even deallocate the first row so there won't be any possibility of referencing the zeroth day. For example, static final int DAYS = 32;Because two-dimensional arrays are stored by row, you can do this. You can use the trick of allocating more columns to use the natural data, but you can't deallocate a column.
static final int HOURS = 24;
. . .
int[][] accidents = new int[DAYS][HOURS];
accidents[0] = null;
Tuesday, 12 October 2010
Arrays in C#
public static void Main()
{
int[] arr = {5, 1, 10, 33, 100, 4};
Array.Sort(arr);
foreach (int v in arr)
Console.WriteLine("Element: {0}", v);
//Making random array
DateTime now = DateTime.Now;
Random rand = new Random ((int) now.Millisecond);
int [] Arr = new int [12];
for (int x = 0; x < Arr.Length; ++x)
{
Arr [x] = rand.Next () % 101;
}
//initialising 2 D array
int[,] sqrs = {
{ 1, 1 },
{ 2, 4 },
{ 3, 9 },
{ 4, 16 },
{ 5, 25 },
{ 6, 36 },
{ 7, 49 },
{ 8, 64 },
{ 9, 81 },
{ 10, 100 }
};
//jagged array
int[][] jagged = new int[3][];
jagged[0] = new int[4];
jagged[1] = new int[3];
jagged[2] = new int[5];
int i;
// store values in first array
for(i=0; i < 4; i++)
jagged[0][i] = i;
}
Sunday, 10 October 2010
Java Vs C# : Arrays
Saturday, 9 October 2010
Java Vs C#
In languages like C and C++, each subarray of a multidimensional array must have
the same dimensions. In Java and C# arrays do not have to be uniform because jagged
arrays can be created as one-dimensional arrays of arrays. In a jagged array the
contents of the array are arrays which may hold instances of a type or references to
other arrays. For this reason the rows and columns in a jagged array need not have
uniform length as can be seen from the following code snippet:
int [][]myArray = new int[2][];
myArray[0] = new int[3];
myArray[1] = new int[9];
No Global Methods
Interfaces, Yes. Multiple Inheritance, No
String
C# has a System.String class which is analogous to the java.lang.String class. Both
classes are immutable meaning that the values of the strings cannot be changed once
the strings have been created. In both instances methods that appear to modify the
actual content of a string actually create a new string to return, leaving the original
string unchanged. Thus the following C# and Java code does not modify the string in
either case
C# Code
String csString = "Apple Jack";
csString.ToLower(); /* Does not modify string, instead returns
lower case copy of string */
Java Code
String jString = "Grapes";
jString.toLowerCase(); /* Does not modify string, instead returns
lower case copy of string */
To create a string-like object that allows modification in C# it is advisable to use the
System.Text.StringBuilder class whereas in Java one would use the
java.lang.StringBuffer class.
NOTE: In C#, the string class can either be written as string or String.
Unextensable classes
Both Java and C# provide mechanisms to specify that a class should be the last one in
an inheritance hierarchy and cannot be used as a base class. In Java this is done by
preceding the class declaration with the final keyword while in C# this is done by
preceding the class declaration with the sealed keyword. Below are examples of
classes that cannot be extended in either language
eg.
C#
sealed class X{}
Java
final class X{}
Exceptions in C# and Java share a lot of similarities. Both languages support the use
of the try block for indicating guarded regions, the catch block for handling thrown
exceptions and the finally block for releasing resources before leaving the method.
Both languages have an inheritance hierarchy where all exceptions are derived from a
single Exception class. Exceptions can be caught and rethrown after some error
handling occurs in both languages. Finally, both languages provide a mechanism for
wrapping exceptions in one another for cases where a different exception is rethrown
from the one that was caught. An example of using the exception wrapping capability
is a three tier application where a SQLException is thrown during database access but
is caught, examined, then an application specific exception is thrown. In this scenario
the application specific exception can be initialized with the original SQLException
so handlers of the application specific exception can access the original exception
thrown if needed. Below are two equivalent code samples that show the similarities
between exceptions in both languages.
NOTE: Although exceptions in both languages support methods for getting a stack
trace, only Java exceptions have methods that allow one to alter the stack trace.
Sunday, 26 September 2010
Cloning
Cloning
Why clone?
Sometimes you need to make a copy of an object. Most of the time the fact that Java uses references to objects is a great advantage because you don't have to worry about making copies of objects, but sometimes you need a copy.
- Protect against changes. You need a copy to hand to someone you don't trust to leave the object unchanged.
- In place of new. The standard way to make new objects is to use the
new
operator, which calls a class constructor. A different way to think about creating multiple objects of a "class" is to create on prototype and create new objects by copying this prototype, typically by calling on a factory method to create new objects. This is useful if different kinds of objects are distinguished by different parameter values.For example, you might want several kinds of arrowheads - filled, empty, diamonds, barbed, etc. With a little planning, code can be written to draw all of these types, differing only in parameter values (isFilled, pointAngle, barbAngle). Different types of graphical objects can simply be created once, and cloned to make a new objects of that "class".
The clone()
method - and why you might want to override it
The Object
class defines a clone()
method that makes a shallow copy of an object.
Protected not public. Even if a shallow copy was sufficient, and it's often not, a user can't get to it because it's protected
and not public
, so only subclasses can see it, but no users! You can make it available by overriding it in your class and making it public -- you can always make an overridden method more visible that it was in the parent class.
Deep vs. Shallow Copies in java
Deep vs. Shallow Copies
Assignment and copies
Assignment. The assignment operator (=) makes a copy of the "value". For a primitive type (int, double, etc) this simply copies the numeric value, but the assignment of a object copies only the reference (address in memory) of the object.
Sharing immutable objects
One object may have many references to it. If an object is immutable, ie can't be changed, it can safely be shared, and there is no reason to have more than one copy of it. The most common example of this is the String class. All string objects are immutable. This is very useful and is fast because there is no need to copy the contents of the string, but only the reference to it (typically 32 bits). If you need a mutable string, then you can use StringBuilder
.
No way to tell if something is immutable
The careful reader of Java keywords may have noticed that there is a const
keyword. Mysteriously, this keyword has no use. The intent was to use it to declare things to be unchangeable, but it turned out to be too hard to make this work in an absolutely safe manner. There is no way to know if objects of a class are immutable, except by reading the documentation.
The final
keyword allows only one assignment to a variable, but doesn't protect the fields of the object that variable references.
Interfaces in java
Note that in java interface naming is like Iterable, etc...i.e ending with able many times.
Non-static or Member inner class
By default, an inner class is non-static:
This fragment defines the class A which contains a non-static inner class B.
A non-static inner class can be instantiated only inside a non-static method of the outer class. This is because every instance of a non-static inner class must be associated with an instance of the outer class. In a sense, every instance of a non-static inner class exists ``inside'' an instance of the outer class. A single instance of the outer class may have associated with it more than one instance of the inner class.
Because an instance of a non-static inner class has an associated instance of the outer class, the methods of the inner class can access directly any of the members (fields or methods) of the outer class instance. For example, the f method defined above can access both x and y directly.
public class AThe Java keyword this can be used in a non-static method to refer to the current object instance. Thus in the method f, this refers to an instance of the inner B class. Every non-static inner class is associated with an instance of A.this.
{
int y;
public class B
{
int x;
void f () {}
}
}
Use: An Enumeration Implemented as a Member Class
public class LinkedStack {
// Our static member interface; body omitted here...
public static interface Linkable { ... }
// The head of the list
private Linkable head;
// Method bodies omitted here
public void push(Linkable node) { ... }
public Linkable pop() { ... }
// This method returns an Enumeration object for this LinkedStack
public java.util.Enumeration enumerate() { return new Enumerator(); }
// Here is the implementation of the Enumeration interface,
// defined as a member class.
protected class Enumerator implements java.util.Enumeration {
Linkable current;
// The constructor uses the private head
//field of the containing class
public Enumerator() { current = head; }
public boolean hasMoreElements() { return (current != null); }
public Object nextElement() {
if (current == null) throw new java.util.NoSuchElementException();
Object value = current;
current = current.getNext();
return value;
}
}
}
Restrictions on Member Classes
- A member class cannot have the same name as any containing class or package. This is an important rule, and one not shared by fields and methods.
- Member classes cannot contain any static fields, methods, or classes (with the exception of constant fields declared both static and final). staticfields, methods, and classes are top-level constructs not associated with any particular object, while every member class is associated with an instance of its enclosing class. Defining a static top-level member within a non-top-level member class simply promotes confusion and bad programming style, so you are required to define all static members within a top-level or static member class or interface.
- Interfaces cannot be defined as member classes. An interface cannot be instantiated, so there is no object to associate with an instance of the enclosing class. If you declare an interface as a member of a class, the interface is implicitly static, making it a static member class.
The most important feature of a member class is that it can access the instance fields and methods in its containing object. We saw this in theLinkedStack.Enumerator() constructor of above link list example:
In this example, head is a field of the LinkedStack class, and we assign it to the current field of the Enumerator class. The current code works, but what if we want to make these references explicit? We could try code like this:public Enumerator() { current = head; }
This code does not compile, however. this.current is fine; it is an explicit reference to the current field in the newly created Enumerator object. It is thethis.head expression that causes the problem; it refers to a field named head in the Enumerator object. Since there is no such field, the compiler generates an error. To solve this problem, Java defines a special syntax for explicitly referring to the containing instance of the this object. Thus, if we want to be explicit in our constructor, we can use the following syntax:public Enumerator() { this.current = this.head; }
The general syntax is classname.this, where classname is the name of a containing class. Note that member classes can themselves contain member classes, nested to any depth. Since no member class can have the same name as any containing class, however, the use of the enclosing class name prepended to this is a perfectly general way to refer to any containing instance. This syntax is needed only when referring to a member of a containing class that is hidden by a member of the same name in the member class.public Enumerator() { this.current = LinkedStack.this.head; }
Accessing superclass members of the containing class
When a class shadows or overrides a member of its superclass, you can use the keyword super to refer to the hidden member. This super syntax can be extended to work with member classes as well. On the rare occasion when you need to refer to a shadowed field f or an overridden method m of a superclass of a containing class C, use the following expressions:C.super.f
C.super.m()
This syntax was not implemented by Java 1.1 compilers, but it works correctly as of Java 1.2.
Specifying the containing instance
As we've seen, every instance of a member class is associated with an instance of its containing class. Look again at our definition of the enumerate() method in :public Enumeration enumerate() { return new Enumerator(); }
When a member class constructor is invoked like this, the new instance of the member class is automatically associated with the this object. This is what you would expect to happen and exactly what you want to occur in most cases. Occasionally, however, you may want to specify the containing instance explicitly when instantiating a member class. You can do this by preceding the new operator with a reference to the containing instance. Thus, the enumerate() method shown above is shorthand for the following:
public Enumeration enumerate() { return this.new Enumerator(); }
Let's pretend we didn't define an enumerate() method for LinkedStack. In this case, the code to obtain an Enumerator object for a given LinkedStackobject might look like this:
The containing instance implicitly specifies the name of the containing class; it is a syntax error to explicitly specify that containing class:LinkedStack stack = new LinkedStack(); // Create an empty stack
Enumeration e = stack.new Enumerator(); // Create an Enumeration for it
Enumeration e = stack.new LinkedStack.Enumerator(); // Syntax error
There is one other special piece of Java syntax that specifies an enclosing instance for a member class explicitly. Before we consider it, however, let me point out that you should rarely, if ever, need to use this syntax. It is one of the pathological cases that snuck into the language along with all the elegant features of inner classes.
As strange as it may seem, it is possible for a top-level class to extend a member class. This means that the subclass does not have a containing instance, but its superclass does. When the subclass constructor invokes the superclass constructor, it must specify the containing instance. It does this by prepending the containing instance and a period to the super keyword. If we had not declared our Enumerator class to be a protected member of LinkedStack, we could subclass it. Although it is not clear why we would want to do so, we could write code like the following:
// A top-level class that extends a member class
class SpecialEnumerator extends LinkedStack.Enumerator {
// The constructor must explicitly specify a containing instance
// when invoking the superclass constructor.
public SpecialEnumerator(LinkedStack s) { s.super(); }
// Rest of class omitted...
}
Scope Versus Inheritance for Member Classes
We've just noted that a top-level class can extend a member class. With the introduction of member classes, there are two separate hierarchies that must be considered for any class. The first is the classhierarchy, from superclass to subclass, that defines the fields and methods a member class inherits. The second is the containmenthierarchy, from containing class to contained class, that defines a set of fields and methods that are in the scope of (and are therefore accessible to) the member class.The two hierarchies are entirely distinct from each other; it is important that you do not confuse them. This should not be a problem if you refrain from creating naming conflicts, where a field or method in a superclass has the same name as a field or method in a containing class. If such a naming conflict does arise, however, the inherited field or method takes precedence over the field or method of the same name in the containing class. This behavior is logical: when a class inherits a field or method, that field or method effectively becomes part of that class. Therefore, inherited fields and methods are in the scope of the class that inherits them and take precedence over fields and methods by the same name in enclosing scopes.
Because this can be quite confusing, Java does not leave it to chance that you get it right. Whenever there is a naming conflict between an inherited field or method and a field or method in a containing class, Java requires that you explicitly specify which one you mean. For example, if a member class B inherits a field namedx and is contained within a class A that also defines a field named x, you must use this.x to specify the inherited field and A.this.x to specify the field in the containing class. Any attempt to use the field x without an explicit specification of the desired instance causes a compilation error.
A good way to prevent confusion between the class hierarchy and the containment hierarchy is to avoid deep containment hierarchies. If a class is nested more than two levels deep, it is probably going to cause more confusion than it is worth. Furthermore, if a class has a deep class hierarchy (i.e., it has many superclass ancestors), consider defining it as a top-level class, rather than as a member class.