Tuesday, 22 March 2011

Core and Advanced Java


Java

Java is great programming language for the development of enterprise grade applications. This programming Language is evolved from a language named Oak. Oak was developed in the early nineties at Sun Microsystems as a platform-independent language aimed at allowing entertainment appliances such as video game consoles and VCRs to communicate . Oak was first slated to appear in television set-top boxes designed to provide video-on-demand services. Oak was unsuccessful so in 1995 Sun changed the name to Java and modified the language to take advantage of the burgeoning World Wide Web.
Java is an object-oriented language, and this is very similar to C++. Java Programming Language is simplified to eliminate language features that cause common programming errors. Java source code files are compiled into a format called bytecode, which can then be executed by a Java interpreter.

Java as an Internet Language

Java is an object oriented language and a very simple language. Because it has no space for complexities. At the initial stages of its development it was called as OAK. OAK was designed for handling set up boxes and devices. But later new features were added to it and it was renamed as Java. Java became a general purpose language that had many features to support it as the internet language. Few of the features that favors it to be an internet language are:
Cross Platform Compatibility:  The java source files (java files with .java extension) after compilation generates the bytecode (the files with .class extension) which is further converted into the machine code by the interpreter. The byte code once generated can execute on any machine having a JVM. Every operating system has it's unique Java Virtual Machine (JVM) and the Java Runtime Environment (JRE).
Support to Internet Protocols: Java has a rich variety of classes that abstracts the Internet protocols like HTTP , FTP, IP, TCP-IP, SMTP, DNS etc .
Support to HTML: Most of the programming languages that are used for web application uses the html pages as a view to interact with the user. Java programming language provide it's support to html. For example. Recently the extension package jipxhtml is developed in java to parse and create the html 4.0 documents.
Support to Java Reflection APIs: To map the functionalities, Java Reflection APIs provides the mechanism to retrieve the values from respective fields and accordingly creates the java objects. These objects enables to invoke methods to achieve the desired functionality.
Support to  XML parsing: Java has JAXP-APIs to read the xml data and create the xml document using different xml parsers like DOM and SAX. These APIs provides mechanism to share data among different applications  over the internet.
Support to  Web Services : Java has a rich variety of APIs to use xml technology in diverse applications that supports  N-Tiered Enterprise applications over the internet. Features like JAXB , JAXM, JAX-RPC , JAXR etc enables to implement web services in java applications. It  makes java a most suited internet language.
Support to java enabled Mobile devices: Java programming language is made in such a way so that it is compatible with mobile devices also. Java language also works with any java enabled mobile devices that support MIDP 1.0/2.0 including the symbian OS mobile devices. 
Support to Personal Digital Assistants: Java language is compatible with Personal Java 1.1 such as chaiVM, Jeode, CrEME, and JV-Lite2 or with all the later version and it also support PDAs like HP/Compaq, iPAQ, Fujitsu-Siemens Pocket Loox and SimPad, HHP, NEC, Samsung, Sharp Electronics, Toshiba, psion m5, and any other device with Windows CE/Pocket PC 2002/2003/2005).

Java as a general purpose language

Java is an Object oriented application programming language developed by Sun Microsystems. Java is a very powerful general-purpose programming language. It is a stupendous programming language which is not confined to machine applications only. Java is more than just a tool for building transportable multimedia applications. Due to its versatility, it is a platform independent language, be it a hardware platform or any operating system.
Java programs run as quickly and efficiently as C++ programs due to the implementation of the JVM (Java Virtual Machine). It adds to C++ in the areas of automatic memory management. Moreover it also extends the language support for multithreaded applications.
T he Java applet API is a framework that allows Java-enabled Web browsers to manage and display embedded Java applications within. Java applications can be executed by any software that implements the Java run-time system. Any kind of applications can be written in Java programming language such as any small or large applications, or any standalone application.

Introduction

  • What is case sensitivity 
  • Case sensitivity in Computers 
  • Case Sensitive and case insensitive Languages
  • Examples  
What is case sensitivity:  Case sensitivity is the mechanism in which words can be differ in meaning based on different use of uppercase and lowercase letters. Sometime words can differ in meaning with the same words while starts with capital letter  with lowercase letters.
Case sensitivity in Computers:  Case sensitivity is the mechanism by which computer compares two words to decide whether they are equal, it may or may not consider words equal which only differ in case.
Case Sensitive and case insensitive Languages:   On the basis of case sensitivity, computer languages can be divided into two parts. Computer languages  like C, C++  and java are case sensitive languages while others are case insensitive like BASIC and Pascal.         
Examples:
§         The Java class Helloworld is a completely different class from the class HelloWorld.
§         public static void main(String args[]) is totally different from public static void main(string args[]).
§         If you compare two strings in a case sensitive way then they are considered different if they differ only in capitalization e.g. comparing the string by using the method String.compareTo,   If you compare two Strings in a case insensitive way then they are considered equal if they differ only in capitalization. e.g. comparing the string with String.compareToIgnoreCase,

Java Features

Platform IndependentThe concept of Write-once-run-anywhere (known as the Platform independent) is one of the important key feature of java language that makes java as the most powerful language. Not even a single language is idle to this feature but java is more closer to this feature. The programs written on one platform can run on any platform provided the platform must have the JVM. 
SimpleThere are various features that makes the java as a simple language. Programs are easy to write and debug because java does not use the pointers explicitly. It is much harder to write the java programs that can crash the system but we can not say about the other programming languages. Java provides the bug free system due to the strong memory management. It also has the automatic memory allocation and deallocation system.
Object OrientedTo be an Object Oriented language, any language must follow at least the four characteristics.
  • Inheritance           :       It is the process of creating the new classes and using the behavior of the existing classes by extending them just to                                    reuse  the existing code and adding the additional features as needed.
  • Encapsulation:      :       It is the mechanism of combining the information and providing the abstraction.
  • Polymorphism:     :       As the name suggest one name multiple form, Polymorphism is the way of providing the different functionality by the   
                                       functions  having the same name based on the signatures of the methods.
  • Dynamic binding  :       Sometimes we don't have the knowledge of objects about their specific types while writing our code. It is the way                                   of providing the maximum functionality to a program about the specific type at runtime.        
As the languages like Objective C, C++ fulfills the above four characteristics yet they  are not fully object oriented languages because they are structured as well as object oriented languages. But in case of java,  it is a fully Object Oriented language because object is at the outer most level of data structure in java. No stand alone methods, constants, and variables are there in java. Everything in java is object even the primitive data types can also be converted into object by using the wrapper class.
RobustJava has the strong memory allocation and automatic garbage collection mechanism. It provides the powerful exception handling and type checking mechanism as compare to other programming languages. Compiler checks the program whether there any error and interpreter checks any run time error and makes the system secure from crash. All of the above features makes the java language robust.
DistributedThe widely used protocols like HTTP and FTP are developed in java. Internet programmers can call functions on these protocols and can get access the files from any remote machine on the internet rather than writing codes on their local system.
PortableThe feature Write-once-run-anywhere  makes the java language portable provided that the system must have interpreter for the JVM. Java also have the standard data size irrespective of operating system or the processor. These features makes the java as a portable language.
DynamicWhile executing the java program the user can get the required files dynamically from a local drive or from a computer thousands of miles away from the user just by connecting with the Internet.
SecureJava does not use memory pointers explicitly. All the programs in java are run under an area known as the sand box. Security manager determines the accessibility options of a class like reading and writing a file to the local disk. Java uses the public key encryption system to allow the java applications to transmit over the internet in the secure encrypted form. The bytecode Verifier checks the classes after loading. 
PerformanceJava uses native code usage, and lightweight process called  threads. In the beginning interpretation of bytecode resulted the performance slow but the advance version of JVM uses the adaptive and just in time compilation technique that improves the performance. 
Multithreaded
As we all know several features of Java like Secure, Robust, Portable, dynamic etc; you will be more delighted to know another feature of Java which is Multithreaded.Java is also a Multithreaded programming language. Multithreading means a single program having different threads executing independently at the same time. Multiple threads execute instructions according to the program code in a process or a program. Multithreading works the similar way as multiple processes run on one computer.
Multithreading programming is a very interesting concept in Java. In multithreaded programs not even a single thread disturbs the execution of other thread. Threads are obtained from the pool of available ready to run threads and they run on the system CPUs. This is how Multithreading works in Java which you will soon come to know in details in later chapters.
InterpretedWe all know that Java is an interpreted language as well. With an interpreted language such as Java, programs run directly from the source code.
The interpreter program reads the source code and translates it on the fly into computations. Thus, Java as an interpreted language depends on an interpreter program.
The versatility of being platform independent makes Java to outshine from other languages. The source code to be written and distributed is platform independent.
Another advantage of Java as an interpreted language is its error debugging quality. Due to this any error occurring in the program gets traced. This is how it is different to work with Java.
Architecture NeutralThe term architectural neutral seems to be weird, but yes Java is an architectural neutral language as well. The growing popularity of networks makes developers think distributed. In the world of network it is essential that the applications must be able to migrate easily to different computer systems. Not only to computer systems but to a wide variety of hardware architecture and Operating system architectures as well.  The Java compiler does this by generating byte code instructions, to be easily interpreted on any machine and to be easily translated into native machine code on the fly. The compiler generates an architecture-neutral object file format to enable a Java application to execute anywhere on the network and then the compiled code is executed on many processors, given the presence of the Java runtime system. Hence Java was designed to support applications on network. This feature of Java has thrived the programming language

Java Enabled browsers

Java language is the most powerful language and is widely used in the web application. Today most of the web browser are java compatible. Few of them are:
  • Internet Explorer 
  • Netscape
  • HotJava
  • Firefox 1.0.4
  • Mozilla 1.6
Internet Explorer: It is the most widely used Browser. Internet Explorer abbreviates as IE . Windows Internet Explorer is developed by Microsoft in 1995 and it was included in series of  Microsoft Windows 95 operating system. Advanced version of IE are supported on different operating systems such as Internet Explorer for UNIX, Internet Explorer for Mac. Internet Explorer 7.0 is the recent version available for free update for Windows XP with Service Pack 2 and Windows Server 2003 with Service Pack 1, it  is  also included with Windows Vista.
Netscape: Netscape Web browser version 8.0(as the first version) was first time released in 30 November 2004 . It was developed by Mercusial Communication. Then version 8.0.1 came in the market with a minor enhancement. Various versions of the Netscape were based on  different technology like version 8 was based on Mozila Firefox whereas version 1 to 4 was based on Netscape Navigator and Netscape Communicator whereas  Netscape 6 and 7 are based on Mozilla Application Suite.
HotJava: It is the modular version of the web browser developed by the Sun Microsystems to support the applets. Now it is not currently used. It was just like the clone of the internet browser Mosaic. This browser had three version  HotJava Browser 3.0, HotJava Browser 1.1.5 and HotJava Browser 1.1.2 .
Techniques to check whether a browser is java enabled or not.
Most of the browsers today are java enabled. There are various ways to check whether the browser being used is java enabled or not. However  we manually check its support for java. The following procedure shows how to check, whether the browser is java enabled or not.
Firefox 1.0.4: Just , Go through by putting the following entry in the address bar.
about : java plugins
If java is installed then it will show the multiple entries under the lable "Java Plug-in". It will also provide the information about the version and   installation.
 We can also check manually by going through the following steps in the tool bar.
Click on Tools -> Options -> Web features (or Content ).
 If the check box is checked, the browser is java enabled.
Mozilla 1.6: Mozilla also have the two ways to check manually , whether it is java enabled or not.
Go to click on Help-> About Plug-ins.
If it shows nothing then java is not installed. If java is installed then it shows various plug-in entries according to the version.
The second method is that, Click on Tools -> Web Development. If it shows the Java Console option then java is installed otherwise it shows nothing.

Java Compiler

To commence with Java programming, we must know the significance of Java Compiler. When we write any program in a text editor like Notepad, we use Java compiler to compile it. A Java Compiler javac is a computer program or set of programs which translates java source code into java byte code. 
The output from a Java compiler comes in the form of Java class files (with .class extension). The java source code contained in files end with the .java extension. The file name must be the same as the class name, as classname.java. When the javac compiles the source file defined in a .java files, it generates bytecode for the java source file and saves in a class file with a .class extension.
The most commonly used Java compiler is javac, included in JDK from Sun Microsystems.
Following figure shows the working of the Java compiler:
Once the byte code is generated it can be run on any platform using Java Interpreter (JVM). It interprets byte code (.class file) and converts into machine specific binary code. Then JVM runs the binary code on the host machine. 
How to use Java Compiler
When you run javac command on the command prompt, it shows the following output.
C:\>javac
Usage: javac <options> <source files>
       where possible options include:
  -g                         Generate all debugging info

  -g:none                    Generate no debugging info

  -g:{lines,vars,source}     Generate only some debugging info

  -nowarn                    Generate no warnings

  -verbose                   Output messages about what the compiler is doing

  -deprecation               Output source locations where deprecated APIs are
                             used

  -classpath <path>          Specify where to find user class files and 
                             annotation processors

  -cp <path>                 Specify where to find user class files and 
                             annotation processors

  -sourcepath <path>         Specify where to find input source files

  -bootclasspath <path>      Override location of bootstrap class files

  -extdirs <dirs>            Override location of installed extensions

  -endorseddirs <dirs>       Override location of endorsed standards path

  -proc:{none,only}          Control whether annotation processing and/or 
                             compilation is done.

  -processor <class1>[,<class2>,<class3>...]
                             Names of the annotation processors to run; 
                             bypasses default discovery process

  -processorpath <path>      Specify where to find annotation processors

  -d <directory>             Specify where to place generated class files

  -s <directory>             Specify where to place generated source files

  -implicit:{none,class}     Specify whether or not to generate class files
                             for implicitly referenced files

  -encoding <encoding>       Specify character encoding used by source files

  -source <release>          Provide source compatibility with specified 
                             release

  -target <release>          Generate class files for specific VM version

  -version                   Version information

  -help                      Print a synopsis of standard options

  -Akey[=value]              Options to pass to annotation processors

  -X                         Print a synopsis of nonstandard options

  -J<flag>                   Pass <flag> directly to the runtime system
C:\>
        
Above output shows the different options of javac tool.
Using java compiler to compile java file:Following example shows how a Compiler works. It compiles the program and gives the Syntax error, if there is any. Like in this example, we haven't initialized 'a' and we are using it in the next statement as 'int c=a+b'. That is why its showing a syntax error.
class A{
 public static void main(String[] args){
     int a;
     int b=2;
     int c=a+b;
    System.out.println(c);
    }
 }
