7 programming languages on the rise

April 21st, 2011

This is the title of an article on InfoWorld, that list the programming languages that are gaining more programmers.

  1. Python
  2. Ruby
  3. Matlab
  4. Javascript
  5. R
  6. Erlang
  7. Cobol
  8. CUDA extensions

The link to Google trends to compare those languages references on the web.

ThoughtWorks’ Fowler and Humble Talk Continuous Delivery

March 10th, 2011

Summary
Two of ThoughtWorks’ finest, Martin Fowler and Jez Humble, talk about the notion of Continuous Delivery, which enables organizations to build software that is production ready at all times. To do this, enterprises automate the build, deployment, and testing process, and improve collaboration between developers, testers, and operations. The duo discusses a variety of related issues.

Jez Humble is the product manager for the Go product at ThoughtWorks Studios and is co-author of “Continuous Delivery: Reliable Software Releases through Build, Test, and Deployment Automation.” Martin Fowler an author, speaker, and pundit on the topic of software development. He is chief scientist at ThoughtWorks and has written six books on software development.

Watch the interview here:

http://www.infoq.com/interviews/jez-humble-martin-fowler-cd

SCJP – Threads

February 28th, 2011

Dont forget

  • wait, notify or notifyAll must have the this object lock. So look if they are in a syncrhonized method

 

 

 

  • To analyze synchronized method issues, don't forget to verify if the threads are being created in same runnable object. If don't the synchronized methods locks will be distinct.
  • public void run() - is the signature of the method that must be extended to implement Runnable or to extend Thread
  • JVM exit after all the non demons threads created by the application complete, or when a thread executes System.exit().
    • if a main thread exits or if it throws a runtime exception, the child threads proceeds without any problem.
