+ All Categories
Home > Documents > Java Notes1

Java Notes1

Date post: 30-May-2018
Category:
Upload: gomsagar
View: 231 times
Download: 0 times
Share this document with a friend

of 150

Transcript
  • 8/14/2019 Java Notes1

    1/150

    History of Java and Tour of JDK

    Java is an object-oriented programming language developed by Sun Microsystems, and modeled

    on C++, the Java language was designed to be small, simple, and portable across platforms andoperating 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 WorldWide Web (WWW), although it was WWW which propelled into java what it is as a languagetoday 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 Internetversion of C++, but it would be a big mistake since Java has practical and philosophicaldifference with C++.

    The history of java goes back to 1991, when a group of Sun Engineers led by Mr. PatrickNaughton and James Gosling wanted to design a small computer language that was to be usedfor consumer and electronic devices like Remote Controls, TV Switchboxes etc. Now since thesedevices were manufactured by different manufacturers who may choose different CPUs (CentralProcessing Units), the program should not be tied down to any single architecture. The projectwas code named Green.

    The languages was then called as Oak and since Oak was already an existing computerlanguages, it was code named as JAVA. But unfortunately, Sun did not get the project for whichthey were bidding and it was in 1994 with the advent of the WWW and browsers, java waspropelled back in to the main stream.

    The JAVA as a language was reveled to the world in the Sun world 1995 conference and fromthere onwards different versions have come out with all the latest technologies beingincorporated. 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 electronicdevices like remote controls, micro-wave ovens etc. The emphasis was on platformindependence.

    Platform independence-that is, the ability of a program to move easily from one computer systemto another-is one of the most significant advantages that Java has over other programminglanguages, particularly if your software needs to run on many different platforms. If you're writingsoftware for the World Wide Web, being able to run the same program on many different systemsis crucial to that program's success.

    It was with the increasing popularity of the Internet, java became as a language for the internetwhich lays emphasis on the client-server programming.

    Java achieves this platform independence by breaking up the process of compilation andinterpretation in to two individual steps. We have two separate executable files for this purposecalled the Compiler and the Interpreter.

    In the earlier programming languages, any code written was compiled and immediatelyinterpreted to the underlying operating system machine standard and hence if the same programwas taken to another machine having a different operating system, it would not work.

  • 8/14/2019 Java Notes1

    2/150

  • 8/14/2019 Java Notes1

    3/150

    Tools of JDK

    After having successfully installed the JDK, we will quickly go through the various tools which willbe 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 orwe 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 andthe same is

    set path= c:\jdk1.3\bin where jdk1.3 is the directory name (default directory in which u have yourjdk installed)

    Once we have executed the batch file, to ensure that our jdk is properly installed, we just need to

    just type javac on the dos prompt and it would give us a list of options. (Incase our jdk is notproperly 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 thesource code file. We can see what the various options of javac are by just calling javac on the dosprompt. To compile a particular source we will have to say javac Test.java wherein Test.java isthe 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. (JavaApplets 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 partof the SL 275 objectives).

    Javas popularity is because of the following 3 important points:-

    a) Appletsb) Securityc) Portability

  • 8/14/2019 Java Notes1

    4/150

    Java Applets are simple java class files embedded in an html file which is dynamicallydownloaded across the network by the web server when an appropriate APPLET Tag isencountered.

    Java Applets are dynamic in the sense that they can respond to events and user inputs and notjust simple animations or sounds.

    Java programs are secure because they run within the JVM (Java Virtual Machine) which will betalked in depth later on. Java achieves the security by confining a java program to the javaexecution 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 andaccomplishments 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 sayabout each buzzword.

    1 Simple

    We wanted to build a system that could be programmed easily without a lot of esoteric trainingand which leveraged todays standard practice. So even though we found that C++ wasunsuitable, we designed java as close to C++ as possible in order to make the system morecomprehensible. Java omits many rarely used, poorly understood, confusion features of C++ thatin 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, pointerarithmetic, structures etc. There has been a lot of improvement of the C++ language, keeping intouch 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) Softwareslike 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 objectoriented carpenter would be mostly concerned with the chair he was building and secondarily withthe tools used to make it, a non object oriented carpenter would think primarily of his tools. Theobject 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 otherfeatures of java. Java language is based on the purists everything is an object paradigm which

    is simple and easy to extend. The advantages of OOPs are explained in the later sections. Themajor difference between Java and C++ lies in multiple inheritance for which java has found abetter solution. The reflection mechanism and object serialization features make it much easier toimplement 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 aswhen accessing a local file System.

  • 8/14/2019 Java Notes1

    5/150

    The networking capabilities of Java are fantastic and there is a separate package called java.nethaving classes related to both Socket Oriented and Packet Oriented data communication. Javaalso improves on the CGI scripting and uses an elegant mechanism called Servlets and JSPwhich makes server side programming in java extremely efficient.

    Java was originally designed for the distributed environment of the internet by properly handlingthe TCI / IP protocols. In many of the earlier languages the distributed environment was an afterthought but not Java. Java has a complete package called java.net which contains classes whichtake care of the distributed environment like URL, Datagram Packet, Datagram Socket, andURLConnection etc.

    4 Robust

    Java is intended for writing programs that must be reliable in a variety of ways. Java puts a lot ofemphasis on early checking for possible problems, later dynamic (run-time) checking andeliminating 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 andcorrupting data.

    Java program is robust by which it will successfully execute reliably in a variety of systems. Itwas possible to achieve this because of the following features / tools of Java

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

    b) Good Memory Management: Memory Management is a tedious and difficulttask in the traditional programming environments and it was the duty of theprogrammer to allocated and de-allocated memory from the programs. In

    java the de-allocation of memory is completely automatic because there is aGarbage 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 failurein the earlier programming languages was the mishandling of exceptionalconditions (specifically the run-time errors). Java provides for a proper objectoriented way of exceptional handling by which all errors (including run-timeerrors) can and should be managed by the program.

    5 Secure

    Java is intended to be used in networked / distributed environments. Towards that end a lot ofemphasis has been placed on security. Java enables the construction of virus - free, tamper freesystems.

    Java achieves this security with the concept of Java Virtual Machine (JVM) which has beenexplained in depth in the later sections.

    6 Architecture - Neutral

    The compiler generates an architecture neutral object file format - the compiled code isexecutable on many processors, given the presence of the Java run-time system. The javacompiler does this by generating byte code instructions which have nothing to do with particular

  • 8/14/2019 Java Notes1

    6/150

    computer architecture. Rather they are designed to be both easy to interpret on any machine andeasily 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 machineto be executed on any other machine. This is possible due to the concept of Byte Codesexplained 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. Thesizes 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 thesimilar way in other platforms also. This is because the data types in Java are having a fixed sizeand having a fixed size of number types eliminates a major porting headache. The Strings aresaved 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 interpreterhas been ported. Since linking is a more incremental and light weight process, the developmentprocess can be much more rapid and exploratory.

    As said earlier Java enables the creation of cross platform programs by compiling into anintermediate representation called Java Bytecode. There is a great advantage while we aredeveloping an application with java being an interpreted language.

    9 High Performance

    While the performance of interpreted bytecodes is usually more than adequate, there aresituations 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 javaalthough interpreted, was carefully designed so that it would be easy to translate directly intonative machine code for very high performance by using a Just-In-Time Compiler. The javaruntime systems that provide this feature lose none of the benefits of the platform independentcode.

    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 themulti-threading remains the same across machines, but the implementation of multithreading isoff-loaded to the underlying operating systems.

    Java supports multi-threaded programming, which allows a programmer to write programs thatdo many things simultaneously. Java comes with a elegant yet sophisticated but simple and easysolutions for multi-process synchronization that enables a programmer to construct smoothlyrunning interactive systems.

  • 8/14/2019 Java Notes1

    7/150

    11 Dynamic

    In a number of ways, Java is more dynamic languages that C or C++. It was designed to adaptto an evolving environment. Libraries can freely add new methods and instance variables withoutany 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 toverify and resolve accesses to objects at run time. This makes it possible to dynamically linkcode in a safe and expedient manner.

    Concept of JVM

    The JVM stands for the Java Virtual Machine, an imaginary machine within which all the javaprograms are executed.

    The three parts of the JVM are

    a) Class Loaderb) Byte-Code Verifierc) Interpreter

    The duty of the Class Loader is to load all the classes necessary for the successful compilation ofthe code. Infact the package java.lang is automatically loaded without the need for importing thesame (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 theByte Code Verifier is called, whose duty is to check whether any changes have been made to thebyte codes after the same have been generated (whether the .class file have been tampered withor not). Incase there is infact a change, it generated an exception or else allows the Interpreter togo 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 codemodule.

    Setting the Path

    By default the codes can be stored anywhere and when you type javac in the dos-prompt, itwould not know whether to look for the javac executable file and hence we need to type asunder:-

    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 typethe above set path on the dos-prompt or even put it in the autoexec.bat file, so that we do nothave to type it every time.

  • 8/14/2019 Java Notes1

    8/150

    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 WorldWide Web and have a lot of features of C++, as it is also an Object Oriented Programminglanguage, 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 exceptionhandling 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 andwith this the performance issues simply goes away. Java is great for network related programsbecause 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 programsthat 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 itwould not be possible for applets to be in touch with the local file system, which the basicrequirement 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 whichis required for running Java Programs. The development environment for Java is very rich andcontains 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 betaversion 1.4 due to release very shortly. We have already seen earlier what programs areavailable 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)

  • 8/14/2019 Java Notes1

    9/150

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

    J2SE is for developing normal applications and applets, but not for the server side programs forwhich we required J2EE Software.

    The program which we work for executing our code is J2SE which we have seen earlier in themodule. The structure of the J2SE API is also discussed earlier. The J2SE JDK can bedownloaded 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 programslike Servlets, Java Server Pages and Enterprise Java Beans. The J2EE is a set of specificationsbased 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 managingn-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 thedesign, development, assembly, and deployment of enterprise applications. The J2EE platformoffers a multi-tiered distributed application model, the ability to reuse components, integratedExtensible Markup Language (XML)-based data interchange, a unified security model, andflexible transaction control.

    Not only can you deliver innovative customer solutions to market faster than ever, but yourplatform-independent J2EE component-based solutions are not tied to the products andapplication programming interfaces (APIs) of any one vendor. Vendors and customers enjoy the

  • 8/14/2019 Java Notes1

    10/150

    freedom to choose the products and components that best meet their business and technologicalrequirements.

    J2ME

    Java 2 Micro Edition is specifically used for writing embedded programs which can be executedon Mobile Phones, PDAs (Personal Digital Assistant) and Palm Tops.

    Java 2 Platform, Micro Edition (J2ME) encompasses VMs and core APIs specified viaConfigurations as well as vertical or market-specific APIs specified in Profiles

    J2ME specifically addresses the vast consumer space, which covers the range of extremely tinycommodities such as smart cards or a pager all the way up to the set-top box, an appliancealmost as powerful as a computer. Like the other editions, J2ME maintains the qualities that Javatechnology 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 andJ2EE

    With the delivery of J2ME, Sun provides a complete, end-to-end solution for creating state-of-the-art networked products and applications for the consumer and embedded market. J2ME enablesdevice manufacturers, service providers, and content creators to gain a competitive advantageand capitalize on new revenue streams by rapidly and cost-effectively developing and deployingcompelling 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 whetherit 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-sideperformance and now a version for client-side performance.

    These two solutions share the Java HotSpot runtime environment, but have different compilerssuited to the distinctly different performance characteristics of clients and servers.

    The Java HotSpot virtual machine (VM) is a key component in maximizing deployment ofenterprise 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, andmanagement 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 theNetBeans Open Source Project

  • 8/14/2019 Java Notes1

    11/150

    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 JVMstypically does not include the latest java features. The java Plugin solves this problem for us. Byusing a plugin It directs a browser to use a specific JRE rather than the browsers JVM. The JREis a subset of JDK. It does not include the tools and classes that are used in a developmentenvironment.

    Java API

    API stands for Application Programming Interface and Java API is a set of pre-defined classeswhich we will be using in our applications and applets. The Java API is not a part of the softwaredownload 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 themachine 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. Thebuilders had in mind the power of what is now called as applets so they made the HotJavabrowser capable of interpreting the intermediate bytecodes. Nowadays most of the browsershave 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 anarchive, 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 appletand its requisite components (.class files, images and sounds) into a single file. Using the newARCHIVE attribute of the tag, this JAR file can be downloaded to a browser in asingle HTTP transaction, greatly improving the download speed. In addition, JAR supportscompression, 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 combineall the java bean codes and then load the jar file in the bean box. This will be explained in Unit 2when we do Java Beans.

    AWT

    This stands for Abstract Window Toolkit which is the GUI part of Java. All the class files related tothe GUI part like Buttons, Checkboxes, Menus are all a part of the awt package present in thecore java API.

    We will be doing AWT in Section II of this module later on and all the class files will be explainedat that time.

  • 8/14/2019 Java Notes1

    12/150

    Swing

    Swing is a part of the Java Foundation Class and it is used for creating 100% pure javacomponents. The AWT class components rely more on the underlying operating system for theirlook and feel and hence a component created in Windows will look slightly different from thesame component created in Mac machine.

    However Swing components are pure and full java components and a swing Button created inwindows will look exactly the same created in Mac. All the swing components are present in theswing package in the core API.

    Applets

    Applets are java class files which are embedded in an html file which is loaded and executed by aweb browser. The important classes and interfaces for Applets are present in the applet packageof the core java API. Applets are executed within the JVM present in the Web Browser andcannot 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 inresponse to a client request in much the same way as CGI programs do. Servlets can be thoughtof as applets that run on the server side without a user interface. Servlets are invoked throughURL invocation.

    The main advantage of Servlet is that once started all the future requests are serviced by theservice () method of the Generic Servlet or the doGet() and doPost() method of the HttpServletclass. Servlets are a part of the J2EE specifications and we can have session tracking, HttpTunneling 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 aset of JSP tags (understood by the server) that extend the ability of the web page designer toincorporate dynamic content in a page. These tags provide functionality such as displayingproperty 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 becompiled. The web page designer simply writes a page that uses HTML and JSP tags, and puts iton their web server. The web page designer does not need to learn how to define Java classes oruse 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 andcompiled by a Java programmer who then publishes the interface to the bean or the Servlet. Theweb page designer can access a pre-compiled bean or servlet from a JSP page without having todo any compiling themselves.

  • 8/14/2019 Java Notes1

    13/150

    Java Beans

    JavaBeans brings component technology to the Java platform. With the JavaBeans API you cancreate reusable, platform-independent components. Using JavaBeans-compliant applicationbuilder tools, you can combine these components into applets, applications, or composite

    components. JavaBean components are known as Beans. The JavaBeans architecture definesJava's reusable software component model.

    Java Beans is a software Component. A bean is a reusable, platform neutral component, whichcan 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 independentdegrees are:

    a) The methods that can be invoked on a beanb) The readable and / or writeable properties that the bean exposec) 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 transactionaldistributed object applications based server side software components. Applications writtenusing EJB is scalable, transactional and multi user secure. These applications may be writtenonce 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 tothe EJB specs. The various parties in the EJB are:

    - The Bean: These are reusable business components that companies can purchase and useto help solve business problems. Beans are not complete applications, but rather aredeployable components that can be assembled into a complete solution.

    - The Container: This supplies the low-level runtime execution environment needed to runEJB applications.

    - The Service Provider: This is the application server logic to contain, manage and deploycomponents. BEA, SilverStream, WebSphere, iPlanet etc.

    - The Application Assembler: This is the overall application architect, for a specificdeployment. The mail goal is to combine various components and write the applications thatuse 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-Javaapplications, in which the methods of remote Java objects can be invoked from other Java virtualmachines, possibly on different hosts.

  • 8/14/2019 Java Notes1

    14/150

    A Java program can make a call on a remote object once it obtains a reference to the remoteobject, by receiving the reference as an argument or a return value. A client can call a remoteobject in a server, and that server can also be a client of other remote objects. RMI uses objectserialization to marshal and unmarshal parameters and does not truncate types, therebysupporting true object-oriented polymorphism

    JDBC

    JDBC is a standard SQL database access interface that provides uniform access to a wide rangeof relational databases. It also provides a common base on which higher level tools andinterfaces can be built. This comes with an ODBC Bridge. All the classes related to databaseconnectivity are in the java.sql package.

    JDBC does the following things:

    a) establish connection with a databaseb) send SQL statementsc) processes the results

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

    1) Import the necessary classes.2) Load the JDBC Driver3) Identify the Data Source4) Allocate a Connection Object5) Allocate a Statement Object6) Execute a Query using the Statement Object7) Retrieve Data from the returned Result Set Object8) Close the RS9) Close the Statement10) Close the Connection

    JNI

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

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

    The Java 2 SDK still supports the old native method interface (NMI), which was originallyimplemented in Java Development Kit (JDKTM) 1.0. The old NMI is not part of the Java platformstandard, 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 withapplications and libraries written in other languages, such as C, C++, and assembly. In addition,the Invocation APIallows 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, andimaging capabilities for Java programs through extensions to the Abstract Windowing Toolkit

  • 8/14/2019 Java Notes1

    15/150

    (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 andimage editors.

    The Java 2D is used to display and print 2D graphics in the java programs. Java 2D API enablesus to display complex charts and graphs that use various lines and fill styles to distinguish sets ofdata and also enables you to store and to manipulate image data--for example, you can easilyperform image-filter operations, such as blur and sharpen

    Java 3D

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

    The Java 3DTM application programming interface (API) provides a set of object-orientedinterfaces 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 anddirectory services in the enterprise.

    As part of the Java Enterprise API set, JNDI enables seamless connectivity to heterogeneousenterprise naming and directory services. Developers can now build powerful and portabledirectory-enabled applications using this industry standard. The Java Naming and DirectoryInterface (JNDI) 1.2 is a major new upgrade release that adds new functionality to the basicnaming and directory support offered in the 1.1.x releases. New features include event

    notification, and LDAPv3 extensions and controls. This release contains valuable contributionsfrom 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 differentplatforms across a network. Java IDL is similar to RMI (Remote Method Invocation), whichsupports distributed objects written entirely in the Java programming language. However, JavaIDL enables objects to interact regardless of whether they're written in the Java programminglanguage or another language such as C, C++, COBOL, or others.

    This is possible because Java IDL is based on the Common Object Request BrokerageArchitecture (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 hasits own IDL mapping--and as its name implies, Java IDL supports the mapping for Java. CORBAand the IDL mappings are the work of an industry consortium known as the OMG, or ObjectManagement Group. Sun is a founding member of the OMG, and the Java IDL team has playedan active role in defining the IDL-to-Java mapping.

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

  • 8/14/2019 Java Notes1

    16/150

    Java Collections

    This is the new API introduced in Jdk 1.2. A collection (sometimes called a container) is simply anobject that groups multiple elements into a single unit. Collections are used to store, retrieve andmanipulate data, and to transmit data from one method to another. Collections typically representdata items that form a natural group, like a poker hand (a collection of cards), a mail folder (acollection 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 tablesfor our use. Collections offer a new way to solve several common programming problems. Thecore 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 otherentity. They allow verification of the claim that a given public key does in fact belong to a givenindividual. Certificates help prevent someone from using a phony key to impersonate someoneelse.

    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 thecertificate, a serial number, and perhaps other information. Most importantly, it contains the digitalsignature of the certificate issuer. The most widely accepted format for certificates is defined bythe ITU-T X.509 international standard and thus, certificates can be read or written by anyapplication 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 publishedin 1988, version 2 was published in 1993, and version 3 was proposed in 1994 and consideredfor approval in 1995.

    JPDA

    The Java Platform Debugger Architecture (JPDA) consists of three interfaces designed for use bydebuggers in development environments for desktop systems.

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

    b) The Java Debug Wire Protocol defines the format of information and requeststransferred between the process being debugged and the debugger front end, whichimplements 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 digitalsignature algorithm and is employed by most browsers, including Netscape Navigator andInternet Explorer

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

  • 8/14/2019 Java Notes1

    17/150

    In order for Plug-in to be able to verify RSA signatures in a browser-independent way, JDK 1.2.2has bundled a Cryptographic Service Provider (CSP) with Plug-in. This CSP is capable ofverifying 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 additionsin 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. Afterthe 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 appletsand 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 islocated 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 ajava object at runtime

    7) Various security features, such as digital signatures, message digests, access controllists 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 bythe 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

  • 8/14/2019 Java Notes1

    18/150

    3) More flexible security mechanism is now available for java program. Policy files candefine 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 beestablished to a specific host and port.

    4) Digital certificates provide a mechanism to establish the identify of a user. You can thinkof 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 sightimpairments 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 thekeyword. 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 DefinitionLanguage).

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

    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 unions2) 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 classes4) No concept multiple inheritance5) No concept of destructors as the feature of Garbage Collector is there.6) No goto keyword

  • 8/14/2019 Java Notes1

    19/150

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

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

    1) Multi-Threading2) Java Package3) 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 Java5) The break and continue jump statements can take labels also6) A new >>> right shift operator7) A new documentation comment which will be used by the javadoc utility8) 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 andis very popular with the concept of Objects. The advantage of OOP is that everything is taken asan 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 componentscalled as objects. Each object has a specific role in the program and all objects can talk to eachother in a well defined way

    The advantage of OOP is that internally each of the components might be extremely complicatedand but we need not know the details of each component. We just need to know the overallsystem 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 beconceptually organized around its code or around its data. The process - oriented modelcharacterizes a program as a series of liner steps (that is code) and can be thought of as codeacting 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 accessto code.

    Any object will have two sections within itself that is data and methods. The data is the variableswhich 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 thedata and the behavior is the methods within the object.

    The four fundamental principals of OOPs are:

    a) Polymorphismb) Data Encapsulationc) Inheritanced) Data Abstraction

  • 8/14/2019 Java Notes1

    20/150

    Polymorphism is taken from the Greek work poly which means many and morphus whichmeans forms and hence polymorphism would mean many forms.

    The simplest example of polymorphism would be the + operator. When we say 10 + 10 it knowsthat it has integers on both the sides and it has to perform arithmetic calculation and would givethe answer as 20, but incase we say Hello + There it would know that both the side are stringsand 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 inthis module.

    Encapsulation is the mechanism that binds together code and the data it manipulates, andkeeps both safe from outside interference and misuse. This is done in java by ensuring that thedata in an object can only be accessed by the methods of that object only and incase any otherobject need to access the data of an object, it cannot do it directly but only through the methodsof that object.

    This feature is like a protective capsule to the data ensuring that only the methods of an objectaccess the data of that object.

    Inheritance is the process by which one object acquires the properties of another object. Theobject from which a class inherits is called the super class or the parent class and the class whichinherits is called the sub class or child class.

    Take the example of Animal class which will have two sub classes called Mammal class andReptile class and this continues. The Inheritance interacts with Encapsulation as well. Forexample, the Animal class encapsulates some properties / features and all the subclasses willhave 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, whenwe start the computer, we are not bothered with the complexities of how the computer boots, butonce 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 wheelcommunicates with the wheels or how the car starts up etc. Similarly when we give a program toa client, we just tell the client to click on the executable file and how the client is abstracted awayfrom the minute details of how the programs functions.

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

    Dissecting the First Code

    Now lets 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 inCapital 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)

  • 8/14/2019 Java Notes1

    21/150

    Code

    public class Test{public static void main (String args []){

    System.out.println (Hello, Welcome to Learning Java with Prof Venkat Krishnan);}

    }

    Points to be noted:

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

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

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

    statement is a syntax error. A syntax error is caused when the compiler cannot

    recognize the statement. The compiler normally issues an error message to help theprogrammer to locate and fix the incorrect statements. Syntax errors are violation ofthe language rules.

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

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

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

    9 There can be only one main () in any source code file.10 There can only be one public class in a source code file.

    11 The syntax of the main () is fixed and is public static void main (String args[])12 Also note the braces. There will be one set of braces for each and every class and

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

    but is java coding standard.

    Now lets see what each of the words in the file is meant:

    1 public This keyword indicates that the class and method is globally accessible. Theother access modifiers are default (nothing given), private and protected, which wewill 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 everymethod to have a return type and incase there is no return type, the method shouldbe pre-fixed with void keyword.

    4 (String args []) Every method has a (), thorough which we can pass any parameterrequired for the method and in this main () we pass the String array having the nameargs. The array is defined by []. The name of the array can be anything, but it is aconvention to type it as args.

  • 8/14/2019 Java Notes1

    22/150

    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 iscontained in a package java.lang so it is always accessible just by using the simpleclass name, System.

    6 out The object out represents the standard output stream your display screen andis a data member of the class System. The member out is a special kind of memberof the System class. Like the main () in our program, it is also static. This means thatout exists even though there is no object of type System. The out member isreferenced by using the class name, System, separated from the member name outby a full stop.

    7 println () This is the println () method that belongs to the object out and that outputsanything that is within the parameters of the method. Over here we are printing outthe 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 thedos-prompt and writing javac Test.java.

    Once the class is properly compiled we will find a .class file with the same name as the sourcecode 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 inthe code two classes String and System. To see what classes are loaded we will compile bywriting 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 iscompiled and finally the .class file is generated and the total amount taken is also mentioned forour 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 samecharacter. We have not done anything but only edit the class file to see whether the Byte CodeVerifier checks it properly or not.

    We will now execute the .class file (without re-compiling the same) (by typing java Test) andbingo it refuses to work and will throw an exception. e.g. ClassFormatError. So the Byte CodeVerifier indeed does it job.

    Now we will again recompile the Test.java so that the old class file is overwritten and thenexecute by calling java Test. When we call the interpreter we will not type any extension after theFile name. The Interpreter calls the class file and not the .java file. We can check this by takingthe .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 seelater on).

  • 8/14/2019 Java Notes1

    23/150

    In a normal source code layout, the package would be the first statement or line in the codelayout 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 namesas 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 throughthe 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 spaceinto 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 aparameter name.

    For example, we have given the class name as Test, so here Test is the identifier and args is theidentifier 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 thisjust 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

  • 8/14/2019 Java Notes1

    24/150

    1Test.java:1: expectedpublic class 1Test

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

    ^3 errors

    Keywords and Blocks

    Keywords are words having special meaning to the Java Technology Compiler. They identify adata type name or program construct name

    goto and const are reserved words in java, which means they are not keywords, but are reservedfor 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 openingbraces ( { ) and closing braces ( } ). All methods and classes have blocks which mean that theyare 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 valuesare stored.

    If you define a variable to store integers, for example you cannot use it to store a value that is ofdecimal fraction or a string value

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

  • 8/14/2019 Java Notes1

    25/150

    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 particularabout the data type and if you specify any variable can hold integer, then that variablecannot hold any other data type (i.e. String, Double, Float etc) and compiler check for thesame.

    c) The place of declaration decides the scope of variables, whether the variable is localvariable or class variable or instance variable.

    Therefore Variables are of 3 kinds namely, Local Variable, Class Variables or InstanceVariables.

    Local Variables - They are local to the method and are visible only inside the method in whichthey are declared. Incase we try to access the variables outside the method it would throw anerror. The important thing to note is that method / local variables need to be initialized or thecompiler 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 compileris trying to tell us that it does not understand what a means over here. This is because int a isdefined in met1 () and hence becomes a method variable and we are trying to access the same inthe 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 becausethe 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 beginningor 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.

  • 8/14/2019 Java Notes1

    26/150

    The Important point to be noted here is that there is only one memory location for the classvariables.

    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 instanceis. An instance is a copy of the object which we are creating with the new keyword and eachinstance 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 tocall the method, then first of all we would be required to create an instance of the class and thencall 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 arecreating 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 thereforethey are associated with the object. They take different value for each object.

    Code

    class Test4{

    int a = 10;

  • 8/14/2019 Java Notes1

    27/150

    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 classvariable is given to each of the instances and hence when we change x.a = 20, we are changingthe value of a for the instance x and when we create a new instance it would by default have thecopy of the original class variable. Over here it is important to understand that there are 3separate memory locations, one for the class variable and two memory locations for the twodifferent 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 keywordcan 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, willgive a compilation error incase applied to a method variable), then it would mean that classvariable would be shared by all the instance of the classes. There would only be one memorylocation and no different locations for the instance variables. Hence any change made by oneinstance would change the original class variable also. Lets 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 changingthe original class variables value also to 20, since there is only one memory location for the staticclass 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-staticmethod only with the instance of the class.

    Code

    class Test5{

    public static void main(String[] args){

    Test5.met1();

  • 8/14/2019 Java Notes1

    28/150

    }

    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 isno 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 cannotaccess 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 staticcontext.

    IMP: Over here one needs to understand the difference between directly printing out the classvariable 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 startingpoint of entry into a source code file and no instance of the class is created (instances can becreated 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 notimplementation 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 itemof that data type, and identifies a legal range of values from which a data item of that data typecan be obtained. Again the Primitive data types can be classified into the following 4 majorcategories

    a) Textual Data Typeb) Integral Data Typec) Logical Data Typed) Floating Data Type

  • 8/14/2019 Java Notes1

    29/150

    Textual Data Type: This is represented by char and individual characters and can hold onlysingle 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 nonegative 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 aninteger type with 8 bits wide. Java uses Unicode to represent characters. Unicode defines a fullyinternational 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 itwould use Unicode to represent characters.

    The following table lists the special codes that can represent nonprintable characters, as well ascharacters 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 twob) 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 thatmean you can use both negative and positive values. The four integer types differ in the range ofvalues they can store, so the choice of types for a variable depends on the range of data valuesyou 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 areworking 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 areAUTOMATICALLY PROMOTED to int before the calculation is done. This has a specific reasonand 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 enoughto hold the desired values

  • 8/14/2019 Java Notes1

    30/150

    We should specifically write L (capital alphabet) or l (small alphabet) after the initialized value of along 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 asa long data type, the compiler has taken the default of integral as int. To ensure that the compilertakes it as a long data type, the initialized value should be followed by L and then we would getthe desired result.

    We said earlier that byte and short are automatically promoted to int before any calculation isdone on them. This because their values are very small and the final result would be within thesize of a byte, but in between the calculation what should be done incase it goes beyond therange. 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 therange 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 intoa int during calculations on byte and short and int values cannot be accommodated in a bytevalue (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 wewould be required to cast the result to ensure that it gets stored in a byte data type and this isdone 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 issuesincase the values go beyond the value of 127. To under this let us see the following code

  • 8/14/2019 Java Notes1

    31/150

    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 figurecomes from. Whenever we cast any value into any smaller data type, there would be issue of lossof 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 therange of a byte as the maximum value of a byte would be only 127, it again goes back and startsputting the bytes in the old blocks. Remember the range of a byte is from -128 to 127. So thevalue of 128 is put in -128 and so on and hence the result of -126. It is very important to noteincase the value is very big, it will go on doing the above thing till it reaches -1 and then 0 andthen 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 booleanshould test for true or false. Also note that boolean states are in small caps and not like otherlanguages 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 expressionsthat require fractional precision. There are two kinds of floating point types, float and doublewhich 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 mandatorilyuse f after the values (like long).

    Code

    class Test9{

    public static void main(String[] args)

  • 8/14/2019 Java Notes1

    32/150

    {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 smallalphabet class, but then it is a convention followed in the java world and hence we would like todiffer from the general rules of convention. The second letter incase one is there in the classshould also start with Capital alphabets. For Example IndexArrayOutOfBoundsException.

    The methods should start with lower alphabets and the second word in the method should becapital. 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 shouldstart 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 theclass 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 wewant a group of integers from 1 to 100 to be reference by a common name, we create an array ofthem.

    Each variable in an array is called array element. It is important to note that the array numberingstars from 0 and not 1.

    Array is an object and not a primitive, even if it is made up of primitives. Like objects, arrayrequired initialization and declaration only creates a reference to the array. To explain in depth, tocreate a array is to 3 steps

    a) Declarationb) Creationc) Initialization

    Declaration

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

  • 8/14/2019 Java Notes1

    33/150

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

    Creation

    Once you declare an array of any data type, you should create the same with the help of the newkeyword 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 valuesand 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 nothingis inside it.

    Initialization

    Once we have the memory reserved, we can put values into each of the individual spaces likethis:

    a[0] = 10; This puts 10 as the first value of the arraya[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 alsocorrect.

    int [] a = new int[10];

    Direct Initialization

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

  • 8/14/2019 Java Notes1

    34/150

    int a [] = { 1,25,30,55}

    This creates an array with variable name as a and with values as put into the {} and with 4elements.

    Accessing Array Values

    You can refer to an element of an array by using the array variable followed by the elementsindex 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 1because, as said earlier, the array indexing begins with 1.

    Important: Any attempt to access array indexes beyond the length of the array causes runtimeerror. For example: If we try to access the 5th element, it will give a runtime error, because thereis no 5th element in the array. The exception thrown would be called asArrayIndexOutOfBoundsException.

    We will cover the topic of runtime error and the different types of exceptions thrown in the othermodules.

    Code

    class Test22{

    public static void main(String[] args){

    int a [] = new int[10];System.out.println(a[10]);

    }}

    Output

    java.lang.ArrayIndexOutOfBoundsExceptionat 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 inan array is stored as part of the array object, as the length attribute. This value is used to performbounds 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];

  • 8/14/2019 Java Notes1

    35/150

    )

    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 torefer to an entirely new array. Since an array cannot be resized, this is the biggest limitation ofarrays.

    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 fromwhere 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 ofobjects. The objects themselves do not change.

    Code

    class Test23{

    public static void main(String[] args){

    int a[] = {1,2,3,4,5};

    int b[] = {10,20,30,40,50,60,70,80};

    System.arraycopy(a,2,b,3,2);

    for (int i = 0; i

  • 8/14/2019 Java Notes1

    36/150

    }

    Output

    10 20 30 3 4 60 70 80

    Multi-Dimensional Arrays

    We have only worked with one-dimensional arrays up to now, that is arrays that use a singleindex.

    Why would you ever need the complications of using more indexes to access the elements of anarray?

    Suppose that you have a fanatical interest in the weather and you are intent on recording thetemperature each day at 10 separate geographical locations throughout the year 1999. Once youhave sorted out the logistics of actually collecting this information, you can use an array of 10elements corresponding to the number of locations, where each of these elements is an array of365 elements to store the temperate values. You would declare this array with the statement

    float temperature [] [] = new float [10] [365];

    There are 10 arrays each having 365 elements. In referring to an element, the first squarebrackets enclose the index for a particular array, and second pair of square brackets encloses theindex value for an element within that array.

    So to refer to the temperate for day 100 for the sixth location, you would use temperature [5] [99].

    In java, multidimensional arrays are actually array of arrays. To declare a multidimensional arraya variable, specify each additional index using another set of square brackets. For example, thefollowing declares a two-dimensional array variable called D.

    int D [] [] = new int [2] [4]

    The above array creates and allocated a 2 by 4 array. Internally this acts like a matrix in which thefirst square bracket is for the number of rows and the second bracket is for the number ofcolumns.

    Remember: Note that you can have an array with 0 columns but not with 0 rows. For example

    int D[] [] = new int [2] [0] - Ok

    int D[] [] = new int [0] [2] - Not Ok.

  • 8/14/2019 Java Notes1

    37/150

    Java Operators

    Java provides a fully featured set of operators, most of which are taken fairly directly from C andC++. However Javas operators differ in some important aspects from their counterparts in theseother languages and you need to understand clearly how javas operators function. The JavaOperators can be classified into 8 Groups as under:

    a) Unary Operatorsb) Arithmetic Operatorsc) Comparison Operatorsd) Bitwise Operatorse) Short-Circuit Operatorsf) Ternary Operatorsg) Assignment Operators

    The Unary operators can be classified further into :

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

    Increment and Decrement Operators

    These operators modify the value of an expression by adding or subtracting 1. So for example, ifan int variable x contains 10, then ++x results in 11 and --x give you 9. This is the case becausethe increment and decrement is done on x and the value is stored in x only

    To understand how the position of these operators ++x and x++ affect their operation, you mustunderstand the different between the values stored by these operations and the result value theygive. For example, you could say y = x++; then the value assigned to y will be the original valueof x and if you say y = ++x, then the value assigned to y will be 1 more than the original value ofx. It is important to note here that in both these cases the value of x will be increment by 1.

    The following table shows the value of x and y, before and after particular assignment using theseoperators:

    Initial value of x Expression Final Value of y Final value of x

    10 y = x++ 10 1110 y = ++x 11 11

    10 y = --x 9 910 y = x-- 10 9

    The Unary + and operators

    The unary + and operators are distinct from the more common binary + and operators whichare usually referred to as + and (add and subtract).

  • 8/14/2019 Java Notes1

    38/150

    The unary + has no effect beyond emphasizing the positive nature of a numeric literal. Unary negates an expression. So one might make a block of assignment just like this:

    x = -3;y = +3;z = -(y+6);

    The Boolean Complement Operator !

    This operator inverts the value of a boolean expression so !true gives false and !false would givetrue. This operator is usually used in the body of if() and else() to be swapped.

    The Cast Operator

    Casting is used for explicit conversion of the type of an expression. This is only possible forplausible target types. The compiler and runtime system check for conformance with typing rulesand incase they do not match, then casting might be required.

    Casts can be applied to change the type of primitive values, for example forcing a double valueinto an int value like this:

    int c = 10;double b = 15.50;int d = (int) (c x b);

    Arithmetic Operators

    The next highest in precedence, after the unary operators are the arithmetic operators. TheArithmetic Operators are divided into two further sub groups, the first group having the *, / and %operators. The second group have the lower precedence + and operators.

    Multiplication and Division Operators

    The above operators can be used on all primitive numeric types and char. Integer division cangenerate an ArithmeticException from a division by zero. The multiplication and division works asit works in simple math examples which we learnt in school.

    The important point to note here is that, whether you multiply or divide two integers, the result willbe calculated using the integer arithmetic in either int or long representation and u will have tostore the same in the wider of the types to ensure that precision is maintained.

    Modulo Operator %

    The modulo Operator gives a value which is related to the remainder of a division. It is generallyapplied to two integers, although it can be applied to floating point numbers also. For examplewhen you say

    int a = 7int b = 3

    int c = a % b the result would be 1.

    The Addition and Subtraction Operators

  • 8/14/2019 Java Notes1

    39/150

    The + and operators perform addition and subtraction and they apply to operands of anynumeric type, but uniquely, the + operator is also permitted when either of the operand is a Stringobject.

    When either of the operands of a + expression is a String object, the meaning of the operator ischanged from numeric addition to concatenation of text. In order to achieve this, both operatorsmust be handled as a text. If both operators are in fact String objects, this simple, however if oneof the operands is not a String object, then the non string operand is converted to a String objectbefore the concatenation is taken place.

    How operands are converted into String Objects??

    It is very useful in practice to know a little about how + converts operands into String objects. Forobject types, conversion to a String object is performed simply by invoking the toString () of thatobject. The toString () is defined in the java.lang.Object class which is the root


Recommended