Output of program:
C:\Program Files\Java\jdk1.6.0_01\bin>javac A.java
A.java:6: variable a might not have been initialized
int c=a+b;
^
1 error

C:\Program Files\Java\jdk1.6.0_01\bin>
Now, lets tweak this example. In this we have initialized 'a' as 'int a =2'. Hence, no syntax error has been detected.
class A{
  public static void main(String[] args) {
     int a=2;
     int b=2;
     int c=a+b;
    System.out.println(c);
    }
  }
Output of program:
C:\Program Files\Java\jdk1.6.0_01\bin>javac A.java

C:\Program Files\Java\jdk1.6.0_01\bin>java A
4

Java Interpreter


We can run Java on most platforms provided a platform must has a Java interpreter. That is why Java applications are platform independent. Java interpreter translates the Java bytecode into the code that can be understood by the Operating System. Basically, A Java interpreter is a software that implements the Java virtual machine and runs Java applications. As the Java compiler compiles the source code into the Java bytecode, the same way the Java interpreter translates the Java bytecode into the code that can be understood by the Operating System.
When a Java interpreter is installed on any platform that means it is JVM (Java virtual machine) enabled platform. It (Java Interpreter) performs all of the activities of the Java run-time system. It loads Java class files and interprets the compiled byte-code. You would be glad to know that some web browsers like Netscape and the Internet Explorer are Java enabled. This means that these browsers contain Java interpreter. With the help of this Java interpreter we download the Applets from the Internet or an intranet to run within a web browser. The interpreter also serves as a specialized compiler in an implementation that supports dynamic or "just in time," compilation which turns Java byte-code into native machine instructions. 
Throughout Java programming, we'll build both, the standalone Java programs and applets. 
Sun's Java interpreter is called java. Lets learn how to start a standalone application with it. Load an initial class and specify it. Some options can also be specified to the interpreter, and any command-line arguments needed for the application as well:
% java [interpreter options] class name [program arguments] 
The class should be specified as a fully qualified class name including the class package, if any.
Note :  Moreover, we don't include the 
.class file extension. Here are a few examples:
% java animals.birds.BigBird
% java test
Once the class is loaded, java follows a  C-like convention and searches for the class that contains a method called main(). If it finds an appropriate main() method, the interpreter starts the application by executing that method. From there, the application starts additional threads, reference other classes, and create its user interface.
Now, lets see how to go about an Applet. Although Java applet is a compiled Java code, the Java interpreter can't directly run them because they are used as part of a larger applications. For this we use Java Applet Viewer. It is a command line program to run Java applets. It is included in the SDK. It helps you to test an applet before you run it in a browser. We will learn more about it later.
The Figure below shows the working of Java Interpreter:

Java Debugger


Java debugger helps in finding and the fixing of bugs in Java language programs. The Java debugger is denoted as jdb. It works like a command-line debugger for Java classes. 
jdb session
The way to start the jdb session is to have jdb launch a new JVM (Java virtual machine) with the main classThen the application of the main class is debugged by substituting the command jdb in command-line. For instance, if the main class of the application is TempClass, the following command is used to debug it:
% jdb TempClass  
There is another way to use jdb i.e.to attach jdb to Java VM which is already running. 
There are few options which are used to debug a VM with jdb. These are:
option 
purpose
-Xdebug 
Enables debugging in the VM
-Xrunjdwp:transport=dt_socket,server=y,suspend=n 
Loads in-process debugging libraries and specifies the kind of connection to be made
The following command will run the TempClass application to which the jdb will connect afterwords.
% java -Xdebug -Xrunjdwp:transport=dt_socket,address=8000,server=y,suspend=n TempClass
Now the jdb will be attached to the VM in this way:  % jdb -attach 8000 
You can go through the basic jdb commands that the Java debugger supports.
cont
Ihis command Continues the execution of the debugged application after a breakpoint, exception, or step.

run
Use run command to start the execution after starting jdb, and setting any necessary breakpoints,  use run command to start the execution . When jdb launches the debugged application then only this command is available. 
print
This command is used to display Java objects and primitive values. The actual value is printed for the variables or fields of primitive types. For objects, a short description is printed. 
Few examples of print command are:
 
print TempClass.myStaticField
 print myObj.myInstanceField
 print myObj.myMethod() 

dump
 This command is similar to print command. For objects, it is used to print the current value of each field defined in the object including Static and instance fields.
The dump command supports the same set of expressions as the print command. 
ExceptionsIf any kind of exception occurs in the program, the VM will print an exception trace and exits. It will only print this exception when there isn't any catch statement in the throwing thread's call stack.
There is another command to be used to stop the debugged applications at other thrown exceptions. The command is catch command. For instance,  
"catch java.io.FileNotFoundException" or "catch mypackage.BigTroubleException. 
Also the ignore command negates the effect of a previous catch command.
help, or ?
The command which helps in displaying the list of recognized commands is the help or ?command.

threads
This command list the threads that are currently running. The name and current status are printed for each thread. The index is also printed that can be used for other commands, for example:
4. (java.lang.Thread)0x1 main running
This example shows that the thread index is 4, the thread is an instance of java.lang.Thread, the thread name is "main", and it is currently running.

thread
This command selects a thread to be the current thread. Some jdb commands are based on the setting of the current thread. The thread index specifies the thread as explained in the threadscommand above.

whereThe command where is used to dump the stack of the current thread. Whereas the commandwhere all is used to dump the stack of all threads in the current thread group. And the where thread index command is used to dump the stack of the specified thread.

Breakpoints
The way to use Breakpoints is to set it in jdb at line numbers or at the first instruction of a method, for example:
 stop at TempClass:14 (sets a breakpoint at the first instruction for line 14 of the source file containing TempClass)
 stop in TempClass.<init> (<init> identifies the TempClass constructor)

It is essential to specify the argument types whenever we overload any method in order to select  the proper method for a breakpoint. For example, 
"TempClass.myMethod(int,java.lang.String)",or "TempClass.myMethod()".
We also use the clear command to remove breakpoints using a syntax as in "clear TempClass:20" and the cont command continues execution.

Command Line Options

 Use jdb in place of the Java application launcher on the command line, it accepts most of the same options as the java command, which includes -D, -classpath, and -X<option>.
Some more options by jdb:
-sourcepath <dir1:dir2:...>
Uses the given path in searching for source files in the specified path. If this option is not specified, the default path of "." is used. 
-attach <address>Attaches the debugger to previously running VM using the default connection mechanism. -launchAs soon as the jdb start sup,launch option launches the debugged application immediately. We need not to use the run command after using this option. -Joption
It passes option to the Java virtual machine, where option is one of the options described on the reference page for the java application launcher. For example, 
-J-Xms48m sets the startup memory to 48 megabytes.
Lets tweak an example:
public class Y {
     public static int add(int a, int b)
 {
  return a+b;
 }
 public static int sub(int a, int b)
 {
  return a-b;
 }
 public static void main(String args[]) 
 {
  int a = 10;
  int b = 20;
  int c;  
  c = add(a, b);
        System.out.println(c);
  c = sub(a, b);
  System.out.println(c);
  } 
}

After compiling and running the above program, we will initialize the java debugger and we will use the Stop command to out a breakpoint. After that we will use run command to start the jdb. In the similar way we can use other commands as well.
C:\javac>jdb Y
Initializing jdb ...
> stop at Y:6
Deferring breakpoint Y:6.
It will be set after the class is loaded.
> run
run Y
Set uncaught java.lang.Throwable
Set deferred uncaught java.lang.Throwable
>
VM Started: Set deferred breakpoint Y:6

Breakpoint hit: "thread=main", Y.add(), line=6 bci=0
6 return a+b;

main[1] where
[1] Y.add (Y.java:6)
[2] Y.main (Y.java:17)
main[1] methods Y
** methods list **
Y <init>()
Y add(int, int)
Y sub(int, int)
Y main(java.lang.String[])
java.lang.Object <init>()
java.lang.Object registerNatives()
java.lang.Object getClass()
java.lang.Object hashCode()
java.lang.Object equals(java.lang.Object)
java.lang.Object clone()
java.lang.Object toString()
java.lang.Object notify()
java.lang.Object notifyAll()
java.lang.Object wait(long)
java.lang.Object wait(long, int)
java.lang.Object wait()
java.lang.Object finalize()
java.lang.Object <clinit>()

Javah -  Header File Generator


In Java programming we need to implement some native methods. You must be wondering about what's native methods.

Firstly
, The native methods are in pure C code, not C++. The function prototypes are in an object-oriented form of C which are being provided by javah , but they are still not object methods.

Secondly, We can call native methods applications only. However due to some security reasons, we cannot call applets from native methods.

Thirdly,  native methods are platform-specific. This is the most important point to remember, you have to build a dynamically loadable library to link your java application with the native operating system (Windows OS, Machintosh, Linux, Unix ..).  For each native platform your application targets, a dynamically loadable library is needed to be shipped.. That means any system-specific code has to be ported along with the java code.
On the other hand, native methods are the only way to use any system features not provided by the Java Virtual Machine.
To implement these methods Javah generates C header and source files that are used by C programs to reference an Object's instance variables from native source code. The name of the header file and the structure declared within it are derived from the name of the class.
By default javah creates a header file for each class listed on the command line and puts the files in the current directory. As stated above the name of the header file is derived from the name of the class. If any class inside the package is passed to javah, the package name gets prepended to both the header file name and the structure name.
Following are some options to use : 
-o outputfile
This option concatenates the resulting header or source files for all the classes listed on the command line into output file. 
-help
Print help message for javah usage.
-d directory
This option sets the directory where javah saves the header files or the stub files. Only one of -d or -o may be used.
-classpath path
Specifies the path javah used to look up classes. Overrides the default or the CLASSPATHenvironment variable if it is set. Directories are separated by semi-colons. Thus the general format for path is:
.;<your_path>
For example:
.;C:\users\dac\classes;C:\tools\java\classes
-stubs
Causes javah to generate C declarations from the Java object file.
-verbose
Indicates verbose output and causes javah to print a message to stdout concerning the status of the generated files.
-version
Prints out javah version information.


Javadoc


Sun Microsystems has provided a computer software tool known asJavadoc. This tool is used to generate API documentation into HTML format from Java source code. It is interesting to know that Javadoc is the industry standard for documenting Java classes.
 Javadoc is a program that is already included in JDK. We can use Javadoc to run over the source code to produce documentation of our classes in the HTML files . We have to tag our code with by using some comment formats to use javadoc tag on our source code. For instance Javadoc comments looks like this:
NOTE : To start a Javadoc comments use /** to start, and */ to end, and use tags such as @param, @return, and @exception in between to describe the workings of a method.
The format is given below to use the Javadoc comments:
/**
* Summary of the sentence.
*  information about the
* program, class, method or variable
* then the comment, using as many lines
* as necessary.
*
* zero or more tags to specify any type
* of information, such as parameters and return
* values for a method
*/

Start with comment delimiter (/*) followed by another (*). The next line starts with an asterisk and write as many line as you want starting with an asterisk. The last line ends with the delimiter (*/). The first sentence to start with is a "summary sentence" showing the description of the program, class, method or variable. We can write few more lines if required, but not any blank lines. After writting the general description, a sequence of tags follows leaving a blank line.
Use different tags to display different situations. The example below shows a Javadoc comment without tags that describes the variable declared immediately below it:

/**
* The number of employees in a company. This variable must not be
* negative or greater than 200.
*/
public int numEmployees;


One interesting thing to know about Javadoc comments is that we can embed HTML tags to format the text. For example:
/**
* <B>Java declaration</B>
*/ 

Lets have a look on Javadoc tags
 Tag 
 Description
 @version 
 Shows the version number of a class or method.
 @author 
 Shows the Developer name
 @return 
 Documents the return value. This tag should not be used for constructors or methods defined with a void return type.
 @deprecated
 Marks a method as deprecated. Some IDEs will issue a compilation warning  if the method is called. 
 @see 
 Documents an association to another method or class.
 @param 
 Defines a method parameter. Required for each parameter.
 @throws 
 Documents an exception thrown by a method. A synonym for @exception   introduced in Javadoc 1.2.
 @since 
 Documents when a method was added to a class.
 @exception 
 Documents an exception thrown by a method — also see @throws.
 private
 Displays all classes and members
 use
 It creates class and package usage pages
 Windowtitle
 It shows the window title of the document
 Header
 It includes for header text of the page
 Footer
 It includes footer text for the page  
 Bottom
 It includes bottom text for the page
 Package
 Shows package classes and members
 Protected
 shows protected classes and members
 Classpath
 Helps to find user class files
 noindex
 doesn't provide the index
 nohelp
 doesn't provide the help link
 notree
 doesn't provide class hierarchy
 To document source code developers use certain commenting styles and Javadoc tags. A Java block comment starting with /** will begin a Javadoc comment block This comment block will be included in the HTML. Some tags are provided in the above table which begins with an "@" (at sign).

The Java Applet Viewer

Applet viewer is a command line program to run Java applets. It is included in the SDK. It helps you to test an applet before you run it in a browser. Before going any further, lets see what an applet is?An applet is a special type of application that's included as a part of an HTMLpage and can be stored in a web page and run within a web browser. The applet's code gets transferred to the system and then the Java Virtual Machine (JVM) of the browser executes that code and displays the output.. So for running the applet,  the browser should be Java enabled. To create an applet, we need to define a class that inherits the Applet.
We generally use web browsers to run applets. Its not always mandatory to open a Web browser for running an applet. There is another way as well. The other way to run an applet is throughJava applet viewer. This is a tool that acts as a test bed for Java applets. The working of Applet viewer is a bit different from a Web browser, though they are logically same. The Applet viewer runs on the HTML documentation, and uses embedded applet tags. The difference in using the applet viewer and the web browser to run the applet is that the applet viewer only deals with the applet code not the HTML cod i.e. it doesn't display HTML code. So we should test our program in applet viewer and web browser to confirm its working.
The applet viewer command connects to the documents or resources designated by urls. It displays each applet referenced by the documents in its own window.
The syntax for the applet viewer is:appletviewer Options URLWhere the URL specifies the location of the applet program and the Options argument specifies how to run the Java applet. We can use only one option -debug that starts the applet viewer in the Java debugger. Using this option we can debug an applet.
The following program shows how to build an applet and the HTML file for it. Firstly create a class. Then start the applet using init method. After that enter a string as str = "This is my first applet". Use paint method to give the dimensions of the applet. Beneath that is the HTML file which shows how to give the body for applet.
Here is the Java File:
import java.applet.*;
import java.awt.*;
public class Myapplet extends Applet{
 String str;
 public void init(){
  str = "This is my first applet";
 }
 public void paint(Graphics g){
  g.drawString(str, 50,50);
 }
}
Here is the HTML File:
<HTML>
<BODY>
<applet code="Myapplet",height="200" width="200">
</applet>
</BODY>
</HTML>
After building the program, run the applet and the applet viewer as shown below.
C:\javac> javac Myapplet.java

C:\javac>appletviewer Myapplet.html
When we run the applet viewer it will display the window as shown below.

Java Comments

To comprehend any programming language, there are several kind of comments which are used. These comments are advantageous in the sense that they make the programmer feel convenient to grasp the logic of the program. Although these comments are ignored by the Java compiler, they are included in the program for the convenience of the user to understand it.To provide the additional information about the code, use comments. These comments give the overview of the code in the form of the information which is not available in the code itself.

There are three types of comments used in Java. These are:
1. // text
    
To add a comment to the program, we can use two slashes characters i.e. //The line starting from slashes to the end is considered as a comment. We can write only a single line comment use these slashes. For instance

/
/ This comment extends to the end of the line.
// This type of comment is called a "slash-slash" comment
2. /* text */
   To add a comment of more than one line, we can precede our comment using /*. The precise way to use this is to start with delimiter /* and end with delimiter */.  Everything in between these two delimiters is discarded by the Java compiler. For instance