defined inThread defined inObject static final declare achecked exception Can throw aruntime exception
run X
start X
join X X
sleep X X
yield X X
currentThread X X
wait X X
notify X
notifyAll X

 

  • isAlive() - tests if this thread is alive. A thread is alive if it has been started and has not yet died.
  • If the thread doesn't own a lock on the object, and if we try to wait on this object, an IllegalMonitorStateException is thrown at runtime.
  • If a thread is waiting on another thread, and if those thread finishes the main thread is released without any problem.
  • synchronized block should be defined on an object: synchronized(this) {}
  • Thread.sleep causes the currently executing thread to sleep, even if called on a thread instance, not on the thread refereed in the code
  • Priority 1 is low priority, 5 is normal, 10 is maximum prioprity
  • interrupt and isInterrupted are Thread methods

 

  • The small execution block (means: don't allow to change running thread) - is per bytecode line, not by intermediate expression. To be confirmed
  • to a thread call wait, notify or notifyAll on a obj, the thread must own the lock for those obj.
  • Thread.sleep - don't release the lock
  • wait releases the lock

 

Synchronized  methods

  • public static SafeDeposit getInstance(int code) {} , with a private static instance and a private constructor
    • does not guarantees only one instance, because the getinstance is not synchronized

 

  • A class to be thread safe, the variables need to be private, and the get and set methods need to be synchronized

SCJP – Primitive types / Operators / Format

February 24th, 2011
Java Primitive Data Types
Type Values Default Size Range
byte signed integers 0 8 bits -128 to 127
short signed integers 0 16 bits -32768 to 32767
int signed integers 0 32 bits -2147483648 to 2147483647
long signed integers 0 64 bits -9223372036854775808 to 9223372036854775807
float IEEE 754 floating point 0.0 32 bits +/-1.4E-45 to +/-3.4028235E+38,
+/-infinity, +/-0, NAN
double IEEE 754 floating point 0.0 64 bits +/-4.9E-324 to
+/-1.7976931348623157E+308,
+/-infinity, +/-0, NaN
char Unicode character \u0000 16 bits \u0000 to \uFFFF0, 65535 (converted to int)
boolean true, false false 1 bit used in 32 bit integer NA

Table from here, with some explanations.

  • not possible to use instanceof with primitives int x=1; if (x instanceof Integer) //compilation fails:
  • Integer have a constructor: Integer(String s)

Wrappers and Autoboxing

  • unboxing a null will throw exception at runtime.
  • for small values wrappers created through boxing will be pooled. For numbers (int, short, long) until 127
    • the == comparison will be true
    • not if we create the Integer explicitly by the constructor
  • A literal is always boxed first. Then it is asigned to a variable.

Conversion issues - loss of precision

Operation error?
fix
Float c = 4; Error cannot widen then boxing Float c = 4f;
Float d = 4.0; Error conversion from double to float - loss of precision Float d = 4.0f;
float f1 = 4; ok float can handle int - floating point representation
float f2 = 4.0; Error conversion from double to float - loss of precision float f2 = 4.0f;
Double a1 = 4; Error cannot widen then boxing Double a1 = 4d;
Double a2 = 4.0; ok double to double
double d3 = 4; ok double can handle int
double d4 = 4.0; ok double to double
Double a1 = 4f; error cannot widen then boxing Double a1 = 4d;
  • widen then box don't compile. byte b=5; go(b) compilation error with void go(Long x). This is just too much for the compiler
  • Boxing operation followed by a widening (simply superclass issue) operation it's ok for the compiler
    • byte b=5; go(b); void go(Object o)
  • new java.lang.Byte(4); //compilation error - Byte have no constructor with int

 

with overload

  • compiler will always choose the oldest technology (Java version)
  • the compiler will choose widening over boxing. int i=5; go(i) will prefer to match long instead of Integer
  • var-args method is "looser" than the other method, even against boxing (rule above)

Assignments rules between short, char, byte and int

  • all short, char, byte and int, can be handled same way
  • assignments with literals compiles if they are inside a range.
    • byte b = 'a'; //works
    • byte b = 'ã'; //compile error
    • assigns with operations between literals works fine if the resulting literal is in the range.
      • byte b = 'a' + 1; //works fine
  • assignments with expressions that contains at least on variable. (compiler don't know the value)
    • Expressions with + operator results to a int type.
    • should be assigned to a type that can hold a the int, other way only with a cast.
    • byte c=1; byte b = c+1 //compile error
  • int x =5; x=-x; //this compiles and is the negative variable value
  • (x++)*2  //only increments after the operator, even with ()

Operators

  • Operator == used between objects, the references must be the same type or hierarchy, other way it will give compiler error
  • Operator == between a primitive and a object, first the object is unboxed and then the primitives are compared
    • between 2 objects, for instance between two Integers, objects are compared are will result false
  • valueOf static method that returns an object instance
    • takes primitives or String, is box operation or conversion from String
  • parseXxx and xxxValue return primitives
    • parseXxx - takes String and returns primitives
    • xxxValue takes no argument, just unbox
  • both valueOf or parseXxx (the methods that takes as arguments a String), consider "011" not as octal but as decimal.
method class static? returns args
valueOf String static String any primitive
valueOf Integer static Integer int or String
valueOf Float static Float float or String
parseInt Integer static int String
parseFloat Float static float String
intValue Integer int -
floatValue Float float -

 

Operations

  • every primitives( byte,short,int,long) in an expression is first converted into int then the expression is evaluated
    • if we are assigning the result of the expression to narrower primitives(like byte or short) without explicitly typecasting it then it will cause compiler error.
  • float/0 --> Infinity or -Infinity
  • int/0 --> ArithmeticException
  • Infinity / Infinity --> NaN

 

 

Formating

%[arg_index$][flags][width][.precision]conversion char

  • "-" Left justify this argument
  • "+" Include a sign (+ or -) with this argument
  • "0" Pad this argument with zeroes
  • "," Use locale-specific grouping separators (i.e., the comma in 123,456)
  • "(" Enclose negative numbers in parentheses

Conversion

  • b boolean
  • c char
  • d integer
  • f floating point
  • s string

NumberFormat

String s = "123.456xyz";
NumberFormat nf = NumberFormat.getInstance();

NumberFormat.getInstance(Locale.FRENCH);

  • nf.parse(s);
    • Parses text from the beginning of the given string to produce a number. The method may not use the entire text of the given string.
  • nf.format(s);
    • To format a number for the current Locale ---
    • May throw an exception if founds not numbers as input

DateFormat

  • java.text.DateFormat
  • java.util.Date
  • java.util.Locale
  • DateFormat.getInstance() - doesn't receive parameters
  • DateFormat.getDateInstance(DateFormat.FULL) Other args: DateFormat.FULL, SHORT, LONG,...
  • DateFormat.getTimeInstance
  • DateFormat.getTimeInstance(DateFormat.FULL)
Locale[] la = { new Locale("it", "IT"), new Locale("pt") };
Date d = new Date();
DateFormat df = DateFormat.getInstance();
DateFormat df = DateFormat.getDateInstance(DateFormat.FULL, l[0]);
System.out.println(df.format(d));

Calendar operations

Calendar cal1 = new GregorianCalendar(2009,5,5);
Calendar cal2 = new GregorianCalendar(); 

Date d = calendar.getInstance().getTime();   // the same as new Date();

cal1.roll(Calendar.MONTH, true);

System.out.println("Year: " + cal1.get(Calendar.YEAR));
cal2.set(Calendar.MONTH, Calendar.MAY);  

Date date = cal1.getTime();

Locale

String, StringBuffer and StringBuilder

String StringBuffer / StringBuilder
concat X
contains X
format X
chatAt X X
indexOf X X
isEmpty X
lastIndexOf X X
length X X
replace X X
split X
subString X X
toLowerCase X
append X
delete X
insert X
replace X
toString X X
valueOf X

Bit operations

int x = 5;

x = x << 97;

  • << 1 moves all bits 1 position to the left. It's the same as move 1 positions and adds a 0 at the right. The same as multiply by 2. Example: 5 << 1 ---> 10
  • >>1 moves 1 bit to the right, and drops the most right bit
  • the shift operations by 97 its the same as rotate by 1 (for 32 bits variables), you can remove the 32 multiples.

 

  • >>> unsigned shift. Ignores the sign bit, means that rotates also the sign bit. rotate right by 1 a negative number results a big positive number
  • <<< doesn't exists
  • <<= left shift and assign: i<<=2 means i=i<<2, like in i++

 

  • 011 - in java represents an octal number. converted to decimal is 9.
  • 0x11 - in java represents hexadecimal number

Bitwise Operators

  • Bitwise operators compare two variables bit by bit, and return a variable
  • &, |, ^ - NOT IN EXAM

Logical Operators

  • &&
short-circuit AND The short-circuit feature of the && operator is so named because it doesn't waste
its time on pointless evaluations
  • ||
short-circuit OR
  • &
non-short-circuit AND non-short-circuit operators, they evaluate both sides
of the expression, always!
  • |
non-short-circuit OR
  • ^
exclusive-OR (XOR) EXACTLY one operand must be true ()non-short-circuit operator
  • !
boolean invert

 

Increment operator precedence (++)

  • return i++ // first returns the i value and then increments i
  • if ((i++ < 2) || i == 1) {} // in the second logical operation the i is already incremented
  • ++i or i++ only is different for the most inner logical operator where ++ is in.

Boolean

  • The constructor Boolean(String a) will result in false for null or for any string other "TRUE" or "true"

Static utilities

  • Arrays.asList(aArray) - returns a ist backed by the given array:
    • changes affects both objects
    • the list cannot grow, it's backed by a fixed length array

SCJP – Inner Classes

February 22nd, 2011

[[pageindex]]

Don't forget

  • Inner classes cannot have static methods. Exception is static inner classes.

Classes in the same file - NOT inners classes

  • not inner classes
  • there can only be one public class per .java file, as public classes must have the same name as the source file.

 

 

Inner classes (class inside a class)

  • inner class can't have static declarations of any kind

Instantiating an Inner Class

  • from Within the Outer Class
MyInner in = new MyInner();  //make sure that we are not in a static context.
  • from outside the Outer Class Instance Code
MyOuter.MyInner inner = mo.new MyInner();
or
outerObjRef.new MyInner();

Referencing the Outer Instance from Within the Inner Class

MyOuter.this   //just 'this' is a reference to the inner class
  • to access members of the outer class the syntax is as the following: Outer.this.name;

Method Local Inner Classes (class inside a method)

  • inner class can't have static declarations of any kind
  • An inner class defined inside a method cannot access the method local variables unless these local variables are final
    • this because if method ends, and the reference to the inner class stills live, the local variables are not preserved anymore
  • can see the any (private or not) member of the outer class.
  • A method-local inner class can be instantiated only within the method where the inner class is defined.
  • Inner class inside method cannot have static members or blocks

Anonymous inner classes

  • inner class can't have static declarations of any kind
  • Popcorn p = new Popcorn() {} ;        where Popcorn can be a interface or class
    • if new methods are defined they are not visible using Popcorn interface, of course.
  • semicolon at the end - because this is just an assignment with an extra class definition
  • anonymous inner classes can be declared on method and constructors and also in initilization blocks

Static Nested Classes

  • The class itself isn't really "static"; Static inner classes doesn't share any relationship with outer class.
  • new BigOuter.Nest();
  • A static inner class cannot be instantiated by an instance of the outer class
    • new Outer().new Inner()  //compilation error

Visibility

  • Inner classes are visible from the outer class, even if the inner have private modifiers
    • It's possible to invoke a private inner class constructor

Modifiers

  • For inner classes only abstract and final modifiers are allowed

SCJP – Language fundamentals

February 16th, 2011

[[pageindex]]

Don't forget

  • to look to call to a non-static context from a static context. E.g. call from main to a non-static method. Or to refer from any static method to this.
  • to check the initialization of local variables that are used for reading. In particular in main method.
  • to check if variable are initialized, other way it will give NullPointException at runtime.
  • to check it there is any missing import.
  • on System.out.print(ga.i + " " + ga.getI()); first are executed each part and only after is printed
  • a cast of null is always ok. Don't forget to check the variable current value to see if it throw a ClassCastException
  • a cast of two type not in same hierarchy give compilation error.
  • to check unreachable code: after a throw, while (false), catch block.
  • ASCII table: 123 ABC abc

Notes

  • [static] [public] [final] <return type> <method name ! attribute name>
    • static public and final can change the order in between
  • args[0].equals() in the main method will throw an ArrayIndexOutOfBound, not a NullPointException
  • abstract methods ends with ; -- non abstracts methods must have body{}
  • Identifiers can't start with a digit or characters other than '_' or '$' or letters,
    • the remaining of the identifier can contain digits, letters, '_' or '$' but not other
  • oThe escape sequences are as follows: '\b' (backspace), '\f' (formfeed, new page), '\n' (newline), '\r' (carriage return), '\t' (horizontal tab), '\\' (backslash), st'\"' (double quote), '\'' (single quote). Yes, you must memorize the escape sequences! Just remember "big farms need red tractors".
  • Invalid escape sequence (valid ones are \b \t \n \f \r \" \' \\ )
  • A method cannot be abstract and final at same time. It's the opposite.
  • Immutable objects are simply objects whose state (the object's data) cannot change after construction.
  • final classes cannot be sub classed
  • If a class is not final cannot be immutable.
  • Class1 HAS A Class2- could be indirectly by Class1 HAS A Class3 that HAS A Class2

Java Keywords

  • const
  • goto
  • instanceof - not "instance of" or instanceOf

JavaBeans

  • getters and setters must be public
  • must be named using camelCase
  • depending on the method's purpose, must start with set, get, is, add, or remove.

Constructors

  • It's possible to have a method with the same name as the constructor/class: protected void Foo() { }
  • Only public, protected, private and default (no modifier) are legal when declaring constructors
  • Foo extends Bar.
    • If Bar have a default constructor, no issues in the Foo constructor: no need no call super in the non-default constructors.
    • If Bar have only non-default constructors, the Foo have to call super(...) to invoke the parent non-default constructor
  • If you've typed in a constructor with arguments, you won't have a no-arg constructor unless you type it in yourself!
  • Every constructor has, as its first statement, either a call to an overloaded constructor (this()) or a call to the superclass constructor (super()), although remember that this call can be inserted by the compiler.
    • the call to super cannot be inside a try catch block. It must be really the first statement of the constructor.
  • The no-argument constructor provided by the compiler when no constructor is explicitly provided in the code always defaults to the access modifier provided for the class
  • No constructor calls are allowed inside a method. A constructor call (super() or this() ) must be the first statement inside a constructor.
  • Constructors can throw exception as any other method.
  • If the Super class provides a constructor that throws a checked exception, then the sub classes must define an explicit constructor that also throws the same exception or one of its super types
    • This because the all constructors (explicit or implicit) have a call to the super constructor. The super() call (explicit or implicit) must be the first line and so it's not allowed even the try/catch o catch a non handle exception thrown by the super constructor.
  • The parent class constructor must be visible: With a private constructor, the Child will give compilation error.

Initializations, Static and init blocks

  • if you try to use local variables without initialization it give compilation error.
    • if is a instance variable without initialization doesn't give compilation error, because some other method can change it.
  • final instance variable must be initialized: immediately, in all constructors or in a initialisation block.
  • variable can be initializaed using a method call. (Issue with usual static calls rules)

Initiatization order

  • Static variables/static blocks are executed, run once, when the class is first loaded.
    • first the blocks from the super class
    • file order if more than one: if a block appears first then a static variable it's initialized first
  • Instance variables are assigned default values
  • constructor runs
    • instance variables and Instance initialization blocksrun after all super-constructors and before the constructor's code has run.
      • If multiple init blocks exist in a class, they run in the order in which they appear in the source file.
    • rest of the constructor is executed

 

  • Doesn't compile if we try to use in a subclass explicit call to super(variable) a instance variable defined on the super class because the instance hasn’t been created yet.
  • If the super constructor call a method that is overriden in a subclass it works and the polymorphism works also
    • If the instance variable are not initialized yet, the default values are used
  • if a class with no main is called, it will fail with NoSuchMethodError, but it will first execute the static init block.
  • static int[] a;
    static {
    a[0] = 5;
    }
  • This wil throw a java.lang.ExceptionInInitializerError (caused by a NullPointException), because static block is trying to access to a null object: note that array a is not initialized.
    • If the assign was in a non-static init block, or in a constructor or in the main, the result was simply the NullPointException

Interfaces

  • Interface methods are implicitly public, and abstract
    • so the methods being implemented must also marked be public.
  • Interface attributes are implicitly public, static, and final : interface constants.
    • as they are final, must always be initialized on the declaration
  • No others modifiers are allowed: It's not possible to have methods protected or private
    • It's not possible to have methods static or final
  • It's allowed to declare inner classes inside a interface
  • Interface extends another interface: both can have the same method (same name) defined. And a class can implement both interfaces, and of course need to implement one only method.

Finalize and GC

  • For any given object, finalize() will be called only once (at most) by the garbage collector.
  • finalize() method ignores the throw of a runtime exception inside of it.
  • If finalize assigns the this reference to other object, it cannot be garbage collected.
    • But at second change to GC runs, it will be garbage collected anyway.
  • new Fiji().go(); //on the line bellow this object is eligible for GC
  • reference variables live on the heap
  • stack variables are not GC. they are removed when the method exists.
  • WRONG: only objects that have no reference variables can be GC. No because the islands of objects can also be GC.

Serialization

  • transient - if a variable (instance only) is marked as transient it will not be serialised
    • When the object is rebuild (via readObject), the value is the default, not the previous neither the initialized value.
      • transient int a = 5; After readObject is will be 0.
  • volatile - for instance variables only, not is exam, is not related with serialization, is related with thread-safe.
    • value is not lost during the serialization
  • The order of writing/reading fields must be the same.
  • Class fields with the modifiers static and transient will not be serialized.
  • if a superclass is not marked Serializable the data is not saved and then on rebuild the constructor is invoked
  • If a class member is not Serializable, it will skip it. No compiler error.
try {
   FileOutputStream fos = new FileOutputStream("data.txt");
   ObjectOutputStream os = new ObjectOutputStream(fos);
   os.writeObject(derived1);
   os.close();
   FileInputStream fis = new FileInputStream("data.txt");
   ObjectInputStream is = new ObjectInputStream(fis);
   Derived derived2 = (Derived) is.readObject();
   System.out.print(derived2.code);
   is.close();
} catch (Exception x) {
}

Modifiers

  • Visibility modifiers order:
    • private
    • default (package)
    • protected - this also includes package
    • public
  • outer classes could be public or abstract, or default
  • inner classes could be public, protected, private or default, as any other class member
  • abstract interface == interface
  • strictfp applies to classes, interfaces and methods
  • An abstract method cannot be marked static.
  • An abstract method can be marked protected
  • Local variables cannot have access modifiers: cannot be protected or private
  • If a method is private, the subclass can define it again, but in this case is not a override.
    • Any method call using the type reference to the super, will call the super method, the polymorphism doesn't work because isn't a override
    • The private method in the super can be final, and even that could be defined again in the subclass, because it's not visible.
  • Don't forget to see if a method is public to be access from the outside the class (different packages), even is called on a instance of the same type.
    • Same package is ok in most of the cases
  • u.do1() - to check if the visibility of the do1() allows this call, must be checked also the u object
    • if do1() is protected and in another package, in a subclass if u is the superclass it's not visible

Exceptions

  • Throwable is a class, not an interface
  • RuntimeException extends Exception extends Throwable
    • Of course a catch(Exception e) will catch also RuntimeExceptions
  • Error extends Throwable
    • so AssertionError is not catch in the catch by Exception
    • Error is a (and RuntimeException) unchecked exception
  • When there are multiple catch block, the most specific exception is caught (in the case of subclasses)
  • Pay attention to Unreachable catch block on try catch statements: if a catch that appears first catch the exception bellow, it's a unreachable block
  • finally block runs before the exception in the try block is thrown
  • protected void finalize() throws Throwable { } - is the signature of the finalize method on Object

List of Runtime Exceptions

  • ArithmeticException
  • IllegalMonitorStateException
  • IllegalThreadStateException
  • NumberFormatException extends IllegalArgumentException
  • IllegalStateException
  • IllegalArgumentException
  • almost all IllegalXXX are runtime exceptions

List of checked Exceptions

  • InterruptedException
  • ClassNotFoundException
  • ParseException

Strings

  • Any operation with strings (substring, upperCase, replace, ...) if returns the same content, it returns the same object: this.
  • Strings starts and ends with "" (empty string)
  • String are kept in a string pool, managed and limited by JVM
  • Numbers (int short, long) also have a pool until 127

Override

  • The method definition is name + arguments.
  • To override a method is must have the same name+arguments (Same type, not a subtype). Otherwise it will be an overloaded method.
  • applies ONLY to inherited methods
  • is related to polymorphism
  • object type (NOT reference variable type) determines which overridden method will be used at runtime
  • overriding method MUST have the same return type;
  • exceptions rules:
      • it must throw the same exception declared in the super class, or
      • it must throw one sub-class of the one declared in the super class, or
      • throw nothing, or
      • throw RuntimeException (unchecked exceptions)
    • this rules also are applied to interfaces
    • The existing code, prepared to catch some exception, must be valid if we override a method, and so the exception thrown must be equal or less than original (subclass or nothing)
  • overriding method MUST NOT have more restrictive access modifier, but MAYhave less restrictive one
    • the same to implement interface methods: it's a override !!
    • due to other code that calls the method, that can invoke on a polymorphic instance
  • abstract methods MUST be overridden
  • final methods CANNOT be overridden
  • static methods CANNOTbe overridden
    • but must follow all rules for overriden method, but of course that polymorphism doesn't exists.
    • even cannot be defined a non-static method with same signature in a subclass.
  • constructors CANNOT be overridden
  • declare a override method with <T> don't compile
  • method declaration with byte, short, int or char are all different, not an override.

Overload

  • if the method name + arguments are the same then it's a override and should follow the override rules
  • reference type determines which overloaded method will be used
    • the method that will be used it chosen at compile time
  • match always the most specific object. someMethod(Object o) and someMethod(String s), called with null as arg it choose String.
  • calling methods with null arg only fails with ambiguous case, when there is two overloaded methods with different args that one IS NOT the another one (IS in sense to hierarchy)
  • overloading can take place in the same class or in the subclass
  • overloaded methods MUST have a different argument list
  • overloaded methods MAY change the return type (in case argument list is different)
  • overloaded methods MAY change the access modifier
  • overloaded methods MAY throw new or broader checked excpetions
  • constructors MAY be overloaded
  • you cannot have a static method and a non-static method with the same signature
  • methods adjustment in connection with overloaded method’s arguments:
    • you cannot widen and then box (int -> Long)
    • you can box and then widen (int -> Object, via Integer)
    • you cancombine var args with either widening (byte -> int) or boxing (int -> Integer):
      • widening is over boxing
      • widening is over var args
      • boxing is over var args
  • As method arguments: String[] and String... are the same type, and then it's a duplicate
    • List<String> and String... are different types
  • You can pass values or an array to a vararg method, but not both. Ex: rest(1,{2}) rest(int ... a) //compile error
  • With tMeth(Integer... i) and tMeth(int... i) methods a call like tMeth(7) will give compilation error
    • the error in that the call is ambiguous. The error is on the call.
    • If we and a third method tMeth(int i), of course is not ambiguos anymore
  • Reference type determines which overloaded method is used at compile time.
  • Object type determines which overriden method is used at runtime.

 

Operators

  • i++ vs ++i :
    • in a for loop, the 3rd block is only compute at the end, so no matter if it's i++ or ++i
    • in a comparison ++i is evaluated first

Static

  • static variables are not serialized. They belong to the class, not to an instance.
    • The static variables current value is not kept, the value will revert to the init value.
  • Static methods can be called using an instance. Even if the instance is null.
    • It will call the method based on the object type, not object instance
  • It's not possible to have two methods with same signature, one static and another non-static.
  • A class has two methods: static void print(Integer arg) and void print(int arg)
    • To call from a (non-static block) or (in a static block but using an instance reference), only the rules for overload with boxing applies

Polymorphism

  • polymorphism to access class variables doesn't work. A classic example to show polymorphism in methods doesn't work.
  • if a instance attribute is defined both in parent and a child classes, and parent method is executed on a child instance it reads the parent attribute
  • super.aMethod - calls exactly the super method, no polymorphism here
    • this.AMethod is the same but for this
  • g.super.aMethod - compilation error
  • super.super.aMethod - compilation error

Switch

  • Switch without no break statement proceeds to the next case, even if the case doesn't match.
  • Switch only works with integer convertible (int, short, byte, char) or with enum (even with a enum literal: is a enum anyway)
    • with a enum in the switch selector, the cases could be only the values (without qualification of the enum name)
    • it's not allowed box/unbox: doesn't work with final Integer in the case instead of int
  • default don't need to be the last statement after all the cases

If Else

  • Chained "if else" statements without brackets works fine, no compilation error for ambiguous code.

For loop

for (initialization; termination; increment) {
    statement(s)
}
  • The initialization expression initializes the loop; it's executed once, as the loop begins.
  • When the termination expression evaluates to false, the loop terminates.
  • The increment expression is invoked after each iteration through the loop; it is perfectly acceptable for this expression to increment or decrement a value.
  • for(int i = 0; i<10; i++){} is the same as for(int i = 0; i<10; ++i){

Coupling, cohesion and encapsulation

Tips to check those concepts over a code snippet.

Encapsulation

  • well-encapsulated code is that methods can be re-implemented without causing side effects
  • Getters and setters are the requirement for encapsulation
    • It's not related with coupling or cohesion

Coupling

  • Loosely coupled - if there is few interface calls
  • loose coupling is when one class can change without adversely affecting the workings of classes that interact
    with it.
  • A is-a class B, or A has-a class B --- it’s possible for them to still be loosely coupled

Cohesion

  • Somewhat subjective, but look to the class where where should be placed the methods

 

Arrays

  • short [] z [][]; // It's a coorect declaration of t 3-dimension array!
  • A[] a=new C[1]{ new Test(), new D() };
    • This array, C , can accept all object that pass the IS a C
    • The reference types are A
  • A[] a=new C[1]; a[0] = new A(); (C extends A)
    • compiles Ok
    • java.lang.ArrayStoreException at runtime -
    • array instances knows their type at runtime, in opposite to the generic collection

Not related

  • Equals method defined in jre classes first check if the classes are the same! Also is they are ==
  • public int compare(T o)
  • return statement in main exits but still runs the finally. System.exit(0) exits immediately.
  • "extends" comes before "implements"
  • s.concat() will produce a new String object and will not modify the original. Strings are immutable
  • TIP: Which methods are defined for both type String and type StringBuffer?
    • equals is a correct answer, despite it is defined only in Object object and String equals is defined on String object.
  • pay attention to the unreachable code
    • while (false){unreachable code} // compilation error
    • if (false){dead code} // warning, no compilation error

Instanceof

  • instanceof with null returns false, not a NullPointExecption
    • null instanceof Number --> compiles and returns false
  • Operands of instanceof must be in the same inheritance tree. Other way it give compilation error. Only if type is a class
    • variable instanceof Type. If Type is a interface: compilation ok. Because some instance that the variable can hold, in for instance is a subclass, can implement the interface. So, this is only possible to know at runtime.

 

Labels

  • Labels must be just before a loop
  • break exits only the most inner loop
  • break <label> exists from the loop with label
  • label: statement --- 'break label' or 'continue label' must be inside the labeled statement.
    • This means that if the label is not immediately before the loop, it will not be found when referenced by the break or continue.

Assertions

  • assert(exp) - will throw an exception if exp is false
  • In a question with assert code, don't forget to check if the assertions are enabled at runtime (java -ea), other way they are ignored
  • Run old code with assert as a variable name, not yet as keyword (Java 1.3)
    • javac -source 1.3 OldCode.java
  • Enable assertions at runtime:
    • java -ea com.geeksanonymous.TestClass
    • java -enableassertions com.geeksanonymous.TestClass
    • java -ea:com.foo.Bar com.geeksanonymous.TestClass
    • java -ea -da:com.foo...
    • java -ea -dsa Enable assertions in general, but disable assertions in system classes.
  • assertion is not appropriate if: (Assert should test invariants)
    • it is testing the args of main.
    • it is testing args of public methods
    • if they change variables state

Java, Javac and jar command line

  • java -cp t.jar Test.java
  • java -classpath /home/t.jar Test
    • if we need also to run a file in the current folder we need to add the . to the classpath (only if the classpath is explicitly indicated at command line)
    • this only yo run, doesn't apply to javac

Javac

  • By default, the compiler puts a .class file in the same directory as the .java
  • -d option lets you tell the compiler in which directory to put the .class files it generates
    • javac -d classes source/MyClass.java
    • if the destination directory you specify doesn't exist, you'll get a compiler error.

Java

  • java [options] class [args]
    • java PirateTalk -DargProp="dog," // the property is ignored, must come before the class name
  • java -DmyProp=myValue MyClass x 1
    • To read the properties in java code:
      • Properties p = System.getProperties(); p.getProperty("myProp");
    • whitespaces between "" - java -DcmdProp="cmdVal take 2" TestProps

Classpath search (both for java and javac)

  • As soon as they find the class they're looking for, they stop searching for that class.
  • Search order:
    • J2SE lib folders
    • directories defined by classpaths
      • command line classpath
      • system classpath

Jar

  • jar -cf MyJar.jar myApp

Main Java packages

  • java.lang
    • 'primitive objects', String, StringBuilder, StringBuffer, Thread, main execptions and errors, Comparable
  • java.text
    • DateFormat, NumberFormat
  • java.util
    • all collections and maps interfaces and classes, related exceptions, Date, Claendar, Locale, Scanner, Comparator
  • java.util.regex
    • Matcher, Pattern
  • java.io
    • File, Stream, Writers and Reader, related exceptions, console

Imports

  • import static <package+className>.*
    • imports all static methods, constants (which are static and final), and static object references. And can be used only by name.
    • static import don't compile.

SCJP – Regex

January 31st, 2011
  • left to the right
  • the chars are consumed
  • "\d" compile error    --> escape like this: "\\d"   --> This is a metachar
  • "\." compile error    --->escape like this: "\\."   --> This is a dot, not a metachar
  • 0[xX]([0-9a-fA-F])+    -- The parentheses and "+" augment the previous find-the-hex expression by saying in effect: "Once we've found our 0x or 0X, you can find from one to many occurrences of hex digits."
  • [AB] means a A or a a B
    • [\\s\\d] - means a space or a digit

Greedy vs Reluctant quantifiers

Greedy Reluctant
* *?
? ??
+ +?

Greedy quantifiers looks to the entire source data, and right to left matches to the bigger expression.

void testSimpleGreedy() {
		System.out.println("======= testSimpleGreedy ====");
		Pattern p = Pattern.compile(".*xx");
		Matcher m = p.matcher("yyxxxyxx");
		while (m.find()) {
			System.out.println(m.start() + "-" + m.group());
		}
	}

	void testSimpleReluctant() {
		System.out.println("======= testSimpleReluctant ====");
		Pattern p = Pattern.compile(".*?xx");
		Matcher m = p.matcher("yyxxxyxx");
		while (m.find()) {
			System.out.println(m.start() + "-" + m.group());
		}
	}

Output

======= testSimpleGreedy ====
0-yyxxxyxx
======= testSimpleReluctant ====
0-yyxx
4-xyxx

Match empty string

'*' at the end of the pattern will match one time the empty string at the end!

	void testSimple2() {
		System.out.println("======= testSimple2 ====");
		Pattern p = Pattern.compile("\\w*");
		Matcher m = p.matcher("babaa2aaab");
		while (m.find()) {
			System.out.println(m.start() + "-" + m.group());
		}
	}

Output

======= testSimple2 ====
0-babaa2aaab
10-
  • group() will throw a IllegalStateExceptionif the matcher doesn't found anything
    • usually m.group is conditional to the m.find returns true, as in example above

Metacharacters

  • \d A digit
  • \s A whitespace character
  • \w A word character (letters, digits, or "_" (underscore))
  • "\s" - is a compiler error. We need to escape this character with \. "\\s" its a correct space.

SCJP – Generics

January 6th, 2011
  • Generics it's a only compile time java feature. After the bytecode generation everything works as before.
  • It's not correct to use ? on the constructor invocation, the second part. We need to make an instance of a concrete type.
    • new ArrayList<?>(); // doesn't work because it must be instantiated with a concrete type
    • new ArrayList<Set<?>>(); // It works because the type is concrete, only the inner type is generic...

 

  • Polymorphic assignments applies only to the base type, not the generic type parameter.
    • List<Animal> aList = new ArrayList<Animal>(); // yes
    • List<Animal> aList = new ArrayList<Dog>(); // no
    • The polymorphic assignment rule applies everywhere an assignment can be made. The following are NOT allowed:
      • void foo(List<Animal> aList) { } // cannot take a List<Dog>
      • List<Animal> bar() { } // cannot return a List<Dog>
  • List<Number> list1 = null;
    List<? super Integer> list2 = null;
    list2 = list1;     // compiles Ok
  • Queue<?> q1 = null;
    Queue<Integer> q2 = null;
    q1 = q2;          // compiles Ok
  •  NavigableSet<?> set = new TreeSet<Object>();
    set.add(new Object());    // compiles error
  • class Test extends ArrayList<? extends Number> {}   // compiles error
  • Wildcard syntax allows a generic method, accept subtypes (or supertypes) of the declared type of the method argument:
    • void addD(List<Dog> d) {} // can take only <Dog>
    • void addD(List<? extends Dog>) {} // take a <Dog> or <Beagle>

 

  • When using a wildcard, List<? extends Dog>, the collection can be accessed but not modified.
    • When using a wildcard, List<?>, any generic type can be assigned to the reference, but for access only, no modifications.
    • The same for a map. read only access. map.put(...)
  • List<Object> refers only to a List<Object>, while List<?> or
    List<? extends Object> can hold any type of object, but for access only.
  •  If a method returns List<? extends Chewable>
    • the return value cannot be assigned to a List<Chewable>, The compiler don't know the concrete type of the returned list. Note this is only compile time check, so doesn't matter the list that is in runtime

Issue with calling add in List <? extends E> object

The compiler never know for which type the list will be instantiated.

  • void add(Set<? extends String> set) {set.add(new String("aas")); }  // Compiler error
  • void add(Set<? extends String> set) {set.add(null); }  // OK

 

// The a variable can be assigned with a ArrayList of E
         List <? extends E> a = new ArrayList<E>;
// or with a ArrayList of A (A extends E). The compiler never knows.
         List <? extends E> a = new ArrayList<A>;

public void addNewE(E e){
   a.add(e);
 }

This doesn't work because the object a could be instantiated with, for instance, new ArrayList<A> , when A extends E. So, when we are trying to invoke the the add method on List object, it is typified with T, that is the same T in add method parameter, and so we never know if the list if a list of E or a list of A, and for that the compiler gives an compiler error.

  • You can pass a generic collection into a method that takes a non-generic collection, but the results may be disastrous. The compiler can't stop the method from inserting the wrong type into the previously type safe collection.
    • If the method tries to add something to the collection, the compiler you raise a warning: potentially "unsafe".
  • The wildcard keyword extends is used to mean either "extends" or "implements.

 

 Issue with calling add in List <? super E> object

  • List<? super Number> queue6 = new ArrayList<Object>();       queue6.add(new Integer(1));
    • with any type that IS a Number of course that works.
  • List<? super Number> queue7 = new ArrayList<Object>();      queue7.add(new Object());
    • with any type super than Number doesn't work because queue7 could be instantiated with, for instance, ArrayList<Number>

Method override

class Parent {
   void say(List<String> list) {
       System.out.println("parent");
   }
}
class Child extends Parent {
   void say(List<Integer> list) {
      System.out.println("child");
}
This is a method override, but doesn't compile because must be a List of the same type.
  • my instanceof T (T is a generic type definition)
    • Cannot perform instanceof check against type parameter T.
      • Use instead its erasure Object instead since further generic type information will be erased at runtime
  • private T[] array = new T[7];   //T is a generic type. Cannot create a generic array of T. It's not possible to use generic type on constructor side.
  • It's possible to subclass a generic class, putting the type on the extends statement, and so the subclass is just a plain non- generic class. Here we can put all code that depends on the type.
    • Generics is not for the need of different implementation for the classes, it's for when we can have the same code dealing with different classes.

Warnings

  • List<String> lst1=new Vector();     //compiles OK, warnings
  • List lst2=new Vector<String>();     //compiles OK, no warnings
  • List<?> queue4 = new ArrayList();  //ok -  No compile error. With warnings.
  • NavigableSet<? extends Object> set1 = new TreeSet<Object>();        set1.add(new Object());
    • Doesn't work because compiler doesn't know the type of set1. For instance, if the type is TreeSet<String>, the compiler don't let us to add anything don't know it and you could try to add Integers: the variable definition lets

SCJP – Java Collections Cheat Sheet

December 27th, 2010

This is just a compilations of some notes together with my own notes during the preparation for SCJP exam. I expect to be the first post on the same subject, one for each chapter or topic.
[[pageindex]]

 

Interfaces

Implementations

Implementations
Hash Table Resizable Array Balanced Tree Linked List Hash Table + Linked List
Interfaces Set HashSet TreeSet LinkedHashSet
List ArrayListVector LinkedList
Map HashMapHashtable TreeMap LinkedHashMap

Read the rest of this entry »

SCJP – Study Resources

December 27th, 2010

Books:


Here are the linkroll for my saved bookmarks on delicious, filtered by scjp (Sun Certified Java Programmer). The links to mock exams and other practice exercises marked with mock tag.