Java Notes1

Share Embed Donate


Short Description

This is guide for how to use tomcat server for jsp and servelt...........

Description

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 jdk installed)

where jdk1.3 is the directory name (default directory in which u have your

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) b) c)

Applets Security 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

5

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.

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) b) c)

Class Loader Byte-Code Verifier 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) c)

Java 2 Enterprise Edition (J2EE) 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-theart 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) 2) 3) 4) 5) 6) 7) 8) 9) 10)

Import the necessary classes. Load the JDBC Driver Identify the Data Source Allocate a Connection Object Allocate a Statement Object Execute a Query using the Statement Object Retrieve Data from the returned Result Set Object Close the RS Close the Statement 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) b) c) d)

Polymorphism Data Encapsulation Inheritance 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 2 3 4 5

6 7

8

9 10 11 12 13

All source codes should be done within classes. There can be either one class or more than one class in any source code file. A class is a template for data and is also an object. The opening brace {and the closing brace} define the body of the class or the method. If the braces do not occur in matching pairs, the compiler indicates an error. 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. There should be atleast a semi-colon or an opening brace ( { ) but not both as together at the end of a line. 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 (). 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. There can be only one main () in any source code file. There can only be one public class in a source code file. The syntax of the main () is fixed and is public static void main (String args[]) Also note the braces. There will be one set of braces for each and every class and one for the method. 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) b) c) d)

Textual Data Type Integral Data Type Logical Data Type 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 [] String s []

-

This is a array of integers with the variable a 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; i3

= 3

Object Type comparison is done with the help of the instanceof Operator This is the operator, which tests the class of an object at runtime. The left-hand argument can be any object reference expression, usually a variable, while the right hand operand must be a class, interface or array type. You cannot use a java.lang.Class object or its string name as the right hand operands.

The instanceof operator returns true if the class of a left hand argument is the same or is some subclass of the class specified by the right hand operand. The right hand operand may equally well be an interface. In such a case, the test determines if the object at the left hand argument implements the specified interface. Note: If the left hand argument is a null type, the instanceof test simply returns false – it does not cause an exception. Code class Test13 { public static void main(String[] args) { A x = new A(); B y = new B(); C z = new C(); boolean k = x instanceof B; boolean l = y instanceof A; boolean m = z instanceof B;

//

System.out.println(k); System.out.println(l); } } class A { }; class B extends A { }; class C extends A { }; Output: It would be false and true. Over here we have class A which has 2 subclasses. Now we have introduced a new keyword called extends. It is this keyword which makes possible inheritance possible in Java. Then we create 3 instances of each of the classes. Since all comparison operators return a boolean value, we are capturing the same in a boolean variable. First we check whether x is a instanceof B and it return false because a superclass instance cannot be a instance of the subclass. Then we check whether y is a instance of A and it returns true because a subclass variable is a instance of the subclass and also of the super class since the subclass extends the super class.

incase we remove the comment and printout the variable m also, it would result into a compilation error because there cannot be a relationship between two unrelated classes. It will not give false also, but a compilation error. Equality comparison operators: == and != and equals() The Equality comparison can be on two grounds: a)

Checking the Memory location equality (whether both the variables being checked belong to the same memory location or not).

b)

The content Equality. (checking the contents of the String)

The operators == and != test for equality and inequality, respectively returning a boolean value. For primitive type, the concept of equality is quite straightforward and is subject to promotion rules so that for example a float value of 10.0 is considered equal to a byte value of 10. For variables of object type, the “value” is taken as the reference to the object; typically this is the memory address. You should not use these operators to compare the contents of objects, such as Strings because they will return true if two reference refer to the same object, rather than if the two objects have an equivalent meaning. Code class Test14 { public static void main(String[] args) { String s = "Hello"; String s1 = "Hello"; String s2 = new String ("Hello"); String s3 = new String ("Hello"); boolean a = s == s1; boolean b = s1 == s2; boolean c = s2 == s3; System.out.println(a); System.out.println(b); System.out.println(c); } } Output: It would be true, false and false. Now before we go to the result, we need to understand what do one mean by memory location. There are two parts of a computer memory, a stack and a heap. In the earlier programming languages, String was a primitive data type, but in java, they wanted it to be an object and also as a data type and hence String is the only class which can be created without the new keyword. When String is initialized without the new keyword it is taken as a primitive data type and when it is initialized with the new keyword it is taken as a proper object. Hence we cannot call the methods of a String object on the primitive data type.