/* This comment, a "slash-star" comment, includes multiple lines.
* It begins with the slash-star sequence (with no space between
* the '/' and '*' characters) and extends to the star-slash sequence.
*/
Slash-star comments may also be placed between any Java tokens:
int i = /* maximum integer */ Integer.MAX_VALUE;
3. /** documentation */
    
This is a special type of comment that indicates documentation comment. This type of comment is readable to both, computer and human. To start the comment, use /** instead of /* and end with */. This type of comment is a documentation which is interpreted as an official document on how the class and its public method work. For instance
/**
* These are used to extract documentation from the Java source.
*/
Comments in String Literals
Comments occurring in string literals are not parsed as comments. Like,
String text = "/* This is not a comment */";
Unicode Characters in Comments
Remember that Java still interprets Unicode sequences within comments. For example, Java compiler processes the Unicode sequence \u002a\u002f (whose codepoints correspond to */) of the source file, even before comments are processed. So we can use this format for Unicode characters.
/* This is a comment. \u002a\u002f
String statement = "This is a comment.";
and is lexically equivalent to

/* This is a comment. */
String statement = "/* This is a comment. */";
(The '*' character is Unicode 002A and the '/' character is Unicode 002F).
This also applies to newline characters in slash-slash comments.
For example:

//This is a single line comment \u000a This is code
That is because the \u000a is the Unicode for a new line, here the compiler thinks that you have added a new line.
This may be useful when declaring more than one thing on a line and you still wish to use // type comments
int x = 0; //X is the value of the carr \u000a int y=0; //Y is the intrest

Java Keywords


There are few keywords in Java programming language. Remember, we cannot use these keywords as identifiers in the program. The keywords const andgoto are reserved though, they are not being currently used.
The brief description of each one of the keyword is given below.
abstract
When a class is not to be instantiated, useabstract keyword but rather extended by other classes. This keyword is used to in a method declaration to declare a method without providing the implementation. 
assert
It is used to define an assert statement. Any boolean condition in a program is declared with the help of assert statement. The condition is checked at runtime if the program is running with assertions . If the condition is false, the Java runtime system throws an AssertionError.

boolean
This keyword is used to pertain to an expression or variable that can have only a true or false value.

byte
This is 8-bit integer. This keyword is used to declare an expression, method return value, or variable of type byte.

case
This keyword is used to defines a group of statements. The value defined by the enclosing switch statement should match with the specified value.

catchThis keyword is used to handle the exceptions that occur in a program preceding try keyword. When the class of the thrown exception is assignment compatible with the exception class declared by the catch clause then only the code is executed.

charThis Java keyword is used to declare an expression, method return value, or variable of type character.

classThis keyword is used to define the implementation of a particular kind of object.

const This keyword has been deprecated from Java programming language.

continueThis keyword is used for the continuation of the program at the end of the current loop body.

defaultIf the value defined by the enclosing switch statement does not match any value specified by a case keyword in the switch statement, default keyword is used to define a group of statements to begin the execution.

doUsed to declare a loop that will iterate a block of statements. The loop's exit condition is specified with the while keyword. The loop will execute once before evaluating the exit condition.

doubleA 64-bit floating point value. A Java keyword used to declare an expression, method return value, or variable of type double-precision floating point number.

elseThis keyword is used to test the condition. It is used to define a statement or block of statements that are executed in the case that the test condition specified by the if keyword evaluates to false.

enum Enumerations extend the base class Enum.This Java keyword is used to declare an enumerated type.

extends To specify the superclass in a class declaration, extends keyword is used. It is also used in an interface declaration to specify one or more superinterfaces.

finalIt is used to define an entity once that cannot be altered nor inherited later. Moreover, a final class cannot be subclassed, a final method cannot be overridden, and a final variable can occur at most once as a left-hand expression. All methods in a final class are implicitly final.

finallyThis keyword is used when the finally block is executed after the execution exits the try block and any associated catch clauses regardless of whether an exception was thrown or caught.
break
Used to resume program execution at the statement immediately following the current enclosing block or statement. If followed by a label, the program resumes execution at the statement immediately following the enclosing labeled statement or block.
strictfp
To get the precise results in Floating point calculations use strictfp keyword regardless of any operating system and hardware platform.



Java Data Types


Java programming language is a language in which all the variables must be declared first and then to be used. That means to specify the name and the type of the variable. This specifies that Java is a strongly-typed programming language. Like
        int pedal = 1;
This shows that there exists a field named 'pedal' that holds a data as a numerical value '1'. The values contained by the variables determines its data type and to perform the operations on it.
There are seven more primitive data types which are supported by Java language programming in addition to int. A primitive data type is a data type which is predefined in Java. Following are the eight primitive data types:
intIt is a 32-bit signed two's complement integer data type. It ranges from -2,147,483,648 to 2,147,483,647. This data type is used for integer values. However for wider range of values uselong.
byte
The byte data type is an 8-bit signed two's complement integer. It ranges from -128 to127 (inclusive). We can save memory in large arrays using byte. We can also use byte instead of int  to increase the limit of the code.
short
The short data type is a 16-bit signed two's complement integer. It ranges from -32,768 to 32,767. short is used to save memory in large arrays.
long
The long data type is a 64-bit signed two's complement integer. It ranges from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807. Use this data type with larger range of values.  
float
The float data type is a single-precision 32-bit IEEE 754 floating point. It ranges from 1.40129846432481707e-45 to 3.40282346638528860e+38 (positive or negative). Use a float (instead of double) to save memory in large arrays. We do not use this data type for the exact values such as currency. For that we have to use 
java.math.BigDecimal class
doubleThis data type is a double-precision 64-bit IEEE 754 floating point. It ranges from 4.94065645841246544e-324d to 1.79769313486231570e+308d (positive or negative). This data type is generally the default choice for decimal values. 
boolean
The boolean data type is 1-bit  and has only two values: true and false. We use this data type for conditional statements. true and false are not the same as True and False. They are defined constants of the language. 
char
The char data type is a single 16-bit, unsigned Unicode character. It 
ranges from 0 to 65,535. They are not same as ints, shorts etc.
The following table shows the default values for the data types:
 Keyword
 Description 
 Size/Format
 byte
 Byte-length integer
 8-bit two's complement
 short 
 Short integer
 16-bit two's complement
 int
 Integer 
 32-bit two's complement
 long 
 Long integer 
 64-bit two's complement
 float
 Single-precision floating point
 32-bit IEEE 
 double
 Double-precision floating point
 64-bit IEEE 
 char 
 A single character 
 16-bit Unicode character
 boolean 
 A boolean value (true or false) 
 true or false
When we declare a field it is not always essential that we initialize it too. The compiler sets a default value to the fields which are not initialized which might be zero or null. However this is not recommended. 

Java Literals

By literal we mean any number, text, or other information that represents a value. This means what you type is what you get. We will use literals in addition to variables in Java statement. While writing a source code as a character sequence, we can specify any value as a literal such as an integer. This character sequence will specify the syntax based on the value's type. This will give a literal as a result. For instance
int month  = 10;
In the above statement the literal is an integer value i.e 10. The literal is 10 because it directly represents the integer value.
In Java programming language there are some special type of literals that represent numbers, characters, strings and boolean values. Lets have a closer look on each of the following.
Integer LiteralsInteger literals is a sequence of digits and a suffix as L. To represent the type as long integer we use L as a suffix. We can specify the integers either in decimal, hexadecimal or octal format. To indicate a decimal format put the left most digit as nonzero. Similarly put the characters as ox to the left of at least one hexadecimal digit to indicate hexadecimal format. Also we can indicate the octal format by a zero digit followed by the digits 0 to 7. Lets tweak the table below.
 659L
 Decimal integer literal of type long integer
 0x4a
 Hexadecimal integer literal of type integer
 057L
 Octal integer literal of type long integer
 
Character LiteralsWe can specify a character literal as a single printable character in a pair of single quote characters such as 'a', '#', and '3'. You must be knowing about the ASCII character set. The ASCII character set includes 128 characters including letters, numerals, punctuations etc. There are few character literals which are not readily printable through a keyboard. The table below shows the codes that can  represent these special characters. The letter d such as in the octal, hex etc represents a number. 
 Escape
 Meaning
 \n
 New line
 \t
 Tab
 \b
 Backspace
 \r
 Carriage return
 \f
 Formfeed
 \\
 Backslash
 \'
 Single quotation mark
 \"
 Double quotation mark
 \d
 Octal
 \xd
 Hexadecimal
 \ud
 Unicode character
It is very interesting to know that if we want to specify a single quote, a backslash, or a nonprintable character as a character literal use an escape sequence. An escape sequence uses a special syntax to represents a character. The syntax begins with a single backslash character.
Lets see the table below in which the character literals use Unicode escape sequence to represent printable and nonprintable characters both.
 'u0041'
 Capital letter A
 '\u0030'
 Digit 0
 '\u0022'
 Double quote "
 '\u003b'
 Punctuation ;
 '\u0020'
 Space
 '\u0009'
 Horizontal Tab 
Boolean LiteralsThe values true and false are also treated as literals in Java programming. When we assign a value to a boolean variable, we can only use these two values. Unlike C, we can't presume that the value of 1 is equivalent to true and 0 is equivalent to false in Java. We have to use the values true and false to represent a Boolean value. Like   boolean chosen = true;
Remember that the literal true is not represented by the quotation marks around it. The Java compiler will take it as a string of characters, if its in quotation marks.

Floating-point literalsFloating-point numbers are like real numbers in mathematics, for example, 4.13179, -0.000001. Java has two kinds of floating-point numbers: float and double. The default type when you write a floating-point literal is double.
Type
Size
Range
Precision
name
bytes
bits
approximate
in decimal digits
float
4
32
+/- 3.4 * 1038
6-7
double
8
64
+/- 1.8 * 10308
15
A floating-point literal can be denoted as a decimal point, a fraction part, an exponent (represented by E or e) and as an integer. We also add a suffix to the floating point literal as D, d, F or f.  The type of a floating-point literal defaults to double-precision floating-point.
The following floating-point literals represent double-precision floating-point and floating-point values.
 6.5E+32 (or 6.5E32)
 Double-precision floating-point literal
 7D
 Double-precision floating-point literal
 .01f
 Floating-point literal
String LiteralsThe string of characters is represented as String literals in Java. In Java a string is not a basic data type, rather it is an object. These strings are not stored in arrays as in C language. There are few methods provided in Java to combine strings, modify strings and to know whether to strings have the same value.
We represent string literals as
String myString = "How are you?";
The above example shows how to represent a string. It consists of 
a series of characters inside double quotation marks.
Lets see some more examples of string literals:""                                      // the empty string
"\""                                   // a string containing "
"This is a string"               // a string containing 16 characters
"This is a " +                   // actually a string-valued constant expression,
"two-line string"             // formed from two string literals
Strings can include the character escape codes as well, as shown here:String example = "Your Name, \"Sumit\"";
System.out.println("Thankingyou,\nRichards\n");
Null Literals
The final literal that we can use in Java programming is a Null literal. We specify the Null literal in the source code as 'null'. To reduce the number of references to an object, use null literal. The type of the null literal is always null. We typically assign null literals to object reference variables. For instance
s = null;
An this example an object is referenced by s. We reduce the number of references to an object by assigning null to s. Now, as in this example the object is no longer referenced so it will be available for the garbage collection i.e. the compiler will destroy it and the free memory will be allocated to the other object. Well, we will later learn about garbage collection.

Introduction to Java Arrays

