- An enum specifies a list of constant values that can be assigned to a particular type.
- An enum is NOT a String or an int; an enum constant's type is the enum type. For example, WINTER, SPRING, SUMMER, and FALL are of the enum type Season.
- An enum can be declared outside or inside a class, but NOT in a method.An enum declared outside a class must NOT be marked static, final, abstract, protected, or private.
- Enums can contain constructors, methods, variables, and constant class bodies.
- enum constants can send arguments to the enum constructor, using the syntax BIG(8), where the int literal 8 is passed to the enum constructor.
- enum constructors can have arguments, and can be overloaded.
- enum constructors can NEVER be invoked directly in code. They are always called automatically when an enum is initialized.
- The semicolon at the end of an enum declaration is optional.
Wednesday, December 31, 2008
Enums
Sunday, December 21, 2008
Coupling and cohesion
"Cohesive means that a certain class performs a set of closely related actions. A lack of cohesion, on the other hand, means that a class is performing several unrelated tasks. Though lack of cohesion may never have an impact on the overall functionality of a particular class or of the application itself the application software will eventually become unmanageable as more and more behaviours become scattered and end up in wrong places."
"Whenever one object interacts with another object, that is a coupling. In reality, what you need to try to minimise is coupling factors. Strong coupling means that one object is strongly coupled with the implementation details of another object. Strong coupling is discouraged because it results in less flexible, less scalable application software. However, coupling can be used so that it enables objects to talk to each other while also preserving the scalability and flexibility."
"In OO programming, coupling is unavoidable. Therefore, the goal is to reduce unnecessary dependencies and make necessary dependencies coherent."
Java Date
Date and time, An essential factor in a program for implementing many concepts at real-time. Java provides a special class – date Class in the java.util Package (sort of catch-all for handy utilities).
Date provides methods for examining and manipulating date and time. Time in java is measured in milliseconds since January 1, 1970. Java attempts to handle time from the system with which it is interfacing. UTC is coordinated Universal Time, which seems to be the worldwide standard.
Note : In the date class, dates before January 1, 1970 are generally not usable.
List of the methods to see full scope of the Date class:
Methods | Purpose |
UTC(int, int, int, int, int) | Calculates a UTC value from YMDHMS |
after(Date) | check whether this date comes after the specified date |
before(Date) | Checks whether this date comes before the specified date |
equals(Object) | Compares this object against specified object |
getDate() | Returns the day of the month |
getDay() | Returns the day of the week |
getHours() | Returns the hour |
getMinutes() | Returns the minute |
getMonth() | Returns the month |
getSeconds() | Returns the seconds |
getTime() | Returns the time in milliseconds since the epoch |
getTimezoneOffset() | Returns the time zone offset in minutes for the current locale that is appropriate for this time |
getYear() | Returns the year after 1900 |
hashCode() | Compares a number that is used when storing objects in hash tables. |
parse(String) | given a string representing a time, parses it and returns the time value. |
setDate(int) | Sets the date |
setHours(int) | Sets the hour |
setMinutes(int) | Sets the minute |
setMonth(int) | Sets the month |
setSecondsint() | Sets the seconds |
setTime(int) | Sets the time |
setYear(int) | Sets the year |
toGMTString() | Converts a date to string object, using the internet GMT conversions. |
toLocalString() | Converts a date to string object, using the locale conversions. |
toString() | Converts a date to string object, using UNIX conversions. |
It is important to remember that months start with 0, which is January, and end with 11, which is December. The days of the week also start with 0, which is Sunday, and go through 6, which is Saturday. Dates of the month are normal.
Tuesday, December 9, 2008
Find Bugs in Java Programs
FindBugs program which uses static analysis to look for bugs in Java code. It is free software, distributed under the terms of the Lesser GNU Public License. The name FindBugs™ and the FindBugs logo are trademarked by The University of Maryland. As of July, 2008, FindBugs has been downloaded more than 700,000 times.
FindBugs requires JRE (or JDK) 1.5.0 or later to run. However, it can analyze programs compiled for any version of Java. The current version of FindBugs is 1.3.6, released on 12:34:14 EST, 13 November, 2008.Additional open source projects
The following software is being made available by the University of Maryland and the FindBugs project. The software is still preliminary, and needs volunteers to help mature it.
- Multithreaded test case, a framework designed to make it easy to create test cases for concurrent software in which multiple threads must coordindate their activity to perform a test (e.g., testing a concurrent blocking queue, with one thread that blocks when it trys to add to a full queue, and another thread that unblocks the first by removing an element).
- Checked uncontended lock, an implementation of the Java 5 Lock and ReadWriteLock interfaces that throw exceptions if they detect lock contention. These locks are designed to be used for debugging, and can be used in places where you don't believe you need to use a lock but want to verify that at runtime.
Monday, December 8, 2008
Garbage collection
The garbage collector first performs a task called marking. The garbage collector traverses the application graph, starting with the root objects; those are objects that are represented by all active stack frames and all the static variables loaded into the system. Each object the garbage collector meets is marked as being used, and will not be deleted in the sweeping stage.
The sweeping stage is where the deletion of objects take place. There are many ways to delete an object: The traditional C way was to mark the space as free, and let the allocator methods use complex data structures to search the memory for the required free space. This was later improved by providing a defragmenting system which compacted memory by moving objects closer to each other, removing any fragments of free space and therefore allowing allocation to be much faster:
For the last trick to be possible a new idea was introduced in garbage collected languages: even though objects are represented by references, much like in C, they don’t really reference their real memory location. Instead, they refer to a location in a dictionary which keeps track of where the object is at any moment.
Fortunately for us - but unfortunately for these garbage collection algorithms - our servers and personal computers got faster (and multiple) processors and bigger memory capacities. Compacting memory areas this large often was very taxing on the application, especially considering that when doing that, the whole application had to freeze due to the changes in the virtual memory map. Fortunately for us though, some smart people improved those algorithms in three ways: concurrency, parallelization and generational collection.
Sunday, December 7, 2008
Know thy acronyms
Just for fun, while eating lunch (yeah I know it's bad habit) I compiled a list off the top of my head of what an average developer might be subjected to, when tracking technologies in the Java space.
- AWT - Abstract Window Toolkit (UI)
- BGGA - Gilad Bracha, Neal Gafter, James Gosling, and Peter von der Ahe (Closures)
- CICE - Concise Instance Creation Expressions (Closures)
- EAR - Enterprise ARchive (Packaging)
- EDT - Event Dispatching Thread (Lingo)
- EJB - Enterprice Java Beans (Packaging/technology)
- FCM - First Class Methods (Closures)
- JAR - Java ARchive (Packaging)
- JAX-RPC - Java API for Xml-based Remote Procedure Call
- JAX-RS - The Java API for RESTful Web Services
- JAX-WS - Java API for Xml-based Web Services
- JAXB - Java Archtecture for Xml Binding
- JAXP - Java API for Xml Processing
- JCK - Java Compatibility Kit
- JCP - Java Community Process
- JDBC - Java DataBase Connector
- JDK - Java Development Kit
- JDO - Java Data Objects
- JDOM - Java Document Object Model
- JEE - Java Enterprise Edition
- JLS - Java Language Specification
- JME - Java Micro Edition
- JMM - Java Memory Model
- JMS - Java Messenging Service
- JMX - Java Management Specification
- JNDI - Java Naming and Directory Interface
- JNI - Java Native Interfacing
- JNLP - Java Network Launch Protocol
- JPA - Java Persistency API
- JPQL - Java Persistency Query Language
- JRE - Java Runtime Environment
- JRO - Java Runtime Object
- JSE - Java Standard Edition
- JSF - Java Server Faces
- JSP - Java Server Pages
- JSR - Java Specification Request
- JSTL - JavaServer Pages Standard Tag Library
- JTA - Java Transaction API
- JTS - Java Transaction Service
- JVM - Java Virtual Machine
- JWS - Java Web Start (Deployment)
- JXTA -Juxtapose (Peer-2-Peer)
- NIO - New Input/Output API
- NPE - NullPointerException (Lingo)
- POJO - Pure Old Java Object (Lingo)
- RT - Runtime (rt.jar, the JRE)
- SAF - Swing Application Framework (JSR-296)
- SOP - System.out.print (Lingo)
- SWT - Standard Widget Toolkit (UI)
- StAX - Pull-parsing XML
- WAR - Web ARchive (Packaging)
The amount of acronym soup is staggering. No wonder people are sometimes overwhelmed.
NetBeans plugin: Special copy/paste
Special copy/paste
The plugin will add a couple of new actions to the context-sensitive popup-menu of the source editor, which will allow you to copy the selected text as preformatted HTML, as well as a CSS version which will preserve the formatting used in NetBeans.
Using the "Copy as HTML and CSS" menu as in the above screen dump will result in you being able to paste it directly into a website/wiki/blog and have it display like this:
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
}
For a larger example of what the output of the plugin looks like, take a look at the plugin's own source code.It's supposed to be language agnostic, in that it should work with all types of sources NetBeans is able to tokenize. The plugin will try to mimic the formatting of the tokens in regard to font family, keyword and literal colors. It will however *not* be able to show member-wide variables in green as NetBeans does nor show method and class decelerations in bold. This is a limitation caused by the fact that I am only using the NetBeans lexer API rather than doing any kind of semantic analysis or parsing.
If you want to give the plugin a try, download it from NetBean's Plugin Portal. Source code is available here.
Update:
It has been made clear to me through the comments, that NetBeans already contains functionality to extract source code as HTML. You can find the feature in the "File" menu under the ill named item "Print to HTML". Since it would appear other people than just me did not associate "print" with that of exporting HTML content, I have filed an issue for the relocation and/or renaming of this.
@SuppressWarnings-Unchecked
Meta-data and how to associate it has always been a bit of a confusing topic in Java. For instance, the transient modifier is really a kind of marker annotation, as is the @deprecated javadoc tag compilers are also required to process, as is the marker interface Serializable. Then in JDK 1.5, a dedicated annotation facility was added, probably in light of the success of C#'s attributes. One of the first practical uses of annotations appears to be as a way to suppress compiler warnings.
@SuppressWarnings
This build-in annotation allows the developer to signal a respecting compiler that it should forgo a particular warning. It can be applied in front of a type, a field, a method, a parameter, a constructor as well as a local variable. It is up to the compiler to make sense of whatever you put inside the String, the only value mandated by the JLS is the "unchecked". Compilers as well as IDE's will typically implement each their own set of warning types, the Eclipse IDE defines far more of these than NetBeans does for instance.
Here I will only cover the ones supported by the SUN compiler. To see the supported types, issue a "javac -X" command. On my JDK1.6.0_03 system I get:
Of those ones, "all", "empty", "path" and "overrides" doesn't seem to have any effect when using the SUN compiler or when used inside NetBeans. The following lists the remaining ones and how to use them.
-Xlint:{all,cast,deprecation,divzero,empty,unchecked,
fallthrough,path,serial,finally,overrides}
@SuppressWarnings("deprecation")
Use this when you are deliberately using a deprecated method, realizing full well that your code might one day break, but you do not wish to be notified of this. In the following example, we use getYear of java.util.Date which has been deprecated:
@SuppressWarnings("deprecation")Without suppressing the warning, the compiler (if invoked with -Xlint:deprecation) would've complained:
public void suppressWarningsTest()
{
Date date = new Date();
int year = date.getYear();
}
warning: [deprecation] getYear() in java.util.Date has been deprecated
int year = date.getYear();
@SuppressWarnings("unchecked")
Java 1.5 brought a crippled, but mostly working generics facility into play. This of course vastly improves type-safety. However, you often need to mix non-generic and generic types and this usually provoked the compiler into complaining. Take the following example:
Without suppresssing the warning, the compiler (if invoked with -Xlint:unchecked) will complain with something like:
@SuppressWarnings("unchecked")
public void uncheckedTest()
{
List nonGenericStringList = new ArrayList();
nonGenericStringList.add("Some string");
ListgenericStringList = (List )nonGenericStringList;
}
@SuppressWarnings("fallthrough")
warning: [unchecked] unchecked call to add(E) as a member of the raw type java.util.List
nonGenericStringList.add("Some string");
warning: [unchecked] unchecked cast
found : java.util.List
required: java.util.List
List genericStringList = (List)nonGenericStringList;
Java has always followed the C-style of switch statements, where you need to explicititly break out of a switch unless you wish to simply fall through and execute the code in the case below. This can be dangerous of cousee and errors of this kind can be very hard to track down. In the following example, case 1 lacks a break:
@SuppressWarnings("fallthrough")Without suppresssing the warning, the compiler (if invoked with -Xlint:fallthrough) will complain with something like:
public void fallthroughTest(int i)
{
switch (i)
{
case 1:
// Execute both 1 and 2
case 2:
// Execute only 1
}
}
warning: [fallthrough] possible fall-through into case
case 2:
@SuppressWarnings("serial")
To ensure a serialized class is consistent with how the Java runtime perceives this object (based on its class definition), it is important that serialVersionUID be present. In practice, most people rely on the compiler to insert an appropriate UID:
Without suppressing this warning, the compiler (if invoked with -Xlint:serial) will complain with something along the following lines:
@SuppressWarnings("serial")
class Serialest implements Serializable
{
}
@SuppressWarnings("finally")
warning: [serial] serializable class SerTest has no definition of serialVersionUID
class SerTest implements Serializable
Since try-finally blocks are really glorified goto instructions, the compiler can be instructed to complain if it sees a violation of "good practice" when it comes to execution flow. In the following example we issue a return from within a finally. The compiler allows this, since the JLS specifies a finally clause will always get executed, but realize that any exception thrown in the try may be completely disregarded:
@SuppressWarnings("finally")Without suppressing this warning, the compiler (if invoked with -Xlint:finally) will complain with something along the following lines:
public String finallyTest(String str)
{
try
{
str+=".";
}
finally
{
return str.toUpperCase();
}
}
warning: [finally] finally clause cannot complete normally
@SuppressWarnings("divzero")
This can be used to catch explicit integer division by 0. It should be default in my opinion, since the compiler KNOWS that executing the code will always result in a a java.langArithmeticException. The annotation has no effect on double's or float's, since these can represent infinity:
Without suppressing this warning, the compiler (if invoked with -Xlint:divzero) will complain with:
@SuppressWarnings("divzero")
public void divzeroTest()
{
long l = 12l/0;
}
warning: [divzero] division by zero
long l = 12l/0;
Thursday, December 4, 2008
JavaPhone API
The JavaPhone API is a vertical extension to the PersonalJava platform developed through an open process between Sun Microsystems and key leaders in the telecommunications industry. Combined with the PersonalJava platform, the JavaPhone API provides an ideal environment allowing the safe delivery of dynamic information services on telephony devices.
The API is designed to provide access to the functionality unique to client telephony devices such as wireless smartphones and Internet screenphones. This functionality includes:
- Direct telephony control
- Datagram messaging
- Address book and calendar information
- User profile access
- Power monitoring
- Application installation
The JavaPhone API allows device manufacturers to shorten development cycles and improve the quality of their products through the use of prebuilt software components on a stable deployment platform. The API also broadens the market for content providers by providing portability across a wide number of telephony devices. Finally, the JavaPhone API allows network operators to dynamically deliver new types of applications and value-added services to a variety of telephony devices, lowering operation costs and increasing customer loyalty.
J2ME Core Concepts
Configurations
A configuration is a complete Java runtime environment, consisting of three things:
* A Java virtual machine (VM) to execute Java bytecode.
* Native code to interface to the underlying system.
* A set of core Java runtime classes.
To use a configuration, a device must meet certain minimum requirements as defined in the configuration's formal specification. Although a configuration does provide a complete Java environment, the set of core classes is normally quite small and must be enhanced with additional classes supplied by J2ME profiles or by configuration implementor. In particular, configurations do not define any user interface classes.
J2ME defines two configurations, the Connected Limited Device Configuration (CLDC) and the Connected Device Configuration (CDC). The CLDC is for very constrained (limited) devices -- devices with small amounts of memory and/or slow processors. The VM used by the CLDC omits important features like finalization, while the set of core runtime classes is a tiny fraction of the J2SE core classes, just the basics from the java.lang, java.io and java.util packages, with a few additional classes from the new javax.microedition.io package. The CDC, on the other hand, includes a full Java VM and a much larger set of core classes, so it requires more memory than the CLDC and a faster processor. The CDC is in fact a superset of the CLDC. We'll discuss the configurations in detail in the next two articles in this series.
Profiles
A profile adds domain-specific classes to a configuration to fill in missing functionality and to support specific uses of a device. For example, most profiles define user interface classes for building interactive applications.
To use a profile, the device must meet all the minimum requirements of the underlying configuration as well as any additional requirements mandated by the profile's formal specification.
There are several profiles in various stages of development. The first profile to be released was the Mobile Information Device Profile (MIDP), a CLDC-based profile for running applications on cellphones and interactive pagers with small screens, wireless HTTP connectivity, and limited memory. Another CLDC-based profile under development is the Personal Digital Assistant Profile (PDAP), which extends MIDP with additional classes and features for more powerful handheld devices. In terms of CDC-based profiles, the Foundation Profile (FP) extends the CDC with additional J2SE classes, the Personal Basis Profile (PBP) extends the FP with lightweight (AWT-derived) user interface classes and a new application model, and the Personal Profile extends the PBP with applet support and heavyweight UI classes. We'll also be discussing these profiles later on in this series.
Optional Packages
An optional package is a set of APIs in support of additional, common behaviors that don't really belong in one specific configuration or profile. Bluetooth support, for example, is defined as an optional package. Making it part of a profile wouldn't work, because none of the behaviors of a profile can be optional -- if a device supports a profile, it must support the entire profile -- and that would limit the profile to Bluetooth-enabled devices.
Optional packages have their own minimum requirements, of course, just like configurations and profiles. Optional packages also have specific dependencies on a particular configuration and/or one or more profiles -- they do not define a complete runtime environment, just sets of related APIs.
There are many optional packages in development, including the RMI Optional Package, which adds RMI support to CDC/FP-based profiles, the Java APIs for Bluetooth, which adds Bluetooth support to CLDC-based profiles, and the JDBC Optional Package for CDC/Foundation Profile, which defines a subset of JDBC (database access APIs) for use with CDC/FP-based profiles. Again, we'll be covering these later on in the series as the need arises.
Wednesday, December 3, 2008
Overview of J2EE
Why use J2EE
J2EE may not be the perfect choice for developing enterprise applications. You should consider other alternatives before deciding to use J2EE. Some advantages of using J2EE for enterprise applications are listed below:
• Low level services are already implemented
An enterprise application needs to implement very complex services to be successful. Some of those services are transaction and state management, resource pooling and multi-threading. J2EE architecture separates those low level services from the application logic. Since all those services are implemented by applications servers, you can save a lot of time if you need those services.
• J2EE is well documented and understood
J2EE is developed by a consortium formed by several major companies in the industry. For more information on this consortium you can search for “Java Community Process” (see links section)
• J2EE is a standardized and reliable software architecture
Using standardized and reliable software architecture in your development will most likely decrease your future costs and ensure longevity of your applications.
• J2EE gives you a lot of flexibility
Once you develope your application with J2EE, you can deploy it wherever you need to. You can deploy your application to any application server with small changes.
• APIs used in J2EE are well documented.
Several APIs are used to implement low level details of enterprise applications. Since those APIs are already written and well documented, this will save you a lot of time.
J2EE Platform Architecture
J2EE platform uses a multi-tiered distributed application model. Application logic is divided into components and each component is installed on a specific machine based on which tier that component resides.
Figure-1 J2EE Application Model
As you can see from the Figure-1, there are four tiers in J2EE application model: client tier, web tier, business tier and enterprise information system (EIS) tier. Business and web tiers are generally existed in a server application called application server or J2EE server. Application server provides complex services needed by components in business and web tiers.
Figure-2 Interaction between client, web and business tiers in J2EE
Client tier can have two types of components: web client or application client. Web clients access the components in the web tier namely servlets or java server pages (jsp). Web browsers as a web client are generally used to access web tier components.Application clients are standalone applications that do not run in browsers (e.g. swing application). They directly accesses to the components in the business tier.
Figure-3 Business and EIS tiers
Figure-3 shows Business and EIS tiers in detail. EIS tier contains database and legacy systems and can be accessed from the business tier.There are three types of components in business tier: entity beans, session beans and message-driven beans. We will discuss them separately in detailed subsequent tutorials.
Another important concept in J2EE architecture is the “container” concept. An enterprise application needs to implement very complex services to be successful. Some of those services are transaction and state management, resource pooling and multi-threading. J2EE architecture separates those low level services from the application logic by implementing those services in containers. So, web containers are mainly used to provide low level services to web components (e.g. servlet) or EJBs (e.g. entity beans) Containers are also used to manage execution of the components in business tier. Figure-4 may demystify this idea more.Figure-4 J2EE Application Server and Containers
Introduction of Enums
Type safe enum was long awaited feature in Java language. It has been introduced in Java 5.
To represent a constant custom type there was no way except definition String or int constant literals like
public static final String DAY_MONDAY = “Monday”;public static final String DAY_TUESDAY = “Tuesday”;
But now with the introduction of enums in Java, there is a type safe and standard mechanism of defining custom types for multiple values.
Example:
enum DAY { MONDAY, TUESDAY }This way, Monday and Tuesday are no longer String literals and also String operations cannot be performed on them (which are actually not required).
New Convenient for Loop
The “for” loop in Java language has been enhanced to iterate through collections. Here is the example how it works with collections.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
/*Old way of iterating through collections*/;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
void oldForLoop(Collection
.....for (Iterator<> i = c.iterator(); i.hasNext(); );;;;;;;;;;;;;;;;
..........if (i.next().intValue() == 4);;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
..........i.remove();;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
}..........;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
/* New way of iterating through collections*/;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
void newForLoop(Collection
.....for (Integer i : c);;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
..........if (i.next().intValue() == 4);;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
..........i.remove();;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
}.....;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
If you notice here, to iterate through a collection using a “for” loop has been very simple now. Prior to this, most time Iterator and Enumerator classes were used to iterate through collection objects. And in most implementations people need to iterate through collection objects.
This new implementation also helps in avoiding NoSuchElementException at run time. It also makes the code more readable and maintainable.Tuesday, December 2, 2008
Assertion
- Declare an assertion
You declare assertions with a new Java language keyword, assert. An assert statement has two permissible forms:
assert expression1;
assert expression1 : expression2;
In each form, expression1 is the boolean-typed expression being asserted. The expression represents a program condition that the developer specifically proclaims must be true during program execution. In the second form, expression2 provides a means of passing a String message to the assertion facility. The following are a few examples of the first form:
assert 0 < value;
assert ref != null;
assert count == (oldCount + 1);
assert ref.m1(parm);
The asserted expression must be of type boolean, which the first three expressions obviously are. In the fourth expression, the method call m1(parm) must return a boolean result. A compile-time error occurs if expression1 does not evaluate to type boolean.
- Enable assertions
Command-line options to the java command allow enabling or disabling assertions down to the individual class level. The command-line switch -enableassertions, or -ea for short, enables assertions. The switch (I use the short form) has the following permissible forms:
-ea
-ea:
-ea:...
-ea:...
- Class AssertionError
The new assertion facility adds the class AssertionError to the java.lang package. AssertionError contains a default constructor and seven single-parameter constructors. The assert statement's single-expression form uses the default constructor, whereas the two-expression form uses one of the seven single-parameter constructors.
To understand which AssertionError constructor is used, consider how assertions are processed when enabled:
Evaluate expression1
If true
No further action
If false
And if expression2 exists
Evaluate expression2 and use the result in a single-parameter form of the AssertionError constructor
Else
Use the default AssertionError constructor - Since the assert statement in class Foo uses the single-expression form, the violation triggered in passing -1 to method m1(int) prompts the use of the default AssertionError constructor. The default constructor effectively uses java.lang.Throwable's default constructor to print an exception message that includes a textual stack trace description.
Overview of covariance/contravariance in Java
Generics were introduced in Java in Java 5.0 to allow type-safe generic programming. Unlike arrays, generic classes are neither covariant nor contravariant. For example, neither List
List
a.add("foo");
// b is a List of Object
List
However, generic type parameters can contain wildcards (a shortcut for an extra type parameter that is only used once). Example: Given a requirement for a method which operates on Lists, of any object, then the only operations that can be performed on the object are those for which the type relationships can be guaranteed to be safe.
List
a.add("foo");
// b is a List of anything
List b = a;
// retrieve the first element
Object c = b.get(0); // This is legal, because we can guarantee that the return type "?" is a subtype of Object
// Add an Integer to b.
b.add(new Integer (1)); // This is a compile-time error; we cannot guarantee that Integer is a subtype of the parameter type "?"
Wildcards can also be bound, e.g. "? extends Foo" or "? super Foo" for upper and lower bounds, respectively. This allows to refine permitted performance. Example: given a List, then an element can be retrieved and safely assigned to a Foo type (contravariance). Given a List, then a Foo object can be safely added as an element (covariance).