Table of Contents Intermediate Java

Size: px
Start display at page:

Download "Table of Contents Intermediate Java"

Transcription

1 Table of Contents Intermediate Java Intermediate Java and OO Development 1 Course Overview 2 Workshop Agenda 3 Workshop Agenda 4 Workshop Objectives - Java 5 Workshop Objectives - Tools 6 Course Methodology 7 Labs 8 Release Level 9 Typographic Conventions 10 Session 1 - Getting Started 11 Session Objectives 12 A Simple Application Class 13 Compiling HelloWorld 14 Java Source and Java Bytecode 15 Life Cycle of a Java Program 16 Java Programs Insulated From Environment 17 Java is Dynamic - The Runtime Process 18 Lab HelloWorld 19 Session 2 Review: Class and Object 43 Session Objectives 44 Defining Classes 45 Classes and Objects 46 The Class in Java 47 Storing Data in Objects 48 Behavior and Methods 49 Data Access and Return Values in Methods 50 Pretty Pictures 51 About Java Primitive Data Types 52 Strings 53 Lab Writing a Class Definition 54 Working With Methods and Data 62 Working Within Methods 63 Local Variables 64 Overloading Methods 65 The tostring() Method 66 Encapsulation and Access Control 67 Encapsulation: Black Boxes 68 Encapsulation 69 Private Access 70 Public Access 71 Lab Encapsulation 72 Constructors 80 Constructors 81 Using Constructors 82 Lab Adding Constructors to a Class 83 Other Capabilities 88 Copyright LearningPatterns Inc. All rights reserved i

2 Static Members 89 Accessing Static Members 90 final Variables 91 Comparison 92 Null Objects 93 Wrapper Classes 94 Session 3 - Review: Flow of Control, String and Array 95 Session Objectives 96 Flow of Control 97 The Comparison Operators 98 The Logical Operators 99 if-else Statement 100 switch Statement 101 while Statement 102 do-while Statement 103 for Statement 104 break Statement 105 continue Statement 106 Strings 107 Using Strings 108 Classes StringBuffer and StringBuilder 109 Using StringBuffer and StringBuilder 110 Arrays 111 Arrays 112 Arrays 113 Arrays of Class Types 114 Iterating Over Arrays 115 Lab Arrays 116 Session 4 - Review: Packages 120 Session Objectives 121 Packages Overview 122 Packages 123 The import Statement 124 Importing 125 Resolving Naming Conflicts 126 Creating a Package 127 Access Control for Class Members 128 Finding Classes 129 Finding Classes 130 Organizing Files and Packages 131 Class Path 132 Classpath Example 133 Classpath Example 134 What is a JAR? 135 Classpath Example 136 javac Revisited 137 java Revisited 138 Lab Packages 139 Session 5 - Composition and Inheritance 145 Session Objectives 146 Copyright LearningPatterns Inc. All rights reserved ii

3 Composition 147 Dealing With Complexity and Composition 148 Composition 149 Delegation 150 Benefits/Problems of Composition 151 About Object Relationships 152 The USES Relationship 153 Other Kinds of Relationships 154 Lab Composition 155 Inheritance 161 Inheritance and Dealing With Complexity 162 Inheritance Hierarchy 163 The extends Keyword 164 Inheriting from the Superclass 165 Inheritance and Superclass Data Members 166 A Subclass IS-A Superclass 167 Accessing Superclass Members 168 Constructors and Inheritance 169 Final Classes 170 Overriding and Polymorphism 171 Changing Behavior with Method Overriding 172 OO Concepts - Polymorphism 173 Polymorphism 174 Importance of Polymorphism 175 The super Keyword 176 Access Control - protected Access 177 Access Control - protected Access 178 Lab Inheritance and Polymorphism 179 class Object 187 Class Object 188 Methods of Class Object 189 Automatic Storage Management 190 Abstract Classes 191 Abstract Classes 192 Abstract Methods 193 Using Abstract Classes 194 Session Review 195 Session 6 - Interfaces 196 Session Objectives 197 What if All You Have to Share is an Idea 198 Interface Types 199 Interface Definitions 200 The implements Keyword 201 Example of Using Interface Types 202 Interface Types - Revisited 203 Interface Types - Revisited 204 Extending Interfaces 205 Implementing Extended Interfaces 206 Example of Using Interface Types 207 Example of Using Interface Types 208 Example of Using Interface Types 209 Interfaces are Abstract 210 Copyright LearningPatterns Inc. All rights reserved iii

4 Data Members in Interfaces 211 Implementing Multiple Interfaces 212 Lab Interfaces 213 Session Review 220 Session 7 - Exceptions 221 Session Objectives 222 Exception Hierarchy 223 Overview of Exceptions 224 Exception Hierarchy 225 Exception Hierarchy 226 Exception, Error, RuntimeException 227 Handling Exceptions try and catch 228 Handling Exceptions with try and catch 229 Exceptions and Program Flow 230 Variable Scope 231 The throws Clause 232 Throwing Exceptions with throw 233 User-Defined Exceptions 234 User-Defined Exceptions 235 Multiple catch Blocks 236 Multiple catch Blocks 237 finally Block 238 Runtime Exceptions 239 Lab Using Exceptions 240 Session Review 247 Session 8 - JDBC Java Database Connectivity 248 Session Objectives 249 JDBC Overview 250 Relational Database Description 251 Web-Based Data Access Architecture 252 What is JDBC? 253 JDBC Characteristics 254 JDBC Specification and Packages 255 JDBC Architecture and API 256 JDBC Architecture 257 The Fundamental JDBC API 258 The DriverManager Class 259 What is a JDBC Driver? 260 Drivers Must Be Loaded 261 Loading a Driver 262 Naming Databases with URLs 263 JDBC URL Syntax 264 Database Connections 265 Database Connections 266 Establishing a Database Connection 267 Database Connection - Example 268 Closing the Connection 269 Using finally to Close the Connection 270 Lab Connecting to a Database 271 Issuing Statements and Processing Data 282 Creating Statements 283 Copyright LearningPatterns Inc. All rights reserved iv

5 The Statement Interface 284 Using Statement - Example 285 The ResultSet Interface 286 Extracting Data from a ResultSet 287 SQL -> Java Type Mappings 288 Extracting Data from a ResultSet - Example 289 Prepared Statements 290 Using PreparedStatement - Example 291 Lab Using JDBC 292 Session Review 298 Session 9 Collections and Generics 299 Session Objectives 300 Overview 301 Java Collections Framework Overview 302 java.util Collection Interfaces 303 Collection Interface 304 List and ArrayList 305 List Interface 306 ArrayList 307 Using ArrayList - Example 308 The for-each Construct 309 Generics and Autoboxing 310 Generics and Type-Safe Collections 311 Life Before Type-Safe Collections - Example 312 Using Generics - Example 313 Autoboxing 314 Using Autoboxing/Unboxing - Example 315 Summarizing New Collections Features 316 Other Collection Types 317 Set Interface 318 Map Interface 319 HashMap 320 Creating and Using HashMap 321 Iterating Through a HashMap 322 Generic HashMaps Java Generic HashMap Example 324 Iterator 325 Processing Items with an Iterator 326 Iterator Interface 327 Using Iterator - Example 328 Lab Using Collections 329 More About Generics 335 What Are Generics 336 Summary - Basic Generics Usage 337 Inheritance with Generic Types 338 Inheritance with Generic Types 339 Assignment with Generic Types 340 Wildcard Parameter Types 341 Generic Methods 342 Session Review 343 Session 10 - Additional Language Features 344 Copyright LearningPatterns Inc. All rights reserved v

6 Session Objectives 345 Assertions (1.4) 346 Assertions Defined 347 Assertion Uses 348 Assertion Non-Uses 349 Assertion Syntax 350 Using Assertions to Check State - Example 351 Using Assertions to Check Flow of Control 352 Assuring Their Presence in Compiled Code 353 Enabling/Disabling Assertions at Runtime 354 Enabling/Disabling Assertions - Examples 355 What They Look Like at Runtime 356 Type-Safe Enums (5.0) 357 Enumerated Types Defined 358 Problems with int Enumerated Types 359 The enum Keyword 360 More enum Examples 361 switch on enum 362 for-each with enum 363 Advanced enum Features 364 Annotations (5.0) 365 The Issue 366 Annotations - The Solution 367 Example Applications 368 Session Review 369 Session 11 - I/O Streams 370 Session Objectives 371 Readers and Writers 372 Overview of I/O Streams 373 Character Streams 374 Class Reader 375 Class Writer 376 Common Reader Subclasses 377 Common Writer Subclasses 378 High-Level and Low-Level Streams 379 Using Readers and Writers 380 Using Readers and Writers - Example 381 Path Separators 382 Filter Streams 383 High-Level and Low-Level Streams 384 Using Filter Streams - Example 385 Filter Stream Base Classes 386 Creating Filter Streams - Example 387 InputStreams and OutputStreams 388 Java 1.0 Byte Stream Classes 389 Common InputStream Subclasses 390 Common OutputStream Subclasses 391 Converting between Streams and Readers/Writers 392 High-Level and Low-Level Streams 393 Converting Between Byte & Character Streams 394 Converting Between Byte & Character Streams 395 Copyright LearningPatterns Inc. All rights reserved vi

7 Character Stream & Byte Stream Equivalents 396 New I/O (NIO) APIs 397 New I/O (NIO) 398 NIO Features 399 NIO Features 400 Lab Using Readers and Writers 401 Session Review 405 Session 12: Nested / Inner Classes 406 Lesson Objectives 407 Nested and Inner Classes 408 Why Use Inner Classes 409 Example Inner Class 410 Example Inner Class 411 Types of Inner Classes 412 Anonymous Inner Classes 413 Static Inner Classes 414 Local Inner Classes 415 Summary 416 [Optional] Lab Using Inner Classes 417 Review Questions 422 Lesson Summary 423 Lesson Summary 424 Session 13: Reflection 425 Lesson Objectives 426 Reflection Overview 427 The Class Class 428 Getting Class Instances 429 Accessing Information About a Type 430 Accessing Information About a Type 431 Accessing Information About a Type 432 Lab 13.1 Inspecting with Reflection 433 Working With Constructor Objects 440 Creating an Object Using Reflection 441 Working With Method Objects 442 Invoking a Method Using Reflection 443 Working With Field Objects 444 [Optional] Lab 13.2 Invoking with Reflection 445 Review Questions 451 Summary 452 Summary 453 Session 14: Introduction to ant 454 Lesson Objectives 455 Overview 456 What is ant? 457 A Simple Build File 458 Running Ant 459 Installing and Running ant 460 Acquiring ant 461 ant Installation 462 Running ant 463 Command Line Options 464 Lab 14.1 Setting Up ant 465 Copyright LearningPatterns Inc. All rights reserved vii

8 ant Basics 472 ant Buildfiles and Projects 473 ant Targets 474 A More Complicated Buildfile 475 ant Tasks 476 The <javac> Task 477 The <java> and <delete> Tasks 478 A Complete Buildfile 479 Running our Buildfile 480 How is ant Useful? 481 Lab 14.2 Working with Buildfiles 482 Working With Properties 487 Working With Properties 488 Built-in Properties 489 Lab 14.3 Working with Properties 490 Session 15: Working with Paths and Resource Collections 494 Lesson Objectives 495 Paths 496 Path-like Structures 497 Specifying the Classpath 498 Nested <classpath> Element 499 Nested <classpath> Element 500 Lab 15.1 Working with Paths 501 Resource Collections 506 Resource Collections 507 Patterns 508 Patterns 509 Nested <include> and <exclude> 510 Other Uses of <fileset> 511 Using <path> 512 Lab 15.2 Working with Fileset 513 Session 16: Ant Tasks 516 Lesson Objectives 517 <javac> and <java> 518 <javac> - Specifying Source Files 519 <javac> - Compiler Options 520 <java> - Passing Arguments 521 <java> - forking and JVM arguments 522 Lab 16.1 Working with <javac> and <java> 523 Other Tasks 527 Creating Archives with <jar> 528 Creating Archives with <jar> 529 Creating Web Archives with <war> 530 Example of <war> 531 Example of <war> 532 Other Archive Tasks 533 File Related Tasks 534 Other Useful Tasks 535 Including New Tasks 536 [Optional] Lab 16.2 Working with <jar> and <war> 537 Session 17: Ant Modularity 544 Copyright LearningPatterns Inc. All rights reserved viii

9 Lesson Objectives 545 Properties Files 546 Properties Files 547 Lab 17.1 Working with Properties Files 548 [Optional] Modularizing Build Files 551 <import> - Importing Another Buildfile 552 Buildfile Defining Common Targets 553 Buildfile Importing Another 554 <ant> - Invoking Another Build 555 Using <ant> 556 [Optional] Lab 17.2 Review <import> and <ant> 557 Session 18: JUnit 560 Lesson Objectives 561 JUnit Overview 562 Testing Overview - Unit Testing 563 JUnit Overview 564 Writing a Test - Simple Example 565 Running a Test - Simple Example 566 Lab 18.1 Running JUnit 567 Writing JUnit Tests 574 What Is A Unit Test 575 The org.junit.assert Class 576 The org.junit.assert Class 577 The Assert Class and Static Imports 578 Writing Tests 579 A Simple Test Class 580 Testing For Exceptions 581 Running the Tests 582 The Result and Failure Classes 583 Example - Running Tests 584 What to Test 585 Lab 18.2 Working with JUnit 586 Session 19: Organizing Tests with JUnit 595 Lesson Objectives 596 Fixtures and Suites 597 Test Fixtures 598 Test Fixture Example 599 Test Suites 600 Test Suite Example 601 Lab 19.1 Test Fixtures and Test Suites 602 <junit> ant task 607 <junit> ant Task 608 <junit> Output 609 Setting Up Ant for Using <junit> 610 [Optional] JUnit JUnit 3 Overview 612 JUnit 3 Example 613 JUnit 3 Example 614 GUI Runner 615 Test Suites in JUnit Copyright LearningPatterns Inc. All rights reserved ix

10 Session 20: Introduction to Logging & log4j 617 Lesson Objectives 618 Overview 619 Logging Overview 620 Apache Log4J Overview 621 Apache log4j Overview 622 Using log4j 623 log4j - Simple Example 624 Lab 20.1 Using Log4j 625 Configuring log4j 629 Lab 20.2 Configuring log4j 630 Loggers, Levels, and Appenders 633 log4j Loggers 634 Using Loggers 635 log4j Appenders 636 Configuration File Details 637 Configuring Appenders and Loggers 638 Logger Hierarchy 639 Configuring Logger Levels 640 Level Inheritance 641 Lab 20.3 Configuring Levels 642 log4j Appenders 645 Configuring Appenders 646 Appender Additivity 647 Additivity Example 648 Lab 20.4 Appenders 649 Layouts 652 Layout 653 PatternLayout 654 PatternLayout 655 HTMLLayout 656 About Categories and Priorities 657 Lab 20.5 Layouts 658 Other Details 661 Disabling Debugging and Performance 662 Java Logging 663 Apache Commons Logging 664 Recap 665 Tools - Recap of what we've done 666 Tools - What Else is There 667 Tools Resources 668 Copyright LearningPatterns Inc. All rights reserved x

11 Intermediate Java and OO Development The Java Developer Education Series LearningPatterns Inc. Copyright LearningPatterns Inc. All rights reserved. 1

