Tuesday, April 29, 2014

Packages in java (Part 1/2)

This is the first article on packages. 

Simply put, a package is a folder that organizes related top-level classes and interfaces.

A package contains source code files (containing top-level classes and interfaces) and sub-packages with source code files of their own. 

Important points about packages:
  • The package statement should be the first line of code in a compilation unit.
  • There is only one package statement in each compilation unit.
  • The package java.lang.* is imported automatically in each .java file.
  • The containing package may be imported. Such an import is ignored.

//First line of code is package statement

package com.choosejava.blogspot;

//java.lang package is automatically imported

//May specify redundantly
import java.lang.*;
import somepackage.*;

//This line is ignored
import com.choosejava.blogspot.*;

//Top-level classes and interfaces
class A{...}
interface I1{...}

You cannot single-import a type with the same simple name as a top-level class or interface.

Also, 2 single-type import declarations should not attempt to import types with the same simple name. Following is invalid.

package somepackage;

import otherpackage.TestClass;

class TestClass{...}

//Reference to TestClass will be ambiguous

Following is also invalid:

import otherpackage.Vector;
import java.util.Vector;
//Reference to Vector class will be ambiguous


Duplicate import declarations are allowed.

Let's modify the above code with TestClass a little bit. 

Following is valid:

package somepackage;

import otherpackage.*;

class TestClass{...}

//Refer to otherpackage.TestClass using the fully qualified name

Monday, April 28, 2014

Identifiers in Java

Identifiers are names of classes, interfaces, methods, variables and packages.
Must start with:
  • A - Z or a - z                     
  • $  or _ (underscore)
Can also contain:
  • 0-9
Cannot be 
  • null literal
  • boolean literal (true or false)
  • a keyword
No limits on number of characters.
List of keywords:
Note: goto and const are reserved keywords in Java. (They are not used anywhere).
Legal identifiers:
MyClass (Class name)
m1 (Method name)
var (Variable name)
_123 (Not recommended but legal)
$UNLIMITED (Strange)
MAX_VALUE (static final variable)
Illegal identifiers
public (keyword)
123_ (starts with number)
null (null literal)