java programming basics

Upload: chloe8hauxwell

Post on 12-Oct-2015

38 views

Category:

Documents


2 download

DESCRIPTION

This is an introduction to program, particularly those that are object oriented.

TRANSCRIPT

PowerPoint Presentation

Chapter 1. Introduction to programming and the Java languageWhat is Programming?Basic Computer ConceptsData RepresentationIntroduction to Programming LanguagesIntroduction to ProgrammingProgramming BasicsProgram Design with PseudocodeDeveloping a Java Application

What is Programming?Creating an application such as a ticketing kiosk, a game, a restaurant ordering system or another business application. Programming is a scienceMany techniques have been developed for accomplishing basic programming tasksSoftware engineering practices insure that the program is correct and maintainableProgramming is also creativeWe get to solve problemsBasic Computer ConceptsHardwareCentral Processing UnitMemory and Storage DevicesOperating SystemsApplication SoftwareComputer Networks and the InternetTypical Computer HardwareCPUexecutes the instructions of the programHard disk and CD-ROMstore instructions and data so program can be loaded into memory and executedMain memorystores the program instructions and data while executingKeyboard and mouseused for data inputMonitorused to display output from a programOther accessories, such as a printerA Typical Design of a Personal Computer

Central Processing Unit (CPU)Arithmetic Logic Unitperforms integer arithmetic and logical operationsFloating-point Unitperforms floating-point operationsHardware registersstore data and memory addressesInstruction Pointerkeeps track of next instruction to executeExamples of CPUs: Intel Pentium dual-core E5400, Oracle Sun SPARC, Hewlett-Packard PA-RISC, IBM POWER processorCPU InstructionsMove data from one location to anotherPerform a calculationCompare dataChange the sequence of instructions to execute (the flow of control)CPU SpeedRated in MHz or GHzIn one clock cycle, a CPUfetches an instruction from memory,decodes the instruction, orexecutes the instructionPipelining allows overlap of operations to improve performance3.4-Ghz CPU can execute 3.4 billion instructions per second

Memory or Storage DevicesMemory consists of cells that hold one bit.A bit's value can be 0 or 1A byte is 8 binary digits (bits)Storage capacity is expressed as:Kilobytes (1,024 bytes)Megabytes (1,048,576 bytes)Gigabytes (1,073,741,824 bytes)Terabytes ( 1.09951 x 1012 bytes)Operating System (OS) SoftwareOS boots when computer is turned on, and runs continuouslyControls the peripheral devices (disks, keyboard, mouse, etc.)Supports multitasking (multiple programs executing simultaneously)Allocates memory to each programPrevents one program from damaging another programExamples: Microsoft Windows, Linux, MacOS

Application SoftwareWritten to perform specific tasksRuns "on top of" the operating systemExamples: word processor, spreadsheet, database management system, games, Internet browser, etc.Computer NetworksNetworks connect two or more computers so they can share files or devicesLocal Area Network (LAN)computers located geographically close to one anotherServers provide servicesaccess to databasedownloading of filesemail deliveryClients use these services.Most desktop computers are clients.The InternetA network of networksEvolved from the ARPANET military research projectWeb servers deliver Internet content (web pages) to clients via a browser.Web pages are identified using a URL (Uniform Resource Locator)Domain Name System (DNS) Serverstranslate a URL to an Internet Protocol (IP) addressData Representation Binary NumbersExpressed in base 2 system (two digits are 0 and 1)Hexadecimal NumbersBase-16 system used as shorthand for representing binary numbersThe Unicode Character SetUsed to represent charactersBinary Equivalents of Decimal Numbers Decimal Binary Equivalent 000001000120010 3001140100 50101601007011181000Powers of 2 Decimal Decimal20 1 28 25621 2 29 51222 4 210 1,02423 8 211 2,04824 16 212 4,09625 32 213 8,19226 64 214 16,38427 128 215 32,768Decimal (base 10) numbersA decimal number can be represented as the sum of powers of 10 (the base) with coefficients in the base 10 alphabet (0 - 9)

For example:2485 = 2 * 103 + 4 * 102 + 8 * 101+ 5 * 1002485 = 2 * 1000 + 4 * 100 + 8 * 10 + 5 * 12485 = 2000 + 400 + 80 + 5

Converting From Decimal to BinaryJust as a decimal number can be represented as a sum of powers of 10 (the base) with coefficients in the base 10 alphabet (0 to 9)A decimal number can be represented as the sum of powers of 2 (the base of the binary system) with coefficients in the base 2 alphabet (0 and 1) So we need an algorithm to do thatConverting From Decimal to BinaryFind the largest power of 2 that is smaller than or equal to the decimal numberSubtract that number from the decimal numberInsert 1 in the binary number for the position equivalent to that power of 2Repeat 1 - 3, until you reach 0Example: convert 359 to binaryLargest power of 2 that is smaller than 359 is 256 (28)359 - 256 = 103 so 359 = 28 * 1 + 103Largest power of 2 that is smaller than 103 is 64 (26)103 - 64 = 39 so 359 = 28 * 1 + 26 * 1 + 39 (continued on next slide)Example: convert 359 to binaryLargest power of 2 that is smaller than 39 is 32 (25)39 - 32 = 7 so 359 = 28*1 + 26*1 + 25*1 + 7Largest power of 2 that is smaller than 7 is 4 (22)7 - 4 = 3 so 359 = 28 * 1 + 26 * 1 + 25 * 1 + 22 * 1 + 3(continued on next slide)

Example: convert 359 to binaryLargest power of 2 that is smaller than 3 is 2 (21)3 - 2 = 1 so 359 = 28 * 1 + 26 * 1 + 25 * 1 + 22 * 1 + 21 * 1 + 1Largest power of 2 that is smaller than or equal to 1 is 1 (20)1 - 1 = 0, so we are finished