12 Course Overview This is a 5-day course that provides participants with a strong grounding in using Java in a productive manner It goes well beyond the basics and covers important topics such as composition, inheritance, polymorphism, interfaces and exceptions, JDBC, other advanced topics It also covers the use of tools such as ant and JUnit to make your programming more productive and your code of higher quality Be prepared to work hard and learn a great deal! The course consists of 50% discussion, 50% hands-on labs that exercise all the important concepts discussed The course is suitable for both a Java 5 and Java 6 environment Introduction The Java platform has evolved rapidly However, many people are still using older versions The labs are designed to support those using Java 5, as well as later versions JDK 6.0 primarily introduced advanced features for running Java programs, and did not chance the API, though it did add to it However, those features are beyond the scope of this course Accordingly, this course can be used in Java 6 environments as well as Java 5 Some of the new features introduced in Java 6 are Support for Web Services (JAX-WS) Rewrite of the user interface classes to better support native look and feel Increased security support JMX support Support for scripting in other languages Copyright LearningPatterns Inc. All rights reserved. 2

13 Workshop Agenda Session 1 Getting Started Session 2 Review: Class and Object Session 3 Review: Flow of Control, String and Array Session 4 Review: Packages Session 5 Composition and Inheritance Session 6 Interfaces Session 7 Exceptions Session 8 Java Database Connectivity (JDBC) Session 9 Collections and Generics Session 10 Additional Language Features Session 11 I/O Streams Session 12 Nested / Inner Classes Session 13 Reflection Continued Introduction Copyright LearningPatterns Inc. All rights reserved. 3

14 Workshop Agenda Session 14 Session 15 Session 16 Session 17 Session 18 Session 19 Session 20 Introduction to ant Ant Paths and Resource Collections Ant Tasks Ant Modularity Introduction to JUnit Organizing Tests with JUnit Introduction to Logging and log4j Introduction Copyright LearningPatterns Inc. All rights reserved. 4

15 Workshop Objectives - Java Review Java basics and basic OO programming concepts Understand advanced OO principles such as inheritance and polymorphism Use Java packages to organize code Understand interfaces, their importance, and their uses Understand how exceptions are used for error handling Understand the basics of Java Database Connectivity (JDBC) Learn the basics of the Collections Framework See some of the new/advanced Java language features Understand and use basic I/O streams Understand and use inner classes Understand Java reflection, and use it to examine classes at runtime Introduction Copyright LearningPatterns Inc. All rights reserved. 5

16 Workshop Objectives - Tools ant: Understand how ant and buildfiles work Create buildfiles, and use ant to control a build Use the many built-in ant tasks Build modular buildfiles JUnit: Be familiar with testing and test-driven development Use JUnit to create good testing structures for your Java code Logging: Understand and use log4j for logging Be aware of other logging choices available in Java Introduction Copyright LearningPatterns Inc. All rights reserved. 6

17 Course Methodology This course reviews basic Java and Object-Oriented (OO) programming, and covers more advanced concepts in depth Including composition, inheritance, exceptions, JDBC, inner classes, reflection Including the tools; ant, JUnit and log4j Basic Java knowledge and programming experience is required The concepts and syntax are reinforced by frequent practice in the form of hands-on labs Labs are done using the Eclipse development environment The lab solutions are provided on a CD We use a very simple development environment, as its easier to learn concepts that way * Introduction For this course, we don't use a sophisticated IDE like Eclipse, because that often helps you "too much" It can shield you from some of the intricacies of the language Normally, when productivity is a goal, that's a good thing However, when you're trying to learn about those intricacies, it can get in the way Accordingly, we use a very simple editor for writing the code, and the JDK from a command prompt for compiling and executing This lets you see, and learn, exactly what is going on In the later tool sections, once you have learned the language features, we use ant to compile and run to make labs go faster Copyright LearningPatterns Inc. All rights reserved. 7

18 Labs Lab The workshop consists of approximately 50% discussion, 50% hands-on lab exercises, including a series of brief labs The labs are contained directly in the course book, and have detailed instructions on what needs to be done NOTE: Read the notes sections of for the labs there are often tips and examples there to help you The lab numbering follows the session numbering e.g., Lab 3.2 for the second lab in Session 3 The course includes a setup zip file with any needed lab code It also creates a directory structure for the labs There is also a solution zip file that contains completed lab code Lab slides contain an icon like the one in the upper right corner of this slide The end of each lab is clearly marked with a stop STOP like this one to the right Introduction Copyright LearningPatterns Inc. All rights reserved. 8

19 Release Level Lab This manual contains instructions for creating and running the labs using the following Java platforms: Java 5 or Java 6 Eclipse Java EE version - any recent release Apache Ant (any recent ant version should work) All labs have been tested on Windows XP Complete lab instructions for this platform are included in the student manual Introduction Sun Microsystems recently changed the version numbering of the Java Software Development Kit. After version 1.4.2, the next version was called 5.0. However, note that the default home directory path for a 5.0 installation contains references to the fact that it is really version 1.5 renamed, i.e., C:\Program Files\Java\jdk Copyright LearningPatterns Inc. All rights reserved. 9

20 Typographic Conventions Code that is inline in the text will appear in a fixed-width code font, such at this: JavaTeacher teacher = new JavaTeacher() Any class names, such as JavaTeacher, method names, or other code fragments will also appear in the same font If we want to emphasize a particular piece of code, we'll also bold it (and in the slide, change it's color) such as BeanFactory Filenames will be in italics, such as JavaInstructor.java We sometimes denote more info in the notes with a star * Lastly, longer code examples will appear in a separate code box as shown below package com.javatunes.teach; public class JavaInstructor implements Teacher { public void teach() { System.out.println("BeanFactories are way cool"); } } Introduction Additional notes would appear here Copyright LearningPatterns Inc. All rights reserved. 10

21 Session 1 - Getting Started Copyright LearningPatterns Inc. All rights reserved. 11

22 Session Objectives Look at a simple Java program, and how it is compiled and run Set your computer up for Java development Setting paths, environment variables, etc. Use a text editor to type in a simple Java class Use the Java Development Kit to compile and run the code Session 1: Getting Started Copyright LearningPatterns Inc. All rights reserved. 12

23 A Simple Application Class To get started, we'll look at a very simple Java application, that displays the string "Hello World" This is a simple non-graphic standalone application that runs on its own All programs in Java are just a class with a main method in it The HelloWorld class needs to appear in a file HelloWorld.java The main method is a special method that is the starting point for every Java application It must be declared as shown, and has to appear in a class System.out.println how you print things to the console public class HelloWorld { public static void main(string[] args) { System.out.println("Hello World"); } } Session 1: Getting Started Java classes can be deployed into several runtime execution environments, including: Standalone applications that are run explicitly, like our Hello World application. Servlets, which are run in a Web server. Applets, which are downloaded from a Web server and run in a Web browser. We will concentrate on applications in this course. main is the special method which is the starting point for every standalone Java application. Applets and servlets work a little differently The main method has to appear inside a class. main takes an argument an array of Strings. This array holds arguments that are given on the command line when the application is run. System.out.println causes something to be printed to System.out, which is the standard output (the console ) more on this later. Copyright LearningPatterns Inc. All rights reserved. 13

24

25 Java Source and Java Bytecode You write a program in the Java programming language And store it in a.java file, for example MyClass.java Before running it, you compile it, which translates it into an intermediate language called Java bytecode Stored in a.class file, for example MyClass.class These are platform independent codes that are interpreted by an interpreter, the Java Virtual Machine, or JVM You can think of bytecode as the native instructions for the JVM Bytecode helps make "write once run anywhere" possible The JVM converts the bytecode into the native code for the target machine it is running on Session 1: Getting Started Copyright LearningPatterns Inc. All rights reserved. 15

26 Life Cycle of a Java Program Java Source Code HelloWorld.java public class HelloWorld { } Java Compiler javac Java Bytecode HelloWorld.class 0 aload_0 1 invokespecial #3 4 aload_0 5 aload_1 UNIX JVM java Windows JVM java Solaris JVM java MVS JVM java Mac OS JVM java UNIX Native code Windows Native code Solaris Native code MVS Native code Mac OS Native code Session 1: Getting Started The JVMs for Solaris and Windows are available from Sun Microsystems. JVMs for other platforms are available from their respective vendors. Copyright LearningPatterns Inc. All rights reserved. 16

27 Java Programs Insulated From Environment Java provides a platform that programs can run on independently of the environment It is a software only platform made up of the Java API and the JVM SomeProgram.java Java API Java Virtual Machine Native Platform Session 1: Getting Started Copyright LearningPatterns Inc. All rights reserved. 17

28 Java is Dynamic - The Runtime Process Several phases take place at runtime Java Bytecode HelloWorld.class Includes symbolic reference information from the compiler Java Class Loader java Loads bytecode into memory Java Verifier java Java Interpreter java Confirms that bytecodes are valid and follow security rules Translates bytecode into native code and performs final name resolution (linking) Session 1: Getting Started Copyright LearningPatterns Inc. All rights reserved. 18

29 Lab HelloWorld Copyright LearningPatterns Inc. All rights reserved. 19

30 Lab 1.1 A Simple Java Program Lab Overview: In this lab, we will set up and use Eclipse, and then compile and run a very simple Java program Objectives: Become familiar with the lab structure Set up and use Eclipse Write a very simple Java program Use Eclipse to compile and execute the program Builds on previous labs: None Approximate Time: minutes Lab 1.1: HelloWorld Copyright LearningPatterns Inc. All rights reserved. 20

31 Information Content and Task Content Lab Within a lab, information only content is presented in the normal way the same as in the student manual pages Like these bullets at the top of the page Tasks that the student needs to perform are in a box with a slightly different look to help you identify them - like the one below Tasks to Perform Look at these instructions, and notice the different look of the box as compared to that above Make a note of how it looks, as future labs will use this format Make sure that you have Java installed Likely installed in a directory like C:\Program Files\Java\jdk1.5.0_06 * If not, you'll need to install it - It can be downloaded from: OK Now get out your setup CD; we're ready to start working Lab 1.1: HelloWorld If you are using a different version of Java, then the installation directory will change accordinglyfor example: For Java 1.4 it will be something like: C:\j2sdk1.4.2_08 Java 6, it will be something like: C:\Program Files\Java\jdk1.6.0_03 The setup zip will either be given to you on a CD or supplied by your instructor Copyright LearningPatterns Inc. All rights reserved. 21

32 Extract the Lab Setup Zip File Lab To set up the labs, you'll need the course setup zip file * It has a name like: INTMJ_Eclipse_LabSetup_ zip Our base working directory for this course will be C:\StudentWork\INTMJ This directory will be created when we extract the Setup zip It includes a directory structure and files (e.g., Java files and other) that will be needed in the labs All instructions assume that this zip file is extracted to C:\. If you choose a different directory, please adjust accordingly Unzip the lab setup file to C:\ Tasks to Perform This will create the directory structure, described in the next slide, containing files that you will need for doing the labs Lab 1.1: HelloWorld The CD may also contain additional folders with extra content InstallFiles: Extra software install files (e.g. simple editor) Resources: Documentation, specifications, etc. Which extra files are supplied will vary based on space limitations Copyright LearningPatterns Inc. All rights reserved. 22

33 Lab Directory Structure Lab StudentWork\INTMJ contains Derby: Database for JDBC labs LabSetup: setup files needed for labs LabNN: subdirectory for a lab with setup files Resources : Extra files (e.g. docs), software workspace: Lab directories StudentWork\INTMJ\workspace will contain the following folders: common: shared files LabNN : Root directory for Lab NN - contains skeleton files for the labs otherdirectories : Sample code that is not a lab done by students Lab 1.1: HelloWorld Some of the labs have a directory already present under the workspace directory We do this to supply files that are needed for the labs in an easy to use manner Other labs don't need any files, so there is no directory present for them You just make the directory when you start the lab The lab instructions will tell you clearly where to do each lab Copyright LearningPatterns Inc. All rights reserved. 23

