java programming part i

Upload: pareshbapna

Post on 07-Jul-2018

228 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/18/2019 Java Programming Part I

    1/120

    COALESCE

    1

     Java Programming

    COALESCE Technologies Pvt. Ltd

  • 8/18/2019 Java Programming Part I

    2/120

    COALESCE

    1

    Table of Contents

    Chapter

    1.  Java as a OOP Language.................................................................................6 1.4. Goals of Java Programming Language....................................................................6 

    1.5. Concept of Bytecode...............................................................................................7 

    1.6. The Key features of Java..........................................................................................7 

    1.4. Platform Independence...........................................................................................7 

    1.5. Simplicity................................................................................................................7 

    1.6. Object-oriented.......................................................................................................7 

    1.7. Robustness..............................................................................................................7 

    1.8. Multithreaded..........................................................................................................8 

    1.9. Interpreted and High Performance..........................................................................8 

    1.10. Distributed.............................................................................................................8 

    1.11. Dynamic.................................................................................................................8 

    1.12. Review Questions...................................................................................................8 

    2.  Object-Oriented Programming.....................................................................9 

    2.1.  OOPS vs. Procedural Programming........................................................................9 

    2.2.  Data Abstraction & Encapsulation....................................................................... 11

    2.3.  Inheritance...........................................................................................................12 

    2.4.  Polymorphism......................................................................................................12 

    3.  The Java Architecture.......................................................................................13 

    3.1. The Java Virtual Machine......................................................................................13 

    3.2. Garbage Collection................................................................................................13 

    3.3.  Code Security.......................................................................................................14 

    3.4.  The JVM Runtime Environment...........................................................................14 

    3.5. Class Loader.........................................................................................................14 

    3.6.   Verification Process..............................................................................................15 

    3.7. Review Quastions.................................................................................................15 

    4.  Creating a program in Java............................................................................16 

    4.1. The source file layout............................................................................................16 

    4.2.  Compiling & Running a Program.........................................................................17 

    4.3.   Java Classes & Packages.......................................................................................17 

    4.4.   Java Keywords......................................................................................................18 

  • 8/18/2019 Java Programming Part I

    3/120

    COALESCE

    2

    4.5. Wrapper Classes...................................................................................................18 

    4.6. Primitive Data Type Wrapper Class.....................................................................19 

    4.7. Variables..............................................................................................................19 

    4.8. Member & Automatic variables............................................................................19 

    4.9. Object Reference Variables..................................................................................20 

    4.10. Type Conversion and Casting...............................................................................20 

    4.11.   Widening conversions permitted in Java...............................................................21

    4.12.  Narrowing Conversions allowed...........................................................................21

    4.13.  Operators and Assignments.................................................................................21

    4.14.  The Bitwise operators..........................................................................................22 

    4.15.  Relational Operators............................................................................................22 

    4.16.  Boolean Logical operators....................................................................................23 

    4.17.  The ternary operator.............................................................................................23 4.18.  Classes in Java......................................................................................................24 

    4.19.  Methods in Java...................................................................................................24 

    4.20. 'this’ keyword.......................................................................................................25 

    4.21.  Overloading.........................................................................................................25 

    4.22.  Overriding...........................................................................................................27 

    4.23.  Passing arguments using Call by value & using Call by reference........................27 

    4.24.   Access control-using Modifiers............................................................................28 

    4.25.  Other Modifiers...................................................................................................28 4.26.   Abstract:............................................................................................................299 

    4.27.  Static....................................................................................................................29 

    4.28.  Native..................................................................................................................30 

    4.29.  Nested and inner classes......................................................................................31

    4.30.  Classes Defined Inside Methods..........................................................................32 

    4.31.   Anonymous classes............................................................................................322 

    4.32.   Additional Features of Anonymous Inner Classes................................................33 

    4.33.  Properties of Inner classes...................................................................................33 

    4.34.  Collection API.....................................................................................................33 

    4.35.  The Vector Class..................................................................................................33 

    4.36.  Review Quastions................................................................................................35 

    5.  Reflection API...................................................................................................36 

    5.1. Object class.........................................................................................................36 

    5.2.   Abstract Classes...................................................................................................37 

  • 8/18/2019 Java Programming Part I

    4/120

    COALESCE

    3

    6.  Packages..............................................................................................................38 

    6.1.  Package DefaultPackage;.....................................................................................38 

    6.2.  Classpath.............................................................................................................38 

    6.3.  Protection of Access............................................................................................39 

    7.  Importing of Packages....................................................................................41 

    7.1.  Classes versus Abstract class versus Interface......................................................41

    7.2.  Interfaces.............................................................................................................41

    8.   Accessing implementations Through Interface References..............43 

    8.1.  Extending Interfaces............................................................................................43 

    8.2.  Review Questions................................................................................................44 

    9.  Input/Output in Java......................................................................................45 

    9.1.   What Are Streams?...............................................................................................45 9.2.  Byte-Oriented Streams.........................................................................................45 

    9.3.  Character Oriented Streams.................................................................................45 

    9.4.  Character Stream Classes and Interfaces..............................................................47 

    9.5.  Reading and Writing from and to a File...............................................................48 

    9.6.  Review Question..................................................................................................50 

    10.   APPLETS.............................................................................................................51 

    10.1.  The steps involved in running an Applet..............................................................51

    10.2.   AppletViewer.......................................................................................................53 

    11.  The HTML APPLET Tags..........................................................................54 

    11.1.   Applet Architecture..............................................................................................55 

    11.2.   An Applet Skeleton...............................................................................................55 

    11.3.   Applet Display......................................................................................................56 

    11.4.   Applet Initialization and Termination..................................................................56 

    11.5.  The Applet Class..................................................................................................57 

    11.6.  paint(Graphics g)................................................................................................58 

    11.7.  repaint()..............................................................................................................58 

    11.8.  To set Background and Foreground colors..........................................................58 

    11.9.  Requesting Repainting........................................................................................59 

    11.10.  The Status Window.............................................................................................59 

    11.11.  Passing Parameters to Applets............................................................................60 

    11.12.  Difference between Applications and Applets.....................................................61

    11.13.  Review Questions...............................................................................................62 

  • 8/18/2019 Java Programming Part I

    5/120

    COALESCE

    4

    12.  Fundamentals of Exception Handling.....................................................63 

    12.1. Exception Types...................................................................................................64 

    12.2. try and catch.........................................................................................................65 

    12.3. Multiple Exceptions.............................................................................................65 

    12.4. Throw...................................................................................................................66 

    12.5. Throws.................................................................................................................67 

    12.6. finally...................................................................................................................68 

    12.7. Java’s Built in Exceptions....................................................................................68 

    12.8. Java’s Unchecked RuntimeException Subclasses:...............................................69 

    12.9. Java’s checked exceptions defined in java.lang....................................................69 

    12.10. User defined Exception Subclasses:.....................................................................69 

    12.11. Review Questions................................................................................................70 

    13.  Event Handling..................................................................................................71 

    13.1. Event Handling Mechanisms................................................................................71

    13.2. Outward rippling model or Hierarchical Event Model...........................................71

    13.3. Delegation event model........................................................................................71

    13.4. Event Sources.......................................................................................................72 

    13.5. EventListeners......................................................................................................72 

    13.6. EventClasses........................................................................................................72 

    13.7. Methods...............................................................................................................72 

    13.8. Hierarchy of Event Classes in java.awt.event........................................................73 13.9. Main Event Classes in java.awt.event....................................................................73 

    13.10. The Classes, Methods and Interfaces used by AWT..............................................74 

    13.11. The WindowEvent Class......................................................................................78 

    13.12. Using the delegation event model........................................................................79 

    13.13. Adapter Classes....................................................................................................79 

    13.14. Inner Classes........................................................................................................80 

    13.15. Anonymous Inner Classes....................................................................................80 

    13.16. Review Questions................................................................................................8114.   AWT Controls....................................................................................................82 

    14.1. Window Fundamentals.........................................................................................83 

    14.2. The class hierarchy for panel and frame................................................................84 

    14.3. Component...........................................................................................................84 

    14.4. Container..............................................................................................................84 

    14.5. Panel....................................................................................................................84 

  • 8/18/2019 Java Programming Part I

    6/120

    COALESCE

    5

    14.6. Frame...................................................................................................................84 

    14.7. Handling Events in a Frame Window...................................................................85 

    15.   Adding & Removing Controls......................................................................87 

    15.1. Labels...................................................................................................................87 

    15.2. Buttons.................................................................................................................87 

    15.3. Check Box............................................................................................................88 

    15.4. Choice Controls....................................................................................................90 

    15.5. Lists.....................................................................................................................91

    15.6. ScrollPane.............................................................................................................93 

    15.7. Scrollbar...............................................................................................................93 

    15.8. TextField & TextArea...........................................................................................94 

    15.9. TextArea...............................................................................................................96 

    15.10. Radio Buttons......................................................................................................97 15.11. Review Questions.................................................................................................98 

    16.  Layout Managers..............................................................................................99 

    16.1. Identifying GUI requirements...............................................................................99 

    16.2. Selection of the Components................................................................................99 

    16.3. Sketching the GUI..............................................................................................100 

    16.4. Using Layout Managers......................................................................................100 

    16.5. Containers and Components...............................................................................100 

    16.6. Common subclasses of java.awt.Container..........................................................10116.7. Component Size and Position..............................................................................101

    16.8. Layout Managers................................................................................................102 

    16.9. FlowLayout Manager..........................................................................................102 

    16.10. BorderLayout Manager......................................................................................103 

    16.11. GridLayout Manager.......................................................................................... 105 

    16.12. CardLayout Manager.........................................................................................107 

    16.13. GridBagLayout Manager.....................................................................................110 

    16.14. anchor constraint.................................................................................................11116.15.  fill constraint.......................................................................................................112 

    16.16. Insets..................................................................................................................113 

    16.17. Null Layout Manager..........................................................................................116 

    16.18. Choosing Layout Managers................................................................................117 

    16.19. Review Questions...............................................................................................117 

    17.  Index ....................................................................................................................119 

  • 8/18/2019 Java Programming Part I

    7/120

    COALESCE

    6

    1. Java as a OOP Language

     Java was conceived by a team of engineers in Sun Microsystems in 1991 as a part of aresearch project, which was led by James Gosling and Patrick Naughton. It took 18 monthsto develop the first working version. This language was initially called “Oak” but wasrenamed as “Java” in 1995.

    Modeled after C++, the Java language was designed to be small, simple, and portable acrossplatforms and operating systems, both at the source and at the binary level, which meansthat Java programs (applets and applications) can run on any machine that has the Java

     virtual machine installed.

    1.1.  Goals of Java Programming Language

     JAVA language is an effective programming language for it…

    •  Is object-oriented; and helps the programmer visualize the program in real-life terms.

    •  Eliminates pointer arithmetic and memory management that affect code robustness.

    ♦   An interpreted environment resulting the following two benefits:

    • 

    Speed of development.

    •  Code portability – enables the operating system to make system level calls onbehalf of the runtime environment.

    •   A way for programs to run more than one unit of execution called a thread of activity.

    •   A means to change programs dynamically during their runtime life by allowing them todownload code modules.

    Security

     Java is a secured programming language because it provides the user with a Virtual Firewallbetween the networked applications and the computer thus ensuring that the data in theuser’s system is protected by any possible Infectious contents. This is achieved by confiningthe Java program within the Java Runtime Environment.

    Portability  

     Java can be easily ported on any type of system and irrespective of the operating systembeing used. Java achieves this portability due to its feature of Implementation Independency.

  • 8/18/2019 Java Programming Part I

    8/120

    COALESCE

    7

    1.2. Concept of Bytecode

    The Security and the portability concerns of the user was solved by the Java Programminglanguage, because the out put of a Java program is not a executable piece of code, instead it

    isBytecode

     which is the output of the Java Compiler. This Bytecode is understood by, the Java Virtual Machine (JVM), which is the interpreter for Bytecode. The JVM ’ s are differentfor different operating systems.

    1.3. The Key features of Java

    The factors that have played an important role in moulding the final form of Java languageare:

    1.4 Platform I ndependence

    Platform independence-that is, the ability of a program to move easily from one computersystem to another-is one of the most significant advantages that Java has over otherprogramming languages, particularly if your software needs to run on many differentplatforms. If you're writing software for the World Wide Web, being able to run the sameprogram on many different systems is crucial to that program's success. Java is platformindependent at both the source and the binary level.

    1.5 Simplicity   Java was designed to be easy for the professional programmer to learn and use effectively.Being simple means Being small also. Java achieves this by enabling the programmer to builda- software that can be runstand-aloneeven on small machines.

     A system, which functions independently without the help of any network resources, isknown as astand-alone system.

    1.6 Object-oriented

    Object-Oriented design is a technique of programming, which mainly focuses on the Objectand it’s Interfaces. To make a comparison, an object-oriented mechanic would be botheredonly about repairing the vehicle, and secondarily on the tools that he is going to use. A non-object-oriented mechanic would primarily be concerned of his tools rather than the vehicle.The object-oriented features of Java are very much of C++ itself.

    1.7 Robustness

    The multi-platform environment places extraordinary demands on a program, because theprogram must execute reliably in a variety of systems. Java emphasizes a lot on earlychecking for problems, later dynamic or runtime checking, thus eliminating error-pronesituations.

  • 8/18/2019 Java Programming Part I

    9/120

    COALESCE

    8

    1.8 M ult it hreaded  Multithreading is a concept, where different process, run simultaneously. Java supportsmultithreaded programming because of its better interactive responsiveness and real timebehavior.

    1.9 I nterpreted and H igh Performance  The code can be easily interpreted on any system that provides a Java Virtual Machine. Theconversion of the Interpreted code into the machine code at Run Time for the particularCPU on which the application is running is called High Performance.

    The compilation of code in an interpreted environment is done line by line & hence thedebugging of the code becomes very easy, as the interpreter points exactly to the line wherethe error ocurs.

    1.10 D istr ibuted  It is designed for the distributed environment of the Internet, as it handles TCP/ IPprotocols. Java allows objects on two different computers to execute procedures remotely. Java has revived these interfaces in a package calledRemote Method Invocation (RMI).

    1.11 Dynamic   Java programs carry with them substantial amounts of run-time type information that is usedto verify and resolve access to objects at run time. This makes it possible to dynamically linkcode in a safe manner.

    1.12 Review Questions  

    1.  What are Bytecodes?

    2.  What do we mean by saying Java is Interpreted?

    3.  If Java is platform independent, why doesn’t it run on all platforms?

  • 8/18/2019 Java Programming Part I

    10/120

    COALESCE

    9

    2. Object-Oriented Programming

    OOP is the dominant programming paradigm these days, having replaced the Structured 

    mode of programming techniques that were developed in the early 70s. Java is an object-oriented programming language like C++, Ada, Simula, Small-talk.

    The key to being most productive in OOP is to make each object responsible for carryingout a set of related tasks. If an object relies on a task that isn’t its responsibility, it needs tohave access to an object whose responsibilities include that task. The first object then asksthe second object to carry out the task. This is done with a more generalized version of thefunction call that you are familiar with in procedural programming. In java we call this asmethod calls. In particular an object should never directly manipulate the internal data ofanother object. All communication should be via messages that is, method calls. Bydesigning your objects to handle all appropriate messages & manipulate their data internally, you maximize reusability, reduce data dependency & minimize debugging time.

    2.1. OOPS vs. Procedural Programming

    In procedure oriented programming, you identify the tasks to be performed and then:•  Break the task to be performed into sub-tasks and those into smaller subtasks, until

    the subtasks are simple enough to be implemented directly.•  Write procedures to solve simple tasks & combine them into more sophisticated

    procedures, until you have the functionality achieved.

    Most programmers use a mixture of the top-down & bottom-up strategies to solve aprogramming problem. The important difference is that in OOP you first isolate the classesin the project only then you look for the methods of the class. And there is anotherimportant difference between traditional procedures & OOP methods: each method isassociated with the class that is responsible for carrying out the operation.

    For small problems the breakdown into procedures works very well. But for largerproblems, classes & methods have two advantages. Classes provide a convenient clusteringmechanism for methods. A simple web browser may require 1000 functions for itsimplementation or it may require 100 classes with an average of 10 methods per class. Thelatter structure is much easier to grasp by the programmer or to handle by teams ofprogrammers. The Encapsulation built into classes helps you here as well: classes hide their

    data representations from all code except their own methods.

  • 8/18/2019 Java Programming Part I

    11/120

    COALESCE

    10

    Procedural Programming.

    Object Oriented Programming

    The above figure shows that if a programming bug messes up the data it is easier tosearch for the culprit among the methods that had access to that data item among thoseprocedures.

    GLOBAL DATA

    FUNCTION

    FUNCTION

    FUNCTION

    OBJECT DATA

    OBJECT DATA

    OBJECT DATA

    method

    method

    method

    method

    method

  • 8/18/2019 Java Programming Part I

    12/120

    COALESCE

    11

    There is a more serious problem, while classes are factories for multiple objects with thesame behavior, you cannot get multiple copies of a useful module. Suppose you have amodule encapsulating a collection of orders, together with a balanced binary tree moduleto access them quickly. Now it turns out that you actually need two such collections, onefor the pending orders & one for the completed orders. You cannot simply link the

    order tree twice. And you don’t really want to make a copy & rename all the proceduresin order for the linker to work.

    Classes do not have this limitation. Once a class has been defined it is easy to constructany number of instances of that class type, where as a module can have only oneinstance.

    Classes

    The Class is a container that holds both data & code together in a single unit. It is a templatefor objects. Classes are user defined data types and behave like built in data types of a

    programming language. Once a class has been defined, we can create any number of objectsbelonging to that class.Ex:  Fruit Grape, Fruit Water melon and Fruit Pine Apple.

    Here the class Fruit has different instances with the same properties but different values.

    Objects

    Objects are the basic run-time entities in an object-oriented system.Ex: Person, Bank Account, Table of data or any item that the program must handle.

    They contain data and code to manipulate that data. When a program is executed, theobjects can interact with each other without knowing the details of each other’s data or code.

    Ex:  A Customer Object requesting the Account Object for the Bank balance.

    2.2. Data Abstraction & Encapsulation

    Encapsulation is the mechanism that binds together code and the data it manipulates, andkeeps both safe from outside interference and misuse. The data is not accessible to theoutside world and only those functions that are wrapped in the class can access it. Thesefunctions provide the interface between the object’s data and the program. The insulation ofthe data from the direct access by the program is calleddata hiding.

  • 8/18/2019 Java Programming Part I

    13/120

    COALESCE

    12

    2.3. Inheritance

    Inheritance is the process by which one object acquires the properties of another object. Thisis important because it supports the concept of hierarchical classification. Inheritanceinteracts with encapsulation as well. Inheritance provides the idea of reusability of code and

    each sub class defines only those features that are unique to it.Flora

    Plants Trees

    Rose Tomato Oak Coconut

    2.4. Polymorphism

    Polymorphism is a feature that allows one interface to be used for a general class of actions.

     An operation may exhibit different behavior in different instances. The behavior dependson the types of data used in the operation. It plays an important role in allowing objectshaving different internal structures to share the same external interface. Polymorphism isextensively used in implementing inheritance.

    Ex:  add(int a, int b) add(int a, float b, int c) add(int a, int b, float c, double d)

    Here different datatypes are being added using the same interface.

  • 8/18/2019 Java Programming Part I

    14/120

    COALESCE

    13

    3. The Java Architecture

     Java essentially uses the following features to fulfill its goals:

    • 

    The Java Virtual Machine•  The Garbage Collector

    •  Code security  

    3.1. 

    The Java Vi rtual Machine

     Java achieves the concept of platform-independence by inventingan abstract computer of itsown and running on that. This virtual machine, as it is called runs a special set of instructions,called bytecodes that are simply a stream of formatted bytes, each of which has a precise

    specification of exactly what each byte code does to this virtual machine. The virtualmachine is also responsible for certain fundamental capabilities of Java, such as objectcreation and garbage collection.The JVM is defined as “An abstract machine that is implemented by emulating it in software on areal machine”. 

    The JVM provides the hardware platform specifications to which all java technology code iscompiled. This specification enables java software to be platform independent because thecompilation is done for a generic machine known as Java Virtual Machine (JVM). This generic machine can be emulated into software to run on various existing computer systemsor implemented in hardware.

    The compiler takes the java application source code and generates bytecodes. Every java

    interpreter, regardless of whether it is a java technology development tool or a web browserthat can run applets, has an implementation of JVM. The Java virtual machine specificationconsists of the following:

    •  The byte code syntax, including opcode and operand sizes, values, and types, andtheir alignment.

    •  The values of any identifiers (for example, type identifiers) in bytecodes or insupporting structures

    •  The layout of the supporting structures that appear in compiled Java code

    •  The Java .class file format

    3.2. 

    Garbage Collection

    In the Java programming language, the dynamic allocation of objects is achieved using thenewoperator. An object once created uses some memory and the memory remains allocatedtill there are references for the use of the object. When there are no references for an object,it is assumed to be no longer needed and the memory occupied by the object can bereclaimed. There is no explicit need to destroy an object as java handles the de-allocationautomatically. The technique that accomplishes this is known asGarbage Collection.

  • 8/18/2019 Java Programming Part I

    15/120

    COALESCE

    14

    Programs that do not de-allocate memory can eventually crash when there is no memory lefton the system to allocate. These programs are said to have memory leaks.

    Garbage collection happens automatically during the lifetime of a java technology program,eliminating the need to de-allocate memory and avoiding memory leaks. Such processes arecalled background processes.

    There are methods, System.gc()  and Runtime.gc()  that look as if they “run the garbagecollector” but even these methods do not have any control on the Garbage CollectionProcess. 

    3.3. 

    Code Securit y  

    Source File Class Loader

    Byte Code Verifier

     javac Hello.java Network Interpreter JIT Code

    Generator

    Hello.class Runtime

    Hardware

    3.4. The JVM Runtime Environment

    The byte codes are stored in class files. At runtime, the bytecodes that make up a javasoftware program are loaded, checked, and run in an interpreter. In the case of applets thebytecodes can be downloaded and then interpreted by the JVM built into the browser. Theinterpreter has two functions: it executes bytecodes, and makes the appropriate calls to theunderlying hardware.

     A Java technology runtime environment runs code compiled for a JVM and performs threemain tasks:

    •  Loads Code - Performed by the class loader

    • 

     Verifies Code - Performed by the byte code verifier

    •  Executes Code - Performed by the runtime interpreter

    3.5. Class Loader

    The class loader loads all classes needed for the execution of a program. The class loaderadds security by separating the namespaces for the classes of the local file system from thoseimported from network sources.

  • 8/18/2019 Java Programming Part I

    16/120

    COALESCE

    15

    Once all the classes have been loaded, the memory layout of the executable file isdetermined. At this point specific memory addresses are assigned to symbolic referencesand the lookup table is created. Because memory layout occurs at runtime, the javatechnology interpreter adds protection against unauthorized access into the restricted areasof code.

     Java software code passes several tests before actually running on your machine. The JVMputs the code through a byte code verifier that tests the format of code fragments andchecks code fragments for illegal code – code that forges pointers, violates access rights onobjects, or attempts to change object type.

    3.6. Verifi cation Process

    The byte code verifier makes four passes on the code in a program. It ensures that the codefollows the JVM specifications and does not violate system integrity. If the verifiercompletes all four passes without returning an error message, then the following is ensured.The classes follow the class file format of the JVM specification

    •  There are no access restriction violations

    •  The code causes no operand stack overflows or underflows

    •  The types of parameters for all operational codes are known to always be

    correct.

    No illegal data conversions, such as converting integers to object references, have occurred.

    3.7. 

    Review Questi ons

    1.  What kind of Garbage Collection does the Java Virtual Machine use?

  • 8/18/2019 Java Programming Part I

    17/120

    COALESCE

    16

    4. Creating a program in Java A Java program file is an ordinary text file with “. java”  extension.  Java source files arecreated in a plain text editor, or in an editor that can save files in plain ASCII without any

    formatting characters. It contains one or more class definitions. In Java all code must resideinside a class. Generally the class name written in the .java file will be the name for the .javafile too. 

    4.1. The source file layout  

    There are three top-level  elements that may appear in a file. None of these elements isrequired. If they are present, they must appear in the following order:

    •  Package Declaration (optional – only one)

    • 

    Import Statements (optional – any number)•  Class Definitions (Any number – only one public class)

    SimpleExample.java

    / / A SAMPLE PROGRAM IN JAVA

    import java.io.*;

    public class SimpleExample

    { public static void main(String args[])

    { System.out.println("Hey I am successful in writing my prog");

    }

    }  What does this whole program has to say..?

    The program is a java application, since it has main() method. Now let us understand thesignature of the main() method:

    Themain() method is:

    public:  so that it can be accessed by anything, including the java technology interpreter.

    static:  Tells the compiler that the main() method is usable in the context of the classSimpleExample and should be run before the program does anything else.

     void: Indicates that it does not return anything.

    String args[ ]: Contains command line arguments. args[0] stores the first command lineparameter.

    Object creation: In java, objects are created by explicitly calling the constructor of the class forwhich it holds the reference.

     Java programs do not directly deal with objects. Rather it deals with the reference of theobject, which the constructor returns.

  • 8/18/2019 Java Programming Part I

    18/120

    COALESCE

    17

    4.2. Compiling & Running a Program

    To compile the SimpleExample program, execute the compiler, javac, specifying the name ofthe source file on the command line, as shown here:

    C:\ >javac SimpleExample.java 

    The javac compiler creates a file called SimpleExample.class. This .class file is nothing but the bytecode for the program. The bytecode is the intermediate representation of your programthat contains instructions the Java interpreter will execute. Thus, the output of javac is notthe code that can be directly executed.

    To actually run the program, you must use the Java interpreter, called java. To do so, pass theclass name SimpleExample at the command-line:

    C:\>java SimpleExample 

    When the program is run, the following output is displayed:

    Hey I am successful in writing my prog.

    4.3. Java Classes & Packages

     A class is a term for a template that provides data and the functionality , which will work on thatdata.

    The Java Development Kit comes with a standard set of class (Java Class Library) thatimplements most of the basic behaviors needed - not only for programming tasks, but alsofor graphics and networking database etc.

     A Package is a group of related classes. The class library is organized in to many packages,each containing several classes. The following packages are prominent:

    • 

     java.lang: contains classes that form the core of the language, such as String, Math,Integer and thread. It is automatically imported by default into all the user definedSource files.

    • 

     java.awt: contains classes that make up the Abstract Window Toolkit (AWT). Thispackage is used for constructing and managing the graphical user interface of theapplication.

    •   java.net: Contains classes for performing network related operations and dealing withsockets and uniform resource locators (URLs).

    •   java.io: Contains classes that deal with file Input/Output. 

    • 

     java.util:  Contains utility classes for tasks, such as random number generation,defining system properties, and using date and calendar related functions.

  • 8/18/2019 Java Programming Part I

    19/120

    COALESCE

    18

    4.4. Java Keywords

    There are 52 reserved keywords defined in the Java language. These keywords, combinedwith the syntax of the operators and separators, form the definition of the Java language.

    Keywords in Java Language:

     Abstract Const Finally Implements Public This

    Boolean Continue For Instanceof Throw Transient

    Break Float If Null  Short Void

    Byte Default Import Int Super Volatile

    Case Do False Return Switch While

    Catch Double Interface Package Synchronized

    Char Else Long Private Static

    Class Extends Goto Protected Try

    True Final New Native Throws

    Data Types

    Type In bits Range 

    Byte  8 -27 to 27-1

    Short  16 -215 to 215-1

    Int  32 --231to 231-1 

    Long  64 -263 to 263-1 

    Float  32 3.4e-038 to 3.4e+038

    Double  64 1.7e-308 to 1.7e+308

    Boolean  8 True/False

    Char   16 0 to 65,636 (216-1)

    4.5. 

    Wrapper Classes

     Java deals with two different types of entities: Primitivetypesandtrueobjects. Although Java istruly object-oriented, it does not use most primitive types for the usual reason: performance. 

    Manipulating primitive type without any object-oriented overhead is quite a bit moreefficient. Java contains many subsystems that can work only with objects. Bywrapping  theprimitive types in some object sugar coating the programmer can easily create a class whosesole purpose is encapsulation. The net effect would be to obtain an object giving theprogrammer the universality and power that come with dealing with only objects.

    Ex: Class Integer for primitivetypeint.

    ClassShort for primitivetypeshort. 

  • 8/18/2019 Java Programming Part I

    20/120

    COALESCE

    19

    The following table shows the primitive types & the wrapper classes present in the java.langpackage. 

    Many Java Classes prefer to work with objects rather that the primitive data types. Thus theWrapper classes come as help. They provide object versions of the data type. They alsoprovide methods to convert strings to various data types. 

    4.6. Prim it ive Data Type Wrapper Class

    Data type Wrapper Class Data type Wrapper Class

    boolean  Boolean  byte Byte 

    char Character  Short Short 

    Long  Long  Int  Integer

    Float Float Double Double

    Wrapper class is constructed by passing the value to be wrapped into the appropriateconstructor.

    int pint=500; Integer wint=new Integer(pint); int p2=wint.intValue();

    4.7. Variables

    The variable is the basic unit of storage in a Java program. A variable is defined by thecombination of an identifier, a type, and an optional initializer. The variables have a scope,which defines their visibility and lifetime. The variable name is a name given to the memorylocation in a computer and not for the value present in it.

    In Java all variables must be declared before they can be used.Type identifier [=value], identifier [=value];

    int i,j,k; int a=2,b=4,c=6; float pi=3.14f; double do=20.22d; char a=’v’

     Java allows variables to be initialized dynamically, using any expression valid at the time the variable is declared.

    RightAngledTriangle.java

    / / DYNAMIC INITIALIZATION

    class RightAngledTriangle

    { public static void main(String args[])

    { double a=6.0, b=7.0;double c=Math.sqrt(a * a + b * b);

    System.out.println("Hypotenuse of the right angled triangle is "+c);

    }

    }

    4.8. Member & Automatic variables

     Java supports variables of two different lifetimes:

  • 8/18/2019 Java Programming Part I

    21/120

    COALESCE

    20

    •   A member variable of a class is created when the instance is created, and is accessiblefrom any method in the class.

    •   Anautomatic variable also called the local variable of a method is created on entry to

    the method, exists only during execution of the method. Every automatic variable must

    be explicitly initialized before being used.

    4.9. Object Reference Variables

     Java programs do not directly deal with objects. When an object is constructed, theconstructor returns a value – a bit pattern – that uniquely identifies the object. This value isknown as areference to the object.

    Button ok;

    ok=new Button(“Ok”);

    In the above example the Button constructor returns a reference to the just-constructed

    button – not the actual button object or a copy of the button object. This reference isstored in the variable ok. 

    4.10.  Type Conversion and Casti ng

     A variable of one type can receive the value of another type. There are situations in whichthe system implicitly  changes the type of an expression without your explicitly performing acast. You can explicitly change the type of a value by casting. Casting means assigning a value of one type to a variable of another type. Automatic, non-explicit type changing isknown asConversion.

    If the two types are compatible, then java will perform the conversion automatically else, thecast operator has to be explicitly used to convert the data between incompatible types.

    Ex: An int value can be assigned to a long variable but there is no conversion defined fromfloat to byte.

    CastingExample.java

    / / TYPE CASTING

    class CastingExample

    { public static void main(String args[])

    { byte x;

    int a=270;double b =128.128;

    System.out.println("\n int converted to byte");

    x=(byte) a;

    System.out.println("a and x "+ a +" "+x);

    System.out.println("\n double converted to int");

    a=(int) b;

    System.out.println("b and a "+ b +" "+a);

  • 8/18/2019 Java Programming Part I

    22/120

    COALESCE

    21

    System.out.println("\n double converted to byte");

    x=(byte) b;

    System.out.println("b and x "+b +" "+x);

    }

    4.11.  Widening conversions permi tted in Java

    •  From a byte to a short, an int, a long, a float, or a double

    •  From a short to an int, a long, a float, or a double

    •  From an int to a long, a float, or a double

    •  From a long to a float, or a double

    • 

    From a float to a double

    Char

    Int long float double

    Byte Short

    4.12.  N arrowing Conversions allowed

    •  From a byte to a char

    • 

    From a short to a byte or a char•  From a char to a byte or a short

    •  From an int to a byte, a short, or a char

    •  From a long to a byte, a short, a char, or an int

    •  From a float to a byte, a short, a char, an int, or a long

    •  From a double to a byte, a short, a char an int, a long, or a float

    4.13.  Operators and Assignm ents

     Java provides a fully featured set of operators. All operators are evaluated left to right. Forassignments associativity is right-to-left.

    OPERATOR RESULT

    +   Addition

    -  Subtraction

    *  Multiplication 

    /   Division 

  • 8/18/2019 Java Programming Part I

    23/120

    COALESCE

    22

    %  Modulus 

    ++  Increment (Unary) 

    +=   Addition assignment 

    - = 

    Subtraction assignment 

    *=  Multiplication assignment 

    / =  Division assignment 

    %=  Modulus assignment 

    --  Decrement

    4.14.  The Bi twise operators

    The Bit wise operators defined in java can be applied to the integer types, long, int, short, char

    and byte.OPERATOR RESULT

    ~ Bit wise Unary NOT

    & Bit wise AND

    | Bit wise OR

    ̂ Bit wise exclusive OR

    >> Shift right (Performs a signed shift)

    >>> Shift right zero fill (Performs a unsigned shift)

    >= Shift right assignment

    >>>= Shift right zero fill assignment

  • 8/18/2019 Java Programming Part I

    24/120

    COALESCE

    23

    > Greater than

    < Lesser than

    >= Greater than or equal to

  • 8/18/2019 Java Programming Part I

    25/120

    COALESCE

    24

    4.18.  Classes in Java

    The class defines a new data type and this data type is used to create objects of that type.“class is an template for an object”.

    Following is the general from of the class:

    class MyClass

    { variable1;

     variable2;

    Method1()

    { / / Body of Method1.

    }

    Method2(parameters)

    { / / Body of Method2.

    }

    }

    4.19. 

    Methods in Java

     A method contains code to operate on the data present in a class. A method does notoperate on the data; rather, the data operates on itself.

    < name>([parameter list])[throws exception]

    {

    body of the method;} 

    ConstructorsThey are used to initialize the data members of a class, immediately after an object is created.It has the same name as the class, in which it resides and is syntactically similar to a method.Once defined, the constructor is automatically called immediately after the object is created.Constructors do not have a return type. This is because the implicit return type of a classconstructor is the class type itself. The reason why the parentheses are needed after theclass name while initializing an object is, to call the constructor for the class being defined.

    class Cube

    { int length;

    int volume;

    / /Default constructor which takes no parameters.

    public Cube() {

    }/ / Overloaded parameterized constructor.

    public Cube(int x){

      length = x;

  • 8/18/2019 Java Programming Part I

    26/120

    COALESCE

    25

    } public int calVolume(){

      volume = length*length*length;

    return volume;

    } public static void main(String args[])

    { int volumeReturn;

    / /  creating the object of the class Cube using the new operator with the constructor. 

    Cube c=new Cube(3);

     volumeReturn=c.calVolume();

    }

    }

    The class Cube is used for calculating the volume of a cube. The constructor  receives thelength of the cube as aparameter and initializes the instance variable length with the supplied value. Themethod calVolume calculates the Volume of the cube.

    Using the keyword new in the constructor causes the following:•  First the space for the new object is allocated and initialized to the zero form or

    null.

    •  Second, any explicit initialization is performed.

    •  Third, a constructor, which is a special method, is executed. Arguments passed inthe parentheses to the new are passed to the constructor.

    •  The final stage of a new object is to call a method called aconstructor. 

    It is also possible to pass parameters to the constructors and they are known asparameterizedconstructors.

    4.20.  ‘thi s’ keyword

    It is used in any method to refer to thecurrent object or class instance.  That is, this is always areference to the object on which the method was invoked.

    fruit(mango m, apple a, grape g)

    { this.green=m;

    this.red=a;

    this.black=g;

    }

    4.21.  Overloading

    Reusing the same method name with different types and/or number of arguments andperhaps a different return type is known asoverloading. 

  • 8/18/2019 Java Programming Part I

    27/120

    COALESCE

    26

    Using the same method name with identical arguments and return type is known asoverriding. Method overriding forms the basis for one of Java’s most powerful concept,dynamic method dispatch. Dynamic method Dispatch is the mechanism by which, a call to anoverridden function is resolved at run time rather than compile time. Dynamic methoddispatch is important because this is how java implements run-time polymorphism.

     A superclass reference variable can refer to a subclass object. Java uses this fact to resolvecalls to overridden methods at run time. Here is how. When an overridden method is calledthrough a superclass reference, java determines which version of that method to executebased upon the type of the object being referred to at the time the call occurs. Thus, thisdetermination is made at run time. When different types of objects are referred to, different version of an overridden method will be called. In other words, it is the type of the objectbeing referred to (not the type of there reference variable) that determines which version ofan overridden method will be executed. Therefore, if a super class contains a method that isoverridden by a subclass, then when different types of objects are referred to through asuper class reference variable, different versions of the method are executed.

    Overloading  is used while creating several methods that perform closely related functionsunder different conditions within a class. The compiler will treat each of these methods asdifferent method. A method name can be reused anywhere, if it follows the following:

    •  In an unrelated class, no special conditions apply and the two methods are notconsidered related in any way.

    •  In the class that defines the original method, or a subclass of that class, the methodname can be reused if the argument list differs in terms of the type of at least oneargument.

    OverLoadingExample.javaclass OverLoading{ void plan() {System.out.println(“Default Constructor”);}/ / overloading the method plan with a parameter of type int. void plan(int x) {System.out.println(“The value of x is :”+x);

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

    {

    OverLoading ol= new OverLoading();/ / calling all the forms of the method plan.ol.plan();ol.plan(5);

    }}

    In the above program plan()  is overloaded twice. The first time is without a parameter,which prints Default Constructor and the second is with a parameter of type int. Whenever amethod, which is overloaded is called, a match between the arguments used to call themethod and the method’s parameters is searched by Java.

  • 8/18/2019 Java Programming Part I

    28/120

    COALESCE

    27

    4.22.  Overriding

    In a strict subclass of the class that defines the original method, the method name can bereused with identical argument types and order and with identical return type. This is

    overriding. In this case, additional restrictions apply to the accessibility of, and exceptions that may bethrown by, the method.When an overloaded method is called, java looks for a match between the arguments used tocall the method and the method’s parameters. However, this match need not always beexact. In some cases Java’s automatic type conversion can play role in overload resolution. Java will employ its automatic type conversions only if no exact match is found.

    The key differences between overloading and overriding are

    OverLoading OverRiding

    It is the relationship between the methodsavailable in the same class. It is the relationship between a superclassmethod and a subclass method.It does not block inheritance from thesuperclass.

    It blocks inheritance from the superclass.

    In overloading separate methods share thesame name.

    In overriding subclass method replaces thesuperclass method.

    It follows different method signatures. It follows same method signature.It may have different return types. It must have matching return types.It may have different declared exceptions. It must have compatible declared exceptions.

    OverridingExample.java

    abstract class Base{ abstract public void call();

    } class Derived extends Base

    { public void call()

    { System.out.println(“Hello Everybody”);

    }

    }class OverridingExample

    {public static void main(String args[])

    { Base b;

    Derived d= new Derived();

    b=d;

    b.call();

    }

    }

    4.23.  Passing arguments using Call by value & using Call by reference

     An argument to a sub routine can be passed in two ways.

  • 8/18/2019 Java Programming Part I

    29/120

    COALESCE

    28

    1.  call by value.2.  call by reference.

    In call by  value, the method receives a copy of the original data and therefore, changes inthe method have no effect on the original value.

    In call by reference, a reference of a variable is passed as a parameter to the method. Since areference is passed to the method changes to it are affected at all places where the variable(object) will be used.

    4.24.  Access control -using M odif iers

    Modifiers are Java keywords that give the compiler information about the nature & scope ofcode, data or classes. Modifiers specify, that a particular class or variable or a method isstatic, or final, or transient. With these access modifiers encapsulation is worked out

    according to the need of the program. A member access level is determined by the access specifier, that modifies its declaration. Java’s access specifiers are public, private and protected.  Java also defines a default accesslevel.

    public: It is the most generous access modifier. A public class, variable, or method may beused in any java program without restriction.

    private:The least generous access modifier is private. Top level classes may not be declaredprivate.

    protected:  A protected access specifier defines that only the members of the class and its subclass in which it is defined can access that feature.

    When no access specifier is used, then by default the member of a class is public within itsown package, but cannot be accessed outside the package.

    4.25.  Other M odifiers

    final:  The final modifier applies to classes, methods, and variables. The meaning of final varies from context to context, but the essential idea is the same.•   A final class may not be sub classed.

    • 

    If applied to a variable it means to say that the value is constant.•   A final object reference variable may not be changed but the data owned by the object

    that is referred as final can be changed.

     A final method may not be overridden. This is done for security reasons and these methodsare used for optimization. 

  • 8/18/2019 Java Programming Part I

    30/120

    COALESCE

    29

    4.26.  abstract:

    The abstract modifier can be applied to classes and methods. A class that is abstract cannotbe instantiated. Abstract classes provide way to defer implementation to sub classes. A class must be declared abstract if any of the following conditions is true:•  The class has one or more abstract methods.

    • 

    The class inherits one or more abstract methods (from an abstract parent) for which itdoes not provide implementations.

    •  The class declares that it implements an interface but does not provide implementationsfor every method of that interface.

    4.27.  Static

    The static modifier can be applied to class variables, methods, and even a code that is not apart of method. It cannot be assigned to a top-level class definition but it can be assigned toan inner class level definition.

     A static class member can be accessed directly by the class name and doesn’t need anyobject. A single copy of a static member is maintained through out the program regardlessof, the number of objects created.

    Static variables are initialized only once and at the start of the execution during the lifetimeof a class. These variables will be initialized first before the initialization of any instance variables.

    Methods declared as static (class methods) have several restrictions:•  They can only call other static methods.

    •  They must only access static data. Attempt to access non-static data causes a compiler

    error.•  Non-static methods can access static data and methods.•  They cannot refer to this orsuper  in anyway.

    •  These methods can be accessed using the class name rather than a object reference.•  main() is static because it must be accessible for an application to run, before any

    instantiation takes place.•  When main() begins, no objects are created, so if you have a member data, you must

    create an object to access it. StaticExample.java/ / STATIC INITIALIZERSclass StaticExample

    { static int x =8;static float y;double z; void display(){ System.out.println("Infosys");}static void inf(int i){ System.out.println("i = "+i);

    System.out.println("x = "+x);System.out.println("y = "+y);

    } static

  • 8/18/2019 Java Programming Part I

    31/120

    COALESCE

    30

    { System.out.println("Initialising the Static Block"); y=x*2;

    }public static void main(String args[]){ StaticExample se=new StaticExample();

    inf(25);

    se.display();}

    4.28.  N ative

    The native modifier can refer only to methods. A method declared as native says that thebody of the method i.e, the code is outside the JVM in a library.Native code is written in a non-java language, typically in C or C++, and compiled for asingle target machine type. It is mainly used for GUI components, network communication,

    and a broad range other platform-specific functionality.

    When a native method is invoked, the library that contains the native code ought to beloaded and available to the java virtual machine; if it is not loaded, there will be a delay. Thelibrary is loaded by callingSystem.loadLibrary(“Library name”);.The following gives the code snippet:

    Class NativeExample{

    / / Native method declarationnative void doSomethingLocal(int i);static{ System.loadLibrary(“Mynativelib”);}

    Callers of native methods do not have to know that the method is native. The call is madein exactly the same way as if it were non-native.

    NativeExample natex;Natex=new NativeExample();Ne.doSomethingLoacal(5);

    synchronized:  The synchronized modifier is used to control access to critical code inmultithreaded programs. We will look into it when we learn Multithreading

     Volatile:   volatile variables are of interest in multiprocessor environments. Declaring a variable volatile says that it might be modified asynchronously, so the compiler takes specialprecautions.

  • 8/18/2019 Java Programming Part I

    32/120

    COALESCE

    31

    MODIFIER CLASS VARIABLE METHOD/ CONSTRUCTOR

    public  yes yes yesprotected  no yes yesFriendly   yes yes yes

    private  no yes yesfinal  yes yes yesabstract  yes yes yesstatic  yes yes yesnative  no no yestransient  no yes nosynchronized  no no yes

    4.29.  N ested and inner classes

     A class written within another class is known as nested class.  Inner classes are a usefulfeature because they allow you to group classes that logically belong together and to controlthe visibility of one within another. The scope of the nested class is bounded by the scopeof its enclosing class. A nested class has access to the members, including private members,of the class in which it is nested. However, the enclosing class does not have access to themembers of the nested class. The access to the enclosing class’s scope is possible becausethe inner class actually has a hidden reference to the outer class context.There are two types of nested classes static and non-static. If a inner class is static, it mustaccess the members of its enclosing class through an object. That is, it cannot refer tomembers of its enclosing class directly.The most important type of nested class is thenon-static inner class. It has access to all of the variables and methods of its outer class and may refer to them directly in the same way thatother non-static members of the outer class do. Thus an inner class is fully within the scopeof its enclosing class.

    InnerClassExample.java/ / DEMONSTRATING NESTED CLASSESclass InnerClass{ int far_x=45;

     void plan(){ Inner inner=new Inner();

    inner.display();} class Inner{ void display()

    { System.out.println("Displaying : far_x : "+far_x);}

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

    { InnerClass ic=new InnerClass();ic.plan();

    }} 

  • 8/18/2019 Java Programming Part I

    33/120

    COALESCE

    32

    4.30.  Classes Defined Inside Methods

     Java allows a class to be defined inside a method. Any variable, either a local variable or aformal parameter, can be accessed by methods within an inner class, provided that variable ismarked final.  An object created inside a method is likely to outlive the method invocation.Since local variables and method arguments are conventionally destroyed with their method

    exits, these variables would be invalid for access by inner class methods after the enclosingmethod exits. By allowing access only to final variables, it becomes possible to copy the values of those variables into the object itself, thereby extending their lifetime.

    MOuter.java/ / CLASSES DEFINED INSIDE METHODSpublic class MOuter{ private int i=10;

    final int j=20;public static void main(String args[]){ MOuter that=new MOuter();

    that.go((int)(Math.random()*100),(int)(Math.random() * 100));}

    public void go(int x, final int y){ int a=x+y;

    final int b=x-y;class MInner{ public void method()

    { / / System.out.println(("X : "+x); / / IllegalSystem.out.println("Y : "+y);/ / System.out.println("a : "+a); / / IllegalSystem.out.println("b : "+b);System.out.println("i : "+i); / / accessibleSystem.out.println("j : "+j); / / accessible

    }} MInner that=new MInner();

    that.method();}}

    4.31.  Anonymous classes

    Some classes that you define inside a method do not need a name. A class defined in thisway without a name is an anonymous class.  In fact, they are defined in the place they areconstructed.public void amethod(){ theButton.addActionListener(new ActionLIstener()

    { public void actionPerformed(ActionEvent ae){ System.out.println(“Action performed”);}

    });

     An anonymous class cannot have a constructor. Since you do not specify a name for theclass, you cannot use the name to specify a constructor.

  • 8/18/2019 Java Programming Part I

    34/120

    COALESCE

    33

    4.32.  Addit ional Features of Anonymous Inner Classes

     An anonymous class can be a subclass of another explicit class, or it can implement a singleexplicit interface. An anonymous class cannot be both an explicit subclass and implementan interface.

    4.33.  Propert ies of Inner classes

    •  The class name can be used only within the defined scope.

    •  The inner class can also be defined inside a method generally known as anonymous class.•  The inner class can use both static and instance variables of enclosing classes and final

    local variables of enclosing blocks.•   An inner class can act as an interface implemented by another inner class.

    •  Inner classes that are declared static automatically become top-level classes.•  Inner classes cannot declare any static members; only top-level classes can declare static

    members.•  Public, private, static are all legal access modifiers for this inner class.

    •  Inner classes can extend any class or interface•  They can access all static, final and instance variables.

    4.34.  Collection API

     A collection is a single object representing a group of objects, known as its elements.The java programming language supports collection classes Vector, Bits, Stack, Hashtable,BitSet, LinkedList, and so on. For example, Stack implements a last-in-first-out (LIFO)sequence and Hashtable provides an associative array of objects.

    Collections maintain references to objects of type Object. This allows any object to bestored in the collection. It also necessitates the use of correct casting before you can use theobject, after retrieving it from the collection.

    The collection API typically consists of interfaces that maintain objects.Collection: A group of objects with no specific ordering.Set: A group of objects with no duplication.List: A group of ordered objects; duplicates are permitted.

    The API also contains classes, such as HashSet, and ArrayList, which implement these

    interfaces. The API also provides methods supporting some algorithms, such as sorting,binary searching, evaluating the minimum and maximum out of lists, and collections.

    4.35.  The Vector Class

    The vector class provides methods for working with dynamic arrays of varied element types.   Java.lang.Object 

     Java.util.AbstractCollection

  • 8/18/2019 Java Programming Part I

    35/120

    COALESCE

    34

     Java.util.AbstractList

     Java.util.Vector

    Public class Vector extends AbstractList Implements List, Cloneable, Serializable

    Each vector maintains a capacity and a capacityIncrement. As elements are added to a vector, storage for the vector increases, in chunks to the size of the capacityIncrement variable. The capacity of a vector is always at least as large the size of the vector (It is usuallylarger).

    Constructors:  public Vector()public Vector(int initialCapacity)public Vector(int initialCapacity, int capacityIncrement)

     Variables: The vector class contains the following instance variables.

    Protected int capacityIncrement – The size of the increment. (If 0, the size of the buffer isdoubled every time it needs to grow).Protected int elementCount – The number of elements in the buffer.Protected Object elementData[] – The buffer where elements are stored.

    Methods:  The following are some of the methods in the Vector class.

    public int size() – Returns the number of elements in the Vector. (This is not the same as the Vector capacity)

    public boolean contains(Object elem) – Returns true if the specified object is a value of thecollection.public int indexOf(Object elem)  – Searches for the specified object starting from the firstposition, and returns an index to it (or –1 if the element is not found). It uses the object’sequals() method, so if this object does not override Object’s equals() method, it comparesonly object references, not object contents.public synchronized Object elementAt(int index) – Returns the element at the specified index. Itthrows ArrayIndexOutOfBoundsException if index is invalid.public synchronized void setElementAt(int index) – Replaces the element at the specified indexwith the specified object. It throws ArrayIndexOutOfBoundsException if index is invalid.public synchronized void removeElementAt(int index) – Deletes the element at the specifiedindex. It throws ArrayIndexOutOfBoundsException if index is invalid.public synchronized void addElementAt(int index)  – Adds the specified object as the lastelement of the vector.public synchronized void insertElementAt(int index) – Inserts the specified object as an elementat the specified index, shifting up all elements with equal or greater index. It throws ArrayIndexOutOfBoundsException if index is invalid.

    MyVector.java/ / DEMONSTRATING VECTORSimport java.util.*;public class MyVector extends Vector

  • 8/18/2019 Java Programming Part I

    36/120

    COALESCE

    35

    { public MyVector(){ / / STORAGE CAPACITY AND CAPACITY INCREMENT

    super(1,1);} public void addInt(int i){ / / addElement requires object argument

    addElement(new Integer(i));

    } public void addFloat(float f){ addElement(new Float(f));} public void addString(String s){ addElement(s);} public void addCharArray(char a[]){ addElement(a);} public void printVector(){ Object o;

    / / compare with capacityint length=size();System.out.println("Number of vector elements is : "+length+" and they are ");for(int i=0;i

  • 8/18/2019 Java Programming Part I

    37/120

    COALESCE

    36

    5. Reflection APIThe reflection API is a safe secure API, which can be used for object introspection. We canfind out which class the object extends and what are the methods and variables etc. The API

    can be used to: 

    •  Construct new class instances and new arrays.

    •   Access and modify fields of objects and classes.•  Invoke methods ob objects and classes.•   Access and modify elements of arrays.

    These operations are possible only if the security policy permits them. The Reflection API isuseful in situations where you need to retrieve and manipulate information at runtime.

    The following are some of the core Reflection API, which defines classes and methods:

    • 

    The class java.lang.Class provides methods that provide information about a class and itsfields, constructors and methods•  The class java.lang.reflect.Field provides methods that set and get information about the

    fields in the class.•  The class java.lang.reflect.Method provides methods that access and call methods in the

    class, and get their signatures.•  The class java.lang.reflect.Array  enables an introspection of an array object.•  The class java.lang.reflect.Constructor  provides reflection access to constructors. 

    The Java Security Manager controls access to the core Reflection API on class-by-class basis.Standard Java programming language access control is enforced when:

    •   A Field is used to get or set a field value.•   A Method is used to invoke a method.•   A Constructor is used to create and initialize a new instance of a class.

    5.1. Object class

    This is one special class, called Object, defined by java. All other classes are subclasses ofobject. That is, object is a superclass of all other classes. This means that a reference variableof typeobject can refer to an object of any other class. Also, since arrays are implemented asclasses, a variable of type object can also refer to any array.

    Object defines the following methods:

    METHOD  PURPOSE 

    Object clone() Creates a new object that is the same as the object beingcloned.

    Boolean equals(Object object) Determines whether one object is equal to another.

  • 8/18/2019 Java Programming Part I

    38/120

    COALESCE

    37

     Void finalize() Called before an unused object is recycled.

    Class getClass() Obtains the class an object at run time.

    Int hashCode() Returns the hash code associated with the invoking object.

     Void notify() Resumes execution of a thread waiting on the invokingobject.

     Void notifyAll() Resumes execution of all threads waiting on the invokingobject.

    String toString() Returns a string that describes the object.

     Void wait()

     void wait(long milliseconds)

     void wait(long milliseconds,

    int nanoseconds)

    Waits on another thread for execution.

    The methods getClass(), notify(), notifyAll(), and wait() are declared as final.The other methods can be overridden. equals() methods compares the contents of twoobjects. ThetoString() method returns a string that contains a description of the object onwhich it was called. Also, this method is automatically called when an object is output usingprintln(). Many classes override this method.

    5.2. Abstract Classes

     Any class containing one or many abstract methods should also be declared abstract. Thekeyword abstract is used before the keyword class to declare a class as abstract. The abstract

    class cannot have objects of its own, i.e, it cannot be directly instantiated using the newoperator. Abstract constructors and abstract static methods also cannot be declared in aabstract class. Any subclass of an abstract class must either implement all the abstractmethods in the superclass, or it should be declared abstract.

    abstract class One

    { abstract void mine(); void mineonly(){ System.out.println("A Concrete method");}

    }class Two extends One{ void mine()

    { System.out.println("Implementation of mine by Two");}

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

    { Two t = new Two();t.mine();t.mineonly();

    }}

  • 8/18/2019 Java Programming Part I

    39/120

    COALESCE

    38

    6. Packages

     A package is a collection of related classes. Packages are containers for classes that are used

    to keep the class name space compartmentalized. Using interface, you can specify a set ofmethods, which can be implemented by one or more classes. The interface, itself, does notactually define any implementation.The package declaration, if any, must be at the beginning of the source file. You mustprecede it with white space and comments, but nothing else. Only one package declarationis permitted and it governs the entire source file.Packages and Interfaces are two of the basic components of a java program. A java programcan contain any of the following four parts.•   A single package statement (optional)•   Any number of import statements (optional)

    •   A single public class declaration (required)

    • 

     Any number of classes private to the package (optional)

    The package statement defines a namespace in which classes are stored. It is nothing but adirectory, in which a class is defined. When the package name is omitted, it is put into thedefault package, which has no name.

    6.1. Package DefaultPackage;

     Java uses file system directories to store packages. Any classes you declare to be part ofDefaultPackage must be stored in a directory called DefaultPackage. The case is significant,

    and thedirectory namemust match thepackagename exactly. More than one file can include thesame package statement. The package statement simply specifies to which package theclasses define belong.

    6.2. Classpath

    It is a environmental variable, which contains the path for the default-working directory(.).The specific location that java compiler will consider, as the root of any package hierarchy is,controlled byClasspath.

    To define a class calledMyPackage in a package called, Package the class MyPackageis defined in a directory called pack . When this program is compiled, the MyPackage.class 

    created is stored under the pack directory but it cannot be run from the same directory path,as it is no longer referred as MyPackage.Enumerating its package hierarchy, separating the packages with dots must refer the class. Itis because; the classpath is at the top of the class hierarchy. So, the file has to be run bychanging the current directory up by one level (parent directory), or add the top of yourdevelopment class hierarchy to the class path environmental variable. Then it is possible touse  java.Package.MyPackage from any directory.

    If the source code is in the directory called c:\ Infosys, then the classpath settingshould be 

  • 8/18/2019 Java Programming Part I

    40/120

    COALESCE

    39

    ...;c:\Infosys;c:\ java\ classes;.

     An inherited file cannot be compiled from the same directory. When a Subclass creates anobject for a superclass present in some other program file then, the Subclass cannot becompiled from the same directory as the compiler tries to access the class for which the

    object is being created in its child directory.

    PackageDemonstration.java/ / PACKAGES DEMONSTRATIONpackage abc;class Requirement{ String name;

    double balance;Requirement(String x, double y){ name=x;

    balance=y;} void show(){ if(balance

  • 8/18/2019 Java Programming Part I

    41/120

    COALESCE

    40

    Same package No Yes Yes YesSubclass

    Same package No Yes Yes Yesnon –subclass

    Different No Yes Yes Yespackagesubclass

    Different No No No YesPackagenon-subclass

     A class has only two possible access levels: default and public. When a class isdeclared as public, it is accessible by any other code. If a class has default access, then it can

    only be accessed by other code within its same package.

  • 8/18/2019 Java Programming Part I

    42/120

    COALESCE

    41

    7. Importing of PackagesTo use the functionality of a class A present in a package, by a class Bpresent in some otherpackage, the class A has to be imported by class B.

    There are no Java classes in the unnamed default package; all of the standard classes arestored in some named package. Since classes within packages must be fully qualified withtheir package name or names, it could become tedious to type in the long dot-separatedpackage path name for every class you want to use. In Java theimportstatement is utilized tobring certain classes.Ex: import java.util.*;

    import java.awt.event.* ;import javax.servlet.* ;import javax.swing.* ; 

    In the second example, AWT is the top-level package & the event is the sub-ordinatepackage inside the AWT package. While importing the packages each sub-ordinate package

    is separated from its base package by adotoperator.

    7.1. Classes versus Abstract class versus I nterface

    CLASS ABSTRACT CLASS INTERFACESpecifies the full set ofmethods for an object.

    Specifies the full set ofmethods for an object. 

    Specifies a subset ofmethods for an object.

    Implements all of itsmethods.

    Implements none, some orall of its methods.

    Implements none of itsmethods.

    Can have instances. Cannot have instances. Cannot have instances.Can have subclasses Useless without subclasses. It

    must have subclasses.

    Cannot have subclasses,

    must have classes thatimplement it. It is uselesswithout them.

    7.2. I nterfaces

     An interface is a set of predefined methods to be implemented by one or more classes infuture. An Interface will just give what the method should do, but it will not give theimplementation for it. This helps the programmer to write his own logic in his class, whichimplements the particular interface. The methods in an interface will have no body and it

     just mention the method signature.

    Interfaces are very similar to classes syntactically. Interfaces do not have any instance variables. Any variable declared in an interface is automatically taken as public, static andfinal. To implement an interface, a class must implement the complete set of methodsdeclared by the interface.

    It is through interfaces that Java achieves multiple inheritance. By providing the interface keyword, Java allows to fully utilize the “one interface, multiple methods” aspect ofpolymorphism. Interfaces are designed to support dynamic method resolution at run time.

  • 8/18/2019 Java Programming Part I

    43/120

    COALESCE

    42

    The general form of declaring an interface is as follows:access  classclassname [extends superclass ] implements interface[interface ]{ / / body}

    Implementing Interfaces

    By including theimplements clause in a class definition, we implement an interface.public class classname2 [extends classname1]

    [implements interface…] {  } 

    The methods that implement an interface must be declaredpublic. Also, the type signature ofthe implementing method must match exactly the type signature specified in the definitionof the interface.

     An interface is defined in the following way.

    Math.java

    public interface Math{

    public int Add(int a, int b);

    }

    Save the above defined interface as Math.java and compile the same.TestInterface.java/ / Class implementing the interface Math.public class TestInterface implements Math{

    public int Add(int a, int b){

    return(a+b);}public static void main(String args[]){

    int result;TestInterface ob = new TestInterface();result = ob.Add(20,22);System.out.println("The sum of 20 & 22 is :" + result);

    }}