JAVA - asdfasdf PDF

Title JAVA - asdfasdf
Author David Nguyen
Course Linear Algebra for cse
Institution The University of Texas at Arlington
Pages 42
File Size 1.4 MB
File Type PDF
Total Downloads 84
Total Views 123

Summary

asdfasdf...


Description

CHAPTER 2: FUNDAMENTAL DATA TYPES INTRODUCTION When your program executes computations and receive data you’ll want to store the values so you can use them later. In Java, variables are used to store values. variable: a storage location with a name How that data is stored and associated with a variable is called variable declaration, where a variable is assigned a type and sometimes a value. Variable Declaration Syntax: typeName variableName = value; Example: int secondsPassed = 38; When variables are declared they are usually initialized, or given a specified initial value. There are several data types: numbers, text strings, files, dates, etc. The variable type must be specified when a variable is declared.

NUMBER TYPES There are several different types of numbers in Java. The two primary types are integers (int) and floatingpoint (double). Integer types denote whole numbers without the fraction portion.  Integers can be positive, negative, and zero.  If initializing or assigning a floating-point number to an int type variable, the number is truncated to include only the whole number portion and ignores the fractional part. Example: int numberOfVotes = 3.567; //The value stored in numberOfVotes is 3. Floating-point types denote decimal numbers. In Java, the type double is commonly used.  Floating-point numbers can be positive, negative, and zero. Example: double numberOfVotes = 3.567; //The value stored in numberOfVotes is 3.567. 

If initializing or assigning an integer number to a double type variable, the number is appended with a decimal and zero. Example: double numberOfVotes = 3; //The value stored in numberOfVotes is 3.0.

VARIABLE NAMES When declaring variables, it is good practice to pick a name that explains the variable’s purpose.  It’s easier to understand the purpose of the variable name “hypotenuse” rather than the variable name “c”. Variable Naming Rules: ☐ MUST start with a letter or underscore character. Following characters MUST be letters, numbers, or underscores. ☐ CANNOT use symbols such as “?” or “%”. Spaces are also NOT permitted.  You can use uppercase letters to denote word boundaries. Example:

homeworkAssignment

This is called camel case. It is typically used in hashtags on Twitter or other social media platforms. ☐ Are CaSE SeNsiTivE.  firstName and firstname refer to different variables. ☐ CANNOT be reserved words, or words reserved exclusively for the special Java meanings. 

Example:

double or class

It is programming convention that variables names start with a lowercase letter and class names start with an uppercase letter. firstName  variable

Example:

StudentGrades  class

ASSIGNMENT STATEMENT Used to place a new value into a variable. Example:

firstName = “Sarah”;

The left contains the variable name, the right contains the value or expression. That value is stored overwriting the variable’s previous contents. Example:

REMEMBER:

int numberOfStudents = 40;  declaration … numberOfStudents = 50;  assignment

Variables have to be declared BEFORE they can be assigned. The assignment operator (=) DOES NOT mean equality. It is an instruction to do something, typically place a value into a variable.

Assignment Syntax: variableName = value; Example:

int numberOfGuesses = 5;

int wrongGuesses = 3; numberOfGuesses = numberOfGuesses – wrongGuesses;

CONSTANTS When a variable is defined with the reserved word final, the value can never change. Constants are normally written in all capital letters to visually distinguish them from regular variables. Example:

final int SECONDS_IN_MINUTE = 60;

Using constants is a good way to explain the use of number literals rather than just using the number. Example:

SECONDS_IN_MINUTE vs. 60

Constant Syntax: final typeName variableName = value; Example:

final double CAN_VOLUME = 0.355;

COMMENTS As programs become more complex, comments should be used to explain rationale and purpose of the program for human readers. Example:

final double CAN_VOLUME = 0.355; //The number of liters in a 12 oz. can.

Comments are denoted by the delimiter “//”. The compiler does not process comments at all. It ignores the everything from a “//” delimiter to the end of the line. “//” is used for short comments. For longer comments, enclose the comment between “ /*” and “*/” delimiters. The compiler ignores everything between them. If a comment explains the purpose of the program use the “/**” delimiter rather than “/*”. This is for tools that analyze source code files that rely on this convention.