34 The Eclipse Platform Lab Eclipse ( is an open source platform for building integrated development environments (IDEs) - Used mainly for Java development - can be extended via plugins and used in other areas (e.g. C# programming) Originally developed by IBM Released into open source IBM's RAD environment is built on top of Eclipse Eclipse products have two fundamental layers The Workspace files, packages, projects, resource connections, configuration properties The Workbench editors, views, and perspectives We will set up the workspace and workbench, then describe it in more detail at the end of the lab Lab 1.1: HelloWorld The Workbench sits on top of the Workspace and provides visual artifacts that allow you to access and manipulate various aspects of the underlying Workspace resources. If you need to download Eclipse, go to Under the Eclipse Packages section, click on the link for the Eclipse IDE for Java EE Developers You can also use the plain Java version, but the Java EE version is more versatile Save the zip file to your computer, and unzip it (easiest location to unzip it to is C:\, but another location is fine as long as you can get to it to run the eclipse.exe executable) Copyright LearningPatterns Inc. All rights reserved. 24

35 Getting Started With Eclipse Lab Tasks to Perform Make sure you have Eclipse installed - likely in C:\eclipse If not - you'll need to install it - see instructions in notes Launch Eclipse: Go to c:\eclipse and run eclipse.exe A dialog box should appear prompting for a workbench location Set the workbench location to C:\StudentWork\INTMJ\workspace If a different default Workbench location is set, change it In the window that opens, click the Workbench icon (see notes) Lab 1.1: HelloWorld You can also put a shortcut on your desktop to start Eclipse The workbench icon is in different places in Eclipse 3.4 (below on left) and 3.5 (below on right) Copyright LearningPatterns Inc. All rights reserved. 25

36 Workbench and Java Perspective Lab Tasks to Perform You'll likely be in a Java or Java EE perspective - depending on which Eclipse version you use - If in a Java perspective, that's fine - there is nothing else to do If in a Java EE perspective, open a Java one by clicking the Perspective icon at the top right of the Workbench, and select Java (as shown below left) Close the Java EE perspective by right clicking its icon, and selecting close (as shown below right) Lab 1.1: HelloWorld Copyright LearningPatterns Inc. All rights reserved. 26

37 Unclutter the Workbench Lab Tasks to Perform Let's unclutter the Java Perspective by closing some views Close the Task List, Outline and Hierarchy views (click on the X) Open the Navigator View (Window Show View Navigator) You can save this as the default if you want (see note) Lab 1.1: HelloWorld To save the perspective as the default Java perspective go to Window Save Perspective As Java You can reset the perspective to it's defaults via Window Reset Perspective Copyright LearningPatterns Inc. All rights reserved. 27

38 Create a Project for our Application Lab Tasks to Perform Close any open welcome screens Create a Java Project * Call the project Lab01.1 Make sure Create new project in workspace is checked Eclipse will then automatically set the project directory to Lab01.1 Click Next This will bring you to a dialog where you can set the Java Settings for the project Lab 1.1: HelloWorld To create a new Java Project, use the menu item File New Project Java Java Project There are many other ways to create a project You can use the new icon on the left hand side of the toolbar, as shown above You will need to create a new Java project in Eclipse each time the lab instructions tell you to use a new Lab directory This happens several times in the course, and you'll need to create a new project each time Copyright LearningPatterns Inc. All rights reserved. 28

39 Create a Project for our Application Lab Tasks to Perform The defaults are fine in the next dialog Click Finish Lab 1.1: HelloWorld Copyright LearningPatterns Inc. All rights reserved. 29

40 Your First Application Lab Tasks to Perform Create a new Java class within the project * File New Class Call the class HelloWorld Generate a main method by checking the box in the dialog Click Finish HelloWorld.java will open in the editor Add in some simple code that prints to the console (see notes) Lab 1.1: HelloWorld There are multiple ways to get to the new class wizard File New... Right Click in a View New... New Toolbar Icon New... Etc. Don't worry about the warning that "The use of the default package is discouraged" We'll learn about and use packages later You can add in a simple line of code in main() to produce output System.out.println("Hi"); Copyright LearningPatterns Inc. All rights reserved. 30

41 Compilation and the Problems View Lab Tasks to Perform After building the project (either automatically or manually), you should resolve any warnings or errors the compiler adds to the Problems view The Problems view gets populated via problems in your code A compiler may add errors and warnings that need resolution Clicking on a problem will immediately move you to the location in the code associated with that problem Add an error in your code to see it in the problem view See the next slide for an example Lab 1.1: HelloWorld By default classes get compiled when you save the source file This setting can be changed in the Workbench Preferences window: Window Preferences General Workspace by Checking/Unchecking the Build Automatically selection It's usually best to leave the setting to build automatically Copyright LearningPatterns Inc. All rights reserved. 31

42 Seeing a Problem Lab Tasks to Perform Notice the missing semicolon at the end of line 17 Note the error message in the problem view Note: Line numbers can be turned on via the menu selection: Window Preferences General Editors Text Editors Check the Show line numbers box Lab 1.1: HelloWorld Copyright LearningPatterns Inc. All rights reserved. 32

43 Testing your Application Lab Tasks to Perform After a clean build (one that is error-free, but not necessarily warning-free), test the application as follows Select HelloWorld.java in the Navigator or Package Explorer view Click the run button arrow on the task bar * Choose Run As Java Application from the menu that appears Lab 1.1: HelloWorld To run the application you can also select Run from the menu You can also right click on the HelloWorld.java file and select Run As Copyright LearningPatterns Inc. All rights reserved. 33

44 Testing your Application Lab Tasks to Perform You will see the results in the console view as shown below If necessary, open the Console (Window Show View Console) To run again, you can press the Run Icon as shown at bottom This brings up a list of previously run programs that you can pick from Just select the HelloWorld program Lab 1.1: HelloWorld When you select the Run icon, it shows a list of the existing launch configurations The configurations are named, and will appear in the run drop downs when you click on it See the next slide for information on launch configurations Copyright LearningPatterns Inc. All rights reserved. 34

45 Launch Configurations Lab Eclipse actually creates a Launch configuration to run the program These allow you to customize the execution of an application You can look at it by going to the Run icon, selecting Open Run Dialog, and selecting HelloWorld from the dialog that comes up Lab 1.1: HelloWorld As you see, the launch configuration has all the information necessary to run the program Including the project, and the class that has the main method in it We'll need to work with the launch configuration in the future when we use program arguments that are passed to the main method Copyright LearningPatterns Inc. All rights reserved. 35

46 The Project Directory Lab Tasks to Perform Look at the C:\StudentWork\INTMJ\workspace\Lab01.1\ - src and bin directories You ll see HelloWorld.java and HelloWorld.class files (in src and bin) In the project root, you can also see.project and.classpath files that are used by Eclipse to maintain the project Lab 1.1: HelloWorld Copyright LearningPatterns Inc. All rights reserved. 36

47 Important Notes for Using Eclipse Lab Any lab that has a new lab directory will require you to create a new Eclipse project Sometimes several labs are done one directory, in which case you will use the same project for all of them If you COPY files into a project directory using the file system (e.g. lab setup files) you need to Refresh the project Right click on the project, select Refresh You can also copy directly into an Eclipse view (e.g. Navigator View) in which case a refresh is not needed For anyone not familiar with Eclipse, the next few slides give a (very) brief overview of how Eclipse is structured There is nothing you need to do in those slides they are for information purposes only Lab 1.1: HelloWorld Take note of the Lab instructions Any lab that starts out saying that it will be done in a new directory will require you to create a new Java project You'll create the project with the name of the directory specified in the lab Any lab that has you copy files from the setup to your working directory will require you to refresh the project as described above This allows Eclipse to become aware of the new files. Copyright LearningPatterns Inc. All rights reserved. 37

48 The Eclipse Paradigm Lab Eclipse products have two fundamental layers The Workspace files, packages, projects, resource connections, configuration properties The Workbench editors, views, and perspectives The Workbench sits on top of the Workspace and provides visual artifacts that allow you to access and manipulate various aspects of the underlying resources, such as: Editor A component that allows a developer to interact with and modify the contents of a file. View A component that exposes meta-data about the currently selected resource. Perspective A grouping of related editors and views that are relevant to a particular task and/or role. You can have multiple perspectives open to provide access to different aspects of the underlying resources Lab 1.1: HelloWorld The physical directory structure for the Workspace can be found in the workspace directory The default location is under the Eclipse home directory You can specify a different workspace location when you start Eclipse It is even possible to set up multiple workspaces (with corresponding Workbenchs). Simply create a folder to house the additional workspace, and write a script that uses the Eclipse executable file and supplies the data argument with the location of the workspace directory to load: eclipse.exe -data other_workspace_folder A Perspective is basically a collection of views that are focused on a given task They provide different tools to work with the resources For example, the debugging perspective has views open for debugging, such as: Active Threads, Variables, Breakpoints, etc. There are perspectives for Java development (Java Perspective), and so on What perspectives are available depends on what version of Eclipse you have, and what plugins you have installed Copyright LearningPatterns Inc. All rights reserved. 38

49 Workbench and Workspace Lab Workspace (Model) Workbench (View) Lab 1.1: HelloWorld We use the terms Model and View here in the same sense as when talking about Model-View-Controller (MVC) The Model is the actual data (the files) The View is the Eclipse Workbench Copyright LearningPatterns Inc. All rights reserved. 39

50 Navigator View Lab Shows how different resources are structured There are three kinds of resources: Files Correspond to files on the file system Folders Like directories on the file system Projects Used to organize all your resources and for version control. When you create a new project, you assign a physical location for it on the file system. A third-party SCM (Source Control Manager) may be used to properly share project files amongst developers. Lab 1.1: HelloWorld The Navigator view is one of the most commonly used views. It provides a file-based organization of the various resources. There are other views that give application-based, and project-based organization of data Here we show a class - HelloWorld.java Copyright LearningPatterns Inc. All rights reserved. 40

51 Package Explorer Lab The Package Explorer view, is shown by default in the Java perspective It shows the Java element hierarchy of the Java projects in your workbench It provides a Java-specific view of the resources shown in the Navigator It also makes it easy to work with Java resources for example to create a new class, just click on the package you want and select New Class * Lab 1.1: HelloWorld Copyright LearningPatterns Inc. All rights reserved. 41

52 Editors Lab There is a source editor (like this one for a.java file) for all character files. (.java,.jsp,.html, etc.) STOP Lab 1.1: HelloWorld Copyright LearningPatterns Inc. All rights reserved. 42

53 Session 2 Review: Class and Object Defining Classes Working with Methods and Data Encapsulation and Access Control Constructors Other Capabilities Copyright LearningPatterns Inc. All rights reserved. 43

54 Session Objectives Create and test a class definition in Java, complete with Instance variables Getter/setter methods Constructors Session 2: Review Class and Object Copyright LearningPatterns Inc. All rights reserved. 44

55 Defining Classes Defining Classes Working with Methods and Data Encapsulation and Access Control Constructors Other Capabilities Session 2: Review Class and Object Copyright LearningPatterns Inc. All rights reserved. 45

56 Classes and Objects A class is one way to define a new type in Java Think of it as the blueprint that describes the properties and behavior of a type of object Properties are attributes or data representing the object s characteristics Methods perform the behaviors of an object An object or instance is the actualization of what a class describes as shown in the UML based diagrams below CLASS Person name : String age : double standup() : void drink() : void OBJECT/INSTANCE Person name="joe Montana" age=35 REFERENCE boss Session 2: Review Class and Object If Person is a class it might contain name and age properties. Our Person class might have methods to standup() and drink(). Another example: a house is described by an architectural diagram The diagram can be used to make an unlimited number of the same kind of house The house is the object and the diagram is the class that describes how to make houses Note that the method of diagramming classes used above is similar to class diagrams used in UML the Unified Modeling Language The rectangle in the diagram denotes the class and consists of: The classname (Person) The data fields, with their type (e.g. name : String) The methods with their return value (e.g. standup() : void) The Object/Instance rectangle denotes an instance (indicate by underlining the classname Person) and consists of The classname (Person) The data fields, with their values Copyright LearningPatterns Inc. All rights reserved. 46

57 The Class in Java A class is defined in a class definition A class may contain both data and methods Everything happens within classes There are no global data or methods Here is the syntax for defining a class // define a class to represent an alarm clock public class AlarmClock { /* Details omitted } You create, or instantiate, instances of a class using the new operator and the class name, in an allocation expression AlarmClock analarmclock = new AlarmClock(); Session 2: Review Class and Object Some directives, such as the import and package directives, appear outside a class. They don't actually create anything, or execute code. We will discuss them later. The class keyword introduces the class AlarmClock is the name of the class {starts the class body, data and methods are declared within the body, } ends the class Generally, a variable is used to reference an object instance A variable contains data, and has a name and a type In the example in the slide, the left hand side declares a variable whose type is AlarmClock, and initialize it to reference our newly created AlarmClock instance When you're starting out with Java, it can be hard to understand when you're creating objects As opposed to just passing them around The new operator is a sure indication that an object is being created The heap is a common pool of memory that is available to your program Think of the heap as a huge ball of memory dough that you can pull chunks off of to make objects Note that we'll often use the terms instance and object interchangeably Copyright LearningPatterns Inc. All rights reserved. 47

58 Storing Data in Objects Classes can have data associated with instances of the class This data is declared in instance fields (or instance variables) in the class We can access a field from outside the class, by referencing it through an instance You use the dot operator. to access members within a class // class AlarmClock with instance variable for snooze time public class AlarmClock { // Variable declared & initialized to 100 (see notes) int snoozeinterval = 100; } // Example of accessing a field with an instance public class EarlyMorning { public static void main(string[] args) { AlarmClock myclock = new AlarmClock(); int snoozeinterval = myclock.snoozeinterval; } } Session 2: Review Class and Object As their name indicates, instance fields can vary from instance to instance Each instance of a class has its own copy of a field Whenever a new instance of a class is allocated, space is allocated for all the fields within the class This makes sense every person has their own name, each clocks stores its own time The fields in an instance are initialized to a default value You can also have an initializer for the instance variable, usually to hold some standard value for your program We'll look soon at the actual data and data types for variables Default values include: Integer/Floating point primitive types: 0 / 0.0 boolean primitive type: false char primitive type: \u0000 class type: null Accessing a field directly through an instance is legal Java, but NOT good practice We'll talk more about this later Copyright LearningPatterns Inc. All rights reserved. 48

59 Behavior and Methods Java defines behavior in methods, that are declared and defined in the body of a class public class AlarmClock { void snooze() { System.out.println("ZZZZZ"); } } They associate executable code with classes, they can return values, they can be passed arguments Methods are invoked by using an instance, followed by the dot operator. and then the method name public class EarlyMorning { // Program using AlarmClock public static void main(string[] args) { AlarmClock myclock = new AlarmClock(); myclock.snooze(); } } Session 2: Review Class and Object All method definitions must appear within the body of a class definition. A void return value means nothing is returned You always need an instance for a regular method Copyright LearningPatterns Inc. All rights reserved. 49

60 Data Access and Return Values in Methods Methods in a class can access the instance variables Methods can return values using the return keyword public class AlarmClock { int snoozeinterval = 100; int getsnoozeinterval() { return snoozeinterval; } // Must return an int // Returns the instance var } void snooze() { /* */ } public class EarlyMorning { public static void main(string[] args) { AlarmClock myclock = new AlarmClock(); // int snoozeinterval = myclock.getsnoozeinterval(); System.out.println("More sleep: " + snoozeinterval); myclock.snooze(); } } Session 2: Review Class and Object You simply access fields in a class using the name of the variable (snoozeinterval in this example) The data accessed is the data in the particular instance that the method is called with Remember that there is always an instance associated with a normal method call return must return a value of the type identified in the method signature. Copyright LearningPatterns Inc. All rights reserved. 50

61 Pretty Pictures AlarmClock myclock = new AlarmClock(); snooze() int snoozeinterval = myclock.snoozeinterval; snoozeinterval: 0 int snoozeinterval = myclock.getsnoozeinterval(); getsnoozeinterval() Session 2: Review Class and Object Copyright LearningPatterns Inc. All rights reserved. 51

62 About Java Primitive Data Types All data in Java has a type The possible types are: Class or interface type, e.g., List (we will cover these later) One of the primitive types: Type Size (bits) Range byte to 127 short 16-32,768 to 32,767 int 32-2,147,483,648 to 2,147,483,647 long 64-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 float 32 ±1.4E-45 to ±3.40E+38 double 64 ±4.9E-324 to ±1.797E+308 char 16 Unicode character set boolean true or false Session 2: Review Class and Object All numeric types are signed, that is they can hold both positive and negative numbers. float and double conform to the 1985 IEEE 754 standard, including NaN, Infinity, etc. To ensure portability, primitive types have the same strictly specified representations on all platforms. Integer values default to type int (recommended usage). Floating point values default to type double (recommended usage). Java uses the Unicode character set this 16-bit international character set includes: The characters "A" through "Z" and "a" through "z". Other familiar characters, such as "$" and "_". A number of foreign language character sets. ASCII is a subset of Unicode (the first 256 characters). Copyright LearningPatterns Inc. All rights reserved. 52

63 Strings Java handles strings in a special way There is a class String that Java defines to represent strings You can declare a string using the type String, and initialize it with a double-quoted string literal String hi = "Hello"; We'll look at the details after we know a little more about classes A string literal is a sequence of characters in double-quotes, e.g., "Hello World" Session 2: Review Class and Object Copyright LearningPatterns Inc. All rights reserved. 53

64 Lab Writing a Class Definition Lab 2:.1 Writing a Class Definition Copyright LearningPatterns Inc. All rights reserved. 54

65 Lab 2.1 Class Definition Lab Overview: In this lab, we will create a class that has methods and instance variables We will also write and run a test program that creates instances of the class and works with those instances NOTE: we will continue to modify and add to this class as we learn more of Java's capabilities Objectives: Define a new class with methods and instance variables Use that class in a program Builds on previous labs: None Approximate Time: minutes Lab 2:.1 Writing a Class Definition Copyright LearningPatterns Inc. All rights reserved. 55

66 Lab Preparation Lab The root lab directory where you will do all your work is: C:\StudentWork\INTMJ\workspace\Lab02.1 This is a new lab directory We will create a class named Television It will contain brand and volume instance variables to work with the concepts we just learned (but no main method) We will also create a class named TelevisionTest It will have a main method where you create instances of Television, get the property values using the get methods, and print them Note that the word property is often used to describe the data values of an object Tasks to Perform Close all files you have open for editing, and close all projects * Create a new Java project called Lab02.1 in your workspace See the Lab 1.1 instructions on how to do this if you don't remember Lab 2:.1 Writing a Class Definition For Eclipse, and most likely for any other project based environments you might be using, you'll need to do the same configuration you did for the first project you created For example, adding in user libraries, or modifying the classpath by adding in jars or libraries For this simple lab, there aren't any library or classpath issues to deal with To close a project, just right click on it, and select Close Project Copyright LearningPatterns Inc. All rights reserved. 56

67 Creating a Class Lab Tasks to Perform Create a new class called Television This will be in a file named Television.java Use the new class wizard as you did in the earlier lab In your Television class, declare two instance variables: String brand; int volume; // brand of Television // current volume Write methods to access our data * Create getter methods for each data element - The method names should start with get and be followed by the logical name of the variable, e.g., getvolume What should the complete signature of the get methods be? Refer to the AlarmClock class code for an example Lab 2:.1 Writing a Class Definition WARNING: Java is case-sensitive! If you create a class named Television, then it must be saved in a file named Television.java. If you save it in a file named television.java, you will end up having problems later. The method names should follow the same conventions as variables, i.e., first "word" in lower case, each subsequent "word" capitalized, e.g., setvolume, getvolume, etc. For any method parameters you may wish to use some other naming convention, like volumein, brandin, etc. Copyright LearningPatterns Inc. All rights reserved. 57

68 Writing a Test Class Lab Tasks to Perform Create a new class, TelevisionTest Include a main method in TelevisionTest Eclipse will add in a main method for you when you are creating the class if you check off the appropriate box in the new class wizard In the main method of TelevisionTest, instantiate two Televisions You'll need Television references also, of course Television tv1 = (what goes here?) Use System.out.println to print out the values of each of the properties in each Television object Use the get methods to access the properties (see notes) Lab 2:.1 Writing a Class Definition Again, TelevisionTest will be saved in a file named TelevisionTest.java Your System.out.println can look something like this: System.out.println("Television: brand=" + tv1.getbrand() + ", volume=" + tv1.getvolume()); It's good practice to use a comment on each line above or next to your declaration of a variable, describing what the variable is. NOTE: we normally make all our data private, for design reasons. We will discuss that later in this session. NOTE: We are creating classes in the default package right now This isn't recommended practice, and we'll move them into a package later In our compile command, we're now using wildcards (the * character) to specify "any file that ends with the.java extension This is easier than listing all the.java files separately From now on, we'll assume that you know that you need to compile your code after any modifications, and won't mention it anymore Copyright LearningPatterns Inc. All rights reserved. 58

69 Running the Program Lab Tasks to Perform Run your program (see notes) You have two classes now, Television and TelevisionTest Which class should be your class to run the program? java Television java TelevisionTest Hint: Use the one with the main method in it Is the output what you expect? Next, add initializers in Television for brand and volume String brand = "Sony"; int volume = 17; Run the program again. What do you see now? Lab 2:.1 Writing a Class Definition Select your.java file in the Navigator or Package Explorer view Click the run button arrow on the task bar Choose Run As Java Application from the menu that appears What happens if you try to run a class with no main method? Try it and see. Copyright LearningPatterns Inc. All rights reserved. 59

70 Additional Things to Do Lab Tasks to Perform Try accessing the instance variables directly instead of using the get methods e.g. try doing something like tv1.brand instead of tv1.getbrand() Run your program - what happens? This will work for now Leave at least one access like this, as we'll use it to illustrate encapsulation in the next lab Eclipse includes several very useful features to assist in writing software by hand Some of these features can be accessed via the Edit menu and hotkeys Some features are only accessible by right clicking in the editor window Look at the following slide, and take a few minutes to experiment with some of the features Lab 2:.1 Writing a Class Definition Copyright LearningPatterns Inc. All rights reserved. 60

71 Handy Editor Features Some of the more common features include Undo (C-Z), Redo (C-Y), Cut (C-X), Copy (C-C), Paste (C-V), Select All (C-A]), etc. Content Assistance ( C-spacebar ) Code Formatting ( Select code, right-click, Source Format ) Jump to a Line ( C-L ) Find/Replace ( C-F ) Add bookmark ( Edit menu or right-click on source line) Add task or breakpoint ( right-click in left margin ) Searching: ( C-H ) Note that C- is an abbreviation for pressing the Ctrl key along with the associated key STOP Lab 2:.1 Writing a Class Definition Copyright LearningPatterns Inc. All rights reserved. 61

72 Working With Methods and Data Defining Classes Working with Methods and Data Encapsulation and Access Control Constructors Other Capabilities Session 2: Review Class and Object Copyright LearningPatterns Inc. All rights reserved. 62

73 Working Within Methods Method parameters are used to pass data to a method You use parameter specifiers that consist of a type and a name You can access parameters and instance variables in the method public class AlarmClock { int snoozeinterval = 0; void setsnoozeinterval(int snoozein) { snoozeinterval = snoozein; } } When you call the method, you can pass data via the parameters public class EarlyMorning { public static void main(string[] args) { AlarmClock myclock = new AlarmClock(); // Pass in a value for the parameter when invoking myclock.setsnoozeinterval(1000); } } Session 2: Review Class and Object Parameters are local to the method they are used in. When invoked, the compiler checks the type of the parameters passed in to the type declared in the method signature. It's good practice to name the method parameters so they're easily identifiable in the method body This helps to keep from confusing them with instance fields In this example, we've ended the parameter with the word in (calling it snoozein) Other common names are things like newtime If you have more than one parameter, use a comma-separated list of parameter specifiers If our snooze time consisted of separate hour and minute values (hey, we need our sleep), we could declare a method and call it as below, : void setsnoozeinterval(int hourin, int minutein) // Elsewhere in code myclock.setsnoozeinterval(1, 30); Copyright LearningPatterns Inc. All rights reserved. 63

74 Local Variables You can declare local variables within a method These are accessible only within the method public class AlarmClock { int snoozeinterval = 0; void setsnoozeinterval(int snoozein) { int oldsnooze = snoozeinterval; snoozeinterval = snoozein; System.out.println("Old time was " + oldsnooze); } } There is a special variable called this, available inside every instance method, which refers to the object itself public class AlarmClock { int snoozeinterval = 0; // what if parameter names & field names are the same? void setsnoozeinterval(int snoozeinterval) { this.snoozeinterval = snoozeinterval; } } Session 2: Review Class and Object Local variables are also called automatic variables because the storage is automatically allocated (on the stack) and then reclaimed when the method exits So we now have two types of variables: Local or automatic variables. Declared within a method block, Must be initialized, Destroyed when the method exits. Instance or member variables. Declared inside a class but not inside a method block, Exist as long as the object exists. Will be initialized with default values if initializer isn't used. (Initialized to "zero" for that type.) The this variable is often not needed, but it is available when it is There are two common occasions when the this variable is used When you need to clarify that an instance variable is being referred to, as opposed to a local variable of the same name When an object needs to pass a reference to itself to some other objects which will be easier to understand after we talk more about how objects collaborate Copyright LearningPatterns Inc. All rights reserved. 64

75 Overloading Methods You can have multiple versions of a method that work with different kinds of data - This is called method overloading The methods must have different parameter lists They may have different return types For example, System.out.println( ) works with anything // System.out is actually a PrintStream object - detail omitted public class PrintStream { public void println(object obj) { /*... */ } public void println(string s) { /*... */ } public void println(int i) { /*... */ } // etc. } The version that is used is determined at the point of call public static void main(string[] args) { System.out.println("2 + 2 = "); // call println(string) System.out.println(4); // call println(int) } Session 2: Review Class and Object When an overloaded method is called, the actual arguments to the call are used at compile time to determine which method will be invoked Java looks at the parameters, and uses the method whose parameter list most closely matches the passed parameters The return type is not used to resolve the call We'll see shortly what the public modifier means We'll also talk more about System.out.println Copyright LearningPatterns Inc. All rights reserved. 65

76 The tostring() Method The tostring() method is a special method defined by Java to "return a String representation of the Object" What that means, is left up to the developer of each class There is a default version which returns a string formed by concatenating the class name and the return value of the (default) hashcode() method (defined in class Object) You can override the default tostring() public class AlarmClock { int snoozeinterval = 0; } // Here's a very simple version public String tostring() { return "You're set to snooze for: " + snoozeinterval; } Session 2: Review Class and Object Copyright LearningPatterns Inc. All rights reserved. 66

77 Encapsulation and Access Control Defining Classes Working with Methods and Data Encapsulation and Access Control Constructors Other Capabilities Session 2: Review Class and Object Copyright LearningPatterns Inc. All rights reserved. 67

78 Encapsulation: Black Boxes Many terms for encapsulation Helps to manage complexity Only reveal the essentials Reduce the number of details known to the outside world Exposed details Hidden implementation details and inner workings Open-closed principle: Session 2: Review Class and Object Information hiding follows the "open-closed" principle, which means that a class of objects is open to extension, yet is also closed so that it is available for use by other classes with a stable, well-defined description of its behavior (the operations that it can do) and attributes. Note that, like an iceberg, the well-defined description may only cover a small part of the class's abilities the rest of its behavior is hidden because it is unimportant to its use by other classes. For example, a teller class in a bank simulation may support deposit and withdraw methods, but as a user of the teller class it is not important how those actions are performed and it's also not relevant what the teller's salary is in fact, these days it's not even important to know the teller's name; as long as the transaction is performed properly as requested, it isn't relevant whether the teller is human or machine. Manage complexity: By reducing the amount of information revealed by a class, it makes the use of instances of that class easier. A toaster is easier to use than a car because the toaster only reveals one operation or behavior make toast, and one attribute the darkness (or toastiness) setting. A car is more complicated because it requires the user to perform a number of actions (start car, put in gear, depress gas pedal, turn wheel, etc.) in a certain sequence, in order to get from one place to another. It would be a lot easier if we could just get in, tell it where we want to go and sit back and relax (sounds like a taxi) while the actions of driving are hidden from us. Copyright LearningPatterns Inc. All rights reserved. 68

79 Encapsulation Encapsulation is a "black box" approach to building types It is based on hiding the implementation of a type's behavior and is also called Information Hiding or Abstraction, Java provides support for enforcing the concepts of encapsulation with access protections These allows you to control access to the internals of classes through the access modifier keywords: public, protected, and private Applicable to both data members and methods Every field (i.e., data member) and method may be declared public, protected, or private If access is not declared, the default access is used Very often, fields are kept private while methods are made public Session 2: Review Class and Object Encapsulation is one of the foundations of the object model The user interacts with the type only through the behavior that is exposed The internals are hidden, and never accessed directly For example, consider a Person type, which has the behavior standup To have a person stand up, we would invoke this behavior We would not want to have to reach in and explicitly deal with a bunch of muscles and ligaments The access modifiers give you the ability to prevent or allow access to variables and methods Access control is required to assure that you are properly hiding your implementation (i.e., encapsulation), by exposing only the classes and methods that are necessary for use by other classes Access control is an enforcement mechanism Access control works the same for both data members and methods The access modifier goes before the type name We'll talk more about protected, and about the default access level (when none of these are specified) later Copyright LearningPatterns Inc. All rights reserved. 69

80 Private Access A private field or method is only directly accessible by code that appears within the class where it is defined public class AlarmClock { // Make the data private for encapsulation private int snoozeinterval = 0; } void setsnoozeinterval(int snoozein) { snoozeinterval = snoozein; } int getsnoozeinterval() { return snoozeinterval; // OK - Returns the instance var } public class EarlyMorning { public static void main(string[] args) { AlarmClock myclock = new AlarmClock(); myclock.snoozeinterval = 10; // ERROR: not accessible } } Session 2: Review Class and Object Note that you can bypass this restriction by using the Java reflection API The Java Security Manager will only let you do this if you have appropriate rights The details of doing this are beyond the scope of this course Do a Web search on "Java reflection access to private members" for some more information on this Copyright LearningPatterns Inc. All rights reserved. 70

81 Public Access A public field or method is accessible to any other class public class AlarmClock { private int snoozeinterval = 0; // Make the methods public for access public void setsnoozeinterval(int snoozein) { snoozeinterval = snoozein; } public int getsnoozeinterval() { return snoozeinterval; // Returns the instance var } } public class EarlyMorning { public static void main(string[] args) { AlarmClock myclock = new AlarmClock(); myclock.setsnoozeinterval(10); // OK: Method accessible } } Session 2: Review Class and Object If you can get to the class, you can get to its public members. The get and set methods for working with snooze time are a standard way of naming "accessor" methods for the "snoozeinterval" property It comes from a Java specification called JavaBeans Copyright LearningPatterns Inc. All rights reserved. 71

82 Lab Encapsulation Lab 2.2:. Encapsulation Copyright LearningPatterns Inc. All rights reserved. 72

83 Lab 2.2 Encapsulation Lab Overview: In this lab, we will encapsulate the data in Television by making the instance variables private We will create public getter and setter methods to access and modify their values We'll also define a tostring() method for Television to describe a Television instance in String form Objectives: Work with the data access modifiers to encapsulate data Define and use the tostring() method Explore some of the other Eclipse views Builds on previous labs: 2.1 Continue to work in the Lab02.1 project Approximate Time: minutes Lab 2.2:. Encapsulation Copyright LearningPatterns Inc. All rights reserved. 73

84 Encapsulating Data Lab Tasks to Perform Encapsulate the data in the Television class by making the instance variables private By prefixing each declaration with the private modifier Make your getter methods public with the public modifier Make sure you still have a direct access to an instance variable in TelevisionTest from the previous lab Save the file to recompile your application, and see what error messages the compiler generates. Why are you getting them? Remove the direct instance variable access in TelevisionTest Complete the methods for accessing our encapsulated data Create mutator (setter) methods for each data element The method names should start with set, and be followed by the logical name of the variable, e.g., setvolume What should the signature of the set methods be? * Lab 2.2:. Encapsulation Refer to the AlarmClock class samples for an example of encapsulation and the definition of getter/setter methods The method names should follow the same conventions as variables, i.e., first "word" in lower case, each subsequent "word" capitalized, e.g., setvolume, getvolume, etc. For the method parameters of the setter methods, you may wish to use some other naming convention, like volumein, brandin etc. Copyright LearningPatterns Inc. All rights reserved. 74

85 Modifying TelevisionTest Lab Tasks to Perform Change TelevisionTest to only use the new accessor methods to access the properties Use the setter methods to initialize each Television's data elements Use the getter methods to retrieve each Television's data elements, and print them out as before, using System.out.println Run your program to see that it works Television tv1 = new Television(); tv1.setbrand("rca"); tv1.setvolume(10); System.out.println("Television: brand=" + tv1.getbrand() + ", volume=" + tv1.getvolume()); Lab 2.2:. Encapsulation Copyright LearningPatterns Inc. All rights reserved. 75

86 Writing a tostring Method Lab Tasks to Perform Create a tostring method in class Television It should return a String that includes the name of the class and the values of the instance variables The signature of the method must be: public String tostring() { } Consider formatting the returned String, so it looks like this: Television: brand=sony, volume=6 In TelevisionTest use this tostring method to display each Television object's data then run your program // for a Television reference, tv1: System.out.println(tv1.toString()); System.out.println(tv1); // Same result as above Lab 2.2:. Encapsulation The method tostring is a special method inherited from the class Object. We will discuss class Object later in the course in Session 8 - Composition and Inheritance. We will also see that tostring will be invoked automatically if you just try to print out an object by its reference variable. System.out.println(tv1); // tostring gets called You can look up class Object in the Javadoc if you are interested. The Object class is located in the java.lang package. Copyright LearningPatterns Inc. All rights reserved. 76

87 Review Eclipse Outline View Lab Open the Outline View (Window Show View Outline ) It is an overview of the key elements that make up the resource that is being edited Allows quick and easy navigation through your resource using a tree model for organizing related elements Clicking in the outline view will bring you to the equivalent location in the editor Try opening it and moving around Television.java with it Lab 2.2:. Encapsulation Copyright LearningPatterns Inc. All rights reserved. 77

88 Review Eclipse Bookmarks View Lab Designed to help keep your development environment and process more organized You can add bookmarks in one of two ways The edit menu (Edit Add Bookmark ) Right-clicking in an editor s left-hand margin The bookmark view allows you to quickly jump to any resource with a bookmark, even to a specific line of code (if it is bookmarked) Open the Bookmark view and see how it works Window Show View Other General Bookmarks Try adding a bookmark, then going to a bookmark using the Bookmark view * See following slide Lab 2.2:. Encapsulation You can just double-click on a bookmark in the Bookmark view to go to the associated line of code You can also right click on the bookmark and select "Go To" Copyright LearningPatterns Inc. All rights reserved. 78

89 Eclipse Bookmarks Lab STOP Lab 2.2:. Encapsulation Copyright LearningPatterns Inc. All rights reserved. 79

90 Constructors Defining Classes Working with Methods and Data Encapsulation and Access Control Constructors Other Capabilities Session 2: Review Class and Object Copyright LearningPatterns Inc. All rights reserved. 80

91 Constructors Constructors are special methods that are called when objects are created, and are used to initialize the new object They look like regular methods that have the same name as their class They have no return value specified a reference to an instance of the class itself is the return value, since that is what's being created public class AlarmClock { private int snoozeinterval = 0; // Create an AlarmClock with the default snooze time public AlarmClock() { } } // Create an AlarmClock with the specified snooze time public AlarmClock(int snoozein) { setsnoozeinterval(snoozein); // Why do it this way? } // Session 2: Review Class and Object Constructors work like overloaded methods. They are used to create and initialize new objects in one step. Instead of multiple lines of code: AlarmClock myclock = new AlarmClock(); // create myclock.setsnoozeinterval(1500); // initialize data You can do it in one line of code: AlarmClock myclock = new AlarmClock(1500); // one step Notice that the constructor calls the setter method to actually set the data. This leverages any validation code in the setter method. If the constructor just set the data directly, it might take a negative snooze time and assign that to the instance variable and negative snooze times are invalid. Copyright LearningPatterns Inc. All rights reserved. 81

92 Using Constructors Constructors are invoked when an object is created using new // create AlarmClock with no-arg, or (default), constructor AlarmClock a1 = new AlarmClock(); // create AlarmClock with constructor that takes an int AlarmClock a2 = new AlarmClock(1500); One constructor can invoke another constructor You must invoke it in the first statement, using this(), with a list of arguments in the parentheses public class AlarmClock { public AlarmClock(int snoozein) { // invoke other constructor explicitly this(snoozein, 0); } public AlarmClock(int snoozein, long currentin) { setsnoozeinterval(snoozein); setcurrenttime(currentin); } } Session 2: Review Class and Object The correct constructor is selected based on the arguments passed - as with overloaded methods The no-arg constructor is called when you create an object without using any arguments It's sometimes called a default constructor because it is generated automatically If no constructors are declared for a class, then a no-argument constructor is implicitly and automatically provided by the Java compiler, e.g., AlarmClock() { } Once you declare any constructors, then the no-argument is not implicitly declared for you If you want one, you simply code it yourself To share common code among constructors a "detailed" constructor (one that takes all the arguments) can be called from all the other constructors. The detailed constructor usually accepts an argument for each instance variable that can be initialized. The other constructors pass the arguments they have been given, along with default values for the others, to the detailed constructor. Constructors should use setters to initialize instance variables, rather than assigning values themselves, since setters are where the validation logic is coded. Copyright LearningPatterns Inc. All rights reserved. 82

93 Lab Adding Constructors to a Class Lab 2.3:. Constructors Copyright LearningPatterns Inc. All rights reserved. 83

94 Lab 2.3 Constructors Lab Overview: In this lab, we will add constructors to Television We will create both default (no-arg) constructors, and detailed constructors with multiple arguments Objectives: Add constructors to a class Use constructors in a program Builds on previous labs: 2.2 Continue to work in the Lab02.1 project Approximate Time: minutes Lab 2.3:. Constructors Copyright LearningPatterns Inc. All rights reserved. 84

95 Adding Constructors to Television Lab Tasks to Perform Create a constructor to allow the user to set both data elements of Television We'll call this one the "detailed" constructor It should take two arguments one for volume, one for brand The arguments are used to initialize the instance variables What should the signature of the constructor be? Refer to the AlarmClock class samples for an example NOTE: make sure that you call the setter methods from your detailed constructor don't set the data directly by assigning the arguments to the instance variables Why is this important? Lab 2.3:. Constructors Why not set the instance variables directly in your constructor? Since we usually have data validation in the setter methods, we want the constructors to leverage this code. This will prevent the user from setting the variables to invalid values at object creation time, i.e., AlarmClock bogus = new AlarmClock (-3); // invalid data Copyright LearningPatterns Inc. All rights reserved. 85

96 Adding Constructors to Television Lab Tasks to Perform Create another constructor that takes no arguments the default or no-argument constructor This constructor should call the detailed constructor, using this() You can simply supply hardcoded values for brand and volume, e.g., this("rca", 10) In TelevisionTest create a valid Television using each of your constructors Print out some information from each television instance Run your program and see how it works Television tv1 = new Television(); Television tv2 = new Television("Hitachi", 17); Lab 2.3:. Constructors NOTE: what happens in your default constructor code if you try invoking the detailed constructor using Television("RCA", 10) instead of this("rca", 10)? OPTIONAL: In Television add a one-argument constructor for brand and add a one-argument constructor for volume. Have each one call the detailed constructor using this(). Here's an example: Television(String brandin) { this(brandin, 0); } In TelevisionTest create a TV using each of these constructors. Television tv = new Television("RCA"); Copyright LearningPatterns Inc. All rights reserved. 86

97 Eclipse - Maximize a View or Editor Lab You can maximize a view by double clicking in its tab Try it with the Television.java file in the editor This is nice, as it lets you easily view a larger piece of a file You can minimize it by double clicking again STOP Lab 2.3:. Constructors Copyright LearningPatterns Inc. All rights reserved. 87

98 Other Capabilities Defining Classes Working with Methods and Data Encapsulation and Access Control Constructors Other Capabilities Session 2: Review Class and Object Copyright LearningPatterns Inc. All rights reserved. 88

99 Static Members A static or class data member is associated with a particular class rather than with an instance They are often used to define class constants Class or static methods are not associated with objects so they can be invoked without an instance static methods do not have a reference to this, since there is no instance associated with them The static keyword is used to define static fields and methods The example below comes from the java.lang.math class Which holds a number of constants and utility methods public final class Math { public static final double PI = ; public static double sin(double a) { /* */ } //... } Session 2: Review Class and Object static doesn't mean "without change" it means only one per class, i.e., it doesn't change from instance to instance, but is shared by all instances of the class. The runtime system allocates a class variable once per class, at the time the class is loaded, before any instances exist of that class A static variable can change if it isn't declared final. They are also called class variables, because a class variable has the same value for all instances of the class You use class variables for items that you need only one copy of and which must be accessible by all objects instantiated from the class in which the variable is declared Class variables are often used with final to define constants You can also specify a method to be a static (class) method Can only operate on static variables and can't access instance fields defined in the class. Often used for utility functions and can be invoked without first creating an instance Don't have a reference to this, since there is no instance associated with them Copyright LearningPatterns Inc. All rights reserved. 89

100 Accessing Static Members To access a static data member, we reference it through the class name, not an instance name We use the dot operator here also, but with the class name class UsingPI { public static void main(string[] args) { System.out.println("Pi equals " + Math.PI); System.out.println("sin(0) = " + Math.sin(0)); } } We don't use an instance name, because PI and sin() are members of the class, not a particular instance In fact, we'll probably never create an instance of Math, since everything in it is static Session 2: Review Class and Object You can actually access a static member through an instance - but this is confusing, and is considered bad practice Some other examples of useful static variables are the MIN_VALUE, MAX_VALUE, NaN, NEGATIVE_INFINITY, and POSITIVE_INFINITY variables in the wrapper classes. static data members are practically like global variables when qualified with their class name. A special example of a static property is System.out. out is a static final variable in the System class that refers to the standard output of the underlying system. The System class defines a platform independent interface to system facilities. main is a special static method, as it is invoked automatically by the Java virtual machine. Others need to be explicitly invoked. Copyright LearningPatterns Inc. All rights reserved. 90

101 final Variables Variables can be declared as read-only, or constant, using the final modifier public final class Math { public static final double PI = ;... } A final variable must have an initializer Any attempt to modify a final variable is an error They are used to create constant variables They are usually used in conjunction with static, since if they always have the same value, why keep multiple copies around? public static final variables are also called class constants, and often use an ALL_CAPS naming convention You would refer to the above variable as Math.PI Session 2: Review Class and Object Sorry Indiana, you can't change the value of PI Copyright LearningPatterns Inc. All rights reserved. 91

102 Comparison You can compare variables of a class type using == and!= This checks to see if the two references in the comparison refer to the same object or same instance of a class AlarmClock myclock = new AlarmClock(); AlarmClock yourclock = myclock; if (myclock == yourclock) { // true System.out.println("one Clock"); } == tests for identity, i.e., checks if the two references refer to the same object We'll see later how to test for equality (two objects having the same value or same contents) Session 2: Review Class and Object Copyright LearningPatterns Inc. All rights reserved. 92

103 Null Objects Java has a special object reference called null Class type variables of any class can be assigned the value null null basically means "not a valid object" // Initialize myclock to point to null AlarmClock myclock = null; Objects can be tested for null using == and!= if (myclock == null) // true { System.out.println("My God We're out of time!"); } Session 2: Review Class and Object Copyright LearningPatterns Inc. All rights reserved. 93

104 Wrapper Classes Primitive types are not objects There is no class associated with them, e.g., class int These are the only things which are not objects in Java this is done for efficiency There are class representations for each of the primitive types, called wrapper classes For example, there is an Integer class, which is an object wrapper around a primitive int These classes provide some useful functionality (such as data conversion from a string value) that the primitive types don't have (see notes) They also enable you to treat primitive types as objects when necessary (see notes) Session 2: Review Class and Object If you need to convert a string representation of an integer to a real int, you can use the Integer.parseInt method to do this: String age_string = "38"; int age = Integer.parseInt(age_string); Recall that command line arguments are delivered to the main method as an array of Strings String[] args. This is a case in which you may need to convert a string-based number to an int. There are also situations in which you need to store primitive values in a collection class, such as ArrayList. (We will discuss collection classes later.) Collection classes are generic in the sense that they will store anything, but the data stored must be in object form. You thus cannot store ints in an ArrayList, but you can store Integer objects in one. int age = 38; Integer age_integer = new Integer(age); Copyright LearningPatterns Inc. All rights reserved. 94

105 Session 14: Introduction to ant Overview Installing and Running ant ant Basics Copyright LearningPatterns Inc. All rights reserved. 454

106 Lesson Objectives Understand the background and need for a tool like ant Understand how ant is used to control the building of Java software projects Learn basic ant capabilities, and use them to build Java software projects Session 14: Introduction to ant Copyright LearningPatterns Inc. All rights reserved. 455

107 Overview Overview Installing and Running ant ant Basics Session 14: Introduction to ant Copyright LearningPatterns Inc. All rights reserved. 456

108 What is ant? ant is a cross-platform Java-based build tool that uses XML configuration files to control the building of software projects Handles many common software project tasks Compiling code, building archives (zip, jar, etc), running programs Working with files and directories - copying, creating, deleting Creating sets of files / directories, and using them e.g in classpaths Much, much more Allows you to create your own tasks by writing Java classes Provides for easy extensibility and integration with other software e.g. Apache Tomcat has tasks to deploy to a Tomcat server ant is mostly used in the Java world But there are other versions and tools for other environments For example, there is a.net version, and a version for C/C++ Session 14: Introduction to ant ant stands for "Another Neat Tool" according to the initial author (James Duncan Davidson) Later explanations go along the lines of "ants do an extremely good job at building things", or "ants are very small and can carry a weight dozens of times their own" - describing what Ant is intended to be. [ant FAQ] ant was created in conjunction with the Tomcat Web server To help build Tomcat It was noticed by other open source / Apache developers, and became widely used in that community Eventually it was promoted to a project of its own, and released to the general Java community It has since become one of the most popular build tools around Copyright LearningPatterns Inc. All rights reserved. 457

109 A Simple Build File To illustrate ant, let's look at the fairly simple build file below without going into all of its details - which we'll look at later Our build file is named build.xml - the default build file name It allows us to echo some messages to the console <?xml version="1.0"?> <project name="helloant" default="hello"> <!-- Say Hello --> <target name="hello" > <echo>hello Ant World!</echo> </target> <!-- Say Goodbye --> <target name="bye"> <echo>bye - Thanks for using Ant</echo> </target> </project> Session 14: Introduction to ant The XML declaration at the very top of the file is standard XML It's the standard preamble for normal XML documents, and not specific to ant It is not required by ant, but it's a good idea to include it Copyright LearningPatterns Inc. All rights reserved. 458

110 Running Ant Below left, is our working directory, with the ant build file, build.xml We can run ant by typing ant on the command line We've set up build.xml to tell ant to echo some text to the console Below right, we can see the ant output At bottom right, we see the output from running the bye target - which echoes a different message - we'll cover this all in depth later Session 14: Introduction to ant We'll talk in just a little bit about installing ant, and setting up your environment so that it is easy to run ant comes with its own XML parser, so it doesn't need any additional installation for working with the XML files The build.cmd file shown in the Lab directory is there to help you easily run ant without changing your environment We'll talk about it in the lab Copyright LearningPatterns Inc. All rights reserved. 459

111 Installing and Running ant Overview Installing and Running ant ant Basics Session 14: Introduction to ant Copyright LearningPatterns Inc. All rights reserved. 460

112 Acquiring ant The ant website is: ant is an open source project managed by Apache You can download ant from the "Binary Distribution" link off the home page (source downloads are also available) Available as.zip,.tar.gz and other formats Just uncompress (e.g. unzip) the distribution to your file system Default location is to C:\, but you can put it anywhere you want The resulting install directory - known as ANT_HOME will be named something like C:\apache-ant Most Java IDEs ship with ant already installed For example, Eclipse, NetBeans, & IntelliJ IDEA all include ant Generally, these IDEs also allow you to upgrade the ant version Session 14: Introduction to ant In this section, we will assume that you are working with version of ant If you are working with a different version, then the installation directory will change Depending on what other version you use, other things may change also Any 1.6.x version should also be similar to this Earlier versions will have greater differences.tar.gz is a gzip compressed tar file Copyright LearningPatterns Inc. All rights reserved. 461

113 ant Installation The ant directory structure is shown at bottom Only the lib and bin directories are needed to run ant There is a complete set of documentation in the docs dir This is an extremely useful resource - use it! Additional setup that is needed: Set the ANT_HOME environment variable to the ant install dir add ANT_HOME\bin to your path Set your JAVA_HOME environment variable to your Java install Session 14: Introduction to ant The startup scripts that run ant, need to know where ANT_HOME is They can sometimes guess what ANT_HOME is, but it's better to set it ANT_HOME\bin contains the startup scripts for running ant To run ant easily from a command prompt, this directory should be on your path If you don't want to change your path (or can't) there are other ways of doing this, which we'll show in the labs JAVA_HOME is necessary if you want to use Java related tasks such as <javac> for compiling Java files Copyright LearningPatterns Inc. All rights reserved. 462

114 Running ant When installed as described previously, it's simple Just type ant at the command line, as seen in our examples By default, ant will use build.xml in the current directory as the build file It will run the target specified in the default attribute of the <project> tag You can specify a different build file using -buildfile file, e.g. ant -buildfile mybuildfile.xml You can also specify different target(s) by listing them after the ant command, for example Run the hello target: ant hello Run the hello and bye targets ant hello bye Session 14: Introduction to ant You can also specify a buildfile with the -file, or -f options They are synonyms for -buildfile We'll learn more about targets and the rest of the buildfile very soon Copyright LearningPatterns Inc. All rights reserved. 463

115 Command Line Options ant has many options - we list some important ones here: Type ant -help at the command line for a complete list of options The documentation has more information about ant -help, -h print the ant help message -version print the version information and exit -diagnostics print information that might be helpful to diagnose or report problems (useful for debugging if ant doesn't run properly) -quiet, -q be extra quiet -verbose, -v be extra verbose (useful for debugging build scripts) -debug, -d print debugging information (useful for debugging build scripts) -D<property>=<value> use value for given property Session 14: Introduction to ant Copyright LearningPatterns Inc. All rights reserved. 464

116 Lab 14.1 Setting Up ant Copyright LearningPatterns Inc. All rights reserved. 465

117 Lab 14.1 Set up the Environment Lab Overview: In this lab, we will become familiar with ant, set up our ant working environment, and test it to make sure it is running well The end goal is to compile and run an application using ant We will NOT use Eclipse for this Objectives: Set up our ant environment Compile and run a simple application using ant Builds on previous labs: None Approximate Time: minutes Lab 14.1: Setting Up ant Copyright LearningPatterns Inc. All rights reserved. 466

118 Setup Environment Lab Tasks to Perform Make sure that ant 1.7.x is installed likely in a directory such as C:\apache-ant-1.7.x If it's been installed in a different directory, you'll need to modify the instructions in the lab to refer to your install directory If it isn't installed, you'll need to download it (from and unzip it The root lab directory where you will do your work for this lab is: C:\StudentWork\INTMJ\workspace\Lab14.1 This directory is already in your workspace, and includes files for the lab you'll do all your work within this directory You need to configure your system to run ant in 1 of 2 ways Set your environment variables and path and run ant directly Use batch files supplied by us to run the ant program Lab 14.1: Setting Up ant In general, all the files you will work on for a lab will be under the root directory (and instructions are given relative to this directory) The most common way to configure your system is to use ant directly If you don't want to configure your system (or can't), you can use our batch files Copyright LearningPatterns Inc. All rights reserved. 467

119 Option 1: Configure Your System Lab Tasks to Perform Check your ANT_HOME, PATH and JAVA_HOME environment variable in any command window, by typing C:\>set ANT_HOME C:\>set PATH C:\>set JAVA_HOME ANT_HOME should point to your Ant installation (e.g. C:\apache-ant-1.7.0) PATH needs to contain %ANT_HOME%\bin JAVA_HOME should point to your Java installation (e.g. C:\Program Files\Java\jdk1.5.0_06) If you need to update (or create) any of the above, locate the environment variables dialog box (see notes) In the User variables section, create or update each of the environment variables above to contain values that are correct for your system Lab 14.1: Setting Up ant For ANT_HOME and JAVA_HOME, if your system has ant or Java installed at a different location, you would use the location that is correct for your system To get the environment variables dialog box: Windows 2000 and XP: Start Settings...Control Panel System Advanced tab Environment Variables You can set environment variables in the dialog box there. Another approach is to right click on the MyComputer icon and select Properties Advanced tab Environment Variables Windows NT: Start Settings Control Panel System Environment. You can set environment variables in the dialog box there. NOTE: always close and reopen command windows or editors after changing an environment variable to make sure they use the new value. Copyright LearningPatterns Inc. All rights reserved. 468

120 Option 2: Use Our Batch Files Lab We supply a command file, build.cmd, to invoke ant for the labs It uses the file common\buildsetenv.cmd to configure the environment props needed to run ant Tasks to Perform Open common/buildsetenv.cmd with a text editor Check the ANT_HOME and JAVA_HOME environment variables, and modifies them if necessary * These are used to invoke ant properly from the command line When running labs, instead of invoking the ant program directly (e.g. ant bye), use build.cmd to invoke ant, e.g. build bye Lab 14.1: Setting Up ant The ANT_HOME environment variable is used to invoke ant in our build command script, and will be set something like this: set ANT_HOME=C:\apache-ant The JAVA_HOME environment variable points to the Java home directory If you do not have the full Java JDK on your classpath, AND if you do not have the JAVA_HOME environment variable set, then you'll need to set JAVA_HOME in this file There is a sample command that sets it that is commented out You'll need to uncomment it, and modify it so it points to the correct location for Java 5 in your environment Copyright LearningPatterns Inc. All rights reserved. 469

121 Test Out Ant Lab The Lab14.1 directory contains a build.xml file (the ant configuration file) as shown in the student manual example Running ant from the command line should run the hello task in the buildfile - if everything is set up properly Tasks to Perform Open a command window in workspace\lab14.1, and run ant with no arguments as shown below (see notes) > ant This runs the default run target to compile and run the app If using our command file, build.cmd then type build instead > build In future lab instructions, we'll assume you use ant directly If you don't, just substitute build wherever you see ant See the next slide for expected output Lab 14.1: Setting Up ant build.cmd uses the buildsetenv.cmd file you just configured to find ant To make it easier to open command windows in the lab dirs, we've included a utility in the setup (under Resources\InstallFiles) that allows you to right click on a folder to open a command prompt in it To install this: Go to the Resources\InstallFiles\CommandPromptHere folder Right click on the.reg file there, and select Merge Once you've done that, right clicking on a folder will show a Command Prompt Here selection in the context menu - Select that to open a command prompt in the directory Copyright LearningPatterns Inc. All rights reserved. 470

122 The Results of the Build Lab Tasks to Perform Check that your output is similar to that shown below If ant doesn't run at all, check to make sure that your ANT_HOME and PATH are correct You can try running ant -diagnostics to find out if your system is configured properly Try running the bye target also Check with your instructor if you need help STOP Lab 14.1: Setting Up ant Copyright LearningPatterns Inc. All rights reserved. 471

123 ant Basics Overview Installing and Running ant ant Basics Session 14: Introduction to ant Copyright LearningPatterns Inc. All rights reserved. 472

124 ant Buildfiles and Projects ant buildfiles are written in XML, and contain: One (only) top-level project (defined in <project>) At least one target (configured in <target>s) Working with buildfiles is the largest part of using ant <project> : Top level container for most buildfile contents - including all targets Can contain a <description> element describing the project <project> defines three attributes name: The name of the project default: Default target to use, if not specified when running ant basedir: Base directory from which path calculations are done <?xml version="1.0"?> <project name="helloant" default="hello" basedir="."> <description>this is our first buildfile</description> <!-- Much detail omitted --> </project> Session 14: Introduction to ant ant defines a specific set of XML elements to create build files e.g. <project> and <target> Build files consist of a single top-level <project> containing one or more <target> elements <project> may also contain other elements (e.g. <property>) that we'll cover later The <description> element can be used by tools to describe build files It is also used if you run ant with the -projecthelp option Additional details about the project attributes include: name: Can be any combination of alphanumeric characters that constitute valid XML. default: Was required in versions prior to version 1.6, but a default target is no longer required. Starting with 1.6.0, there is an implicit target which contains any and all top-level tasks and/or types. This target will always be executed as part of the project's initialization, even when Ant is run with the -projecthelp option. basedir: The base directory from which any relative directories used within the Ant build file are referenced from. If this is omitted the parent directory of the build file will be used Copyright LearningPatterns Inc. All rights reserved. 473

125 ant Targets <target> contains a collection of tasks to execute Targets are named - name can be used in the build file, and when invoking ant <target> attributes include: name: Name of the target depends: Comma separated list of targets this target depends on Ant will try to execute the targets in the depends attribute in the order they appear Dependencies give you a way to specify the order of execution of targets description: Short description of the target's function - used when running ant with -projecthelp When running ant, you can specify the target(s) to execute ant - Run the default target (if any) ant hello - Run the hello target ant hello bye - Run the hello target, then the bye target Session 14: Introduction to ant ant dependencies allow you to specify that a certain target should not run until its prerequisite targets have been run Ant tries to execute the targets in the depends attribute in the order they appear (left to right) Keep in mind that it is possible that a target can get executed earlier when an earlier target depends on it - for example, looking at the following targets/dependencies: <target name="a"/> <target name="b" depends="a"/> <target name="c" depends="b"/> <target name="d" depends="c,b,a"/> Suppose we want to execute target D. From its depends attribute, you might think that first target C, then B and then A is executed. Wrong! C depends on B, and B depends on A, so first A is executed, then B, then C, and finally D. Targets without a description are deemed internal, and will not be listed when ant is run with projecthelp A target also has the ability to perform its execution if (or unless) a property has been set This is done using the "if" or "unless" attributes Copyright LearningPatterns Inc. All rights reserved. 474

126 A More Complicated Buildfile In the buildfile below, we can see a number of targets, some of which depend on other targets We'll show the tasks for the targets shortly The all target has no tasks - it's only there to collect its dependencies, and it is used as the default target Not required, but often useful <?xml version="1.0"?> <!-- build.xml --> <project name="helloant" default="all"> <target name="clean" description="deletes compiled files"> <!-- Details omitted --> </target> <target name="compile" description="compiles the source"> <!-- Details omitted --> </target> <target name="run" depends="compile" description="runs HelloAnt"> <!-- Details omitted --> </target> <target name="all" depends="clean, compile, run" description="runs everything"/> </project> Session 14: Introduction to ant There is nothing special about the all target It can have normal tasks, as well as depends targets In this example, it has no tasks defined It is used to provided a convenient target to execute all the other targets Copyright LearningPatterns Inc. All rights reserved. 475

127 ant Tasks A task represents an action that you want executed Large selection of pre-defined tasks for many common needs Over 90 core tasks, and many additional optional tasks Many additional tasks written by others - e.g, tasks to deploy to the Tomcat Web server Can write your own task, by writing a Java class that extends org.apache.tools.ant.task * We will not attempt to cover all the ant tasks We'll cover the most common tasks - read the docs for others Each task defines an element, with attributes specific to that task, written a follows: <taskname attribute1="val1" attributen="valn"> Session 14: Introduction to ant Writing your own tasks is beyond the scope of this course It's not very hard, and the ant manual has instructions on how to do it You can extend the Task class mentioned in the slide, or one of a small number of specialized classes that ant supplies (e.g. JDBCTask) There are so many tasks that come with ant, that it would be impossible to cover them all in a short course like this Once you are familiar with ant, it is fairly easy to learn what the different tasks that are available do LOOK AT THE DOCUMENTATION! Copyright LearningPatterns Inc. All rights reserved. 476

128 The <javac> Task Lets review the <javac> task to explore the task structure <javac srcdir="."/> <javac> compiles a Java source tree rooted at srcdir By default,.class files are put in the same directory as the source The destdir attribute specifies a different location for.class files (considered good practice) <javac> searches the source tree, compares each.java file to its.class files (if it exists) and compiles the source if needed If the.class file is newer than the.java file, it won't compile it Below, we show <javac> configured to compile all the.java files under the src dir, and place the.class files in the build dir <javac srcdir="src" destdir="build"/> Session 14: Introduction to ant <javac> will recursively scan the srcdir directory and its subdirectories for files to compile <javac> will only compile those source files that it believes it needs to If a classfile already exists, and that classfile's corresponding source file hasn't been changed since the classfile was generated, then that source file won't be recompiled The output of the javac task shows the number of source files that were actually compiled It is good practice to write a clean target that removes any generated classfiles from that target directory - This can then be used if you want to make sure that all of the source files are compiled This behavior characterizes many of Ant's tasks: If the task can determine that the requested operation doesn't need to be performed, then it will be skipped [IBM DeveloperWorks - Apache Ant 101: Make Java builds a snap] Copyright LearningPatterns Inc. All rights reserved. 477

129 The <java> and <delete> Tasks <java> executes a Java class within the running Ant VM The classname attribute specifies the Java class to execute The classpath attribute allows you to set the classpath Multiple items allowed in the classpath, separated by either ":" or ";" The fork attribute allows you to execute within another VM * Below, we use<java> to run the HelloAnt program <java classname="helloant" classpath="."/> <delete> deletes a file, a directory, or a collection of files The file or dir attribute specify a file or dir to delete For example, below we specify a task to delete HelloAnt.class <delete file="helloant.class"/> Session 14: Introduction to ant Sometimes you want to execute in a separate VM, because of side effects within the VM from ant itself The ant reference manual suggests that if you are seeing odd behavior when using <java> try using <java fork="true" > to use a new VM For the classpath, ant converts whatever separator character you use into the appropriate character for the OS The <javac> task also runs within the same VM This is usually desirable because it is much more efficient to run javac within the same process - however it can have side effects Windows Note:When the modern compiler is used in unforked mode on Windows, it locks up the files present in the classpath of the <javac> task, and does not release them. The side effect of this is that you will not be able to delete or move those files later on in the build. The workaround is to fork when invoking the compiler. [Ant Reference Manual] Copyright LearningPatterns Inc. All rights reserved. 478

130 A Complete Buildfile Below, we show a complete buildfile, with all tasks included clean uses <delete> to delete HelloAnt.class, compile uses <javac> to compile all Java files in/below the current directory run uses <java> to run the HelloAnt program all provides a convenient way to run all the targets in the buildfile On the next slide we show various runs of ant with this buildfile <?xml version="1.0"?> <!-- build.xml --> <project name="helloant" default="all"> <target name="clean" description="deletes compiled file"> <delete file="helloant.class"/> </target> <target name="compile" description="compiles the source"> <javac srcdir="."/> </target> <target name="run" depends="compile" description="runs HelloAnt"> <java classname="helloant" classpath="."/> </target> <target name="all" depends="clean, compile, run" description="runs everything"> </target> </project> Session 14: Introduction to ant Copyright LearningPatterns Inc. All rights reserved. 479

131 Running our Buildfile ant -projecthelp Shows different targets with their descriptions ant all Runs the clean, compile, run targets ant run Don't need to compile again, so compile does nothing Session 14: Introduction to ant Copyright LearningPatterns Inc. All rights reserved. 480

132 How is ant Useful? The core functionality of ant is to automate the build process for Java software systems In the previous example, ant automated the building of our system (and also ran our program) The needed steps were configured in the XML build file (by default named build.xml) ant has support for much more complex build scenarios For example, multiple source directories, working with version control systems (e.g. CVS) creating archives such as an EAR or WAR, multiple projects (e.g. an EAR and a WAR project), etc. This simplifies our build process tremendously The more complex our build requirements, the more ant helps us Session 14: Introduction to ant Building complex software projects by hand can be very tedious and error prone Carrying out all the proper steps in their proper order can be very complicated An automated build tool, that knows the proper sequence of steps, makes it much easier Ant was created to provide a true cross-platform build tool. It uses XML to control the build - An XML file is created containing targets where various tasks needed in a build get executed It replaces tools like make, which used platform-specific shell commands to define tasks ant uses Java classes to extend its capabilities Each task is run by a Java object that implements a particular Task interface The standard Ant tasks are already implemented You can define your own tasks by writing new Java classes implementing Task It is very powerful and very widely used You don't need an IDE to use Ant It is a very simple, non-gui build tool Copyright LearningPatterns Inc. All rights reserved. 481

133 Lab 14.2 Working with Buildfiles Copyright LearningPatterns Inc. All rights reserved. 482

134 Lab 14.2 Working with Buildfiles Lab Overview: In this lab, we will work with a simple buildfile There are various targets in the buildfile that you'll need to complete so they work properly Objectives: Become familiar with the different parts of a basic ant buildfile Create a simple buildfile for ant Builds on previous labs: none Approximate Time: minutes Note: To edit the files in the ant labs, use any simple editor you are comfortable with We supply a useful programmers editor you can use called Notepad++ - in the setup files (under Resources\InstallFiles) * Lab 14.2: Working with BuildFiles If you install Notepad++, it installs a context menu item which allows you to right click on a file and open it in the editor Copyright LearningPatterns Inc. All rights reserved. 483

135 Lab Preparation Lab The root lab directory where you will do all your work is: C:\StudentWork\INTMJ\workspace\Lab14.2 This is a new lab directory which already exists in your workspace The Lab14.2 directory contains the TeachMeAnt Java program and build.xml with the following targets that should work as follows: clean: Remove the compiled Java files compile: Compile Java source in the Lab14.2 directory run: Run the TeachMeAnt program (run should depend on the compile target, so compilation will happen first if needed) all: Depends on the clean, compile, and run targets, but doesn't have any tasks of its own Tasks to Perform Close all files from any previous labs If your editor allows you to configure a home directory, you can set it to the root lab directory Open a command prompt in the root lab directory described above Lab 14.2: Working with BuildFiles Copyright LearningPatterns Inc. All rights reserved. 484

136 Finish build.xml Lab Open up build.xml for editing Tasks to Perform Look for the TODOs, and finish up the following elements so the targets work as described on the previous page: <project>, <javac>, <delete>, <java>, and the all target Note that TeachMeAnt.java is directly in the Lab14.2 directory Save the file Open up a command window in the Lab14.2 directory Run ant to test the build file Run it with the -projecthelp option, with the all target, and with the "clean and run" targets Does it work properly? If you have problems compiling or running, check that JAVA_HOME is correct, and try the -verbose, or -debug options to get more information Lab 14.2: Working with BuildFiles Copyright LearningPatterns Inc. All rights reserved. 485

137 [Optional] build.xml Lab [Optional] Tasks to Perform Once you've got build.xml completely finished, you can try the following if you have time Rename build.xml to something else (e.g. mybuild.xml) Run ant using -buildfile (or -f) to use your buildfile Create a directory, src, and move TeachMeAnt.java to src Remember to delete TeachMeAnt.class manually What change do you need to make to your buildfile for it to work? Hint - look at the <javac>, <java>, and <delete> targets Make the changes, and test your buildfile Modify <javac> so compiled files go into the build directory Create the build directory yourself (we'll automate this later) Make any other needed changes to build.xml, and run it We'll soon see how properties make your life easier! STOP Lab 14.2: Working with BuildFiles Copyright LearningPatterns Inc. All rights reserved. 486

138 Working With Properties Ant allows you to define properties with a name and value within your buildfiles They are immutable - once set, they can't be changed They ease maintenance of build files, and are often used in multiple locations or build files Properties can be defined using <property> Usually defined under <project> <property name="build.dir" value="build"/> Properties can be used in tasks with the syntax ${propname} i.e. - a dollar sign, with the property name in curly braces Below, we use the build.dir property to specify that <javac> should put all compiled files in the build directory <javac srcdir="src" destdir="${build.dir}"/> Session 14: Introduction to ant Often, property values are used in multiple locations in the build file, so using properties makes maintenance much easier e.g. we might use the build.dir property in a clean target, to remove all the compiled files Properties are similar to string constants in a programming language - they are immutable This is one of the reasons that that targets tend to run consistently without side effects Properties can also be set in properties files (covered later), or when invoking ant Properties are defined on the command line using the syntax: -Dname=value, for example -Dbuild.dir=build <property> can also appear inside a target The property is set when the target is executed - this is not that commonly used In the event you should need to include this construct literally (i.e. without property substitutions), simply "escape" the '$' character by doubling it For example, the following task <echo>$${build.dir}=${build.dir}</echo> Would output: ${build.dir}=build Copyright LearningPatterns Inc. All rights reserved. 487

139 Working With Properties <property> also has a location attribute to make it easier to refer to files and directories It converts the path separator to the platform specific value <property name="db.file" location="resources/javatunes.db"/> Properties can be used anywhere in a buildfile At bottom, we see how a property (build.dir) is used to define another property (main.class) <project name="helloant" default="run"> <description>a more complicated buildfile</description> <property name="build.dir" value="build"/> <property name="main.class" value="${build.dir}/teachmeant.class"/> <!-- Much detail omitted --> </project> Session 14: Introduction to ant When using the location attribute, the property is set to the absolute filename of the given file If the value of this attribute is an absolute path, it is left unchanged (with / and \ characters converted to the current platforms conventions) Otherwise it is taken as a path relative to the project's basedir and expanded. Copyright LearningPatterns Inc. All rights reserved. 488

140 Built-in Properties Ant provides access to all the system properties as if they had been defined with <property> For example, ${os.name} expands to the OS name Ant itself includes the following built-in properties basedir: Absolute path of project's basedir (set with basedir attribute of <project>) ant.file: Absolute path of the buildfile ant.version: Version of Ant ant.project.name: Name of project currently executing (set with name attribute of <project>) ant.java.version: The JVM version Ant detected Session 14: Introduction to ant For a list of all the system properties, see the Javadoc of java.lang.system.getproperties() Currently ant.java.version can hold the values "1.2", "1.3", "1.4", "1.5", and "1.6" Copyright LearningPatterns Inc. All rights reserved. 489

141 Lab 14.3 Working with Properties Copyright LearningPatterns Inc. All rights reserved. 490

Table of Contents Fast Track to Java 8 EVALUATIONA COPY

Table of Contents Fast Track to Java 8 EVALUATIONA COPY Table of Contents Fast Track to Java 8 Fast Track to Java 8 and OO Development 1 Course Overview 2 Course Objectives 3 Course Objectives 4 Labs 5 Typographic Conventions 6 Course Outline 7 Session 1 -

More information

WA1278 Introduction to Java Using Eclipse

WA1278 Introduction to Java Using Eclipse Lincoln Land Community College Capital City Training Center 130 West Mason Springfield, IL 62702 217-782-7436 www.llcc.edu/cctc WA1278 Introduction to Java Using Eclipse This course introduces the Java

More information

is Fast Track to Java 8 and OO Development

is Fast Track to Java 8 and OO Development or tri N s di IO n tio AT uc od pr re U ed AL riz ho ut na EV U is i ib d tie PY oh pr O n C io t bu Fast Track to Java 8 and OO Development This material is copyrighted by LearningPatterns Inc. This content

More information

Java Programming Course Overview. Duration: 35 hours. Price: $900

Java Programming Course Overview. Duration: 35 hours. Price: $900 978.256.9077 admissions@brightstarinstitute.com Java Programming Duration: 35 hours Price: $900 Prerequisites: Basic programming skills in a structured language. Knowledge and experience with Object- Oriented

More information

(800) Toll Free (804) Fax Introduction to Java and Enterprise Java using Eclipse IDE Duration: 5 days

(800) Toll Free (804) Fax   Introduction to Java and Enterprise Java using Eclipse IDE Duration: 5 days Course Description This course introduces the Java programming language and how to develop Java applications using Eclipse 3.0. Students learn the syntax of the Java programming language, object-oriented

More information

SYLLABUS JAVA COURSE DETAILS. DURATION: 60 Hours. With Live Hands-on Sessions J P I N F O T E C H

SYLLABUS JAVA COURSE DETAILS. DURATION: 60 Hours. With Live Hands-on Sessions J P I N F O T E C H JAVA COURSE DETAILS DURATION: 60 Hours With Live Hands-on Sessions J P I N F O T E C H P U D U C H E R R Y O F F I C E : # 4 5, K a m a r a j S a l a i, T h a t t a n c h a v a d y, P u d u c h e r r y

More information

Course Description. Learn To: : Intro to JAVA SE7 and Programming using JAVA SE7. Course Outline ::

Course Description. Learn To: : Intro to JAVA SE7 and Programming using JAVA SE7. Course Outline :: Module Title Duration : Intro to JAVA SE7 and Programming using JAVA SE7 : 9 days Course Description The Java SE 7 Fundamentals course was designed to enable students with little or no programming experience

More information

Introduction to Java

Introduction to Java Introduction to Java Module 1: Getting started, Java Basics 22/01/2010 Prepared by Chris Panayiotou for EPL 233 1 Lab Objectives o Objective: Learn how to write, compile and execute HelloWorld.java Learn

More information

CS 231 Data Structures and Algorithms, Fall 2016

CS 231 Data Structures and Algorithms, Fall 2016 CS 231 Data Structures and Algorithms, Fall 2016 Dr. Bruce A. Maxwell Department of Computer Science Colby College Course Description Focuses on the common structures used to store data and the standard

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

Java 8 Programming for OO Experienced Developers

Java 8 Programming for OO Experienced Developers www.peaklearningllc.com Java 8 Programming for OO Experienced Developers (5 Days) This course is geared for developers who have prior working knowledge of object-oriented programming languages such as

More information

Introduction to Visual Basic and Visual C++ Introduction to Java. JDK Editions. Overview. Lesson 13. Overview

Introduction to Visual Basic and Visual C++ Introduction to Java. JDK Editions. Overview. Lesson 13. Overview Introduction to Visual Basic and Visual C++ Introduction to Java Lesson 13 Overview I154-1-A A @ Peter Lo 2010 1 I154-1-A A @ Peter Lo 2010 2 Overview JDK Editions Before you can write and run the simple

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

Java Programming Training for Experienced Programmers (5 Days)

Java Programming Training for Experienced Programmers (5 Days) www.peaklearningllc.com Java Programming Training for Experienced Programmers (5 Days) This Java training course is intended for students with experience in a procedural or objectoriented language. It

More information

Oracle 10g: Java Programming

Oracle 10g: Java Programming Oracle 10g: Java Programming Volume 1 Student Guide D17249GC12 Edition 1.2 July 2005 D19367 Author Kate Heap Technical Contributors and Reviewers Ken Cooper Brian Fry Jeff Gallus Glenn Maslen Gayathri

More information

Eclipse Tutorial. For Introduction to Java Programming By Y. Daniel Liang

Eclipse Tutorial. For Introduction to Java Programming By Y. Daniel Liang Eclipse Tutorial For Introduction to Java Programming By Y. Daniel Liang This supplement covers the following topics: Getting Started with Eclipse Choosing a Perspective Creating a Project Creating a Java

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

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

Atelier Java - J1. Marwan Burelle. EPITA Première Année Cycle Ingénieur.

Atelier Java - J1. Marwan Burelle.  EPITA Première Année Cycle Ingénieur. marwan.burelle@lse.epita.fr http://wiki-prog.kh405.net Plan 1 2 Plan 3 4 Plan 1 2 3 4 A Bit of History JAVA was created in 1991 by James Gosling of SUN. The first public implementation (v1.0) in 1995.

More information

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson Introduction History, Characteristics of Java language Java Language Basics Data types, Variables, Operators and Expressions Anatomy of a Java Program

More information

CompSci 125 Lecture 02

CompSci 125 Lecture 02 Assignments CompSci 125 Lecture 02 Java and Java Programming with Eclipse! Homework:! http://coen.boisestate.edu/jconrad/compsci-125-homework! hw1 due Jan 28 (MW), 29 (TuTh)! Programming:! http://coen.boisestate.edu/jconrad/cs125-programming-assignments!

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

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

Java is a high-level programming language originally developed by Sun Microsystems and released in Java runs on a variety of

Java is a high-level programming language originally developed by Sun Microsystems and released in Java runs on a variety of Java is a high-level programming language originally developed by Sun Microsystems and released in 1995. Java runs on a variety of platforms, such as Windows, Mac OS, and the various versions of UNIX.

More information

Core Java - SCJP. Q2Technologies, Rajajinagar. Course content

Core Java - SCJP. Q2Technologies, Rajajinagar. Course content Core Java - SCJP Course content NOTE: For exam objectives refer to the SCJP 1.6 objectives. 1. Declarations and Access Control Java Refresher Identifiers & JavaBeans Legal Identifiers. Sun's Java Code

More information

104. Intermediate Java Programming

104. Intermediate Java Programming 104. Intermediate Java Programming Version 6.0 This course teaches programming in the Java language -- i.e. the Java Standard Edition platform. It is intended for students with previous Java experience

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

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

Certified Core Java Developer VS-1036

Certified Core Java Developer VS-1036 VS-1036 1. LANGUAGE FUNDAMENTALS The Java language's programming paradigm is implementation and improvement of Object Oriented Programming (OOP) concepts. The Java language has its own rules, syntax, structure

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

Getting Started (1.8.7) 9/2/2009

Getting Started (1.8.7) 9/2/2009 2 Getting Started For the examples in this section, Microsoft Windows and Java will be used. However, much of the information applies to other operating systems and supported languages for which you have

More information

Java Programming with Eclipse

Java Programming with Eclipse One Introduction to Java 2 Usage of Java 3 Structure of Java 4 Flexibility of Java Programming 5 Using the Eclipse Software 6 Two Running Java in Eclipse 7 Introduction 8 Using Eclipse 9 Workspace Launcher

More information

Chapter 1 Getting Started

Chapter 1 Getting Started Chapter 1 Getting Started The C# class Just like all object oriented programming languages, C# supports the concept of a class. A class is a little like a data structure in that it aggregates different

More information

Java Programming. Price $ (inc GST)

Java Programming. Price $ (inc GST) 1800 ULEARN (853 276) www.ddls.com.au Java Programming Length 5 days Price $4235.00 (inc GST) Overview Intensive and hands-on, the course emphasizes becoming productive quickly as a Java application developer.

More information

MEAP Edition Manning Early Access Program Get Programming with Java Version 1

MEAP Edition Manning Early Access Program Get Programming with Java Version 1 MEAP Edition Manning Early Access Program Get Programming with Java Version 1 Copyright 2018 Manning Publications For more information on this and other Manning titles go to www.manning.com welcome First,

More information

Introduction. Overview of the Course on Java. Overview of Part 1 of the Course

Introduction. Overview of the Course on Java. Overview of Part 1 of the Course Introduction Michael B. Spring Department of Information Science and Telecommunications University of Pittsburgh spring@imap.pitt.edu http://www.sis.pitt.edu /~spring Overview of the Course on Java Part

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

Javac and Eclipse tutorial

Javac and Eclipse tutorial Javac and Eclipse tutorial Author: Balázs Simon, BME IIT, 2013. Contents 1 Introduction... 2 2 JRE and JDK... 2 3 Java and Javac... 2 4 Environment variables... 3 4.1 Setting the environment variables

More information

2 Getting Started. Getting Started (v1.8.6) 3/5/2007

2 Getting Started. Getting Started (v1.8.6) 3/5/2007 2 Getting Started Java will be used in the examples in this section; however, the information applies to all supported languages for which you have installed a compiler (e.g., Ada, C, C++, Java) unless

More information

Prerequisites for Eclipse

Prerequisites for Eclipse Prerequisites for Eclipse 1 To use Eclipse you must have an installed version of the Java Runtime Environment (JRE). The latest version is available from java.com/en/download/manual.jsp Since Eclipse includes

More information

3 CREATING YOUR FIRST JAVA APPLICATION (USING WINDOWS)

3 CREATING YOUR FIRST JAVA APPLICATION (USING WINDOWS) GETTING STARTED: YOUR FIRST JAVA APPLICATION 15 3 CREATING YOUR FIRST JAVA APPLICATION (USING WINDOWS) GETTING STARTED: YOUR FIRST JAVA APPLICATION Checklist: The most recent version of Java SE Development

More information

OracleAS 10g R3: Java Programming

OracleAS 10g R3: Java Programming OracleAS 10g R3: Java Programming Volume I Student Guide D18382GC20 Edition 2.0 April 2007 D50171 Authors Patrice Daux Kate Heap Technical Contributors and Reviewers Ken Cooper C Fuller Vasily Strelnikov

More information

CS 11 java track: lecture 1

CS 11 java track: lecture 1 CS 11 java track: lecture 1 Administrivia need a CS cluster account http://www.cs.caltech.edu/ cgi-bin/sysadmin/account_request.cgi need to know UNIX www.its.caltech.edu/its/facilities/labsclusters/ unix/unixtutorial.shtml

More information

Java Intro 3. Java Intro 3. Class Libraries and the Java API. Outline

Java Intro 3. Java Intro 3. Class Libraries and the Java API. Outline Java Intro 3 9/7/2007 1 Java Intro 3 Outline Java API Packages Access Rules, Class Visibility Strings as Objects Wrapper classes Static Attributes & Methods Hello World details 9/7/2007 2 Class Libraries

More information

Peers Techno log ies Pv t. L td. Core Java & Core Java &Adv Adv Java Java

Peers Techno log ies Pv t. L td. Core Java & Core Java &Adv Adv Java Java Page 1 Peers Techno log ies Pv t. L td. Course Brochure Core Java & Core Java &Adv Adv Java Java Overview Core Java training course is intended for students without an extensive programming background.

More information

JAVA. 1. Introduction to JAVA

JAVA. 1. Introduction to JAVA JAVA 1. Introduction to JAVA History of Java Difference between Java and other programming languages. Features of Java Working of Java Language Fundamentals o Tokens o Identifiers o Literals o Keywords

More information

Before you start working with Java, you need to set up a Java development

Before you start working with Java, you need to set up a Java development Setting Up the Java Development Environment Before you start working with Java, you need to set up a Java development environment. This includes installing the Java Standard Edition (SE) Development Kit

More information

Fast Track to Core Java 8 Programming for OO Developers (TT2101-J8) Day(s): 3. Course Code: GK1965. Overview

Fast Track to Core Java 8 Programming for OO Developers (TT2101-J8) Day(s): 3. Course Code: GK1965. Overview Fast Track to Core Java 8 Programming for OO Developers (TT2101-J8) Day(s): 3 Course Code: GK1965 Overview Java 8 Essentials for OO Developers is a three-day, fast-paced, quick start to Java 8 training

More information

Java Bytecode (binary file)

Java Bytecode (binary file) Java is Compiled Unlike Python, which is an interpreted langauge, Java code is compiled. In Java, a compiler reads in a Java source file (the code that we write), and it translates that code into bytecode.

More information

Core Java Syllabus. Overview

Core Java Syllabus. Overview Core Java Syllabus Overview Java programming language was originally developed by Sun Microsystems which was initiated by James Gosling and released in 1995 as core component of Sun Microsystems' Java

More information

Java Programming Constructs Java Programming 2 Lesson 1

Java Programming Constructs Java Programming 2 Lesson 1 Java Programming Constructs Java Programming 2 Lesson 1 Course Objectives Welcome to OST's Java 2 course! In this course, you'll learn more in-depth concepts and syntax of the Java Programming language.

More information

2 rd class Department of Programming. OOP with Java Programming

2 rd class Department of Programming. OOP with Java Programming 1. Structured Programming and Object-Oriented Programming During the 1970s and into the 80s, the primary software engineering methodology was structured programming. The structured programming approach

More information

Index. Course Outline. Grading Policy. Lab Time Distribution. Important Instructions

Index. Course Outline. Grading Policy. Lab Time Distribution. Important Instructions Index Course Outline Grading Policy Lab Time Distribution Important Instructions 2 Course Outline Week Topics 1 - History and Evolution of Java - Overview of Java 2 - Datatypes - Variables 3 - Arrays 4

More information

Software Development & Education Center. Java Platform, Standard Edition 7 (JSE 7)

Software Development & Education Center. Java Platform, Standard Edition 7 (JSE 7) Software Development & Education Center Java Platform, Standard Edition 7 (JSE 7) Detailed Curriculum Getting Started What Is the Java Technology? Primary Goals of the Java Technology The Java Virtual

More information

Language Features. 1. The primitive types int, double, and boolean are part of the AP

Language Features. 1. The primitive types int, double, and boolean are part of the AP Language Features 1. The primitive types int, double, and boolean are part of the AP short, long, byte, char, and float are not in the subset. In particular, students need not be aware that strings are

More information

Chapter Two Bonus Lesson: JavaDoc

Chapter Two Bonus Lesson: JavaDoc We ve already talked about adding simple comments to your source code. The JDK actually supports more meaningful comments as well. If you add specially-formatted comments, you can then use a tool called

More information

Core Java Syllabus. Pre-requisite / Target Audience: C language skills (Good to Have)

Core Java Syllabus. Pre-requisite / Target Audience: C language skills (Good to Have) Overview: Java programming language is developed by Sun Microsystems. Java is object oriented, platform independent, simple, secure, architectural neutral, portable, robust, multi-threaded, high performance,

More information

Complete Java Contents

Complete Java Contents Complete Java Contents Duration: 60 Hours (2.5 Months) Core Java (Duration: 25 Hours (1 Month)) Java Introduction Java Versions Java Features Downloading and Installing Java Setup Java Environment Developing

More information

Chapter 4 Defining Classes I

Chapter 4 Defining Classes I Chapter 4 Defining Classes I This chapter introduces the idea that students can create their own classes and therefore their own objects. Introduced is the idea of methods and instance variables as the

More information

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 2: SEP. 8TH INSTRUCTOR: JIAYIN WANG

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 2: SEP. 8TH INSTRUCTOR: JIAYIN WANG CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 2: SEP. 8TH INSTRUCTOR: JIAYIN WANG 1 Notice Class Website http://www.cs.umb.edu/~jane/cs114/ Reading Assignment Chapter 1: Introduction to Java Programming

More information

COMP 110/401 APPENDIX: INSTALLING AND USING ECLIPSE. Instructor: Prasun Dewan (FB 150,

COMP 110/401 APPENDIX: INSTALLING AND USING ECLIPSE. Instructor: Prasun Dewan (FB 150, COMP 110/401 APPENDIX: INSTALLING AND USING ECLIPSE Instructor: Prasun Dewan (FB 150, dewan@unc.edu) SCOPE: BASICS AND BEYOND Basic use: CS 1 Beyond basic use: CS2 2 DOWNLOAD FROM WWW.ECLIPSE.ORG Get the

More information

For live Java EE training, please see training courses at

For live Java EE training, please see training courses at Java with Eclipse: Setup & Getting Started Originals of Slides and Source Code for Examples: http://courses.coreservlets.com/course-materials/java.html For live Java EE training, please see training courses

More information

Core Java Contents. Duration: 25 Hours (1 Month)

Core Java Contents. Duration: 25 Hours (1 Month) Duration: 25 Hours (1 Month) Core Java Contents Java Introduction Java Versions Java Features Downloading and Installing Java Setup Java Environment Developing a Java Application at command prompt Java

More information

Page 1

Page 1 Java 1. Core java a. Core Java Programming Introduction of Java Introduction to Java; features of Java Comparison with C and C++ Download and install JDK/JRE (Environment variables set up) The JDK Directory

More information

[Course Overview] After completing this module you are ready to: Develop Desktop applications, Networking & Multi-threaded programs in java.

[Course Overview] After completing this module you are ready to: Develop Desktop applications, Networking & Multi-threaded programs in java. [Course Overview] The Core Java technologies and application programming interfaces (APIs) are the foundation of the Java Platform, Standard Edition (Java SE). They are used in all classes of Java programming,

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

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

Rules and syntax for inheritance. The boring stuff

Rules and syntax for inheritance. The boring stuff Rules and syntax for inheritance The boring stuff The compiler adds a call to super() Unless you explicitly call the constructor of the superclass, using super(), the compiler will add such a call for

More information

3 Getting Started with Objects

3 Getting Started with Objects 3 Getting Started with Objects If you are an experienced IDE user, you may be able to do this tutorial without having done the previous tutorial, Getting Started. However, at some point you should read

More information

ICOM 4015 Advanced Programming Laboratory. Chapter 1 Introduction to Eclipse, Java and JUnit

ICOM 4015 Advanced Programming Laboratory. Chapter 1 Introduction to Eclipse, Java and JUnit ICOM 4015 Advanced Programming Laboratory Chapter 1 Introduction to Eclipse, Java and JUnit University of Puerto Rico Electrical and Computer Engineering Department by Juan E. Surís 1 Introduction This

More information

Module Road Map. 7. Version Control with Subversion Introduction Terminology

Module Road Map. 7. Version Control with Subversion Introduction Terminology Module Road Map 1. Overview 2. Installing and Running 3. Building and Running Java Classes 4. Refactoring 5. Debugging 6. Testing with JUnit 7. Version Control with Subversion Introduction Terminology

More information

Lesson 10A OOP Fundamentals. By John B. Owen All rights reserved 2011, revised 2014

Lesson 10A OOP Fundamentals. By John B. Owen All rights reserved 2011, revised 2014 Lesson 10A OOP Fundamentals By John B. Owen All rights reserved 2011, revised 2014 Table of Contents Objectives Definition Pointers vs containers Object vs primitives Constructors Methods Object class

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

Project 1 Computer Science 2334 Spring 2016 This project is individual work. Each student must complete this assignment independently.

Project 1 Computer Science 2334 Spring 2016 This project is individual work. Each student must complete this assignment independently. Project 1 Computer Science 2334 Spring 2016 This project is individual work. Each student must complete this assignment independently. User Request: Create a simple movie data system. Milestones: 1. Use

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

Lecture 02, Fall 2018 Friday September 7

Lecture 02, Fall 2018 Friday September 7 Anatomy of a class Oliver W. Layton CS231: Data Structures and Algorithms Lecture 02, Fall 2018 Friday September 7 Follow-up Python is also cross-platform. What s the advantage of Java? It s true: Python

More information

Outline. Overview. Control statements. Classes and methods. history and advantage how to: program, compile and execute 8 data types 3 types of errors

Outline. Overview. Control statements. Classes and methods. history and advantage how to: program, compile and execute 8 data types 3 types of errors Outline Overview history and advantage how to: program, compile and execute 8 data types 3 types of errors Control statements Selection and repetition statements Classes and methods methods... 2 Oak A

More information

Teiid Designer User Guide 7.5.0

Teiid Designer User Guide 7.5.0 Teiid Designer User Guide 1 7.5.0 1. Introduction... 1 1.1. What is Teiid Designer?... 1 1.2. Why Use Teiid Designer?... 2 1.3. Metadata Overview... 2 1.3.1. What is Metadata... 2 1.3.2. Editing Metadata

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

Introduction to Java. Lecture 1 COP 3252 Summer May 16, 2017

Introduction to Java. Lecture 1 COP 3252 Summer May 16, 2017 Introduction to Java Lecture 1 COP 3252 Summer 2017 May 16, 2017 The Java Language Java is a programming language that evolved from C++ Both are object-oriented They both have much of the same syntax Began

More information

13 th Windsor Regional Secondary School Computer Programming Competition

13 th Windsor Regional Secondary School Computer Programming Competition SCHOOL OF COMPUTER SCIENCE 13 th Windsor Regional Secondary School Computer Programming Competition Hosted by The School of Computer Science, University of Windsor WORKSHOP I [ Overview of the Java/Eclipse

More information

5/3/2006. Today! HelloWorld in BlueJ. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont.

5/3/2006. Today! HelloWorld in BlueJ. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. Today! Build HelloWorld yourself in BlueJ and Eclipse. Look at all the Java keywords. Primitive Types. HelloWorld in BlueJ 1. Find BlueJ in the start menu, but start the Select VM program instead (you

More information

Programming. Syntax and Semantics

Programming. Syntax and Semantics Programming For the next ten weeks you will learn basic programming principles There is much more to programming than knowing a programming language When programming you need to use a tool, in this case

More information

Getting Started with Eclipse for Java

Getting Started with Eclipse for Java Getting Started with Eclipse for Java Maria Litvin Phillips Academy, Andover, Massachusetts Gary Litvin Skylight Publishing 1. Introduction 2. Downloading and Installing Eclipse 3. Importing and Exporting

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

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

Project #1 rev 2 Computer Science 2334 Fall 2013 This project is individual work. Each student must complete this assignment independently.

Project #1 rev 2 Computer Science 2334 Fall 2013 This project is individual work. Each student must complete this assignment independently. Project #1 rev 2 Computer Science 2334 Fall 2013 This project is individual work. Each student must complete this assignment independently. User Request: Create a simple magazine data system. Milestones:

More information

Crash Course Review Only. Please use online Jasmit Singh 2

Crash Course Review Only. Please use online Jasmit Singh 2 @ Jasmit Singh 1 Crash Course Review Only Please use online resources @ Jasmit Singh 2 Java is an object- oriented language Structured around objects and methods A method is an action or something you

More information

EMC Documentum Composer

EMC Documentum Composer EMC Documentum Composer Version 6.0 SP1.5 User Guide P/N 300 005 253 A02 EMC Corporation Corporate Headquarters: Hopkinton, MA 01748 9103 1 508 435 1000 www.emc.com Copyright 2008 EMC Corporation. All

More information

E Oracle 10g Java Bootcamp I v1

E Oracle 10g Java Bootcamp I v1 E Oracle 10g Java Bootcamp I v1 Student Guide Volume 1 D22059GC10 Edition 1.0 October 2005 D22281 Authors Jeff Gallus Glenn Stokol Editor Gayathri Rajagopal Technical Contributors and Reviewers Kenneth

More information

Java with Eclipse: Setup & Getting Started

Java with Eclipse: Setup & Getting Started Java with Eclipse: Setup & Getting Started Originals of slides and source code for examples: http://courses.coreservlets.com/course-materials/java.html Also see Java 8 tutorial: http://www.coreservlets.com/java-8-tutorial/

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

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

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

F1 A Java program. Ch 1 in PPIJ. Introduction to the course. The computer and its workings The algorithm concept

F1 A Java program. Ch 1 in PPIJ. Introduction to the course. The computer and its workings The algorithm concept F1 A Java program Ch 1 in PPIJ Introduction to the course The computer and its workings The algorithm concept The structure of a Java program Classes and methods Variables Program statements Comments Naming

More information

CHAPTER 6. Java Project Configuration

CHAPTER 6. Java Project Configuration CHAPTER 6 Java Project Configuration Eclipse includes features such as Content Assist and code templates that enhance rapid development and others that accelerate your navigation and learning of unfamiliar

More information

Java SE 7 Programming

Java SE 7 Programming Oracle University Contact Us: Local: 1800 103 4775 Intl: +91 80 4108 4709 Java SE 7 Programming Duration: 5 Days What you will learn This is the second of two courses that cover the Java Standard Edition

More information

JAVA: A Primer. By: Amrita Rajagopal

JAVA: A Primer. By: Amrita Rajagopal JAVA: A Primer By: Amrita Rajagopal 1 Some facts about JAVA JAVA is an Object Oriented Programming language (OOP) Everything in Java is an object application-- a Java program that executes independently

More information

Programming overview

Programming overview Programming overview Basic Java A Java program consists of: One or more classes A class contains one or more methods A method contains program statements Each class in a separate file MyClass defined in

More information

A PROGRAM IS A SEQUENCE of instructions that a computer can execute to

A PROGRAM IS A SEQUENCE of instructions that a computer can execute to A PROGRAM IS A SEQUENCE of instructions that a computer can execute to perform some task. A simple enough idea, but for the computer to make any use of the instructions, they must be written in a form

More information