The rules for Stack and Heap are as under:a)

primitive data types are always stored in the stack.

b)

The rule in the stack is that, once we have a particular value, a memory location is allotted to it and when another variable is initialized to the same value, a different memory location is not created, but the same memory location now points to both the variables.

c)

Objects are always stored in the heap.

d)

Whenever a object is created with a new keyword a new memory location is created irrespective of the contents of the Object.

Now based on the above rules, we can analyze the above code as under:a)

Both the String values of s and s1 would be stored in the stack.

b)

Since both the values of s and s1 are the same, it would have the same memory location and hence s == s1 returns true.

c)

Now s2 and s3 are created with the new keyword and hence they would be allotted separate memory locations, in the help although they have the same contents.

d)

Hence s2 == s3 would return false.

e)

s1 == s2 would definitely give false, because they are in separated areas of memory.

To achieve a in-depth comparison, so that two different String objects containing the text “Hello” are considered equal, you must see the equals() rather than the == method. IMP: We have a equals method in the Object class, which is similar to the == method which checks for the equality on the basis of the memory location. However in the String class the equals method have been overridden to check for the equality on the basis of contents. Check the following code Code class Test15 { public static void main(String[] args) { String s = new String ("Hello"); String s1 = new String ("Hello"); StringBuffer sb1 = new StringBuffer("Hello"); StringBuffer sb2 = new StringBuffer("Hello"); boolean a = s.equals(s1); boolean b = sb1.equals(sb2); System.out.println(a); System.out.println(b); }

} Output The answer would be true and false. This is because as said earlier, the equals method have been overridden in the String class to check for the contents whereas in the StringBuffer class the same have not been overridden and hence it checks like the normal equals method which is the memory location and since both are object created with the new keyword, they would have different memory locations and hence false. Bitwise Operators The Bitwise Operators &, ^ and | provide AND, Exclusive-OR (XOR) and OR Operations respectively. They are applicable to internal types. The bitwise operations calculate each bit of their results by comparing the corresponding bits of the two operands on the basis of these 3 rules: a) For AND Operations, 1 and 1 produces 1 and any other combination produces 0 b) For XOR Operations, 1 XOR 0 produces 1 as does 0 XOR 1 and any other combination produces 0 c) For OR Operation 0 OR 0 produces 0 and any other combination produces 1 The names AND, XOR and OR are intended to be mnemonic for these operations. You get 1 result from an AND operation if both the first operand and second operand are 1. An XOR gives 1 result if one or the other operand, but not both (the exclusivity part) is 1. In the OR Operation, you get 1 result if either the first operand or the second operand (or both) is 1 Code class Test16 { public static void main(String[] args) { int a = 10; int b = 15; int c = a & b; int d = a | b; int e = a ^ b; System.out.println(c); System.out.println(d); System.out.println(e); } } Output The answer would be 10, 15 and 5 To check this let us first take a scientific calculator and out the bit pattern of 10 and 15. The bit pattern of 10 is = 1010 The bit pattern of 15 is = 1111

(please remember that int is of 32 bits and since there are zeros in the beginning it is not coming the calculator, but for calculation purpose we need to work out the 28 initial zeros also. Now each bit in the first value will be calculated with the first bit of the second value and similarly all the 32 bits are calculated and then finally whatever bit number comes it is converted in to a integer comes and that is how the values of 10, 15 and 5 came in the above example. Bitwise on Boolean Operations The &, ^ and | operators behave in fundamental the same way when applied to arguments of boolean rather than integral types. However instead of calculating the result on a bit by bit basis the boolean values are treated as single bits, with true corresponding to a 1 bit and false to a 0 bit. The general rules discussed in the previous section may be modified like this when applied to boolean values a) For AND Operations, true AND true produces true and any other combination produces false. b) For XOR Operations, true XOR false produces true or false XOR true produces true and any other combination produces false. For OR Operation, false OR false produces false and for any other combination produces true. Operator

Meaning

~

Bitwise complement

> y)

>>>=

Zero fill right shift assignment (x = x >>> y)

x&=y

AND assignment (x = x & y)

x|=y

OR assignment (x = x | y)

x^=y

XOR assignment (x = x ^ y)

