Java Introduction and Language

Embed Size (px)

Citation preview

  • 7/31/2019 Java Introduction and Language

    1/53

  • 7/31/2019 Java Introduction and Language

    2/53

    2

    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, psionm5, and any other device with Windows CE/Pocket PC 2002/2003/2005).

    3) 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.

  • 7/31/2019 Java Introduction and Language

    3/53

    3

    Java Features

    4) Casesensitive:

    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,

    5) Java is Simple and platform Independent

    Platform Independent

    The 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.

  • 7/31/2019 Java Introduction and Language

    4/53

    4

    Simple

    There 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 Oriented

    To 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.

    Robust

    Java has the strong memory allocation and automatic garbage collection mechanism. It

    provides the powerful exception handling and type checking mechanism as compare to otherprogramming 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.

    Distributed

    The 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.

  • 7/31/2019 Java Introduction and Language

    5/53

    5

    Portable

    The 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.

    Dynamic

    While 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.

    Secure

    Java 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 likereading 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.

    Performance

    Java 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.

    Interpreted

    We 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.

  • 7/31/2019 Java Introduction and Language

    6/53

    6

    Architecture Neutral

    The 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.

    6) Java Enabled browsers

    ava 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 themost 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 7are 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.

  • 7/31/2019 Java Introduction and Language

    7/53

    7

    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 Tools

    7) 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 Compilerjavac is a computer program or set of programs which translates java

    source code intojava byte code.

    The output from a Java compiler comes in the form ofJava 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 thejavac 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 isjavac, included in JDK from Sun Microsystems.

  • 7/31/2019 Java Introduction and Language

    8/53

    8

    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:\>javacUsage: javac

    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 Specify where to find user class files and

    annotation processors

    -cp Specify where to find user class files and

    annotation processors

    -sourcepath Specify where to find input source files

    -bootclasspath Override location of bootstrap class files

    -extdirs Override location of installed extensions

  • 7/31/2019 Java Introduction and Language

    9/53

    9

    -endorseddirs Override location of endorsed standards path

    -proc:{none,only} Control whether annotation processing and/or

    compilation is done.

    -processor [,,...]Names of the annotation processors to run;

    bypasses default discovery process

    -processorpath Specify where to find annotation processors

    -d Specify where to place generated class files

    -s Specify where to place generated source files

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

    for implicitly referenced files

    -encoding Specify character encoding used by sourcefiles

    -source Provide source compatibility with specified

    release

    -target 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 Pass 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 voidmain(String[] args){

    int a;int b=2;int c=a+b;System.out.println(c);}}

  • 7/31/2019 Java Introduction and Language

    10/53

    10

    Output of program:

    C:\ProgramFiles\Java\jdk1.6.0_01\bin>javac A.javaA.java:6: variable a might not havebeen 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 voidmain(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:\ProgramFiles\Java\jdk1.6.0_01\bin>java A4

    8) 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 bytecodeinto 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 Javainterpreter we download the Applets from the Internet or an intranet to run within a web

  • 7/31/2019 Java Introduction and Language

    11/53

    11

    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:

  • 7/31/2019 Java Introduction and Language

    12/53

    12

    9) Java Debugger

    Java debugger helps in finding and the fixing of bugs in Java language programs. The Java

    debugger is denoted asjdb. 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 class. Then 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.

    contIhis command Continues the execution of the debugged application after a breakpoint,

    exception, or step.

    runUse 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.

    printThis 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.

  • 7/31/2019 Java Introduction and Language

    13/53

    13

    Few examples of print command are:

    print TempClass.myStaticField

    print myObj.myInstanceField

    print myObj.myMethod()

    dumpThis 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.

    Exceptions

    If 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.

    threadsThis 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.

    threadThis 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 threads

    command above.

    where

    The 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.

    BreakpointsThe 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. ( 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()".

  • 7/31/2019 Java Introduction and Language

    14/53

    14

    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 thesame options as the java command, which includes -D, -classpath, and -X.

    Some more options by jdb:

    -sourcepath

    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

    Attaches the debugger to previously running VM using the default connection mechanism.

    -launch

    As 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.

    -JoptionIt 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.

  • 7/31/2019 Java Introduction and Language

    15/53

    15

    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 ()

    Y add(int, int)

    Y sub(int, int)Y main(java.lang.String[])

    ava.lang.Object ()

    ava.lang.Object registerNatives()

    ava.lang.Object getClass()

    ava.lang.Object hashCode()

    ava.lang.Object equals(java.lang.Object)

    ava.lang.Object clone()

    ava.lang.Object toString()

    ava.lang.Object notify()

    ava.lang.Object notifyAll()

    ava.lang.Object wait(long)ava.lang.Object wait(long, int)

    ava.lang.Object wait()

    ava.lang.Object finalize()

    ava.lang.Object ()

  • 7/31/2019 Java Introduction and Language

    16/53

    16

    10) 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 anobject-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 defaultjavah 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 getsprepended to both the header file name and the structure name.

    Following are some options to use :

    -o outputfileThis option concatenates the resulting header or source files for all the classes listed on the

    command line into output file.

    -helpPrint help message for javah usage.

    -d directoryThis option sets the directory where javah saves the header files or the stub files. Only one of

    -d or -o may be used.

    -classpath pathSpecifies the path javah used to look up classes. Overrides the default or the CLASSPATH

    environment variable if it is set. Directories are separated by semi-colons. Thus the general

    format for path is:

    .;

    For example:

    .;C:\users\dac\classes;C:\tools\java\classes

  • 7/31/2019 Java Introduction and Language

    17/53

    17

    -stubsCauses javah to generate C declarations from the Java object file.

    -verboseIndicates verbose output and causes javah to print a message to stdout concerning the status

    of the generated files.

    -versionPrints out javah version information.

    11) Javadoc

    Sun Microsystems has provided a computer software tool known as Javadoc. 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 aJavadoc 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 anasterisk 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.*/

  • 7/31/2019 Java Introduction and Language

    18/53

    18

    public int numEmployees;

    One interesting thing to know about Javadoc comments is that we can embed HTML tags to

    format the text. For example:

    /*** Java declaration

    */

    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.

    @paramDefines 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 pagePackage 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 beginswith an "@" (at sign).

  • 7/31/2019 Java Introduction and Language

    19/53

    19

    12) 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.

    An applet is a special type of application that's included as a part of an HTML page 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 theJava 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

    through Java 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 logicallysame. 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 URL

    Where 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 paintmethod 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);

    }

    }

  • 7/31/2019 Java Introduction and Language

    20/53

    20

    Here is the HTML File:

    After building the program, run the applet and the applet viewer as shown below.

    C:\javac> javac Myapplet.java

    C:\javac>appletviewerMyapplet.html

    When we run the applet viewer it will display the window as shown below.

    Section II- Java Language

    1) 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.

  • 7/31/2019 Java Introduction and Language

    21/53

    21

    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 betweenthese 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 CommentsRemember 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

  • 7/31/2019 Java Introduction and Language

    22/53

    22

    /* 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

    2) Java Keywords

    There are few keywords in Java programming language. Remember, we cannot use these

    keywords as identifiers in the program. The keywords const and goto are reserved though,they are not being currently used.

    The brief description of each one of the keyword is given below.

    abstractWhen a class is not to be instantiated, use abstract 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.

    booleanThis 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, orvariable of type byte.

    caseThis keyword is used to defines a group of statements. The value defined by the enclosing

    switch statement should match with the specified value.

    catch

    This 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.

  • 7/31/2019 Java Introduction and Language

    23/53

    23

    char

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

    character.

    class

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

    const

    This keyword has been deprecated from Java programming language.

    continue

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

    default

    If 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.

    do

    Used 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.

    double

    A 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.

    else

    This keyword is used to test the condition. It isused 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 aninterface declaration to specify one or more superinterfaces.

    final

    It is used todefine 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.

    finally

    This 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.

  • 7/31/2019 Java Introduction and Language

    24/53

    24

    breakUsed 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.

    strictfpTo get the precise results in Floating point calculations use strictfp keyword regardless of

    any operating system and hardware platform.

    3) 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 languageprogramming in addition to int. A primitive data type is a data type which is predefined inJava. Following are the eight primitive data types:

    int

    It 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 valuesuse long.

    byteThe 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.

    shortThe 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.

    longThe 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.

    floatThe 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 usejava.math.BigDecimal class.

  • 7/31/2019 Java Introduction and Language

    25/53

    25

    double

    This 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.

    booleanThe 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.

    charThe 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

    4) 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;

  • 7/31/2019 Java Introduction and Language

    26/53

    26

    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 Literals

    Integer 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 Literals

    We 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. TheASCII 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

  • 7/31/2019 Java Introduction and Language

    27/53

    27

    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 Literals

    The 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 Javacompiler will take it as a string of characters, if its in quotation marks.

    Floating-point literals

    Floating-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 typewhen 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.

  • 7/31/2019 Java Introduction and Language

    28/53

    28

    6.5E+32 (or 6.5E32) Double-precision floating-point literal

    7D Double-precision floating-point literal

    .01f Floating-point literal

    String Literals

    The 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 ofa 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.

  • 7/31/2019 Java Introduction and Language

    29/53

    29

    5) 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 extendsjava.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.

  • 7/31/2019 Java Introduction and Language

    30/53

    30

    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

  • 7/31/2019 Java Introduction and Language

    31/53

    31

    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 voidmain(String[] args)

    {

    int[] x = new int [101];

    for (int i = 0; ijavac Sum.java

    C:\tamana>java Sum

    5050

    C:\tamana>

    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

  • 7/31/2019 Java Introduction and Language

    32/53

    32

    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.

  • 7/31/2019 Java Introduction and Language

    33/53

    33

    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

  • 7/31/2019 Java Introduction and Language

    34/53

    34

    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 arraydest 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 voidmain(String[] args){

    char[] copyFrom = {'a','b','c','d','e','f','g','h','i','j'};

    char[] copyTo = new char[5];

    System.arraycopy(copyFrom, 2, copyTo, 0, 5);

    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 :

    6) 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

  • 7/31/2019 Java Introduction and Language

    35/53

    35

    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

    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 operatorsthat 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 + -

  • 7/31/2019 Java Introduction and Language

    36/53

    36

    shift > >>>

    relational < > , = instanceof

    equality == , !=

    bitwise AND &

    bitwise exclusive OR ^

    bitwise inclusive OR |

    logical AND &&

    logical OR ||

    ternary ? :

    assignment= , +=, -=, *=, /=, %=, &=, ^=,

    |=, =, >>, >=

    7) Controlling your program

    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.

    Selection

    In 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 ifstatement

    To 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 onlybe 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 validboolean expressions to the if statement.

  • 7/31/2019 Java Introduction and Language

    37/53

    37

    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 voidmain(String[] args){

    int a = 20;

    int b = 40;

    if (ajavac compare.java

    C:\javac>java compare

    a is smaller

    Theswitch 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.

  • 7/31/2019 Java Introduction and Language

    38/53

    38

    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 anoptional 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.");}

  • 7/31/2019 Java Introduction and Language

    39/53

    39

    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 voidmain(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-worldproblems.

    Thefor 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 three parts i.e. initialization, condition, and iteration.

  • 7/31/2019 Java Introduction and Language

    40/53

    40

    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

  • 7/31/2019 Java Introduction and Language

    41/53

    41

    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 voidmain(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: 9Count is: 10

  • 7/31/2019 Java Introduction and Language

    42/53

    42

    We would like to suggest to use this form of for loop if possible.

    The while anddo-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 awhile 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 voidmain (String args[]){

    System.out.print("Bonjour "); // Say Hello

    inti = 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

    (ijavac Bonjour.java

    C:\javac>java Bonjour

    Bonjour

  • 7/31/2019 Java Introduction and Language

    43/53

    43

    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 voidmain (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.

  • 7/31/2019 Java Introduction and Language

    44/53

    44

    Thebreak StatementWe use break statement to terminate the loop once the condition gets satisfied. Lets see a

    simple example using break statement.

    class BreakDemo{

    public static voidmain(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. Thenwe 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

    12

    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 ofunlabeled 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 voidmain(String[] args)

    {

    for (int i = 0; i < 10; i++) {

    System.out.print("\n");

    for (int j = 0; j

  • 7/31/2019 Java Introduction and Language

    45/53

    45

    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

  • 7/31/2019 Java Introduction and Language

    46/53

    46

    ******

    ******

    ******

    ******

    ******

    C:\javac>

    Thecontinue statement

    The 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

  • 7/31/2019 Java Introduction and Language

    47/53

    47

    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 : 0chandan

    Value of a : 0

    chandan

    Value of a : 0

    chandan

    Value of a : 0

  • 7/31/2019 Java Introduction and Language

    48/53

    48

    8) Classes in Java

    Exceptions

    There 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 anykind 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 datatypes, 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 expression

    The set of strings which are based on common characteristics are shared by each string in theset. 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.

  • 7/31/2019 Java Introduction and Language

    49/53

    49

    9) 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