Lecture notes Advanced Java

java lecture notes pdf complete reference, lecture notes for core java, lecture notes for advanced java programming, java fundamentals lecture notes
Dr.DavisHardy Profile Pic
Published Date:22-07-2017
Your Website URL(Optional)
423149 FM.qxd 7/10/03 2:03 PM Page ix Contents Acknowledgments xix About the Author xxi Introduction xxiii Chapter 1 Getting Started with Java 1 Why Java? 1 The Java Virtual Machine 2 The Editions of Java 4 J2SE 4 J2ME 5 J2EE 5 Downloading the Java 2 SDK 6 Installing the SDK 7 Running the SDK Tools 8 Running the javac Compiler 9 Running the JVM 10 A Simple Java Program 10 Step 1: Write the Source Code 11 Step 2: Compile the Program 13 Step 3: Run the Program 14 Summary 17 Chapter 2 Java Fundamentals 21 Java Keywords 21 Identifiers 22 Java’s Eight Primitive Data Types 23 Variables 24 Assigning Variables 25 Integral Types 27 ixb423149 FM.qxd 6/30/03 3:36 PM Page x x Contents Floating-Point Types 29 Boolean Data Type 30 Char Data Type 31 Strings 33 References versus Primitive Data 35 Constants 37 Java Operators 37 Increment and Decrement Operators 39 Assignment Operators 40 Shift Operators 40 Comparison Operators 42 Boolean Operators 43 Ternary Operator 43 Java Comments 44 Summary 46 Chapter 3 Control Structures 51 Flow of Control 51 Boolean Logic 52 The and Operator 52 The or Operator 53 The exclusive or Operator 54 The not Operator 54 Boolean Operators 55 The if Statement 57 The if/else Statement 59 The switch Statement 61 The while Loop 64 The do/while Loop 67 The for Loop 70 The break Keyword 74 The continue Keyword 76 Nested Loops 78 Summary 80 Chapter 4 Classes and Objects 85 Overview of Classes and Objects 85 Procedural Programming 86 Object-Oriented Programming 87 Object-Oriented Analysis and Design 88 Writing a Java Class 89 Adding Fields to a Class 89 Adding Methods to a Class 90 Instantiating an Object 92 Garbage Collection 94 Accessing Fields and Methods 97 Using the Dot Operator 97 Step 1: Write the Employee Class 97 Step 2: Compile the Employee Class 98b423149 FM.qxd 6/30/03 3:36 PM Page xi Contents xi Step 3: Write the EmployeeDemo Class 98 Step 4: Compile the EmployeeDemo class 99 Step 5: Run the EmployeeDemo program 99 The this Reference 100 Summary 103 Chapter5Methods 107 Method Call Stack 107 Invoking Methods 108 Method Signature 111 Arguments and Parameters 113 Call-by-Value 116 Overloading Methods 121 Constructors 125 Default Constructor 128 Using Constructors 129 A Class with Multiple Constructors 130 Using this in a Constructor 131 Summary 136 Chapter 6 Understanding Inheritance 139 An Overview of Inheritance 139 The is aRelationship 144 Implementing Inheritance 145 Instantiating Child Objects 146 Single versus Multiple Inheritance 149 The java.lang.Object Class 150 The Methods of the Object Class 151 Method Overriding 154 The super Keyword 157 The final Keyword 160 final Methods 161 The Instantiation Process 162 Invoking a Parent Class Constructor 165 Summary 170 Chapter 7 Advanced Java Language Concepts 175 An Overview of Packages 175 Adding a Class to a Package 176 The Namespace Created by Packages 178 The import Keyword 180 The Directory Structure of Packages 183 Step 1: Write and Save the Source Code for Vehicle 185 Step 2: Compile the Source Code Using the -d Flag 185 Step 3: Write the CarDealer Class 186 Step 4: Set the CLASSPATH 187 Step 5: Compile and Run the CarDealer Program 188 The Access Specifiers 190 Encapsulation 194b423149 FM.qxd 6/30/03 3:36 PM Page xii xii Contents Benefits of Encapsulation 197 Understanding Static Members 198 Accessing Static Fields and Methods 199 Static Initializers 203 Instance Initializers 205 Summary 209 Chapter 8 Polymorphism and Abstraction 213 An Overview of Polymorphism 213 Using Parent Class References to Child Objects 214 Casting References 218 The instanceof Keyword 221 Polymorphic Parameters 225 Heterogeneous Collections 229 Virtual Methods 230 Taking Advantage of Virtual Methods 233 An Overview of Abstraction 238 Abstract Classes 239 Abstract Methods 241 Summary 247 Chapter9Collections 253 Arrays 253 Accessing Arrays 255 The length Attribute 255 Arrays of References 256 Array Initializers 259 Copying Arrays 261 Multidimensional Arrays 263 Example of a Heterogeneous Collection 265 Overview of the Java Collections Framework 272 The Vector Class 273 Adding Elements to a Vector 275 Accessing and Removing Elements in a Vector 277 The Hashtable Class 281 Adding Elements to a Hashtable 283 Accessing Elements in a Hashtable 285 Summary 290 Chapter10Interfaces 295 An Overview of Interfaces 295 Declaring Interfaces 296 User-Defined Interfaces 298 Write the Interface Source Code 299 Compile the Interface 299 Implementing an Interface 300 Write a Class That Implements Paintable 300 Save and Compile the Rectangle Class 301 Add the paint() Method 302 Write a Class That Uses Paintable 302b423149 FM.qxd 6/30/03 3:36 PM Page xiii Contents xiii Using Interfaces 303 Exposing Methods via an Interface 304 Forcing Behavior on a Class 310 Declaring Fields in Interfaces 316 Extending Interfaces 317 Extending Multiple Interfaces 319 Interfaces and Polymorphism 321 Summary 326 Chapter 11 Exception Handling 329 Overview of Exception Handling 329 Flow of Control of Exceptions 330 Throwable Classes 333 Methods of the Throwable Class 333 Catching Exceptions 334 Writing try/catch Blocks 335 Multiple catch Blocks 337 Handle or Declare Rule 341 Declaring Exceptions 343 The throws Keyword 345 Throwing Exceptions 348 The finally Keyword 351 Overridden Methods and Exceptions 354 User-Defined Exceptions 357 Summary 361 Chapter 12 An Introduction to GUI Programming 367 AWT versus Swing 367 Creating Windows 369 java.awt.Frame Class 369 javax.swing.JFrame Class 372 Containers and Components 375 Adding Components to a Container 375 Layout Managers 378 FlowLayout Manager 379 BorderLayout Manager 383 Panels 385 GridLayout Manager 388 BoxLayout Manager 390 Nesting Panels 392 Using No Layout Manager 396 Summary 401 Chapter 13 GUI Components and Event Handling 405 The Delegation Model 405 The Event Listener Interfaces 407 Creating an Event Listener 409 Registering a Listener with an Event Source 410 The Event Adapter Classes 412b423149 FM.qxd 6/30/03 3:36 PM Page xiv xiv Contents Buttons 417 AWT Buttons 417 Swing Buttons 418 Check Boxes 421 AWT Check Boxes 421 Swing Check Boxes 423 Radio Buttons 425 AWT Radio Buttons 425 Swing Radio Buttons 427 Labels 429 Text Components 430 AWT Text Components 430 Swing Text Components 434 Lists 437 AWT Lists 437 Swing Lists 439 Combo Boxes 440 AWT Choice 440 Swing Combo Boxes 442 Progress Bars 445 Menus 445 Summary 452 Chapter14Applets 457 An Overview of Applets 457 The java.applet.Applet Class 459 Swing Applets 462 Life Cycle of an Applet 465 Step 1: Write the Applet Class 467 Step 2: Write the HTML Page 468 Step 3: View the HTML Page 468 Step 4: View the Java Console 469 The applet Tag 473 Document and Code Base 478 The appletviewer Tool 479 Sandbox Security 481 The Applet Context 485 Displaying Images 488 Playing Audio 490 JAR Files and Applets 494 Summary 500 Chapter15Threads 503 Overview of Threads 503 Life Cycle of a Thread 506 Creating a Thread 507 Implementing Runnable 508b423149 FM.qxd 6/30/03 3:36 PM Page xv Contents xv Extending the Thread Class 511 Methods of the Thread Class 516 Timer and TimerTask Classes 519 Scheduling Tasks 522 Multithreading Issues 526 synchronized Keyword 530 Deadlock Issues 532 Ordering Locks 534 wait() and notify() Methods 536 Summary 546 Chapter 16 Input and Output 551 An Overview of the java.io Package 551 The Output Streams 552 The Input Stream Classes 553 The Writer Class 553 The Reader Class 554 Low-Level and High-Level Streams 557 Low-Level Streams 557 High-Level Streams 559 Chaining Streams Together 561 Low-Level Readers and Writers 564 High-Level Readers and Writers 564 File I/O 565 The RandomAccessFile Class 566 Using Pipes 570 An Overview of Serialization 574 Serializing an Object 577 Deserializing an Object 578 The Logging APIs 579 An Example of Logging 581 Summary 587 Chapter 17 Network Programming 591 An Overview of Network Programming 591 Transmission Control Protocol 592 User Datagram Protocol 592 Using Sockets 594 The ServerSocket Class 596 Socket Class 599 Communicating between Sockets 600 Java Secure Socket Extension (JSSE) 602 Secure Server Socket 603 Secure Client Socket 607 Communicating over a Secure Socket 610 Overview of Datagram Packets 612 DatagramSocket Class 612 DatagramPacket Class 613b423149 FM.qxd 6/30/03 3:36 PM Page xvi xvi Contents Receiving a Datagram Packet 614 Sending a Datagram Packet 615 Working with URLs 617 URLConnections 619 Summary 625 Chapter 18 Database Programming 629 An Overview of JDBC 629 JDBC Drivers 632 Connecting to a Database 633 Using the DriverManager Class 634 Using the DataSource Class 636 An SQL Primer 637 Creating Data 638 Reading Data 639 Updating Data 640 Deleting Data 641 Creating Statements 641 Simple Statements 642 Working with Result Sets 647 Navigating a Result Set 647 Viewing a Result Set 648 Updating a Result Set 651 Prepared Statements 652 Step 1: Preparing the Statement 652 Step 2: Setting the Parameters 654 Step 3: Executing a Prepared Statement 654 Callable Statements 656 Summary 663 Chapter19JavaBeans 669 Overview of JavaBeans 669 Simple Properties 672 Packaging a Bean 675 Step 1: Write the Bean Class 676 Step 2: Write the Manifest File 676 Step 3: Create the JAR File 677 Step 4: Download the Bean Builder 678 Step 5: Run the Bean Builder 678 Step 6: Load the Movie Bean into the Bean Builder 681 Step 7: Using the Movie Bean in the Builder Tool 681 Bound Properties 684 Step 8: Binding Properties in the Bean Builder 687 Constrained Properties 690 Vetoing an Event 693b423149 FM.qxd 6/30/03 3:36 PM Page xvii Contents xvii Overview of Events 694 Step 9: Hooking up Buttons to the Movie Bean 695 Step 10: Viewing Beans in Preview Mode 696 Generating User-Defined Events 698 BeanInfo Class 703 Summary 708 Appendix About the 60 Minutes Web Site 713 Index 717b423149 FM.qxd 6/30/03 3:36 PM Page xviiib423149 FM.qxd 6/30/03 3:36 PM Page xix Acknowledgments I would like to thank the editors for their hard work on this book: J.W. (Jerry) Olsen, Nancy Sixsmith, and Susan Hobbs, and everyone at Wiley Publishing who helped in this project, especially Ben Ryan. Thanks also to Donis Marshall for the opportunity to write a book for the 60 Minutes a Day series as well as to Jerry for managing the editors on behalf of Gearhead. And then there is everyone out there who played a role, whether small or large, in my writing of this book: Susan Raposa, javalicense.com, my Mom (who can read it now), and most importantly, Megan, Ryan, Katelyn, and Emma. And finally, to all of those who kept asking me when my book would be published: Leo and Linda Schaefbauer; Steve, Beth, Geoffrey, Nathan, and Aurora Venteicher; Michael and Tammy Schaefbauer; David Schaefbauer; Betty Haefner; Mark, Margaret, Marie, Melissa, and Jay VanDerWerff; Michele, Gabe, and Seth Raposa; Allen, Denise, Joseph, Rechele, Kathalena, Kurstin, Joshua, and Kristina Raposa; Dave, Maryann, Daniel, Duke, Davey, Dylan, and Darby Knoll; and Barb and Steve Sachs. xixb423149 FM.qxd 6/30/03 3:36 PM Page xxb423149 FM.qxd 6/30/03 3:36 PM Page xxi About the Author Richard F. Raposa is a Java instructor for JLicense, Inc., a Java courseware and training firm based in Rapid City, SD. One of the first Sun Certified Java Instructors, Rich has taught courses on Java, J2EE, XML, Web Services, C++, Visual C++/MFC, Win32 Internals, UML, and other object-oriented technolo- gies at companies around the country. He has developed courses on almost every aspect of Java and the J2EE technologies. xxib423149 FM.qxd 6/30/03 3:36 PM Page xxiib423149 FM.qxd 6/30/03 3:36 PM Page xxiii Introduction An Overview of Java in 60 Minutes a Day I will never forget taking my first Java class at Sun Microsystems in Dallas, Texas, in May, 1998. I had heard the many promises about Java and how it would revolutionize software development, but I was skeptical and arrogant as I sat in the back of the class anxious to make life hard on the instructor. At the time, I was programming and teaching C++, mostly Visual C++ and the Microsoft Foundation Classes. For some reason, after I learned C++, I fig- ured that would be the last programming language I would ever need to learn. My boss, on the other hand, had different ideas, because I was slated to become a Sun Certified Java Instructor. Contrary to my expectations, I was blown away by Java It was logical, pre- dictable, powerful, and simple (compared to C++). Sun had taken the best of the existing object-oriented programming languages and removed many of the idiosyncrasies and problem areas. And the best part: Java is platform inde- pendent You write a program once, and it can be executed on different oper- ating systems and devices without your even having to recompile your code. I have been travelling the country teaching Java now for the last 5 years, and I still get excited about standing up in front of a classroom of students who are seeing Java for the first time. One of my goals was to capture that enthusiasm on the pages of this book. I want you to appreciate why Java has become one of the most popular and widely used programming languages in software development today. xxiiib423149 FM.qxd 6/30/03 3:36 PM Page xxiv xxiv Introduction How This Book Is Organized The goal of this book is for you to be able to study each chapter in one hour, like a student sitting through a one-hour lecture. After you finish a chapter, there are labs that solidify what you learned by having you write code. You will also find review questions and answers at the end of each chapter to help you review the key points of the chapter. Also throughout the book are Class- room Q&A sections where I answer questions that I have frequently been asked by students in the classroom. The book contains 19 chapters. The first eight chapters discuss the funda- mentals of the Java language, and should be read in order. The order of the last 11 chapters isn’t quite as important, although you will find that many of the labs build on the ones from previous chapters. The following sections describe what you will learn in this book’s chapters. Chapter 1: Getting Started with Java It just wouldn’t be a programming class if I didn’t start with the “Hello, World” application. In Chapter 1, you will learn what all the hype is about with Java. I will discuss the life cycle of a Java program, then you will see how to write, compile, and execute a Java program using the Java 2 Platform, Stan- dard Edition (J2SE) Standard Developer Kit (SDK). Here’s a tip: If you have a slow Internet connection, you might want to start downloading the J2SE SDK before you start reading the chapter. Chapter 2: Java Fundamentals This chapter covers the fundamentals of Java, such as keywords, the built-in data types, strings, variables, references, and arithmetic operators. The infor- mation in this chapter establishes the foundation for the remainder of the book, so take your time and make sure you understand everything. If you are a C or C++ programmer, don’t skip over this chapter thinking you already know what’s in it. Java looks similar to C++, but it behaves quite dif- ferently. Chapter 3: Control Structures In this chapter, you will learn the various control structures in Java and the details of how to use them, including if/else, switch, do/while, and if state- ments. I will also cover Boolean operators and the truth tables. There are some fun labs in this chapter, including one where you write a program to simulate the Powerball lottery.b423149 FM.qxd 6/30/03 3:36 PM Page xxv Introduction xxv Chapter 4: Classes and Objects In my opinion, this is the most important chapter in the book, whether or not you are new to object-oriented programming (OOP). Java is purely object- oriented, so to be a Java programmer is to understand classes and objects. In this chapter, you will learn how to think like an object-oriented programmer, as opposed to thinking procedurally. The basics of OOP are discussed: that objects consist of attributes and behaviors, and that classes describe objects. I will also briefly discuss the Unified Modeling Language (UML) and give you a taste of Object Oriented Analysis and Design (OOAD). The important topic of Java references is also covered in detail. Spend extra time on this chapter if you need to, because all of the topics require your complete understanding before you can write Java programs. Chapter 5: Methods The behaviors of an object becomes methods in a class. By Chapter 5, you will be familiar with writing classes, so it’s time to discuss all of the details about writing and invoking Java methods. Topics covered in this chapter include the method call stack, method signatures, parameters, arguments, method over- loading, constructors, and the always-important discussion of call-by-value in Java. The labs in this chapter give you the opportunity to really get a feel for objects and OOP. You will write classes, instantiate objects, and invoke meth- ods on those objects. Chapter 6: Understanding Inheritance Object-oriented programming has four major aspects: inheritance, encapsula- tion, polymorphism, and abstraction. This chapter focuses on the most impor- tant of the four: inheritance. A new child class can be written that extends an existing class, inheriting the attributes and behaviors of its parent. This chap- ter discusses when and how to use inheritance, including the “is a” relation- ship, the extends keyword, the Object class, method overriding, and a repeat discussion on constructors and how they are affected by inheritance. If I were to rank chapters in order of their importance, I would put this one second behind Chapter 4, “Classes and Objects.” An understanding of inheri- tance is essential to understanding the remaining chapters of the book. Chapter 7: Advanced Java Language Concepts In this chapter, I tie up some loose ends and discuss the details of some of the more advanced topics of Java. Topics covered in this chapter include packages,b423149 FM.qxd 6/30/03 3:36 PM Page xxvi xxvi Introduction the access specifiers, encapsulation, static fields and methods, and the javadoc tool. Some of these topics, such as packages and the javadoc tool, are of special interest because they are concepts unique to Java. I think javadoc is one of the most impressive features of the Java language, as you may also agree after you see how it works. Chapter 8: Polymorphism and Abstraction Polymorphism is the capability of an object to take on different forms. Abstrac- tion refers to the use of abstract classes, classes that cannot be instantiated. In this chapter, I discuss the details of these two object-oriented concepts, includ- ing polymorphic parameters, heterogeneous collections, the instanceof key- word, virtual methods, and abstract methods. This is likely the most difficult chapter in the book. The concept of polymor- phism is crucial but difficult to explain, so I make an asserted effort to simplify my discussions. Read this chapter carefully, and refer back to it whenever you need to. Chapter 9: Collections After eight days of building a foundation for programming in Java, you will now be ready to start using some of the many Java APIs that compose the Java 2 Platform, Standard Edition (J2SE). Chapter 9 covers the classes in the Java Collections API. If you have ever had to write code to create a linked list, hash table, tree, or other data structure, you will be happy to find that the J2SE con- tains classes for all the commonly used data structures. This is a useful chapter for anyone, no matter what types of problems you will be solving in your Java programming future. Chapter 10: Interfaces The Java language contains the concept of interfaces, which allow you to cre- ate data types based on a set of behaviors. A class implements an interface, thereby causing the class to take on the data type of the interface. The class must also implement the methods of the interface, which is how interfaces can be used to force behavior on classes. This chapter covers the details of writing and implementing interfaces. Knowledge of interfaces is an absolute must in Java, so study this chapter closely.b423149 FM.qxd 6/30/03 3:36 PM Page xxvii Introduction xxvii Chapter 11: Exception Handling Exception handling is a built-in feature of Java, and you need to know how to catch an exception before continuing further in the book. This chapter dis- cusses the two types of exceptions: runtime and checked. You will learn the details of a try/catch block and how it affects the flow of control of a method. Other topics include the Handle or Declare Rule, the finally keyword, and writing user-defined exceptions. Chapter 12: Introduction to GUI Programming Now, we get to the fun part of Java: GUI (graphical user interface) program- ming. I am still impressed with the ability to be able to write a GUI program that runs on different operating systems. In this chapter, you will learn how to lay out GUI components in a container using the various layout managers. You have two options in Java for creating a GUI: AWT or Swing. This chapter compares these two APIs and shows you how to use them both. The labs in this chapter are the start of a project that has you create an Instant Messaging application. The program will gradually evolve throughout the rest of the book. Chapter 13: GUI Components and Event Handling There is a lot of information in creating GUIs and handling the events of the components, so I separated the topics into two days. In this chapter, you will learn how to handle the events from the GUIs you created in the previous chapter. Different components generate different types of events, and my goal in this chapter is to show you how to determine for yourself what types of events a component generates. Event handling is accomplished using the Del- egation Model, which I discuss in detail. By the end of this chapter, you will be able to write fully functional Java GUI applications. Chapter 14: Applets An applet is a Java program that runs in a Web browser. Applets are actually GUI containers, so you will be writing applets in no time, knowing what you learned in the previous two chapters. This chapter discusses the details of writing applets and embedding them in an HTML page. Don’t worry if you are new to HTML. I will show you enough so that you can create simple Web pages containing your applets.

Advise: Why You Wasting Money in Costly SEO Tools, Use World's Best Free SEO Tool Ubersuggest.