Short Circuit Logical Operators The short circuit logical operators && and || provides logical AND and OR operations on boolean types. Note that there is no XOR operation provided. Superficially this is similar to the & and | operators with the limitation of only being applicable to boolean values and not integral types. However the && and || operators have a valuable additional feature: the ability to short-circuit a calculation if the result is definitely known. This feature makes these operators central to a popular null-reference-handling idiom in java programming. The main difference between the & and && and the | and || operators is that the right hand side operand might not be evaluated at all. This behavior is based on two mathematical rules that define conditions under which the result of a boolean AND or OR operations is entirely determined by one operand without regard for the value of the other: a) For a AND operation, if the Left Hand operand is false, the result is false, without regard to the other operand. b) For an OR operation, if the Left Hand is true, the result is true, without regard to the other operand.

Given these rules, if the left hand operand of a boolean AND operation is false, the result is definitely false whatever the right hand operand may be. It is therefore unnecessary to evaluate the right hand operand. Similarly, if the left hand operand of a boolean OR operation is true, the result is true and the right hand operand need not be evaluated. For Example if ((s != null) && (s.length() > 20)) { System.out.println(s); } Now here if the String reference is null, then calling the s.length() method would raise a NullPointerException. If we use the short-circuit && then that situation would not arise, because if (s != null) returns false, then the whole test expression is guaranteed to be false. Where the first operand is false then in && the second operand is not evaluated at all and the s.length () is not evaluated at all. The Ternary Operator: The ternary operator provides a way to code simple situations (if/else) into a single expression. The syntax for a ternary operator is (boolean condition) ? true : false. Here the boolean condition is evaluated and if the result is true then the value of the expression after the ? is evaluated (here true) otherwise it is the value after the colon will be evaluated ( here false). The sub expressions (true and false) on either side of the colon must have the same type. Example: int a = 10; int b = 20; inc c = (a>b)?40:50. This will give the value of c as 50, since (a>b) returns false and hence the right hand side of the colon will be evaluated. Assignment Operators The assignment operators set the value of a variable or expression to a new value. Simple assignment uses =. Besides simple assignments, compound “calculate and assign” is provided by operators such as += and *=. These operators do the calculation and then assigns. The point to be noted here with the right hand operand must be a type that is assignment compatible with the left hand operand. Expression

Meaning

x += y

x=x+y

x -= y

x=x-y

x *= y

x=x*y

x /= y

x=x/y

Loops in Java

The Flow Controls in java is broken in to 3 modules which are as under: b) c) d)

Loops Selection statements Jump statements

The loops in java are a) b) c)

The for loop The while loop The do-while loop

The for Loop A common requirement in programming is to perform a loop so that a single variable is incremented over a range of values between two limits. This is frequently provided for by a loop that uses the keyword for. The primary purpose of the for loop is to execute a block of statements a given number of time. The for loop syntax is for (initialization ; loop condition ; increment expression) { body of the loop; } The control for the for loop appears in parentheses followed by the keyword for. It has three parts separated by semi-colons. 1. The first part, initialization is executed before the execution of the loop starts. This is typically used to initialize a counter for the number of loop iterations, for example i = 0. With a loop controlled by a counter, you can count up or doing using a integer or a floating point variable. It is only used to set up a starting conditions. 2. The second part is the loop condition, which means the execution of the loop continues as long as the condition you have specified in this is true. That means the loop conditions should be a boolean conditions which will either return a true or false. This loop conditions is checked at the beginning of each loop iteration and when it is false the execution stops and the program continues with the statement after the loop. A simple example of loop conditions is i < 10, which would mean that the loop would execute as long as the variable has a value less than 10 and the moment it increases the value of 10, the loop conditions will retune false the loop stops. 3. The third part the increment expression, is executed immediately after the body of the loop, just before the test is performed again. Commonly this is used to increment the loop counted. This could be i++, which will increment the loop counter by one. Of course you might want to increment the loop counter in steps other than one and in that case you can write i +=2, in which case the loop counter gets increment by 2.

Example for (int i = 0 ; ib) then the value of int c will be the value of a and if int b is higher then the value of int c will be the value of int b as stated in the else part of the body.

Nested ifs A nested if is an if statement that is the target of another if or else. Nested ifs are very common in programming and when you nest a if, the important point to remember is that an else statement always refer to the nearest if statement that is within the same block as the else.

