Java: Basic Concepts Flashcards Preview

Java: Basic concepts > Java: Basic Concepts > Flashcards

Flashcards in Java: Basic Concepts Deck (114):
1

What happens in java when we write 7/10? Why?

7/10 in java will return zero. If we want to divide 7 by 10, then we must write 7.0/10 (which will return 0.7

Reason: 7/10 presents the problem as involving 2 integers. Java returns an integer because you asked for an integer. It runs the calculation, sees where the decimal is, and truncates the decimal. If you want it to return a float, you must use a float.

2

What is casting?

Typecasting is when one object reference can be type cast into another object reference.

3

Java has two casting scenarios. What are they?

Upcasting and downcasting

4

What is upcasting?

.Upcasting is when we cast an instance of a subclass to a variable of a superclass. Remember, an instance of a subclass is ALWAYS an instance of its superclass.

5

What is an implicit cast?

Instead of writing:

Object o = new Student();
m(o);

We can use an implicit cast:

m(new Student());

This works because an instance of Student is an instance of Object.

6

What is an explicit cast?

Sometimes we must explicitly tell the compiler that an object of its own class is in fact an object of its class.

Student b = o; [does not work]

Student b = (Student)o; [works]

We use this to downcast correctly.

7

What is downcasting, and why do we do it?

A downcast is when we cast an instance of a superclass to a variable of its subclass. We must use explicit casting to confirm our intention to the compiler with the (SubclassName) cast notation.

First, make sure the object to be casted is an instance of the subclass. use instanceof

Good analogy, pg 426. Fruit is a superclass. Apple and Orange are subclasses. We can easily assign an instance of Apple to a variable for Fruit. But because a fruit is not necessarily an apple, we must explicitly assign an instance of Fruit to a variable of Apple.

myObject.getDiamter [doesn't work because the Object class doesn't have getDiameter]

((Circle)myObject.getDiameter()); [DOES work because we told the compiler that the variable is an instance of a superclass, in this case, Circle]

8

What is a unary operator? Give example

A unary operation is an operation with only one operand. A negative number's -x for instance

9

How does preincrement work, and why do we do it?

++var

Increments a variable and then returns that variable. (does not return the variable and then increment, as postincrement does)

If a variable does nothing but increment, then ++var and var++ are identical.

BUT

i = 1;
int j = ++i;
// j is 2, i is 2 [the new var is used in the statement]

i = 1
int j = i++;
// j is 1, i is 2 [ the original var value is used in the statement]

Increments j by 1, then returns j
(whereas postincrement returns j, then increments j by 1)

10

How does predecrement work, and why do we do it?

--var

Decrements a variable and then returns that variable. (does not return the variable and then increment, as postdecrement does)

If a variable does nothing but decrement, then --var and var-- are identical.

BUT

i = 1;
int j = --i;
// j is 0, i is 0 [the new var is used in the statement]

i = 1
int j = i++;
// j is 1, i is 0 [ the original var value is used in the statement]

Decrements j by 1, then returns j
(whereas postdecrement returns j, then increments j by 1)

11

What is a literal?

A literal is the value assigned to a variable.

double weight = 0.305;

the literal is 0.305

12

What are augmented assignment operators?

+= -= *= /= %=

example:

i += 8

i = i + 8

these are the same

13

Describe the char data type

a single 16-bit unicode character

14

Describe what a string is

A string is an object from the string class.

A string is immutable

A string is "changed" through methods that actually make a new string object

15

What does \t do

inserts a tab in the text at this point

16

what does \b do

inserts a backspace in the text at this point

17

what does \n do

inserts a newline in the text at this point

18

what does \r do

inserts a carriage return in the text at this point

19

what does \f do

inserts a formfeed in the text at this point

20

what does \' do

inserts a single quote character in the text at this point

21

what does \" do

inserts a double quote character in the text at this point

22

what does \\ do

insert a backslash character in the text at this point

23

what does next() do

Part of Scanner class. Finds and returns the next complete token from this scanner. whitespace is the default delimiter.

this is called a token reading method

24

what does nextInt(), nextFloat(), etc do

Scans the next token of the input as an int, double, etc (read the Scanner class for more)

this is called a token reading method

25

Say we want a list of random numbers, 1-50. how do we do it?

We use java's Random class. Remember, if you write:

Random rand = new Random();
int pickedNumber = rand.nextInt(40);

This will pick a number 0-39

To get 1-40:

int pickedNumber = rand.nextInt(40) + 1;

Basically, add the number of the range that you need. 5-35 needs:

int pickedNumber = rand.nextInt(31) + 5;

26

what is an off by one error?

an off by one error is when a loop iterates one time too many or too few.

mistake is usually made when using a "is less than or requal to" where "is less than" should have been used in a comparison or fails to take into account that a sequence starts at zero rather than one (as with array indicies in many languages)

27

In what situations is a for loop best?

a for loop is best when we know how many repetitions we need.

pretest loop

28

is what situations is a while loop best?

a while loop is best when we don't have a fixed number of repetitions

pretest loop

29

is what situations is a do-while loop best?

a do-while can replace a while if the loop body has to be executed before the continuation condition is tested.

posttest loop

use this if code must execute at least one time

30

what is a sentinel value

a special value whose presence guarantees termination of a loop that processes structured (especially sequential) data.

for example, a user may enter "0" to signal to the computer that he or she is done entering data

31

what is input and output redirection?

if we have a lot of data to enter, it can be a pain to do it from a keyboard. we can store the data in a textfile and separate it with whitespace.

in input redirection the program takes the input from the text file rather than asking the user to type in the data at runtime from a keyboard.

output redirection writes output to a file rather than display it on the console

32

describe the keywords break and continue

break breaks out of a loop

continue breaks out of an iteration

int sum = 0;
int number = 0;
while (number < 20) {
number++;
if (number == 10 | | number == 11)
continue;
sum += number;
}

System.out.println("The sum is " + sum);

this program sums all the numbers except 10 and 11. the continue escapes that iteration and then continues

33

what is "the stack"?

A call stack has several purposes. Mainly, it is for keeping track of the point to which each active subroutine should return control when it finishes executing.

34

what happens with the stack when a method is invoked?

the system creates an "activation record" (also called an "activation frame").

Stores parameters and variables for the method and places the activation record on the stack.

35

what happens with the stack when a method's work is finished?

when the work is finished and the data returns to its called, its activation record is removed from the call stack

36

how does the stack store activation records?

last in, first out. the activation record for the method that is invoked last is removed first from the call stack

m1 calls m2 and m3

m1 is pushed onto the stack first, then m2 and m3.

m3 is finished, activation record removed
m2 is finished, activation record removed
m1 is finished, activation record removed

37

Describe a void method

The void return type does work for us, but doesn't return a value to us.

38

can a void method use "return"?

yes, we can use "return" in a void method if we simple want to pop a frame from the call stack and return control to the line following the function call

39

what is a static method

a static method belongs to the class, and not to the object(instance)

a static method can only access static data (cannot access instance variables)

a static method can call only other static methods. cannot call a non-static method

a static method can be accessed directly by the class name. doesnt need an object

a static method cannot refer to "this" or "super" keywords

Syntax: .

Integer.toHexString(whatever);

This is a static method from the Integer class

*** There's only one copy of this no matter how many objects we've created (or even if we haven't created any objects yet) because it belong to the class. it does not belong to the instances of the class we create.

****Note: a static method can be called without creating an instance of the class



40

what is an static variable

a static variable belongs to the class, not to the object

a static variable is initialized ONCE, at the start of execution. initialized before instance variables.

a static variable is a single copy to be shared by all instances of the class

a static variable can be accessed directly by the class name and doesn't need any object

Syntax: .

Basically, you would create this in a class as a data field. for a bike class, if you wanted to keep track of how many objects of that class have been created, you would do:

private static int numberOfBikes = 0;

to reference it (to increment it, in this instance):

Bike.numbeOfBikes


*** Use this when you want all the instances of a class to share data. Static variables store values for the variables in a common memory location. Because of this common location, if one object changes the value of a static variable, all objects of the same class are affected.

41

pass by value

the method copies the value of an argument into the formal parameter of the subroutine.

as for people who say java passes objects by reference, this is not true. There is no difference between passing primitive data types and objects when talking about method arguments. You always pass a copy (not the object, and not the reference itself) of the bits of the value of the reference

if primitive, these bits will contain the value of the primitive data type itself

if object, the bits will contain the value of the address that tells the JVM how to get to the object

42

pass by reference

java doesn't pass by reference. java passes the value of the reference and not the reference itself (and not the object). see pass by value

43

name 3 advantages to modularizing code

1.methods and such can be used by other programs

2. errors are confined to particular methods, easier to debug

3. isolating methods makes the logic easier to follow, easier to read

44

Break down what this means:

System.out.println("whatever);

the dot operator connects classes and objects to members.

System is the name of a class. out is one of that class's static fields. println is a method in that class. So System.out.println(); invokes the println() method of the System.out object.

Said another way: The "System" object is actually a class from which you are accessing the static object out. Then you access the println method on that object.

45

explain the dot operator in java

the dot operator means that you are accessing a member (a variable or a method) of an object.

page 304 in textbook, but it's a bit crappy..

46

Create an example of a class with an addition method with 2 variables. Then access that method in main.

public class DotOperatorDemo {
public int add(int a, int b){
return a+b;
}
public static void main(String[] args) {

// create object of the class DotOperatorDemo
DotOperatorDemo dod = new DotOperatorDemo();

//using dot(.) operator calling method of that class
int result = dod.add(5, 10);

System.out.println("Addition of 5 and 10 is :"+result);
}
}

47

What are we referencing when we talk about an object's "member"?

1. data fields
2. methods

Example:

objectRefVar.dataField references a data field in the object

objectRefVar.method(arguments) invokes a method on the object

In concrete terms:

myCircle.radius references the radius in myCircle

myCircle.getArea() invokes the getArea method on myCircle.

Methods are invoked as operations on objects

48

What is an instance variable?

The data field in a class

for example, in the textbook's Circle class, radius is an instance variable. it is dependent on a specific instance.

49

what is an instance method?

instance methods are just regular object methods that can be only called by an instantiated object and which are only relevant within a specific class instance (aka object)

Every method you write will be an instance method unless you define it as "static."

Example:

Class: Cat

method: meow

Cat fluffy = new Cat("Fluffy");
Cat spooky = new Cat("Spooky");

fluffy.meow();
spooky.meow();

You have a Class representing Cat. Each Cat can do some things, like meow. Each of those things is the same action no matter what cat does it, so the method is a method of the class Cat.But each particular meowing is done by one particular cat, so it's an instance method.

50

what is a class method?

a class method is a STATIC method

51

how do you call a class method?

You must reference the class name to call a class method. The dot operator calls the method:

MyClass.classIdIncrementer();

Math.pow(3, 2.5);

52

how do you call an instance method?

You must invoke an instance method from an object using:

objectRefVar.methodName(arguments(;

myCircle.getArea();

myClass

53

When we create a data field for a class, what is the default value of a reference type if we don't specify a value?

If a data field of a reference type does not reference any object, the data field is null. null is a literal just like true and false.

private String name;

the value is null

54

What is a reference type?

There are primitive types (int, char, boolean, etc) and there are reference types. Reference types are related to specific classes, interfaces, or arrays. String, for example. Be default all are set to null.

55

What is the default value of a boolean instance variable?

false

56

What is the default value of a char instance variable?

\u0000

57

What is the default value of a numeric instance variable?

0

58

Every value represents a memory location that holds a value. When we declare a variable, we are telling the compiler what type of value the variable can hold. What does a variable of the reference type hold?

A reference variable (like String, for instance), holds a reference to where the contents of the reference is stored in memory.

Circle c c holds a reference

59

Every value represents a memory location that holds a value. When we declare a variable, we are telling the compiler what type of value the variable can hold. What does a variable of the primitive type hold?

A primitive variable holds the primitive value itself:

int i = 1 1 is held in memory

60

Can a static method access instance members of the class?

no

61

what kind of method can be called without creating an instance of the class?

static methods pg. 315

62

What can a static method invoke and access?

A static method can invoke a static method

A static method can access a static data field

pg. 315

63

What can't a static method invoke or access?

A static method cannot invoke an instance method

A static method cannot access an instance data field

Why: static methods are static data fields don't belong to a particular object

pg 315

64

How do we decide whether to write an instance method or a static method?

A variable or method that is dependent on a specific instance of the class should be an instance variable or method.

A variable or method that is not dependent on a specific instance of the class should be a static variable or method.

Example:

Every circle has its own radius, so radius is dependent on a specific circle. Radius is an instance variable of the Circle class.

Since getArea() is dependent on a specific circle, it is an instance method.

None of the methods in the Math class, such as random, pow, sin, and cos, is dependent on a specific instance. These methods are static.

65

What are we passing when we pass an object to a method?

We are passing a reference to an object.

Pass by value on references can be best described semantically as pass by sharing; that is, the object reference in the method is the same as the object being passed.

66

What is overloading a method?

Overloadng methods enables you to define the methods with the same name as long as their signatures are different.

public static int max( int num1, int num2)

public static double max(double num1, double num2)

67

If we have an overloaded method for adding two numbers, one that takes ints, and one that takes doubles, and we want to add an int and a double, could we?

yes. the JVM would convert one of the numbers to a double and do that method. The java compiler finds the most specific method for a method invocation. 193

68

Explain variable scope

The scope of a variable is the part of the program where the variable can be referenced. 196

a scope inside a method is a LOCAL variable.

a parameter is a local variable

69

what is a stub? what do they enable you to do?

is this a top-down or bottom-up approach?

a stub is a simple but incomplete version of a method that can be used for the methods waiting to be implemented.


stubs enable you to quickly build the framework of a program. 205

this is a top-down approach to design

70

What is an array?

An array is a data structure. It stores a fixed-size sequential collection of elements of the same type.

71

When we declare an array variable, is memory allocated for the array?

No. When we declare an array variable we are only creating a storage location for the reference to an array.

72

What notation do we use to reference an array index?

java uses brackets [index]

(some languages use parenthesis)

73

What is an array initializer?

An array initializer is a java shorthand way to declare, create, and initialize an array in one statement.

elementType[] arrayRefVar = {v1, v2, v3..., vk};

int[] myList = {1, 2, 3, 4};

**Notice the word "new" is not used

74

What do we use a lot to process arrays? Why?

for loops.

1. all of the elements are of the same type

2. the size of the array is known

75

Name 9 ways to process an array with for loops

(pg. 227)

1. Initialize arrays with input values

2. Initialize arrays with random values

3. Display arrays

4. Summing all elements

5. Finding the largest element

6. Finding the smallest index of the largest element.

7. Random shuffle

8. Shifting elements (sometimes you want the elements to move to different positions)

9. Simplify coding (processing months, for example)

76

Describe a "for each loop."

The "for each" loop hides the iterator. That makes it not good for filtering, replacing elements, of iterating over multiple collections.

But it is excellent for nested loops:

for (Suit suit : suits)
for (Rank rank : ranks)
sortedDeck.add(new Card(suit, rank);

And it was made for iterating over arrays and collections.

Traditional:

for (int i = 0; i < arr.length; i++) {
type var = arr[i];
body-of-loop

For-Each:

for (type var : arr) {
body-of-loop

With numbers:

int[] ar = {1, 2, 3};
int sum = 0

for (int d : ar) {
sum += d;

77

What 5 things should we keep in mind when using a for each loop?

1. Only access. elements cannot be assigned, can't increment each element in a collection.

2. Only single structure. It's not possible to traverse two structures at once, eg, to compare two arrays.

3. Only single element. Use only for single element access, eg, not to compare successive elements.

4. Only forward. Can only move forward in single steps.

5. At least java 5. Don't use if you need compatibility with pre version 5 java

78

What is the off-by-one error?

The off by one error is when programmers mistakenly reference the first element in an array with index 1 instead of 0.

79

Where are arrays stored?

arrays are stored in a heap

80

If you pass an array to a method, what happens to the array?

If you pass a variable with a primitive value to a method, what happens to the variable with a primitive value?

pg. 238

The method takes the reference to the array, so whatever you do to the array in the method will be reflected outside of that method. Be careful.

The method takes the variable with a primitive value and works with just the value. It does not change the variable outside of the method as it does with arrays.

81

What is returned when a method returns an array?

A reference to the array is returned (it doesn't make a new array)

82

How do we create a variable-length argument for a method?

Java treats variable-length parameters as an array.

public static void(double... numbers) {
//do stuff
}

83

What is the best way to search an array for a particular element?

Binary search. pg. 246

The list must be ordered. It should be ascending. what half is the key in? keep cutting until you find it.

84

What java class contains useful methods for common array operations?

The Array class

java.util.Arrays

sorting and searching

85

java.util.Arrays contains what kinds of common array operations?

sorting and searching

86

What does the "this" in a class mean?

"this" refers to the current object.

private int counter;

public Incrementor(int counter) {
this.counter = counter;

the this.counter means the counter variable defined in the class and the method argument counter is a local variable for the constructor.
Basically, it explicitly signals that you are using the variable of the current object. Improves readability.

part of professor's program, GenericMethod:

MAIN:
if (car.compareTo(list[i]) > 0) {
car = list[i];

CLASS METHOD:
public int compareTo(Car o) {
if(this.horsePower < o.horsePower) {
return 1;
} else if (this.horsePower > o.horsePower) {
return -1;
} else
return 0;
}

EXPLANATION:

we call the compare method in main. "car" is the object we want to compare with the object at "index i." So when this call goes to the method this.horsepower is "car," and o.horsePower is the object at "index i".

this.horsepower refers to the current object. o.horsepower refers to the argument object's horsepower.

"The keyword this refers to the calling object that invokes the method" pg. 373

ANOTHER EXAMPLE. pg. 373

f1 and f2 are objects of F.

private int i = 5;

public void setI(int i) {
this.i = i;

Invoking f1.setI(10) is to execute
this.i = 10, where this refers to f1

Invoking f2.setI(45) is to execute
this.i = 45 where this refers to f2

**Note, you can reference a hidden static field with the class name.

private static double k = 0;

public static void setK(double k) {
F.k = k;
}

Invoking F.setK(33) is to execute
F.k = 33 setK is a static method

87

name a common use of 2 dimensional arrays

store a table
store a matrix

88

how do we access an element in a 2 dimensional array?

row and column index

89

how do you declare a 2 dimensional array?

elementType[][] arrayRefVar;

matrix = new int[row_size_][index_size]

90

1 2 3
4 5 6
7 8 9

how do you access #6 from a 2d array?

[1][2]

row 1, column 2

91

what is a ragged array

each row in a 2d array is an array itself. rows can have different lengths, making the array "ragged."

92

how do we typically process 2d arrays

nested for loops

93

name 7 types "for loops" for processing 2d arrays listed by the text. 267

1. initializing arrays with input values
2. initializing arrays with random values
3. printing arrays
4. summing all elements
5. summing elements by column
6. which row has largest sum?
7. random shuffling

94

what happens when a 2d array is passed to a method

a reference to the array is passed, NOT the array

95

name a use for a multidimensional array

a multidimensional array, say, an array with 3 arrays, might be used to store students, each with five exams that have 2 parts per exam.

such a 3d array consists of an array of 2d arrays

96

what is a class?

a class is a template for objects. it defines the properties of objects and provides constructors for creating objects and methods for manipulating them

**a class is also a data type

97

what is an object?

an object is an instance of a class

98

how do you create an object?

use the new operator

99

what operator must you use to access members of an object through its reference varaiable

dot operator

100

what is a reference variable

a reference variable is used to store the reference of an object

Button b = new button();

b is the object of button
b is a reference variable of type button

101

can a static method be invoked without using instances?

yes

102

what does it mean for an object to have 'state' and what are 2 other words for it?

"properties"
"attributes"

think of state as characteristics. a dog has a height, color, breed, etc.

103

what defines the behavior of an object?

methods

104

what does a constructor method do?

it initializes an object

105

what condition must be met for a default constructor to be created automatically?

a default no arg constructor is only created automatically if no constructors are explicitly defined in the class

106

is an object created when you declare an object?

Circle mycircle;

No.

107

what operator must be used to create an object?

new

108

why might we just declare an object instead of creating one?

Circle mycircle;

this is for use with anonymous objects

109

why use an anonymous object? give an example

save memory. they die after use

In I/O streams and AWT, we use many objects only once. best to go anon to get rid of them

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

[inputstreamreader is the anon object]

g.setColor(new Color(100, 200, 80));

new Demo().display

110

best practice: what is the upper limit of anonymous object use?

1 time use is the best practice.

111

what is null

null is a literal for reference type

112

how do you get the garbage collector to take a reference variable away after you use it?

assign the value to null. the garbage collector will reclaim the space.

113

what is a visibility modifier?

visibility modifiers are used to specify the visibility of a class and its members

114

name java's visibility modifiers

public, private, protected