In this section you will be introduced to the concept of Arrays in Java Programming language. You will learn how the Array class in java  helps the programmer to organize the same type of data into easily manageable format. 
Program data is stored in the variables and takes the  memory spaces, randomly. However, when we need the data of the same type  to store in the contiguous memory allocations we use the data structures like arrays. To meet this feature java has provided an Array class which abstracts the array data-structure. 
The java array enables the user to store the values of the same type in contiguous memory allocations. Arrays are always a fixed length abstracted data structure  which can not be altered when required.
The Array class implicitly extends java.lang.Object so an array is an instance of Object.
Structure of Arrays
Now lets study the structure of Arrays in java. Array is the most widely used data structure in java. It can contain multiple values of the same type. Moreover, arrays are always of fixed length i.e. the length of an array cannot be increased or decreased.
Lets have a close look over the structure of Array. Array contains the values which are implicitly  referenced through the index values. So to access the stored values in an array we use indexes. Suppose an array contains "n"  integers. The first element of this array will  be indexed with the "0" value and the last integer will be referenced by "n-1" indexed value.
Presume an array  that contains 12 elements as shown  in the figure. Each element is holding a distinct value. Here the first element is refrenced by a[0] i.e. the first  index value. We have filled the 12 distinct values in the array each referenced as:
a[0]=1
a[1]=2
...
a[n-1]=n
...
a[11]=12
The figure below shows the structure of an Array more precisely.
Array Declaration
As we declare a variable in Java, An Array variable is declared the same way. Array variable has a type and a valid Java identifier i.e. the array's type and the array's name. By type we mean the type of elements contained in an  array. To represent the variable as an Array, we use [] notation. These two brackets are used to hold the array of a variable.
By array's name, we mean that we can give any name to the array, however it should follow the predefined conventions. Below are the examples which show how to declare an array :-
int[] array_name;     //declares an array of integers
String[] names;
int[][] matrix;    //this is an array of arrays
It is essential to assign memory to an array when we declare it. Memory is assigned to set the size of the declared array. for example:
int[] array_name = new int[5];
Here is an example that creates an array that has 5 elements.
public class Array
{
   public static void main(String[] args)
   {
      int[] a = new int[5];
   }
}
Array Initialization
After declaring an array variable, memory is allocated to it. The "new" operator is used for the allocation of  memory to the array object. The correct way to use the "new" operator is
String names[];
names = new String[10];
Here, the new operator is followed by the type of variable and the number of elements to be allocated. In this example [] operator has been used to place the number of elements to be allocated.
Lets see a simple example of an array,
public class Sum 
{
  public static void main(String[] args) 
  {
    int[] x = new int [101];
    for (int i = 0; i<x.length; i++ )
      x[i] = i;
    int sum = 0;
    for(int i = 0; i<x.length; i++)
      sum += x[i];
      System.out.println(sum);
  }
}
In this example, a variable 'x' is declared which  has a type array of int, that is, int[]. The variable x is initialized to reference a newly created array object. The expression 'int[] = new int[50]' specifies that the array should have 50 components. To know the length of the Array, we use field length, as shown.

Array Usage
We have already discussed that to refer an element within an array, we use the [] operator. The [] operator takes an "int" operand and returns the element at that index. We also know that the array indices start with zero, so the first element will be held by the 0 index. For Example :-
                                                                                        int month = months[4];    //get the 5th month (May)
