JAVA. Object Oriented Programming with. M.T. Somashekara D.S.Guru K.S. Manjunatha

Size: px
Start display at page:

Download "JAVA. Object Oriented Programming with. M.T. Somashekara D.S.Guru K.S. Manjunatha"

Transcription

1 PH IL ea rn in g C op yr ig ht ed JAVA M at er ia l Object Oriented Programming with M.T. Somashekara D.S.Guru K.S. Manjunatha

2 Object Oriented Programming with JAVA M.T. SOMASHEKARA Department of Computer Science and Applications Bangalore University, Bengaluru D.S. GURU Department of Studies in Computer Science University of Mysore, Mysuru K.S. MANJUNATHA Department of Computer Science Maharani s Science College for Women, Mysuru Delhi

3 Foreword xv Preface xvii Acknowledgements xix v Contents 1. Introduction to Object Oriented Programming Paradigm Introduction Evolution of Higher Level Languages The General Topology of Object Based and Objects Oriented Language Complexity of Softwares and their Attributes Object Orientated Programming Paradigm Basic Principles of Object Oriented Programming Advantages of Object Oriented Programming Applications of Object Oriented Programming Object Oriented Programming Languages 13 Summary 13 Review Questions Introduction to the JAVA Language Introduction Evolution of Java Salient Features of Java Language Java, Internet and World Wide Web The Java Environment 19 Summary 20 Review Questions 20

4 vi Contents 3. The JAVA Language Preliminaries Introduction Keywords and Identifiers Constants Numeric Constants Character Constants Variables Data Types Console I/O Structure of a Java Program Sample Program Executing a Java Program Errors 32 Summary 33 Review Questions Operators and Expressions Introduction The Assignment Operator [=] The Arithmetic Operators [unary +, unary, +,, *, /, %] Types of Arithmetic Expressions Precedence of Arithmetic Operators and Associativity The Relational Operators [<, <=, >, >=, ==,!=] The Short Circuit Logical Operators [&&,,!] The Arithmetic Assignment Operators [+=, =, *=, /=, %=] The Increment/Decrement Operators [++, ] The Conditional Operator [?:] Nesting of Conditional Operators The InstanceOf() Operator The Dot Operator [.] The Bitwise Operators [&,, ^, ~, <<, >>, >>>] Application of Bitwise Operators Type Conversion Precedence Levels and Associativity among all the Operators 69 Summary 70 Review Questions 70 True/False Questions 73 Programming Exercises 73

5 Contents vii 5. Selection Introduction The Simple if Statement The If-Else Statement The Nested If-Else Statement The else-if Ladder The Switch Statement Nested Switch Statement 96 Summary 98 Review Questions 98 True/False Questions 99 Programming Exercises Iteration Introduction The while loop The for loop Variations of for Loop The Do-While loop Which Loop to Use When? Jumps in Loops Nesting of Loops Jumps in Nested Loops Labeled Loops 132 Summary 133 Review Questions 133 True/False Questions 134 Programming Exercises Classes, Objects and Methods Introduction Class Definition Instance Variables and Member Methods Declaration and Creation of Objects, Accessing Members Classification of Member Methods Constructors Constructors without Arguments Constructors with Arguments Copy Constructors The this Keyword Passing Objects to Methods as Arguments Methods Returning an Object 157

6 viii Contents 7.9 Static Member Data Static Member Methods Static Blocks Nesting of Member Methods Recursion Nested Classes Non-static Nested Classes or Inner Classes Static Nested Classes Local Classes Anonymous Classes Final Members Variable Arguments Objects of One Class as Instance Variables of Another Class (Containment) Garbage Collection and Finalise Method 189 Summary 189 Review Questions 190 True/False Questions 191 Programming Exercises Inheritance Introduction Types of Inheritance Single Level Inheritance Multilevel Inheritance Multiple Inheritance Hierarchical Inheritance Hybrid Inheritance Constructors and Inheritance Abstract Classes and Methods Dynamic Method Dispatch Object Slicing Object Typecasting The Final Keyword 230 Summary 231 Review Questions 232 True/False Questions 233 Programming Exercises Interfaces Introduction Defining Interfaces Implementing Interfaces 236

7 Contents ix 9.4 Polymorphism through Interfaces Implementing an Interface Partially Extending Interfaces Implementing Multiple Interfaces Multiple Inheritance through Interfaces 248 Summary 253 Review Questions 253 True/False Questions 254 Programming Exercises Packages Introduction Classification of Packages Creating and Using a Package To Create a Package Spread across Multiple Files Importing Classes from a Package (Hiding Classes in a Package) Nested Packages Extending Imported Classes Classes and Interfaces in a Package and Using Them Static Importing Access Control Private Access Default Access Protected Access Public Access 282 Summary 287 Review Questions 287 True/False Questions 287 Programming Exercises Arrays Introduction One-dimensional Arrays Multi-dimensional Arrays Two-dimensional Arrays (2-D arrays) Three-dimensional Arrays Arrays and Methods One-dimensional Arrays as Arguments to Methods Passing Two-dimensional Arrays to Methods Arrays within Class One-dimensional Array within Class Two-dimensional Array within Class 329

8 x Contents 11.6 Arrays of Objects 332 Summary 335 Review Questions 335 True/False Questions 336 Programming Exercises String Handling Introduction The String Class The Constructors of the String Class The Member Methods of the String Class The StringBuffer Class The Constructors of the StringBuffer Class The Member Methods of the StringBuffer Class 351 Summary 354 Review Questions 354 True/False Questions 355 Programming Exercises Exception Handling Introduction Types of Exceptions Built-in Exceptions Custom Exceptions Default Exception Handling Mechanism User-Defined Exception Handling Mechanism Single Try Block and Multiple Catch Blocks Catching Multiple Exceptions with a Single Catch Block Nested Try Blocks Stack Unwinding Chained Exceptions Throw Statement Throws Statement Finally Statement Try with Resources Statement Custom Exceptions 384 Summary 386 Review Questions 386 True/False Questions 387 Programming Exercises 387

9 Contents xi 14. Multithreaded Programming Introduction The Java Thread Model The Life Cycle of a Thread The Thread Class The Main Thread Creating Our Own Threads Extending the Thread Class Implementing Runnable Interface Creating Multiple Children Threads Forming Groups of Threads Thread Priorities Synchronisation Synchronised Method The Synchronised Statement Deadlock Suspending and Resuming Threads Producer-Consumer Relationship between Threads Daemon Threads 433 Summary 435 Review Questions 436 True/False Questions 436 Programming Exercises File Handling Introduction The File Class I/O Stream Classes Related to File Handling The Character Stream Classes The Byte Stream Classes Mixed Data I/O Streams Object I/O Streams Random Access File 469 Summary 470 Review Questions 471 True/False Questions 472 Programming Exercises Applets Introduction Types of Applets 474

10 xii Contents 16.3 The Life Cycle of an Applet Creating and Executing an Applet The Attributes in the <applet> Tag Passing Parameters to Applets 484 Summary 492 Review Questions 493 True/False Questions 493 Programming Exercises Introduction to AWT Introduction AWT Hierarchy Event Handling AWT Controls Labels Buttons Checkbox CheckboxGroup Lists Choice Control Scrollbar Control TextField TextArea Layout Managers Flow Layout Border Layout Grid Layout Card Layout GridbagLayout Panels AWT Window-Level Controls Windows Handling Keyboard Events Handling Mouse Events Handling Events with Specialised Classes Handling MouseEvents through MouseAdapter Class Inner Classes Anonymous Inner Classes 549 Summary 551 Review Questions 552 True/False Questions 552 Programming Exercises 553

11 Contents xiii 18. Basic Utility Classes [java.lang Package] Introduction The Wrapper Classes The Number Class The Byte Class The Short Class The Integer Class The Long Class The Float Class The Double Class The Character Class The Boolean Class The System Class The Object Class The Class Class The Runtime Class The Process Class The Void class The Math Class 579 Summary 581 Review Questions 581 True/False Questions 582 Bibliography Index

12 Foreword Computer programming has evolved over the last six decades, starting from assembly language programming and progressing through simple procedural languages, block structured procedural languages, object oriented languages, functional languages, and scripting languages. Each evolution was started by the prevailing hardware and the demand for applications. One major evolution was the emergence of object oriented languages, which were later adapted to be applicable in this era of the Internet in which diverse computers distributed all over the world are interconnected. Java, which was initially developed as a small object oriented language to program embedded systems, evolved as a general purpose programming language to meet the needs of programmers who were required to write programs which could be executed on the Internet. Currently, Java is the programming language of choice in many industries, particularly those involved in creating large-scale applications using the Internet. This book by Dr. M.T. Somashekara, Dr. D.S. Guru, and Mr. K.S. Manjunatha is a very useful addition to the library of books on Java programming. The main merit of this book is that it starts from basics and builds gradually to a substantially high level to enable students to write programs for Internet applications. All important concepts are illustrated with Java programs, an important pedagogical tool. The book is well written with a number of learning aids such as summary, review questions, true-false questions, and programming exercises. This book has been classroom tested by the experienced authors Dr. Somashekara, Dr. Guru, and Mr. Manjunatha. The book is suitable for the undergraduate students of Computer Science. I am sure students as well as working professionals will find this book an invaluable aid in learning how to program using Java. xv V. Rajaraman Indian Institute of Science Bengaluru

