Intro to Java Midterm 1

Pataasin ang iyong marka sa homework at exams ngayon gamit ang Quizwiz!

Mod Operator

%, Gets the remainder from division

Expression

A simple value or a set of operations that produces a value

Operator

A special symbol (like + or *) that is used to indicate an operation to be performed on one or more values. Operands are the values used in the expression.

String objects

A string is an object storing a sequence of text characters String objects have ◦ Fields (or data values): the characters in the string ◦ Methods (or operations): get the length of the string, get a substring, etc Strings in Java are immutable, which means that once they are constructed, their value can never change

String Literals

A string of text surrounded by quotation marks that will send it as output

Class

A unit of code that is the basic building block of Java programs. In Java nothing can exist outside of a class.

Parameters

An actual parameter is a specific value or expression that appears inside parentheses in a method call ex: charAt(3) A formal parameter is a variable that appears inside parentheses in the header of a method. It is used to generalize the method's behavior (ex: int index) A parameter is a special type of variable that allows us to pass information into a method

Statement

An executable snippet of code that represents a complete command Each statement ends with a semicolon

Object

An object stores some data and has methods that on its data. It is a programming entity that contains state (data) and behavior (methods) The objects of a given class are built according to its blueprint The objects of a class are also referred to as instances of the class

for loop

Check if the test is true. If not, stop ◦ Execute the statements ◦ Perform the update for (int i = 0; i < 4; i++) { System.out.println("|"); }

String Concatenation

Combining several strings into a single string, or combining a string with other data into a new, longer string. Ex: System.out.println("Hours in a year = " + hours);

Printf

Syntax: System.out.printf ("format string", <list parameters>); The format string is like a placeholders where the parameters are inserted These placeholders are used instead of + concatenation o %d integer o %f real numbers o %s string Precision: %.Df real number, rounded to D digits after decimal %W.Df real number, W characters wide, D digits after decimal Ex: double gpa = 3.253764 System.out.printf("your GPA is %.1f\n", gpa); Output: your GPA is 3.3 Note: printf does not drop to the next line unless you use \n

Java Import Utilities Syntax

Syntax: import java.util.*; (scanner is in utilities)

Print Statement

System.out.println

Comment

Text that programmers include in a program to explain their code the compiler ignores comments // one line /* multiple lines*/

Precedence

The binding power of an operator, which determines how to group parts of an expression (*,/,%) have higher precedence than (+,-) Arithmetic operators are evaluated from left to right

API of a Class

The methods defined within a class are known as the API of that class ◦ API = application programming interface You can consult the API of an existing class to determine which operation are supported

Methods that Return Values

The return is the result of a method that can be used in an expression in the program A method can return any legal type (int, double, char,...) or any other type. Return values send information out from a method to its caller. Void methods that do not return any value

1 *2 **3 ***4

There is one repeating pattern (stars) in the first output. The number is not a repeating pattern because there is never more than one number on any given output line. Based on the tips/tricks that we've learned we can expect: 1. An outer-most INCREMENTING (because the output line size is getting larger) "for" loop that counts to 4 (number of output lines). 2. A single nested "for" loop for the repeating stars ("*") that uses the value of the outermost loop counter to affect the inner repeating pattern because the number of stars is changing. 3. A print statement after the nested "for" loop to output the numeric. for (int i = 1; i <= 4; i++) { for (int j = 1; j < i; j++) { System.out.print("*"); } System.out.println(i); }

What are an object's methods called?

They are called non-static or instance methods

Cast a value

To convert a double into an int you put the name of the type you want to cast to in parentheses in front of the value you want to cast. ex: (int) 4.75 or (int) (3.4*2.9)

Printf New Line

To get a newline %n is used. Note that the characters are surrounded with double quotes.

Left/Right Justified Printf

To get the left-justified column, you need a percentage symbol, a minus symbol, the number of characters, and then the letter "s" (lowercase). So ''%-15s'' means fifteen characters left-justified. To get a right-justified column the same sequence of characters are used, except for the minus sign.

To know how many characters are in a string

To know how many characters are in s1 you can use the length() method s1.length() System.out.println("Length of s1: " + s1.length());

Method

A program unit that represents a particular action or computation

Declaration

A request to set aside a new variable with a given name and type. Of the form <type> <name>;

Tricks for Nest for Loops

1. The outermost loop typically controls the number of lines printed. 2. Nested loops typically control repeating patterns within each individual output line.