It is very important that you use block of codes, when using the nested ifs or otherwise you will find a result other than what you were expecting. if-else-if ladder The if-else-if ladder syntax looks like this if (condition) { Statement; } else if (condition) { Statement; } else if (condition) { Statement; } else { Statement; }

The if condition in the first if will be considered and like the normal if-else will not go to the else part, but it will check the else if condition and like this it goes down the ladder. After the last else if is encountered and then also the condition is not true then the else statement at the end of the ladder will be executed. Remember, if the last else statement is not there and if all the else if condition returns false then nothing will be executed. switch Statement If you need to make a choice between multiple alternative execution paths and the choice can be based on a non-boolean value, then you should use the switch () construct as we cannot use the if-else loop. The syntax is as under: switch (expression) { case value1: { Statement; } case value2: { Statement; } case value3: {

Statement; } default: { Statement; } IMP: It is very important to note here that the expression must be of type byte, short, int or char and each of the values in the cases (e.g. case value1 ....) must be type compatible with the expression and each case should be a unique (e.g. it should not be a constant or a variable). Duplicate case values are also not allowed. IMP: There is a fundamental difference between the switch in C++ and java wherein we need to mandatorily use the break statement to jump out once the case have been matched, otherwise the control will enter all the cases and then reach the end of the loop. To understand the meaning of the above statement, please have a look at the following code. Code class Test17 { public static void main(String[] args) { for (int i = 0;i default --> protected -->

public

Importing packages All of java classes are stored in packages and one would not find a single class just hanging in open air. Since classes within packages must be fully qualified with their package name or names, it would be tedious to type in the long dot-separated package name for every class you want to us. For this java has a special statement called import statements, which will certain class or the entire packages into visibility? The import statement tells the compiler where to find the particular classes.3

Once imported, a class can be referred to directly, using only its name. The import statement is a convenience to the programmer and is not technically needed to write a complete java program. In a normal java source code, the import statement occurs immediately after the package statement. The general form of a import statement is: import package1.package2.*; This would mean that all the classes in package1.package2 would be imported. But remember it would also take for the basic source java file to compile, as all the classes will have to be imported. If one know a file which is to be specifically imported then it should be written as: import package1.package2.Test; All the standard java classes are included in a basic package called java. The basic language functions are stored in a package inside the java package called java.lang. Normally one will have to import every package or class that you want to use, but since java is useless without much of the functionalities in java.lang, the compiler for all programs implicitly imports it.

protected keyword

A Protected Access Modifier is actually a misnomer and is often confusing. By general understanding of the term is seems to be more restrictive that private, but is not actually so. When we declare a member of a class as protected, and then it is available to all members inside the package and also to classes, which is a subclass in a different package. Remember that the protected modifier can be for variables and method only and we cannot declare the class as protected. Now as already learnt there are the two ways in which any variable in one class be accessed in another class a)

by creating an instance and calling the variable with the instance

b)

by way of inheritance. (the sub class automatically gets all the variables other than the private one’s)

Recap of Access Modifiers a)

private keyword variables and methods are accessible only in the class in which they are declared and not even in the subclasses.

b)

default keyword is accessible in the package in which they are declared either by way of inheritance (in subclass) or (in any other class) by way of creating an instance of the class in which the variable is there.

c)

protected modifier is accessible in the package in which they are declared like the default modifier (by way of inheritance or by creating instance of the class) and also in another package in a class which is a subclass of the class which contains the protected keyword.

Remember protected keywords are accessible in another packages only in the subclasses, by creating an instance of the subclass and not by creating an instance of the class which contains the protected keyword. Also protected keywords cannot be accessible in other classes in another package by creating an instance of the class in which the protected keyword is there. Also the class which contains the protected keyword should be declared as public. d)

The public keyword variables / methods are accessible everywhere by creating of the class which contains the public keyword items

Now let us have two classes which we will store in two different packages and also try out the protected keyword Code package one; public class Test54 { protected int a = 10; } Now to compile this code we should use the -d option so that the compiler will automatically create a directory by the name of the package (i.e. one) and put Test54.class inside that. Assuming Test54.java is there in c:\java directory, we will go to that directory and type the following command javac -d c:\java Test54.java Over here c:\java specifies that the new directory called as one will be created below c:\java directory. Now to check whether the compiler has done the job we can go the c:\java\one directory and type dir to check the contents of the directory. Now we will create another source code file in another package to access this class variable a. Code package two; import one.*; class Test55 extends Test54 { public static void main(String arg[]) { Test55 x = new Test55(); System.out.println(x.a); } } We will compile the above code also with the -d option as explained earlier.