13 Preface The Java language is a general purpose and a purely object oriented language invented by a group of computer scientists at Sun Micro Systems during 1990s to meet the varied needs of embedded world. The fascinating and principal features of the language such as object oriented, platform independence, architectural neutral, robust and security were needed to support the development of embedded software for various electronic devices like TVs, refrigerators, etc. Incidentally the same features were required to be supported for computing in the internet world and also considering the heterogeneous nature of the computing devices employed in the internet world. As a result, the Java language became very close to the internet computing world. Because of its affinity to the internet, the language is referred to as the language of the internet. The book is expected to cater to the needs of both undergraduate and postgraduate students of Computer Science and Information Technology offered by Indian universities because the contents of the book has been developed after paying due attention to the syllabi of various Indian universities. Another hallmark of the book is that it needs no previous knowledge of programming. The book takes the reader from the basic principles of Java programming towards advanced aspects like exception handling, multithreading, IO streams, etc. in an incremental fashion. The readers will, no doubt, experience comfort while assimilating the concepts and programming using them. The book has been organised in well-planned 18 chapters. Chapter 1 introduces the object oriented paradigm, its advantages and disadvantages; identifies the languages supporting the object oriented paradigm; and also sets the tone for learning the Java language. Chapter 2 highlights the importance of the Java language by discussing the striking features offered by it to align itself to support platform independence and thereby finding a predominant place in the internet programming. Chapter 3 talks about the preliminaries of the Java language. Chapter 4 discusses the operators supported by the Java language with suitable illustrations for each kind of operators. Chapter 5 throws light on the selection structures supported by xvii

14 xviii Preface Java with examples and programs for each variation of the structures. Chapter 6 throws light on the iterative structures supported by Java with examples and programs for each variation of the structures. Chapter 7 introduces the concepts of classes, objects and methods, the core concepts underlying the object oriented programming. Chapter 8 discusses another important feature of OOP, the concept of inheritance in detail. Chapter 9 deals with the concept of interfaces. Chapter 10 deals with the concept of packages, wherein we can logically group classes and interfaces depending on the requirement. The concept of packages enables us to compartmentalise the classes and interfaces for better management of them. Chapter 11 delves into the concept of arrays in detail. Here arrays of one dimension, two dimensions, three dimensions and array of objects, and methods with arrays are explained in detail. Chapter 12 details string handling in Java. The detailed discussion includes various string manipulation methods available in the String class and also the String buffer class. Chapter 13 delves into exception handling mechanism supported by Java. It also discusses types of exceptions and the ways they are handled. Chapter 14 focuses on multithreaded programming, which is one of the striking features of Java supporting optimisation of the systems resources and enhancement of the speed of execution of programs. Chapter 15 provides a thorough discuss on IO-Streams and their handling with the help of the built-in classes and their methods. Chapter 16 turns our attention towards applets, a special category of programs that are developed in Java and their relationship to web programming. Chapter 17 deals with the graphical user interface facility provided by Java through a group of classes embodied in a toolkit called AWT toolkit. The toolkit contains a number of classes each representing a type of window control used in the design of the graphical user interface. Chapter 18 details most of the commonly used utility classes housed in the java.lang package which are used frequently while developing applications with Java. Almost all the chapters are followed by a brief summary of the concepts covered to better enable the readers to consolidate their learning, review questions, true-false questions and programming exercises. Constructive criticism and suggestions from the readers are always welcome. They will go a long way in further improvement of the book. In fact, this is how the knowledge and the book grow. You may kindly reach us at somashekar_mt@hotmail.com or dsguruji@yahoo.com or kowshik.manjunath@gmail.com with your feedback. M.T. Somashekara D.S. Guru K.S. Manjunatha

15 INTRODUCTION Applets All the Java programs developed so far in the previous chapters are called application programs developed for the purpose of accomplishing a task. There is another type of programs which can be developed using Java. They are called applets that run on WWW. The applets are small Java programs written for the purpose of accomplishing a part of a task. The applets reside in web pages in the WWW and they are executed by the web browsers when the web pages containing them are loaded in the client systems. They are capable of displaying graphics, playing audio, etc. In all, the applets enable the Java programmers to provide the right graphical user interface. As we have noticed, the Java applications are characterised by the following features: 1. They are normally programs of bigger size. 2. They have main() method, from where the execution of the program starts. 3. The Java applications are run by the Java interpreter. 4. The Java applications are standalone programs as they can be executed directly by launching them. 5. They can access the files and other resources at the local system, where they are launched for execution. 6. They advocate character user interface. Because of the association of the Java language with the internet and ability to contribute to the internet application developers and the users powered by its inherent features, one more kind of Java programs originated are called applets. Following are the features of Applets which are different from the Java applications: 1. Applets are tiny programs. 2. Applets do not have main() method. They must be embedded in a web program to run them. 473

16 474 Object Oriented Programming with JAVA 3. Applets are run by Java enabled browsers and appletviewer tool shipped with the JDK. 4. They advocate graphical user interface. 5. Applets are web based programs TYPES OF APPLETS The applets can be classified into two types depending on where they originate from. They are (i) Local applets and (ii) Remote applets. Local applets, as the name itself indicates, are those that are created at the local system and they can be run in the system. Remote applets are those that are created in the remote systems and downloadable from the remote systems to the local systems and they can be run. As there are chances of security violations by the applets, certain restrictions are imposed on applets in the interest of the security of the systems. They are the following: 1. They cannot access the files and other resources at the local system for security reasons. 2. They cannot communicate with other servers in the network. 3. They cannot execute other programs. 4. They can not invoke routines of other languages like C, C++. The Applet class in the Java.applet package hierarchy is central to implementing the applets. The Java.applet.Applet class extends the Java.awt.panel class, the Java.awt.Container class, the Java.awt.Component class and the Java.lang.Object class in a multilevel hierarchy. The hierarchy is depicted in Figure Applet class inheritance hierarchy. The most commonly used methods in the Applet class are given in Table 16.1 and important methods of the component class are given in Table 16.2.

17 Applets 475 Methods in the Applet class void init() void start() void stop() void destroy() Method with signature AppletContext getappletcontext() String getappletinfo() AudioClip getaudioclip(url url) URL getcodebase() URL getdocumentbase() Image getimage(url url) Image getimage(url url, String imagename) String getparameter(string param) void play(url url) void play(url url, String clipname) Purpose Begins the execution of the applet. This is the first method called on an applet. Starts the executing the applet. Gets called automatically when init() is called. It also called to resume the applet s execution if the applet had been stopped earlier. Stops the applet temporarily. Informs the applet to destroy itself after releasing the resources used by it. Returns the context associated with the applet. Returns a string that describes the applet. Returns an AudioClip object for the audio clip found at the location identified by URL. Returns the URL associated with the applet. Returns the URL of the html document of the applet. Returns an Image object for the image found at the location identified by url. Returns an Image object for the image found at the location identified by url and with the same name as imagename. Returns the parameter associated with the name param. Returns null if the parameter is not found. Plays an audio clip found at the location identified by url. Plays the audio clip found at the location identified by url and having the name clipname. void resize(dimension d) Resizes the applet according to the dimension d. void showstatus(string str) Displays the string str in the status window of the browser or the appletviewer. No action takes place if the browser or the appletviewer does not support a status window. Methods of the Component class Component class void paint(graphics g) void update(graphics g) void repaint() void setbackground(colour bcolour) Purpose Draws text or graphics on the screen. Fills the screen with the background colour and calls the paint() method. Schedules call to the update() method. Sets the background colour of the component with bcolour. (Contd...)

18 476 Object Oriented Programming with JAVA Methods of the Component class (Contd...) Component class void setforeground(colour fcolor) Purpose Sets the foreground colour of the component with fcolour. synchronised void setfont(font f) Sets the font of the component with the font f. Font getfont() void setsize(dimension d) void setsize(int width, int height) Dimension getsize() Retrieves the font of the component. Sets the size of the component with the dimension d. The Dimension class has width and height as the data members. Sets the size of the component with the given width and height. Retrieves the size of the component THE LIFE CYCLE OF AN APPLET An applet goes through a number of states from the point of its creation to the point of destruction. They are: 1. Initialization state 2. Running state 3. Idle state or stopped state 4. Dead state The life cycle of an Applet is shown in Figure Initialisation State Life cycle of an applet. When an applet is loaded into memory of the client machine by the web browser or the appletviewer, the init() method of the applet of the Applet class is invoked. The execution of the init() method brings the applet to the initialisation state. During the initialisation state, we can initialise the required variables, create the required objects, load the required images and fonts and set the required colours, etc. An applet assumes the initialisation state only once in its life cycle. The initialisation behaviour of an applet can be realised by overriding the init() method of the Applet class as follows:

