850 likes | 889 Views
Chapter 2: Java Fundamentals. Starting Out with Java From Control Structures through Data Structures 1e by Tony Gaddis and Godfrey Muganda. To understand: the meaning and placement of the parts of a simple Java program statements that display console output the use of variables
E N D
Chapter 2: Java Fundamentals Starting Out with JavaFrom Control Structures through Data Structures 1e by Tony Gaddis and Godfrey Muganda
To understand: the meaning and placement of the parts of a simple Java program statements that display console output the use of variables the primitive data types the use of literals and the different types of literals the arithmetic operators and the order of operations how to use parentheses to group parts of a mathematical expression Introduction To Computers And JavaChapter Objectives
To understand: statements using combined assignment operators named constants using the final key word String objects primitive data type variables and a reference variables the concept of scope single-line and multi-line comments the uses of indentations, spaces, and blank lines in a program to reflect a programming style the Keyboard class provided with this book to read keyboard input. Introduction To Computers And JavaChapter Objectives
Chapter Topics Chapter 2 discusses the following main topics: • The Parts of a Java Program • The print and println Methods, and the Java API • Variables and Literals • Primitive Data Types • Arithmetic Operators • Combined Assignment Operators
Chapter Topics (2) • Creating named constants with final • The String class • Scope • Comments • Programming style • Using the Scanner class for input • Dialog boxes
Parts of a Java Program • A Java source code file contains one or more Java classes. • If more than one class is in a source code file, only one of them may be public. • The public class and the filename of the source code file must match. ex: A class named Simple must be in a file named Simple.java • Each Java class can be separated into parts.
Parts of a Java Program • Example: Simple.java • To compile the example: • javac –source 1.5 Simple.java • Notice the .java file extension is needed. • This will result in a file named Simple.class being created. • To run the example: • java Simple • Notice there is no file extension here. • The java command assumes the extension is .class.
Analyzing The Example This is a Java comment. It is ignored by the compiler. // This is a simple Java program. This is the class headerfor the class Simple public class Simple{} This area is the body of the class Simple. All of the data and methods for this classwill be between these curly braces.
Analyzing The Example public class Simple{} public static void main(String [] args){ } This is the method header for the main method. The main method is where a Java application begins. // This is a simple Java program. This area is the body of the main method. All of the actions to be completed during the main method will be between these curly braces.
Analyzing The Example public class Simple{} public static void main(String [] args){ System.out.println("Programming is great fun!"); } // This is a simple Java program. This is the Java Statement that is executed when the program runs.
Parts of a Java Program • Comments • The line is ignored by the compiler. • The comment in the example is a single-line comment. • Class Header • The class header tells the compiler things about the class such as what other classes can use it (public) and that it is a Java class (class), and the name of that class (Simple). • Curly Braces • When associated with the class header, they define the scope of the class. • When associated with a method, they define the scope of the method.
Parts of a Java Program • Main Method • This line must be exactly as shown in the example (except the args variable name can be programmer defined). • This is the line of code that the java command will run first. • This method starts the Java program. • Every Java application must have a main method. • Java Statements • When the program runs, the statements within the main method will be executed. • Can you see what the line in the example will do?
Java Statements • If we look back at the previous example, we can see that there is only one line that ends with a semi-colon. System.out.println("Programming is great fun!"); • This is because it is the only Java statement in the program. • The rest of the code is either a comment or other Java framework code.
Java Statements • Comments are ignored by the Java compiler so they need no semi-colons. • Other Java code elements that do not need semi colons include: • class headers • Terminated by the code within its curly braces. • method headers • Terminated by the code within its curly braces. • curly braces • Part of framework code that needs no semi-colon termination.
Short Review • Java is a case-sensitive language. • All Java programs must be stored in a file with a .java file extension. • Comments are ignored by the compiler. • A .java file may contain many classes but may only have one public class. • If a .java file has a public class, the class must have the same name as the file.
Short Review • Java applications must have a main method. • For every left brace, or opening brace, there must be a corresponding right brace, or closing brace. • Statements are terminated with semicolons. • Comments, class headers, method headers, and braces are not considered Java statements.
Console Output • The console that starts a Java application is typically known as the standard output device. • The standard input device is typically the keyboard. • Java sends information to the standard output device by using a Java class stored in the standard Java library.
Console Output • Java classes in the standard Java library are accessed using the Java Applications Programming Interface (API). • The standard Java library is commonly referred to as the Java API.
Console Output • The previous example uses the line: System.out.println("Programming is great fun!"); • This line uses the System class from the standard Java library. • The System class contains methods and objects that perform system level tasks. • The out object, a member of the System class, contains the methods print and println.
Console Output • The print and println methods actually perform the task of sending characters to the output device. • The line: System.out.println("Programming is great fun!"); is pronounced: System dot out dot println … • The value inside the parenthesis will be sent to the output device (in this case, a String).
Console Output • The println method places a newline character at the end of whatever is being printed out. • The following lines: System.out.println(“This is being printed out"); System.out.println(“on two separate lines."); Would be printed out on separate lines since the first statement sends a newline command to the screen.
Console Output • The print statement works very similarly to the println statement. • However, the print statement does not put a newline character at the end of the output. • The lines: System.out.print(“These lines will be"); System.out.print(“printed on"); System.out.println(“the same line."); Will output: These lines will beprinted onthe same line. Notice the odd spacing? Why are some words run together?
Console Output • For all of the previous examples, we have been printing out Strings of characters. • Later, we will see that much more can be printed. • There are some special characters that can be put into the output. System.out.print (“This line will have a newline at the end.\n”); • The \n in the String is an escape sequence that represents the newline character. • Escape sequences allow the programmer to print characters that otherwise would be unprintable.
Java Escape Sequences • Even though the escape sequences are comprised of two characters, they are treated by the compiler as a single character. System.out.print("These are our top sellers:\n"); System.out.print("\tComputer games\n\tCoffee\n "); System.out.println("\tAspirin"); Would result in the following output: These are our top seller: Computer games Coffee Asprin • With these escape sequences, complex text output can be achieved.
Variables and Literals • A variable is a named storage location in the computer’s memory. • A literal is a value that is written into the code of a program. • Programmers determine the number and type of variables a program will need. • Variable.java
Variables and Literals The integer 5 will be printed out here. Notice no quote marks? This line is called a variable declaration. int value; The value 5 is stored in memory. The following line is known as an assignment statement. value = 5; 0x000 0x001 5 0x002 0x003 This is a String literal. It will be printed as is. System.out.print("The value is "); System.out.println(value);
The + Operator • The + operator can be used in two ways. • as a concatenation operator • as an addition operator • If either side of the + operator is a String, the result will be a String. System.out.println(“Hello “ + “World”); System.out.println(“The value is: “ + 5); System.out.println(“The value is: “ + value); System.out.println(“The value is: “ + ‘/n’ + 5);
String Concatenation • Java commands that have String literals must be treated with care. • A String literal value cannot span lines in a Java source code file. System.out.println(“This line is too long and now it has spanned more than one line, which will cause a syntax error to be generated by the compiler.”);
String Concatenation • The String concatenation operator can be used to fix this problem. System.out.println(“These lines are ” +”are now ok and will not ” +”cause the error as before.”); • String concatenation can join various data types. System.out.println(“We can join a string to ” +”a number like this: ” + 5);
String Concatenation • The Concatenation operator can be used to format complex String objects. System.out.println(“The following will be printed ” + ”in a tabbed format: “ + \n\tFirst = “ + 5 * 6 + “,” + “\n\tSecond = “ (6 + 4) + “,” + “\n\tThird = “ + 16.7 + “.”); • Notice that if an addition operation is also needed, it must be put in parenthesis.
Identifiers • Identifiers are programmer-defined names for: • classes • variables • methods • Identifiers may not be any of the Java reserved keywords.
Identifiers • Identifiers must follow certain rules: • An identifier may only contain: • letters a–z or A–Z, • the digits 0–9, • underscores (_), or • the dollar sign ($) • The first character may not be a digit. • Identifiers are case sensitive. • itemsOrdered is not the same as itemsordered. • Identifiers cannot include spaces.
Java Reserved Keywords abstract boolean break byte case catch char class const continue default do double else extends final finally float for goto if implements import instanceof int interface long native new package private protected public return short static strictfp super switch synchronized this throw throws transient try void volatile while
Variable Names • Variable names should be descriptive. • Descriptive names allow the code to be more readable; therefore, the code is more maintainable. • Which of the following is more descriptive? double tr = 0.0725; double salesTaxRate = 0.0725; • Java programs should be self-documenting.
Java Naming Conventions • Variable names should begin with a lower case letter and then switch to title case thereafter: Ex: int caTaxRate • Class names should be all title case. Ex: public class BigLittle • More Java naming conventions can be found at: http://java.sun.com/docs/codeconv/html/CodeConventions.doc8.html • A general rule of thumb about naming variables and classes are that, with some exceptions, their names tend to be nouns or noun phrases.
byte short int long float double boolean char Primitive Data Types • Primitive data types are built into the Java language and are not derived from classes. • There are 8 Java primitive data types.
Variable Declarations • Variable Declarations take the following form: • DataType VariableName; • byte inches; • short month; • int speed; • long timeStamp; • float salesCommission; • double distance;
Integer Data Types • byte, short, int, and long are all integer data types. • They can hold whole numbers such as 5, 10, 23, 89, etc. • Integer data types cannot hold numbers that have a decimal point in them. • Integers embedded into Java source code are called integer literals. • IntegerVariables.java
Floating Point Data Types • Data types that allow fractional values are called floating-point numbers. • 1.7 and -45.316 are floating-point numbers. • In Java there are two data types that can represent floating-point numbers. • float - also called single precision (7 decimal points). • double - also called double precision (15 decimal points).
Floating Point Literals • When floating point numbers are embedded into Java source code they are called floating point literals. • The default type for floating point literals is double. • 29.75, 1.76, and 31.51 are double data types. • Java is a strongly-typed language. • Sale.java
Floating Point Literals • A double value is not compatible with a float variable because of its size and precision. • float number; • number = 23.5; // Error! • Doubles can be forced into a float by appending the letter F or f to the literal. • float number; • number = 23.5F; // This will work.
Floating Point Literals • Literals cannot contain embedded currency symbols or commas. • grossPay = $1,257.00; // ERROR! • grossPay = 1257.00; // Correct. • Floating-point literals can be represented in scientific notation. • 47,281.97 == 4.728197 x 104. • Java uses E notation to represent values in scientific notation. • 4.728197X104 == 4.728197E4.
Scientific and E Notation SunFacts.java
The boolean Data Type • The Java boolean data type can have two possible values. • true • false • The value of a boolean variable may only be copied into a boolean variable. TrueFalse.java
The char Data Type • The Java char data type provides access to single characters. • char literals are enclosed in single quote marks. • ‘a’, ‘Z’, ‘\n’, ‘1’ • Don’t confuse char literals with String literals. • char literals are enclosed in single quotes. • String literals are enclosed in double quotes. Letters.java
Unicode • Internally, characters are stored as numbers. • Character data in Java is stored as Unicode characters. • The Unicode character set can consist of 65536 (216) individual characters. • This means that each character takes up 2 bytes in memory. • The first 256 characters in the Unicode character set are compatible with the ASCII* character set. Letters2.java *American Standard Code for Information Interchange
Unicode 00 65 00 66 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 1 1 1 A B