ARITHMETIC expression: the combination of variables, literals, operators, and/or method calls. Example: Does a + b / 2 equal ( a + b ) / 2 ? The order of operations applies when expressions are computed just like in regular algebraic notation. Order of Operations: P – Parentheses E – Exponents M – Multiplication D – Division

A – Addition S - Subtraction

INCREMENT & DECREMENT Changing a variable by adding or subtracting one (1) is so common in that there is a special shorthand for it. ++  operator increments a variable counter++; //Adds 1 to the value of counter.

Example:

- -  operator decrements a variable counter--; //Subtracts 1 to the value of counter.

Example:

INTEGER DIVISION & REMAINDER Division works as expected as long as one of the numbers involved is a floating-point number. Example:

19 / 4.0 = 19.0 / 4 = 19.0 / 4.0 = 4.75

However, if all numbers are all integers the result will be an integer with the remainder discarded. Example:

19 / 4 = 4

If you are interested in the remainder only, then use the modulus (%) operator. (Also called “modulo” or “mod”.)

POWERS & ROOTS There are no symbols for powers and roots in Java. In order to compute them, you must call methods. Square Root  Math.sqrt() Example:

√x  Math.sqrt(x)

Power  Math.pow() Example:

xn  Math.pow(x,n)

There are several other Math methods that can be used in Java. (See Table 6 on pp. 43-44.)

CONVERTING FLOATING-PO INT NUMBERS TO INTEGERS Sometimes you need to convert a number of type double to int. Converting from one primitive data type to another is called casting. It is an error to assign a floating-point value to and integer. Example:

double totalPrice = cartSum(1 + taxRate);

int dollarsRemaining = dollarsAvailable – totalPrice; You can use the cast operator to convert the floating-point value to an integer. You can also use the cast operator to cast an expression if the result needs to be an integer. Cast Syntax: (typeName) expression Example:

int dollarsRemaining = dollarsAvailable – (int) totalPrice; int balance = (int) (total * 100);

NOTE: Discarding the fraction portion may not always be best. Sometimes it may be most appropriate to round before casting. You can use Math.round(). However, this method returns a long integer type, since int cannot store large floating-point numbers. Example:

long rounded = Math.round(balance); //If balance is $13.75 the it is rounded to $14.

If you know the value can be stored on an int and does not require a long type, you can use a cast. Example:

int rounded = (int) Math.round(balance);

Exercise: 1. Analyze the code snippet below. int courseAverage = 93; int assignment1 = 15; //Variable needs to be declared & initialized int assignmentTotal = 90; //Variable needs to be declared & initialized assignmentTotal = assignmentTotal + assignment1; int homework1 = 85; //Variable must be declared int homework2 = “96”; //Cannot save string value as an Integer int quiz4; //Bad coding practice. Variable need to be initialized. double overallAverage, cse1310Average; //Bad coding practice. Variable need to be initialized. double overallAverage = 1, cse1310Average = 3; System.out.println(homework1); System.out.println(assignmentTotal); 2. Write a sample program that finds the average monthly expenses for a group of roommates. Tom, Sara, Nick, and Janet had the following expenses for the month of September: Rent:

$1596.11

Water:

$47.33

Gas:

$69.78

Cable:

$123.47

$69.98

Internet:

a. What would be the average cost if they added a new roommate? b. What would the cost be if the four roommates decided to get phone service for $38.76 per month?

READING INPUT In order to get information from the user, the program should first ask the user for input. This message requesting input from the user is called a prompt. To display a prompt to the user, you can use a print method. print is often preferred over println because you may prefer the user’s input appear on the same line as the prompt. Example: REMEMBER:

System.out.print( “What is your name?“ );

When using the print method, you must add spaces before and/or after the first/last characters in you printed message.

To read the user’s input you have to use a class called Scanner. Example:

Scanner input = new Scanner(System.in);