19 Applets 477 void init() { // code for the expected behaviour here } Running State After the initialisation state, the start() method of the Applet class is invoked automatically. Then the applet is said to have moved to the running state. The start() method also gets invoked on the resumption of the execution of an applet automatically when the applet had been stopped for a while (when we leave a web page temporarily and return back to the same web page). We may override the start() method also of the Applet class to alter the course of action of the applet as follows: void start() { // code for the expected behaviour here }` Soon after the applet moves into the running state, the applet s paint() method gets executed which displays the outputs in a window of the applet on the screen. Idle State An applet enters into the idle state when its execution is stopped temporarily. Stopping the execution of the applet can be done by leaving the web page containing the applet temporarily or invoking the stop() method on the applet explicitly. An applet in the idle state can be brought back to running state by bringing the web page containing the applet into focus or by calling the start() method on the applet explicitly. In essence, an applet can switch from idle state to running state and vice-versa many times. Dead State An applet enters into dead state when the web browser or the appletviewer invokes the destroy() method on the applet. The dead state is the final state of an applet. Normally the destroy() method does not need to be overridden to reclaim the resources used by the applets as the Java has a built-in mechanism called garbage collector to do the job. However, if an applet has created threads, the destroy() is overridden to release them. The overridden destroy() method takes care of the expected behaviour has the following form: void destroy() { // code for the expected behaviour here }

20 478 Object Oriented Programming with JAVA Painting The process of displaying of outputs on the window of an applet is accomplished by paint() method of the Applet class. In fact, the paint()in the Applet class method does nothing. It needs to be overridden to display the required text, graphics on the window of the applet. It gets called automatically whenever the applet gets into the running state. It also gets called when the window of the applet is resized or when the window is moved from one location to another location. The overridden paint() method takes the form as: void paint(graphics g) { // painting code here } Note that the paint() method is the only method which takes an argument. Here the argument is of type Graphics class. The package Java.awt which contains the class should be imported into the program CREATING AND EXECUTING AN APPLET There are four steps involved in creating and executing an applet. They are: 1. Creating a Java source file for the applet (.java file ) 2. Compiling the Java source file to get the equivalent class file (.class file) 3. Creating an html file 4. Executing the applet Let us now follow these steps to create a simple applet and execute it. Creating a Java source file for the applet (.java file ) Here we create the Java source file namely AppletDemo.Java and write in it the required Java code for an applet. Creating the AppletDemo.Java file import Java.awt.*; import Java.applet.*; public class AppletDemo extends Applet { public void paint(graphics g) { g.drawstring( First Applet, 100, 100); } }

21 Applets 479 The classes in the packages Java.awt and Java.applet are imported with the statements import Java.awt.*; and import Java.applet.*;. The public class AppletDemo extends the class Applet and it overrides the paint() method. Note that the method paint() takes an object of type Graphics as its argument and in the body of the method, the drawstring() method of the Graphics class is invoked to display the string First Applet at the position 75, 75 in the window of the applet. Compiling the Java source file We compile the Java source file AppletDemo.java using the Java compiler Javac: Javac AppletDemo.Java [return] The class file AppletDemo.class is created on successful compilation of the source file AppletDemo.Java. Creating an html file Here we create an html file with the same name as that of the class for the applet in the Java source code with the extension.html. So the html file being created is AppletDemo.html. The AppletDemo.html file <html> <head> <body> <applet code = AppletDemo.class width = 50 height = 50> </applet> </body> </head> </html> Executing the applet Here we use the appletviewer tool of the JDK to run the applet. Note that the input to the appletviewer is the html file. appletviewer AppletDemo.html [return] The applet window appears as below on its execution.

22 480 Object Oriented Programming with JAVA Output We can even embed the applet tag within the Java source file itself and make it a comment and compile the source file using javac compiler and the program can also be run using the Java tool appletviewer. The argument to the appletviewer is the Java source file itself. Let us modify the AppletDemo.Java to have the applet tag as a comment and compile it using Javac and execute it using the Java tool appletviewer. // AppletDemo1.Java PROGRAM 16.1 To illustrate an applet import Java.awt.*; import Java.applet.*; /* <applet code = AppletDemo1.class width = 300 height = 300 align = top> </applet> */ public class AppletDemo1 extends Applet { public void paint(graphics g) { g.drawstring( First Applet, 125, 150); } }

23 Applets 481 Compiling AppletDemo.Java Javac AppletDemo1.Java [return] After successful compilation, we will run it using the Java interpreter as given below: Running the applet Appletviewer AppletDemo1.Java Output // AppletDemo2.Java PROGRAM 16.2 To illustrate an applet import Java.awt.*; import Java.applet.*; /* <applet code = AppletDemo2.class Height = 200 width = 200> </applet> */ public class AppletDemo2 extends Applet { public void paint(graphics g) { int length, breadth;

24 482 Object Oriented Programming with JAVA length = 10; breadth = 5; } } int area = length * breadth; String str1 = Length = + String.valueOf(length); String str2 = Breadth = + String.valueOf(breadth); String str3 = Area = + String.valueOf(area); String str = Area = + String.valueOf(area); g.drawstring(str1, 50, 60); g.drawstring(str2, 50, 75); g.drawstring(str3, 50, 100); Compiling the AppletDemo2.Java Javac AppletDemo2.Java [return] Running the applet Output Appletviewer AppletDemo2.Java [return]

25 Applets THE ATTRIBUTES IN THE <APPLET> TAG Table 16.3 contains the attributes of the applet tag and their purposes. Attributes of the applet tag and their purposes Attribute CODEBASE = codebase_url (Optional) CODE = AppletFilename.class WIDTH = pixels HEIGHT = pixels NAME = instance name of the applet (Optional) ALIGN = alignment (Optional) HSPACE = pixels (Optional) Purpose Specifies the URL of the directory where the applet resides. If the applet and the html file reside in the same directory, then the codebase attribute may be omitted. Specifies the name of the applet class file and it should be specified. Specifies the width of the applet window. Specifies the height of the applet window. A name may be specified for an applet to identify it. Naming of applets is useful in case of inter-applet communication. Specifies the position of the applet on the webpage. This attribute can take any of the following values: TOP, BOTTOM, LEFT, RIGHT, MIDDLE, ABSMIDDLE, ABSBOTTOM, TEXTTOP, BASELINE Specifies the amount of horizontal space surrounding the applet. This is used only when the attribute ALIGN is set to either LEFT or RIGHT. VSPACE = pixels (Optional) Specifies the amount of vertical space surrounding the applet. This is used only when the attribute ALIGN is set to either TOP or BOTTOM. ALT = alternate text (Optional) Non-Java browsers will display this text. The syntax of the <APPLET> tag in its full form is as follows: <APPLET [CODEBASE = codebase_url] CODE = AppletFileaname.class [ALT = alternate text] [NAME = instance name of the applet] WIDTH = pixels HEIGHT = pixels [ALIGN = alignment] [VSPACE = pixels] [HSPACE = pixels] > [ <PARAM NAME = param1 VALUE = value1> ] [ <PARAM NAME = param2 VALUE = value2> ] </APPLET>

26 INTRODUCTION Introduction to AWT One of the notable things of the Java programming language is its ability to support graphical user interface (GUI). We have already seen the usage of the GUI elements like textboxes, buttons, labels, etc. that are used in applets in the previous chapter. These are user friendy as they offer ease of use and flexibility to interact with the applets. A separate package namely java.awt is dedicated for the purpose of encapsulating the facility of GUI elements like labels, buttons, textfields, scrollbars, lists, choices, etc. Each of these controls is implemented with the help of a separate dedicated class. All these classes are held in the java.awt package. The AWT facility uses the native GUI support of the system. It provides an abstraction of the native GUI and thus offers flexibility to the programmers shielding the internal details of the native GUI. The package java.awt should invariably be imported into the program which uses any of the classes in it AWT HIERARCHY The AWT hierarchy comprises of a number of classes useful for creating and using the AWT controls like Labels, TextField, TextArea, List, Choice, Window, Frame, Dialog, etc. The Figure 17.1 depicts the hierarchy of the classes for the AWT components. Component Component is the super class for all the classes related to AWT components. It represents an object having graphical representation that can be displayed on the screen and the user can interact with it. It has a number of methods for various operations like event handling, managing graphics, dealing with size of the component, etc. Labels, Buttons, Choices and Lists are all examples of components. 495