Most of the times it is not known in the program that which elements are of interest in an array. To find the elements of interest in the program, it is required that the program must run a loop through the array. For this purpose "for" loop is used to examine each element in an array. For example :-
String months[] = 
         {"Jan", "Feb", "Mar", "Apr", "May", "Jun", 
          "July", "Aug", "Sep", "Oct", "Nov", "Dec"};
           //use the length attribute to get the number
          //of elements in an array
          for (int i = 0; i < months.length; i++ ) {
          System.out.println("month: " + month[i]);
Here, we have taken an array of months which is,
                                                                 String months[] =
                                                                                {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
                                                                               "July", "Aug", "Sep", "Oct", "Nov", "Dec"};
Now, we run a for loop to print each element individually starting from the month "Jan".
                                                                                for (int i = 0; i < months.length; i++ )
In this loop int i = 0; indicates that the loop starts from the 0th position of an array and goes upto the last position which is length-1,                          i < months.length; indicates the length of the array and i++ is used for the increment in the value of i which is i = i+1.
Multi-dimensional arrays
So far we have studied about the one-dimensional and two-dimensional arrays. To store data in more dimensions a multi-dimensional array is used. A multi-dimensional array of dimension n is a collection of items. These items are accessed via n subscript expressions. For example, in a language that supports it, the element of the two-dimensional array x is denoted by x[i,j].
The Java programming language does not really support multi-dimensional arrays. It does, however, supports an array of arrays. In Java, a two-dimensional array ' x' is an array of one-dimensional array : For instance :-
                                                                                       int[][] x = new int[3][5];
The expression x[i] is used to select the one-dimensional array; the expression x[i][j] is ued to select the element from that array. The first element of this array will  be indexed with the "0" value and the last integer will be referenced by "length-1" indexed value. There is no array assignment operator.
Two-dimensional arrays
Two-dimensional arrays are defined as "an array of arrays". Since an array type is a first-class Java type, we can have an array of ints, an array of Strings, or an array of Objects. For example, an array of ints will have the type int[]. Similarly we can have int[][], which represents an "array of arrays of  ints". Such an array is said to be a two-dimensional array.
The command
                   int[][] A = new int[3][4]
declares a variable, A, of type int[][], and it initializes that variable to refer to a newly created object. That object is an array of arrays of ints. Here, the notation int[3][4] indicates that there are 3 arrays of ints in the array A, and that there are 4 ints in each of those arrays.
To process a two-dimensional array, we use nested for loops. We already know about for loop. A loop in a loop is called a Nested loop. That means we can run another loop in a loop. 
 Notice in the following example how the rows are handled as separate objects. 
Code: Java
int[][] a2 = new int[10][5];
 // print array in rectangular form
 for (int r=0; r<a2.length; r++) {
     for (int c=0; c<a2[r].length; c++) {
         System.out.print(" " + a2[r][c]);
     }
     System.out.println("");
 }
In this example, "int[][] a2 = new int[10][5];" notation shows a two-dimensional array. It declares a variable a2 of type int[][],and it initializes that variable to refer to a newly created object. The notation int[10][5] indicates that there are 10 arrays of ints in the array a2, and that there are 5 ints in each of those arrays.
Copying Arrays
After learning all about arrays, there is still one interesting thing left to learn i.e. copying arrays. It means to copy data from one array to another. The precise way to copy data from one array to another is
public static void arraycopy(Object source,
                   int srcIndex,
                   Object dest,
                   int destIndex,
                   int length)
Thus apply system's arraycopy method for copying arrays.The parameters being used are :-
src              the source array
srcIndex     start position (first cell to copy) in the source array
dest            the destination array
destIndex   start position in the destination array
length         the number of array elements to be copied
The following program, ArrayCopyDemo(in a .java source file), uses arraycopy to copy some elements from the copyFrom array to the copyTo array.

public class ArrayCopyDemo{
  public static void main(String[] args){
    char[] copyFrom = {'a','b','c','d','e','f','g','h','i','j'};
    char[] copyTo = new char[5];
    System.arraycopy(copyFrom, 2, copyTo, 05);
    System.out.println(new String (copyTo));
  }
}
In this example the array method call begins the copy of elements from element number 2. Thus the copy begins at the array element 'c'. Now, the arraycopy method takes the copie element and puts it into the destination array. The destination array begins at the first element (element 0) which is the destination array copyTo. The copyTo copies 5 elements : 'c', 'd', 'e', 'f', 'g'. This method will take "cdefg" out of "abcdefghij", like this :

Operators


Operators are symbols that performs some operations on one or more than one operands. Once we declare and initialize variables, we can use operators to perform certain tasks like addition, subtraction etc.
Simple Assignment Operator

=      Simple assignment operator

Arithmetic Operators
     Additive operator (also used for String concatenation)
-      Subtraction operator
*      Multiplication operator
/       Division operator
%     Remainder operator

Unary Operators
+      Unary plus operator; indicates positive value (numbers are positive without this, however)
-       Unary minus operator; negates an expression
++    Increment operator; increments a value by 1
--     Decrement operator; decrements a value by 1
!       Logical compliment operator; inverts the value of a boolean

Equality and Relational Operators
==    Equal to
!=     Not equal to
>      Greater than
>=    Greater than or equal to
<      Less than
<=    Less than or equal to

Conditional Operators
&&     Conditional-AND
||          Conditional-OR
?:         Ternary (shorthand for if-then-else statement)

Type Comparison Operator
instanceof        Compares an object to a specified type

Bitwise and Bit Shift Operators
~         Unary bitwise complement
<<       Signed left shift
>>       Signed right sift
>>>     Unsigned right shift
&         Bitwise AND
^          Bitwise exclusive OR
|           Bitwise inclusive OR
These operators follow some precedence to apply. The table below shows the list of operators that follow the precedence. Operators with higher precedence are evaluated before operators with relatively lower precedence. However, Operators on the same line have equal precedence. The rule to deal with equal precedence operators is that all binary operators except for the assignment operators are evaluated from left to right; assignment operators are evaluated right to left.   
 Operators
 Precedence
 postfix
 expr++,, expr--
 unary
 ++expr, --expr, +expr, -expr ~ !
 multiplicative
 * / %
 additive
 + -
 shift 
 << >> >>>
 relational
 < > , <= , >=  instanceof
 equality
 == , !=
 bitwise AND
 &
 bitwise exclusive OR
 ^
 bitwise inclusive OR
 |
 logical AND
 &&
 logical OR
 ||
 ternary
 ? :
 assignment
 = , +=,  -=,  *=,  /=,  %=, &=,  ^=,  |=,  <<=,  >>=, >>, >=
Java Controll Statements

We all know that the execution of the statements in a program takes place from top to bottom. We will learn how the different kinds of statement have different effects in looping like decision-making statements (if-then, if-then-else, switch), the looping statements (for, while, do-while), and the branching statements (break, continue, return) in Java programming language.
SelectionIn this section we will learn how to use if-then,  if-the else and switch statements in Java programming. These are the two alternative structure statements in Java.
The if statementTo start with controlling statements in Java, lets have a recap over the control statements in C++. You must be familiar with the if-then statements in C++. The if-then statement is the most simpler form of control flow statement. It directs the program to execute a certain section of code. This code gets executed if and only if the test evaluates to true. That is the if statement in Java is a test of any boolean expression. The statement following the if will only be executed when the boolean expression evaluates to true. On the contrary if the boolean expression evaluates to false then the statement following the if will not only be executed.
Lets tweak the example below:
if (a > 1)
System.out.println("Greater than 1");
if (a < 1)
System.out.println("Less than 1");

In the above example if we declare int a = 1, the statements will show some of the valid boolean expressions to the if statement.
We are talking about if statements here so we can't forget the else statement here. The if statement is incomplete without the else statement. The general form of the statement is:if (condition)
statement1;
else
statement2;
The above format shows that an else statement will be executed whenever an if statement evaluates to false. For instance,
if (a>1){
System.out.println("greater than 1");
}
else{
System.out.println("smaller than 1");
}
Lets have a look at a slightly different example as shown below:
class compare{
  public static void main(String[] args){
    int a = 20;
    int b = 40;
    if (a<b){
      System.out.println("a is smaller");
    }
    else{
      System.out.println("b is smaller");
    }
  }
}
The above example shows that we have taken two numbers and we have to find the smallest amongst them. We have applied a condition that if a<b, print 'a is smaller' else print 'b is smaller'. The following is the output which we will get in the command prompt.
C:\javac>javac compare.java

C:\javac>java compare
a is smaller
The switch statement
Sometimes it becomes cumbersome to write lengthy programs using if and if-else statements. To avoid this we can use Switch statements in Java. The switch statement is used to select multiple alternative execution paths. This means it allows any number of possible execution paths. However, this execution depends on the value of a variable or expression. The switch statement in Java is the best way to test a single expression against a series of possible values and executing the code.
Here is the general form of switch statement:
switch (expression){
case 1:
code block1
case 2:
code block2
.
.
.
default:
code default;
}
The expression to the switch must be of a type byte, short, char, or int. Then there is a code block following the switch statement that comprises of multiple case statements and an optional default statement.
The execution of the switch statement takes place by comparing the value of the expression with each of the constants. The comparison of the values of the expression with each of the constants occurs after the case statements. Otherwise, the statements after the default statement will be executed. 
Now, to terminate a statement following a switch statement use break statement within the code block. However, its an optional statement. The break statement is used to make the computer jump to the end of the switch statement. Remember, if we won't use break statement the computer will go ahead to execute the statements associated with the next case after executing the first statement.
Here is an example which will help you to understand more easily:
switch (P {       // assume P is an integer variable
case 1:
System.out.println("The number is 1.");
break;
case 2:
case 4:
case 8:
System.out.println("The number is 2, 4, or 8.");
System.out.println("(That's a power of 2!)");
break;
case 3:
case 6:
case 9:
System.out.println("The number is 3, 6, or 9.");
System.out.println("(That's a multiple of 3!)");
break;
case 5:
System.out.println("The number is 5.");
break;
default:
System.out.println("The number is 7,");
System.out.println(" or is outside the range 1 to 9.");
}
For example the following program Switch, declares an int named week whose value represents a day out of the week. The program displays the name of the day, based on the value of week, using the switch statement.
class Switch{
  public static void main(String[] args){
    int week = 5;
        switch (week){
            case 1:  System.out.println("monday")break;
            case 2:  System.out.println("tuesday")break;
            case 3:  System.out.println("wednesday")break;
            case 4:  System.out.println("thursday")break;
            case 5:  System.out.println("friday")break;
            case 6:  System.out.println("saturday")break;
            case 7:  System.out.println("sunday")break;
            
            default: System.out.println("Invalid week");break;
        }
    }
}
 In this case, "friday" is printed to standard output.
C:\javac>javac Switch.java

C:\javac>java Switch
friday

One other point to note here is that the body of a switch statement is known as a switch block.The appropriate case gets executed when the switch statement evaluates its expression.
Iteration
The concept of Iteration has made our life much more easier. Repetition of similar tasks is what Iteration is and that too without making any errors. Until now we have learnt how to use selection statements to perform repetition. Now lets have a quick look at the iteration statements which have the ability to loop through a set of values to solve real-world problems.   
The for Statement
In the world of Java programming, the for loop has made the life much more easier. It is used to execute a block of code continuously to accomplish a particular condition. For statement consists of tree parts i.e. initialization, condition, and iteration.
 initialization : 
It is an expression that sets the value of the loop control variable. It executes only once.
 condition :  
This must be a boolean expression. It tests the loop control variable against a target value and hence works as a loop terminator. 
 iteration : 
It is an expression that increments or decrements the loop control variable.
 Here is the form of the for loop:
for(initialization; condition; iteration){
//body of the loop
}
For example, a sample for loop may appear as follows: int i;
for (i=0; i<10; i++)
System.out.println("i = " +i); 
In the above example, we have initialized the for loop by assigning the '0' value to i. The test expression, i < 100, indicates that the loop should continue as long as i is less than 100. Finally, the increment statement increments the value of i by one. The statement following the for loop will be executed as long as the test expression is true as follows:System.out.println("i = " + i); 
Well, we can add more things inside a loop. To do so we can use curly braces to indicate the scope of the for loop. Like,
 int i;
for (i=0; i<10; i++) {
MyMethod(i);
System.out.println("i = " + i);


There is a simpler way to declare and initialize the variable used in the loop. For example, in the following code, the variable is declared directly within the for loop: 
for (int i=0; i<100; i++)
System.out.println("i = " +i); 
Lets see a simple example which will help you to understand for loop very easily. In this example we will print 'Hello World' ten times using for loop.
class printDemo{
  public static void main(String[] args){
    for (int i = 0; i<10; i++){
      System.out.println("Hello World!");
    }
  }
}
Here is the output:
C:\javac>javac printDemo.java

C:\javac>java printDemo
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
After learning how to use a for loop, I would like to introduce another form of for loop to be used for iteration through collection and arrays. This form has enhanced the working of for loop. This is the more compact way to use a for loop.
Here we will take an array of 10 numbers.
int[] numbers = {1,2,3,4,5,6,7,8,9,10};

The following program, arrayDemo,displays the usage of for loop through arrays. It shows the variable item that holds the the current value from the array.
class arrayDemo{
  public static void main(String[] args){
    int[] numbers = {1,2,3,4,5,6,7,8,9,10};
    for (int item : numbers) {
      System.out.println("Count is: " + item);
    }
  }
}
Here is the output of the program 
C:\javac>javac arrayDemo.java

C:\javac>java arrayDemo
Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
Count is: 6
Count is: 7
Count is: 8
Count is: 9
Count is: 10
We would like to suggest to use this form of for loop if possible. 
The while and do-while Statements
Lets try to find out what a while statement does. In a simpler language, the while statement continually executes a block of statements while a particular condition is true. To write a while statement use the following form:
while (expression) {
statement(s)
}
Lets see the flow of the execution of the while statement in steps:
1. Firstly, It evaluates the condition in parentheses, yielding true or false.
2. Secondly, It continues to execute the next statement if the condition is false and exit the while statement.
3. Lastly, If the condition is true it executes each of the statements between the brackets and then go back to step 1.
For example:
// This is the Hello program in Java

class Bonjour{
  public static void main (String args[]){
    System.out.print("Bonjour ");            // Say Hello
    int i = 0;                          
  
// Declare and initialize loop counter
        while (i < args.length){              // Test and Loop
      System.out.print(args[i])
            System.out.print(" ");
            i = i + 1;                 // Increment Loop Counter
    }
    System.out.println();                   // Finish the line
  }
}
In the above example, firstly the condition will be checked in the parentheses, while (i<args.length). If it comes out to be true then it will continue the execution till the last line and will go back to the loop again. However, if its false it will continue the next statement and will exit the while loop.
The output is as follows:
C:\javac>javac Bonjour.java

C:\javac>java Bonjour
Bonjour

The while statement works as to for loop because the third step loops back to the top. Remember, the statement inside the loop will not execute if the condition is false. The statement inside the loop is called the body of the loop. The value of the variable should be changed in the loop so that the condition becomes false and the loop terminates.
Have a look at do-while statement now.
Here is the syntax:do {
statement(s)
} while (expression);
Lets tweak an example of do-while loop.
class DoWhileDemo{
  public static void main (String args[]) {
    int i = 0
    do{
      System.out.print("Bonjour");     // Say Bonjour
            System.out.println(" ");
            i = i + 1;               // Increment LoopCounter
    }while (i < 5)
  }
}
In the above example, it will enter the loop without checking the condition first and checks the condition after the execution of the statements. That is it will execute the statement once and then it will evaluate the result according to the condition. 
The output is as follows:
C:\javac>javac DoWhileDemo.java

C:\javac>java DoWhileDemo
Bonjour
Bonjour
Bonjour
Bonjour
Bonjour
You must have noticed the difference between the while and do-while loop. That is the do-while loop evaluates its expression at the bottom of the loop. Hence, the statement in the do-while loop will be executed once. 
Jumping
Sometimes we use Jumping Statements in Java. Using for, while and do-while loops is not always the right idea to use because they are cumbersome to read. Using jumping statements like break and continue it is easier to jump out of loops to control other areas of program flow.
The break Statement
We use break statement to terminate the loop once the condition gets satisfied. 
Lets see a simple example using break statement.
class BreakDemo{
  public static void main(String[] args) {
    for (int i = 0; i < 5; i++) {
      System.out.println(i);
      if (i==3) {
        break ;
      }
    }
  }
}
In the above example, we want to print 5 numbers from 0 to 1 at first using for loop as shown. Then we put a condition that 'if i = = 3', the loop should be terminated. To terminate the loop after satisfying the condition we use break. 
It gives the following output:
C:\javac>javac BreakDemo.java

C:\javac>java BreakDemo
0
1
2
3
The break statement has two forms: labeled and unlabeled. You saw the labeled form in the above example i.e. a labeled break terminates an outer statement. However, an unlabeled break statement terminates the innermost loop like switch, for, while, or do-while statement. 
Now observe the example of unlabeled form below. We have used two loops here two print '*'. In this example, if we haven't use break statement thus the loop will continue and it will give the output as shown below. 
class BreaklabDemo1 
{
public static void main(String[] args) 
{
    for (int i = 0; i < 10; i++) {
    System.out.print("\n");
    for (int j = 0; j<=i; j++)
   {
    System.out.print("*");
    if (j==5)
   {                 // break;
   }
}
}

 
Output:
C:\javac>javac BreaklabDemo1.java

C:\javac>java BreaklabDemo1

*
**
***
****
*****
******
*******
********
*********
**********
C:\javac>
However in the following example we have used break statement. In this the inner for loop i.e."for (int j=0; j<=i; j++)" will be executed first and gets terminated there n then. Then the outer for loop will be executed i.e. "for (int i=0; i<10; i++)". And it will give the output as shown below.
class BreaklabDemo{
  public static void main(String[] args){
    for (int i = 0; i < 10; i++) {
      System.out.print("\n ");
      for (int j = 0; j<=i; j++){
        System.out.print("*");
        if (j==5)
        break;
      }
    }
  }
}
Output:
C:\javac>javac BreaklabDemo.java

C:\javac>java BreaklabDemo

*
**
***
****
*****
******
******
******
******
******
C:\javac>
The continue statementThe continue statement is used in many programming languages such as C, C++, java etc. Sometimes we do not need to execute some statements under the loop then we use the continue statement that stops the normal flow of the control and control returns to the loop without executing the statements written after the continue statement. There is the difference between break and continue statement that the break statement exit control from the loop but continue statement keeps continuity in loop without executing the statement written after the continue statement according to the conditions.

In this program we will see that how the continue statement is used to stop the execution after that.
Here is the code of the program : 
public class Continue{
public static void main(String[] args){
Thread t = new Thread();
int a = 0;
try{
for (int i=1;i<10;i++)
{
if (i == 5)
{
continue;
//control will never reach here (after the continue statement).
//a = i;
}
t.sleep(1000);
System.out.println("chandan");
System.out.println("Value of a : " + a);
}
}
catch(InterruptedException e){}
}
}
Output of the program :
If we write the code in the given program like this : 
if (i == 5 )
{
continue;
a = i;
}


Then the program will generate an error on compile time like : 
C:\chandan>javac Continue.java
Continue.java:12: unreachable statement
a = i;
^
1 error

If we write the code in the given program like this : 
if (i == 5 )
{
continue;
}

Then the program prints the output like : 
C:\chandan>javac Continue.java

C:\chandan>java Continue
chandan
Value of a : 0
chandan
Value of a : 0
chandan
Value of a : 0
chandan
Value of a : 0
chandan
Value of a : 0
chandan
Value of a : 0
chandan
Value of a : 0
chandan
Value of a : 0



Classes in Java

ExceptionsThere are some kind of errors that might occur during the execution of the program. An exception is an event that occurs and  interrupts the normal flow of instructions. That is exceptions are objects that store the information about the occurrence of errors. When any kind of error or unusual condition occurs, these exceptions are being thrown. Any exception used to occur earlier always resulted in a program crash. However, some programming languages like java have mechanisms for handling exceptions. This is known as catching exception in Java. The exceptions that occur in the program can be caught using try and catch block.  Remember, the program will crash if the exception would not be caught. There are three types of exceptions in Java. These are -:

1. Checked Exceptions
2. The error
3. Runtime exception

Error and Runtime exceptions are known as unchecked exceptions. This chapter covers how to throw an exception and catch it. A detailed explanation on the types of exceptions and the advantages of the exceptions.
Basic I/O In this section we will learn about basic input and out put operations in Java. Different kinds of sources and destinations are represented by a Stream like disk files, devices, memory arrays etc.  A Stream is a sequence of data. An Input Stream is used by the program to read data from the source. Similarly, a program uses an Output stream to write data to a destination. It also supports different kinds of data including simple bytes, primitive data types, objects etc. We will learn about I/O Steams and how to use them.
Concurrency Concurrency is generally used to perform multiple tasks simultaneously. In this section we will learn how to write applications to perform multitasking. There are two types of units of execution process and threads. Thread is the most important unit in concurrent programming. There are many processes and threads which are active in a computer system. However only one threads executes at a time even in systems that only have a single execution core.
Regular expressionThe set of strings which are based on common characteristics are shared by each string in the set. Basically, Regular expressions are a set of strings. 
This regular expression as a Java string, becomes "\\\\". That is 4 backslashes to match a single one. As in literal Java strings the backslash is an escape character. The literal string as a single backslash is denoted by "\\". In this chapter we will learn to create a syntax for regular expressions and how to use them.

Inheritance


To know the concept of inheritance clearly you must have the idea of class and its features like methods, data members, access controls, constructors, keywords this, super etc.
As the name suggests, inheritance means to take something that is already made. It is one of the most important feature of Object Oriented Programming. It is the concept that is used for reusability purpose. Inheritance is the mechanism through which we can derived classes from other classes. The derived class is called as child class or the subclass or  we can say the extended class and the class from which we are deriving the subclass is called the base class or the parent class. To derive a class in java the keyword extends is used. To clearly understand the concept of inheritance you must go through the following example.
The concept of inheritance is used to make the things from general to more specific e.g. When we hear the word vehicle then we got an image in our mind that it moves from one place to another place it is used for traveling or carrying goods but the word vehicle does not specify whether it is two or three or four wheeler because it is a general word. But the word car makes a more specific image in mind than vehicle, that the car has four wheels . It concludes from the example that car is a specific word and vehicle is the general word. If we think technically  to this example then vehicle is the super class (or base class or parent class) and car is the subclass or child class because every car has the features of it's parent (in this case vehicle) class.
The following kinds of inheritance are there in java.
  •   Simple Inheritance
  •   Multilevel Inheritance
Pictorial Representation of Simple and Multilevel Inheritance
Simple Inheritance
Multilevel Inheritance
Simple Inheritance
When a  subclass is derived simply from it's parent class then this mechanism is known as simple inheritance. In case of simple inheritance there is only a sub class and it's parent class. It is also called single inheritance or one level inheritance.                                             
eg.
class {
  int x;
  int y;
  int get(int p, int q){
    x=p; y=q; return(0);
    }
    void Show(){
      System.out.println(x);
      }
}

class extends A{
  public static void main(String args[]){
    A a = new A();
    a.get(5,6);
    a.Show();
    }
    void display(){
      System.out.println("B");
      }
}
Multilevel Inheritance
It is the enhancement of the concept of inheritance. When a subclass is derived from a derived class then this mechanism is known as the multilevel inheritance. The derived class is called the subclass or child class for it's parent class and this parent class works as the child class for it's just above ( parent ) class.  Multilevel inheritance can go up to any number of level.
e.g. 
class {
  int x;
  int y;
  int get(int p, int q){
    x=p; y=q; return(0);
    }
    void Show(){
      System.out.println(x);
      }
}
class extends A{
  void Showb(){
    System.out.println("B");
    }
}

class extends B{
  void display(){
    System.out.println("C");
  }
  public static void main(String args[]){
    A a = new A();
    a.get(5,6);
    a.Show();
    }
}
Java does not support multiple Inheritance
Multiple Inheritance
The mechanism of inheriting the features of more than one base class into a single class is known as multiple inheritance. Java does not support multiple inheritance but the multiple inheritance can be achieved by using the interface.
In Java Multiple Inheritance can be achieved through use of Interfaces by implementing more than one interfaces in a class.
super keyword
The super is java keyword. As the name suggest super is used to access the members of the super class.It is used for two purposes in java.
 The first use of keyword super is to access the hidden data variables of the super class hidden by the sub class.
e.g. Suppose class A is the super class that has two instance variables as  int a and float b. class B is the subclass that also contains its own data members named a and b. then we can access the super class (class A) variables a and b inside the subclass class B just by calling the following command.
super.member;
Here member can either be an instance variable or a method. This form of super most useful to handle situations where the local members of a subclass hides the members of a super class having the same name. The following example clarify all the confusions. 
class A{
  int a;
  float b;
  void Show(){
    System.out.println("b in super class:  " + b);
  }

}

class extends A{
  int a; 
  float b;
  B( int p, float q){
    a = p;
    super.b = q;
  }
  void Show(){
    super.Show();
    System.out.println("b in super class:  " super.b);
    System.out.println("a in sub class:    " + a);
  }

  public static void main(String[] args){
    B subobj = new B(15);
    subobj.Show();
  }
}
Output:
C:\>java B
b in super class: 5.0
b in super class: 5.0
a in sub class: 1
Use of super to call super class constructor: The second use of the keyword super in java is to call super class constructor in the subclass. This functionality can be achieved just by using the following command.
super(param-list);
Here parameter list is the list of the parameter requires by the constructor in the super class. super must be the first statement executed inside a super class constructor. If we want to call the default constructor then we pass the empty parameter list. The following program illustrates the use of the super keyword to call a super class constructor. 
class A{
  int a;
  int b;
  int c;
  A(int p, int q, int r){
    a=p;
    b=q;
    c=r;
  }
}
  
  class extends A{
    int d;
    B(int l, int m, int n, int o){
      super(l,m,n);
      d=o;
      }
    void Show(){
      System.out.println("a = " + a);
      System.out.println("b = " + b);
      System.out.println("c = " + c);
      System.out.println("d = " + d);
    }

    public static void main(String args[]){
      B b = new B(4,3,8,7);
      b.Show();
    }
  }
Output:
C:\>java B
a = 4
b = 3
c = 8
d = 7

Collections API

As the name indicates, collections is a group of objects known as its elements. Basically it is a package of data structures that includes ArrayListsLinkedLists,HashSets, etc. A collection is simply an object that groups multiple elements into a single unit. It is also called as a container sometimes. It is used to store, retrieve, manipulate, and communicate aggregate data. Typically, it represents data items that form a natural group and allows duplicate elements while others do not. It consists of both ordered and unordered elements. There is no direct implementation of this interface however SDK provides implementations of more specific sub interfaces like Set and List. The manipulation and passing of collections is done by this interface.
The Two "standard" constructors should be provided by all the general-purpose Collection implementation classes. These classes typically implement Collection indirectly through one of its sub interfaces.
  1. Void (no arguments) constructor which creates an empty collection.
  2. Constructor with a single argument of type Collection, which creates a new collection with the same elements as its argument.
The user can copy any collection using void constructor to produce an equivalent collection of the desired implementation type. As interfaces cannot contain constructors there is no way to enforce this convention. However all of the general-purpose Collection implementations comply this in the Java platform libraries.  
The Java Collections API:
Java Collections of API (Application Programming Intreface) Consists of several interfaces, and classes that implement those interfaces, within the java.util package. It provides tools for maintaining a data container of objects. Each primitive value must be wrapped in an object of its appropriate wrapper class (BooleanCharacterIntegerDouble, etc.) to maintain a collection of primitive data. It is an alternative tool to the creation of custom data structures.
You must be familiar with collections if you have worked with Java programming language . Collection implementations included VectorHashtable, and array are available in earlier (pre-1.2) versions of the Java platform, but those versions do not include the collections framework. Hence the new version of the Java platform contains the collections framework.

Collections Framework


Collections Framework:
The Collections Framework provides a well-designed set of interfaces and classes for storing and manipulating the groups of data into a single unit. The collections framework is a unified architecture which is used to represent and manipulate collections. The framework allows the collections to get manipulated independently, additionally it reduces the programming efforts and increases performance.

It includes implementation of interfaces and algorithms. Basically it is a unified architecture that consists the following collections:  
  1. Interfaces: These are the abstract data types that represent collections. With the help of interfaces we  manipulate collections independently. A hierarchy is generally formed with interfaces in object-oriented languages.
  2. Implementations: They are the reusable data structures with the concrete implementations of the collection interfaces.
  3. Algorithms: Algorithms are used to perform computations, such as searching, sorting etc on the objects that implement collection interfaces. They provide reusable functionality i.e. the same method can be used with different implementations of the collection interfaces. Hence they are also said to be polymorphic.  
  4. General-purpose Implementations: These are the primary implementations of the collection interfaces.  
  5. Infrastructure: Interfaces that provide essential support for the collection interfaces.  
  6. Array Utilities: Utility functions for arrays of primitives and reference objects.
    This functionality was added to the Java platform as a part of the Collections Framework. 
Advantages of collections framework:
The Java Collections Framework provides the following benefits:
  1. Reduces the efforts to learn and use the new APIs: We need not to learn multiple ad hoc collection APIs.  
  2. Fosters software reuse: It provides a standard interface for collections that fosters software reuse and also provides algorithms to manipulate them.  
  3. Reduces the efforts to design new APIs: It reduces the efforts required to design and implement APIs by eliminating the need to produce ad hoc collections APIs.  
  4. Reduces the programming efforts: It provides useful data structures and algorithms that reduces programming efforts due to which we need not to write them ourselves.  
  5. Increases performance: It provides high-performance implementations of useful data structures and algorithms that increases the performance.
  6. Provides interoperability between the unrelated APIs: It helps in establishing a common language to pass collections back and forth to provide interoperability between the unrelated APIs.
  7. Provides resizable capability: Collection is resizable i.e.  it can grow dynamically.
Disadvantages of collections framework:
  1. It must cast to correct type.
  2. avoids the compile-time type checking.

Collection Interfaces

The Collections Framework is made up of a set of interfaces  for storing and manipulating groups of data into a single unit. It consists of several interfaces, and classes that implement those interfaces, contained within the java.util package. It provides tools for maintaining a data container of objects.

Different interfaces describe different types of functionalities.
The following diagrams shows the framework of core collection interfaces hierarchy.

Table of the ordered and unordered Collection interfaces shown as: 
 Interface name
 Ordered
 Allows duplicates
 Maps key to object
 Collection
 No
 Yes
 No
 Set
 No
 No
 No
 List
 Yes
 Yes
 No
 Map
 No
 No
 Yes
 SortedSet
 Yes
 No
 No
 SortedMap
 Yes
 No
 Yes
Collection Interface:
The Collection interface is the root interface for the Java collections hierarchy. It is extended by the ListSet, and the SortedSet interfaces. The Collection interface is used to represent a group of objects, or elements. Typically, it represents data items that form a natural group. Some collection allows duplicate elements while others do not. It consists of both ordered and unordered elements. The declaration of the Collection interface is shown as:
public interface Collection<E>.. 
The <E> syntax tells that, the declared interface is a generic interface i.e. when you declare a Collection instance you should specify the type of object contained in the collection.
This interface supports basic operations like adding and removing. When you try to remove an element, only a single instance of the element in the collection is removed, if it is available. 
Following methods can be used for adding and deleting an element respectively.
boolean add(Object element)    
boolean remove(Object element)
The list of other methods belonging to the Collection interface is shown in the table given below
Method
Uses
 add(E o)
    
  Adds the specified element to this set if it is not already present (optional operation).
         
 clear()
  Removes all of the elements from this set (optional operation).
contains(Object o)
 Returns true if this set contains the specified element.
 equals(Object o)
  Compares the specified object with this set for equality.
 hashCode()
  Returns the hash code value for this set.
  isEmpty() 
  Returns true if this set contains no elements.
 iterator()
  Returns an iterator over the elements in this set.
 remove(Object o)
  Removes the specified element from this set if it is present (optional operation).
 size()
  Returns the number of elements in this set (its cardinality).







Set Interface


The Set interface extends the Collectioninterface. It neither contains duplicate elements nor  maps a key value to an object. It permits a single element to be null. TheSet interface contains only methods inherited from Collection interface, these are shown in the table given below:




Method
Uses
 add( )
Adds an object to the collection
 clear( )
Removes all objects from the collection
 contains( )
Returns true if a specified object is an element within the collection
 isEmpty( )
Returns true if the collection has no elements
 iterator( )
Returns an Iterator object for the collection which may be used to retrieve an object
 remove( )
Removes a specified object from the collection
 size( )
Returns the number of elements in the collection
In the Java platform, Collections Framework provides three general-purpose Set implementation-classes: 
 HashSet
 TreeSet
 LinkedHashSet
HashSet:This is a class which stores its elements in a hash table and doesn't allow to store duplicate collections. This class permits the null element and is used to perform the basic operations such asadd, remove, contains and size. This is the best way to perform set implementation.
TreeSet:The TreeSet implementation is useful when you need to extract elements from a collection in a sorted manner. The elements added to a TreeSet are sortable in an order. It is generally faster to add elements to a HashSet, then converting the collection to a TreeSet for sorted traversal.
 LinkedHashSet:
It is a class which is implements both the Hash table and linked list implementation of the Setinterface. This implementation differs from HashSet that it maintains a doubly-linked list. The orders of its elements are based on the order in which they were inserted into the set (insertion-order). 
SortedSet Interface:
The SortedSet interface extends the Set interface. It maintains its elements in ascending order.  It neither contains duplicate elements nor  maps a key value to an object. It permits a single element to be null. In addition to methods of  the Set interface, it also provides two following methods:
 first( )
 last( ) 
The first( ) method returns the first (lowest) element currently in the collection while the last( )method returns the last (highest) element currently in the collection.
Let see an example that stores a group of numbers to the Hash table using HashSet class.
import java.util.*;

public class SetDemo {
  public static void main(String args[]) { 
    int count[]={3422,10,60,30,22};
   Set<Integer> set = new HashSet<Integer>();
  try{
  for(int i=0; i<5; i++){
    set.add(count[i]);
  }
    System.out.println(set);
  
    TreeSet sortedSet=new TreeSet<Integer>(set);
  System.out.println("The sorted list is:");
    System.out.println(sortedSet);

    System.out.println(
"The First element of the set is: "+
                          (Integer)sortedSet.first());
    System.out.println(
"The last element of the set is: "+
                        (Integer)sortedSet.last());

  }
  catch(Exception e){}
  }
}
This program creates a HashSet and adds a group of numbers, including a number "22" twice. The program than prints out the list of numbers in the set, note that the duplicate number is not added to the set. Then the program treats the set as a TreeSet and displays the sorted list of the set. The first( ) and the last( ) methods display the first & last elements of the set respectively.

List and Queue Interface

List Interface :
The List interface extends the Collectioninterface to define an ordered collection. It is also known as the sequence collection which permits duplicates element to accommodate in  the set but does not map a key value to an object. It permits one or more elements to be null. 
This interface adds position-oriented operations such as insert an element, getan element as well as remove or change an element based on their numerical position in the list. It also performs search operation to allow searching a specified object in the list and returns its numerical position.
In addition to methods of  the Set interface, it provides following three methods shown in the table below:
Method
Uses
 get( )
Returns the element at the specified index position in this collection
 listIterator( )
Returns a List Iterator object for the collection which may then be used to retrieve an object
 remove( )
Removes the element at the specified index position in this collection
Queue Interface:
Queue interface extends the Collection interface to define an ordered collection for holding elements  in a FIFO (first-in-first-out) manner to process them i.e. in a FIFO queue the element that is inserted firstly will also get removed  first. 
Besides basic collection operations, queues also provide additional operations such as insertion,removal, and inspection .
The Methods of this interface are as follows.
Method
Uses
 peek( )
Returns an element but if queue is empty then it returns null
 poll( )
Removes an element but returns null if the queue is empty.
In the Java platform, Collections Framework provides three general-purpose List and Queueimplementation-classes:
ArrayList
LinkedList
RunArrayList
The following program demonstrates the implementation of List and Queue interfaces.
import java.util.*;

public class ListQueueDemo {
  public static void main(String args[]) { 
    int numbers[]={3422,10,60,30};
   List <Integer>list = new ArrayList<Integer>();
  try{
  for(int i=0; i<5; i++){
    list.add(numbers[i]);
  }
  System.out.println("the List is: ");
    System.out.println(list);
  LinkedList <Integer>queue = new LinkedList<Integer>();
  for(int i=0; i<5; i++){
    queue.addFirst(numbers[i]);
  }
  System.out.println("The Oueue is: ");
     System.out.println(queue);
  queue.removeLast();
    System.out.println("After removing last element the queue is: "+ queue);
    
  }
  catch(Exception e){}
  }
}



This program creates a List and Queue, and inserts a group of numbers in these lists. The program than prints out the list of numbers in the set. The addFirst( ) and removeLast( )methods add and remove an element in a FIFO manner, i.e. the first element of the queue is removed first .

Introduction to Map and SortedMap Interface


Introduction to Map and SortedMap Interface

                          
Map Interface:
Map is an object that maps keys to values. It is not an extension of thecollection interface rather it has own interface hierarchy. Map provides a more general way for storing elementswithout containing duplicate keys. It allows you to store pairs of elements, termed "keys" and "values", where each key maps to one value. Thus the keys in a map must be unique.
The Map interface methods can be broken down into three sets of operations:
Altering: The alteration operations allow you to add and remove key-value pairs from the map. Both the key and value can be null.
Querying: 
The query operations allow the user to retrieve key/value pairs from the Map.
Providing alternative views: 
This method allow you to work with the different views which can be used to analyze Map key/value Objects.
Map Methods Returning Views:
These methods return objects which allow you to traverse the elements of the Map, and also delete elements from the Map.
Method
Uses
 entrySet()
Returns a Set view of the mappings contained in the map. Each element in the set is a Map.Entry object which can have it's key and value elements accessed with getKey() and getValue() methods (also has a setValue() method)
keySet()Returns a Set view of the keys contained in the map. Removing elements from the Set will also remove the corresponding mapping (key and value) from the Map
values()Returns a Collection view of the values contained in the map. Removing elements from the Collection will also remove the corresponding mapping (key and value) from the Map
Map.Entry Interface:

Each element is a map has a key and value. Each key-value pair is saved in ajava.util.Map.Entry object. A set of these map entries can be obtained by calling a map'sentrySet( ) method. Iterating over a map is done by iterating over this set.
The Collections Framework provides three general-purpose Map implementation:
HashMap
TreeMap
LinkedHashMap
HashMap:The HashMap is a class which is used to perform some basic operations such as inserting,deleting, and locating elements in a Map . The  java.util.HashMap class is implemented with and roughly equivalent to a Hashtable  except that it is unsynchronized and permits null. It works with the Iterators requires a well-defined implementation of the method hashCode( ).
TreeMap:The TreeMap implementation is useful when you need to traverse the keys from a collection in a sorted manner. The elements added to a TreeMap must be sortable in order to work properly. It is depend upon the size of the specified collection, it may be faster to add elements to aHashMap , then convert the map to a TreeMap for traversing the sorted keys.
LinkedHashMap:A LinkedHashMap is implemented using both Hash table and linked list implementation of theMap interface. This implementation differs from HashMap that maintains a doubly-linked list running through all of its entries in it. The orders of its elements are based on the order in which they were inserted into the set (insertion-order). 
The list of methods supported by Map interface are shown in the table given below:
Method
Uses
 put(Object key, Object value)
Associates the specified value with the specified key in the map.
 clear( )
Removes all mappings from the map
 putAll(Map t)
Copies all of the mappings from the specified map to the map.
 isEmpty( )
Returns true if this map contains no key-value mappings.
 iterator( )
Returns an Iterator object for the collection which may be used to retrieve an object.
 remove(Object key)
Removes the mapping for this key from this map if it is present.
 keySet( ) Returns a set view of the keys contained in this map.
 entrySet( ) Returns a set view of the mappings contained in this map.
 values( ) Returns a collection view of the values contained in this map.
 size( )
Returns the number of key-value mappings in this map.
SortedMap Interface:
The Collection Framework provides a special Map interface for maintaining elements in a sorted order called SortedMap The SortedMap interface extends the Map interface which maintains its elements in ascending order. Working with a SortedMap is just similar to aSortedSet except, the sort is done on the map keys. In addition to methods of  the Map interface, it provides two methods shown as:
firstKey( )
lastKey( ) 
The firstKey( ) method returns the first (lowest) value currently in the map while the lastKey( )method returns the last (highest) value currently in the map.
Let see an example implementing the HashMap and TreeMap class.
import java.util.*;

public class MapDemo {
  public static void main(String args[]) { 
    String days[]={"Sunday""Monday""Tuesday""Wednesnday",
                         
"Thursday""Friday""Saturday"};
   Map<Integer, String> map = new HashMap<Integer, String>();
  try{
  for(int i=0; i<7; i++){
    map.put(i, days[i]);
  }
  
  TreeMap<Integer, String> tMap=new TreeMap<Integer, String>(map);
     //Rerieving all keys
    System.out.println("Keys of tree map: " + tMap.keySet());
    //Rerieving all values
    System.out.println("Values of tree map: " + tMap.values());
    //Rerieving the First key and its value
    System.out.println("First key: " + tMap.firstKey() 
                  " Value: " 
+ tMap.get(tMap.firstKey()) "\n");
      
    //Removing the first key and value
    System.out.println("Removing first data: " 
                          + tMap.remove
(tMap.firstKey()));
    System.out.println("Now the tree map Keys: " + tMap.keySet());
    System.out.println("Now the tree map contain: " + tMap.values() "\n");
    //Rerieving the Last key and value
    System.out.println("Last key: " + tMap.lastKey() +
                       
" Value: " + tMap.get(tMap.lastKey()) "\n");  
    //Removing the last key and value
    System.out.println("Removing last data: " + tMap.remove(tMap.lastKey()));
    System.out.println("Now the tree map Keys: " + tMap.keySet());
    System.out.println("Now the tree map contain: " + tMap.values());
  }
  catch(Exception e){}
  }
}

The given program stores the values mapping with their keys to the map. The keySet( ) method retrieves all keys from the map and the values( ) method retrieves all the values added to a map. The remove( ) method removes the key from the map with its value specified in it.

collection Implementations


The Collections Framework provides a well-designed set of interfaces and classes used for storing and manipulating groups of data into a single unit. The collections framework is a unified architecture which is used to represent and manipulate collections. The framework allows the collections to get manipulated independently as well as reduces programming effort for increasing performance.
It includes implementations of interfaces, and algorithms included in it to manipulate them. Basically it is a unified architecture that consists the following collections:  
Implementations are the reusable data objects used to store collections, which implement the collection interfaces.  Implementations are also responsible for documenting the operations which they support. All of the general-purpose implementations of the Java platform support all of the optional operations.
The following kinds of implementations are described below:
  • General-purpose implementations: These are the most commonly used implementations, designed for performing all optional operations contained within the defined interfaces. They are summarized in the table below.
InterfacesImplementations
 Hash tableTreeLinked listHash table + Linked list
SetHashSetTreeSet LinkedHashSet
List  LinkedList 
Queue    
MapHashMapTreeMap LinkedHashMap

  • The Java Collections Framework provides several general-purpose implementations of theSetList , and Map interfaces. Each of the general-purpose implementations provides all optional operations contained in its interface. All permit null elements, keys, and values.
  • Special-purpose implementations: These are designed to use in special situations and display nonstandard performance characteristics, usage restrictions, or behavior.
  • Concurrent implementations: These are designed to support high concurrency. These implementations are part of the java.util.concurrent package.
  • Wrapper implementations: These are used in combination with other types of implementations.
  • Convenience implementations: These are mini-implementations, typically made via static factory methods, that provide convenient, efficient alternatives to general-purpose implementations for special collections.
  • Abstract implementations: These are implementations that facilitate the construction of custom implementations.
The following description describes the categories in which the Collection Framework interfaces are implemented.
The Set implementations are grouped into general-purpose and special-purpose implementations.List implementations are grouped into general-purpose and special-purpose implementations.Map implementations are grouped into general-purpose, special-purpose, and concurrent implementations. The Queue implementations are grouped into general-purpose and concurrent implementations.

Collection Algorithms


Algorithms:
The Collections and Arrays classes, available as a part of the Collections Framework, support various algorithms. The  Java platform provides great majority of the algorithms to perform different kind of operations such as sorting andsearching.
I. Sorting Algorithm:
The sort algorithm reorders a List such that its elements are in ascending order according to an ordering relationship. The sort operation uses a slightly optimized merge sort algorithm which is fast and stable. TreeSet and TreeMap classes offers a sorted version of sets and maps, there is no sorted List collection implementation. Sorting of a List is done with the sort( ) method.
For example, the following program prints the arguments (the arguments, given through command line) of a  List in an alphabetical order.
import java.util.*;

public class SortDemo {
    public static void main(String[] args) {
        List<String> list = Arrays.asList(args);
        Collections.sort(list);
        System.out.println(list);
    }
}

Searching Algorithm :
Besides sorting, the Collections and Arrays classes provide a mechanism to search a List or an array, as well as to find the first and last values within a Collection. The binarySearch algorithm searches for a specified element in a sorted List. This algorithm  takes a List and an element to search for the search key. This form assumes that the List is sorted in ascending order according to the natural ordering of its elements.
Before searching an element, the List must be sorted, Once you have sorted the List, usingCollection.sort( ) method, you can perform a quickly binary search  operation using the overridden binarySearch( ) method. 
For example, the following program prints the sorted arguments list (the arguments, given through command line) and then search the position of a specified key value.
import java.util.*;

public class SearchDemo {
    public static void main(String[] args) {
    try{
        List<String> list = Arrays.asList(args);
        Collections.sort(list);
        System.out.println("The sorted list is: "+list);
    int pos = Collections.binarySearch(list, list.get(2));
    System.out.println("The position of the searched element is : "+pos
                     +
" and the element is:"+list.get(2));
    }
    catch(Exception e){}
           
    }
}


Java 6.0 Collection Framework


Some of the new collections APIs have been introduced in Java 6.0. These are:
  1. Deque: It is used to represent Double ended queue. With the help of this collection we can add or remove elements at both the ends. Deque implementation can be used as Stack (Last in first out) or Queue (First in First Out). There are two methods in Deque, which are used for insertion, retrieval and removal of elements. One returns status or special value for each operation and the other will throw exception if it fails in an operation.
  1. BlockingDeque: It is similar to Deque but with added functionality. When we try to insert an element in a BlockingDeque and if the BlockingDeque is already full then the element can wait till the space becomes available to insert an element. There are four methods available for BlockingDeque.
    • Methods throws exception
    • Methods that times out (Waits for a given time for space to available)
    • Methods that blocks (Waits indefinitely for space to available)
    • Methods returns special value
  1. NavigableSet: It is used to return the closest matches of elements. For instance if we want retrieve the element, which is immediately greater than, or lower than element 20 or if we want to retrieve all elements greater than or lower than 35 from sorted set elements [10,20,35,5] we can use NavigableSet methods that becomes just a method call.ConcurrentSkipListSet is one of the class that implements NavigableSet.
  1. NavigableMap: In NavigableSet, methods use to return values, but in NaviagableMap methods used to return the key,value pair. ConcurrentSkipListMap is the one of the class which implements NaviagableMap
Some of the new Classes are: 
  1. ArrayDeque: ArrayDeque is a class that implements Deque. If used as a stack or linked list, it performs much faster than before. It is neither thread safe nor has capacity restrictions.
  1. LinkedBlockingDeque: It implements BlockingDeque. Maximum capacity can be specified by using BlockingDeque interface. However the maximum capacity will be Integer.MAX_VALUE if not specified.
  1. ConcurrentSkipListSet: ConcurrentSkipListSet is one of the class that implements NavigableSet. It is used to return the closest matches of elements.
  1. ConcurrentSkipListMap: ConcurrentSkipListMap is the one of the class which implements NaviagableMap. In NavigableSet, methods use to return values.
  1. AbstractMap.SimpleEntry: The key value pair of one single entry in a Map is held by the instance of this class. Moreover it is a static nested class nested inside abstractMap class.
       
  2. AbstractMap.SimpleImmutableEntry: This class is similar to AbstractMap.SimpleEntryclass however it has one difference that it throws the exceptionUnsupportedOperationException when we try to set a value whileAbstractMap.SimpleEntry doesn’t.
Updated Classes in Java 6.0
  1.  LinkedList
     
  2. TreeSet
     
  3. TreeMap
     
  4. Collections
Modified classes                      
To implement the new interfaces we modify some classes like TreeSet is modified to implement NavigableSet, LinkedList is modified to implement Deque, TreeMap is modified to implement NavigableMap etc. Some of the new methods like newSetFromMap and asLifoQueue have been added to Collections 2.
 Hence the bi- directional traversal has become easier with java6.0 collections. We can even retrieve elements as desired.

Collections Framework Enhancements


In Collection framework, we are able to improve the performance hashing function that is used by java.util.HashMap. It provides some new Collection interfaces also.

Following new Interfaces and Classes are provided in JAVA SE 6 :
  • Deque – Deque is a interface. It is a short for “Double Ended Queue”. This interface defines some methods that access the element at both ends. That means by the methods of this interface we can add and remove the elements at both ends.
  • ArrayDeque – ArrayDeque Class implements a Deque interface. This class have no capacity restriction, it can grow according to usage. If the external Synchronization is not available then it don’t support concurrent access by multiple thread.
Constructors Details :
  • public ArrayDeque()
    Above Constructor is used to make a empty array deque with an default capacity that 16 elements.
  • public ArrayDeque(int numElements)
    Above Construtor is used to make a empty array deque with the initial capacity that is sufficient to hold the specified elements.
  • public ArrayDeque<Etype>()
    Etype is the type of the elements that held in this Collection. Above Constructor is used to make a array deque containing elements of specified type.
Methods Details :
  • void addFirst(Etype e)
    Above method is used to insert the element at the starting point of the array deque
  • void addLast(Etype e)
    Above method is used to insert the element at the end point of the array deque.
      Above two methods throws following Exception:
  1. IllegalStateException – Due to capacity restriction the element cannot be added.
  2. ClassCastException – Class of the specified element prevents it from being added to this deque
  3. NullPointerException – If specified element is null.
  4. IllegalArgumentException – If element having some property that prevent it from being added to this deque
  • boolean offerFirst(Etype e)
    Above method is also used to insert the specified element at the starting point of the array deque. This method is preferable when we using a capacity restricted deque. When element is added in array deque then its return true else it return false.
  • boolean offerLast(Etype e)
    Above method is also used to insert the specified element at the end point of the array deque. This method is preferable when we using a capacity restricted deque. When element is added in array deque then its return true else it return false.
    Above two methods throws following Exception: 
  1. ClassCastException – Class of the specified element prevents it from being added to this deque.
  2. NullPointerException – If specified element is null.
  3. IllegalArgumentException – If element having some property that prevent it from being added to this deque.
  • Etype removeFirst()
    Above method is used to remove the first element of the array deque. And we can also retrieve this element. But if array deque is empty then it throws a NoSuchElementException.
  • Etype removeLast()
    Above method is used to remove the last element of the array deque. And we can also retrieve this element. But if array deque is empty then it throws a NoSuchElementException.
  • Etype pollFirst()
    Above method is same as removeFirst(). It is also used to retrieve and remove the first element of the deque. But it does not throws any Exception even the deque is empty, its only return null.
  • Etype pollLast()
    Above method is same as removeLast(). It is also used to retrieve and remove the last element of the deque. But it does not throws any Exception even the deque is empty, its only return null.
  • Etype getFirst()
    Above method is used just for retrieving the first element of deque. But if array deque is empty then it throws a NoSuchElementException.
  • Etype getLast()
    Above method is used just for retrieving the last element of deque. But if array deque is empty then it throws a NoSuchElementException.
  • Etype peekFirst()
    Above method is same as getFirst().It is also used to retrieving the first element of the deque. But it does not throws any Exception even the deque is empty, its only return null.
  • Etype peekLast()
    Above method is same as getLast().It is also used to retrieving the last element of the deque. But it does not throws any Exception even the deque is empty, its only return null.
  • boolean removeFirstOccurrence(Object obj)
    Above method is used to remove the first occurrence of the specified element. It return true when the specified element was remove. But if the deque does not contain the specified element it is unchanged.
  • boolean removeLastOccurrence(Object obj)
    Above method is used to remove the last occurrence of the specified element. It return true when the specified element was remove. But if the deque does not contain the specified element it is unchanged.
The following example demonstrates the above methods:
import java.io.*;
import java.util.*;
public class NewDeque
{
public static void main(String s[])throws IOException
 {
Console c=System.console();
  if(c==null)  
  {
   System.err.println("Console object is not available");
   System.exit(1);
  }
   ArrayDeque<String> dqname = new ArrayDeque<String>();
   String name = null;
name = c.readLine("Enter any String: ");
   dqname.add(name);    
   show(dqname);
 
   name=c.readLine("Enter any string to add on starting 
point of deque by addFirst():");
   dqname.addFirst(name);
   show(dqname);
name=c.readLine("Enter any string to add on ending 
point of deque by addLast():");
   dqname.addLast(name);
   show(dqname);
name=c.readLine("Enter any string to add on starting
 point of deque by offerfirst() :");
   dqname.offerFirst(name);
   show(dqname);
name=c.readLine("Enter any string to add on ending 
point of deque by offerlast() :");
   dqname.offerLast(name);
   show(dqname);
System.out.println("Getting the first element 
by using getFirst()");
   String str1=dqname.getFirst();
   System.out.println("First element is  : "+str1);
System.out.println("Getting the Last element by using 
getLast()");
   str1=dqname.getLast();
   System.out.println("Last element is  : "+str1);
 
System.out.println("Getting the first element by 
using peekFirst()");
   str1=dqname.peekFirst();
   System.out.println("First element is  : "+str1);
 
System.out.println("Getting the Last element by
 using peekLast()");
   str1=dqname.peekLast();
   System.out.println("Last element is  : "+str1);
System.out.println("Removing the first element
 by using removeFirst()");
   str1=dqname.removeFirst();
   show(dqname);   
System.out.println("Removing the Last element
 by using removeLast()");
   str1=dqname.removeLast();
show(dqname);
System.out.println("Removing the first element
 by using pollFirst()");
   str1=dqname.pollFirst();
   show(dqname);
System.out.println("Removing the Last element
 by using pollFirst()");
   str1=dqname.pollLast();
   show(dqname);
 }
static void show(ArrayDeque<String> dqname)
   {
   Iterator<String> nameIter = dqname.iterator();
    while(nameIter.hasNext())
System.out.println(nameIter.next()); 
   }
}


Map Example


We already know that NavigableMap is similar to NavigableSet. In NavigableMap we use methods to return the key value pair like navMap.put(1, "January"); whereas in NavigableSet we use methods to return values. ConcurrentSkipListMap is the one of the class which implements NavigableMap. Lets have a look at the example.
Description of program:
The following program helps you in inserting, removing and retrieving the data from the NavigableMap. It uses the put() method to add the element. If you want to retrieve the data at first and last position from the NavigableMap, you use the firstEntry() and lastEntry()methods. The descendingMap() method represents all data to the NavigableMap in descending order. 
You can retrieve the nearest less than or equal to the given number and the greatest key strictly less than the given number floorEntry() and lowerEntry() methods. And you retrieve a key-value associated with the least key strictly greater than the given key, you use the higherEntry()method. The pollFirstEntry() method removes the first data from the NavigableMap andpollLastEntry() method also removes the data at the last position from the NavigableMap.
Here is the code of program:
import java.util.*;
import java.util.concurrent.*;

public class NavigableMapExample{
  public static void main(String[] args) {
    System.out.println("Navigable Map Example!\n");
    NavigableMap <Integer, String>navMap = new
                       
ConcurrentSkipListMap<Integer, String>();
    navMap.put(1"January");
    navMap.put(2"February");
    navMap.put(3"March");
    navMap.put(4"April");
    navMap.put(5"May");
    navMap.put(6"June");
    navMap.put(7"July");
    navMap.put(8"August");
    navMap.put(9"September");
    navMap.put(10"October");
    navMap.put(11"November");
    navMap.put(12"December");
    //Displaying all data
    System.out.println("Data in the navigable map: " +
                                          navMap.descendingMap
()+"\n");
    //Retrieving first data
    System.out.print("First data: " + navMap.firstEntry()+"\n");
    //Retrieving last data
    System.out.print("Last data: " + navMap.lastEntry()+"\n\n");
    //Retrieving the nreatest less than or equal to the given key
    System.out.print("Nearest less than or equal to the given key: "
                            
+ navMap.floorEntry(5)+"\n");
    //Retrieving the greatest key strictly less than the given key
    System.out.println("Retrieving the greatest key strictly less than
                         the given key: " 
+ navMap.lowerEntry(3));
    //Retrieving a key-value associated with the least key
                    strictly greater than the given key

    System.out.println("Retriving data from navigable map greter than
                 the given key: " 
+ navMap.higherEntry(5)+"\n");
    //Removing first
    System.out.println("Removing First: " + navMap.pollFirstEntry());
    //Removing last
    System.out.println("Removing Last: " + navMap.pollLastEntry()+"\n");
    //Displaying all data
    System.out.println("Now data: " + navMap.descendingMap());
  }
}


Linked List Example


This section discusses an example to demonstrate the various methods of List interface. We are using two classesArrayList and LinkedList in the example code. The code below is similar to the previous example, but it performs many List operationsLets discuss the example code.
Description of program:
This program helps you in storing the large amount of data as a collection. The LinkedList is a part of collection that constructs a list containing the elements of the specified collection. Iterator methods returns the values in the order in which they are stored.
If you want to insert the data in the linkedList then use add() method. The hasNext() method returns true if the iterator contains more elements and the next() method returns the next element in the iteration. To insert and remove the data at first, last and specified position in the linkedList, you use the addFirst()addLast()add()removeFirst()removeLast() and remove()methods. To retrieve the element with respect to a specified position use the getFirst(),getLast() and get() methods.  
Here is the code of program:
import java.util.*;

public class LinkedListExample{
  public static void main(String[] args) {
    System.out.println("Linked List Example!");
    LinkedList <Integer>list = new LinkedList<Integer>();
    int num1 = 11, num2 = 22, num3 = 33, num4 = 44;
    int size;
    Iterator iterator;
    //Adding data in the list
    list.add(num1);
    list.add(num2);
    list.add(num3);
    list.add(num4);
    size = list.size();
    System.out.print"Linked list data: ");  
    //Create a iterator
    iterator = list.iterator();     
    while (iterator.hasNext()){
      System.out.print(iterator.next()+" ");  
    }
    System.out.println();
    //Check list empty or not
    if (list.isEmpty()){
      System.out.println("Linked list is empty");
    }
    else{
      System.out.println"Linked list size: " + size);
    }
    System.out.println("Adding data at 1st location: 55");
    //Adding first
    list.addFirst(55);
    System.out.print("Now the list contain: ");
    iterator = list.iterator();
    while (iterator.hasNext()){
      System.out.print(iterator.next()+" ");  
    }
    System.out.println();
    System.out.println("Now the size of list: " + list.size());
    System.out.println("Adding data at last location: 66");
    //Adding last or append
    list.addLast(66);
    System.out.print("Now the list contain: ");
    iterator = list.iterator();
    while (iterator.hasNext()){
      System.out.print(iterator.next()+" ");  
    }
    System.out.println();
    System.out.println("Now the size of list: " + list.size());
    System.out.println("Adding data at 3rd location: 55");
    //Adding data at 3rd position
    list.add(2,99);
    System.out.print("Now the list contain: ");
    iterator = list.iterator();
    while (iterator.hasNext()){
      System.out.print(iterator.next()+" ");  
    }
    System.out.println();
    System.out.println("Now the size of list: " + list.size());
    //Retrieve first data
    System.out.println("First data: " + list.getFirst());
    //Retrieve lst data
    System.out.println("Last data: " + list.getLast());
    //Retrieve specific data
    System.out.println("Data at 4th position: " + list.get(3));
    //Remove first
    int first = list.removeFirst();
    System.out.println("Data removed from 1st location: " + first);
    System.out.print("Now the list contain: ");
    iterator = list.iterator();
    //After removing data
    while (iterator.hasNext()){
      System.out.print(iterator.next()+" ");  
    }
    System.out.println();
    System.out.println("Now the size of list: " + list.size());
    //Remove last
    int last = list.removeLast();
    System.out.println("Data removed from last location: " + last);
    System.out.print("Now the list contain: ");
    iterator = list.iterator();
    //After removing data
    while (iterator.hasNext()){
      System.out.print(iterator.next()+" ");  
    }
    System.out.println();
    System.out.println("Now the size of list: " + list.size());
    //Remove 2nd data
    int second = list.remove(1);
    System.out.println("Data removed from 2nd location: " + second);
    System.out.print("Now the list contain: ");
    iterator = list.iterator();
    //After removing data
    while (iterator.hasNext()){
      System.out.print(iterator.next()+" ");  
    }
    System.out.println();
    System.out.println("Now the size of list: " + list.size());
    //Remove all
    list.clear();
    if (list.isEmpty()){
      System.out.println("Linked list is empty");
    }
    else{
      System.out.println"Linked list size: " + size);
    }
  }
}

Reflection API 

Reflection API is a powerful technique (that provides the facility) to find-out its environment as well as to inspect the class itself. Reflection API was included in Java 1.1. The classes of Reflection API are the part of the package java.lang.reflect and the methods of Reflection API are the parts of the package java.lang.class. It allows the user to get the complete information about interfaces, classes, constructors, fields and  various methods being used. It also provides an easy way to create a Java Application that was not possible before Java 1.1. You can create methods like event handlers, hash code etc and also find-out the objects and classes.
With the help of Reflection API you can get the information about any class of the java.lang package. There are some useful methods like getName() and getInterfaces(), which allows us to retrieve the name of the class and the interfaces of the package respectively.
Avoid using Reflection API in those applications wherever it affects the application's performance, security related code of the application such as in Applet programming. Reflection API also affects the application if the private fields and methods are there.
Here we are providing few of the examples to give a better overview of the Reflection API 

implemented Interfaces


Create an object of class Finterface and assign it with java.util.Integer.class.. Now retrieve Interfaces (included in the program) and store their references in an array of class Class by using the getInterfaces() method.
Here is the code of the Example :
Finterface.java:   
import java.lang.reflect.*;

public class Finterface {
  public static void main(String str[]){
  Class cls = java.util.List.class;
  Class[] intfs = cls.getInterfaces();
  int len = intfs.length;
  for (int i =0; i < len; i++)
  {
  System.out.println(intfs[i]);
  }

  }
}

Retrieving the class name through Reflection API

A more generic way, how to retrieve the name of the class (that is used in the program) that reflects the package name by using the getName() method. Here is an example that provides the proper way to use the getName() method.
Here we create an object of class Fclass and assign the reference of the class java.util.Integer.class to it. Now retrieve the class name (that is included in the program) by using the getName() method.
Here is the code of the Example :



Fclass.java
import java.lang.reflect.*;
public class Fclass{
  public static void main(String[] args){
    Class cls = java.lang.Integer.class;
    String info;
    info = cls.getName();     // It will show java.lang.Integer
    System.out.println(info);
  }
}



Finding out the super class name of the class


Here we show you the way to find out the Superclass name by using the getSuperclass() method. The given example demonstrates the use of getSuperclass() method in more detail.
Create a class "Fsupercls". Po
pulate it with the Checkbox objects. Now retrieve the Superclass name by using the getSuperclass() method.
Here is the code of the Example :
Fsupercls.java: 
import java.lang.reflect.*;
import java.awt.*;

public class Fsupercls  {
     public static void main(String[] args) {
       Checkbox big = new Checkbox();
       printName(big);
     }
     static void printName(Object objct) {
     Class cls = objct.getClass();
     Class sup = cls.getSuperclass();   
     System.out.println(sup);
     }
}


Getting the method name used in the Application


In this section we describe how to retrieve method name by using the getMethods() method. Here is an example that demonstrates the use of the getMethods() method in more detail.
Define a class named "Fmethod" and then create an object of this class and get the reference of java.util.Integer.class into it.Now retrieve the method name by using the getMethods() method.
Here is the code of the Example :
Fmethod.java:  
import java.lang.reflect.*;
public class Fmethod{
  public static void main(String[] args){
    Class cls = java.lang.Integer.class;
    Method method = cls.getMethods()[0];
    String info;
    info = method.getName()
    System.out.println(info);
  }
}


Finding out the object of the class

This section illustrates how to retrieve an object name that reflects the package name by using the object.getClass() method. Here is an example that provides the proper usage of the object.getClass() method in more detail.
Create a class "Fobject" with an object Checkbox. Now retrieve an object namethat reflects the package name by using the object.getClass() method.
Here is the code of the Example :
Fobject.java:
import java.lang.reflect.*;
import java.awt.*;
public lass Fobject{
   public static void main(String[] args) {
       Checkbox bos = new Checkbox();
       printName(bos);
   }
   static void printName(Object objct) {
      Class cls = objct.getClass();
      String strng = cls.getName();
      System.out.println(strng);
  }
}


Finding out the class fields


This section explores you, how to retrieve the fields of the class by using the getFields() method. For this we are taking an example that provides the use of the getFields() method in detailed way.
Create a class "Ffield" and create an object of this class and assign it the reference of java.util.Integer.class class.Now retrieve the class fields by using the getFields() method.
Here is the code of the Example :
Ffield.java:
import java.lang.reflect.*;
public class Ffield{
  public static void main(String[] args){
    Class cls = java.lang.String.class;
    Field field = cls.getFields()[0];
    String name;
    name = field.getName();     // It'll show CASE_INSENSITIVE_ORDER
    System.out.println(name);
  }
}


Getting information about Construct


In this section you will learn, how to retrieve the information about the constructor by using the getConstructors() method. Here is an example that provides the usage of the getConstructors() method.
Declare a class "Fconstructor" and thencreate an object of this class and take the reference of the class java.util.Integer.class into it. Make a Constructor named constructor. Now retrieve the name of the constructor by using the getConstructors() method.
Here is the code of the Example :



Fconstructor.java
import java.lang.reflect.*;
public class Fconstructor{
  public static void main(String[] args){
    Class cls = java.lang.String.class;
    Constructor constructor = cls.getConstructors()[0];
    String name;
    name = constructor.getName();      //It'll show java.lang.String
    System.out.println(name);
  }
}


No Argument Constructor Example


Here is an example that provides the usage of thenewInstance() method in more detail.
Here in our example we have used"forName()" static method of Classand then we have invokednewInstance() method to create a new object without any argument. InvokingnewInstance() method throws a NoSuchMethodException if the class does not have any no-argument constructor.
NoArgConstructor.java

import java.lang.reflect.*;
import java.util.ArrayList;

public class NoArgConstructor {
  public static void main(String str[]){
    try{
       ArrayList list = (ArrayList)
       (
Class.forName("java.util.ArrayList").newInstance());
       System.out.println("No-Argument Constructor exist.");
       System.out.println("New Object created Successfully");
    }catch(Exception e){
      System.out.println("No-argument constructor does not exist.");
      System.out.println(e.getMessage());
    }
   }
}
Output:

Getting Methods Information of a class


n this part of tutorial you will learn how to retrieve information of all methods of a class (that included in the program) byusing the getMethods() method. Here is an example that provides the usage of thegetMethods() method in more detail.
Create an object of class. Now retrieve all methods list in Method[] array. Now we can get other information of that methods by using different methods on that method object.
Here is the example code of MethodInfo.java
MethodInfo.java

import java.lang.reflect.*;
import java.util.HashSet;

public class MethodInfo{
  public static void main(String str[]){
  HashSet set = new HashSet();
  Class classObj = set.getClass();
      Method[] methods = classObj.getMethods();
      for (int i = 0; i < methods.length; i++) {
         String methodName = methods[i].getName();
            System.out.println("Name: " + methodName);
            String returnString =
               methods[i].getReturnType().getName();
            System.out.println("Return Type: " + returnString);
            Class[] parameterTypes = 
               methods[i].getParameterTypes();
            System.out.print("Parameter Types: ");
            for (int k = 0; k < parameterTypes.length; k ++) {
               String parameterName = 
                  parameterTypes[k].getName();
               System.out.print(" " + parameterName);
         }
         System.out.println();
      }
   }
}
Output:


Identifying array using Reflection

Here is an example that demonstrates the use of the isArray()method for identification of Array object.
In our example we are taking two variable objects of type integer and String respectively. In these two one is an array and another is not. So when we will callisArray() method on them then Array variable "var" returns true hence you will get the following message on your command prompt. "var is an Array" and will return "false" in case of string object "notvar".
Here is the example code for IdentifyArray class:
IdentifyArray.java

import java.lang.reflect.*;

public class IdentifyArray {
  public static void main(String str[]){
  int[] var = {1,2,3,4};
  String notvar="Hello";
  Class varcls= var.getClass();
  Class notvarcls= notvar.getClass();
  if(varcls.isArray())
    System.out.println(" var is an Array ");
  else
    System.out.println(" var is not an Array ");
  if(notvarcls.isArray())
    System.out.println(" notvar is an Array ");
  else
    System.out.println(" notvar is not an Array ");
  }
}
Output:     






No comments:

Post a Comment