JAVA CLASSES

Ace your homework & exams now with Quizwiz!

How many times is sVATRate created when new objects are created if it is static?

Only one of sVATRate created ever, and each object references this state variable rather than having a new sVATRate created for each object

All value types

- byte - short - int - long - float - double - boolean - char

Method-local Inner Class

- can be instantiated only within the method where the inner class is defined.

this

-allows an object to refer to itself -the currently executing object

Public visibility

-anyone can edit variables anywhere -public methods provide services to clients

Class

-blueprint of an object -model or pattern from which objects are created

Static method

-can be called through class name -instantiation of an object is not needed to call method -cannot refer to instance variables since it was not called through an object, which holds those variables

Private visibility

-can only be accessed from inside the class -support other methods in the class (encapsulation)

nested classes

-class inside a class -nested class can use enclosed class's private variables but not vice versa

Interfaces

-class with abstract methods and constants (no code) -formal contract as to what a class must implement -semicolon after each method header, interface used in class line (public interface test) -class must implement interface in class line -ex. comparable (compareTo)

Objects

-contains states and behaviors -state = variables -behaviors = methods

Exceptions

-describes and unusual or erroneous situation -exceptions are thrown by a program, and may be caught by another part -stack-trace used to find errors -try{ statements} catch (name of exception){ statements}

message dialog

-displays output string

Instance data

-each instance of the object has its own version of the variable -variables declared at the beginning of the class -class declares type of data, but does not reserve memory -have default values

reference assignment

-for object references, assignment copies the memory location (copies pointer) -will delete any object not being pointed to (trash collector) -if you change one, both are changes -for primitive data types, a copy of the value is made

Objects as parameters

-for primitive data types, copy of actual parameter is stored into the formal parameter -when objected is passed to a method, actual and formal parameters become aliases (copy of pointer)

Static Nested Class

-is a nested class which is a static member of the outer class. -can be accessed without instantiating the outer class, using other static members. -does not have access to the instance variables and methods of the outer class.

Constructor

-method that has the same name as the class -no return type Public name (parameters)

Two expectations for constructors

-name must be same as its class name -must have no explicit return type

input dialog

-presents a prompt and single input text field

confirm dialog

-presents user w/ simple yes-or-no question

Overloading

-processing of using same method for multiple methods -parameters (signatures) are different

Void

-return type of a method -doesn't need to return anything

Aliases

-two or more references that refer to the same object

null

-variable does not currently point to anything -an object declared at class level (instance variable) is automatically initialized to null

Static variable

-variable shared among all instances of a class -objects share same variable -changed for one=changed for all

What is necessary in a class?

-variables and methods -constructor -getters and setters -toString

Inner Class

-write a class within a class. -can be private and once you declare an inner class private, cannot be accessed from an object outside the class.

exp of abstraction

-you understand its external behavior -you dont understand its inner details and you dont need to

constructor

A class contains constructors that are invoked to create objects from the class blueprint. Constructor declarations look like method declarations—except that they use the name of the class and have no return type. For example, Bicycle has one constructor: public Bicycle(int startCadence, int startSpeed, int startGear) { gear = startGear; cadence = startCadence; speed = startSpeed; }

instance method

A non-static method that has access to this and the instance variables.

You cannot begin variable names with what?

A number . Ex) 5data

Math.min()

Returns the smallest parameter Ex int m = Math.min(10, 20); // 10

Getter

Returns value

Math.ceil()

Rounds to nearest integer up when using double

Math.max()

Rounds to the nearest integer down when using dobule

Protected

Same as default, with the addition that subclasses can access protected methods and variables of the superclass (learn more about subclasses and superclass later)

"he"

String s1 = "The Beatles"; String s2 = s1.substring(1, 3)

11

String s1 = "The Beatles"; int len = s1.length()

Create a string declaration assigning the string "Hello" to the variable value.

String value = "Hello";

Examples of immutable types in java

String, Integer, Float, Double, Byte, Character, Long

API

Application programming interface, a collection of packages that comes with most IDE's

Attributes

Characteristics in an object. For example, a car can be red or blue

T/F arrays cannot contain primitive types

F

T/F default constructor is generated by the compiler even when another constructor defined in the class

F

T/F if a class is immutable, it needs setters

F

T/F static members can be associated with any specific instance of the class

F

T/F private variables can be seen in methods from other classes

F

T/F static variables can only be used in static methods

F

T/F boxing is the automatic conversion of a private variable to a wrapper class

F, it is the automatic conversion of a primitive type to the corresponding wrapper class

Method

Synonymous for behavior Coding def: a collection of statements that are grouped together to perform an operation

This class contains methods and objects that perform system level tasks.

System

Scanner objects work with...

System.in

Write the Java code to print the line "Hello World!" out to the system.

System.out.println("Hello World!");

T/F ArrayLists can contain other ArrayLists

T

T/F arrays can contain ArrayLists

T

T/F arrays can contain other arrays

T

T/F encapsulation restricts access to data within a class

T

T/F if there is no constructor defined, the compiler generates a default constructor

T

T/F a constructor can assign a value to a constant (variable defined final) with all variables

F, only for class variables. not variables defined within the constructor or within already created objects

T/F it is okay to have two constructors with the same name but different parameters

T

T/F the default equals method checks memory location

T

T/F you can make a class immutable by setting the variables to final

T

T/F Encapsulation controls access to variables (ie private vs public) using getters and setters

T

T/F Every class is a subclass of another class

T

T/F a constructor will control how the instance variables are initialized

T

The default constructor sets all of the class' boolean fields to?

False

Class

Templates for a set of objects, classes represent various concepts.

What does a driver program do?

Tests the capabilities of other classes.

What does a class's interface provide?

The information needed to use a class without revealing anything about its implementation

What are members of a class?

The instance variables and methods

How would you encapsulate data?

Through getter and setter methods

identical

Two values that are the same. In the case of objects, two variables that refer to the same object, also called aliases

How many classes are created when this program is compiled and what are the names of them?

Two, Vehicle.class and VehicleDemo.class

How many parameters does isFact have?

Two, a and b

Which lines represent the main program?

