history of java and tour of jdkgomsagar.yolasite.com/resources/notes/java notes1.pdfhistory of java...

150
History of Java and Tour of JDK Java is an object-oriented programming language developed by Sun Microsystems, and modeled on C++, the Java language was designed to be small, simple, and portable across platforms and operating systems, both at the source and at the binary level, which means that Java programs (applets and applications) can run on any machine that has the Java virtual machine installed One might be surprised to learn that Java did not come into being because of Internet or World Wide Web (WWW), although it was WWW which propelled into java what it is as a language today and a de-facto standard for Server Side Softwares. Because of the similarities between C++ and Java, it is tempting to think of Java as the “Internet version of C++”, but it would be a big mistake since Java has practical and philosophical difference with C++. The history of java goes back to 1991, when a group of Sun Engineers led by Mr. Patrick Naughton and James Gosling wanted to design a small computer language that was to be used for consumer and electronic devices like Remote Controls, TV Switchboxes etc. Now since these devices were manufactured by different manufacturers who may choose different CPUs (Central Processing Units), the program should not be tied down to any single architecture. The project was code named “Green”. The languages was then called as Oak and since Oak was already an existing computer languages, it was code named as JAVA. But unfortunately, Sun did not get the project for which they were bidding and it was in 1994 with the advent of the WWW and browsers, java was propelled back in to the main stream. The JAVA as a language was reveled to the world in the Sun world 1995 conference and from there onwards different versions have come out with all the latest technologies being incorporated. The different versions are being dealt with separately in the coming modules. Java was basically invented as a platform independent software to be run on various electronic devices like remote controls, micro-wave ovens etc. The emphasis was on platform independence. Platform independence-that is, the ability of a program to move easily from one computer system to another-is one of the most significant advantages that Java has over other programming languages, particularly if your software needs to run on many different platforms. If you're writing software for the World Wide Web, being able to run the same program on many different systems is crucial to that program's success. It was with the increasing popularity of the Internet, java became as a language for the internet which lays emphasis on the client-server programming. Java achieves this platform independence by breaking up the process of compilation and interpretation in to two individual steps. We have two separate executable files for this purpose called the Compiler and the Interpreter. In the earlier programming languages, any code written was compiled and immediately interpreted to the underlying operating system machine standard and hence if the same program was taken to another machine having a different operating system, it would not work.

Upload: others

Post on 01-Feb-2021

4 views

Category:

Documents


0 download

