Lesson 01 - Introduction to Java and OOP

Ace your homework & exams now with Quizwiz!

high-level language

A programming language like Python that is designed to be easy for humans to read and write.

boolean

A single value of either TRUE or FALSE

Java Virtual Machine

A software "execution engine" that safely and compatibly executes the byte codes in Java class files on a microprocessor (whether in a computer or in another electronic device).

byte-code

A special kind of object code used for Java programs. Byte code is similar to a low-level language, but it is portable like a high-level language. code readable by a computer.

block comment

(/*) Creates a block comment, computers will read the first (/*) and ignore all text until the final (*/). (for multiply line instructions or comments)

invoking a method

(calling the method) allowing the method to execute; also known as called into action object.method(arguments)

25. What is the output produced by the following? String test = "abcdefg"; System.out.println(test.length()); System.out.println(test.charAt(1));

7 b

line comment

Comments preceded by two slashes (//).

System.out.println

Displays text for the user: Ex. System.out.println("Hello") Hello

34. What is the output produced by the following Java code? /** Code for Exercise. */ System.out.println("Hello"); //System.out.print("Mr. or Ms. "); System.out.println("Student");

Hello Student

Variable Name Rules

Must start with a letter or _ Can't use other symbols like % or ? No spaces allowed Variable names are case sensitive Can't use reserved words like double or class Start with a lowercase letter

Suppose you compile the class NiceClass. What will be the name of the file with the resulting byte-code?

NiceClass.class

char charAt(Position)

Returns the character in the calling object string at the Position. Positions are counted 0, 1, 2, etc. Example After program executes String greeting = "Hello!"; greeting.charAt(0) returns 'H', and greeting.charAt(1) returns 'e'.

char type

Store single unicode characters (international character set) and can be initialised with character literals enclosed in '. E.g. 'a'.

assignment operator

The '=' character causes the compiler or interpreter to evaluate to the expression on its right and store the result in the variable(s) on its left.

35. What is the normal spelling convention for named constants?

The normal spelling convention is to spell named constants using all uppercase letters with the underscore symbol used to separate words.

objects

Objects can contain many values. For example if there was an object named car, you might want to store multiple values about the car, like name, price, weight, or color. Creating an object would allow you to store all of that information about the car in one place.

char singleQuote

char singleQuote = '\''

char vs string

char uses 'single quotes' string uses "double quotes"

Write a Java assignment statement that will set the value of the variable distance to the value of the variable time multiplied by 80. All variables are of type int.

int distance = time * 80;

Give the declaration for two variables called feet and inches. Both variables are of type int and both are to be initialized to zero in the declaration.

int feet = 0 , inches = 0;

33. What are the two kinds of comments in Java?

line and block

object-oriented programming

methodology that views a program as similarly consisting of objects that interact with each other by means of actions. designing a program by discovering objects, their properties, and their relationships.

Naming Constants

public static final Type Variable = Constant;

36. Write a line of Java code that will give the name ANSWER to the intvalue 42. In other words, make ANSWER a named constant for 42.

public static final int ANSWER = 42;

String Processing

strings are immutable objects meaning they cannot be changed.

identifier

the name of a variable

type coercion

when a value of one data type is implicitly (automatically) changed to another data type

16. What is the output produced by the following lines of program code? char a, b; a = 'b'; System.out.println(a); b = 'c'; System.out.println(b); a = b; System.out.println(a);

b c c

30. What is the output of the following two lines of Java code?System.out.println("2 + 2 = " + (2 + 2)); System.out.println("2 + 2 = " + 2 + 2);

2 + 2 = 4 2 + 2 = 22

Type Casting

Converting data from one type to another, e.g., from string to int, potentially losing information.

interpreter

Converts a program written in a higher level language into a lower level language and executes it, beginning execution before converting the entire program.

If the following statement were used in a Java program, it would cause something to be written to the screen. What would it cause to be written to the screen? System.out.println("Java is not a drink.");

Java is not a drink

String method - int indexOf(A_String, Start)

Returns the index (position) of the first occurrence of the string A_String in the calling object string that occurs at or after position Start. Positions are counted 0, 1, 2, etc. Returns −1 if A_String is not found. Example After program executes String name = "Mary, Mary quite contrary"; name.indexOf("Mary", 1) returns 6. The same value is returned if 1 is replaced by any number up to and including 6. name.indexOf("Mary", 0) returns 0. name.indexOf("Mary", 8) returns -1.

Declare a variable

Specifying the type and name for a variable. This sets aside memory for a variable of that type and associates the name with that memory location. ex: int num; double weight, total weight;

System.out

The System class is calling a field from the Printstream class. an object used for sending outputs to the screen.

decrement operator (--)

The operator (--) that decreases the value of a numerical variable by one.

arguments

The parameters of a function.

string concatenation

The plus symbol (+), when used with Strings, stands for String concatenation. It merges two Strings together into one.

24. What is the output produced by the following? String verbPhrase = "is money"; System.out.println("Time" + verbPhrase);

Timeis money

assignment statement

Uses the equal sign to give the object property on the left of the equal sign the value on the right of the equal sign.

Suppose you define a class named YourClass in a file. What name should the file have?

YourClass.java

intermediate language

an internal language used as the representation of a program during compilation, such as trees or quadruples. The source language is translated to intermediate language, which is then translated to the object language. (byte-code)

What is the output produced by the following? String test = "abcdefg"; System.out.println(test.substring(3));

defg

Write a Java assignment statement that will set the value of the variable interest to the value of the variable balance multiplied by the value of the variable rate. The variables are of type double.

double interest = balance * rate;

machine languages

first generation language - instructions written in binary (0's and 1's); runs directly on the computer

Java application program

is a class with a method named main; when you run the Java program, the run-time system automatically invokes the method named main (that is, it automatically initiates the mainaction). An application program is a "regular" Java program.

\n

new line

What is the output produced by the following lines of program code? int quotient, remainder; quotient = 7 / 3; remainder = 7 % 3; System.out.println("quotient = " + quotient); System.out.println("remainder = " + remainder);

quotient = 2 remainder = 1

What is the output of the following program lines? double number = (1/3) * 3; System.out.println("(1/3) * 3 is equal to " + number);

(1/3) * 3 is equal to 0.0Since 1 and 3 are of type int, the / operator performs integer division, which discards the remainder, so the value of 1/3 is 0, not 0.3333 . . . . This makes the value of the entire expression 0 * 3, which of course is 0.

What is a complier?

A compiler translates a program written in a programming language such as Java into a program in a low-level language. When you compile a Java program, the compiler translates your Java program into a program expressed in Java byte-code.

int

A primitive type representing the integers, which are positive whole numbers and their opposites.

What do you call a program that runs java byte-code instructions?

A program that runs Java byte-code instructions is called an interpreter. It is also often called the Java Virtual Machine (JVM).

low-level language

A programming language that is designed to be easy for a computer to execute; also called machine language or assembly language.

logic error

An error in a program that makes it do something other than what the programmer intended.

run-time error

An error that is not detected until your program is run is called a run-time error. If the computer detects a run-time error when your program is run, then it will output an error message. The error message may not be easy to understand, but at least it lets you know that something is wrong.

String methods - int compareToIgnoreCase(A_String)

Compares the calling object string and the string argument to see which comes first in the lexicographic ordering, treating upper- and lowercase letters as being the same. (To be precise, all uppercase letters are treated as if they were their lowercase versions in doing the comparison.) Thus, if both strings consist entirely of letters, the comparison is for ordinary alphabetical order. If the calling string is first, it returns a negative value. If the two strings are equal ignoring case, it returns zero. If the argument is first, it returns a positive number. Example After program executes String entry = "adventure"; entry.compareToIgnoreCase("Zoo") returns a negative number, entry.compareToIgnoreCase("Adventure") returns 0, and "Zoo".compareToIgnoreCase(entry) returns a positive number. Some methods for the class String depend on counting positions in the string. Positions are counted starting with 0, not with 1. So, in the string "Surf time", 'S' is in position 0, 'u' is in position 1, and so forth. A position is usually referred to as an index. So, it would be preferable to say: 'S' is at index 0, 'u' is at index 1, and so on.

String methods - int compareTo(A_String)

Compares the calling object string and the string argument to see which comes first in the lexicographic ordering. Lexicographic order is the same as alphabetical order but with the characters ordered as in Appendix 3. Note that in Appendix 3, all the uppercase letters are in regular alphabetical order and all the lowercase letters are in alphabetical order, but all the uppercase letters precede all the lowercase letters. So, lexicographic ordering is the same as alphabetical ordering provided both strings are either all uppercase letters or both strings are all lowercase letters. If the calling string is first, it returns a negative value. If the two strings are equal, it returns zero. If the argument is first, it returns a positive number. Example After program executes String entry = "adventure"; entry.compareTo("zoo") returns a negative number, entry.compareTo("adventure") returns 0, and entry.compareTo("above") returns a positive number.

29. What is the output produced by the following? String test = "Hello Tony"; test = test.toUpperCase(); System.out.println(test);

HELLO TONY

String method - equals (other_string)

Method *equals* (a method of class Object overridden in String) tests any two objects for equality. The method returns true if the contents of the objects are equal, and false otherwise. Method equals uses a lexicographical comparison

println

Method that displays output to the screen and then moves the insertion point to the next line.

class

Objects of the same kind or of the same type for example: lasagna, poutine and jolly rice are all food objects in the food class.

String method - trim()

Returns a string with the same characters as the calling object string, but with leading and trailing white space removed. White space characters are the characters that print as white space on paper, such as the blank (space) character, the tab character, and the new-line character '\n'. Example After program executes String pause = " Hmm "; pause.trim() returns "Hmm".

String method - int indexOf(A_String)

Returns the index (position) of the first occurrence of the string A_String in the calling object string. Positions are counted 0, 1, 2, etc. Returns −1 if A_String is not found. Example After program executes String greeting = "Hi Mary!"; greeting.indexOf("Mary") returns 3, and greeting.indexOf("Sally") returns −1.

int lastIndexOf(A_String)

Returns the index (position) of the last occurrence of the string A_String in the calling object string. Positions are counted 0, 1, 2, etc. Returns −1, if A_String is not found. Example After program executes String name = "Mary, Mary, Mary quite so"; greeting.indexOf("Mary") returns 0, and name.lastIndexOf("Mary") returns 12.

String method - length()

Returns the number of characters in a string, counting from 1. E.g. "12345".length() would return 5. An empty String has length 0.

String method - substring(Start)

Returns the substring of the calling object string starting from Start through to the end of the calling object. Positions are counted 0, 1, 2, etc. Be sure to notice that the character at position Start is included in the value returned. Example After program executes String sample = "AbcdefG"; sample.substring(2) returns "cdefG".

String method - substring(Start, End)

Returns the substring of the calling object string starting from position Start through, but not including, position End of the calling object. Positions are counted 0, 1, 2, etc. Be sure to notice that the character at position Start is included in the value returned, but the character at position End is not included. Example After program executes String sample = "AbcdefG"; sample.substring(2, 5) returns "cde".

Applets

Small programs written in Java, which are downloaded as needed and executed within a Web page or browser. Applets and applications are almost identical. The difference is that applications are meant to be run on your computer like any other program, whereas an applet is meant to be run from a Web browser, and so can be sent to another location on the Internet and run there. Applets always use a windowing interface, but not all programs with a windowing interface are applets

Give a statement or statements that can be used in a Java program to write the following to the screen: I like Java. You like tea.

System.out.println("I like Java"); System.out.println("You like tea.");

Given the following fragment that purports to convert from degrees Celsius to degrees Fahrenheit, answer the following questions: double celsius = 20; double fahrenheit; fahrenheit = (9 / 5) * celsius + 32.0; What value is assigned to fahrenheit? Explain what is actually happening, and what the programmer likely wanted. Rewrite the code as the programmer intended.

What value is assigned to fahrenheit? 52.0 Explain what is actually happening, and what the programmer likely wanted. 9/5 has int value 1; because the numerator and denominator are both of type int, integer division is done; the fractional part is discarded. The programmer probably wanted floating-point division, which does not discard the part after the decimal point. Rewrite the code as the programmer intended. double celsius = 20; double fahrenheit; fahrenheit = (9.0/5) * celsius + 32.0;

What is a source program?

a program that contains the language instructions to be converted to machine language with a complier

Complier

a program used to translate the source code of a computer program into binary form using only 0s and 1s

27. What is the output produced by the following?System.out.println("abc\ndef");

abc def

28. What is the output produced by the following?System.out.println("abc\\ndef");

abc\ndef

methods

actions that an object can perform

increment operator (++)

increases the value of a variable by 1

Give the declaration for two variables called count and distance. count is of type int and is initialized to zero. distance is of type double and is initialized to 1.5.

int count = 0; double distance = 1.5;

primitive types

int, double, boolean, char, and the shorter and longer versions of these

syntax error

is a grammatical mistake in your program; that is, a mistake in the allowed arrangement of words and punctuations. If you violate one of these rules—for example, by omitting a required punctuation—it is a syntax error. The compiler will catch syntax errors and output an error message telling you that it has found the error, where it thinks the error is, and what it thinks the error is. If the compiler says you have a syntax error, you undoubtedly do. However, the compiler could be incorrect about where and what the error is.

double type

is the larger type of the floating-point data types. It is twice as big and twice as precise as the float type (14-15 significant digits of accuracy).

% operator

its output gives us what is left after the division is made Ex: 14/3 = 4 (bcuz its int) Ex: 14%3 = 2 (there is two left bcuz 3x4 is 12)

22. What is the output produced by the following lines of program code? int n = (int)3.9; System.out.println("n == " + n);

n == 3

What is the output produced by the following lines of program code? int n = 3; n++; System.out.println("n == " + n); n−−; System.out.println("n == " + n);

n == 4 n == 3

3. Write a complete Java program that uses System.out.println to output the following to the screen when run:Hello World!Note that you do not need to fully understand all the details of the program in order to write the program.

public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } }

main method

public static void main(String[] args) A Java program is really a class definition (whatever that is) with a method named main. When the program is run, the method named main is invoked; that is, the action specified by main is carried out. The body of the method main is enclosed in braces, {}, so that when the program is run, the statements in the braces are executed.

Which of the following may be used as variable names in Java? rate1, 1stPlayer, myprogram.java, long, TimeLimit, numberOfWindows

rate1, numberOfWindows 1stPlayer - starts with a number myprogram.java - has a period in it long - keyword TimeLimit - while legal, violates the style rule that all variable names begin with a lowercase letter.

String method - toLowerCase()

returns a string with the same characters but lowercase.

String method - toUpperCase()

returns a string with the same characters but uppercase.

31. Suppose sam is an object of a class named Person and suppose increaseAge is a method for the class Person that takes one argument that is an integer. How do you write an invocation of the method increaseAge using sam as the calling object and using the argument 10? The method increaseAge will change the data in sam so that it simulates sam aging by 10 years.

sam.increaseAge(10);

String method - equalsIgnoreCase (other_string)

same as equals but ignores case

What is an object program?

the machine language version of the high-level language program. The translated program that is produced a complier is called object program or object code.

32. The following code is supposed to output the string in lowercase letters but it has an error. What is wrong? String test = "WHY ARE YOU SHOUTING?"; test.toLowerCase(); System.out.println(test);

why are you shouting?

Can a Java program have two different variables named number and Number?

yes but it would not be good style


Related study sets

Test 3 Neurologic Dysfunction #2 - From Mom

View Set

Med Surg Chapter 36 Assessment of the Hematologic System & 37 Concepts of Care for Patients with Hematologic Problems Ignatavicius, Chapter 55: Anticoagulant, Antiplatelet, and Thrombolytic Drugs Burchum: Lehne’s Pharmacology for Nursing Care, 11th E…

View Set

Section 10: Secure Software Development

View Set

APUSH Chapter 5 Identification and Cause and Effect

View Set

Chp 18 Tenant-Landlord Relationships

View Set

Principles of Biology 1 Final Exam

View Set