Now we need to run the interpreter and we will have to go a directory one above which contains the .class file that is c:\java and type java two.Test55. Output 10 This will print out the value of the class variable in Test54 since Test55 extends Test54.

interfaces

We have discussed about the concept of inheritance and have understood that java has simple inheritance only. There are many cases when a particular method will be used by a lot of classes and this can be done by defining them in an interface and all the classes which needs that method will be implementing the interface to provide body to the abstract method. An interface is also like a normal class, but it has only public static and final variable (constants) and public and abstract methods. That would mean that it is similar to abstract classes, but since the interface is by abstract and all the methods are abstract (remember abstract classes can also have non-abstract methods) there is no need to write abstract before the interface. Similarly, all the data members declared in an interface are by default constants, there is no need to explicitly insert a final, static or final modifier before them. But we need to prefix the class name with interface instead of class. For example, the general syntax of an interface is: interface Test { met1(); } implements clause A class declares all of the interfaces it is implementing using the implements clause. The implements clause consists of the keyword implements followed by the list of interfaces separated by commas and it must be put after the extends keyword (if any). This would mean that a class can implement more than one interface. An interface gives the illusion of bending the java technology single inheritance rule, while a class can extend only a single class, it can implement as many interfaces as needed, but it is the duty of that class to mandatorily override all the methods otherwise it should be declared as a abstract class. (since the class has a abstract method which is not overridden). Code interface Temp { int a; void met1(); }

Output Temp.java:3: = expected int a; ^ 1 error This is because final variable need to be initialized when they are declared. Not to properly run the code have the int a initialized to a value of 10. Code class Test56 implements Temp { public static void main(String[] args) { Test56 x = new Test56(); x.met1(); } public void met1() { a = 20; System.out.println("Inside met1"); } } Output Test56.java:10: cannot assign a value to final variable a a = 20; ^ 1 error The above error proves that all the values in the interfaces are final. Now to properly run the code, remove the line a = 10 and insert a System.out.println (Temp.a) line. The output would be Inside met1 10 This would prove that the variable in the method are static also. Now incase we do not override the method in the interface let us see what happens (for this comment the overriding part) and the output would be Test56.java:1: Test56 should be declared abstract; it does not define met1 () in Test56 class Test56 implements Temp ^ 1 error Interfaces are useful for: a) Declaring methods that one or more classes are expected to implement.

b) Determining an object’s programming interface without revealing the actual body of the class. c) Capturing the similarities between unrelated classes without forcing a class relationship. Variables in Interfaces One can also use interfaces to import shared constants into multiple classes by simply declaring an interface that contains variables, which are initialized to the desired values. When you then implement the interface all those variable names will be in scope as constants.

Interfaces can be extended One interface can inherit another with the help of the usual extends keyword. When a class implements an interface that inherits another interface, it must provide implementation for all methods defined within the interface inheritance chain.

Partial Implementation It is very much possible that a class will implement an interface, but does not want to override all the abstract method, but will override some abstract methods and leave the further implementation to its own subclasses. In this case we should declare the class as abstract, because there is some abstract method in the class. Code interface Two extends One { void met2(); } interface One { void met1(); }

abstract class PartialImplementation implements Two { public void met2() { System.out.println("This is inside met2()"); } } class FullImplementation extends PartialImplementation { public static void main(String[] args) { System.out.println("Hello World!"); } public void met1() {

System.out.println("This is inside met1"); } } Output class FullImplementation extends PartialImplementation { public static void main(String[] args) { FullImplementation x = new FullImplementation(); x.met1(); x.met2(); } public void met1() { System.out.println("This is inside met1"); } } In the above classes, the PartialImplementation class should be declared as abstract, since it is implementing Interface Two, but does not override all the methods of the interface, that is specifically it does not override met1(). Although met1() is not specifically in Interface Two, it is there in Interface One which Interface Two is extending.

Garbage Collection

