Chapter 1 Introduction to JAVA. Why Learn JAVA? Java is one of the fastest growing programming...

26
Chapter 1 Chapter 1 Introduction to JAVA Introduction to JAVA

Transcript of Chapter 1 Introduction to JAVA. Why Learn JAVA? Java is one of the fastest growing programming...

Page 1: Chapter 1 Introduction to JAVA. Why Learn JAVA? Java is one of the fastest growing programming language in the world. Java is one of the fastest growing.

Chapter 1Chapter 1

Introduction to JAVAIntroduction to JAVA

Page 2: Chapter 1 Introduction to JAVA. Why Learn JAVA? Java is one of the fastest growing programming language in the world. Java is one of the fastest growing.

Why Learn JAVA?Why Learn JAVA?

Java is one of the fastest growing Java is one of the fastest growing programming language in the world.programming language in the world.

Java is a modern object-oriented Java is a modern object-oriented programming language.programming language.

Java is secure, robust, and portable.Java is secure, robust, and portable.• Enables the construction of virus-free, tamper Enables the construction of virus-free, tamper

free systems (secure)free systems (secure)• Supports the development of programs that do Supports the development of programs that do

not overwrite memory (robust)not overwrite memory (robust)• Yields programs that can be run on different Yields programs that can be run on different

types of computers without change (portable)types of computers without change (portable)

Page 3: Chapter 1 Introduction to JAVA. Why Learn JAVA? Java is one of the fastest growing programming language in the world. Java is one of the fastest growing.

Why Learn JAVA?Why Learn JAVA?

Java supports the use of advanced Java supports the use of advanced programming concepts such as threads.programming concepts such as threads.• ThreadThread – a process that can run – a process that can run

concurrently with other processes.concurrently with other processes. Java bears a superficial resemblance to Java bears a superficial resemblance to

C++, which is currently the world’s C++, which is currently the world’s most popular industrial strength most popular industrial strength programming language.programming language.

Page 4: Chapter 1 Introduction to JAVA. Why Learn JAVA? Java is one of the fastest growing programming language in the world. Java is one of the fastest growing.

The JAVA Virtual MachineThe JAVA Virtual Machine

Compilers usually translate a higher-level Compilers usually translate a higher-level language into the machine language of a language into the machine language of a particular type of computer.particular type of computer.

However, the Java compiler translates Java However, the Java compiler translates Java not into machine language, but into a not into machine language, but into a pseudo-machine language called Java pseudo-machine language called Java byte byte code.code.

Byte codeByte code - is the machine language for an - is the machine language for an imaginary Java computer. To run Java byte imaginary Java computer. To run Java byte code on a particular computer, you must code on a particular computer, you must install a Java virtual machine (JVM) on that install a Java virtual machine (JVM) on that computer.computer.

A JVM is a program that behaves like a A JVM is a program that behaves like a computer. Such a program is computer. Such a program is interpreter.interpreter.

Page 5: Chapter 1 Introduction to JAVA. Why Learn JAVA? Java is one of the fastest growing programming language in the world. Java is one of the fastest growing.

User Interface StylesUser Interface Styles

There are two types of user interfaces a There are two types of user interfaces a programmer can develop.programmer can develop.

Terminal I/O interface – A text based Terminal I/O interface – A text based DOS console window.DOS console window.

Graphical User Interface (GUI) – A Graphical User Interface (GUI) – A windowed based environment with text windowed based environment with text and graphics displayed in the window.and graphics displayed in the window.

We will focus on Terminal I/O in this We will focus on Terminal I/O in this class.class.

Page 6: Chapter 1 Introduction to JAVA. Why Learn JAVA? Java is one of the fastest growing programming language in the world. Java is one of the fastest growing.

JAVA Class LibrariesJAVA Class Libraries

Java ProgramsJava Programs• Classes contain methods, which perform tasksClasses contain methods, which perform tasks• Consist of pieces called classesConsist of pieces called classes

Class librariesClass libraries• Rich collection of predefined classes, which you Rich collection of predefined classes, which you

can usecan use Two parts of learning JavaTwo parts of learning Java

• Learning the language itself, so you can create Learning the language itself, so you can create your own classesyour own classes

• Learning how to use the existing classes in the Learning how to use the existing classes in the librarieslibraries

Page 7: Chapter 1 Introduction to JAVA. Why Learn JAVA? Java is one of the fastest growing programming language in the world. Java is one of the fastest growing.

Basics of a Typical Java Basics of a Typical Java EnvironmentEnvironment

Java SystemsJava Systems• Consist of environment, language, Class librariesConsist of environment, language, Class libraries

Java programs have five phasesJava programs have five phases- Edit - Edit