27 496 Object Oriented Programming with JAVA Container AWT window hierarchy. A Container is a component which can hold other components. Examples of Containers in the GUI are Frames, Dialogs, Windows and Panels. All these are inherited from the Container class. All the other components are discussed in detail in the sections to follow: 17.3 EVENT HANDLING Central to interaction with the GUI elements used by Java applets and Java applications are handling the events generated by the GUI elements. An event is defined to be a change in the state of an object. The object which generates the events is called the event source. Examples for event sources include the input devices such as keyboard, and mouse. The event sources also include all the AWT controls like Button, TextField, List, Choice, Scrollbar, etc. In the section to follow, we delve into the details of all the events and their sources. The Delegation Event Model The delegation event model is the modern and sophisticated approach towards handling events generated by different sources. Here the sources are registered with predefined interfaces designated as event listeners, which embody the signatures of the methods responsible for handling the events. The events handling is delegated to classes, which provide the implementation for the methods. Hence here we see a clean separation between the events sources and the event handlers. Event source is registered with event listener implemented by event handler. Registering an event listener for an event source is done with the method: void addeventlistener(eventlistener el) We can even unregister an event listener, if need be. Unregistering an event listener for an event source is done with the method:

28 497 void removeeventlistener(eventlistener el) The event handler class has the following form: class classname implements EventListener { Methods for handling the events } Let us now get to know the participants in the delegation event model which play their roles in handling events in a clean and efficient way. The participants include event classes, events, event listeners and event handling methods. Table 17.1 shows the list of events and the situations in which the events are generated. Name of the event class and situation in which the event is generated Name of the event class ActionEvent AdjustmentEvent ComponentEvent ContainerEvent FocusEvent InputEvent ItemEvent KeyEvent MouseEvent TextEvent WindowEvent Events and Event Listeners Situations in which the event is generated Whenever a menu item is selected or ENTER key is pressed, a list item is double-clicked in a TextField or in a TextArea Whenever a scrollbar is manipulated Whenever a component is hidden, moved, resized and made visible Whenever a component is added or removed from a container Whenever a component gains or losses keyboard focus Whenever a mouse event or key event occurs Whenever a checkbox is checked, an item in a list control is selected, a choice control is selected, and a checkable menu item is selected or deselected Whenever input from the keyboard is accepted Whenever the mouse is dragged, moved, pressed, released and when the mouse enters or leaves a component Whenever the content in a TextField or a TextArea is changed Whenever a window is activated, deactivated, iconified, deiconified, opened or closed Each event is associated with its corresponding listener. Table 17.2 shows the list of events and the corresponding event listeners. Events and event listeners Events ActionEvent AdjustmentEvent ComponentEvent ContainerEvent Event listeners ActionListener AdjustmentListener ComponentListener ContainerListener (Contd...)

29 498 Object Oriented Programming with JAVA FocusEvent ItemEvent KeyEvent MouseEvent TextEvent WindowEvent Events and event listeners Events Event listeners FocusListener ItemListener KeyListener MouseListener TextListener WindowListener Each event is associated with one or more methods for handling the event. Table 17.3 shows the list of events and the corresponding event handling methods. ActionEvent AdjustmentEvent ComponentEvent ContainerEvent FocusEvent ItemEvent KeyEvent MouseEvent TextEvent Events and event handling methods Events Event handling methods actionperformed() adjustmentvaluechanged() componenthidden() componentmoved() componentresized() componentshown() componentadded() componentremoved() focusgained() focuslost() itemstatechanged() keypressed() keyreleased() keytyped() MouseClicked() MouseEntered() MouseExited() MousePressed() MouseReleased() MouseDragged() MouseMoved() textvaluechanged() WindowEvent windowactivated() windowclosed() windowclosing() windowdeactivated() windowiconified() windowdeiconified() windowopened()

30 AWT CONTROLS The AWT controls that can be placed on the containers like Labels, Buttons, TextFields, etc. are discussed with the supporting programs in detail here Labels A Label is a control used for holding a static text. It is usually placed before a control which can hold text that can be changed, for instance a TextField. For example, a label with the text Name: is placed before a TextField which is meant for receiving a string for the name of a person from a user. Following are the constructors of the Label class which may be used for creating a label: Label() Creates a label with no string assigned to it. Label(String s) Creates a label with the string s assigned to it. Label(String s, int align) Creates a label with the string s assigned to it and also sets the alignment of the string within the label through the argument of int type align. The possible values that can be taken by the int argument align are LEFT, RIGHT and CENTRE to indicate that the string in the label be left justified, right justified and be centred respectively. The following are the other methods in the Label class which are used to write and read the text value and the alignment value of a label: void settext(string s) Sets the text of a label with the string s. String gettext() Retrieves the text of a label. void setalignment(int align) Sets the alignment of the text within a label. int getalign() Returns the alignment of the text in a label. The program 17.1 illustrates the usage of a label. The code for the applet to be created to demonstrate Label control is provided in the class LabelDemo in the program. PROGRAM 17.1 To illustrate Label control import java.awt.*; import java.applet.*;

31 18 Basic Utility Classes [java.lang Package] 18.1 INTRODUCTION The java.lang package houses a number of classes that are of importance. Here we discuss some of the most frequently used classes and their methods in a reasonable detail THE WRAPPER CLASSES A Wrapper class is one which wraps a primitive type within it. As there are eight primitive types in Java, there are eight wrapper classes, one for each primitive type. They are Byte, Short, Integer, Long, Float, Double, Character and Boolean for the primitive types byte, short, int, long, float, double, char and boolean respectively. The wrapper classes provide the ability to create object representations to the primitive types. The objects of wrapper classes are immutable, i.e., the values assigned to the objects cannot be altered The Number Class The Number class is the abstract class which is used as the super class for all the wrapper classes. Table 18.1 shows the list of abstract methods available in the class which are to be implemented by the wrapper classes. Methods with their signature and purpose Methods with their signature byte bytevalue() short shortvalue() Purpose Returns the value of the specified number as a byte Returns the value of the specified number as a short value (Contd...) 555

32 572 Object Oriented Programming with JAVA Boolean(String str) Creates an object of Boolean class wrapping the boolean value extracted out of the argument str of String type. Example 2: Boolean bt = new Boolaen( false ); Creates the object bt of Boolean type with the boolean value false. Table 18.9 depicts the methods of the s class. Methods boolean booleanvalue() boolean equals(object bool) String tostring() Static boolean valueof(string bool) Purposes Returns the Boolean value equivalent Returns true if the invoking object is equivalent to the object bool, otherwise, it returns false Returns the string equivalent of the invoking object Returns true if the string bool contains the string either true or TRUE, otherwise it returns false The following program illustrates the Boolean class by displaying the values of the constants Boolean.TRUE, Boolean.FALSE and Boolean.TYPE to be true, false and Boolean respectively. PROGRAM To illustrate Boolean class Output public class Boolean1 { public static void main(string s[]) { System.out.println( Boolean.TRUE = + Boolean.TRUE); System.out.println( Boolean.FALSE = + Boolean.FALSE); System.out.println( Boolean.TYPE = + Boolean.TYPE); } } Boolean.TRUE = True Boolean.FALSE = False Boolean.TYPE = Boolean 18.3 THE SYSTEM CLASS The System class is at the core of the java.lang package. It holds a number of static member methods and variables. The standard input, output and error of the Java runtime are stored

33 579 } Output } System.out.println( Total Memory = + tm); System.out.println( Free Memory = + fm); System.out.println( Used Space = + (tm - fm)); System.out.println( Maximum Memory = + mm); System.out.println(); Total Memory = Free Memory = Used Space = Maximum Memory = THE PROCESS CLASS The Process class is an abstract class in the java.lang package. It encapsulates a process, which is a program in the status of execution. The class process acts as a super class for the objects created by the method exec() in the Runtime class of the same Java package. The Process class contains a number of abstract methods. Following are the frequently used methods of the Process class (Table 18.14). void destroy() int exitvalue() Methods InputStream getinputstream() OutputStream getoutputstream() InputStream geterrorstream() 18.8 THE VOID CLASS Purposes Terminates the process Returns the exit code obtained from a subprocess Returns an input stream that reads input from the out output stream of the process Returns an output stream that writes output to the in input stream of the process Returns an input stream that reads input from the err output stream of the process The Void class has one field namely TYPE, which holds a reference to the Class instance for the primitive type void. The Void class cannot be instantiated THE MATH CLASS The Math class provides a number of static methods which are used for performing various mathematical operations. Table 18.5 furnishes the commonly used ones.

GUI Event Handling 11. GUI Event Handling. Objectives. What is an Event? Hierarchical Model (JDK1.0) Delegation Model (JDK1.1)

GUI Event Handling 11. GUI Event Handling. Objectives. What is an Event? Hierarchical Model (JDK1.0) Delegation Model (JDK1.1) Objectives Write code to handle events that occur in a GUI 11 GUI Event Handling Describe the concept of adapter classes, including how and when to use them Determine the user action that originated the

More information

Contents. iii Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services August 1998, Revision B

Contents. iii Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services August 1998, Revision B Contents About the Course...xv Course Overview... xvi Course Map... xvii Module-by-Module Overview... xviii Course Objectives... xxii Skills Gained by Module... xxiii Guidelines for Module Pacing... xxiv

More information

Advanced Java Programming (17625) Event Handling. 20 Marks