Before the Scanner class can be used, it must be imported from its package. package: a collection of classes with a related purpose. //Math is a package. Scanner class belongs to the java.util package. In order to import the Scanner class, the import statement must be located outside of the class method in your program, typically at the top of program code. Scanner Import Syntax: import java.util.Scanner;

Once you have imported the Scanner class, you can also use additional methods found with that class. nextInt()  reads integers nextDouble()  reads doubles next()  reads strings

FORMATTED OUTPUT You can control how the output looks. For example, you may want to specify the number of decimal places that prints or the spacing of the output. Format specifiers exist to give the programmer some control over how the output looks. justification: the alignment of the text when printed, either left (negative) or right (positive) aligned. width: the number of spaces the content should consume, denoted by numeric value that precedes the format specifier.

precision: the number of digits to display after the decimal in floating-point numbers, denoted by the numeric value that succeeds the decimal point (.).

Format Specifiers: %d



integers

+/-



justification

%f



floating-point

#



width

%s



strings

.



precision

To use these format specifiers, you must use a special print method called printf. You can also use the printf method to organize output into neat columns. Example:

NOTE:

int numerator = 22; int denominator = 7; double pi = (double) numerator / (double) denominator; System.out.printf(“Pi is %5d divided by %-3d or %8.2f for short.”, numerator, denominator, pi); “Pi is _ _ _22 divided by 7_ _ or _ _ _ _ 3.14 for short”

The printf method does not start a new line after the output is printed. This can be done by adding System.out.println() on a separate line for now.

Exercise: Write a program that asks the user for the name and price of five items and the prints the items, prices, the total in columnar format. Write a final print statement that calculates the average price of all items entered by the user. The average price should be right justified, with a width of 12 and a precision of 4.

STRINGS Most programs process text, not numbers. Text consists of characters, which can be letters, numbers, punctuation, spaces, etc. string: a sequence of characters Example:

“cheese”



a sequence of characters

STRING TYPE To declare a string variable: String month = “September”;

You can also find the length of a string by using the length() method.

int monthLength = month.length(); //monthLength equals 9

Example:

The length method returns the number of characters in the string. A string with a length of zero (0) is called an empty string. This means that the string contains no characters and is written as “”.

CONCATENATION Just like with integers and floating-point numbers, strings have operators also. One operator is the “ +” sign or concatenation. concatenation: to combine into one Example:

String name = “XBOX”; int version = 360; String console = name + version; System.out.println(console);

Concatenation also reduces the number of print statements. Example:

int age = 6; System.out.print(“My boxer, Kobe, is “); System.out.println(age); can be reduced to… System.out.println(“My boxer, Kobe, is “ + age);

STRING INPUT In order to read a string from the console (user input), use the next() method located in the Scanner class, which is part of the java.util.Scanner package. Example:

System.out.print(“Please enter your name: “); //Morty String name = in.next(); String fullName – in.nextLine(); //for full name

If the user input contains a space the next() method stores the first sequence of characters before the space. The second sequence of characters can be captured by calling the next() method again. Example:

System.out.print(“Please enter your name: “); //Eric Cartman String firstName = in.next(); //Stores “Eric” in firstName String lastName = in.next(); //Stores “Cartman” in lastName

ESCAPE SEQUENCES Sometimes you want to include characters like quotation marks (“) or backslashes (\) in your output. In order to accomplish this, precede the character with a backslash. Example:

String phrase = “Nina said, \”Hello\”.”;

To include a backslash in a string precede it with the escape character (\\).

Another common escape sequence is \n, which is called a newline character. A newline character causes the start of a new line (or enter) on the display. Example:

System.out.print(“*\n**\n***\n”); .Output= * ** ***

STRINGS & CHARACTERS Strings are sequences of Unicode characters. In Java, a character is a value of type char. Characters have numeric values, which can be found in Appendix A. Characters are denoted by single quotes (‘ ‘) and should not be confused with a string. Example:

char letter = ‘H’; String alpha = “H”;

 

character string