• Use an editor to type Java programUse an editor to type Java program• Notepad, Jbuilder, Visual J++, Jcreator, BlueJ, EclipseNotepad, Jbuilder, Visual J++, Jcreator, BlueJ, Eclipse• .java extension.java extension

- Compile- Compile• Translates program into bytecodes, understood by Java Translates program into bytecodes, understood by Java

interpreterinterpreter• Creates .class file, containing bytecodes Creates .class file, containing bytecodes

(MyProgram.class)(MyProgram.class)

Page 8: Chapter 1 Introduction to JAVA. Why Learn JAVA? Java is one of the fastest growing programming language in the world. Java is one of the fastest growing.

Basics of a Typical Java Basics of a Typical Java EnvironmentEnvironment

Java programs have five phases (continued)Java programs have five phases (continued)- Loading - Loading

• Class loader transfers .class file into memoryClass loader transfers .class file into memory• Applications - run on user's machineApplications - run on user's machine• Applets - loaded into Web browser, temporaryApplets - loaded into Web browser, temporary

• Classes loaded and executed by interpreter with java Classes loaded and executed by interpreter with java commandcommand

• HTML documents can refer to Java Applets, which are HTML documents can refer to Java Applets, which are loaded into web browsers. loaded into web browsers.

• appletviewer is a minimal browser, can only interpret appletviewer is a minimal browser, can only interpret appletsapplets

Page 9: Chapter 1 Introduction to JAVA. Why Learn JAVA? Java is one of the fastest growing programming language in the world. Java is one of the fastest growing.

Basics of a Typical Java Basics of a Typical Java EnvironmentEnvironment

Java programs have five phases (continued)Java programs have five phases (continued)- Verify- Verify

• Bytecode verifier makes sure bytecodes are valid and do Bytecode verifier makes sure bytecodes are valid and do not violate securitynot violate security

• Java must be secure - Java programs transferred over Java must be secure - Java programs transferred over networks, possible to damage files (viruses)networks, possible to damage files (viruses)

- Execute- Execute• Computer (controlled by CPU) interprets program one Computer (controlled by CPU) interprets program one

bytecode at a timebytecode at a time• Performs actions specified in programPerforms actions specified in program

Program may not work on first tryProgram may not work on first try• Make changes in edit phase and repeatMake changes in edit phase and repeat

Page 10: Chapter 1 Introduction to JAVA. Why Learn JAVA? Java is one of the fastest growing programming language in the world. Java is one of the fastest growing.

Example ProgramExample Program

Java programJava program //Example Program Welcome.java

//A first program in Java