Our ResultsInsert a coefficient of 0 for any missing powers of 2Thus, 359 = 28*1 + 27*0 + 26*1 + 25*1 + 24*0 + 23*0 + 22*1 + 21*1 + 20*1

Removing powers of 2, we get: 1 0 1 1 0 0 1 1 1or 1 0110 0111

Hexadecimal NumbersBase-16 number systemUses digits 0 - 9 and letters A FFor example: C in hex represents 12 in decimalOne hexadecimal digit can express decimal values from 0 to 15 Thus, one hexadecimal digit can represent 4 bitsHexadecimal - Binary EquivalentsHex Binary Hex Binary 0 0000 8 1000 1 0001 9 1001 2 0010 A 1010 3 0011 B 1011 4 0100 C 1100 5 0101 D 1101 6 0110 E 1110 7 0111 F 1111

ExamplesBinary number: 0001 1010 1111 1001Hex equivalent: 1 A F 9

Binary number: 1011 0011 1011 1110Hex equivalent: B 3 B E The Unicode Character SetEach character is stored as 16-bitsMaximum number of characters that can be represented: 65,536 (216) ASCII character set (used by many programming languages) stores each character as 7 bits (maximum number of characters is 128). For compatibility, first 128 characters of Unicode set represent the ASCII characters

Some Unicode CharactersCharacter Decimal Value Hex Value *42002A 1490031 2 500032 A650041 B 660042 a 970061 b980062 } 125007DProgramming LanguagesMachine languageAssembly languageHigh-level languagesMachine and Assembly LanguagesMachine languageWritten using CPU instruction setDifficult to write and not portableAssembly languageWritten using mnemonics for instructions and symbolic names for variablesAssembler converts code to machine languageEasier to write, but still not portableHigh-Level LanguagesExamples: Fortran, COBOL, Perl, Objective C, C++, PHP, Python, and JavaHighly symbolicPortable among CPU architecturesLanguages can be designed for specific uses:Perl, PHP, and Python: Internet applicationsFortran: scientific applicationsCOBOL: business applications

High-Level LanguagesCompiledCompiler converts source code (instructions) into machine language, then program is executedInterpretedInterpreter converts instructions into machine language at run time as instructions are executed Usually executes more slowly than compiled program

JavaCombination of compiler and interpreterCompiler converts source code into byte codes (an instruction set for a virtual, machine-independent processor) At run time, the Java Virtual Machine (JVM) interprets the byte codes and converts them into the machine language for the platform on which the program is running.Object-Oriented Programming (OOP)Class tool for encapsulating data and operations (methods) into one unitdefines a template, or model, for creating and manipulating objectsObjectsdata created using the class and its methodsan object is an instance of the classcreating an object is called instantiation OOP Advantage: ReuseWell-written classes can be reused in new applicationsShortens development time because programmers don't need to write that codePrograms are more robust because the class code is already tested The Java LanguageCreated by Sun Microsystems in 1995 (Oracle Corp. bought Sun in 2010)Syntax is based on C++Object-orientedSupports Internet applicationsProvides extensive library of classesIs portable among platformsHas built-in networkingJava ProgramsAppletsSmall programs designed to add interactivity to websitesDownloaded with the web page and launched by an Internet browserServletsRun by web server on the serverTypically generate web content ApplicationsPrograms that run standalone on a clientAn Introduction to ProgrammingProgramming BasicsProgram Design with PseudocodeDeveloping a Java ApplicationProgramming BasicsProgramming is translating a problem into ordered steps consisting of operations a computer can perform:InputPerform calculationsCompare valuesMove dataOutput The order of execution of instructions is called flow of control Program Design with PseudocodePronounced sue-dough-codeEnglish-like language for specifying the design of a programProgrammers can concentrate on design of program without worrying about Java language rules (syntax)Programmers then convert pseudocode into Java codeFour Types of Flow of ControlSequential ProcessingExecute instructions in orderMethod CallJump to code in method, then returnSelectionChoose code to execute based on data valueLooping or IterationRepeat operations for multiple data valuesSequential ProcessingThe pseudocode for calculating the sum of two numbers would look like this:read first numberread second numberset total to (first number + second number) output total

Method CallCalling the method executes the methodMethods can take arguments (data to use) and return valuesHere is pseudocode for calculating the square root of an integer: read an integer call the square root method, passing the integer and receiving the square root output the square rootSelectionThe pseudocode for determining if a number is positive or negative is:

read a numberif the number is greater than or equal to 0 write "Number is positive." else write "Number is negative." LoopingThe pseudocode for finding the sum of a set of numbers is:

set total to 0 read a number while there was a number to read, add number to total read the next number write totalDeveloping a Java ApplicationWrite the source codeUsing an Integrated Development Environment (IDE) or text editorSave in a .java file Compile the source code: javac ClassName.javaThe compiler creates a .class fileExecute the application: java ClassNameThe Java Virtual Machine runs the codeA First Application 1 // First program in Java 2 // FirstProgram.java 3 4 public class FirstProgram 5 { 6 public static void main( String [] args ) 7 { 8 System.out.println( "Programming is not " 9 + " a spectator sport!" );10 System.exit( 0 ); 11 }12 }

Java is case-sensitive. The source file must be saved with the same name as the class name with a .java extension. The class name and the source filename must match exactly, including capitalization.

Common Error TrapTypes of Program ErrorsCompiler errorsFound by the compiler. Usually caused by incorrect syntax or spellingRun-time errorsReported by the JVMUsually caused by incorrect use of prewritten classes or invalid dataLogic errorsFound by testing the programIncorrect program design or incorrect execution of the design