Line 6 and onwards

What does the dot operator do?

Links the name of an object with the name of a member.

What are static variable allowed to use?

Local variables and static variables...can't use anything that is instance-specific

What method is the starting point for any program?

Main method

Differences between a typical functional programming language and a typical imperative programming language

Nature of functions, type inference, classes and objects vs no units, specifying what to do vs how and what to do

How does Java have mutable state?

You can change the values of state after you've initialised it

Q: How would you describe the difference between this() and super()?

You can use this() for invoking the constructor of the class while super() helps to call the super class constructor.

Q: What difference you see between superclass and subclass?

You can use this() for invoking the constructor of the class while super() helps to call the super class constructor.

code reuse

You can write a method once, and use it multiple times, without having to rewrite the code each time

Encapsulation

a mechanism of wrapping the data (variables) and code acting on the data (methods) together as a single unit

accessor

a method that lets clients examine object state exp: distance, distance,FromOrigin

a module is a +++++ not a ++++++

a module is a partial program, not a complete program

java.util

a package of classes

a variable holds the object, or a reference to an object?

a reference to an object

module

a resable piece of software stored as a class

a void method does not need to contain?

a return statement

object

a runtime entity that contains data and responds to messages

class

a software package or template that describes the characteristics of similar objects

local variable

a variable defined inside a method, or block

field

a variable inside an object that is part of its state -each object has its own copy of each field

reference

a variable that ism declared to have a class type is a ____ to an object

reference variable

a variable which has a primitive type contains a value of that type

constructor syntax

access specifier(PUBLIC) -> name of class -> list of parameters including data type { constructor body }

method syntax

access specifier(public or private) -> return type of variable -> method name -> list of incoming variables including their type { method body }

instance field syntax

access specifier(public or private) -> type of variable -> name of variable

accessors

accesses an object and returns information about that object without altering the object

3 types of methods

accessor, mutator, helper

methods

actions of the object (bank account = withdrawals, deposits)

point method: translate(dx,dy)

adjusts the point's x and y by the givenamounts

helper method

aids the program in solving problems... usually done behind the scenes

server class

all the methods/data that is stored

private

can only be used inside that class

identity

distinguish from other objects in memory, as handled by the JVM

declaring a variable (does/does not) create an object

does not

immutable means

does not change

instance method(or object method)

exits inside each object of a class and gives behavior to each object

A constant made up of variables, operators, and method invocation

expression

What syntax is used to get one class to inherit data and behavior from another class?

extends <a class>

For loop syntax