public class Welcome{

public static void main(String [ ] args{

System.out.println(“Welcome to Java Programming!”);}

}

Program OutputProgram OutputWelcome to Java Programming!

Page 11: Chapter 1 Introduction to JAVA. Why Learn JAVA? Java is one of the fastest growing programming language in the world. Java is one of the fastest growing.

Commenting CodeCommenting Code

//Example Program Welcome.java

// indicates the remainder of the line is a // indicates the remainder of the line is a commentcomment

• Comments are ignored by the compilerComments are ignored by the compiler• Use comments to document and describe codeUse comments to document and describe code• Commenting code is GOOD PROGRAMMING Commenting code is GOOD PROGRAMMING

STYLESTYLE Can also use multiple line comments: /* ... */Can also use multiple line comments: /* ... */

ex. ex. /* This is a multiple/* This is a multiple line comment. It canline comment. It can

be split over many lines */be split over many lines */

Page 12: Chapter 1 Introduction to JAVA. Why Learn JAVA? Java is one of the fastest growing programming language in the world. Java is one of the fastest growing.

public class Welcome

{

-Begins a class definition for class -Begins a class definition for class WelcomeWelcome

Every Java program has at least one user-Every Java program has at least one user-defined classdefined class

classclass keyword immediately followed by keyword immediately followed by class nameclass name

• Keyword: words reserved for use by JavaKeyword: words reserved for use by Java Naming classes: capitalize every wordNaming classes: capitalize every word

• SampleClassNameSampleClassName

Beginning a ProgramBeginning a Program

Page 13: Chapter 1 Introduction to JAVA. Why Learn JAVA? Java is one of the fastest growing programming language in the world. Java is one of the fastest growing.

Beginning a ProgramBeginning a Programpublic class Welcome{

Identifier NamesIdentifier Names• Series of characters consisting of letters, Series of characters consisting of letters,

digits, digits, underscores ( _ ) and dollar signs ( $ )underscores ( _ ) and dollar signs ( $ )

• Does not begin with a digitDoes not begin with a digit• Contains no spacesContains no spaces• Examples: Welcome1, $value, _value, button7Examples: Welcome1, $value, _value, button7• 7button is invalid7button is invalid• Case sensitive (capitalization matters) Case sensitive (capitalization matters)

• a1 and A1 are differenta1 and A1 are different

Page 14: Chapter 1 Introduction to JAVA. Why Learn JAVA? Java is one of the fastest growing programming language in the world. Java is one of the fastest growing.

Beginning a ProgramBeginning a Programpublic class Welcome{

Saving filesSaving files• File name is class name with .java extensionFile name is class name with .java extension• Welcome.javaWelcome.java

BracesBraces• Left brace starts every classLeft brace starts every class• Right brace ends every classRight brace ends every class

public static void main(String [] args){

Part of every Java applicationPart of every Java application• Applications begin executing at mainApplications begin executing at main

• Parenthesis indicate main is a methodParenthesis indicate main is a method• Java applications contain one or more methodsJava applications contain one or more methods

Page 15: Chapter 1 Introduction to JAVA. Why Learn JAVA? Java is one of the fastest growing programming language in the world. Java is one of the fastest growing.

A Simple Program: Printing a A Simple Program: Printing a Line of TextLine of Text

public static void main(String [] args){

Exactly one method must be called Exactly one method must be called mainmainMethods can perform tasks and return Methods can perform tasks and return informationinformation

• void means main returns no informationvoid means main returns no information• For now, mimic main's first lineFor now, mimic main's first line

Left brace begins body of method Left brace begins body of method definitiondefinition

Page 16: Chapter 1 Introduction to JAVA. Why Learn JAVA? Java is one of the fastest growing programming language in the world. Java is one of the fastest growing.

A Simple Program: Printing a A Simple Program: Printing a Line of TextLine of Text

System.out.println(“Welcome to Java Programming!”);

Instructs computer to perform an actionInstructs computer to perform an action• Prints string of characters between double quotesPrints string of characters between double quotes

• String - series characters inside double quotesString - series characters inside double quotes• White spaces in strings are not ignored by compilerWhite spaces in strings are not ignored by compiler

System.out - standard output objectSystem.out - standard output object• Allows java to print to command window (i.e., MS-DOS Allows java to print to command window (i.e., MS-DOS

prompt)prompt) Method System.out.println displays a line of Method System.out.println displays a line of

texttext• Argument inside parenthesisArgument inside parenthesis

Entire line known as a statementEntire line known as a statement• All statements must end with a semicolon ;All statements must end with a semicolon ;

Page 17: Chapter 1 Introduction to JAVA. Why Learn JAVA? Java is one of the fastest growing programming language in the world. Java is one of the fastest growing.

A Simple Program: Printing a A Simple Program: Printing a Line of TextLine of Text

}

Ends method definitionEnds method definition

}

Ends class definitionEnds class definition Some programmers add comments to keep Some programmers add comments to keep

track of ending bracestrack of ending braces The last two lines could be rewritten as:The last two lines could be rewritten as:

} //end of method main()} //end of class welcome

Remember that the compiler ignores Remember that the compiler ignores commentscomments

Page 18: Chapter 1 Introduction to JAVA. Why Learn JAVA? Java is one of the fastest growing programming language in the world. Java is one of the fastest growing.

A Simple Program: Printing a A Simple Program: Printing a Line of TextLine of Text

Compiling a programCompiling a program• Click compile button. Located on toolbar by an Click compile button. Located on toolbar by an

upside down arrowupside down arrow• If there are no errors, file Welcome.class is createdIf there are no errors, file Welcome.class is created

• Contains Java bytecodes that represent applicationContains Java bytecodes that represent application• Bytecodes passed to Java interpreterBytecodes passed to Java interpreter

Executing a programExecuting a program• Click Execute button. Located on toolbar by an arrow Click Execute button. Located on toolbar by an arrow

pointing to the right. F5 will also Executepointing to the right. F5 will also Execute• Launches interpreter to load .class file for class WelcomeLaunches interpreter to load .class file for class Welcome• .class extension omitted from command.class extension omitted from command

• Interpreter calls method mainInterpreter calls method main

Page 19: Chapter 1 Introduction to JAVA. Why Learn JAVA? Java is one of the fastest growing programming language in the world. Java is one of the fastest growing.

A Simple Program: Printing a A Simple Program: Printing a Line of TextLine of Text

Other methodsOther methods• System.out.printlnSystem.out.println

• Positions cursor on new line after displaying Positions cursor on new line after displaying argumentargument

• System.out.printSystem.out.print• Keeps cursor on same line after displaying Keeps cursor on same line after displaying

argumentargument

Page 20: Chapter 1 Introduction to JAVA. Why Learn JAVA? Java is one of the fastest growing programming language in the world. Java is one of the fastest growing.

A Simple Program: Printing a Line A Simple Program: Printing a Line of Textof Text// Example Welcome.java

// Printing a line with multiple statementes

public class Welcome{

public static void main(String [ ] args){

System.out.print(“Welcome to “);System.out.println(“Java Programming!”);

}}

Program OutputProgram OutputWelcome to Java Programming!

System.out.print keeps the cursor on the same line, so System.out.println continues on the same line.

Page 21: Chapter 1 Introduction to JAVA. Why Learn JAVA? Java is one of the fastest growing programming language in the world. Java is one of the fastest growing.

A Simple Program: Printing a A Simple Program: Printing a Line of TextLine of Text

Escape charactersEscape characters Backslash ( \ )Backslash ( \ ) Indicates that special characters are to be outputIndicates that special characters are to be output

Backslash combined with a character makes an escape Backslash combined with a character makes an escape sequencesequence

\n - newline\n - newline \t - tab\t - tab

UsageUsage Can use in System.out.println or System.out.print Can use in System.out.println or System.out.print

to create new linesto create new lines System.out.println( "Welcome\nto\nJava\System.out.println( "Welcome\nto\nJava\

nProgramming!" );nProgramming!" );

Page 22: Chapter 1 Introduction to JAVA. Why Learn JAVA? Java is one of the fastest growing programming language in the world. Java is one of the fastest growing.

A Simple Program: Printing a Line A Simple Program: Printing a Line of Textof Text

Notice how a new line is output for each \n escape sequence.

// Example Welcome.java

// Printing multiple lines with a single statement

public class Welcome{

public static void main(String [ ] args){

System.out.println(“Welcome\nto\nJava\nProgramming!”);}

}

Program OutputWelcometoJavaProgramming!

Page 23: Chapter 1 Introduction to JAVA. Why Learn JAVA? Java is one of the fastest growing programming language in the world. Java is one of the fastest growing.

Template for Java FileTemplate for Java File

//Name//Project Name and #//Date

public class Welcome{

public static void main(String [ ] args){ Code that makes your program work}

}

This section contains statements that complete the program.

Page 24: Chapter 1 Introduction to JAVA. Why Learn JAVA? Java is one of the fastest growing programming language in the world. Java is one of the fastest growing.

Programming StyleProgramming Style

One thing to remember when developing One thing to remember when developing applications is that typically programs have a applications is that typically programs have a long life and are usually maintained by many long life and are usually maintained by many people other than their original authors. people other than their original authors. Therefore, the developer should take into Therefore, the developer should take into account the following items:account the following items: LayoutLayout ReadabilityReadability IndentationIndentation Name usageName usage

Page 25: Chapter 1 Introduction to JAVA. Why Learn JAVA? Java is one of the fastest growing programming language in the world. Java is one of the fastest growing.

Example Program with Example Program with ReadabilityReadability

import TerminalIO.KeyboardReader;import TerminalIO.KeyboardReader;

public class Convert public class Convert {{

public static void main(String [] args) public static void main(String [] args) {{

KeyboardReader reader = new KeyboardReader();KeyboardReader reader = new KeyboardReader(); double fahrenheit;double fahrenheit; double celsius;double celsius; System.out.print("Enter degrees Fahrenheit: ");System.out.print("Enter degrees Fahrenheit: "); fahrenheit = reader.readDouble();fahrenheit = reader.readDouble(); celsius = (fahrenheit - 32.0) * 5.0 / 9.0;celsius = (fahrenheit - 32.0) * 5.0 / 9.0; System.out.print("The equivalent in Celsius is ");System.out.print("The equivalent in Celsius is "); System.out.println(celsius);System.out.println(celsius); reader.pause(); reader.pause(); }}}}

Page 26: Chapter 1 Introduction to JAVA. Why Learn JAVA? Java is one of the fastest growing programming language in the world. Java is one of the fastest growing.

Example Program without Example Program without ReadabilityReadability

import TerminalIO.KeyboardReader;import TerminalIO.KeyboardReader;

public class public class Convert {public static Convert {public static

void main(String [] args) {void main(String [] args) { KeyboardReader KeyboardReader reader = new KeyboardReader();doublereader = new KeyboardReader();double fahrenheit;fahrenheit; double celsius;System.out.print("Enter degrees Fahrenheit: ");double celsius;System.out.print("Enter degrees Fahrenheit: "); fahrenheit fahrenheit = = reader.readDouble();reader.readDouble(); celsius = (fahrenheitcelsius = (fahrenheit - 32.0) * 5.0 / 9.0;- 32.0) * 5.0 / 9.0; System.System. out.printout.print("The equivalent in Celsius is ");("The equivalent in Celsius is ");

System.outSystem.out.println(celsius);.println(celsius); reader.reader. pause(); pause(); }}}}