Вы находитесь на странице: 1из 53

Section I - Introduction to Java

1) What is Java?
Java is a high-level object-oriented programming language developed by the Sun Microsystems. Though it is associated with the World Wide Web but it is older than the origin of Web. It was only developed keeping in mind the consumer electronics and communication equipments. It came into existence as a part of web application, web services and a platform independent programming language in the 1990s. Earlier, C++ was widely used to write object oriented programming languages, however, it was not a platform independent and needed to be recompiled for each different CPUs. A team of Sun Microsystems including Patrick Naughton, Mike Sheridan in the guidance of James Goslings decided to develop an advanced programming language for the betterment of consumer electronic devices. They wanted to make it new software based on the power of networks that can run on different application areas, such as computers and electronic devices. In the year 1991 they make platform independent software and named it Oak. But later due to some patent conflicts, it was renamed as Java and in 1995 the Java 1.0 was officially released to the world.

2) 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 NTiered 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 JVLite2 or with all the later version and it also support PDAs like HP/Compaq, iPAQ, FujitsuSiemens Pocket Loox and SimPad, HHP, NEC, Samsung, Sharp Electronics, Toshiba, psion m5, 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.

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.

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

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

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

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 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 -g:{lines,vars,source} -nowarn -verbose doing -deprecation are -classpath <path> -cp <path> -sourcepath <path> -bootclasspath <path> -extdirs <dirs> Generate no debugging info Generate only some debugging info Generate no warnings Output messages about what the compiler is Output source locations where deprecated APIs used Specify where to find user class files and annotation processors Specify where to find user class files and annotation processors Specify where to find input source files Override location of bootstrap class files Override location of installed extensions

-endorseddirs <dirs> -proc:{none,only}

Override location of endorsed standards path 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> -d <directory> -s <directory> -implicit:{none,class} -encoding <encoding> files -source <release> -target <release> -version -help -Akey[=value] -X -J<flag> C:\> Specify where to find annotation processors Specify where to place generated class files Specify where to place generated source files Specify whether or not to generate class files for implicitly referenced files Specify character encoding used by source Provide source compatibility with specified release Generate class files for specific VM version Version information Print a synopsis of standard options Options to pass to annotation processors Print a synopsis of nonstandard options Pass <flag> directly to the runtime system

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

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 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 runtime 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
10

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:

11

9) 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 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 Xdebug Xrunjdwp:transport=dt_socket,server=y,suspend=n purpose Enables debugging in the VM 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.

12

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. 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. 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 threads command above. where The command where is used to dump the stack of the current thread. Whereas the command where 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()".
13

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

14

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

15

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 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 CLASSPATH environment 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
16

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

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

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 @version @author @return Description Shows the version number of a class or method. Shows the Developer name Documents the return value. This tag should not be used for constructors or methods defined with a void return type. Marks a method as deprecated. Some IDEs will issue a compilation warning if the method is called. Documents an association to another method or class. Defines a method parameter. Required for each parameter. Documents an exception thrown by a method. A synonym for @exception introduced in Javadoc 1.2. Documents when a method was added to a class. Documents an exception thrown by a method ? also see @throws. Displays all classes and members It creates class and package usage pages It shows the window title of the document It includes for header text of the page It includes footer text for the page It includes bottom text for the page Shows package classes and members shows protected classes and members Helps to find user class files doesn't provide the index doesn't provide the help link doesn't provide class hierarchy

@deprecated

@see @param @throws

@since @exception private use Windowtitle Header Footer Bottom Package Protected Classpath noindex nohelp notree

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

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

19

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.

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.

20

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
21

/* 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. abstract When 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. 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. 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.

22

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 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. final It 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. 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.

23

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.

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 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: 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 values use long. 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.

24

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. 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 byte short int long float double char boolean Description Byte-length integer Short integer Integer Long integer Single-precision floating point Double-precision floating point A single character A boolean value (true or false) Size/Format 8-bit two's complement 16-bit two's complement 32-bit two's complement 64-bit two's complement 32-bit IEEE 64-bit IEEE 16-bit Unicode character 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;

25

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 0x4a 057L Decimal integer literal of type long integer Hexadecimal integer literal of type integer 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. 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 \n \t \b \r \f \\ \' \" \d \xd \ud Meaning New line Tab Backspace Carriage return Formfeed Backslash Single quotation mark Double quotation mark Octal Hexadecimal Unicode character
26

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' '\u0030' '\u0022' '\u003b' '\u0020' '\u0009' 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 Java compiler 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 type when you write a floating-point literal is double. Type name float double 4 8 Size bytes bits 32 64 Range approximate +/- 3.4 * 10 +/- 1.8 * 10
38 308

Capital letter A Digit 0 Double quote " Punctuation ; Space Horizontal Tab

Precision in decimal digits 6-7 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 floatingpoint values.

27

6.5E+32 (or 6.5E32) 7D .01f String Literals

Double-precision floating-point literal Double-precision floating-point literal Floating-point literal

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

28

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

29

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

30

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. Output for the given program:

C:\tamana>javac 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
31

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

32

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)

33

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, 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

34

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 postfix unary multiplicative additive Precedence expr++,, expr-++expr, --expr, +expr, -expr ~ ! */% +35

shift relational equality bitwise AND bitwise exclusive OR bitwise inclusive OR logical AND logical OR ternary assignment

<< >> >>> < > , <= , >= instanceof == , != & ^ | && || ?: = , +=, -=, *=, /=, %=, &=, ^=, |=, <<=, >>=, >>, >=

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 if statement 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 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.
36

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.

37

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

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

39

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 i 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!"); } } }

40

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
41

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

42

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 dowhile loop evaluates its expression at the bottom of the loop. Hence, the statement in the dowhile 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.

43

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; } } }

44

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


45

****** ****** ****** ****** ****** C:\javac>

The continue 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<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){} } }

46

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

47

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

48

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 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 Simple Inheritance

Multilevel 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.
49

class A { int x; int y; int get(int p, int q){ x=p; y=q; return(0); } void Show(){ System.out.println(x); } } class B 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 A { int x; int y; int get(int p, int q){ x=p; y=q; return(0); } void Show(){ System.out.println(x); } } class B extends A{ void Showb(){ System.out.println("B"); } } class C extends B{ void display(){ System.out.println("C"); } public static void main(String args[]){ A a = new A(); a.get(5,6); a.Show(); } }

50

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 B 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(1, 5); subobj.Show(); } }

Output:
51

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 B 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

52

10) Summary
You have been introduced to the basics of Java language providing a great amount of information. Perhaps it would be a bit arduous to grasp everything at one go. However, the implementation of these little basics will make you a substantial programmer. Since you have perceived the concept of operators, Arrays, controlling the programs (selection, iteration, jumping) etc, we presume you would be eager to discover more about Java in the succeeding chapters. The course will comprehend all facets of Java language, Go Ahead ....................

53

Вам также может понравиться