Introduction to Java Flashcards
In the java programming language:
A program is made up of ________ classes
one or more
In the java programming language:
A program is made up of ________ , methods
one or more
A method contains
program statements
Anatomy of a Java Program:
Comments Reserved words Modifiers Statements Blocks Classes Methods The main method
How do you structure a class?
//comments about the class public class classHeader {
//class body
}
How do you structure a method?
//comments about the class public class classHeader {
public static returnType name(|inputType| tempName) { //method body }
}
Comments in a program are called…
They should be included to…
inline documentation, explain the purpose of the program and describe processing steps
How are comments structured?
// this comment runs the end of line
/* this comment runs to the terminating symbol */
/** comment */
Identifiers are…
the words that a programmer use in a program
Identifiers can be made up of…
letters, digits, underscore and $
Identifiers cannot begin with…
a digit
Java is case…
sensitive
White space includes…
spaces, blank lines, tabs
White spaces are used to…
separate words and symbols in a program and make the program more readable along with indentation
Extra white spaces are
ignored
Reserved words called modifiers are used to
specify properties of the data, methods and classes and how they can be used
private, final, public and static are examples of
modifiers
A statement…
represents an action or a sequence of actions
A statement ends in
;
Blocks can be identified with…
{
}
The syntax rules of a language define…
how we can put together symbols, reserved words, and identifiers to make a valid program
The semantics of a program is…
what the programmer intends the program to achieve/do
A program that is syntactically correct does not mean it is
semantically/logically correct
The three types of errors in java are
- Compile time errors
- Run-time errors
- Logical errors
Compile time errors occur when…
The program is fundamentally flawed (e.g. syntactically incorrect), hence an executable version of the program can not be compuled
Run time errors occur when…
A problem arises halfway through the execution of the program, e.g. divide by 0
Logical errors occur when…
There’s no compile time or runtime errors (i.e. the program runs perfectly) but does not produce the intended results
A class is…
a template or blueprint for constructing objects, it is a program entity that represents either 1. a program/module or 2. a type of object
A method is…
a collection of statements that performs a sequence of actions to return a message (or void)
The main method…
provides the control of program flow
The java interpreter executes the application by invoking the..
main method
The main method looks like…
public static void main(String[] args) { //Statements; }
An algorithm is…
a set of precise instructions that lead to a solution
An algorithm does not..
have to be written in programming language, it can be written in pseudocode (a mix of human and programming languages)
Pseudocode must be…
precise and clear enough so that a programmer can convert it into syntactically correct code easily
Pseudocode is much less…
rigid than programming language
The steps to solving a problem are…
- Understand the problem
- Design a solution
- Consider alternatives and refine the solution
- Implement
- Test
The steps to solving a problem are…
not linear and overlap
The key to designing a solution is…
breaking it down into manageable pieces with classes and objects (i.e. modular programming)
What type of programming language is Java?
OOP Object-Oriented Programming Language
The Scanner class (type) is a template for…
creating many Scanner objects
objects are
an entity that combines data (variables OF the object) and behaviour (methods OF the object)
Object-oriented programming is
program that performs their behaviour as interactions between objects
How is an object constructed?
Type objectName = new Type (parameters);
Calling an object’s method:
objectName.methodName (parameters);
A variable holds either:
- Primitive types
2. Reference to objects
To define an OBJECT REFERENCE variable,
a class name can be used a the type
e.g. String name;
The declaration String title;
does not create a new object, the object is constructed separately or constructed when it is assigned
An object reference variable holds the…
address of an object
title = new String (“Java”);
is…
an example of
- a constructor method
- instantiation (an instance of a particular class is created which is an object)
Once an object is created, the dot operator is used to…
e.g. count = title.length();
invoke a method
The act of assignment…
e.g. num1 = num2
takes a COPY of a value/address and stores it in a variable, nothing is destroyed
Aliases are…
two or more object reference variables that refer to the same object, they are the alias of each other
An object is a garbage when…
It is no longer being referenced, therefore becomes useless
Java performs garbage collection…
automatically and periodically
To create a new String object, the constructor method is_______ because ________.
not required because it is so common
String literals each represent…
a String object
Literal strings are defined by…
enclosing in double quotes “String”
char firstInitial = “Robert”.charAt(0);
calls a method on…
a literal string
The last index of a string is…
length - 1
Does the following declaration create an empty string?
String str;
No, str contains a null
String str = new String(); is an example of…
and it instantiates a…
Constructor method + instantiation
Empty string
Once a String object has been creates, its value and its length cannot…
be changed
An object of the String class is
immutable
List 10 methods of the String class
length(); substring(); charAt(); concat(); indexOf(); lastIndexOf(); equals(); trim(); replace(); toUpperCase(); toLowerCase();
Does word1 = word1.toUpperCase(); destroy any objects?
No, the variable’s reference is changed to another object.
What are the three ways that convert a number into a String object?
- String str = “” + num;
- String str = integer.toString(i);
- String str = String.valueOf(i);
where i is an integer
What is the difference between the next and nextLine methods of a Scanner object?
next - makes String out of a word
nextLine - makes String out of a LINE
What does flow of control refer to?
branching and looping mechanisms
What are the 3 branching mechanisms in Java?
if
if-else
switch
What are the 3 types of loops in Java?
while
do-while
for
Most branching and looping are controlled by…
boolean expressions
What do Decision-Making Statements do?
Determine whether a condition is true, and take some action based on determination
List 9 logical operators in Java
==
&&
||
>=
Conditional operator…
provides a shortcut to writing an if-else statement
Structure
variable = (expression) ? value1 : value2;
switch statements are…
multiple-way if statements
How are switch statements structured?
switch (variable) { case 'X': variable2 = expression; break; case 'Y': variable2 = expression2; break; default: variable2 = 420; }
A compound statement is …
a branch statement that is made up of more than one statement
A compound statement must be enclosed by
{ //curly brackets/braces }
How are multiway if-else statements structured?
if (Boolean_Expression) Statement_1 else if (Boolean_Expression) Statement_2 ... else if (Boolean_Expression_n) Statement_n else Statement_For_All_Other_Possibilities
How is a branch statement in a switch statement structured?
Starts with the reserved word case, followed by a constant called a case label of the same type as the controlling expression, followed by a colon, and then a sequence of statements and BREAK
The default branch of a switch statement is compulsory. T or F?
False, it is optional
What is a boolean expression?
An expression that is either true or false. (involves logical operators)
Give two examples of a boolean expression.
var == var2
var
If the == operator is used on Strings (or any object), what is the output of the boolean expression? Why?
False. Because it tests whether the two objects being compared have the same memory location rather than same value.
Lexicographic ordering is…
ASCII Ordering
In ASCII ordering, upper case letters…
come before lower case
In the following declaration where s1 and s2 are two strings,
s1.compareTo(s2)
if a negative number is returned then…
S1 comes before S2 in ASCII ordering
In the following declaration where s1 and s2 are two strings,
s1.compareTo(s2)
if a positive number is returned then…
S2 comes before S1 in ASCII ordering
In the following declaration where s1 and s2 are two strings,
s1.compareTo(s2)
if 0 is returned then…
S2 and S1 are the same
s1 = a s2 = A
Does s1.compareTo(s2) return a negative number or a positive number? How can we get it to return 0?
Positive
by using compareToIgnoreCase
A boolean expression can be negated by…
Placing ! infront of the boolean expression in brackets
e.g.
!(a>b)
What is the difference between & and &&?
&& is short circuit
& is not
Is the short circuit “and” or “or” operator used more often than non short circuit?
Yes
What do loops do?
Repeated execution of one or a sequence of statements until a terminating condition is reached
What are definite loops?
A loop that executes for a known number of times. e.g. print the first n prime numbers
What are indefinite loops?
A loop that executes for an unknown number of times e.g. prompting the user to enter “u wot m8”
What are post test loops?
Tests terminating conditions at the end of loop instead of start, hence forcing the branch statement to be executed at least once
What is the code that is repeated/executed in a loop called?
The body
What are infinite loops?
Loops are infinite when a terminating condition will never be met.
What does the continue statement do?
Ends the current iteration of the nearest enclosing loop statement
What will the following statement do if someIdentifier is an identifier of a loop?
break someIdentifier;
Exits the labelled loop even if it isn’t the innermost loop
What dos the following do?
someIdentifier:for(int i = 0; i
Labels a for loop with the label “someIdentifier”
System.exit(0);
does…
Ends the entire program.
The two most common kinds of loop errors are …
unintended infinite loops and off-by-one errors
An assertion is…
a sentence that says (asserts) something about the state of a program
An assertion must be either..
true or false
An iterator is…
an object that allows you to process a collection of items one at a time e.g. a Scanner object
What does the next method of an iterator do?
returns the next item
What does the hasNext method of an iterator do?
returns true if there’s at least one more item to be processed
If the condition of a for loop is left out, the loop will be….
Always true and infinite
System.out.println(); does?
Start a new line
An array is…
an object containing a list of elements of the same data type
How is an initialiser structured for a new array?
type[] name = {1, 2, 3, 4, 5, 6};
short[ ] oldValues = {10, 100, 200, 300};
short[ ] newValues = new short[4];
newValues = oldValues;
Is a new array created? (in addition to the blank array)
No. The oldValues addresses are copied but not the object itself.
How do you duplicate an array object?
Copying individual values
When an array is passed as an argument in a method, is the array object copied?
No, only the address is. But the method can modify the content of the array.
How can you compare two arrays?
The only way is by comparing the individual values.
What is a good way to find the highest value of an array?
Create a variable that holds a copy of the highest value encountered so far in the array.
Can a method return an array?
Yes but it really is the address of the array that is returned.
Which two types of declarations does a class contain?
Data (static and instance variables)
Method (behaviours)
Each method is defined within…
a specific class
Mechanics of the Method-Calling Process
- Java evaluates the argument expressions in the context of the calling method.
- Java then copies each argument value into the corresponding parameter variable, which is allocated in a newly assigned region of memory called a stack frame. This assignment follows the order in which the arguments appear: the first argument is copied into the first parameter variable, and so on.
- Java then evaluates the statements in the method body, using the new stack frame to look up the values of local variables.
- When Java encounters a return statement, it computes the return value and substitutes that value in place of the call.
- Java then discards the stack frame for the called method and returns to the caller, continuing from where it left off.
What is method overloading?
When more than one method of the same name is defined. e.g. println
How does java know which version of an overloaded method is to be invoked?
By analysing the signature (i.e. the parameters) and matching them with the correct version
What if more than one overloaded method matches the signature?
Java picks the best match.
What if no method matches the signature?
If some implicit conversion can be done to match a method, then the method is invoke with implicit conversion.
Ints can become doubles automatically but can doubles be ints?
No
What are the two types of scopes in Java?
class scope and block scope
If a variable has a class scope, can it be accessed from within a method?
Yes. static and instance variables of the class
Which three types of variables are accessible from within a method?
- class and instance variables
- local variables (block scope)
- formal arguments
static int min (int num1, int num2) { //body }
Are num1 and num2 formal arguments?
Yes.
What are actual arguments?
The parameters that are copied to the formal arguments in a method.
What are the two types of Parameter Passing?
Call by value
Call by reference
Describe the effects of parameter passing by call by value
The parameter is copied over, the actual argument cannot be altered from within the method.
Describe the effects of parameter passing by call by reference
The address is copied over, the actual argument can be altered from within the method since it has access to the actual object.
List four types of methods.
- access methods : read or display states (or those that can be derived)
- predicate methods : test the truth of some conditions
- action methods, e.g., print
- constructors: a special type of methods
List four properties of a constructor method
-they have the same name as the class there may be more then one constructor per class (overloaded constructors) -they do not return any value it has no return type, not even void -they initialize objects of the class, using the new construct: -you do not have to define a constructor
What are two things that an object has?
state - descriptive characteristics
behaviours - what it can do (or be done to it), may depend on the state, and can change the state
What are two types of modules in Java?
Classes
Methods
What is the process of invoking a method called?
Method call
What are 3 benefits of modularising programs?
- Makes program development more manageable
- Software reusability
- Avoid repeating code
What are the steps to evaluating
System.out.println( Math.sqrt( 4 ) );
?
Math.sqrt(4) is evaluated first
Then System.out.println is evaluated
What is an escape sequence?
An escape sequence is a sequence of two characters beginning with the character \