Advanced Java Programming (17625) Event Handling. 20 Marks Advanced Java Programming (17625) Event Handling 20 Marks Specific Objectives To write event driven programs using the delegation event model. To write programs using adapter classes & the inner classes.

More information

Table of Contents. Chapter 1 Getting Started with Java SE 7 1. Chapter 2 Exploring Class Members in Java 15. iii. Introduction of Java SE 7...

Table of Contents. Chapter 1 Getting Started with Java SE 7 1. Chapter 2 Exploring Class Members in Java 15. iii. Introduction of Java SE 7... Table of Contents Chapter 1 Getting Started with Java SE 7 1 Introduction of Java SE 7... 2 Exploring the Features of Java... 3 Exploring Features of Java SE 7... 4 Introducing Java Environment... 5 Explaining

More information

CONTENTS. Chapter 1 Getting Started with Java SE 6 1. Chapter 2 Exploring Variables, Data Types, Operators and Arrays 13

CONTENTS. Chapter 1 Getting Started with Java SE 6 1. Chapter 2 Exploring Variables, Data Types, Operators and Arrays 13 CONTENTS Chapter 1 Getting Started with Java SE 6 1 Introduction of Java SE 6... 3 Desktop Improvements... 3 Core Improvements... 4 Getting and Installing Java... 5 A Simple Java Program... 10 Compiling

More information

UNIT-3 : MULTI THREADED PROGRAMMING, EVENT HANDLING. A Multithreaded program contains two or more parts that can run concurrently.

UNIT-3 : MULTI THREADED PROGRAMMING, EVENT HANDLING. A Multithreaded program contains two or more parts that can run concurrently. UNIT-3 : MULTI THREADED PROGRAMMING, EVENT HANDLING 1. What are Threads? A thread is a single path of execution of code in a program. A Multithreaded program contains two or more parts that can run concurrently.

More information

Unit 1- Java Applets. Applet Programming. Local Applet and Remote Applet ** Applet and Application

Unit 1- Java Applets. Applet Programming. Local Applet and Remote Applet ** Applet and Application Applet Programming Applets are small Java applications that can be accessed on an Internet server, transported over Internet, and can be automatically installed and run as a part of a web document. An

More information

Syllabus & Curriculum for Certificate Course in Java. CALL: , for Queries

Syllabus & Curriculum for Certificate Course in Java. CALL: , for Queries 1 CONTENTS 1. Introduction to Java 2. Holding Data 3. Controllin g the f l o w 4. Object Oriented Programming Concepts 5. Inheritance & Packaging 6. Handling Error/Exceptions 7. Handling Strings 8. Threads

More information

The AWT Event Model 9

The AWT Event Model 9 The AWT Event Model 9 Course Map This module covers the event-based GUI user input mechanism. Getting Started The Java Programming Language Basics Identifiers, Keywords, and Types Expressions and Flow

More information

Core JAVA Training Syllabus FEE: RS. 8000/-

Core JAVA Training Syllabus FEE: RS. 8000/- About JAVA Java is a high-level programming language, developed by James Gosling at Sun Microsystems as a core component of the Java platform. Java follows the "write once, run anywhere" concept, as it

More information

11/7/12. Discussion of Roulette Assignment. Objectives. Compiler s Names of Classes. GUI Review. Window Events

11/7/12. Discussion of Roulette Assignment. Objectives. Compiler s Names of Classes. GUI Review. Window Events Objectives Event Handling Animation Discussion of Roulette Assignment How easy/difficult to refactor for extensibility? Was it easier to add to your refactored code? Ø What would your refactored classes

More information

SIMPLE APPLET PROGRAM

SIMPLE APPLET PROGRAM APPLETS Applets are small applications that are accessed on Internet Server, transported over Internet, automatically installed and run as a part of web- browser Applet Basics : - All applets are subclasses

More information

Core Java SYLLABUS COVERAGE SYLLABUS IN DETAILS

Core Java SYLLABUS COVERAGE SYLLABUS IN DETAILS Core Java SYLLABUS COVERAGE Introduction. OOPS Package Exception Handling. Multithreading Applet, AWT, Event Handling Using NetBean, Ecllipse. Input Output Streams, Serialization Networking Collection

More information

Java Fundamentals p. 1 The Origins of Java p. 2 How Java Relates to C and C++ p. 3 How Java Relates to C# p. 4 Java's Contribution to the Internet p.

Java Fundamentals p. 1 The Origins of Java p. 2 How Java Relates to C and C++ p. 3 How Java Relates to C# p. 4 Java's Contribution to the Internet p. Preface p. xix Java Fundamentals p. 1 The Origins of Java p. 2 How Java Relates to C and C++ p. 3 How Java Relates to C# p. 4 Java's Contribution to the Internet p. 5 Java Applets and Applications p. 5

More information

SCHEME OF COURSE WORK

SCHEME OF COURSE WORK SCHEME OF COURSE WORK Course Details: Course Title Object oriented programming through JAVA Course Code 15CT1109 L T P C : 3 0 0 3 Program: B.Tech. Specialization: Information Technology Semester IV Prerequisites

More information

Introduction to Programming Using Java (98-388)

Introduction to Programming Using Java (98-388) Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;

More information

Introduction... xv SECTION 1: DEVELOPING DESKTOP APPLICATIONS USING JAVA Chapter 1: Getting Started with Java... 1

Introduction... xv SECTION 1: DEVELOPING DESKTOP APPLICATIONS USING JAVA Chapter 1: Getting Started with Java... 1 Introduction... xv SECTION 1: DEVELOPING DESKTOP APPLICATIONS USING JAVA Chapter 1: Getting Started with Java... 1 Introducing Object Oriented Programming... 2 Explaining OOP concepts... 2 Objects...3

More information

Mobile MOUSe JAVA2 FOR PROGRAMMERS ONLINE COURSE OUTLINE

Mobile MOUSe JAVA2 FOR PROGRAMMERS ONLINE COURSE OUTLINE Mobile MOUSe JAVA2 FOR PROGRAMMERS ONLINE COURSE OUTLINE COURSE TITLE JAVA2 FOR PROGRAMMERS COURSE DURATION 14 Hour(s) of Interactive Training COURSE OVERVIEW With the Java2 for Programmers course, anyone

More information

SELF-STUDY. Glossary

SELF-STUDY. Glossary SELF-STUDY 231 Glossary HTML (Hyper Text Markup Language - the language used to code web pages) tags used to embed an applet. abstract A class or method that is incompletely defined,

More information

OBJECT ORIENTED PROGRAMMING. Course 8 Loredana STANCIU Room B613

OBJECT ORIENTED PROGRAMMING. Course 8 Loredana STANCIU Room B613 OBJECT ORIENTED PROGRAMMING Course 8 Loredana STANCIU loredana.stanciu@upt.ro Room B613 Applets A program written in the Java programming language that can be included in an HTML page A special kind of

More information

1 OBJECT-ORIENTED PROGRAMMING 1

1 OBJECT-ORIENTED PROGRAMMING 1 PREFACE xvii 1 OBJECT-ORIENTED PROGRAMMING 1 1.1 Object-Oriented and Procedural Programming 2 Top-Down Design and Procedural Programming, 3 Problems with Top-Down Design, 3 Classes and Objects, 4 Fields

More information

Framework. Set of cooperating classes/interfaces. Example: Swing package is framework for problem domain of GUI programming

Framework. Set of cooperating classes/interfaces. Example: Swing package is framework for problem domain of GUI programming Frameworks 1 Framework Set of cooperating classes/interfaces Structure essential mechanisms of a problem domain Programmer can extend framework classes, creating new functionality Example: Swing package

More information

Introduction to Java Applets 12

Introduction to Java Applets 12 Introduction to Java Applets 12 Course Map This module discusses the support for applets by the JDK, and how applets differ from applications in terms of program form, operating context, and how they are

More information

Supporting Materials

Supporting Materials Preface p. xxiii Introduction p. xxiii Key Features p. xxiii Chapter Outlines p. xxiv Supporting Materials p. xxvi Acknowledgments p. xxvii Java Fundamentals p. 1 Bits, Bytes, and Java p. 2 The Challenge

More information

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Weiss Chapter 1 terminology (parenthesized numbers are page numbers) Weiss Chapter 1 terminology (parenthesized numbers are page numbers) assignment operators In Java, used to alter the value of a variable. These operators include =, +=, -=, *=, and /=. (9) autoincrement

More information

G51PRG: Introduction to Programming Second semester Applets and graphics

G51PRG: Introduction to Programming Second semester Applets and graphics G51PRG: Introduction to Programming Second semester Applets and graphics Natasha Alechina School of Computer Science & IT nza@cs.nott.ac.uk Previous two lectures AWT and Swing Creating components and putting

More information

CONTENTS. PART 1 Structured Programming 1. 1 Getting started 3. 2 Basic programming elements 17

