BTCOE 404 ObjectOriented Programming using Java Unit 1
BT-COE 404 Object-Oriented Programming using Java Unit 1 6 hrs Introduction to Computers and Java: Computers: Hardware and Software, Data Hierarchy, Computer Organization, Machine Languages, Assembly Languages and High -Level Languages, Introduction to Object Technology, Operating Systems, Programming Languages, Java and a Typical Java Development Environment, Your First Program in Java: Printing a Line of Text, Modifying Your First Java Program, Displaying Text with printf, Another Application: Adding Integers, Memory Concepts, Arithmetic, Decision Making: Equality and Relational Operators.
• Reference Book: 1. Paul Deitel and Harvey Detail, Java: How to Program, Pearson's Publication, 9 th Edition, 2012. 2. Joel Murach and Michael Urban, Murach’s Beginning Java with Eclipse, Murach's Publication, 1 st Edition, 2016. 3. Doug Lowe, Java All-in-One For Dummies, Wiley Publication, 4 th Edition, 2014. 4. Herbert Schildt, Java The Complete Reference, Mc. Graw-Hill Publication, 9 th Edition, 2014. 5. Patrick Niemeyer, Daniel Leuck, Learning Java, O'Reilly Media, 4 th Edition, 2013.
Computers: Hardware and Software • What Is a Computer? • A computer is a device capable of performing computations and making logical decisions at speeds millions (even billions) of times faster than human beings can. • Computers process data under the control of sets of instructions called computer programs. • These programs guide the computer through orderly sets of actions specified by people called computer programmers. • A computer consists of various devices referred to as hardware (e. g. , the keyboard, screen, mouse, disks, memory, DVD, CD-ROM and processing units). The programs that run on a computer are referred to as software.
What Is a Computer? • Computer – Performs computations and makes logical decisions – Millions / billions times faster than human beings • Computer programs – Sets of instructions for which computer processes data • Hardware – Physical devices of computer system • Software – Programs that run on computers 2002 Prentice Hall. All rights reserved.
4 Data Hierarchy. • Data Hierarchy Data hierarchy refers to the systematic organization of data, often in a hierarchical form. Data organization involves characters, fields, records, files and so on Following are the components of data hierarchy (ascending order of complexity) in an information system: D 1. Bit • The term bit is short form for binary digit. It can assume either of two possible states and, therefore, can represent either 0 or 1. In secondary storage, a bit is used to represent data through positive or negative polarity of an electrical charge on a magnetic recording medium, such as tape or disk. Semi conductor ata Record storage is usually used for primary storage. In semiconductor storage, a bit is represented by an electrical circuit that is either conducting or not conducting electricity. A 2. Byte record is a collection of fields relating A • An ability to represent only binary digits in a computer system is not sufficient for business information processing. Numeric and alphabetic characters as well as a wide variety of special characters (such as, dollar signs, question marks and quotation marks) should be stored. In a computer system, a character of information is called a byte. A byte of information is stored by using several bits in specified combination called bit patterns. A widely used bit pattern for personal computers and data communication is the American Standard Code for Information Interchange (ASCII). ASCII uses seven bits to represent one character. Each 1 or 0 corresponds to a single bit. n analogycan be made between a co
3. Data Field or Item • The next level in data hierarchy is a field or item of data. A field or item of data is one or more bytes containing data about the attribute of an entity in an information system. An entity in a payroll system is an individual employee. Attributes are the employees name, pay rate and so on. The basic pay is a field or item of data 4. Data Record • A record is a collection of fields relating to a specific entity. For example, a payroll record contains fields of data relating to a specific employee. • An analogy can be made between a computer-based record an individual folder in a manual file. • A folder in a payroll file may contain almost the same information as a record in a computer-based payroll file. • The field that identifies a record from all other records in a file is the record key. For example, the record key in a payroll record is usually an employees provident fund number or social security number because it is different for each employee.
5. File • A file is a collection of related records. 6. Database • A database consists of all the files of an organization. It is structured and integrated to facilitate update of the files and retrieval of information from them. • The term has often been used rather loosely. • Technically, a database consists of those files that are a part of data base management system. However, a database is often used to refer to all the files of an organization. Now, all this is called as data hierarchy because databases are composed of files, files are composed of records, records are composed of filed, fields composed of data bytes and finally, data bytes are a group of bits. • This is very well a hierarchical structure.
Computer Organization • Six logical units of computer system – Input unit • Mouse, keyboard – Output unit • Printer, monitor, audio speakers – Memory unit • RAM – Arithmetic and logic unit (ALU) • Performs calculations – Central processing unit (CPU) • Supervises operation of other devices – Secondary storage unit • Hard drives, floppy drives 2002 Prentice Hall. All rights reserved.
Computer Organization • computer may be envisioned as divided into six logical units or sections: 1. Input unit. - This “receiving” section obtains information (data and computer programs) from input devices and places this information at the disposal of the other units so that it can be processed. Most information is entered into computers through keyboards and mouse devices. Information also can be entered in many other ways, including by speaking to your computer, by scanning images and by having your computer receive information from a network, such as the Internet. 2. Output unit. - This takes information that the computer has • processed and places it on various output devices to make the information available for use outside the computer. • Most information output from computers today is displayed on screens, printed on paper or used to control other devices. • Computers also can output their information to networks, such as the Internet.
3. Memory unit. -This rapid-access, relatively low-capacity “warehouse” section retains information that has been entered through the input unit, so that it will be immediately available for processing when needed. The memory unit also retains processed information until it can be placed on output devices by the output unit. • Information in the memory unit is typically lost when the computer’s power is turned off. The memory unit is often called either memory or primary memory. 4. Arithmetic and logic unit (ALU). This “manufacturing” section is responsible for • performing calculations, such as addition, subtraction, multiplication and division. • It contains the decision mechanisms that allow the computer, for example, to compare two items from the memory unit to determine whether they are equal.
5. Central processing unit (CPU). -This “administrative” section coordinates and supervises the operation of the other sections. The CPU tells the input unit when information should be read into the memory unit, tells the ALU when information from the memory unit should be used in calculations and tells the output unit when to send information from the memory unit to certain output devices. Many of today’s computers have multiple CPUs and, hence, can perform many operations simultaneously—such computers are called multiprocessors. 6. Secondary storage unit. -This is the long-term, high-capacity “warehousing” section. • Programs or data not actively being used by the other units normally are placed on secondary storage devices (e. g. , your hard drive) until they are again needed, possibly hours, days, months or even years later. Information in secondary storage takes much longer to access than information in primary memory, but the cost per unit of secondary storage is much less than that of primary memory. • Examples of secondary storage devices include CDs and DVDs, which can hold up to hundreds of millions of characters and billions of characters, respectively.
Machine Languages, Assembly Languages and High-Level Languages • Machine language – “Natural language” of computer component – Machine dependent • Assembly language – English-like abbreviations represent computer operations – Translator programs convert to machine language • High-level language – Allows for writing more “English-like” instructions • Contains commonly used mathematical operations – Compiler convert to machine language • Interpreter – Execute high-level language programs without compilation 2002 Prentice Hall. All rights reserved.
Programming Languages Machine Languages, Assembly Languages and High-Level Languages • Programmers write instructions in various programming languages, some directly understandable by computers and others requiring intermediate translation steps. Hundreds of computer languages are in use today. These may be divided into three general types: 1. Machine languages 2. Assembly languages 3. High-level languages • Any computer can directly understand only its own machine language. Machine language is the “natural language” of a computer and as such is defined by its hardware design. • Machine languages generally consist of strings of numbers (ultimately reduced to 1 s and 0 s) that instruct computers to perform their most elementary operations one at a time. • Machine languages are machine dependent (i. e. , a particular machine language can be used on only one type of computer). Such languages are cumbersome for humans
• A programming language is a formal language, which comprises a set of instructions used to produce various kinds of output. Programming languages are used in computer programming to create programs that implement specific algorithms. • Most programming languages consist of instructions for computers, although there are programmable machines that use a limited set of specific instructions, rather than the general programming languages of modern computers. • A machine language consists of the numeric codes for the operations that a particular computer can execute directly. The codes are strings of 0 s and 1 s, or binary digits (“bits”), which are frequently converted both from and to hexadecimal (base 16) for human viewing and modification. Machine language instructions typically use some bits to represent operations, such as addition, and some to represent operands, or perhaps the location of the next instruction. Machine language is difficult to read and write, since it does not resemble conventional mathematical notation or human language, and its codes vary from computer to computer.
• Machine-language programming was simply too slow and tedious for most programmers. Instead of using the strings of numbers that computers could directly understand, programmers began using English-like abbreviations to represent elementary operations. These abbreviations formed the basis of assembly languages. Translator programs called assemblers were developed to convert early assembly-language programs to machine language at computer speeds. • Assembly language is one level above machine language. It uses short mnemonic codes for instructions and allows the programmer to introduce names for blocks of memory that hold data. One might thus write “add pay, total” instead of “ 0110101100101000” for an instruction that adds two numbers.
• high-level languages were developed in which single statements could be written to accomplish substantial tasks. Translator programs called compilers convert high-level language programs into machine language. High-level languages allow programmers to write instructions that look almost like everyday English and contain commonly used mathematical notations. • high-level languages are preferable to machine and assembly language from the programmer’s standpoint. C, C++, Microsoft’s. NET languages (e. g. , Visual Basic . NET, Visual C++ . NET and C#) are among the most widely used highlevel programming languages; Java is the most widely used. • The process of compiling a high-level language program into machine language can take a considerable amount of computer time. Interpreter programs were developed to execute high-level language programs directly, although more slowly. Interpreters are popular in program-development environments in which new features are being added and errors corrected.
• Hierarchy of Computer language – • • • Most Popular Programming Languages – C Python C++ Java SCALA C# R Ruby Go Swift Java. Script
History of C++ • C++ – Evolved from C • Evolved from BCPL and B – Provides object-oriented programming capabilities • Objects – Reusable software components that model real-world items 2002 Prentice Hall. All rights reserved.
History of Java • Java – Originally for intelligent consumer-electronic devices – Then used for creating Web pages with dynamic content – Now also used for: • Develop large-scale enterprise applications • Enhance WWW server functionality • Provide applications for consumer devices (cell phones, etc. ) 2002 Prentice Hall. All rights reserved.
Java Class Libraries • Classes – Contain methods that perform tasks • Return information after task completion – Used to build Java programs • Java contains class libraries – Known as Java APIs (Application Programming Interfaces) 2002 Prentice Hall. All rights reserved.
Other High-Level Languages • Fortran – FORmula TRANslator • COBOL – COmmon Business Oriented Language • Pascal • Basic 2002 Prentice Hall. All rights reserved.
Structured Programming • Structured Programming – Structured programs • Clearer than unstructured programs • Easier to test, debug and modify – Pascal designed for teaching structured programming – ADA • Multitasking – C 2002 Prentice Hall. All rights reserved.
The Internet and the World Wide Web • Internet – Developed over three decades ago with DOD funding – Originally for connecting few main computer systems – Now accessible by hundreds of millions of computers • World Wide Web (WWW) – Allows for locating/viewing multimedia-based documents 2002 Prentice Hall. All rights reserved.
• Characteristics of a programming Language – • A programming language must be simple, easy to learn and use, have good readability and human recognizable. • Abstraction is a must-have Characteristics for a programming language in which ability to define the complex structure and then its degree of usability comes. • A portable programming language is always preferred. • Programming language’s efficiency must be high so that it can be easily converted into a machine code and executed consumes little space in memory. • A programming language should be well structured and documented so that it is suitable for application development. • Necessary tools for development, debugging, testing, maintenance of a program must be provided by a programming language. • A programming language should provide single environment known as Integrated Development Environment(IDE). • A programming language must be consistent in terms of syntax and semantics.
Introduction to Object Technology • Object-orientation is what’s referred to as a programming paradigm. It’s not a language itself but a set of concepts that is supported by many languages. • In computer programming, Objects, or more precisely, the classes used to construct objects, are intended to be reusable software components. • There are string objects, output objects, input objects, graphics objects, date objects, time objects, audio objects, video objects, etc. • a software object in terms of attributes (e. g. , name, color and size) and behaviors (e. g. , calculating, moving and communicating). • Using a modular, object-oriented design and implementation approach can make software-development more productive. Object-oriented programs are often easier to understand, correct and modify.
• Object-oriented programming organizes a program around its data (that is, objects) and a set of well-defined interfaces to that data. An object-oriented program can be characterized as data controlling access to code • All object-oriented programming languages provide mechanisms that help you implement the object-oriented model. They are encapsulation, inheritance, and polymorphism
• Object orientation • Unified Modeling Language (UML) – Graphical language that uses common notation – Allows developers to represent object-oriented designs 2002 Prentice Hall. All rights reserved.
Thinking About Objects (cont. ) • Objects – Reusable software components that model real-world items – Look all around you • People, animals, plants, cars, etc. – Attributes • Size, shape, color, weight, etc. – Behaviors • Babies cry, crawl, sleep, etc. 2002 Prentice Hall. All rights reserved.
Thinking About Objects (cont. ) • Object-oriented design (OOD) – Models real-world objects – Models communication among objects – Encapsulates data (attributes) and functions (behaviors) • Information hiding • Communication through well-defined interfaces • Object-oriented language – Programming is called object-oriented programming (OOP) – Java 2002 Prentice Hall. All rights reserved.
Thinking About Objects (cont. ) • Object-Oriented Analysis and Design (OOAD) – Essential for large programs – Analyze program requirements, then develop solution – We begin OOAD in Chapter 2 • Elevator-simulation case study 2002 Prentice Hall. All rights reserved.
Thinking About Objects (cont. ) • History of the UML – – Need developed for process with which to approach OOAD Brainchild of Booch, Rumbaugh and Jacobson Object Management Group (OMG) supervised Version 1. 4 is current version • Version 2. 0 scheduled tentatively for release in 2002 Prentice Hall. All rights reserved.
Thinking About Objects (cont. ) • UML – Graphical representation scheme – Enables developers to model object-oriented systems – Flexible and extendible 2002 Prentice Hall. All rights reserved.
1. 16 Discovering Design Patterns: Introduction • Effective design crucial for large programs • Design patterns – Proven architectures for developing object-oriented software • Architectures created from accumulated industry experience – – – Reduce design-process complexity Promotes design reuse in future systems Helps identify common design mistakes and pitfalls Helps design independently of implementation language Establishes common design “vocabulary” Shortens design phase in software-development process 2002 Prentice Hall. All rights reserved.
Evolution of Operating Systems • Batch processing – One job (task) at a time – Operating systems developed • Programs to make computers more convenient to use • Switch jobs easier • Multiprogramming – “Simultaneous” jobs – Timesharing operating systems 2002 Prentice Hall. All rights reserved.
1. 5 Personal, Distributed and Client/Server Computing • Personal computing – Computers for personal use • Distributed computing – Computing performed among several computers • Client/server computing – Servers offer common store of programs and data – Clients access programs and data from server 2002 Prentice Hall. All rights reserved.
Operating Systems • An operating system (OS), is software that allows a user to run other applications on a computing device. While it is possible for a software application to interface directly with hardware, the vast majority of applications are written for an OS, which allows them to take advantage of common libraries and not worry about specific hardware details. • The operating system manages a computer's hardware resources, including: Input devices such as a keyboard and mouse, Output devices such as display monitors, printers and scanners • Network devices such as modems, routers and network connections • Storage devices such as internal and external drives • The OS also provides services to facilitate the efficient execution and management of, and memory allocations for, any additional installed software application programs.
• Early computers could perform only one job or task at a time. This is often called single user batch processing. The computer runs a single program at a time while processing data in groups or batches. • In these early systems, users generally submitted their jobs to a computer center on decks of punched cards and often had to wait hours or even days before printouts were returned to their desks. Software systems called operating systems were developed to make using computers more convenient. • Early operating systems smoothed and speeded up the transition between jobs, increasing the amount of work, or throughput, computers could process. As computers became more powerful, it became evident that single-user batch processing was inefficient, because so much time was spent waiting for slow input/output devices to complete their tasks. • It was thought that many jobs or tasks could share the resources of the computer to achieve better utilization. This is called multiprogramming. Multiprogramming involves the simultaneous operation of many jobs that are competing to share the computer’s resources. With early multiprogramming operating systems, users still submitted jobs on decks of punched cards and waited hours or days for results.
• Examples of computer operating systems 1. Microsoft Windows 10 - PC and IBM compatible operating system. Microsoft Windows is the most common and used operating system. 2. Apple mac. OS - Apple Mac operating system. Today, the only Apple computer operating system is mac. OS. 3. Ubuntu Linux - A popular variant of Linux used with PC and IBM compatible computers. 4. Google Android - Operating system used with Android compatible phones and tablets. 5. i. OS - Operating system used with the Apple i. Phone and i. Pads. 6. Chromium - Google operating system used with Chromebooks.
1. 13 Basics of a Typical Java Environment • Java systems contain – – Environment Language APIs Class libraries 2002 Prentice Hall. All rights reserved.
1. 13 Basics of a Typical Java Environment (cont. ) • Java programs normally undergo five phases – Edit • Programmer writes program (and stores program on disk) – Compile • Compiler creates bytecodes from program – Load • Class loader stores bytecodes in memory – Verify • Verifier ensures bytecodes do not violate security requirements – Execute • Interpreter translates bytecodes into machine language 2002 Prentice Hall. All rights reserved.
Fig. 1. 1 A typical Java environment. 2002 Prentice Hall. All rights reserved.
2002 Prentice Hall. All rights reserved.
Java and a Typical Java Development Environment • Java: Sun Microsystems in 1991 funded an internal corporate research project led by James Gosling, which resulted in a C++-based object-oriented programming language Sun called Java. A key goal of Java is to be able to write programs that will run on a great variety of computer systems and computer-control devices. This is sometimes called “write once, run anywhere. ” • Java is now used to develop large-scale enterprise applications, to enhance the functionality of web servers (the computers that provide the content we see in our web browsers), to provide applications for consumer devices (e. g. , cell phones, smartphones, television set-top boxes and more) and for many other purposes. Sun Microsystems was acquired by Oracle in 2009. At the Java. One 2010 conference, Oracle announced that 97% of enterprise desktops, three billion handsets, and 80 million television devices run Java. There are currently over 9 million Java developers, up from 4. 5 million in 2005. 8 Java is now the most widely used software development language in the world.
• Java programs normally go through five phases—edit, compile, load, verify and execute. • We discuss these phases in the context of the Java SE Development Kit (JDK). You can download the most up-to-date JDK and its documentation from www. oracle. com/technetwork/java/ javase/downloads/index. html Phase 1: Creating a Program • Phase 1 consists of editing a file with an editor program, normally known simply as an editor • You type a Java program (typically referred to as source code) using the editor, • make any necessary corrections and save the program on a secondary storage device, such as your hard drive. A file name ending with the. java extension indicates that the file contains Java source code. • integrated development environments (IDEs) are available from many major software suppliers. • IDEs provide tools that support the software development process, including editors for writing and editing programs • Popular IDEs include Eclipse (www. eclipse. org) and Net. Beans (www. netbeans. org).
Phase 2: Compiling a Java Program into Bytecodes • use the command javac (the Java compiler) to compile a program • For example, to compile a program called Welcome. java, you’d type in the command window of your system (i. e. , the Command Prompt in Windows, the shell prompt in Linux or the Terminal application in Mac OS X). If the program compiles, the compiler produces a. class file called Welcome. class that contains the compiled version of the program. • The Java compiler translates Java source code into bytecodes that represent the tasks to execute in the execution phase. Bytecodes are executed by the Java Virtual Machine (JVM)—a part of the JDK and the foundation of the Java platform. • Virtual machine (VM) is a software application that simulates a computer but hides the underlying operating system and hardware from the programs that interact with it. If the same VM is implemented on many computer platforms, applications that it executes can be used on all those platforms. • Java’s bytecodes are portable—without recompiling the source code, the same bytecodes can execute on any platform containing a JVM that understands the version of Java in which the bytecodes were compiled. • The JVM is invoked by the java command. • For example, to execute a Java application called Welcome, you’d type the command in a command window to invoke the JVM as java Welcome
Phase 3: Loading a Program into Memory • JVM places the program in memory to execute it—this is known as loading • The JVM’s class loader takes the . class files containing the program’s bytecodes and transfers them to primary memory. The. class files can be loaded from a disk on your system or over a network (e. g. , your local college or company network, or the Internet).
Phase 4: Bytecode Verification • as the classes are loaded, the bytecode verifier examines their bytecodes to ensure that they’re valid and do not violate Java’s security restrictions
Phase 5: Execution • the JVM executes the program’s bytecodes, thus performing the actions specified by the program. • JVMs typically execute bytecodes using a combination of interpretation and so-called just-in-time (JIT) compilation. In this process, the JVM analyzes the bytecodes as they’re interpreted, searching for hot spots—parts of the bytecodes that execute frequently. For these parts, a just-in-time (JIT) compiler— known as the Java Hot. Spot compiler—translates the bytecodes into the underlying computer’s machine language. • When the JVM encounters these compiled parts again, the faster machine-language code executes. Thus Java programs actually go through two compilation phases—one in which source code is translated into bytecodes (for portability across JVMs on different computer platforms) and a second in which, during execute the bytecodes are translated into machine language for the actual computer on which the program executes.
Your First Program in Java: Printing a Line of Text, Modifying Your First Java Program
1 2 3 4 5 6 7 8 9 10 11 12 13 // Fig. 2. 1: Welcome 1. java // A first program in Java. Outline public class Welcome 1 { // main method begins execution of Java application public static void main( String args[] ) { System. out. println( "Welcome to Java Programming!" ); } } // end method main // end class Welcome 1 Welcome to Java Programming! Welcome 1. java Program Output 2002 Prentice Hall. All rights reserved. 54
55 2. 2 A Simple Program: Printing a Line of Text 1 // Fig. 2. 1: Welcome 1. java – Comments start with: // • Comments ignored during program execution • Document and describe code • Provides code readability – Multiple line comments: /*. . . */ /* This is a multiple line comment. It can be split over many lines */ 2 // A first program in Java. – Another line of comments – Note: line numbers not part of program, added for reference 2002 Prentice Hall. All rights reserved.
56 2. 2 A Simple Program: Printing a Line of Text 3 – Blank line • Makes program more readable • Blank lines, spaces, and tabs are white-space characters – Ignored by compiler 4 public class Welcome 1 { – Begins class definition for class Welcome 1 • Every Java program has at least one user-defined class • Keyword: words reserved for use by Java – class keyword followed by class name • Naming classes: capitalize every word – Sample. Class. Name 2002 Prentice Hall. All rights reserved.
57 2. 2 A Simple Program: Printing a Line of Text 4 public class Welcome 1 { – Name of class called identifier • Series of characters consisting of letters, digits, underscores ( _ ) and dollar signs ( $ ) • Does not begin with a digit, has no spaces • Examples: Welcome 1, $value, _value, button 7 – 7 button is invalid • Java is case sensitive (capitalization matters) – a 1 and A 1 are different – For chapters 2 to 7, use public keyword • Certain details not important now • Mimic certain features, discussions later 2002 Prentice Hall. All rights reserved.
58 2. 2 A Simple Program: Printing a Line of Text 4 public class Welcome 1 { – Saving files • File name must be class name with. java extension • Welcome 1. java – Left brace { • Begins body of every class • Right brace ends definition (line 13) 7 public static void main( String args[] ) – Part of every Java application • Applications begin executing at main – Parenthesis indicate main is a method (ch. 6) – Java applications contain one or more methods 2002 Prentice Hall. All rights reserved.
59 2. 2 A Simple Program: Printing a Line of Text 7 public static void main( String args[] ) • Exactly one method must be called main – Methods can perform tasks and return information • void means main returns no information • For now, mimic main's first line 8 { – Left brace begins body of method definition • Ended by right brace } (line 11) 2002 Prentice Hall. All rights reserved.
60 2. 2 A Simple Program: Printing a Line of Text 9 System. out. println( "Welcome to Java Programming!" ); – Instructs computer to perform an action • Prints string of characters – String - series characters inside double quotes • White-spaces in strings are not ignored by compiler – System. out • Standard output object • Print to command window (i. e. , MS-DOS prompt) – Method System. out. println • Displays line of text • Argument inside parenthesis – This line known as a statement • Statements must end with semicolon ; 2002 Prentice Hall. All rights reserved.
61 2. 2 A Simple Program: Printing a Line of Text 11 } // end method main – Ends method definition 13 – – – } // end class Welcome 1 Ends class definition Can add comments to keep track of ending braces Lines 8 and 9 could be rewritten as: Remember, compiler ignores comments Comments can start on same line after code 2002 Prentice Hall. All rights reserved.
62 2. 2. 1 Compiling and Executing your First Java Application • Compiling a program – Open a command prompt window, go to directory where program is stored – Type javac Welcome 1. java – If no errors, Welcome 1. class created • Has bytecodes that represent application • Bytecodes passed to Java interpreter 2002 Prentice Hall. All rights reserved.
63 2. 2. 1 Compiling and Executing your First Java Application • Executing a program – Type java Welcome 1 • Interpreter loads. class file for class Welcome 1 • . class extension omitted from command – Interpreter calls method main Fig. 2. 2 Executing Welcome 1 in a Microsoft Windows 2000 Command Prompt. 2002 Prentice Hall. All rights reserved.
64 2. 3 Modifying Our First Java Program • Modify example in Fig. 2. 1 to print same contents using different code 2002 Prentice Hall. All rights reserved.
65 2. 3. 1 Displaying a Single Text with Multiple Statements • Modifying programs – Welcome 2. java (Fig. 2. 3) produces same output as Welcome 1. java (Fig. 2. 1) – Using different code 10 9 System. out. print( "Welcome to " ); System. out. println( "Java Programming!" ); – Line 9 displays “Welcome to ” with cursor remaining on printed line – Line 10 displays “Java Programming! ” on same line with cursor on next line 2002 Prentice Hall. All rights reserved.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 // Fig. 2. 3: Welcome 2. java // Printing a line of text with multiple statements. public class Welcome 2 { Welcome 2. java // main method begins execution of Java application public static void main( String args[] ) { System. out. print( "Welcome to " ); System. out. println( "Java Programming!" ); } } Outline // end method main 1. Comments 2. Blank line 3. Begin class Welcome 2 // end class Welcome 2 System. out. print keeps the cursor on the same line, so System. out. println continues on the same line. 3. 1 Method main 4. Method System. out. print 4. 1 Method System. out. println 5. end main, Welcome 2 Program Output Welcome to Java Programming! 2002 Prentice Hall. All rights reserved. 66
2. 3. 2 Displaying Multiple Lines of Text with a Single Statement • Newline characters (n) – Interpreted as “special characters” by methods System. out. print and System. out. println – Indicates cursor should be on next line – Welcome 3. java (Fig. 2. 4) 9 System. out. println( "Welcomenton. Javan. Programming!" ); – Line breaks at n • Usage – Can use in System. out. println or System. out. print to create new lines • System. out. println( "Welcomenton. Javan. Programming!" ); 2002 Prentice Hall. All rights reserved. 67
1 2 3 4 5 6 7 8 9 ); 10 11 12 13 // Fig. 2. 4: Welcome 3. java // Printing multiple lines of text with a single statement. public class Welcome 1 { } Welcome 3. java 1. main // main method begins execution of Java application public static void main( String args[] ) { System. out. println( "Welcomenton. Javan. Programming!" } Outline 2. System. out. println (uses n for new line) Program Output // end method main // end class Welcome 3 Welcome to Java Programming! Notice how a new line is output for each n escape sequence. 2002 Prentice Hall. All rights reserved. 68
2. 3. 2 Displaying Multiple Lines of Text with a Single Statement Escape characters – Backslash ( ) – Indicates special characters be output 2002 Prentice Hall. All rights reserved. 69
Displaying Text with printf • Java SE 5. 0 added the System. out. printf method for displaying formatted data—the` f ‘ in the name printf stands for “formatted. ” below code outputs the strings "Welcome to“ and "Java Programming!" with System. out. printf ( "%sn", "Welcome to", "Java Programming!" ); • Method printf’s first argument is a format string that may consist of fixed text and format specifiers. public class Welcome 4 { public static void main( String args[] ) { System. out. printf( "%sn", "Welcome to", "Java Programming!" ); } } Output: Welcome to Java Programming!
Another Java Application: Adding Integers • Application reads (or inputs) two integers (whole numbers, like – 22, 7, 0 and 1024) typed by a user at the keyboard, computes the sum of the values and displays the result. import java. util. Scanner; // program uses class declaration • Scanner is an import declaration that helps the compiler locate a class that is used in this program Scanner input = new Scanner( System. in ); is a variable declaration statement (also called a declaration) that specifies the name (input) and type (Scanner) of a variable that is used in this program. • A Scanner enables a program to read data • new Scanner( System. in ) expression creates a Scanner object that reads data typed by the user at the keyboard. • standard input object, System. in, enables Java applications to read information typed by the user.
Memory Concepts Variable names such as number 1, number 2 and sum actually correspond to locations in the computer’s memory. Every variable has a name, a type, a size and a value. • In the addition program, when the following statement executes number 1 = input. next. Int(); // read first number from user • the number typed by the user is placed into a memory location to which the compiler assigned the name number 1. • Suppose that the user enters 45. The computer places that integer value into location number 1. Whenever a value is placed in a memory location, the value replaces the previous value in that location. The previous value is lost.
Arithmetic • Most programs perform arithmetic calculations. Arithmetic Expressions in Straight-Line Form • Arithmetic expressions in Java must be written in straight-line form to facilitate entering programs into the computer. Thus, expressions such as “a divided by b” must be written as a / b, so that all constants, variables and operators appear in a straight line. Parentheses for Grouping Subexpressions • Parentheses are used to group terms in Java expressions in the same manner as in algebraic expressions. For example, to multiply a times the quantity b + c, we write a * ( b + c ) • If an expression contains nested parentheses, such as ( ( a + b ) * c ) • the expression in the innermost set of parentheses (a + b in this case) is evaluated first.
Rules of Operator Precedence • Java applies the operators in arithmetic expressions in a precise sequence determined by the following rules of operator precedence, which are generally the same as those followed in algebra: 1. Multiplication, division and remainder operations are applied first. If an expression contains several such operations, the operators are applied from left to right. Multiplication, division and remainder operators have the same level of precedence. 2. Addition and subtraction operations are applied next. If an expression contains several such operations, the operators are applied from left to right. Addition and subtraction operators have the same level of precedence. Sample Algebraic and Java Expressions The following is an example of an arithmetic mean (average) of five terms: • Algebra: a+b+c+d+e m = ------------- 5 • Java: m = ( a + b + c + d + e ) / 5;
Decision Making: Equality and Relational Operators • A condition is an expression that can be either true or false. • Conditions in if statements can be formed by using the equality operators (== and !=) and relational operators (>, <, >= and <=) summarized in Fig. • The equality operators associate from left to right. The relational operators all have the same level of precedence and also associate from left to right.
- Slides: 82