Java: Basic Concepts Flashcards Preview

Java: Basic concepts > Java: Basic Concepts > Flashcards

Flashcards in Java: Basic Concepts Deck (114):

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.


What is casting?

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


Java has two casting scenarios. What are they?

Upcasting and downcasting


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.


What is an implicit cast?

Instead of writing:

Object o = new Student();

We can use an implicit cast:

m(new Student());

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


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.


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]


What is a unary operator? Give example

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


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


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.


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)


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


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.


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)


What is a literal?

A literal is the value assigned to a variable.

double weight = 0.305;

the literal is 0.305


What are augmented assignment operators?

+= -= *= /= %=


i += 8

i = i + 8

these are the same


Describe the char data type

a single 16-bit unicode character


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


What does \t do

inserts a tab in the text at this point


what does \b do

inserts a backspace in the text at this point


what does \n do

inserts a newline in the text at this point


what does \r do

inserts a carriage return in the text at this point


what does \f do

inserts a formfeed in the text at this point


what does \' do

inserts a single quote character in the text at this point


what does \" do

inserts a double quote character in the text at this point


what does \\ do

insert a backslash character in the text at this point


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


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


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;


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)


In what situations is a for loop best?

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

pretest loop


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


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


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


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


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) {
if (number == 10 | | number == 11)
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


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.


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.


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


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


Describe a void method

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


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


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: .


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


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):


*** 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.


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


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


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


Break down what this means:


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.


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..


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);


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

1. data fields
2. methods


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


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.


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."


Class: Cat

method: meow

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


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.


what is a class method?

a class method is a STATIC method


how do you call a class method?

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


Math.pow(3, 2.5);


how do you call an instance method?

You must invoke an instance method from an object using:





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


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.


What is the default value of a boolean instance variable?



What is the default value of a char instance variable?



What is the default value of a numeric instance variable?



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


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


Can a static method access instance members of the class?



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

static methods pg. 315


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


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


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.


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.


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.


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)


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


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


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


What is an array?

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


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.


What notation do we use to reference an array index?

java uses brackets [index]

(some languages use parenthesis)


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


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


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)


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.


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


for (type var : arr) {

With numbers:

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

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


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


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.


Where are arrays stored?

arrays are stored in a heap


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.


What is returned when a method returns an array?

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


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


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.


What java class contains useful methods for common array operations?

The Array class


sorting and searching


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

sorting and searching


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:

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

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


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


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


name a common use of 2 dimensional arrays

store a table
store a matrix


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

row and column index


how do you declare a 2 dimensional array?

elementType[][] arrayRefVar;

matrix = new int[row_size_][index_size]


1 2 3
4 5 6
7 8 9

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


row 1, column 2


what is a ragged array

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


how do we typically process 2d arrays

nested for loops


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


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

a reference to the array is passed, NOT the array


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


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


what is an object?

an object is an instance of a class


how do you create an object?

use the new operator


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

dot operator


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


can a static method be invoked without using instances?



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


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


what defines the behavior of an object?



what does a constructor method do?

it initializes an object


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


is an object created when you declare an object?

Circle mycircle;



what operator must be used to create an object?



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

Circle mycircle;

this is for use with anonymous objects


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(;

[inputstreamreader is the anon object]

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

new Demo().display


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

1 time use is the best practice.


what is null

null is a literal for reference type


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.


what is a visibility modifier?

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


name java's visibility modifiers

public, private, protected