In the earlier programming languages, it was the duty of the programmer to allocate the memory and also to de-allocate the memory. One of the most frequent reasons for the programs crashes was the lack of the memory, since memory was not released by the objects once their work was finished. In java we do not have that problem at all, since we have a Garbage Collector which always runs in the background when the interpreter is called and automatically re-claims the memory. The only problem is that we cannot force the garage collector nor can we predict at a particular point of time, a object will be definitely garbage collected, since Garbage Collector is a low priority thread. The points to be considered in this sub-module can be summarized as under:1. A System Level Thread, which is automatically created by the JVM. 2. Low Priority Thread 3. One cannot predict when the garbage collection of any particular object will be done. 4. One cannot force garbage collection even by using the System.gc() method which will only request the Garbage Collector to run. 5. By using the finalize() method, there is no guarantee that the object will be immediately collected.

6. Also we can be sure that when a object is garbage collected, it will definitely call the finalize () method before the object is garbage collected.

finalize method

We have already learnt about the concept of Garbage Collection, which is done by a system level thread, which will collect an object, which is of no use. But sometimes an object will need to perform some action when it is destroyed. In many cases a particular java object may be holding some non-java resource such as a window character font etc and we must make it sure that these resources are freed before an object is destroyed. To handle such cases, java has a mechanism called finalization. By using finalization, one can define specific actions that will occur, before the garbage collector reclaims the object. To add a finalize to a class, one needs to just define the finalize method. The Java environment calls that method whenever it is about recycle an object of that class. Inside the finalize () method you specify those actions which must be performed before the object is destroyed. The general form of a finalize () is: protected void finalize() { finalization code; } Here the keyword protected is a specifier that prevents access to finalize () by code defined outside its class. It is important to note here that the method is not called when an object goes out-of-scope. The finalize () method is a member of the Object class. Since all classes inherit from the Object class, your classes also contain the default finalize () method. This gives you an opportunity to execute your special cleanup code on each object before the memory is reclaimed.

native Keyword

The native keyword is used to declare native code method. Once declared, these methods can be called from inside your java programs just as you do any other java method. After you declare a native method, you must write the native method and follow a rather complex series of steps to link it with your code. The mechanism used to integrate C code with java programs is called JNI. This methodology was created in 1.1 and then expanded and enhanced in 1.2 The precise steps that you need to follow will vary between different java environments and versions. This also depends on the language that you are using to implement the native method. Native methods seem to offer great promise, because they enable you to gain access to your exiting base of library routines, and they offer the possibility of faster runtime execution. The problems with native methods are:-

a)

Potential security risk: Because a native method executes actual machine code, it can gain access to any part of the hose system. That is native code is not confined to the JVM and this could allow a virus infection. Applets cannot use native methods.

b)

Loss of portability: Because the native code is contained in a DLL, it must be present on the machine that is executing the java program. Further because each native method is CPU and OS dependent, each DLL is inherently non portable. Thus a java application that uses native methods will be able to run only on a machine for which a compatible DLL has been installed.

Thus the use of native methods should be restricted, because they render you java programs non portable and pose significant security risks.

Methods returning Objects

As we know the return type of java method should be some primitive data type or should be specifically declared as void. However methods can also returns object, but care should be taken that there is mandatorily a return statement at the end of the method and the object specified and object returns should be the same. The following example returns a String object, which we capture and print in our program. class ObjectReturn { public static void main(String[] args) { ObjectReturn x = new ObjectReturn(); String s = x.met1(); System.out.println(s); } String met1() { return "Hello"; } } The output would be Hello.

String class

A String is a series of characters treated as a single unit. A string may include letters, digits and other various special characters like +,-,@, # etc.

A white space has no meaning in a java source code, but if included in a String, it is also taken as a character. String is the only object in Java which can be created with out the new keyword and incase it is done so, it is treated as a primitive data type, however when we create String with the new keyword, then it becomes a proper object. Hence the different ways of creating a String are: String s = “Hello”, in which case it is taken as a primitive and stored in the stack, String s1 = new String (“Hello”);, in which case it is taken as a Object properly initialized with the new keyword and stored in the Heap. The 4 Important Constructors of the String class are:a)

String (String s) – creates an object of the character item passed in the parameters.

b)

String () – creates an instance of String with no characters in it.

c)

String (char c[]) – creates an object of the char array passed into it

d)

String (char c[], int startindex, int numberofchars) – This creates an object of the c array starting from the position in the 2nd parameter till the number of characters as specified in the 3rd parameter.

