I know that an API is called a set of functions used to call something, and a library is a collection of classes, but what is actually API in package like Java.lang? I can connect to a class like System without using any API here, so why we say as J2SE API rather than J2SE packages?
Straight from Wikipedia:
In computer science, an application programming interface (API) is an interface that defines the ways by which an application program may request services from libraries
Java contains many libraries in those packages (Swing, etc.), and the API is the interface by which we request services (perform actions, etc.).
The API (Application Programming Interface) is what a library looks like from the outside for a program that's using it. It's the "face" of a library to other programs. The API of a library is the set of publicly accessible classes, interfaces and methods in the library.
You wrote:
I can connect to a class like System without using any API here...
That's not true - class System is a public class in Java's standard library, so it's part of the API of the standard Java library. You are using the API of the standard Java library if you are using class System.
Why do you think you "are not using any API" when you use class System?
Just to restate what I think others are saying more briefly:
A library is a set classes that are generally organized and packaged in some coherent manner to promote reuse.
An API is the way you access a library (or any set of classes).
A quick rule of thumb just to start with: a library is a collection of java classes, usually but not necessarily located in a jar file, and all public methods of those classes form the API of that library.
(the cleaner the code, the more you can rely on this rule ;) )
API is a logical representation of non-empty collection of Java classes and interfaces (add annotations and enums).
Library (being JAR Java library) is a unit of deployment of one, many or part of API.
There is no one-to-one or many-to-one association between two in general since their concerns are orthogonal in nature: API is concerned with logic and functionality; library is concerned with deployment.
Excellent resource that covers these relationships is Robert Martin Principles of OOD - look for last 6 package principles.