CONTENTS. PART 1 Structured Programming 1. 1 Getting started 3. 2 Basic programming elements 17 List of Programs xxv List of Figures xxix List of Tables xxxiii Preface to second version xxxv PART 1 Structured Programming 1 1 Getting started 3 1.1 Programming 3 1.2 Editing source code 5 Source code

More information

Road Map. Introduction to Java Applets Review applets that ship with JDK Make our own simple applets

Road Map. Introduction to Java Applets Review applets that ship with JDK Make our own simple applets Java Applets Road Map Introduction to Java Applets Review applets that ship with JDK Make our own simple applets Introduce inheritance Introduce the applet environment html needed for applets Reading:

More information

Dr. Hikmat A. M. AbdelJaber

Dr. Hikmat A. M. AbdelJaber Dr. Hikmat A. M. AbdelJaber GUI are event driven (i.e. when user interacts with a GUI component, the interaction (event) derives the program to perform a task). Event: click button, type in text field,

More information

Contents. Figures. Tables. Examples. Foreword. Preface. 1 Basics of Java Programming 1. xix. xxi. xxiii. xxvii. xxix

Contents. Figures. Tables. Examples. Foreword. Preface. 1 Basics of Java Programming 1. xix. xxi. xxiii. xxvii. xxix PGJC4_JSE8_OCA.book Page ix Monday, June 20, 2016 2:31 PM Contents Figures Tables Examples Foreword Preface xix xxi xxiii xxvii xxix 1 Basics of Java Programming 1 1.1 Introduction 2 1.2 Classes 2 Declaring

More information

SRM ARTS AND SCIENCE COLLEGE SRM NAGAR, KATTANKULATHUR

SRM ARTS AND SCIENCE COLLEGE SRM NAGAR, KATTANKULATHUR SRM ARTS AND SCIENCE COLLEGE SRM NAGAR, KATTANKULATHUR 603203 DEPARTMENT OF COMPUTER SCIENCE & APPLICATIONS QUESTION BANK (2017-2018) Course / Branch : M.Sc.,CST Semester / Year : EVEN / III Subject Name

More information

COMPSCI 230. Software Design and Construction. Swing

COMPSCI 230. Software Design and Construction. Swing COMPSCI 230 Software Design and Construction Swing 1 2013-04-17 Recap: SWING DESIGN PRINCIPLES 1. GUI is built as containment hierarchy of widgets (i.e. the parent-child nesting relation between them)

More information

Packages: Putting Classes Together

Packages: Putting Classes Together Packages: Putting Classes Together 1 Introduction 2 The main feature of OOP is its ability to support the reuse of code: Extending the classes (via inheritance) Extending interfaces The features in basic

More information

(2½ hours) Total Marks: 75

(2½ hours) Total Marks: 75 (2½ hours) Total Marks: 75 N. B.: (1) All questions are compulsory. (2) Makesuitable assumptions wherever necessary and state the assumptions mad (3) Answers to the same question must be written together.

More information

ощ 'ршорвшэш! цвн-эориэу ощ 'sajbpossv # PIPG DUJ 'ssjmoossv ^ PIPG pipa w н OX ЛЮН VAV

ощ 'ршорвшэш! цвн-эориэу ощ 'sajbpossv # PIPG DUJ 'ssjmoossv ^ PIPG pipa w н OX ЛЮН VAV ощ 'ршорвшэш! цвн-эориэу ощ 'sajbpossv # PIPG DUJ 'ssjmoossv ^ PIPG pipa w н OX ЛЮН VAV Contents Preface Chapter 1 1.1 1.2 1.3 1.4 1.5 1.6 1.7 1.8 1.9 1.10 1.11 1.12 1.13 1.14 1.15 1.16 1.17 1.18 1.19

More information

GUI DYNAMICS Lecture July 26 CS2110 Summer 2011

GUI DYNAMICS Lecture July 26 CS2110 Summer 2011 GUI DYNAMICS Lecture July 26 CS2110 Summer 2011 GUI Statics and GUI Dynamics 2 Statics: what s drawn on the screen Components buttons, labels, lists, sliders, menus,... Containers: components that contain

More information

VALLIAMMAI ENGINEERING COLLEGE

VALLIAMMAI ENGINEERING COLLEGE VALLIAMMAI ENGINEERING COLLEGE SRM Nagar, Kattankulathur 60 0 DEPARTMENT OF INFORMATION TECHNOLOGY QUESTION BANK III SEMESTER CS89- Object Oriented Programming Regulation 07 Academic Year 08 9 Prepared

More information

Contents 8-1. Copyright (c) N. Afshartous

Contents 8-1. Copyright (c) N. Afshartous Contents 1. Classes and Objects 2. Inheritance 3. Interfaces 4. Exceptions and Error Handling 5. Intro to Concurrency 6. Concurrency in Java 7. Graphics and Animation 8. Applets 8-1 Chapter 8: Applets

More information

10/16/2008. CSG 170 Round 5. Prof. Timothy Bickmore. User Analysis Task Analysis (6) Problem Scenarios (3)

10/16/2008. CSG 170 Round 5. Prof. Timothy Bickmore. User Analysis Task Analysis (6) Problem Scenarios (3) Human-Computer Interaction CSG 170 Round 5 Prof. Timothy Bickmore T2: Requirements Analysis Review User Analysis Task Analysis (6) Problem Scenarios (3) 1 T2 Review Requirements Analysis Who is the user?

More information

John Cowell. Essential Java Fast. How to write object oriented software for the Internet. with 64 figures. Jp Springer

John Cowell. Essential Java Fast. How to write object oriented software for the Internet. with 64 figures. Jp Springer John Cowell Essential Java Fast How to write object oriented software for the Internet with 64 figures Jp Springer Contents 1 WHY USE JAVA? 1 Introduction 1 What is Java? 2 Is this book for you? 2 What

More information

Module 5 Applets About Applets Hierarchy of Applet Life Cycle of an Applet

Module 5 Applets About Applets Hierarchy of Applet Life Cycle of an Applet About Applets Module 5 Applets An applet is a little application. Prior to the World Wide Web, the built-in writing and drawing programs that came with Windows were sometimes called "applets." On the Web,

More information

CSE 143. Event-driven Programming and Graphical User Interfaces (GUIs) with Swing/AWT

CSE 143. Event-driven Programming and Graphical User Interfaces (GUIs) with Swing/AWT CSE 143 Event-driven Programming and Graphical User Interfaces (GUIs) with Swing/AWT slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia http://www.cs.washington.edu/331/

More information

GUI Software Architecture

GUI Software Architecture GUI Software Architecture P2: Requirements Analysis User Analysis Task Analysis Problem Scenarios Usability Criteria Scenario Your engineers just developed a new desktop computer. They give you the following

More information

15CS45 : OBJECT ORIENTED CONCEPTS

15CS45 : OBJECT ORIENTED CONCEPTS 15CS45 : OBJECT ORIENTED CONCEPTS QUESTION BANK: What do you know about Java? What are the supported platforms by Java Programming Language? List any five features of Java? Why is Java Architectural Neutral?

More information

PESIT Bangalore South Campus

PESIT Bangalore South Campus PESIT Bangalore South Campus 15CS45 : OBJECT ORIENTED CONCEPTS Faculty : Prof. Sajeevan K, Prof. Hanumanth Pujar Course Description: No of Sessions: 56 This course introduces computer programming using

More information

SNS COLLEGE OF ENGINEERING, Coimbatore

SNS COLLEGE OF ENGINEERING, Coimbatore SNS COLLEGE OF ENGINEERING, Coimbatore 641 107 Accredited by NAAC UGC with A Grade Approved by AICTE and Affiliated to Anna University, Chennai IT6503 WEB PROGRAMMING UNIT 04 APPLETS Java applets- Life

More information

Application Development in JAVA. Data Types, Variable, Comments & Operators. Part I: Core Java (J2SE) Getting Started

Application Development in JAVA. Data Types, Variable, Comments & Operators. Part I: Core Java (J2SE) Getting Started Application Development in JAVA Duration Lecture: Specialization x Hours Core Java (J2SE) & Advance Java (J2EE) Detailed Module Part I: Core Java (J2SE) Getting Started What is Java all about? Features

More information