Code class String1 { public static void main(String[] args) { String s = new String(); String s1 = new String("Hello friends"); char c [] = {'h','e','l','l','o'}; String s2 = new String (c); String s3 = new String(c,0,4); System.out.println(s); System.out.println(s1); System.out.println(s2); System.out.println(s3); } } Output (This is actually a space) Hello friends hello hell The String objects are immutable - their character contents cannot be changed after they are created. A String reference cannot be used to modify a String object to delete or modify a String object from the memory as in other programming languages such as C or C++.

The Important Methods are: 1. int length () – This returns the number of characters that it contains. 2. char charAt (int index) – To extract a single character at the specified index. 3. boolean equals () – actual contents of the String, which included the case sensitiveness also. Code class String2 { public static void main(String[] args) { String s = new String("Hello"); String s1 = new String("Hello"); int a = s.length(); char c = s.charAt(1); boolean b = s.equals(s1); System.out.println("The number of characters in s is = "+a); System.out.println("The character at position 1 in s is = "+c); System.out.println("The contents of S and S1 are equal = "+b); } } Output The number of characters in s is = 5 The character at position 1 in s is = e The contents of S and S1 are equal = true 4. boolean equalsIgnoreCase () – checks without the case sensitiveness. 5. boolean startsWith (String s) – Determines if the String starts with the String specified in the parameter. 6. overloaded version. boolean startsWith (String s, int index) – This allows you to specify a starting point. Code class String3 { public static void main(String[] args) { String s = new String("hello"); String s1 = new String("HELLO"); boolean a = s.equals(s1);

boolean b = s.equalsIgnoreCase(s1); boolean c = s1.startsWith("H"); boolean d = s.startsWith("ll",2); System.out.println("Whether s and s1 contents are similar = "+a); System.out.println("Whether s and s1 contents are similar ignoring case = "+b); System.out.println("Whether s starts with h = "+c); System.out.println("Whether s starts with ll from position 2 = "+d); } } Output Whether s and s1 contents are similar = false Whether s and s1 contents are similar ignoring case = true Whether s starts with h = true Whether s starts with ll from position 2 = true

7. int indexOf (int c or String s) – checks for the first occurrence of the character or the string. 8. int lastIndexOf(int c or String s) – 9. overloaded version – int indexOf (int c, int position) – This enables u to start searching from the specified position. 10. String substring(int startindex) – copies all the characters till the end from the start position in this string to another string. 11. String substring (int start, int end (exclusive)) – copies the characters form the start till the end into another string. Code class String5 { public static void main(String[] args) { String s = new String ("Hello lilly"); int a = s.indexOf('l'); System.out.println("The first occurence of l in String s is = "+a); int b = s.lastIndexOf('l'); System.out.println("The last occurence of l in String s is = "+b); int c = s.indexOf('l',4); System.out.println("The first occurence of l in String s from position 4 is = "+c); String s1 = s.substring(5); System.out.println("The substring of String s from position 5 is = "+s1); String s2 = s.substring(5,9);

System.out.println("The substring of String s from position 5 till 9 is = "+s2); } } Output The first occurence of l in String s is = 2 The last occurence of l in String s is = 9 The first occurence of l in String s from position 4 is = 6 The substring of String s from position 5 is = lilly The substring of String s from position 5 till 9 is = lil 12. String replace (char original, char replacement) – replaces the original character with the replacement character in the whole string and returns a new String. 13. String trim () – removes the white space in the beginning and in the end. 14. String toUpperCase () – converts all the characters to Upper Case 15. String toLowerCase() – 16. static String valueOf (any datatype) – returns the String object of any primitive data type. Code class String6 { public static void main(String[] args) { String s = new String ("Hello"); String s1 = s.replace('l','m'); System.out.println("The new String s1 is = "+s1); String s2 = s1.toUpperCase(); System.out.println("The new String s2 is = "+s2); s2 = s1.toLowerCase(); System.out.println("The String s2 is now = "+s2); String s3 = String.valueOf(10); System.out.println("The new String s3 is = "+s3); } } Output The new String s1 is = Hemmo The new String s2 is = HEMMO The String s2 is now = hemmo The new String s3 is = 10 17. char [] toCharArray() – To convert all the characters in a String to a character array.

18. boolean regionMatches (int startindex, String 2, int String2start index, int no of characters) – This compares a specific region in a string with another specific region in another String Code class String7 { public static void main(String[] args) { String s = new String("Gurukul"); char c[] = s.toCharArray(); for (int a = 0;a
View more...

Comments

Copyright ©2017 KUPDF Inc.
SUPPORT KUPDF