TRANSCRIPT

  • History of Java and Tour of JDK Java is an object-oriented programming language developed by Sun Microsystems, and modeled on C++, the Java language was designed to be small, simple, and portable across platforms and operating systems, both at the source and at the binary level, which means that Java programs (applets and applications) can run on any machine that has the Java virtual machine installed One might be surprised to learn that Java did not come into being because of Internet or World Wide Web (WWW), although it was WWW which propelled into java what it is as a language today and a de-facto standard for Server Side Softwares. Because of the similarities between C++ and Java, it is tempting to think of Java as the “Internet version of C++”, but it would be a big mistake since Java has practical and philosophical difference with C++. The history of java goes back to 1991, when a group of Sun Engineers led by Mr. Patrick Naughton and James Gosling wanted to design a small computer language that was to be used for consumer and electronic devices like Remote Controls, TV Switchboxes etc. Now since these devices were manufactured by different manufacturers who may choose different CPUs (Central Processing Units), the program should not be tied down to any single architecture. The project was code named “Green”. The languages was then called as Oak and since Oak was already an existing computer languages, it was code named as JAVA. But unfortunately, Sun did not get the project for which they were bidding and it was in 1994 with the advent of the WWW and browsers, java was propelled back in to the main stream. The JAVA as a language was reveled to the world in the Sun world 1995 conference and from there onwards different versions have come out with all the latest technologies being incorporated. The different versions are being dealt with separately in the coming modules. Java was basically invented as a platform independent software to be run on various electronic devices like remote controls, micro-wave ovens etc. The emphasis was on platform independence. Platform independence-that is, the ability of a program to move easily from one computer system to another-is one of the most significant advantages that Java has over other programming languages, particularly if your software needs to run on many different platforms. If you're writing software for the World Wide Web, being able to run the same program on many different systems is crucial to that program's success. It was with the increasing popularity of the Internet, java became as a language for the internet which lays emphasis on the client-server programming. Java achieves this platform independence by breaking up the process of compilation and interpretation in to two individual steps. We have two separate executable files for this purpose called the Compiler and the Interpreter. In the earlier programming languages, any code written was compiled and immediately interpreted to the underlying operating system machine standard and hence if the same program was taken to another machine having a different operating system, it would not work.

  • In Java, after compilation a class file is generated which is also called as byte code file and this class file is then interpreted as per the underlying machine standard. If we take this class file from one machine to another, it would still run, because interpretation is done as per that machine’s operating system. The Java compiler takes your Java program and, instead of generating machine codes from your source files, it generates bytecodes. Bytecodes are instructions that look a lot like machine code, but are not specific to any one processor. To execute a Java program, you run a program called a Bytecode interpreter, which in turn reads the bytecodes and executes your Java program. The Java Bytecode interpreter is often also called the Java virtual machine or the Java runtime Java bytecodes are a special set of machine instructions that are not specific to any one processor or computer system. A platform-specific Bytecode interpreter executes the Java bytecodes For running java programs, we would require software called as Java Development Kit, which can be downloaded from www.java.sun.com site. The earlier version of JDK was 1.0 and the other major versions were 1.1, 1.2 and the present version 1.3. Many authors and books also call JDK 1.3 as Java 3 and this is specifically stated to ensure that there is no confusion. We will be studying on Java Development Kit 1.3 and all the codes and error messages are of this version. Please note that the description of error messages differs from version to version. Once we download the software and install the same on the machine, the directory structure would like this and the important directories and files are explained herewith.

    Name of the Folder Description

    bin

    Contains all the executable files which is required to run the java programs like java.exe, javac.exe

    demo

    Contains some demo applets and applications along with source codes.

    jre

    Contains the run-time environment and officially called as the Java Runtime Environment

    lib

    Contains the library files that support the executable and UI development.

    src.jar file

    archive that contains the class library source ode (a collection of files with .java extension)

    Uninst.isu file

    The un-installation file

  • Tools of JDK After having successfully installed the JDK, we will quickly go through the various tools which will be required for execution of the java programs. Now for executing our tools, we would first require to set the path in the autoexec.bat directory or we can individually create a batch file and run the same before executing java codes. We need to insert the following line in the autoexec.bat file or in the user defined batch file and the same is set path= c:\jdk1.3\bin where jdk1.3 is the directory name (default directory in which u have your jdk installed) Once we have executed the batch file, to ensure that our jdk is properly installed, we just need to just type javac on the dos prompt and it would give us a list of options. (Incase our jdk is not properly installed or the path is not properly given then it would give us a bad command output)

    Name of the Executable Description

    javac Compiler

    java Interpreter

    appletviewer Applet viewer

    javadoc Documentation generator

    The first executable used would obviously be javac which would generate a class file from the source code file. We can see what the various options of javac are by just calling javac on the dos prompt. To compile a particular source we will have to say javac Test.java wherein Test.java is the source code file name. (Note: All java files should end with the .java extension). The java executable is for interpreting the .class file generated from the earlier compiler option. Not interpreting a class file, we do not need to give the .java extension and it would simply be java Test, wherein Test is the name of the class file automatically generated. The appletviewer is a mini browser inbuilt into JDK specifically for running the java Applets. (Java Applets are not a part of the certification exam and is not explained hence forth). The javadoc is a document generator by which automatic documentation will be generated from the java codes based on special comments given in the source code file. (This is also not a part of the SL 275 objectives). Java’s popularity is because of the following 3 important points:-

    a) Applets b) Security c) Portability

  • Java Applets are simple java class files embedded in an html file which is dynamically downloaded across the network by the web server when an appropriate APPLET Tag is encountered. Java Applets are dynamic in the sense that they can respond to events and user inputs and not just simple animations or sounds. Java programs are secure because they run within the JVM (Java Virtual Machine) which will be talked in depth later on. Java achieves the security by confining a java program to the java execution environment and not allowing it to access to other parts of the computer. The other main popularity of java is the fact that it is portable (as already explained earlier).

    Features of Java The authors of java had written an influential White Paper that explains the design goals and accomplishments of Java and they are the following which is also called as the features of java. In each of the points the excerpts from the white paper is taken what the java designers say about each buzzword. 1 Simple “We wanted to build a system that could be programmed easily without a lot of esoteric training and which leveraged today’s standard practice. So even though we found that C++ was unsuitable, we designed java as close to C++ as possible in order to make the system more comprehensible. Java omits many rarely used, poorly understood, confusion features of C++ that in our experience bring more grief than benefit”. The basic syntax of Java is a cleaned up version of C++, there is no need for header files, pointer arithmetic, structures etc. There has been a lot of improvement of the C++ language, keeping in touch with the basics of C++. Hence anyone coming into java from the C++ background would find the same very simple. Also a lot of IDEs (Integrated Development Environment) Softwares like JBuilder, Visual Café etc have been made for easy execution of java programs. 2 Object Oriented “Simply stated, object-oriented design is a technique for programming that focuses on the data (= objects) and on the interfaces to that object. To make an analogy with carpentry, an object oriented carpenter would be mostly concerned with the chair he was building and secondarily with the tools used to make it, a non object oriented carpenter would think primarily of his tools. The object facilities of java are essentially those of C++” Java is based on the C++ Model of OOPs which is fundamental in the achievement of the other features of java. Java language is based on the purist’s “everything is an object” paradigm which is simple and easy to extend. The advantages of OOPs are explained in the later sections. The major difference between Java and C++ lies in multiple inheritance for which java has found a better solution. The reflection mechanism and object serialization features make it much easier to implement persistent objects and GUI builders that can integrate off the shelf components. 3 Distributed “Java has an extensive library of routines for coping with TCP/IP protocols like HTTP and FTP. Java applications can open and access objects across the Net via URLs with the same ease as when accessing a local file System.”

  • The networking capabilities of Java are fantastic and there is a separate package called java.net having classes related to both Socket Oriented and Packet Oriented data communication. Java also improves on the CGI scripting and uses an elegant mechanism called Servlets and JSP which makes server side programming in java extremely efficient. Java was originally designed for the distributed environment of the internet by properly handling the TCI / IP protocols. In many of the earlier languages the distributed environment was an after thought but not Java. Java has a complete package called java.net which contains classes which take care of the distributed environment like URL, Datagram Packet, Datagram Socket, and URLConnection etc. 4 Robust “Java is intended for writing programs that must be reliable in a variety of ways. Java puts a lot of emphasis on early checking for possible problems, later dynamic (run-time) checking and eliminating situations that are error prone. The single biggest difference between Java and C/C++ is that java has a pointer model that eliminates the possibility of overwriting memory and corrupting data.” Java program is robust by which it will successfully execute reliably in a variety of systems. It was possible to achieve this because of the following features / tools of Java

    a) Strictly Typed: Java is a strictly typed language and forces the programmer to find the mistakes early in the program development and it also check the code at compile time and at run time also. It follows strict naming principles also.

    b) Good Memory Management: Memory Management is a tedious and difficult

    task in the traditional programming environments and it was the duty of the programmer to allocated and de-allocated memory from the programs. In java the de-allocation of memory is completely automatic because there is a Garbage Collection which will automatically reclaim the unused objects. (Garbage Collection is dealt in depth later on in this module).

    c) Proper Handling of Exceptions: One of the reasons for the program failure

    in the earlier programming languages was the mishandling of exceptional conditions (specifically the run-time errors). Java provides for a proper object oriented way of exceptional handling by which all errors (including run-time errors) can and should be managed by the program.

    5 Secure “Java is intended to be used in networked / distributed environments. Towards that end a lot of emphasis has been placed on security. Java enables the construction of virus - free, tamper free systems.” Java achieves this security with the concept of Java Virtual Machine (JVM) which has been explained in depth in the later sections. 6 Architecture - Neutral “The compiler generates an architecture neutral object file format - the compiled code is executable on many processors, given the presence of the Java run-time system. The java compiler does this by generating byte code instructions which have nothing to do with particular

  • computer architecture. Rather they are designed to be both easy to interpret on any machine and easily translated into native machine on the fly.” With the advantage of byte codes, it is possible for a java code which is compiled on one machine to be executed on any other machine. This is possible due to the concept of Byte Codes explained earlier. The goal of java was “write once, run anywhere, anytime, forever”. 7 Portable “Unlike the C and C++, there are no implementation dependent aspects of the specification. The sizes of the primitive data types are specified as is the behavior of arithmetic on them.” The main advantages of java are that once written on any platform, it can be executed in the similar way in other platforms also. This is because the data types in Java are having a fixed size and having a fixed size of number types eliminates a major porting headache. The Strings are saved in standard Unicode format. “The libraries that are a part of the system define portable interfaces” 8 Interpreted “The java interpreter can execute Java bytecodes directly on any machine to which the interpreter has been ported. Since linking is a more incremental and light weight process, the development process can be much more rapid and exploratory.” As said earlier Java enables the creation of cross platform programs by compiling into an intermediate representation called Java Bytecode. There is a great advantage while we are developing an application with java being an interpreted language. 9 High Performance “While the performance of interpreted bytecodes is usually more than adequate, there are situations where higher performance is required. The bytecodes can be translated on the fly (at run time) into machine code for the particular CPU the application is running on” The earlier attempts at cross platform were done at the expense of performance. But java although interpreted, was carefully designed so that it would be easy to translate directly into native machine code for very high performance by using a Just-In-Time Compiler. The java runtime systems that provide this feature lose none of the benefits of the platform independent code. 10 Multi-Threaded “The benefits of multithreading are better interactive responsiveness and real time behavior” Multi-Threading is very simply in java and threads in java also have the capacity to take advantage of multi-processor systems if the base operating system does so. The code for the multi-threading remains the same across machines, but the implementation of multithreading is off-loaded to the underlying operating systems. Java supports multi-threaded programming, which allows a programmer to write programs that do many things simultaneously. Java comes with a elegant yet sophisticated but simple and easy solutions for multi-process synchronization that enables a programmer to construct smoothly running interactive systems.

  • 11 Dynamic “In a number of ways, Java is more dynamic languages that C or C++. It was designed to adapt to an evolving environment. Libraries can freely add new methods and instance variables without any effect on their clients. In java, finding out run time information is straight forward.” Java programs carry with them substantial amounts of runtime type information that is used to verify and resolve accesses to objects at run time. This makes it possible to dynamically link code in a safe and expedient manner.

    Concept of JVM The JVM stands for the Java Virtual Machine, an imaginary machine within which all the java programs are executed. The three parts of the JVM are

    a) Class Loader b) Byte-Code Verifier c) Interpreter

    The duty of the Class Loader is to load all the classes necessary for the successful compilation of the code. Infact the package java.lang is automatically loaded without the need for importing the same (equivalent to the famous first line include statement in C language). After the compilation, a .class file is generated and when we execute the .class file, first of all the Byte Code Verifier is called, whose duty is to check whether any changes have been made to the byte codes after the same have been generated (whether the .class file have been tampered with or not). Incase there is infact a change, it generated an exception or else allows the Interpreter to go ahead with the code. The Interpreter interprets the code and generates the necessary output. The actual working of the Class Loader and Byte Code Verifier will be explained in the first code module. Setting the Path By default the codes can be stored anywhere and when you type javac in the dos-prompt, it would not know whether to look for the javac executable file and hence we need to type as under:- set path=c:\jdk1.3\bin Here we assume that the directory of the JDK is jdk1.3. Once we do this, then we do not have to worry and we can store the .java file where and just type the above set path on the dos-prompt or even put it in the autoexec.bat file, so that we do not have to type it every time.

  • Mis-Conceptions of Java The following are the common Mis-conceptions of Java: Java is the Internet version of C++ Although it is very true that java became a popular programming language because of the World Wide Web and have a lot of features of C++, as it is also an Object Oriented Programming language, it would be very wrong to take java as an extension of C++ Java has many advantages over C++ in the form of better memory management and exception handling mechanism. Java is Interpreted language and hence is slow for serious applications The earlier versions of Java was slow and hence a JIT (Just in Time Compiler) and introduce and with this the performance issues simply goes away. Java is great for network related programs because of its intrinsic in-built classes. All Java Programs run inside a Web Page Java Applets run inside a web page, but it is quite possible to write stand alone java programs that run independently of the web browser. Java Applets are major security risk This would not be true because all the java applets run within the Java Virtual Machine and it would not be possible for applets to be in touch with the local file system, which the basic requirement of Java Applets.

    Brief explanation of the Important Terminology in Java JDK This is the short form for Java Development Kit. The Java Development Kit is the software which is required for running Java Programs. The development environment for Java is very rich and contains everything they need to get started creating powerful java programs The JDK is available for most operating systems and the current version is JDK 1.3, with the beta version 1.4 due to release very shortly. We have already seen earlier what programs are available under the JDK and the directory structure of JDK. J2SE Java software can be broadly divided into 3 parts namely:

    a) Java 2 Standard Edition (J2SE)

  • b) Java 2 Enterprise Edition (J2EE) c) Java 2 Micro Edition (J2ME)

    J2SE is for developing normal applications and applets, but not for the server side programs for which we required J2EE Software. The program which we work for executing our code is J2SE which we have seen earlier in the module. The structure of the J2SE API is also discussed earlier. The J2SE JDK can be downloaded from the site as under:- http://java.sun.com/j2se/1.3/ Note: J2SE is the same thing as JDK 1.3. J2EE This stands for Java 2 Enterprise Edition, which is specifically for writing server side programs like Servlets, Java Server Pages and Enterprise Java Beans. The J2EE is a set of specifications based on which various Web Servers and Application Servers are said to be J2EE compliant. Java™ 2 Platform Enterprise Edition enables solutions for developing, deploying and managing n-tier server-centric enterprise applications To reduce costs and fast-track enterprise application design and development, the Java 2 Platform, Enterprise Edition (J2EE ) technology provides a component-based approach to the design, development, assembly, and deployment of enterprise applications. The J2EE platform offers a multi-tiered distributed application model, the ability to reuse components, integrated Extensible Markup Language (XML)-based data interchange, a unified security model, and flexible transaction control. Not only can you deliver innovative customer solutions to market faster than ever, but your platform-independent J2EE component-based solutions are not tied to the products and application programming interfaces (APIs) of any one vendor. Vendors and customers enjoy the

  • freedom to choose the products and components that best meet their business and technological requirements. J2ME Java 2 Micro Edition is specifically used for writing embedded programs which can be executed on Mobile Phones, PDAs (Personal Digital Assistant) and Palm Tops. Java™ 2 Platform, Micro Edition (J2ME™) encompasses VMs and core APIs specified via Configurations as well as vertical or market-specific APIs specified in Profiles J2ME specifically addresses the vast consumer space, which covers the range of extremely tiny commodities such as smart cards or a pager all the way up to the set-top box, an appliance almost as powerful as a computer. Like the other editions, J2ME maintains the qualities that Java technology has become famous for:

    - built-in consistency across products in terms of running anywhere, any time, over any device

    - portability of the code - leveraging of the same Java programming language - safe network delivery - applications written with J2ME are upwardly scalable to work with J2SE and

    J2EE With the delivery of J2ME, Sun provides a complete, end-to-end solution for creating state-of-the-art networked products and applications for the consumer and embedded market. J2ME enables device manufacturers, service providers, and content creators to gain a competitive advantage and capitalize on new revenue streams by rapidly and cost-effectively developing and deploying compelling new applications and services to their customers worldwide. JVM This stands for Java Virtual Machine and it is within this imaginary machine all the codes whether it is a java application or a java applet is executed. The details of the JVM are explained later on this module. Java Hotspot The Java HotSpot product line delivers the highest possible performance for Java applications. Sun Microsystems has a version of Java HotSpot-technology-based VM for server-side performance and now a version for client-side performance. These two solutions share the Java HotSpot runtime environment, but have different compilers suited to the distinctly different performance characteristics of clients and servers. The Java HotSpot virtual machine (VM) is a key component in maximizing deployment of enterprise applications. It is a core component of Java 2 Platform, Standard Edition (J2SE) software, supported by leading application vendors and technologies. The Java HotSpot VM supports virtually all aspects of development, deployment, and management of corporate applications, and is used by: Integrated development environments (IDEs), including Forte for Java, Community Edition, Borland JBuilder, WebGain VisualCafé, Oracle JDeveloper, Metrowerks CodeWarrior, and the NetBeans Open Source Project

  • Application server vendors, such as BEA Systems (WebLogic Server) and iPlanet (iPlanetApplication Server) Plugin Many browsers include a JVM that is used to execute applets. Unfortunately browser JVMs typically does not include the latest java features. The java Plugin solves this problem for us. By using a plugin It directs a browser to use a specific JRE rather than the browser’s JVM. The JRE is a subset of JDK. It does not include the tools and classes that are used in a development environment. Java API API stands for Application Programming Interface and Java API is a set of pre-defined classes which we will be using in our applications and applets. The Java API is not a part of the software download and needs to be downloaded separately from the sun site. JRE JRE stands for Java Runtime Environment. Every java program would require a JRE for the programs to be executed. When we install the JDK, the JRE is automatically installed in the machine and the JRE for the applets is inbuilt into the browser. Hot Java HotJava was initial browser build by Sun Microsystems to show off the powers of java. The builders had in mind the power of what is now called as applets so they made the HotJava browser capable of interpreting the intermediate bytecodes. Nowadays most of the browsers have in-build JRE in the system. JAR This stands for Java Archive and is an executable file which is present in the bin directory of the JDK. The jar.exe is used for creating jar files and has various options by which we can add to an archive, or extract from the archive or delete some files from the archive. JAR (Java Archive) is a platform-independent file format that allows you to bundle a Java applet and its requisite components (.class files, images and sounds) into a single file. Using the new ARCHIVE attribute of the tag, this JAR file can be downloaded to a browser in a single HTTP transaction, greatly improving the download speed. In addition, JAR supports compression, which reduces the file size, further improving the download time. The concept of JAR is very important for the preparation of Java Beans in which we will combine all the java bean codes and then load the jar file in the bean box. This will be explained in Unit 2 when we do Java Beans. AWT This stands for Abstract Window Toolkit which is the GUI part of Java. All the class files related to the GUI part like Buttons, Checkboxes, Menus are all a part of the awt package present in the core java API. We will be doing AWT in Section II of this module later on and all the class files will be explained at that time.

  • Swing Swing is a part of the Java Foundation Class and it is used for creating 100% pure java components. The AWT class components rely more on the underlying operating system for their look and feel and hence a component created in Windows will look slightly different from the same component created in Mac machine. However Swing components are pure and full java components and a swing Button created in windows will look exactly the same created in Mac. All the swing components are present in the swing package in the core API. Applets Applets are java class files which are embedded in an html file which is loaded and executed by a web browser. The important classes and interfaces for Applets are present in the applet package of the core java API. Applets are executed within the JVM present in the Web Browser and cannot interact with the local files in the system and hence cannot transmit viruses. Servlets Java Servlets are server-side Java programs that web servers can run to generate content in response to a client request in much the same way as CGI programs do. Servlets can be thought of as applets that run on the server side without a user interface. Servlets are invoked through URL invocation. The main advantage of Servlet is that once started all the future requests are serviced by the service () method of the Generic Servlet or the doGet() and doPost() method of the HttpServlet class. Servlets are a part of the J2EE specifications and we can have session tracking, Http Tunneling and a lot of other server side features with Servlets. JSP It stands for Java Server Pages. A Java Server Page (JSP) is a page much like an HTML page that can be viewed in a web browser. However, as well as containing HTML tags, it can include a set of JSP tags (understood by the server) that extend the ability of the web page designer to incorporate dynamic content in a page. These tags provide functionality such as displaying property values using simple conditionals, and are understood by the server's JSP engine. One of the main benefits of Java Server Pages is that, like HTML pages, they do not need to be compiled. The web page designer simply writes a page that uses HTML and JSP tags, and puts it on their web server. The web page designer does not need to learn how to define Java classes or use Java compilers. JSP pages can access full Java functionality in the following ways:

    • by embedding Java code directly in scriptlets in the page • by accessing Java beans • by using server-side tags that include Java Servlets

    Both beans and Servlets are Java classes that need to be compiled, but they can be defined and compiled by a Java programmer who then publishes the interface to the bean or the Servlet. The web page designer can access a pre-compiled bean or servlet from a JSP page without having to do any compiling themselves.

  • Java Beans

    JavaBeans brings component technology to the Java platform. With the JavaBeans API you can create reusable, platform-independent components. Using JavaBeans-compliant application builder tools, you can combine these components into applets, applications, or composite components. JavaBean components are known as Beans. The JavaBeans architecture defines Java's reusable software component model.

    Java Beans is a software Component. A bean is a reusable, platform neutral component, which can be visually manipulated in a builder tool. Primarily Java Bean is taken as a black box that is a software device with a known functionality, but unknown internal functioning. The 3 interface facets that can be developed to independent degrees are:

    a) The methods that can be invoked on a bean b) The readable and / or writeable properties that the bean expose c) The events that a bean can signal to the outside world or accept from it.

    EJB EJB architecture is component architecture for the development and deployment of transactional distributed object applications based server side software components. Applications written using EJB is scalable, transactional and multi user secure. These applications may be written once and then deployed on any server platform that supports the EJB specs.

    EJB specifies a server side component model. Using a set of classes and interfaces from the javax.ejb packages, developers can create, assemble and deploy components that conform to the EJB specs. The various parties in the EJB are:

    - The Bean: These are reusable business components that companies can purchase and use

    to help solve business problems. Beans are not complete applications, but rather are deployable components that can be assembled into a complete solution.

    - The Container: This supplies the low-level runtime execution environment needed to run

    EJB applications. - The Service Provider: This is the application server logic to contain, manage and deploy

    components. BEA, SilverStream, WebSphere, iPlanet etc. - The Application Assembler: This is the overall application architect, for a specific

    deployment. The mail goal is to combine various components and write the applications that use components.

    - The Deployer: The application made is deployed or installed into one or more application

    servers. - The System Administrator: Overall supervision of the deployed systems.

    RMI Remote Method Invocation (RMI) enables programmers to create distributed Java-to-Java applications, in which the methods of remote Java objects can be invoked from other Java virtual machines, possibly on different hosts.

  • A Java program can make a call on a remote object once it obtains a reference to the remote object, by receiving the reference as an argument or a return value. A client can call a remote object in a server, and that server can also be a client of other remote objects. RMI uses object serialization to marshal and unmarshal parameters and does not truncate types, thereby supporting true object-oriented polymorphism JDBC JDBC is a standard SQL database access interface that provides uniform access to a wide range of relational databases. It also provides a common base on which higher level tools and interfaces can be built. This comes with an ODBC Bridge. All the classes related to database connectivity are in the java.sql package. JDBC does the following things:

    a) establish connection with a database b) send SQL statements c) processes the results

    JDBC is the interface between the database and java end user application, servlet applet. The Steps in JDBC are

    1) Import the necessary classes. 2) Load the JDBC Driver 3) Identify the Data Source 4) Allocate a Connection Object 5) Allocate a Statement Object 6) Execute a Query using the Statement Object 7) Retrieve Data from the returned Result Set Object 8) Close the RS 9) Close the Statement 10) Close the Connection

    JNI Java Native Interface (JNI) is a standard programming interface for writing Java native methods and embedding the Java virtual machine into native applications. The primary goal is binary compatibility of native method libraries across all Java virtual machine implementations on a given platform.

    The Java 2 SDK extends JNI to incorporate new features in the Java platform. The changes are driven by licensee and user comments.

    The Java 2 SDK still supports the old native method interface (NMI), which was originally implemented in Java Development Kit (JDKTM) 1.0. The old NMI is not part of the Java platform standard, and is not supported by the Java HotSpot performance engine.

    The JNI allows Java code that runs within a Java Virtual Machine (VM) to operate with applications and libraries written in other languages, such as C, C++, and assembly. In addition, the Invocation API allows you to embed the Java Virtual Machine into your native applications.

    Java 2D The Java 2D API introduced in JDK 1.2 provides enhanced two-dimensional graphics, text, and imaging capabilities for Java programs through extensions to the Abstract Windowing Toolkit

  • (AWT). This comprehensive rendering package supports line art, text, and images in a flexible, full-featured framework for developing richer user interfaces, sophisticated drawing programs and image editors. The Java 2D is used to display and print 2D graphics in the java programs. Java 2D API enables us to display complex charts and graphs that use various lines and fill styles to distinguish sets of data and also enables you to store and to manipulate image data--for example, you can easily perform image-filter operations, such as blur and sharpen Java 3D

    Developers can easily incorporate high-quality, scalable, platform-independent 3D graphics into Java technology-based applications and applets.

    The Java 3DTM application programming interface (API) provides a set of object-oriented interfaces that support a simple, high-level programming model. This enables developers to build, render, and control the behavior of 3D objects and visual environments.

    By leveraging the inherent strengths of the Java language, Java 3D technology extends the concept of "Write Once, Run Anywhere" to 3D graphics applications.

    JNDI The Java Naming and Directory Interface (JNDI) is a standard extension to the Java platform, providing Java technology-enabled applications with a unified interface to multiple naming and directory services in the enterprise. As part of the Java Enterprise API set, JNDI enables seamless connectivity to heterogeneous enterprise naming and directory services. Developers can now build powerful and portable directory-enabled applications using this industry standard. The Java Naming and Directory Interface (JNDI) 1.2 is a major new upgrade release that adds new functionality to the basic naming and directory support offered in the 1.1.x releases. New features include event notification, and LDAPv3 extensions and controls. This release contains valuable contributions from the following companies: Netscape, Novell, Tarantella Inc, Sun, BEA. Java IDL Java TM IDL is a technology for distributed objects--that is, objects interacting on different platforms across a network. Java IDL is similar to RMI (Remote Method Invocation), which supports distributed objects written entirely in the Java programming language. However, Java IDL enables objects to interact regardless of whether they're written in the Java programming language or another language such as C, C++, COBOL, or others.

    This is possible because Java IDL is based on the Common Object Request Brokerage Architecture (CORBA), an industry-standard distributed object model. A key feature of CORBA is IDL, a language-neutral Interface Definition Language. Each language that supports CORBA has its own IDL mapping--and as its name implies, Java IDL supports the mapping for Java. CORBA and the IDL mappings are the work of an industry consortium known as the OMG, or Object Management Group. Sun is a founding member of the OMG, and the Java IDL team has played an active role in defining the IDL-to-Java mapping.

    To support interaction between objects in separate programs, Java IDL provides an Object Request Broker, or ORB. The ORB is a class library that enables low-level communication between Java IDL applications and other CORBA-compliant applications.

  • Java Collections This is the new API introduced in Jdk 1.2. A collection (sometimes called a container) is simply an object that groups multiple elements into a single unit. Collections are used to store, retrieve and manipulate data, and to transmit data from one method to another. Collections typically represent data items that form a natural group, like a poker hand (a collection of cards), a mail folder (a collection of letters), or a telephone directory (a collection of name-to-phone-number mappings). Java 2 provides several types of collections, such as linked lists, dynamic arrays and hash tables for our use. Collections offer a new way to solve several common programming problems. The core of the Collection API is the new set of Interface called Set, Map and List. X.509 Certificates Certificates are digital documents attesting to the binding of a public key to an individual or other entity. They allow verification of the claim that a given public key does in fact belong to a given individual. Certificates help prevent someone from using a phony key to impersonate someone else. In their simplest form, certificates contain a public key and a name. As commonly used, a certificate also contains an expiration date, the name of the certifying authority that issued the certificate, a serial number, and perhaps other information. Most importantly, it contains the digital signature of the certificate issuer. The most widely accepted format for certificates is defined by the ITU-T X.509 international standard and thus, certificates can be read or written by any application complying with X.509 ITU-T Recommendation X.509 [CCI88c] specifies the authentication service for X.500 directories, as well as the widely adopted X.509 certificate syntax. The initial version of X.509 was published in 1988, version 2 was published in 1993, and version 3 was proposed in 1994 and considered for approval in 1995. JPDA The Java Platform Debugger Architecture (JPDA) consists of three interfaces designed for use by debuggers in development environments for desktop systems.

    a) The Java Virtual Machine Debugger Interface defines the services a VM must provide for debugging.

    b) The Java Debug Wire Protocol defines the format of information and requests

    transferred between the process being debugged and the debugger front end, which implements the Java Debug Interface.

    c) The Java Debug Interface defines information and requests at the user code level.

    RSA Signature Digital Signature are used as a means of security and RSA is the most widely used digital signature algorithm and is employed by most browsers, including Netscape Navigator and Internet Explorer

    In previous releases of Java Plug-in the lack of support for RSA signatures and dynamic trust management has impacted the usability and deployment of the Java security architecture.

  • In order for Plug-in to be able to verify RSA signatures in a browser-independent way, JDK 1.2.2 has bundled a Cryptographic Service Provider (CSP) with Plug-in. This CSP is capable of verifying RSA signatures. In particular, it supports the "MD2withRSA", "MD5withRSA", and "SHA1withRSA" digital signature algorithms.

    The bundled RSA provider is automatically registered with the Java Cryptographic Architecture framework as part of the static initializer of the PluginClassLoader.

    Versions of JDK and overview of Improvements and additions

    in each version and classes deprecated in various versions till JDK1.2

    The initial release of java was revolutionary and it continued to evolve at an explosive pace. After the release of Java 1.0, the features added by java 1.1 were more significant and substantial. JDK 1.1 added many new library elements, redefined the way events were handled by applets and deprecated several features of 1.0. Features added by 1.1

    1) Introduction of Java Beans which is software components that are written in java

    2) Serialization which allows you to save and restore the state of an object

    3) RMI, which allows a java object to invoke the methods of another java object that is located on a different machine. This is very important for distributed applications.

    4) JDBC which allows programs to access SQL databases from many different vendors

    5) JNI, which provides a new way for the programs to interface with code libraries written in

    other languages.

    6) Reflection which is the process of determining the fields, constructors and methods of a java object at runtime

    7) Various security features, such as digital signatures, message digests, access control

    lists and key generation.

    8) Built in support for 16 bit character streams that handle Unicode characters

    9) Significant changes to event handling that improve the way in which events generated by the GUI elements are handled.

    10) Inner classes which allow for one class to be defined within another

    Features added by 2.0

    1) Introduction of JFC of which Swing is the most important part

    2) Introduction of Collection API

  • 3) More flexible security mechanism is now available for java program. Policy files can define the permissions for code from various sources. These determine for example, whether a particular file or directory may be accessed or whether a connection can be established to a specific host and port.

    4) Digital certificates provide a mechanism to establish the identify of a user. You can think

    of them as electronic passport.

    5) Various security tools are available that enable you to create and store digital signatures, sign JAR files and check the signature of a jar file.

    6) The Accessibility library provided feature that make it easier for people with sight

    impairments or other disabilities to work with computers.

    7) The java 2D API provides advanced features for working with shapes, images and text.

    8) Drag and drop capabilities allow you to transfer data within or between applications.

    9) Text components can now receive Japanese, Chinese and Korean characters from the keyword. This is done by using a sequence of keystrokes to represent one character.

    10) The CORBA defines an Object Request Broker (ORB) and an IDL (Interface Definition

    Language). Classes deprecated in various versions till JDK 1.2 In JDK 1.1 The most affected class in the JDK 1.1 was the Date class in which most of the constructors have been deprecated. In JDK 1.2 The most important methods to be deprecated are the suspend (), resume and the stop () methods of the Thread class, because they can typically cause dead lock in the multi-threaded program.

    Difference between Java and C / C++ Although most of the C++ syntax has been taken by java the following are the functionalities, which are present in C++ but not in Java.

    1) Java does not include structures or unions 2) No automatic conversion done that result in loss of precision. For Example conversion

    from long to int must be specifically casted. 3) No global functions or variables. Since code in java programs is encapsulated within one

    or more classes 4) No concept multiple inheritance 5) No concept of destructors as the feature of Garbage Collector is there. 6) No goto keyword

  • 7) Objects are passed by reference only whereas in C++ it can be passed by value or by reference.

    The following are the new features in Java not present in C++

    1) Multi-Threading 2) Java Package 3) Interface. Although we had the concept of abstract classes, there was not a concept of

    interface. 4) There is only the new keyword and no delete keyword in Java 5) The break and continue jump statements can take labels also 6) A new >>> right shift operator 7) A new documentation comment which will be used by the javadoc utility 8) The boolean data type can take only true and false as values.

    OOPs Concepts Object Oriented Programming Skills (OOPs) is one of the latest techniques in Programming and is very popular with the concept of Objects. The advantage of OOP is that everything is taken as an object and relationship between the objects. Object oriented programming is like building structures like for example building a Computer. When we use OOP our overall program is made up of lots of different self contained components called as objects. Each object has a specific role in the program and all objects can talk to each other in a well defined way The advantage of OOP is that internally each of the components might be extremely complicated and but we need not know the details of each component. We just need to know the overall system functions because each component talks to one another in a well defined way. In java everything is taken as an object and object oriented programming is the core of java. All computer programs consist of two elements - code and data and a program can be conceptually organized around its code or around its data. The process - oriented model characterizes a program as a series of liner steps (that is code) and can be thought of as code acting on data. In Object oriented programming model the program is organized around its data (that is objects) and a set of well defined interfaces to that data and can be thought of as data controlling access to code. Any object will have two sections within itself that is data and methods. The data is the variables which the object has and the methods are the functions which act on those variables in the object. These two sections can also be called as the State and Behavior where the state is the data and the behavior is the methods within the object. The four fundamental principals of OOPs are:

    a) Polymorphism b) Data Encapsulation c) Inheritance d) Data Abstraction

  • Polymorphism is taken from the Greek work ‘poly’ which means many and ‘morphus’ which means forms and hence polymorphism would mean many forms. The simplest example of polymorphism would be the ‘+’ operator. When we say 10 + 10 it knows that it has integers on both the sides and it has to perform arithmetic calculation and would give the answer as 20, but incase we say “Hello” + “There” it would know that both the side are strings and it has to add them up or concatenate them.

    Polymorphism is supported in java by means of concept of overloading which we will look later in this module. Encapsulation is the mechanism that binds together code and the data it manipulates, and keeps both safe from outside interference and misuse. This is done in java by ensuring that the data in an object can only be accessed by the methods of that object only and incase any other object need to access the data of an object, it cannot do it directly but only through the methods of that object. This feature is like a protective capsule to the data ensuring that only the methods of an object access the data of that object. Inheritance is the process by which one object acquires the properties of another object. The object from which a class inherits is called the super class or the parent class and the class which inherits is called the sub class or child class. Take the example of Animal class which will have two sub classes called Mammal class and Reptile class and this continues. The Inheritance interacts with Encapsulation as well. For example, the Animal class encapsulates some properties / features and all the subclasses will have the same properties plus any of the properties which it adds as part of its specialization. Data Abstraction is the feature of hiding the implementation from the user. For example, when we start the computer, we are not bothered with the complexities of how the computer boots, but once the computer is fully started then we start working with our programs. Similarly when we sit in a car and drivers, we are not bothered with how the steering wheel communicates with the wheels or how the car starts up etc. Similarly when we give a program to a client, we just tell the client to click on the executable file and how the client is abstracted away from the minute details of how the programs functions.

    So in simple words Data Abstraction means giving only details which are required by the user and not over-burdening him with many details

    Dissecting the First Code Now let’s get to write our first code. We will open any text editor (notepad or edit command in the dos) and type in our code as under: IMP: Remember java is case sensitive, that would mean letters which are supposed to be in Capital should be in Capital only or otherwise specifically. We will now type the following 7 lines of code as specifically written in a file in the text editor (Which can be a Notepad or any other text editor)

  • Code public class Test { public static void main (String args []) { System.out.println (“Hello, Welcome to Learning Java with Prof Venkat Krishnan”); } } Points to be noted:

    1 All source codes should be done within classes. There can be either one class or more than one class in any source code file.

    2 A class is a template for data and is also an object. 3 The opening brace {and the closing brace} define the body of the class or the

    method. 4 If the braces do not occur in matching pairs, the compiler indicates an error. 5 Semi-colons at the end of the line is mandatory and omitting the same at the end of a

    statement is a syntax error. A syntax error is caused when the compiler cannot recognize the statement. The compiler normally issues an error message to help the programmer to locate and fix the incorrect statements. Syntax errors are violation of the language rules.

    6 There should be atleast a semi-colon or an opening brace ( { ) but not both as together at the end of a line.

    7 One can call the class whatever you want (within the limits of identifier, which we will see in the next sub-module), but the method, which is executed first in an application, is always called the main ().

    8 When you run your java application the method main () will typically cause methods belonging to the other classes to be executed, but the simplest possible java application consist of one class containing the main () method.

    9 There can be only one main () in any source code file. 10 There can only be one public class in a source code file. 11 The syntax of the main () is fixed and is public static void main (String args[]) 12 Also note the braces. There will be one set of braces for each and every class and

    one for the method. 13 The class name should always be start with a capital Alphabet. This is not mandatory

    but is java coding standard. Now let’s see what each of the words in the file is meant:

    1 public – This keyword indicates that the class and method is globally accessible. The other access modifiers are default (nothing given), private and protected, which we will see later on.

    2 static – The keyword static ensures that it is accessible even though no objects of the

    class exist.

    3 void – This indicates that the method has no return type. It is mandatory for every method to have a return type and incase there is no return type, the method should be pre-fixed with void keyword.

    4 (String args []) – Every method has a (), thorough which we can pass any parameter

    required for the method and in this main () we pass the String array having the name args. The array is defined by []. The name of the array can be anything, but it is a convention to type it as args.

  • 5 System – This is the name of the standard class that contains variables and methods

    for supporting simple keyboard input and character outputs to the display. It is contained in a package java.lang so it is always accessible just by using the simple class name, System.

    6 out – The object out represents the standard output stream – your display screen and

    is a data member of the class System. The member out is a special kind of member of the System class. Like the main () in our program, it is also static. This means that out exists even though there is no object of type System. The out member is referenced by using the class name, System, separated from the member name out by a full stop.

    7 println () – This is the println () method that belongs to the object out and that outputs

    anything that is within the parameters of the method. Over here we are printing out the text string in the println method.

    Now we will name the source code file as Test.java and we will compile the file by going to the dos-prompt and writing javac Test.java. Once the class is properly compiled we will find a .class file with the same name as the source code file. Over here we will check what the class loader which we have learnt earlier is We will try to see what classes are loaded when we are compiling Test.java. We have written in the code two classes String and System. To see what classes are loaded we will compile by writing javac -verbose Test.java. To see what options are available with javac command just type javac and press enter at the console. After writing -verbose command, we will see that a lot of classes are loaded when the code is compiled and finally the .class file is generated and the total amount taken is also mentioned for our reference. Now we will see what a Byte Code Verifier is. We will open the .class file in an editor, it will all be in junk characters, but we will delete one of the legible characters and again type the same character. We have not done anything but only edit the class file to see whether the Byte Code Verifier checks it properly or not. We will now execute the .class file (without re-compiling the same) (by typing java Test) and bingo it refuses to work and will throw an exception. e.g. ClassFormatError. So the Byte Code Verifier indeed does it job. Now we will again recompile the Test.java so that the old class file is overwritten and then execute by calling java Test. When we call the interpreter we will not type any extension after the File name. The Interpreter calls the class file and not the .java file. We can check this by taking the .java file else whether and then calling the interpreter.

    Source Code Layout and Comments In a source code, as we have seen earlier, it would contain the class keyword. But the other keywords in the layout would be package and import statement (which we will see later on).

  • In a normal source code layout, the package would be the first statement or line in the code layout and will be followed by the import statement (if any) and followed by the class keyword. The above order is mandatory and cannot be changed. Also it is very important to remember that we should not use existing system defined class names as our class names. There are 3 types of comments in java and they are

    a) Single Line comment which is \\ b) Multiple Line comment which is \* and ends with *\

    c) Javadoc comment which is \** and *\.

    A comment is a line which is not read by the java compiler and interpreter when it goes through the source code file. Javadoc is a special comment which is read by the javadoc utility A blank space or white space have no effect in java, as the compiler does not take a white space into consideration other than when it is within a String.

    Identifiers An identifier is something which identifies a class, a method name, a variable name, or a parameter name. For example, we have given the class name as Test, so here Test is the identifier and args is the identifier for the String array being passed in the main method and main the identifier etc. An identifier can begin with the following only:-

    - May begin with a letter - May begin with a Dollar sign ($) - May begin with a underscore (_)

    So any identifier cannot start with a numerical number or any other special character. To try this just change the Test name to 1Test and see the error coming up. Code public class 1Test { public static void main (String args []) { System.out.println ("Hello, Welcome to Gurukul Online Learning Systems"); } } Output

  • 1Test.java:1: expected public class 1Test ^ 1Test.java:7: '{' expected } ^ 1Test.java:1: class is public, should be declared in a file named .java public class 1Test ^ 3 errors

    Keywords and Blocks Keywords are words having special meaning to the Java Technology Compiler. They identify a data type name or program construct name goto and const are reserved words in java, which means they are not keywords, but are reserved for future use. There are 48 basic keywords and they are as under:-

    abstract do implements private throw boolean double import protected throws break else instanceof public transient byte extends int return true case final interface short try catch finally long static void char float native super volatile class for new switch while continue future null synchronized default if package this

    A block is a set of codes which will be executed at once. The block should have the opening braces ( { ) and closing braces ( } ). All methods and classes have blocks which mean that they are executed in one single process.

    Variables A variable is a named piece of memory that you use to store information in your java programs – a piece of data of some description. In short variables are locations in memory in which values are stored. If you define a variable to store integers, for example you cannot use it to store a value that is of decimal fraction or a string value

    Before you can use a variable, you have to declare it. After it is declared, you can then assign values to it and use it. The declaration does the following -

  • a) Tells the compiler what the variable name is, so that it can referenced in future b) Tells the compiler the type of data the variable will or can hold. Java is very particular

    about the data type and if you specify any variable can hold integer, then that variable cannot hold any other data type (i.e. String, Double, Float etc) and compiler check for the same.

    c) The place of declaration decides the scope of variables, whether the variable is local

    variable or class variable or instance variable. Therefore Variables are of 3 kinds namely, Local Variable, Class Variables or Instance Variables. Local Variables - They are local to the method and are visible only inside the method in which they are declared. Incase we try to access the variables outside the method it would throw an error. The important thing to note is that method / local variables need to be initialized or the compiler would throw an error.

    Code class Test1 { public static void main (String[] args) { System.out.println(a); } void met1() { int a = 10; } }

    Output The compiler would throw an error that it cannot resolve the symbol a. Here the compiler is trying to tell us that it does not understand what a means over here. This is because int a is defined in met1 () and hence becomes a method variable and we are trying to access the same in the main method where it does not have a scope. class Test1A { public static void main(String[] args) { int a; System.out.println(a); } } Output The compiler would throw an error stating that variable is not initialized. This is because the rule is that method variables need to be initialized before being used. Class Variables - These variables are declared outside the main method right in the beginning or right at the end. The scope of the class variable is for all the methods in that particular class.

    The class variables need not be initialized as they take default values.

  • The Important point to be noted here is that there is only one memory location for the class variables. Default value of a class variable: Data Type Default Value boolean false char \u0000 (that is nothing) byte 0 short 0 int 0 long 0L float 0.0f double 0.0d String null Before we go to the instance variables, we need to understand what the meaning of an instance is. An instance is a copy of the object which we are creating with the new keyword and each instance shall have a copy of the class variables and methods of that object.

    For example, if we have a class called Test which has a method called met1() and we need to call the method, then first of all we would be required to create an instance of the class and then call the method with that instance.

    Code class Test2 { int a; public static void main(String[] args) { Test2 x = new Test2(); x.met1(); } void met1() { System.out.println(a); } } Output It would be 0 (zero) since it has taken the default value. In the above code we are creating an instance of class Test2 and x is called the instance and with the instance we are calling the method. This is the standard way any non static method needs to be called. Instance Variables: Instance variables are created when objects are instantiated and therefore they are associated with the object. They take different value for each object.

    Code class Test4 { int a = 10;

  • public static void main(String[] args) { Test4 x = new Test4(); x.a = 20; Test4 y = new Test4(); System.out.println(y.a); } } Output: It would print out 10. This is because when we create a new instance a copy of the class variable is given to each of the instances and hence when we change x.a = 20, we are changing the value of a for the instance x and when we create a new instance it would by default have the copy of the original class variable. Over here it is important to understand that there are 3 separate memory locations, one for the class variable and two memory locations for the two different instances and a separate memory location would be created for any new instance. We learnt what is static earlier on, but now we will properly examine this keyword. static keyword can be applied either to a variable or to a method. When static keyword is applied to a class variable (it can be prefixed only to a class variable, will give a compilation error incase applied to a method variable), then it would mean that class variable would be shared by all the instance of the classes. There would only be one memory location and no different locations for the instance variables. Hence any change made by one instance would change the original class variable also. Let’s see this by way of an example. Code class Test4A { static int a = 10; public static void main(String[] args) { Test4 x = new Test4(); x.a = 20; Test4 y = new Test4(); System.out.println(y.a); } } Output: It would give 20 as the answer, because when we said x.a=20, we are infact changing the original class variable’s value also to 20, since there is only one memory location for the static class variable and instances. Non- static class variables are also called as instance variables. Now let us see what the static keyword means when applied to a method. We have already seen that for a non-static method an instance of a class is required and we can call a non-static method only with the instance of the class. Code class Test5 { public static void main(String[] args) { Test5.met1();

  • } static void met1() { System.out.println("Hello World!"); } } Output It would give the output of Hello World. This would mean that for a static method, there is no need for the instance of a class. We can directly call the static method with the class name, since static methods are associated with the class directly. static methods have a limitation however that it can only access static class variables and cannot access non-static class variables. Code class Test6 { int a = 10; public static void main(String[] args) { System.out.println(a); } } Output It would give an error stating that non-static variables cannot be referenced from static context. IMP: Over here one needs to understand the difference between directly printing out the class variable and printing out the class variable with an instance of the class. One of the standard questions in the exam would be why the main method should always be static? The reason is that since the main method is called first by the compiler or it is starting point of entry into a source code file and no instance of the class is created (instances can be created only the main method), hence the main method should be static.

    Data Types The data types specify the size and type of values that can be stored in the variable. There is no sizeof operator in Java as the size and representation of all types is fixed and is not implementation dependent. Hence java is called as a strictly typed language. Each primitive data type has a name, specifies how much memory is required to store a data item of that data type, and identifies a legal range of values from which a data item of that data type can be obtained. Again the Primitive data types can be classified into the following 4 major categories

    a) Textual Data Type b) Integral Data Type c) Logical Data Type d) Floating Data Type

  • Textual Data Type: This is represented by char and individual characters and can hold only single characters - The character should be put inside quotes (‘ ‘) while defining the same. Characters are stored in 16-it Unicode characters and the range is from 0 to 255 and there is no negative char. For example char c = ‘a’; It is important to note that char in C/C++ and in Java are different because in C/C++, char is an integer type with 8 bits wide. Java uses Unicode to represent characters. Unicode defines a fully international character set that can represent all the characters found in all human languages. Since java is designed to allow applets to be written for worldwide use, it makes sense that it would use Unicode to represent characters. The following table lists the special codes that can represent nonprintable characters, as well as characters from the Unicode character set. Characters escape codes.

    Escape Meaning \n New line \t Tab

    The Integral Data Type can be represented in 3 forms namely;

    a) Decimal – Where the decimal value is two b) Octal – Where the leading zero indicates an octal value (E.g. 077) c) Hexadecimal – Where the leading OX indicates a hexadecimal value (E.g. OX22)

    The default Integral type is int and for Long it has to be explicitly followed by the letter L. There are 4 types of variables that you can use to store data and all of these are signed that mean you can use both negative and positive values. The four integer types differ in the range of values they can store, so the choice of types for a variable depends on the range of data values you are likely to need. The four integer types are: Type Size Range

    byte 8 bits -128 to 127 short 16 bits -32,768 to 32,767 int 32 bits -2,147,483,648 to 2,147,483,647 long 64 bits -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 The smallest integral type is byte. This is a signed 8-bit and is especially useful when you are working with a stream of data from a network or file. short is a signed 16-bit data type IMP: It is very important to note here that integer expressions using byte and short are AUTOMATICALLY PROMOTED to int before the calculation is done. This has a specific reason and will be explained later on. The type long is a 64-bit and is useful for those occasions where an int type is not large enough to hold the desired values

  • We should specifically write L (capital alphabet) or l (small alphabet) after the initialized value of a long to ensure that the compiler takes it as a long value, otherwise if we just declare long l = 12345678912, the compiler will take it as a int value and give an error. Code class Test7 { public static void main(String[] args) { long l = 12345678912; System.out.println(l); } } Output The error would be integer number is too large, which proves that in spite of declaring as a long data type, the compiler has taken the default of integral as int. To ensure that the compiler takes it as a long data type, the initialized value should be followed by L and then we would get the desired result. We said earlier that byte and short are automatically promoted to int before any calculation is done on them. This because their values are very small and the final result would be within the size of a byte, but in between the calculation what should be done incase it goes beyond the range. To prevent this, byte and short are automatically promoted to int. For example (10*10*10) / 100 would give answer as 100 but in between the value has gone to 1000 which is beyond the range of a byte. Code class Test8 { public static void main(String[] args) { byte b = 10; byte c = 10; byte d = b + c; System.out.println(d); } } Output: This would a error saying loss of precision since as per the rule byte gets converted into a int during calculations on byte and short and int values cannot be accommodated in a byte value (as int is 32 bits and byte is 8 bits). To ensure that the code gets properly compiled the easy way is to change the data type of d as int. However in many cases, we would want the value of d to be as a byte value only. In this case we would be required to cast the result to ensure that it gets stored in a byte data type and this is done by doing it in the following manner.

    byte d = (byte) (b + c); For values which are below 127, there would be no problem and there would serious issues incase the values go beyond the value of 127. To under this let us see the following code

  • Code class Test8 { public static void main(String[] args) { byte b = 10; byte c = 13; byte d = (byte) (b * c); System.out.println(d); } } Output The output would be -126. Now we would be thinking how in the world did this figure comes from. Whenever we cast any value into any smaller data type, there would be issue of loss of precision. To understand loss of precision, let us take an example of putting a cup of tea into a saucer fully, it is bound to overflow and some tea would be lost. Similarly when we do casting there would be loss of values. Now let us take the above example and analyze the same. Since the value of 130 is beyond the range of a byte as the maximum value of a byte would be only 127, it again goes back and starts putting the bytes in the old blocks. Remember the range of a byte is from -128 to 127. So the value of 128 is put in -128 and so on and hence the result of -126. It is very important to note incase the value is very big, it will go on doing the above thing till it reaches -1 and then 0 and then 1 and till 127 and again -128 and till keep on going like this. In Java, the only logical data type is boolean which takes only two states, true or false. In java, unlike C and C++ boolean is neither a number nor it can be treated as one. All tests of boolean should test for true or false. Also note that boolean states are in small caps and not like other languages where true should mandatorily be declared as TRUE and vice versa. It is also important to note that boolean values cannot be converted or casted with other data types also. The boolean data type is used by the control statements like if and for etc. Floating-point numbers are also known as real numbers are used when evaluating expressions that require fractional precision. There are two kinds of floating point types, float and double which represent single and double precision numbers in the width and range as under:

    Type Size Range

    float 32 bit 3.4e-038 to 3.4e+038 double 64 bit 1.7e-308 to 1.7e+308

    The default of floating point data type is double and hence for using float we should mandatorily use f after the values (like long). Code class Test9 { public static void main(String[] args)

  • { float f = 10.11; System.out.println(f); } } Output It would give an error of loss of precision, since it has taken the default value of a double.

    Coding Conventions Classes should start with Capital Alphabets. The class will compile incase we have a small alphabet class, but then it is a convention followed in the java world and hence we would like to differ from the general rules of convention. The second letter incase one is there in the class should also start with Capital alphabets. For Example IndexArrayOutOfBoundsException. The methods should start with lower alphabets and the second word in the method should be capital. For example. startsWith (), endWidth() or getDocumentBase() methods. The interfaces should also follow the rules layed down for classes. The packages should start with small alphabets. For Example java.lang, java.awt. etc All variables (class and method) should start with small alphabets and the second word should start with Capital Alphabets like the rule for methods. Although the $ sign is permitted as an identifier, we should try to limit the use of $ sign in the class names, because it was a special meaning when we are using the Inner classes.

    Arrays Array is a group of similar kind of data types that is reference by a common name. Suppose if we want a group of integers from 1 to 100 to be reference by a common name, we create an array of them. Each variable in an array is called array element. It is important to note that the array numbering stars from 0 and not 1. Array is an object and not a primitive, even if it is made up of primitives. Like objects, array required initialization and declaration only creates a reference to the array. To explain in depth, to create a array is to 3 steps

    a) Declaration b) Creation c) Initialization

    Declaration One is not obliged to create the array itself when you declare the array variable. The array variable is distinct from the array itself. This is how one declares a array.

  • int a [] - This is a array of integers with the variable a String s [] - This is a array of strings with the variable s

    Creation Once you declare an array of any data type, you should create the same with the help of the new keyword and the same is done like this a = new int [10]; s = new String [5]; The above example shows that the array with the variable a will store integers up to 10 values and the second example creates that the s (String variable) will store Strings up to 5 values.

    Remember: The array length starts from 0 The creation of array only reserves the space in memory for 10 integers and 5 strings, but nothing is inside it.

    Initialization Once we have the memory reserved, we can put values into each of the individual spaces like this: a[0] = 10; This puts 10 as the first value of the array a[1] = 20; This puts 20 as the second value of the array and so on. Similarly we can put strings into the 5 spaces as under; s[0] = “Gurukul” and so on.

    Direct Declaration and Creation The above 1 and 2 steps can be do simultaneous like this int a [] = new int [10]; It is important to note that the [] box can be put before or after the array variable. This is also correct. int [] a = new int[10];

    Direct Initialization Since the above process is cumbersome, we can initialize an array with your own values when you declare it and at the same time determine how many elements it will have. This is done as below:

  • int a [] = { 1,25,30,55} This creates an array with variable name as a and with values as put into the {} and with 4 elements.

    Accessing Array Values You can refer to an element of an array by using the array variable followed by the element’s index value enclosed between square brackets. For Example Existing Array: int a [] = { 1,25,30,55} If we have to access the 2nd element of the array, we will do it like this int a[1], here we use 1 because, as said earlier, the array indexing begins with 1. Important: Any attempt to access array indexes beyond the length of the array causes runtime error. For example: If we try to access the 5th element, it will give a runtime error, because there is no 5th element in the array. The exception thrown would be called as ArrayIndexOutOfBoundsException. We will cover the topic of runtime error and the different types of exceptions thrown in the other modules. Code class Test22 { public static void main(String[] args) { int a [] = new int[10]; System.out.println(a[10]); } } Output java.lang.ArrayIndexOutOfBoundsException at Test22.main(Test22.java:6) Exception in thread "main"

    Array Bounds In the java programming language, all array subscripts begin at zero. The number of elements in an array is stored as part of the array object, as the length attribute. This value is used to perform bounds checking of all runtime accesses. If an out-bounds access occurs, then a runtime error occurs. Use the length attribute to iterate on an array as follows: int list[] = new list [10]; for (int I = 0 ; I < list.length ; I++) { System.out.println[i];

  • ) Using the length attribute makes the program maintenance easier

    Array resizing Once created, an array cannot be resized. However you can use the same reference variable to refer to an entirely new array. Since an array cannot be resized, this is the biggest limitation of arrays. int d[] = new int [6]; d = new int [10]; In this case, the first array is effectively lost unless another reference to it is retained elsewhere.

    Array Copying The java language provides a special method in the System class arraycopy () to copy arrays. The syntax for copying array is: System.arraycopy ( original array, 0 (index to start with), new array, 0 (index of new array from where copying has to start), original array.length (or number of references to be copied); The above method can be proved with the help of this example. // original array. int a[] = {1,2,3,4,5,6}; // new larger array. int d[] = {10,9,8,7,6,5,4,3,2,1}; System.arraycopy{a,0,d,0,a.length); After this, the array d will have the following content: 1,2,3,4,5,6,4,3,2,1} Note: The method System.arraycopy() copies, references, not objects, when dealing with array of objects. The objects themselves do not change. Code class Test23 { public static void main(String[] args) { int a[] = {1,2,3,4,5}; int b[] = {10,20,30,40,50,60,70,80}; System.arraycopy(a,2,b,3,2); for (int i = 0; i

  • } Output

    10 20 30 3 4 60 70 80 Multi-Dimensional Arrays We have only worked with one-dimensional arrays up to now, that is arrays that use a single index.

    Why would you ever need the complications of using more indexes to access the elements of an array? Suppose that you have a fanatical interest in the weather and you are intent on recording the temperature each day at 10 separate geographical locations throughout the year 1999. Once you have sorted out the logistics of actually collecting this information, you can use an array of 10 elements corresponding to the number of locations, where each of these elements is an array of 365 elements to store the temperate values. You would declare this array with the statement float temperature [] [] = new float [10] [365]; There are 10 arrays each having 365 elements. In referring to an element, the first square brackets enclose the index for a particular array, and second pair of square brackets encloses the index value for an element within that array. So to refer to the temperate for day 100 for the sixth location, you would use temperature [5] [99]. In java, multidimensional arrays are actually array of arrays. To declare a multidimensional array a variable, specify each additional index using another set of square brackets. For example, the following declares a two-dimensional array variable called D. int D [] [] = new int [2] [4] The above array creates and allocated a 2 by 4 array. Internally this acts like a matrix in which the first square bracket is for the number of rows and the second bracket is for the number of columns. Remember: Note that you can have an array with 0 columns but not with 0 rows. For example int D[] [] = new int [2] [0] - Ok int D[] [] = new int [0] [2] - Not Ok.

  • Java Operators Java provides a fully featured set of operators, most of which are taken fairly directly from C and C++. However Java’s operators differ in some important aspects from their counterparts in these other languages and you need to understand clearly how java’s operators function. The Java Operators can be classified into 8 Groups as under:

    a) Unary Operators b) Arithmetic Operators c) Comparison Operators d) Bitwise Operators e) Short-Circuit Operators f) Ternary Operators g) Assignment Operators

    The Unary operators can be classified further into :

    1) Increment and Decrement Operators; ++ -- 2) Unary plus and minus Operators; + - 3) The boolean complement operators; ! 4) The Cast operator; ()

    Increment and Decrement Operators These operators modify the value of an expression by adding or subtracting 1. So for example, if an int variable x contains 10, then ++x results in 11 and --x give you 9. This is the case because the increment and decrement is done on x and the value is stored in x only To understand how the position of these operators’ ++x and x++ affect their operation, you must understand the different between the values stored by these operations and the result value they give. For example, you could say y = x++; then the value assigned to y will be the original value of x and if you say y = ++x, then the value assigned to y will be 1 more than the original value of x. It is important to note here that in both these cases the value of x will be increment by 1. The following table shows the value of x and y, before and after particular assignment using these operators: Initial value of x Expression Final Value of y Final value of x 10 y = x++ 10 11 10 y = ++x 11 11 10 y = --x 9 9 10 y = x-- 10 9 The Unary + and – operators The unary + and – operators are distinct from the more common binary + and – operators which are usually referred to as + and – (add and subtract).

  • The unary + has no effect beyond emphasizing the positive nature of a numeric literal. Unary – negates an expression. So one might make a block of assignment just like this: x = -3; y = +3; z = -(y+6); The Boolean Complement Operator ! This operator inverts the value of a boolean expression so !true gives false and !false would give true. This operator is usually used in the body of if() and else() to be swapped. The Cast Operator Casting is used for explicit conversion of the type of an expression. This is only possible for plausible target types. The compiler and runtime system check for conformance with typing rules and incase they do not match, then casting might be required. Casts can be applied to change the type of primitive values, for example forcing a double value into an int value like this: int c = 10; double b = 15.50; int d = (int) (c x b);

    Arithmetic Operators The next highest in precedence, after the unary operators are the arithmetic operators. The Arithmetic Operators are divided into two further sub groups, the first group having the *, / and % operators. The second group have the lower precedence + and – operators. Multiplication and Division Operators The above operators can be used on all primitive numeric types and char. Integer division can generate an ArithmeticException from a division by zero. The multiplication and division works as it works in simple math examples which we learnt in school. The important point to note here is that, whether you multiply or divide two integers, the result will be calculated using the integer arithmetic in either int or long representation and u will have to store the same in the wider of the types to ensure that precision is maintained. Modulo Operator % The modulo Operator gives a value which is related to the remainder of a division. It is generally applied to two integers, although it can be applied to floating point numbers also. For example when you say int a = 7 int b = 3 int c = a % b the result would be 1. The Addition and Subtraction Operators

  • The + and – operators perform addition and subtraction and they apply to operands of any numeric type, but uniquely, the + operator is also permitted when either of the operand is a String object. When either of the operands of a + expression is a String object, the meaning of the operator is changed from numeric addition to concatenation of text. In order to achieve this, both operators must be handled as a text. If both operators are in fact String objects, this simple, however if one of the operands is not a String object, then the non string operand is converted to a String object before the concatenation is taken place. How operands are converted into String Objects?? It is very usef