for (int i=0; i<8; i++){ // or can decrement counter } int j=0; for(; j<8; j++) { // can initialise variable before for }

Looping over array with for loop

for (int i=0; i<arr.length; i++){ } for (String element : arr){ // for each element in array of type String[] }

Creating Format Strings

format(), that returns a String object rather than a PrintStream object - to create a formatted string that you can reuse, as opposed to a one-time print statement.

example of? class MountainBike extends Bicycle{ //new fields and methods defining the subclass MountainBike }

inheritance

constructors

initialization of an object (bank account = 2233, $600)

static variable, class variable

contains a value that is shared by all instances of the class

What syntax do you use to skip the current iteration in a loop?

continue;

When to use lambda expressions

Use it if you are encapsulating a single unit of behavior that you want to pass to other code, or if you need a simple instance of a functional interface and none of the preceding criteria apply

cos()

cosine

When to use local class

Use it if you need to create more than one instance of a class, access its constructor, or introduce a new, named type

When to use anonymous class

Use it if you need to declare fields or additional methods.

To return a string with an object, you would...

create toString method

What does this code do? String [] names = new String[20];

creates an array of 20 strings

Instantiating an object

creating object of a class, use the keyword new

constructor

initialize the instance variables of a newly instantiated object, only activated by keyword "new," all must have the same name as the class

Constants must be _____ by the program before being used.

initialized

What does the second line of code do? PairOfDice dice; //declares a variable of type PairOfDice dice = new PairOfDice();

initializes the object's instance variables and returns a reference to the object

constructor

initializes the state of new objects

Getter syntax

public string getVariable() The first letter of the variable is capitalized

Setter syntax

public void setVariable(String something)

How does the keyword super work with constructors?

super(<parameters>) at the beginning of the corresponding constructor in the subclass

How does the keyword super work with methods other than constructors?

super.<method name>(<parameters>)

default constructor

takes no arguments and provides reasonable initial values for an object

Math.pow()

takes two parameters and returns the first parameter raised to the power of the second parameter ex double p = Math.pow(2, 3); // 8.0

import java.util.Scanner;

tell java that the Scanner class will be used

access specifier

tells which other methods can call this method (public, private, static)

garbage collection

the JVM process of keeping track of which objects need to be stored and which can be deleted

outer class

the class that holds the inner class

methods

the code to manipulate the object data

encapsulation

the combining of data and behavior into a single software package

object reference

the identifier of the object

After executed, what does "dice" refer to? PairOfDice dice; //declares a variable of type PairOfDice dice = new PairOfDice();

the newly created object

'this' keyword refers to what?

the object being created

this

the object is an implicit parameter for the method and is referred with this keyword

implicit parameter

the object on which an instance method is called

In a JUnit test, what does the code below expect? assertFalse(myMethod(5, 15));

the output of the method to be false and triggers an error otherwise

state

the particular value of a instance variable at any moment which changes in response to messages sent to the object

turn(degrees)

the pen adds the indicated degrees to its current direction. positive degrees counterclockwise, negative degrees clockwise

home()

the pen jumps to the center of the graphics window without drawing and point north

down()

the pen lowers itself to the drawing surface

move(distance)

the pen moves the specified distance in the current direction. Can be integer or floating point. expressed in width x height

up()

the pen raises itself from the drawing surface

instantiation

the process of creating a new object

What does the blank in public ______ setName(String name){} represent

the return type -could be void or a type(double,string,int,point,etc)

what must be the name of the constructor?

the same name of the class in which it is defined

String

the second version finds the first occurrence of a

you can define constants with?

the static modifier and the final modifier

interface

the way for the client to interact with the server

two

there are ___ versions of indexOf

public methods

these are accessible to all client programs

private methods and variables

these can only be accessed by methods of that class

default constructors

these constructors have empty parameter lists

String Length

length() method : returns the number of characters contained in the string object.

toLowerCase

method returns a new String containing the original characters, but with all letters in lower case

visibility, return type, name, parameter

method structure

a reference to the current object

this

What modifiers can be used on a constructor definition?

three access modifiers: public, private, and protected

used to throw an exception from within a method. When a throw statement is encountered and executed, execution of the current method is stopped and returned to the caller

throw keyword

dereference

to access data or methods of an object with the dot notation, such as s.length

Strings

treated as objects.

Method syntax

visibility modifier-return type-name-(parameters) -unless void return type, return must occur

method declared ____ does not return a value

void

Formal parameter

what is needed for method to proceed

Actual parameter

what is put in it

.equals()

what method do we want to use when comparing strings?

client class

what the user sees

return type

what type is returned, void means nothing

null pointer exception

when a program attempts to run a method with a null object

the reference changes

when you reassign a string variable, what happens

instance fields

where an object stores its data

Math class

which provides predefined methods for mathematical operations

While loop syntax

while (boolean_expression){ }

? operator

works as an if-then (someCondition ? valueTrue: valueFalse)

points store

x,y daya

Are strings objects?

yes

Can a constructor have a list of formal parameters?

yes

correct? if (std == null)

yes

new

you can instantiate an object by using the keyword

a class combines

• Data — identifiers that hold values. Data can be any type (int, float, String, etc.) • Methods — code that manipulates the data

nextBoolean()

returns the next input as a boolean

nextByte()

returns the next input as a byte

nextDouble()

returns the next input as a double

nextFloat()

returns the next input as a float

nextLong()

returns the next input as a long

nextShort

returns the next input as a short

next()

returns the next token in the input line as a String

when asking the user for something

scanner

how to initialize a scanner

scanner input = new Scanner();

the java class library is a?

set of packages

toString()

A method that returns the value of the Integer as a String.

doubleValue()

A method that returns the value of the Integer as a double.

intValue()

A method that returns the value of the Integer as an int.

initalizing a string input

String name = input.nextLine();

super

We can invoke a constructor of the superclass using the "________" keyword.

Anonymous Inner Class

- An inner class declared without a class name - declare and instantiate them at the same time. -used whenever you need to override the method of a class or an interface.

String class

- immutable, so that once it is created a String object cannot be changed. - to make a lot of modifications to Strings of characters then you should use String Buffer & String Builder Classes.

Testing for equality

-== operator compares object references, are they pointing to the same thing, returns true if aliases -.equals() method does the same thing (unless redefines), also will check is string has same characters

Data scope

-Data declared in the method can only be used in that method, class level can be used in other methods in the class -Data declared within a method (local data) have no default value

Where does the turtle graphics pen originate at?

0,0 cartesian, down, pointing north

primitive type

1 box of data that contains a value

Which lines represent the class?

1 through 5

Interfaces are useful for:

1- Declaring methods that one or more classes are expected to implement. 2- Capturing similarities between unrelated classes without forcing a class relationship. 3- Determining an object's programming interface without revealing the actual body of the class.

Q: Explain the difference between function overloading and overriding?

1- Overloading talks about the relationship between methods of the same class whereas the overriding focuses on the relationship between a superclass method and subclass method. 2- Overloading doesn't impact the inheritance from the superclass whereas the overriding impedes inheritance from the superclass. 3- In overloading, you have different methods sharing the same name whereas in overriding, the methods in subclasses replace the superclass versions. 4- Overloading requires the methods to be implemented with distinct signatures whereas overriding limits to use the same markup.

What are the two rules to remember when using static variables

1. Class methods can reference only the static variables and never the instance variables 2. Instance methods can reference static and instance variables

What are the two benefits to using an interface name?

1. Methods that use interface types are more general, in that they work with any classes that implement the interface 2. It's easier to maintain a program that uses interface types

Why do we declare abstract methods?

1. The abstract class which they are declared implements an interface, but the implementation of these methods is deferred to concrete classes 2. Even if there is no interface, these methods must be implemented in all subclasses, so declaring them abstract enforces this

naming conventions (2)

1. class names start with an uppercase letter 2. capitalize internal words

shadowing

2 variables with same name in same scope

paralell arrays

2+ arrays with related data at same indexes

What are the four numbers outputted? public class QuizClass { public static int num1; public int num2; ... public static void main(String [] args) { QuizClass a = new QuizClass(); QuizClass b = new QuizClass(); a.num1 = 1; a.num2 = 2; b.num1 = 3; b.num2 = 4; System.out.println(a.num1 + " " + a.num2 + " " + b.num1 + " " + b.num2); } }

3, 2, 3, 4 since num1 is static and will be the same for all instances

How many objects of type A will be created? pubic class A{ public A friend; public A(){ friend = null; } public A (A other){ friend = newA(other.friend); } public void setFriend(A newFriend){ friend = newFriend; } A firstVar = new A(); firstVar.setFriend(new A()); A secondVar = new A(firstVar); }

4

Between which lines could you insert a method?

4 and 5

Given the piece of code shown below, in which line(s) is (are) an object(s) created? 1 class Vehicle { 2 int passengers; 3 int fuelcap; 4 int mpg; 5 } 6 class VehicleDemo { 7 public static void main(String args[]) { 8 Vehicle minivan = new Vehicle(); 9 Vehicle truck = new Vehicle(); 10 int range;

8 and 9

Nested classes are divided into two types

:Non-static nested classes − These are the non-static members of a class. :Static nested classes − These are the static members of a class.

constructor name

= to the class name

Why should a programmer use the method equals instead of the operator == to compare two objects for equality?

== is too restrictive. In cases where two distinct objects

What are the two ways to compare objects for equality?

== or the instance method equals

client

A class that uses objects defined in another class.

What is a constructor and what is it used for?

A constructor is a pieces of code within a class. It must have the same name as the class, and it's used for setting initial conditions on variables, or for start up conditions on a program.

Integer(String s)

A constructor that constructs an Integer object that represents the specified String value as an int.

Integer(int n)

A constructor that constructs an Integer object that represents the specified int value.

Package

A group of similar types of classes

Interfaces

A java interface specifies the set of methods available to clients of a class. An interface provides a way of requiring a class to implement a set of methods and a way of informing clients about services regardless of implementation detail

getter

A method that returns the value of an instance variable.

instance

A member of a class. Every object is an instance of some class.

compareTo()

A method that accepts an Integer argument and returns 0 if the Integer is equal to the Integer argument, a value less than 0 if the Integer is numerically less than the Integer argument or a value greater than 0 if the Integer is numerically greater than the Integer argument.

equals()

A method that accepts an Integer argument and returns true if the argument is an Integer object that contains the same int value as this object.

setter

A method that assigns a value to an instance variable.

What is a final method?

A method that cannot be overriden by a subclass

modifier method

A method that changes the state (instance variables) of an object.

Constructor for a class

A method that gets called when the object is constructed to initialise the state of the class for the new object in a convenient way

mutator

A method that modifies an object's state exp: setLocation, translate

constructor

A special method that initializes the instance variables of a newly-constructed object.

Integer.MAX_VALUE

A static field that represents the maximum possible value an int can contain.

Integer.MIN_VALUE

A static field that represents the minimum possible value an int can contain.

pure method

A static method that depends only on its parameters and no other data.

Q: Describe the difference between a Sub-Class and an Inner Class?

A subclass is a class which gets inherited from another class termed as super class. It can easily access all public/protected methods and fields of its superclass. Inner class is a class which gets cradled within another class. An Inner class can access all variables and methods provided by the outer class.

data encapsulation

A technique for bundling multiple named variables into a single object.

classes

A template for creating objects of a given type

What is an argument? For the code below, give an example. What does the program do? class Fact { boolean isFact(int a, int b) { if( (b % a) == 0) return true; else return false; } } class IsFact { public static void main(String args[]) { Fact x = new Fact(); if(x.isFact(2, 20)) System.out.println("Yes it is"); if(x.isFact(3, 20)) System.out.println("this won't be displayed"); } }

A value(s) passed to a method. 3, 20 Decides if the first number is a factor of the second

Default

A variable or method declared with no access control modifier is available to any other class in the same package.

Implementation of an abstract method

Abstract methods are a means of requiring certain behavior in all subclasses

Private

Accessible only within the declared class itself

Protected method

Accessible to a class's descendants, but not to any other classes in the hierarchy

Class method

Activated when a message is sent to the class rather than to an object

one

All Java programs consist of at least ____ class.

What is the role of the visibility modifier protected in a class hierarchy?

Allows subclasses in hierarchy to access instance and class variables or methods or superclasses without allowing other clients in the system to access these items

instance variable

An attribute of an object; a non-static variable defined at the class level.

What is an object?

An instance (copy) of a class

More on interface

An interface by definition has all public members without any implementation. While an abstract class may group different flavors of class members like private, protected, etc. but has at least one abstract method.

Q: What difference you see between an Abstract class and an Interface?

An interface by definition has all public members without any implementation. While an abstract class may group different flavors of class members like private, protected, etc. but has at least one abstract method.

Q: What is an interface and why is it used?

An interface is similar to a class which may contain method's signature only but not bodies, and it is a formal set of method and constant declarations that must be defined by the class that implements it.

What are the two ways that the + operator can be used?

As a concatenation operator and as an addition operator

As Java and most imperative languages don't have type inference, what do we need to do as a programmer?

Assign every value a type when declaring that value, and specify every function's return type and the types of each of a function's arguments

While naming variables...

Case sensitive, constant variables are all caps and underscores, $ may be used.

Instance Variable

Belongs to an object and is allocated storage when the object is created

any group of zero or more statements between braces

Block

What will this output? Person[] people = new Person[3]; people[0] = new Person("Bob"); people[1] = new Person("Alice"); people[2] = new Person("Jane"); // make a copy Person[] peopleCopy = new Person[3]; for (int i = 0; i < 3; i++){ peopleCopy[i] = people[i]; } // now I can change some names people[2].setName("Jane Doe"); people[0] = new Person("Michelle"); System.out.println(peopleCopy[0] + ":" + peopleCopy[1] + ":" + peopleCopy[2]);

Bob:Alice:Jane Doe

How can a class extend its inherited characteristics?

By adding instance variables and methods and by overriding inherited methods

Scope of a variable declared as a method parameter?

Called a parameter variable and like a local variable it is visible only within that method.

static variables, variables that do not change

Class variables

template

Classes are a _________ (or blueprint) used to create specific objects.

What is the difference between a class and an object?

Classes define what properties and procedures each object of the type should have, while each object is a specific implementation with particular values

Describe a hierarchy

Classes inherit the instance variables and methods of the classes above them

What are concrete classes?

Classes that extend abstract classes and are already instantiated

encapsulation

Combining an object's data and methods into a single unit called a class

Identifiers that can hold only a single value

Constants

We can use the this reference to ___.

Construct additional constructors efficiently by making calls to another constructor.

The String object is the only object that can be declared without using a _____.

Constructor

What happens at run time when a method throws an exception

Control is passed immediately to the calling method and from there goes on up the call chainto the main method, where the JVM halts execution with a trace of this call chain

How can youobtain a true copy of an object?

Create a new instance of that object's class and then cop-y the original object's instance variables to the new object's variables.

constructors

Creates an object of the class

What two items are used to cause your method to end?

Curly bracket or return

Hiding internal State and requiring all interaction to be performed through an object's methods

Data encapsulation

The __________ is a constructor with no parameters.

Default constructor

shadowing

Defining a local variable or parameter with the same name and type as an instance variable.

Behavior

Dependent on the object type

Postconditions

Describe what will result if the preconditions are satisfied

Class

Describes what an object will be. It is a blueprint, description, definition of an object

What would be the return type of the square root function you used before?

Double

Name 4 advantages of using static methods

Easier to debug (only depends on static state) Self documenting Groups methods that are related in a class without requiring an object The compiler can produce more efficient code since no specific object is involved (i.e. don't have to define an object first to use these methods)

More on abstract

Every abstract class must provide an instance method that defines its default behavior. While in an Interface, only the declaration of constants and instance methods is permissible, you can't implement the default behavior, and all methods are abstract by default.

What are the differences between functions in ML and functional languages and functions (strictly speaking procedures) in imperative languages, including Java?

Functions in ML don't have side effects whereas functions in imperative languages can use/alter larger system state (are procedures), procedures in OOP languages can have no arguments and return nothing (void) whereas functions in ML must have arguments and return a result that is only dependent on the inputs

Describe the difference between functional and imperative languages in terms of the nature of functions

Functions in a functional language have at least one input argument and must return a value, which is the direct result of operations on the inputs, whereas in imperative languages, functions (procedures) can take no arguments, have side effects (alter state initialised outside the function) and return nothing

aliasing

Having two references for the same object. This causes unintended problems

Three dimensions in object oriented

Identity Attributes Behavior

hides

If a subclass defines a static method with the same signature as a static method in the superclass, then the method in the subclass _______ the one in the superclass.

null reference, null pointer

If an object is uninitialized

When can related classes be used interchangeably in a program?

If they have the same interface

Two examples of a control flow statement

If-Then, Switch

What are the four ways in which methods in a subclass can be related to methods in a superclass?

Implementation, extension, overriding, and finality

How does Java organize classes?

In a hierarchy

How can interfaces be organized?

In an inheritance hierarchy

What is the difference between functional and imperative programming languages in terms of flow control?

In functional flow control is mainly through function calls (incl. recursion) whereas in imperative its mainly through loops, conditionals and method calls.

What is the difference between functional and imperative programming languages in terms of what you specify to the compiler?

In functional languages (subset of declarative), you tell the compiler what you want achieved by giving an example (i.e. tell the compiler what to do but not how), whereas in imperative you specify exactly how you want the desired result to be achieved.

The creation of sub classes using the "extends" keyword

Inheritance

Q: What do you know about anonymous and inner classes?

Inner class- are the ones having their definition within other classes, including those defined in methods. These can assume any accessibility including private, public, etc. Anonymous class- It is a class which has its definition inside a method with no name. You can instantiate or declare it in the same place, and it doesn't support explicit constructors.

non static variables, variables that change

Instance Variables

Objects

Instance of a class

What are the two basic parts of a class?

Instance variables and methods

Q: Are there any performance implications of Interfaces over abstract classes, if yes then specify?

Interfaces require additional indirections to find methods in the implementing class. This behavior makes them slower than abstract classes. Another fact that a QA engineer should know that a class can only extend a single abstract class whereas it can implement multiple interfaces. Also with interfaces, one has to address all of its methods which lead to extra efforts while developing an automation framework.

What is a class?

It is a template that defines the form of an object. It defines the data (variables) and code that acts on the data.

Why can't you specify a return type for a constructor?

It is called using the new keyword, which must return a reference to the newly constructed object

If this is used in a constructor, _____.

It must be the first statement.

What does the real power of object-oriented programming come from?

Its capacity to reduce code and to distribute responsibilities for such things as error handling in a software system

What does each object have?

Its own set of instance variables

java virtual machine

JVM

If you don't specify a constructor for a class, what happens in Java?

Java fills in a default constructor for you which takes no arguments and does nothing, but allows you to make objects of that class type.

final

Keeps a variable constant, any attempt to change it will cause an error ex. class MyClass { public static final double PI = 3.14; public static void main(String[ ] args) { System.out.println(PI); } }

To make a class immutable, what must you do to state that isn't primitive (i.e. accessing that states copies the reference rather than the actual value) or immutable (i.e. that state can change)?

Make a deep clone when accessing that state (i.e. in get method, return new date () / create entirely new array with same values as old one), and make a deep clone when setting that state (i.e. in constructor, create a new date() object

How would you make a mutable class immutable?

Make all state private and possibly final (so no can access state and change it); make all methods final (for weak immutability, i.e. can't change behaviour of class A but can extend behaviour through another class B that extends A) or make class final (for strong immutability i.e. can't extend class A); if a field isn't primitive or immutable, make a deep clone on the way in and the way out; make sure no method tries to change any internal state

What is the effect of polymorphism?

Makes classes easier to use because programmers need to memorize fewer method names

The switch statement in Java is efficient for what?

Making selections.

What is an overloaded method?

Many methods of the same names but of different return types and parameter lists.

When a variable references an object, it contains the ____.

Memory address of the object's location.

What is another name for the code contained within a class?

Method

overloading arguments

Method ____________ is having two or more methods in the same class with the same name but different _______________.

accessor methods

Methods used to obtain information about an object

Polymorphism

Methods with similar function in different classes that are given the same name

How is type inference a difference between functional and imperative programming languages?

Most functional languages have type inference whereas most imperative languages don't (have to specify types when declaring values, return type and type of arguments in functions)

Special properties that constructors have include:

Must have the same name as the class, have no return type (not even void) and may not return any values, and are typically public.

Abstract classes

Must never be instantiated. Their sole purpose is to define features and behavior common to their subclasses

Do parameters within a method have to be of the same type?

No

Does the class in the code above have a method associated with it?

No

If a class is immutable, is it necessary to perform a deep copy in the copy constructor?

No

Should a class have many themes?

No

Is there any point in copying/cloning an immutable type?

No - value can't be changed anyways

Does this code print out the line? Date taxDay = new Date915, "April", 2016); Date alsoTaxDay = new Date(15, "April", 2016); if (taxDay.equals(alsoTaxDay)){ System.out.println("They are the same"); }

No, because the default equals method does not check the value, it checks if the two live at the same memory location

Correct? ArrayList<char> lalaString = new ArrayList<char>();

No, primitive types cannot be stored in array list. Should be character instead

Correct? public class Point { public int x; public int y; public Point(){ x = y = 0; } public static int getX(){ return x; } public static int getY(){ return y; }

No, static methods cannot access class members

How many parameters does your method have?

None

Comment on the following two functions: public int helloworld(int a, int b) {...} public float helloworld(int a, int b) {...}

Not valid overloading of functions as functions of the same name must have different arguments at least and different return type is optional

The default constructor sets all of the class' reference variables to?

Null

A class that is not explicitly a subclass is automatically a subclass of what class?

Object

What class is not a subclass of any other class?

Object

What does OOP stand for?

Object Oriented Programming.

OOP

Object-Oriented Programming

What is the general form of the dot operator?

Object.member

What is immutable state?

Once it is set, the state cannot be changed (i.e. is constant)

What is a protected variable?

One that is accessible throughout the defining class and any of its subclasses

instance methods

Operates on individual objects of a class

Why do you want to make a deep clone when setting non-primitive, mutable state in a constructor of an immutable class?

Otherwise if you pass in a reference to another object of the same type as that state into the constructor, the reference will be copied across for that new object, so if you change the value stored at the original reference, the object's state will be changed as well as it points to this same reference. (not immutable)

Why do you want to make a deep clone when getting non-primitive, mutable state from an object which is an instance of an immutable class?

Otherwise you'll get the reference to that state (and could store without using new so reference is copied across), and if you then decide to change what you got saved under a new identifier name, you'll change the state for the object as well (from the class, so class not immutable). So you want to get deep clone so any changes made don't happen to original class's state.

What is Java's closest thing to polymorphism (writing one function that can be applied to multiple types), other than Generics?

Overloading

What is this an example of: public myfun(int a, int b) {...} public myfun(float a, float b) {...}

Overloading functions

public class PairOfDice { public int die1; public int die2; public _______(int val1, int val2){ die1 = val1; die2 = val2; }

PairOfDice

"args" the main method declaration

Parameters

In which two ways can the term interface be used

Part of the software system that interacts with human users and i a list of a class's public methods

What are the names of the instance variables in this class?

Passengers, fuelcap, mpg

static methods

Performs an operation for the entire class, not its individual objects

class

Previously, we defined a class as a collection of related methods. Now you know that a class is also a template for a new type of object.

These variable actually contain the value that they have been assigned.

Primitive variables

Inheritance

Provides a mechanism for reusing code and can greatly reduce the effort required to implement a new class

If more than one class is in a source code file, only one of them may be ______?

Public

Boolean

Returns possible values, true or false

Objects are ______ by variables.

Referenced

override

Replacing a default implementation of a method, such as toString.

What does a constructor in a UML not contain?

Return type

State the rules for passing a parameter of one class to a method that expects a parameter of another class

Same as the rule for assignment, the class of the actual parameter must be the same as or less inclusive than the class of the formal parameter

Two things to note about constructors

Same name as the class No return type

Object declaration syntax

Scanner in = new Scanner(System.in())

Provide an example Scanner statement:

Scanner keyboard = new Scanner (System.in);

setColor(aColor)

Sets the pen's color to aColor

Setter

Sets value

What is a key point for a well designed class?

Should define one entity (concept)

The this reference is ____.

Simply a name that an object can use to refer to itself.

object

Something that has both state and behavior - an individual instance based on a template

Preconditions

Specify the correct use of a method

Q: What is an abstract class and why is it used?

The abstract class serves as a template, and you can't instantiate it. It may contain static data, and you've to extend it to make it functional. Also, you must note that any class which has an abstract method automatically turns itself abstract.

What are primitive types?

The built in types that form the building blocks for more complicated types

Public

The class is accessible by any other class.

How is the class variable different from the instance variable below? public class Bicycle { private int cadence; private int gear; private int speed; //add inst var for the obj ID private int ID: //add class var for # Bicycle obs instantiated private static int numberOfBicycles = 0; ... }

The class variable is not related to any individual object, but to the class as a whole. It is related to all Bicycle objects. the ID number instance variable is related to one specific individual object.

What are instance variables?

The data members

Reference Types

The identity of the object and the fact that there can be multiple references to the same object are issues that arise when comparing two objects for equality and when copying an object

Finality

The method in the superclass is complete and cannot be modified by the subclasses = final

setDirection(degrees)

The pen points in the indicated direction

information hiding

The practice of making instance variables private to limit dependencies between classes.

scope

The region in which that variable or method is visible and can be accessed.

Dependency

The sender object's class depends on the receiver object's class

Overriding

The subclass method does not invoke the superclass method, instead, the subclass method is intended as a complete replacement of the superclass method

The method of a class are what?

The subroutine.

What happens when an object is assigned to a variable?

The variable contains a reference to the object

What is a parameter?

The variable that receives the argument (numbers).

How do the contents of the variables of minivan compare to the contents of the variables of truck?

They are independent of each other

What is static used for?

To associate state with a class, or in the case of methods, restrict the methods to only use local or static variable

What is the modifier static used for?

To designate class variables and methods

The word static can be used to do what?

To get a subroutine to work on its own within your program.

equivalent

Two objects that are "equal" but not necessarily identical, as defined by the equals method.

What can an interface never contain?

Variables

Write a piece of code that creates an instance of Vehicle called sportscar

Vehicle sportscar = new Vehicle();

What's the name of the class in the code above that represents the main program?

VehicleDemo

Class syntax

Very beginning! public class (name class here) {

Scope of a variable declared inside a method?

Visible only within that method and called a local variable

Scope of a variable declared inside the class but not in a method?

Visible to all methods of the class and called an instance field

What is the return type of the method you just wrote?

Void

Write a method called range that computes and prints out the range of the vehicle within the method itself.

Void range() { System.out.println("Range is " + fuelcap * mpg); }

When is an instance method activated?

When a message is sent to the object

Exceptions for error handling

When a method's preconditions are violated, throw exceptions to catch the errors, thereby halting program execution at the point of the errors

Static variables and methods

When information needs to be shared among all instances of class, that information can be represented in terms of static variables and it can be accessed by means of static methods

When should a method thrown an exceptions?

When its preconditions are violated

subclass

When overriding a method, the entire method signature must be the same. Except that the return type may be a ________________ of the original return type.

What is a side effect?

When state outside the function/procedure being called is changed

Q: What if you declare a class w/o any access modifiers, where can you use this class in your program?

When we don't specify any access modifier for a class, then Java assign package level access to it. It implies that you can access such a class from other classes and interfaces within the boundary of that package.

Reference variable

When you create an object using the constructor

What is overloading a function?

When you have functions with the same name but different arguments and maybe even a different return type (but NOT just a different return type)

Where does execution resume after a call to a method?

With the line of code following the call

Can a class implement more than one interface?

Yes

Correct? public class QuizClass { public int x; public static String text; public int square (int x) { return x * x; } public String getName() { return text; } }

Yes

Can the parameter-list for a constructor be empty?

Yes if the constructor has no parameters

Correct? public class Point{ public final int x; public final int y; public Point(int newx, int newy){ x = newx; y = newy; } }

Yes, a constructor can assign value to a final/constant

Is the return type of a method important?

Yes, boolean, int, and double can not mix

Correct? public boolean equals(Date otherDate){ if (day == otherDate.getDay() && month.equals(otherDate.getMonth()) && year == otherDate.getYear()){ return true; } else{ return false; } }

Yes, use .equals to compare Strings and use == to compare integers

The default constructor sets all of the class' numeric fields to?

Zero

Constructors

____________ are NOT inherited by a subclass. But they can be invoked.

reference type

a box that contains a pointer to an object

nested class

a class within another

What is PairOfDice()? PairOfDice dice; //declares a variable of type PairOfDice dice = new PairOfDice();

a constructor

abstraction

a distancing between ideas and details -we can use objects without knowing how they work

private fields

a field that cannot be accessed from outside the class

Packages

a group made up of similar types of classes, along with sub-packages

Extension

a. the subclass method does not exist in the superclass b. the subclass method invokes the same method in the superclass and also extends the superclass's behavior with its own operations

object

an entity that combines state and behavior

an object

an instance of the class

an object is

an instance of the class

Instance members must be associated with ___

an object

instance of a class

an object in the class

classes declared and instantiated at the same time

anonymous class

fields

attributes of an object (bank account = bank account #, amount of money)

Class variable

belongs to a class, its storage is allocated at program startup and is independent of the number of instances created

Aggregation

between a container class and the classes of the object - has-a relationship

What are primitive types in Java?

boolean - 1 bit byte - 8 bits as a signed integer (-128 to 127) short - 16 bits as a signed integer int - 32 bits as a signed integer long -64 bits as a signed integer float - 32 bits as as floating point number double - 64 bits as a floating point number

helper methods

break a complex task performed by a method into subtasks

What syntax do you use to jump out of a for loop or while loop?

break;

What are the signed primitives?

byte, short, int, long (i.e. all numbers apart from float and double so all integers basically)

Java compiles a program by turning it into

bytecode

mutator method

changes or alters the fields of an object (bank account = withdraw, deposit)

mutators

changes the state of an object by modifying at least one of its instance variable

'l'

char aLetter; String myName = "Charlie Brown"; aLetter = myName.charAt(4)

blueprint from which individual objects are created

class

static member variables and static member methods are sometimes called ___ variables and methods

class

class variables and methods belong to the ____ itself rather than to ____ of that class

class instances

Return value syntax

class MyClass { static int sum(int val1, int val2) { return val1 + val2; } public static void main(String[ ] args) { int x = sum(2, 5); System.out.println(x); } } //output 7 *Note: The return is saying to add val 1 and val 2 (parameters), as you can see in the next function starting with public, there is a variable with x and the sum has (2,5) those two will be added due to the method prior

Declaring a method

class Myclass{ static void sayHello(){ //sayHello is the method System.out.println("Hello World!") } public static void main (String [ ] args) { sayHello(); sayHello(); sayHello(); } } /* output: Hello World! Hello World! Hello World! */

Nested Classes Syntax

class Outer_Demo { class Nested_Demo { } }

class is visible to all classes everywhere

class declared with the modifier "public"

class only visible within its own package

class has no modifier (package-private)

name, instance variables, constructors, methods

class signature

a class can have multiple

constructors

methods

classes provide _____ that are used to extract data values from the class

How can you access a static variable?

classname.staticvariablename

public

client can see data

private

client cannot see data

Concatenating Strings

concatenating two strings , returns a new string that is string1 with string2 added to it at the end. - "My name is ".concat("Zara"); or - "Hello," + " world" + "!"

signature of a method

consists of the method's name and a list of the parameter types

Scanner scanInput; scanInput = new Scanner(System.in);

declare an instance of the scanner class and connect it to the keyboard

object, null

declaring a variable does not create an ____, reference values are initialized with the value ____

3 types of constructors

default, overloaded, copy (ALWAYS PUBLIC)

behavior

defined by methods of the objects class

Inner Classes (Non-static Nested Classes): 3 types

depending on how and where you define them. -Inner Class -Method-local Inner Class -Anonymous Inner Class

visibility modifiers

determine what the client can see: private or public

Driver program

drive other parts of programs

If an equals method has not been implemented, what will this code output? (assume class is called Car and constructor for make of the car has been implemented) Car firstCar = new Car("Dodge"); Car secondCar = new Car("Dodge"); System.out.println(firstCar.equals(secondCar));

false because the default equals method checks the memory location

order in code

fields constructors methods

Constants are declared using what keyword?

final

example of? static final double PI = 3.141592653589793;

final modifier

the value of this field cannot change

final modifier

accessor method

gets information to the user (bank account = get balance)

accessor methods are referred to as?

getter methods

encapsulation

hiding implementation detail for clients

whitespace character

how does scanner's next() method know where the String ends

point method:distance(p)

how far away the point is from point p

What statement must we declare in order to use the Scanner class?

import java.util.Scanner;

. operator

indicates that the accessor is a method of the class to which the object variable belongs

JUnit testing should be applied to

individual methods

An object created from a class is called an ______ of that class

instance

PlayerData class creates an object. that object is an ____ of the PlayerData class. name and age are ____ _____ in the object.

instance instance variables

methods that the object contains

instance methods

variables that the object contains

instance variables

public ____ getArea() { return width * height; }

int

each point object contains two pieces of data

int named x and int named y

What are the parameters of the constructor? public class PairOfDice { public int die1; public int die2; public PairOfDice(int val1, int val2){ die1 = val1; die2 = val2; } public void roll(){ die1 = (int)(Math.random()*6) + 1; die2 = (int)(Math.random()*6) + 1; } }

int val1, int val2

a group of related methods with empty bodies, uses "implements" method

interface

! operator

inverts the value of a Boolean

calling a method

invoking the code to perform a service for an object

toUpperCase

is similar toLowerCase, but returns the original string with all letters in upper case

java import for a scanner

java.util.Scanner

does not

just declaring a variable _____ create an object

like a class variable, but for only one method

local variables

scanner initalization goes in the

main method

instance variable

maintains information in an object

@param

marks a parameter of a method

@throws

marks an exception thrown by the method

@return

marks the returned value of a method

accessors

messages that access the object's state, used to see if a mutator works correctly

mutators

messages that change an object's state

subroutine

method

instance variable declared private is not visible from...

methods within other classes

Write a pieces of code that invokes the range method you wrote on minivan.

minivan.range();

setter method is also referred to as?

mutator method

mutator

mutator method is used to set a value of a private field. It follows a naming scheme prefixing the word "set" to the start of the method name.

class inside of another class

nested class

Objects are created with what operator?

new

What keyword do we need to instantiate an object and what does it return?

new, returns a reference to the newly constructed object

Can a constructor be declared static?

no

can a constructor return void?

no

Correct? public void myMethod(){ int x; if (x>10) { System.out.println("larger than 10"); } }

no because x was never initialized

Does the code below create a new object? public Date (Date oldDate) { this(oldDate.getDay(), oldDate.getMonth(); oldDate.getYear(); } assume Date method is defined earlier in code

no, because it is a copy constructor that sets the values of the current object being created

Will this return a String of the date? Date taxDay = new Date(15, "April", 2016); System.out.println("Tay day is " + taxDay);

no, it will print the location in memory where the object taxDay is stored

Correct? public class QuizClass{ int num; String text; public static void printNice() { System.out.println(text + " " + num); } }

no, text and num are not intialized

files

nstances of Scanner can be connected to other "things", such as ____.

what is an actual value stored in the variable?

null

point is an

object

Static variables are instantiated ____ per ____ not per object

once, not

instance methods

operates on individual objects of a class

a namespace that organizes a set of related classes and interfaces

package

name space that organizes a set of related classes and interfaces

package

when a method takes in something

parameter

formal parameters

parameters that are listed in a method's definition

actual parameters

parameters that are values passed to a method when it is invoked (arguments)

parameter

passes information to a method

block

piece of code enclosed in a { } pair. When exited, the memory for a local variable is automatically dumped

The out object contains what two methods?

print and println

point method:display

print the coordinates

To make data not seen outside the class, you declare it as ___

private

static field syntax

private static String bankName = "TD Bank"

main method

public static void main (String[] args){}

a class is a

program entity that represents either: 1. a program/ module 2. a template for a new type of object

object oriented programming

programs that preform their behavior as interactions between objects

object variables

provides a memory location to a specific object instance, and does not store the objects themselves

change using 'this' public class Point{ public int x = 0; public int y = 0; //constructor public Point(int a, int b){ x = a; y = b; } }

public class Point{ public int x = 0; public int y = 0; //constructor public Point(int x, int y){ this.x = x; this.y = y; } }

What is the prototype/signature of the following function public int add(int x; int y){ return x+y; }

public int add(int x; int y)

constant syntax

public static final double OVERDRAFT_FEE = 5 (YOU REFER TO THIS AS BankAccount.OVERDRAFT_FEE)

String value = scanInput.next();

read a value from the keyboard

null

reference values are initialized with the value

this

refers to the implicit parameter inside your class

scope of variables

region of the program within which the variable can validly appear in lines of code

information hiding

restriction of access

a constructor has no __ type

return

What is the form of a piece of code to return a calculation from a method?

return value;

nextInt()

returns an int that contains the next integer typed on the keyboard

indexOf

returns an int that is the index of the first occurrence of a character

Math.abs()

returns the absolute value of its parameter

nextLine()

returns the input line as a String

default constructor

sets all instance fields to their default values (String = "null", integer = "0", double = "0.0", boolean = false)

overloaded constructor

sets the instance fields to the user input

point method: setLocation(x,y)

sets the point's x andy to the given values

public void setTitle(String newTitle){ title = newTitle; }

setter method

sin()

sine

static field

something that is kept the same with whoever uses the program... always declared as private (bank name = TD Bank)

constants

something that is unable to be changed, is indicated with all capitals in variable name

constructor

special method that creates an object and assigns initial values to the data

Constructors

special methods invoked when an object is created and are used to initialize them.

sqrt()

square root

two characteristics of objects

state and behavior

exp class: string

string class is a template for creating string obkects

immutable

strings are ___ objects which means their value cannot change

primitive type

strings are not a

literal representation

strings are unique since they have a

How can an exception be handled under program control?

try-catch statement

overloaded methods

two or more methods in the same class that have the same name but different parameters

declaration syntax for

type name;

The statement below is an example of int x = new Integer(5);

unboxing

make variables common to all objects

use the static modifier

local variables

used to provide temporary working storage for data in a method, instantiated in the method

accessor

used to return the value of a private field. It follows a naming scheme prefixing the word "get" to the start of the method name

chaining constructors

used when a class has several constructors

copy constructor

uses a prewritten constructor to initialize other objects


Related study sets

Match the definition with the correct term.

View Set

5.1 The Business Intelligence (BI) Stack

View Set

NSG 242 Chapter 33: Caring for Children in Diverse Settings

View Set

ENGLISH SPEAKING COURSE - CHAPTER 2 Bored And How Are You Doing?

View Set

Barnett - Con Law II Final Exam Study

View Set

Which of the following best describes a benefit of increasing the number of offshore wind farms rather than onshore wind farms?

View Set

Module 4: Behavior Change Principles and Application

View Set

Biology Flashcards 8 (CIE IGCSE specific)

View Set