How to call an instance method (object's method) Syntax

<variable>.<method name>(<parameters>);

Static Method

A block of Java statements that is given a name With the form public static void <name>( ) { <statment>; } Notice no ; after the name

Method Call

A command to execute another method, which causes all of the statements inside that method to be executed.

Multiple Parameters

A method can accept multiple parameters (separated by ",") Strings can also be parameters sent

Identifier

A name given to an entity in a program, such as a class or method. Just don't use one of the predefined identifiers.

***1 **22 *333 4444

Based on the tips/tricks that we've learned we can expect: An outer-most "for" loop that counts to 4 (number of output lines). 1. You can either increment or decrement the outer-most loop control variable because the total number of character output per line (4) isn't changing. 2. 2 nested "for" loops, 1 for the repeating stars ("*") and one for the repeating numerics.

Decrement operator

Decrement operator: decreases the value of a variable by 1 ◦ predecrement --x (decrement and then use) ◦ postdecrement x--

String Index (charAt)

First character's index: 0 Last character's index: 1 less than the string's length The individual characters are values of type char

Padding with Zeroes

For integers put 0 after % to indicate should pad with zeroes (to fulfill character limit)

Increase Output Length **** *** ** *

If the length of each subsequent output line repeating pattern is getting longer, try an outermost loop that INCREMENTS. for (int i = 1; i <= 4; i++) { for (int j = 1; j <= i; j++) { System.out.print("*"); } System.out.println(); }

Decreasing Output Length **** *** ** *

If the length of each subsequent output line repeating pattern is getting shorter, try an outermost loop that DECREMENTS Then use the value of the outermost loop counter to affect the inner loop repeating pattern. for (int i = 4; i >= 1; i--) { for (int j = 1; j <= i; j++) { System.out.print("*"); } System.out.println(); }

How to Declare a String

In Java you can declare variable of type String and assign a value to it String s1 = "hello";

Increment operator

Increment operator: increases the value of a variable by 1 ◦ preincrement ++x (increment and then use) ◦ postincrement x++

Cast an int to double and double to int (with variable)

Int to Double: int x = (double) y Double to int double y = (int) x

Java Packages

Java class libraries is a collection of many classes. ◦ Java group related classes into packages A Java program in order to access a package needs to include an import declaration (so the compiler will be able to find it)

Java Lang

Many classes (such as: System, String, Math) are part of the java.lang package

Special Cases for Division Numerator small than denominator: Numerator of 0: Denominator of 0:

Numerator small than denominator: In this case division produces 0 and mod produces the original number. For example, 7/10 is 0 and 7%10 is 7. Numerator of 0: In this case both division and mod return 0. Example, 0/10 is 0. Denominator of 0: Both division and mod are undefined and produce a runtime error.

Creating an Object Def: Syntax:

Objects in Java programs must be constructed before they can be used To create and initialize an object, we typically use a special method known as constructor <type> <variable> = new <ClassName>(<paremeters>);

Print vs Println

Println sends output to the current line and then it moves to the beginning of a new line Print command does only the first of these

Public

Public indicates that the method is available to be used by all parts of the program

Console Input

Responses typed by the user when an interactive program pauses for input

Returning a Value in a Method

Return sends out a value as the result of a method The return is the opposite of a parameter ◦ Parameters send information in from the caller method ◦ Return values send information out from a method to its caller. Doesn't return variable returned, returns the value from the static method to the main method

Rounding to an Integer Rounding to Two Decimals (mathematically)

Rounding to an Integer - Add 0.5 to the double. Truncate as int. Round to Two Decimals - Multiply double by 100. Add 0.5. truncate to int. Convert to double and divide by 100.

Use of a Scanner object To read an integer from the user

Scanner console = new Scanner(System.in); int numGrades = console.nextInt(); Line 2. causes the program to pause until the user types in an integer follow by the [ENTER] key If the user only hits [ENTER], it will continue to pause If the user enters an integer, it is retuned and assigned to numGrades If the user enter a non-integer, an exception is thrown and the program crashes

Creating a Program for Repeating Statements (using static methods)

Separate out the repeating statements Create static methods for each repeating statement Have each following repeating statement use a method call for the previous. Then create static methods for each verse with the unique portions of text

Uppercase or Lowercase the first letter

String lastNameLetterTwo= (lastName.substring(0,1).toUpperCase());

3 Kinds of Errors

Syntax Errors: bad grammar caught by the Java compiler Logic errors: when you write code that doesn't perform the task it is intended to perform Runtime errors: logic errors so severe java stops your program from executing

How to construct a Scanner object to read console input?

Syntax: Scanner <variable> = new Scanner(System.in); ex: Scanner console = new Scanner(System.in);

Using the Mod Operator - Testing whether a number is even - Finding individual digits of a number - Isolating Digits from Left to Right vs Right to Left - How to get change

Using the Mod Operator - Testing whether a number is even number%2 is 0 for evens and 1 for odds - Finding individual digits of a number Number%10 is the final digit Number%100 is the second to last digit and the final digit (think decimal) - Isolating digits from left to right use int division (keeps digits left of decimal), right to left use modulus (keep digits right of decimal) - Use division to get number of first denomination (add 1 if necessary). Then use modulus of change in denomination to get change left over. Use division again to get number of next denomination then modulus of change in denomination for change left over etc

Display a specific character from a string

Using the charAt method, you can request specific characters of a string and the return type is char. Ex: If you ask for s2.charAt(5) you'll get the 6th character System.out.println(s1.charAt(5)); or char = s2.charAt(5) you get the 6th character

****!****!****! ****!****!****!

We have a repeating pattern ("*") which is probably a nested "for" loop, followed by an exclamation point ("!") that is probably printed after exiting the nested "for" loop. However, we also see a pattern of the pattern "****!". This is an indication that an additional level of nested "for" loops is present. There are 3 repetitions of this pattern "****!" per output line, so we expect this additional nested for loop to increment from 1 to 3.

How do we write a program that asks the user to enter a value in the console window (or console input)?

We use the Scanner object

Creating Method with Parameter

When sayPassword is called, the caller must specify the integer code to print

Escape Sequences

\t = space character \n= new line character \" = quotation mark \\=backslash character

Consider the following output ***** ***** *****

and its corresponding nested "for" loop structure for (int i = 1; i <=3 ; i++) { for (int j = 1; j <=5; j++) { System.out.print("*"); } System.out.println(); }

How to compile in Mac terminal (syntax)

cd Desktop/ javac ClassName.java java ClassName

String Methods

charAt(index) - Returns the character at the specified index length() - Returns the number of characters in this string substring(index1, index2) or substring(index1) -Returns the characters in this string from index1 (inclusive) to index2 (exclusive). If index2 is omitted, grabs till end of string. toLowerCase() - Returns a new string with all lowercase letters toUpperCase() - Returns a new string with all uppercase letters

What statement in the body would cause the loop to print: 2 7 12 17 22

for (int count = 1; count <= 5; count ++) { System.out.println(5 * count - 3 + " "); } To see patterns, make a table of count and the numbers to print

What statement in the body would cause the loop to print: 4 7 10 13 16

for (int count = 1; count <= 5; count ++) { System.out.println(3 * count + 1 + " "); } To see patterns, make a table of count and the numbers to print

Four commonly used primitive types in Java

int - integers/whole numbers (ex: 42, -3, 18) double - real numbers with decimal (ex: 7.35, 14.9) char - single characters (ex: a,X,!,//) boolean - logical values (true, false)

for loop exponents (without math class)

int power=1 for (int i =0; i <= exponent; i++) { System.out.println(power); power=2*power; }

4 Key Scanner Methods

nextInt() - reads an int from the user and returns it nextDouble() - reads a double from the user and returns it next() - reads a one-word String from the user and returns it nextLine() - reads a one-line String from the user and returns it

Beginning of any program

public class <name> { public static void main(String[ ] args)

String Substring

s2.substring(4,7) The method substring (start, end) returns a new string having the same characters as the substring that begins at index start through, but not including, end

Static

static indicates that this is a procedural-style method not a object-oriented method

Void

void indicates that the method executes statements but doesn't produce any value


Kaugnay na mga set ng pag-aaral

Ancient civilizations: Greece: dark ages

View Set

Chapter 7 - Nutrition Through the Lifespan

View Set

OA/ arthroplasty practice questions

View Set

Labor & Birth Process Ch. 13 NCLEX questions

View Set

C165 - Unit 3 Chemistry - Lessons 7-19: Quiz

View Set

Spanish 102: Estructura 5.2 The present progressive

View Set

AP World History Penultimate Unit Test (1424 Terms of Mostly Useless Information)

View Set