Virtualians.ning.pk. 2 - Java program code is compiled into form called 1. Machine code 2. native Code 3. Byte Code (From Lectuer # 2) 4.

Virtualians.ning.pk. 2 - Java program code is compiled into form called 1. Machine code 2. native Code 3. Byte Code (From Lectuer # 2) 4. 1 - What if the main method is declared as private? 1. The program does not compile 2. The program compiles but does not run 3. The program compiles and runs properly ( From Lectuer # 2) 4. The program

More information

Chapter 1 GUI Applications

Chapter 1 GUI Applications Chapter 1 GUI Applications 1. GUI Applications So far we've seen GUI programs only in the context of Applets. But we can have GUI applications too. A GUI application will not have any of the security limitations

More information

Which of the following syntax used to attach an input stream to console?

Which of the following syntax used to attach an input stream to console? Which of the following syntax used to attach an input stream to console? FileReader fr = new FileReader( input.txt ); FileReader fr = new FileReader(FileDescriptor.in); FileReader fr = new FileReader(FileDescriptor);

More information

Overloading Example. Overloading. When to Overload. Overloading Example (cont'd) (class Point continued.)

Overloading Example. Overloading. When to Overload. Overloading Example (cont'd) (class Point continued.) Overloading Each method has a signature: its name together with the number and types of its parameters Methods Signatures String tostring() () void move(int dx,int dy) (int,int) void paint(graphicsg) (Graphics)

More information

PESIT Bangalore South Campus

PESIT Bangalore South Campus INTERNAL ASSESSMENT TEST II Date : 20-09-2016 Max Marks: 50 Subject & Code: JAVA & J2EE (10IS752) Section : A & B Name of faculty: Sreenath M V Time : 8.30-10.00 AM Note: Answer all five questions 1) a)

More information

Murach s Beginning Java with Eclipse

Murach s Beginning Java with Eclipse Murach s Beginning Java with Eclipse Introduction xv Section 1 Get started right Chapter 1 An introduction to Java programming 3 Chapter 2 How to start writing Java code 33 Chapter 3 How to use classes

More information

The Sun s Java Certification and its Possible Role in the Joint Teaching Material

The Sun s Java Certification and its Possible Role in the Joint Teaching Material The Sun s Java Certification and its Possible Role in the Joint Teaching Material Nataša Ibrajter Faculty of Science Department of Mathematics and Informatics Novi Sad 1 Contents Kinds of Sun Certified

More information

SD Module-1 Advanced JAVA

SD Module-1 Advanced JAVA Assignment No. 4 SD Module-1 Advanced JAVA R C (4) V T Total (10) Dated Sign Title: Transform the above system from command line system to GUI based application Problem Definition: Write a Java program

More information

Object Oriented Programming with Java. Unit-1

Object Oriented Programming with Java. Unit-1 CEB430 Object Oriented Programming with Java Unit-1 PART A 1. Define Object Oriented Programming. 2. Define Objects. 3. What are the features of Object oriented programming. 4. Define Encapsulation and

More information

SD Module-1 Advanced JAVA. Assignment No. 4

SD Module-1 Advanced JAVA. Assignment No. 4 SD Module-1 Advanced JAVA Assignment No. 4 Title :- Transform the above system from command line system to GUI based application Problem Definition: Write a Java program with the help of GUI based Application

More information

UNIT-2: CLASSES, INHERITANCE, EXCEPTIONS, APPLETS. To define a class, use the class keyword and the name of the class:

UNIT-2: CLASSES, INHERITANCE, EXCEPTIONS, APPLETS. To define a class, use the class keyword and the name of the class: UNIT-2: CLASSES, INHERITANCE, EXCEPTIONS, APPLETS 1. Defining Classes, Class Name To define a class, use the class keyword and the name of the class: class MyClassName {... If this class is a subclass

More information

SRM ARTS AND SCIENCE COLLEGE SRM NAGAR, KATTANKULATHUR

SRM ARTS AND SCIENCE COLLEGE SRM NAGAR, KATTANKULATHUR SRM ARTS AND SCIENCE COLLEGE SRM NAGAR, KATTANKULATHUR 603203 DEPARTMENT OF COMPUTER SCIENCE & APPLICATIONS QUESTION BANK (2017-2018) Course / Branch : MCA Semester / Year : EVEN / II Subject Name : Programming

More information

CS Internet programming Unit- I Part - A 1 Define Java. 2. What is a Class? 3. What is an Object? 4. What is an Instance?

CS Internet programming Unit- I Part - A 1 Define Java. 2. What is a Class? 3. What is an Object? 4. What is an Instance? CS6501 - Internet programming Unit- I Part - A 1 Define Java. Java is a programming language expressly designed for use in the distributed environment of the Internet. It was designed to have the "look

More information

(Refer Slide Time: 02:01)

(Refer Slide Time: 02:01) Internet Technology Prof. Indranil Sengupta Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur Lecture No #29 Java Applets Part: 2 In this lecture we shall be continuing

More information

Get Unique study materials from

Get Unique study materials from Downloaded from www.rejinpaul.com VALLIAMMAI ENGNIEERING COLLEGE SRM Nagar, Kattankulathur 603203. DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING Year & Semester : IV Section : EEE - 1 & 2 Subject Code

More information

Java Graphical User Interfaces AWT (Abstract Window Toolkit) & Swing

Java Graphical User Interfaces AWT (Abstract Window Toolkit) & Swing Java Graphical User Interfaces AWT (Abstract Window Toolkit) & Swing Rui Moreira Some useful links: http://java.sun.com/docs/books/tutorial/uiswing/toc.html http://www.unix.org.ua/orelly/java-ent/jfc/

More information

Essential Series. Springer-Verlag London Ltd.

Essential Series. Springer-Verlag London Ltd. Essential Series Springer-Verlag London Ltd. Also in this series: Essential Visual Basic 4.0 fast 3-540-19998-5 Essential Delphi 2.0 fast 3-540-76026-1 Essential Java fast 3-540-76052-0 Essential Visual

More information

B2.52-R3: INTRODUCTION TO OBJECT ORIENTATED PROGRAMMING THROUGH JAVA

B2.52-R3: INTRODUCTION TO OBJECT ORIENTATED PROGRAMMING THROUGH JAVA B2.52-R3: INTRODUCTION TO OBJECT ORIENTATED PROGRAMMING THROUGH JAVA NOTE: 1. There are TWO PARTS in this Module/Paper. PART ONE contains FOUR questions and PART TWO contains FIVE questions. 2. PART ONE

More information

Assignment No 2. Year: Dept.: ComputerTech. Sanjivani Rural Education Society s Sanjivani KBP Polytechnic, Kopargaon

Assignment No 2. Year: Dept.: ComputerTech. Sanjivani Rural Education Society s Sanjivani KBP Polytechnic, Kopargaon Year: 015-16 ACAD/F/3 Subject: AJP(1765) Division:CMTA(CM6G) Pages: 1-7 CHAPTER :Event Handling(0 Marks) Q.1 package contains all the classes and methods required for Event handling in java. (a) java.applet

More information

DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS

DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS Chapter 1 : Chapter-wise Java Multiple Choice Questions and Answers Interview MCQs Java Programming questions and answers with explanation for interview, competitive examination and entrance test. Fully

More information

B2.52-R3: INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING THROUGH JAVA

B2.52-R3: INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING THROUGH JAVA B2.52-R3: INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING THROUGH JAVA NOTE: 1. There are TWO PARTS in this Module/Paper. PART ONE contains FOUR questions and PART TWO contains FIVE questions. 2. PART ONE

More information

Java Application Development

Java Application Development A Absolute Size and Position - Specifying... 10:18 Abstract Class... 5:15 Accessor Methods...4:3-4:4 Adding Borders Around Components... 10:7 Adding Components to Containers... 10:6 Adding a Non-Editable

More information

Come & Join Us at VUSTUDENTS.net

Come & Join Us at VUSTUDENTS.net Come & Join Us at VUSTUDENTS.net For Assignment Solution, GDB, Online Quizzes, Helping Study material, Past Solved Papers, Solved MCQs, Current Papers, E-Books & more. Go to http://www.vustudents.net and

More information

UNIT -1 JAVA APPLETS

UNIT -1 JAVA APPLETS UNIT -1 JAVA APPLETS TOPICS TO BE COVERED 1.1 Concept of Applet Programming Local and Remote applets Difference between applet and application Preparing to write applets Building applet code Applet life

More information

DHANALAKSHMI SRINIVASAN COLLEGE OF ENGINEERING AND TECHNOLOGY ACADEMIC YEAR (ODD SEM)

DHANALAKSHMI SRINIVASAN COLLEGE OF ENGINEERING AND TECHNOLOGY ACADEMIC YEAR (ODD SEM) DHANALAKSHMI SRINIVASAN COLLEGE OF ENGINEERING AND TECHNOLOGY ACADEMIC YEAR 2018-19 (ODD SEM) DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING SUB: OBJECT ORIENTED PROGRAMMING SEM/YEAR: III SEM/ II YEAR

More information

CS506 Web Programming and Development Solved Subjective Questions With Reference For Final Term Lecture No 1

CS506 Web Programming and Development Solved Subjective Questions With Reference For Final Term Lecture No 1 P a g e 1 CS506 Web Programming and Development Solved Subjective Questions With Reference For Final Term Lecture No 1 Q1 Describe some Characteristics/Advantages of Java Language? (P#12, 13, 14) 1. Java

More information

9. APPLETS AND APPLICATIONS

9. APPLETS AND APPLICATIONS 9. APPLETS AND APPLICATIONS JAVA PROGRAMMING(2350703) The Applet class What is an Applet? An applet is a Java program that embedded with web content(html) and runs in a Web browser. It runs inside the

More information

Java TM Applets. Rex Jaeschke

Java TM Applets. Rex Jaeschke Java TM Applets Rex Jaeschke Java Applets 1997 1998, 2009 Rex Jaeschke. All rights reserved. Edition: 3.0 (matches JDK1.6/Java 2) All rights reserved. No part of this publication may be reproduced, stored

More information

Compaq Interview Questions And Answers

Compaq Interview Questions And Answers Part A: Q1. What are the difference between java and C++? Java adopts byte code whereas C++ does not C++ supports destructor whereas java does not support. Multiple inheritance possible in C++ but not

More information

COP 3330 Final Exam Review

COP 3330 Final Exam Review COP 3330 Final Exam Review I. The Basics (Chapters 2, 5, 6) a. comments b. identifiers, reserved words c. white space d. compilers vs. interpreters e. syntax, semantics f. errors i. syntax ii. run-time

More information

Course Status Networking GUI Wrap-up. CS Java. Introduction to Java. Andy Mroczkowski

Course Status Networking GUI Wrap-up. CS Java. Introduction to Java. Andy Mroczkowski CS 190 - Java Introduction to Java Andy Mroczkowski uamroczk@cs.drexel.edu Department of Computer Science Drexel University March 10, 2008 / Lecture 8 Outline Course Status Course Information & Schedule

More information

Java Applets / Flash

Java Applets / Flash Java Applets / Flash Java Applet vs. Flash political problems with Microsoft highly portable more difficult development not a problem less so excellent visual development tool Applet / Flash good for:

More information

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub Lebanese University Faculty of Science Computer Science BS Degree Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub 2 Crash Course in JAVA Classes A Java

More information

S.No Question Blooms Level Course Outcome UNIT I. Programming Language Syntax and semantics

S.No Question Blooms Level Course Outcome UNIT I. Programming Language Syntax and semantics S.No Question Blooms Level Course Outcome UNIT I. Programming Language Syntax and semantics 1 What do you mean by axiomatic Knowledge C254.1 semantics? Give the weakest precondition for a sequence of statements.

More information

Objective Questions. BCA Part III Paper XIX (Java Programming) page 1 of 5

Objective Questions. BCA Part III Paper XIX (Java Programming) page 1 of 5 Objective Questions BCA Part III page 1 of 5 1. Java is purely object oriented and provides - a. Abstraction, inheritance b. Encapsulation, polymorphism c. Abstraction, polymorphism d. All of the above

More information

Module 4 Multi threaded Programming, Event Handling. OOC 4 th Sem, B Div Prof. Mouna M. Naravani

Module 4 Multi threaded Programming, Event Handling. OOC 4 th Sem, B Div Prof. Mouna M. Naravani Module 4 Multi threaded Programming, Event Handling OOC 4 th Sem, B Div 2017-18 Prof. Mouna M. Naravani Event Handling Complete Reference 7 th ed. Chapter No. 22 Event Handling Any program that uses a

More information

Java for Programmers Course (equivalent to SL 275) 36 Contact Hours

Java for Programmers Course (equivalent to SL 275) 36 Contact Hours Java for Programmers Course (equivalent to SL 275) 36 Contact Hours Course Overview This course teaches programmers the skills necessary to create Java programming system applications and satisfies the

More information

Preface... (vii) CHAPTER 1 INTRODUCTION TO COMPUTERS

Preface... (vii) CHAPTER 1 INTRODUCTION TO COMPUTERS Contents Preface... (vii) CHAPTER 1 INTRODUCTION TO COMPUTERS 1.1. INTRODUCTION TO COMPUTERS... 1 1.2. HISTORY OF C & C++... 3 1.3. DESIGN, DEVELOPMENT AND EXECUTION OF A PROGRAM... 3 1.4 TESTING OF PROGRAMS...

More information

Control Flow: Overview CSE3461. An Example of Sequential Control. Control Flow: Revisited. Control Flow Paradigms: Reacting to the User

Control Flow: Overview CSE3461. An Example of Sequential Control. Control Flow: Revisited. Control Flow Paradigms: Reacting to the User CSE3461 Control Flow Paradigms: Reacting to the User Control Flow: Overview Definition of control flow: The sequence of execution of instructions in a program. Control flow is determined at run time by

More information

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS PAUL L. BAILEY Abstract. This documents amalgamates various descriptions found on the internet, mostly from Oracle or Wikipedia. Very little of this

More information

5/23/2015. Core Java Syllabus. VikRam ShaRma

5/23/2015. Core Java Syllabus. VikRam ShaRma 5/23/2015 Core Java Syllabus VikRam ShaRma Basic Concepts of Core Java 1 Introduction to Java 1.1 Need of java i.e. History 1.2 What is java? 1.3 Java Buzzwords 1.4 JDK JRE JVM JIT - Java Compiler 1.5

More information

1 Shyam sir JAVA Notes

1 Shyam sir JAVA Notes 1 Shyam sir JAVA Notes 1. What is the most important feature of Java? Java is a platform independent language. 2. What do you mean by platform independence? Platform independence means that we can write

More information

An applet is called from within an HTML script with the APPLET tag, such as: <applet code="test.class" width=200 height=300></applet>

An applet is called from within an HTML script with the APPLET tag, such as: <applet code=test.class width=200 height=300></applet> 6 Java Applets 6.1 Introduction As has been previously discussed a Java program can either be run as an applet within a WWW browser (such as Microsoft Internet Explorer or Netscape Communicator) or can

More information

Java 1.8 Programming

Java 1.8 Programming One Introduction to Java 2 Usage of Java 3 Structure of Java 4 Flexibility of Java Programming 5 Two Running Java in Dos 6 Using the DOS Window 7 DOS Operating System Commands 8 Compiling and Executing

More information

INTRODUCTION TO COMPUTER PROGRAMMING. Richard Pierse. Class 9: Writing Java Applets. Introduction

INTRODUCTION TO COMPUTER PROGRAMMING. Richard Pierse. Class 9: Writing Java Applets. Introduction INTRODUCTION TO COMPUTER PROGRAMMING Richard Pierse Class 9: Writing Java Applets Introduction Applets are Java programs that execute within HTML pages. There are three stages to creating a working Java

More information

Graphics. Lecture 18 COP 3252 Summer June 6, 2017

Graphics. Lecture 18 COP 3252 Summer June 6, 2017 Graphics Lecture 18 COP 3252 Summer 2017 June 6, 2017 Graphics classes In the original version of Java, graphics components were in the AWT library (Abstract Windows Toolkit) Was okay for developing simple

More information

CS Exam 1 Review Suggestions

CS Exam 1 Review Suggestions CS 235 - Fall 2015 - Exam 1 Review Suggestions p. 1 last modified: 2015-09-30 CS 235 - Exam 1 Review Suggestions You are responsible for material covered in class sessions, lab exercises, and homeworks;

More information

CSE 331. Event-driven Programming and Graphical User Interfaces (GUIs) with Swing/AWT

CSE 331. Event-driven Programming and Graphical User Interfaces (GUIs) with Swing/AWT CSE 331 Event-driven Programming and Graphical User Interfaces (GUIs) with Swing/AWT slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia http://www.cs.washington.edu/331/

More information

CS201 - Introduction to Programming Glossary By

CS201 - Introduction to Programming Glossary By CS201 - Introduction to Programming Glossary By #include : The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with

More information

"Charting the Course... Java Programming Language. Course Summary

Charting the Course... Java Programming Language. Course Summary Course Summary Description This course emphasizes becoming productive quickly as a Java application developer. This course quickly covers the Java language syntax and then moves into the object-oriented

More information

Contents Introduction 1

Contents Introduction 1 SELF-STUDY iii Introduction 1 Course Purpose... 1 Course Goals...1 Exercises... 2 Scenario-Based Learning... 3 Multimedia Overview... 3 Assessment... 3 Hardware and Software Requirements... 4 Chapter 1

More information

Java - Applets. C&G criteria: 1.2.2, 1.2.3, 1.2.4, 1.3.4, 1.2.4, 1.3.4, 1.3.5, 2.2.5, 2.4.5, 5.1.2, 5.2.1,

Java - Applets. C&G criteria: 1.2.2, 1.2.3, 1.2.4, 1.3.4, 1.2.4, 1.3.4, 1.3.5, 2.2.5, 2.4.5, 5.1.2, 5.2.1, Java - Applets C&G criteria: 1.2.2, 1.2.3, 1.2.4, 1.3.4, 1.2.4, 1.3.4, 1.3.5, 2.2.5, 2.4.5, 5.1.2, 5.2.1, 5.3.2. Java is not confined to a DOS environment. It can run with buttons and boxes in a Windows

More information

A- Core Java Audience Prerequisites Approach Objectives 1. Introduction

A- Core Java Audience Prerequisites Approach Objectives 1. Introduction OGIES 6/7 A- Core Java The Core Java segment deals with the basics of Java. It is designed keeping in mind the basics of Java Programming Language that will help new students to understand the Java language,

More information