You can use the charAt() method to return a char value from a string. In Java, the first position in a string starts with zero (0) and continues from there. String day = “Wednesday”; char firstLetter = day.charAt(0); //Stores the letter ‘W’ char lastLetter = day.charAt(8); //Stores the letter ‘y’ W is at position 0 and y is at position 8

Example:

SUBSTRINGS Once you have a string you can extract substrings by using the substring() method. Example:

String greeting = “Hello, World!”; String word = greeting.substring(0,5); //Stores the string “Hello” String ending = greeting.substring(7); //Stores the string “World!” //Start at 7 and goes to the end.

If two parameters (or arguments) are used with the substring method, the first parameter indicates the index to start capturing the substring. The second string indicates where to stop capturing characters in the string but does not include the final position. If an end parameter is not given the substring method starts at the designated parameter and continues to the end of the string. Exercise: Chapter 2 Review and Programming Exercises

CHAPTER 3: DECISIONS IF-ELSE STATEMENT The if statement is used to implement a decision when a condition is fulfilled. Once the condition is fulfilled, a set of statements is executed. Otherwise, another set of statements is executed. if Statement Syntax: if (condition) { //statements to execute }

Example:

int height = 53; if (height < 60) { System.out.println(“You are not tall enough for this ride.”); } else { System.out.println(“You are tall enough of for this ride! ENJOY!”); }

It is useful to align braces to better identify brace pairs. NOTE:

The else statement is not required when using the if statement. However, in order to use the else statement, the if statement is required.

Height < 60

You are not tall enough.

You are tall enough.

Height < 60

You are not tall enough.

COMPARING NUMBERS & STRINGS Java has six relational operators: >



Greater than

>=



Greater than or equal to

<



Less than

5 && x < 12 ) { System.out.println( “Success” ); } else if ( x >= 12 || x = 100);

Knowing when to use the appropriate loop is helpful in ensuring your program executes as intended. Loop Usage: while loop for loop  do loop 

 When the number of iterations needed is unknown and/or will vary. When the number of iterations needed is known or can be derived. When the condition value needs to be obtained before it is checked or when the input needs to be validated for correctness.

HAND TRACING To better understand the execution of the loop it is a good practice to hand trace to ensure the loop is behaving as expected. How to Hand Trace Loops: ☐ Create a column for the counter (if needed). ☐ Create a column for variable(s) being manipulated during loop execution.

Example:

int count = 0; while (count < 5) { System.out.println(count); count++; }

Hand Trace: COUNT 0 1 2 3 4 5

OUTPUT 0 1 2 3 4 - Stops executing since condition is false (5 is not less than 5)

CHAPTER 5: METHODS METHODS AS A BLACKBOX When writing programs methods enable programmers the ability to create and reuse a portion of code that performs a particular function. method: a sequence of instruction with a name Method Call Example: MethodName(arg1, arg2) MethodName(arg1) MethodName() Example: Math.pow(3, 2); Values, or arguments, are sent, or passed to the method. Results are produced, or returned, by the method. Results that are returned MUST be stored to a variable of the same type or used in some capacity.

IMPLEMENTING METHODS Methods consist of: 1. Header – method’s declaration. Example:

public static double areaOfSquare( double side ) //Method named areaOfSquare

2. Body – set of instructions for a method to compute. Example:

double area = side * side; //Computes area double area = Math.pow(side, 2); //Computes area using a Math.pow method

3. Return – sends results of the method back to the caller. Example:

return area; //Returns calculated value for area back to where it was called.

The return type MUST be of the same type as the method, otherwise an error will occur. Method Syntax: public static returnType methodName( parameterType parameterName, …) { //method body } Example:

public static double areaOfSquare( double side ){ double area = side * side; return area; }

PARAMETER PASSING When creating methods, values can be passed to the method to be used inside. These passed values are referred to as parameters and are stored in variables that can be used in the method’s body. parameter: the values supplied to the method when it is called. Example:

double solution = areaOfSquare( 4.2 ); //Parameter value of 4.2 is provided to the areaOfSquare met...


Similar Free PDFs