Category Archives: Java

Inner Classes

Inner Classes are the classes which are declared inside an outer class i.e classes nesting with in outer class. They can be either static or non static. Static Inner classes are also called as Nested Classes. Inner classes come in Four flavors namely:
Inner Classes

1. Static Member Classes
2. Member Classes
3. Local Classes
4. Anonymous classes

Continue reading

Advertisements

Book Review: Head First Java

Book: Head First Java (Website)Head First Java

Authors: Kathy Sierra, Bert Bates

There are many people around aspiring to learn Java- One of the most powerful OO Languages. But Alas!!!! how to go about the learning process??? Which book is suited for my style of learning??? All these questions pop in one’s mind. Even they were my questions once upon a time. But thanks to my tutor friend who introduced me to Head First Java. Head First Java is one of the books in Head First Series.

The book has everything in it. It is a must read book for any beginner in Java programming. But the reader must have certain programming background i.e the reader must be familiar with either C or the Object Oriented concepts pf C++. The author runs through the initial few chapters which will be sort of revision for programmers with C++ background. The Java concepts are explained in the best possible way. They are explained in such a way that reader will be in a position to explain the same to others. There are nice exercises at the end of each chapter and some brain ticking questions in the chapter. The author has used visual aids in explaining the concepts. The book is more unorthodox in its presentation with more amount of images than text. Initially the reader my find that the book is not serious regarding the concepts but this book is best for starters. It has just what is required for beginners to know. Its not just theory, the author has also given code examples and has also during the course of the book designed one complete software package and also designed some small applications which i feel will help the reader in long way. The exercises are not mere answer the following questions but they include Crossword puzzles – aimed at puzzlers, match the following, find the errors, find the output, fill in the blanks and some mystery related questions.

I think no matter how much i write here but i don’t think one can actually feel the book’s benefits until one reads the book. Its a must for all Java beginners and must for the shelf of Java Programmer.

Know more about Head First Formula here

Interface Vs Abstract Class

There are three differences between an interface and an abstract class:

  • you can implement multiple interfaces at the same time, but only extend one class,
  • an abstract class is allowed to contain implementation (non-abstract methods, constructors, instance initializers and instance variables) and non-public members, and
  • abstract classes may be a tiny bit faster (or they may not.)

Actually the first point is the reason for the existence of interfaces in Java: to provide a form of multiple inheritance. In languages with multiple implementation inheritance, an interface would be equivalent to a fully abstract class (a class with only public abstract members).

The above differentiation suggests when to use an abstract class and when to use an interface:

  • use an abstract class, if you want to provide common implementation to subclasses,
  • use an abstract class, if you want to declare non-public members,
  • use an abstract class, if you want to be free to add new public methods in the future,
  • use an interface if you’re sure the API is stable for the long run
  • use an interface if you want to provide the implementing classes the opportunity to inherit from other sources at the same time.

In general, prefer interfaces if you don’t need to use an abstract class, because they provide more design flexibility.

Resources:
MindProd

Source: JavaRanch

Call By Reference and Call By Value

Java always makes a copy of the argument and passes the copy. The called method has a local copy of the data. If the method changes the data it changes the copy, so the original value is not changed. When we pass a primitive like int this make perfect sense. The method gets its own int variable, a copy of the original.

When we pass an object we have to think very precisely. The value that is copied and sent along is a reference or pointer to the object. The method gets its own copy of the pointer, but it doesn’t get its own copy of the object. If the method changes its copy of the pointer to point to a different object the original pointer is not affected. If the method changes some of the attributes of the object, it changes the original object.

In short in java, object references are passed by reference and primitive types are passed by value.

Source: JavaRanch

Overriding v/s Hiding

Many people have heard that you can’t override a static method. This is true – you can’t. However it is possible to write code like this:

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 is

instanceMethod() in Bar
classMethod() in Foo

Why 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 (drum roll please…) 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.

With classMethod() though. since (ahem) 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. Barring that, you could always come up with this monstrosity:

f.getClass().getMethod(“classMethod”, new Class[]).invoke(f, 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”.

Source: JavaRanch

Java Technology: Part-1

Java Technology:

Java technology is both a high-level, object-oriented programming language and a platform. Java technology is based on the concept of a single Java Virtual Machine (JVM) — a translator between the language and the underlying software and hardware. All implementations of the programming language must emulate the JVM, enabling Java programs to run on any system that has a version of the JVM.

The Java programming language is unusual because Java programs are both compiled (translated into an intermediate language called Java bytecode) and interpreted (bytecode parsed and run by the JVM). Compilation occurs once, and interpretation happens each time the program runs. Compiled bytecode is a form of optimized machine code for the JVM; the interpreter is an implementation of the JVM.

The Java platform is a software-only platform that runs on top of various hardware-based platforms. It comes in three versions (see Multiple editions of the Java platform, below). It consists of the JVM and the Java Application Programming Interface (API), a large collection of ready-made software components (classes) that ease the development and deployment of applets and applications, including robust, secure, and interoperable enterprise applications. It spans everything from basic objects to networking and security and XML generation and Web services. The Java API is grouped into libraries of related classes and interfaces; the libraries are known as packages.

Along with the Java API, every full implementation of the Java platform includes:

  • Development tools for compiling, running, monitoring, debugging, and documenting applications.
  • Standard mechanisms for deploying applications to users.
  • User interface toolkits that make it possible to create sophisticated graphical user interfaces
  • Integration libraries that enable database access and manipulation of remote objects.

Java technology was developed by Sun Microsystems. The Java Community Process (JCP), an open organization of international Java developers and licensees, develops and revises Java technology specifications, reference implementations, and technology compatibility kits. In 2007, Sun made the bulk of its core Java technology available as open-source software under the GNU general public license version 2 (GPLv2).

Source : IBM DeveloperWorks

Java Programming Style Guide

Introduction

The Java language gives you all the room you need to write code that would be very difficult for others to understand. Java also permits you to write code that is very easy to understand. Most development teams would prefer the latter.

A style guide provides provides a map so that the code generated by a group of programmers will be consistent and, therefore, easier to read and maintain. Many people do not care for the style guide offered by Sun. This document is one alternative.

This document covers most areas where there could be confusion or difference of opinion. Areas that have never been a problem in our experience are undocumented.

1 – Formatting

1.1 – Indentation

  • All indents are four spaces. All indenting is done with spaces, not tabs.
  • Matching braces always line up vertically in the same column as their construct.
  • All if, while and for statements must use braces even if they control just one statement.

1.2 – Spacing

  • All method names should be immediately followed by a left parenthesis.
  • All array dereferences should be immediately followed by a left square bracket.
  • Binary operators should have a space on either side.
  • Unary operators should be immediately preceded or followed by their operand.
  • Commas and semicolons are always followed by whitespace.
  • All casts should be written with no spaces.
  • The keywords if, while, for, switch, and catch must be followed by a space.

1.3 – Class Member Ordering

class Order
{
// fields

// constructors

// methods
}

1.4 – Maximum Line Length

Avoid making lines longer than 120 characters.

1.5 – Parentheses

Parentheses should be used in expressions not only to specify order of precedence, but also to help simplify the expression. When in doubt, parenthesize.

2 – Identifiers

All identifiers use letters (‘A’ through ‘Z’ and ‘a’ through ‘z’) and numbers (‘0’ through ‘9’) only. No underscores, dollar signs or non-ascii characters.

2.1 – Classes and Interfaces

All class and interface identifiers will use mixed case. The first letter of each word in the name will be uppercase, including the first letter of the name. All other letters will be in lowercase, except in the case of an acronym, which will be all upper case.

2.2 – Packages

Package names will use lower case characters only. Try to keep the length under eight (8) characters. Multi-word package names should be avoided.

2.3 – All Other Identifiers

  • All other identifiers, including (but not limited to) fields, local variables, methods and parameters, will use the following naming convention. This includes identifiers for constants.
  • The first letter of each word in the name will be uppercase, except for the first letter of the name. All other letters will be in lowercase, except in the case of an embedded acronym, which will be all uppercase. Leading acronyms are all lower case.
  • Hungarian notation and scope identification are not allowed.
  • Test code is permitted to use underscores in identifiers for methods and fields.

3 – Coding

3.1 – Constructs to Avoid

  • Never use do..while.
  • Never use return in the middle of a method.
  • Never use continue.
  • Never use break other than in a switch statement.

3.2 – Do Not Compound Increment Or Decrement Operators

  • Use a separate line for an increment or decrement.
  • Never use pre-increment or pre-decrement

3.3 – Initialization

Declare variables as close as possible to where they are used.

3.4 – Access

All fields must be private, except for some constants.

4 – Self-Documenting Code

“Any fool can write code that a computer can understand. Good programmers write code that humans can understand.”

— Martin Fowler, Refactoring: Improving the Design of Existing Code

Rather than trying to document how you perform a complex algorithm, try to make the algorithm easier to read by introducing more identifiers. This helps in the future in case the algorithm changes but someone forgets to change the documentation.

Source: JavaRanch