JAVA FINAL 12

अब Quizwiz के साथ अपने होमवर्क और परीक्षाओं को एस करें!

How is the import keyword used?

the import keyword is used to let the compiler know that the class is going to use an external package

implicit parameter

the object on which a method is invoked

implicit parameter

the object on which a method is invoked. comes before the method. myAccount.getDeposit(). my account is the implicit parameter

Source code

the original problem-solving, logical solution written in a programming language (ex. JAVA, .java file)

What is a base class?

the parent of a child class

SuperClass

the parent or supertype of a class

scope

the part of a program in which a variable can be accessed

Scope

the part of a program in which the variable is defined

Main method

the primary method in a java application program

operating system

the program that controls the overall operation of the computer; it communicates with the users and carries out their requests

JDBC supports

2-tier and 3-tier

Identifier

A name given to an entity in a program (must start with a letter, and can include _ and $)

Compiler

A program that translate a computer program written in one language to another language (from high-level to machine language)

Method

A program unit that represents a particular action

Import Declaration

A request to access a specific Java package

Declaration

A request to set aside a new variable with a given name and type

BufferedReader

A class. Read text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines.

Test extends Base ( gọi hàm )

1 tham số và 2 tham số

3

Das Ergebnis der folgenden Schleife ist: int result = 0; for (int i = 0; i < 3; i = i + 1) result = result + 1;

3

Das Ergebnis r der folgenden Schleife ist: int r = 0; for (int i = 0; i < 3; i = i + 1) r = r + 1;

Top Down Methode

Das Vorgehen beim Entwickeln eines neuen Programms, bei dem man ganz allgemein beginnt und danach schrittweise verfeinert, heisst: ..

14. The -______- specifies what information can be stored in a variable and what operations can be performed on it.

Data Type

What kind of value and how much will be stored?

Data Type

Members

Data and method declarations of class

DNS

Domain Name System; converts from a symbolic host name such as Columbia.edu to its 32-bit IP address

True or False, octal literals can start with \u.

False

Changes made to variable by another thread are called synchronous changes.

False (asynchronous)

Only type 1 drivers are portable to any JVM.

False (type 4)

What is final class?

Final class can't be inherited.

What is final method?

Final methods can't be overriden.

InterruptedIOException is a subclass of?

IOException

Java Schlüsselwörter

Im Eclipse Code wird die Farbe Rot verwendet für ...

short

Indicates that a value is a 16-bit whole number.

private

Indicates that a variable or method can be used only within a certain class.

What is Inheritance?

Inheritance is a mechanism in which one object acquires all the properties and behaviour of another object of another class. It represents IS-A relationship. It is used for Code Resusability and Method Overriding.

Java

Interpreted, platform independent, object oriented language

default

Introduces a path of execution to take when no case is a match in a switch statement.

Can a constructor have a synchronized modifier?

No; they can never be synchronized.

draw point at (x, y)

StdDraw.point(x, y);

set pen color

StdDraw.setPenColor();

When you type something wrong and java doesn't compile (LANGUAGE)

Syntax error

19. When writing data to a file, what is the difference between the print and the println methods?

After the println method writes its data, it writes a newline character. The print method does not write the newline character.

What does it mean when an object is passed by value?

A copy is made and that copy is passed. When something is passed by value any changes to that value doesn't affect the actual object.

10. What is an infinite loop? Write the code for an infinite loop. ?

An infinite loop is a loop that has no way of stopping, it occurs when a programmer forgets to write code inside the loop that makes the test condition false. There are several possibilities to do an endless loop, here are a few I would choose: for(;;) {} while(1) {} / while(true) {} do {} while(1) / do {} while(true)

True

A variable must be declared before it can be used

Braces{}

A group of statements, such as the contents of a class or a method, are enclosed in

accessor method

A method that gets the value of an instance variable without altering the state of the variable/object.

Megabyte

A million Bytes. Can store large pictures.

Instance Variable

A non static field - a variable that applies only to the instance of the class in which it is instantiated.

Object

A programming entity that contains data and methods

What does the term overloading mean?

overloading a method is to declare two or more methods of the same name with different parameters

Prints x on the same line

print(x)

Prints x on the same line, then moves the cursor to the next line

println(x)

System.out.println

prints statement and creates new line

(int) ((Math.random() * 10) + 1)

random integer between 1 and 10

access modifier

says where a class can be used or referenced

mutator

sets a property

double vertical line

short circuit "or" operator

//comment

short comments

&&

When determining whether a number is inside a range, its best to use this operator

if statement (many commands)

if (true) { }

Character strings are represented by the class ___.

java.lang.String

true

All lines in a conditionally executed block should be indented one level

When you use a timer, you need to define a class that implements the ____ interface. A) TimerListener B) TimerActionListener C) ActionListener D) StartTimerListener

Ans: C Section Ref: 9.10

catch

Introduces statements that are executed when something interrupts the flow of execution in a try clause.

else

Introduces statements that are executed when the condition in an if statement isn't true.

try

Introduces statements that are watched (during runtime) for things that can go wrong.

ALL UPPERCASE IN JAVA

CONSTANTS

Private visibility

Can be used anywhere inside but not outside class definition

System.out.print();

Can be used to produce output on the same line

do

Causes the computer to repeat some statements over and over again (for instance, as long as the computer keeps getting unacceptable results).

Mutator method

Changes a particular value (setter)

char

Character

What does the method .equals do from the String class?

Compares the equality of two strings.

What does the method .equals do from the class object?

Compares two object area memories.

What does Javac do?

Compiles the program.

public static iterator

Complication fails

Interface ___ help manage the connection

Connection

What is a constant?

Constants are variables that cannot be changed.

Compiler

Converts Source Code into an Object File or Machine Code. Detects Syntax Errors.

How do you declare a String Builder/ String Buffer

Declaration: StringBuilder S2 = new StringBuilder("Test String") or by using the default constructor.

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

Define the main method.

Method declaration

Defines code that is executed when method is invoked

class

Defines the characteristics and actions of an object. Models things from the problem domain.

Constructor

Does not have a return type, cannot be called

What happens when you divide and Int by 0?

Exception

1. Briefly describe the difference between the prefix and postfix modes used by the increment and decrement operators. ?

In postfix mode the operator is placed after the operand. In prefix mode the operator is placed before the variable operand. Postfix mode causes the increment or decrement operation to happen after the value of the variable is used in the expression. Prefix mode causes the increment or decrement to happen first.

Will this line compile without errors? Object obj [ ] = new Object [3]();

Incorrect because the () after the [] is not the correct syntax.

Will this line compile without errors? Object obj [] = new {new Object(), new Object()};

Incorrect because the first new operator is being used with the {} initialization method.

Will this line compile without errors? Object [7] obj = new Object [7];

Incorrect because the size is not assigned when it is declared.

Will this line compile without errors? Object obj [ ] = new Object() ;

Incorrect because they have () instead of [] after the type.

void

Indicates that a method doesn't return a value.

float

Indicates that a value is a 32-bit number with one or more digits after the decimal point.

int

Indicates that a value is a 32-bit whole number.

double

Indicates that a value is a 64-bit number with one or more digits after the decimal point.

long

Indicates that a value is a 64-bit whole number.

char

Indicates that a value is a character (a single letter, digit, punctuation symbol, and so on) stored in 16 bits of memory.

byte

Indicates that a value is an 8-bit whole number.

boolean

Indicates that a value is either true or false, in the Java sense.

static

Indicates that a variable or method belongs to a class, rather than to any object created from the class.

final

Indicates that a variable's value cannot be changed, that a class's functionality cannot be extended, or that a method cannot be overridden.

transient

Indicates that, if and when an object is serialized, a variable's value doesn't need to be stored.

What happens when you divide a double or a float by 0?

Infinity

Int

Integer Range is typically of -2,147,483,648 to 2,147,483,648

Can a constructor be declared static?

No, constructors are for creating new instance objects. Static methods are for non-instance code, so it makes no sense to have a static constructor.

Is this valid code? while(false){ System.out.println("Hey"); }

No, it will cause a compilation error because of unreachable code. If their is a boolean that is false and it is put inside the parenthesis it fine.

Can local variables use the static modifier?

No, local variables can only use the final modifier.

When can super() be called.

Only the FIRST line of the constructor.

implements

Reuses the functionality from a previously defined interface.

What happens when their is no main?

Runtime Error

Does constructor return any value?

Technically it returns the constructed object

instanceof

Tests to see whether a certain object comes from a certain class.

π

Math.PI;

Are arrays used only for primitives?

No

Can a local variable be static?

No

Does the StringBuilder class override the equals method in object?

No

Punctuation

These characters serve specific purposes, such as marking the beginning or ending of a statement, or separating items in a list.

Keywords

These have a special meaning in the program and cannot be used in other ways (eg class, if, while)

Threads

These share the process's resources, including memory and open files. This makes for efficient, but potentially problematic, communication.

If a parent throws an exception what must its child constructor do?

Throw that exception or a subclass of it or don't throw anything at all.

Containers are components that house other components.

True

Deadlock can occur when all threads are in a blocked state.

True

For the listener interfaces with more than on method, you can implement the listener indirectly by extending its adapter class.

True

GUIs use a separate thread called the event dispatched thread for drawing and forwarding all paint requests to that thread.

True

If no listeners are registered, the event is delivered to the default listener.

True

Swing components separate the manipulation of data associated with a component from the rendering or graphical-representation component and its contents.

True

Swing uses a separable model architecture.

True

The Drag and Drop API provides the ability to move data between programs created with the Java programming language.

True

The JVM is in charge of scheduling processor time according to the priorities assigned to the threads.

True

The PreparedStatement interface extends Statement.

True

The currentThread is the static method of the Thread class

True

The method setDefaultCloseOperation is a member of the JFrame class.

True

The method that issues an INSERT statement returns an integer value that indicates the number of row affected.

True

The paint and update methods provide a Graphic object as an argument of the method.

True

The properties of transactional integrity have been formalized and are known as the ACID properties.

True

Thread-safe variables belong to one thread alone; different threads have separate copies.

True

True or False, octal literals must start with a 0.

True

You create handlers for user-initiated events by defining classes that implement the listener interfaces.

True

Your threds can launch other threads.

True

code fragmanet, sbuf references.. sbuf.append

True

automatically saves

What does the computer do once you build?

short hand a = a * n

a *= n;

Single Responsibility Principle

a class should do one thing and do it well - which is to say it should be cohesive

What are the eight primitive data types supported by the Java programming language?

byte short long float double int char boolean

code that has been compiled

byte code

3. In the expression number++ , the ++ operator is in what mode? a. prefix b. pretest c. postfix d. posttest

c

blueprints/designs for an object

classes

cast

converting a value from one type to another explicitly

how to give location of error

e.printStackTrace();

Random Access Memory

electronic circuits in a computer that can store code and data of running programs

what is overloading a method

having two methods with same name...the key is the methods must have different parameters

if / else

if (true) { } else { }

String

immutable character holder

get a file

import java.io.* public static void getAFile(String filename) { try{ FileInputStream file = new FileInputStream(filename);} }

Scanner

import java.util.Scanner static Scanner userInput = new Scanner(System.in); public static void main() { ... if (userInput.hasNextInt()) {} }

pseudocode

informal programming language with English-like constructs modeled to look like statements in a java-like language

pseudocode

informal programming language with english like constructs

public and abstract

interface methods are implicitly what?

what is the objects state

its how the object reacts when you invoke those methods

How do you run a program using commands.

javac ClassName.java java ClassName

null

no value

The Basic form of a Java Class

public class <name> { <method> <method> ... <method> }

jump

up and down

formal parameter

the data type and variable name of a reference or value that is defined in a method definition

what is a subclass?

the descendant of a superclass

Method Signature

the method name and parameter list (cannot overload a method by changing the return type if all other properties of the method are equals)

Protected Keyword

the protected keyword limits the access of a class member to only those classes which reside within the same package

What does the public keyword mean?

the public access modifier means that all classes have access to that element

true

the scope of a variable is limited to the block in which it is defined

Interpreter

the software the executes byte code

literal

the source code representation of a fixed value

What does the static keyword mean?

the static keyword is used to define a field or method that will not change across all instances of that class - it defines a class level element that can be accessed without instantiating an object of that class

computer science

the study of algorithms including their formal and mathematical properties, hardware realizations, linguistic realizations, and applications

true

A conditionaly executed statement should be indented one level from the if clause

Switch Statement

A control flow statement that takes an argument and compares it to the cases supplied to it - runs the code under a case if the arguments are equal - will run all the code underlying one case if a 'break' or 'return' is not encountered.

while (cond) { }

while "cond" block syntax

while

while (true) { }

what is abstract method

...

what is collection

...

what is the difference between class and interface

...

What is the length of TEXT?

4

random number between 1 and n

1 + Math.random() * n;

DataSource

A factory for connections to the physical data source that this DataSource object represents.

Class Constant

A named value that cannot be changed, and its scope extends to the entire class

Instantiate

=new

realtional operators

>,<, and == are

1. What will the println statement in the following program segment display? int x = 5; System.out.println(x++); a. 5 b. 6 c. 0 d. None of these

A

Bit

A "1" or "0" representing "on or off"

What file is created after a program is created?

A .class file.

Type

The kind of Value (e.g., Integer, Floating Point Number, Character) is being stored.

Cohesion

A desirable quality in which the responsibilities of a method or process are closely related to each other.

Programmer - defined names

There are words or names that are used to identify storage locations in memory and parts of the program that are created by the programmer.

What is the output of the following code segment? int value = 1; switch (value) { case 0: System.out.println("Dog"); case 1: System.out.println("Cat"); case 1: System.out.println("Fish"); default: System.out.println("Cow"); }

This will not compile because it includes a case statement with the same value twice.

How can you cast a polymorphic object?

To the object type or any of its subclasses.

Set implementation... value-ordered

TreeSet

A Java application window is a frame window.

True

A connection from a DataSource object has the same type as one from a DriverManager object.

True

static variable

A variable defined in a class that has only one value for the whole class, and which can be accessed and changed by any method of that class.

All components have the methods addFocusListener and add MouseListener.

True

Any thread that is executing can all interrupt on another thread.

True

Stopping an active thread asynchronously from the outside, by calling stop or suspend, releases all locks without giving the thread an opportunity to complete potentially critical operations.

True

Spelling Error Examples

Undefined Variable Name Unrecognized KeyWord

Constants

An identifier that is initialized to a value that cannot change. Usually declared at top of program using keyword final. final int MAXHT=100;

What version of Unicode is supported by Java SE 7?

Unicode standard, version 6.0.0

13. What is the advantage of using a sentinel?

Sometimes the user has a list of input values that is very long, and doesn't know the number of items there are. When the sentinel value is entered, it signals the end of the list, and the user doesn't have to count the number of items in the list.

type

Specifies what kind of thing a variable or a parameter is. Example: int, char, boolean...

.class

What is the file extension for byte code?

Concatenation

Combining several strings into one string, or a string with other data into a longer string using the operator "+"

Is this valid? static final long APHELION = 152,097,701;

Commas are not allowed in numeric literals, so a compiler error will occur.

Compiler

Ein ... übersetzt einen Programmtext und erzeugt ein Kompilat. Dieses kann sofort ausführbar oder im Fall von Java ein Zwischencode sein, der noch interpre¬tiert werden muss.

return

Ends execution of a method and possibly returns a value to the calling code.

To select a predefined strategy for positioning components in a container, set up an association between a class that extends LayoutManager or LayoutManager2 and a container.

False

What will be printed if null was on the left side of the instance of operator?

False

The return type of the method that issues an SELECT statement is int.

False (ResultSet)

You can call wait only from a method that own a key.

False (lock)

read back data from file

FileInputStream, RandomAccessFile

Syntax error

Forgetting a semicolon or brace

System.out.println("HelloWorld");

Geben Sie auf der Konsole den folgenden Text aus: Hello World! Danach soll eine Zeile weitergeschaltet werden.

for, while, if, if - else

Geben Sie drei Beispiele für Kontrollstrukturen.

for

Gets the computer to repeat some statements over and over again (for instance, a certain number of times).

Objects

Have a state and set of variables

What is composition?

Holding the reference of the other class within some other class is known as composition.

Will this line compile without errors? Object [ ] obj = new Object [3]();

Incorrect because the () after the [] is not the correct syntax.

Will this line compile without errors? Object [3] obj = new Object [3]() ;

Incorrect because the size is in the declaration and the extra () after the [] is not the correct syntax.

Will this line compile without errors? Object [8] obj = new Object [ ];

Incorrect because the size is not assigned when it is declared.

Can a byte be set to an int variable?

No

Can a class be private?

No

Can a member variable be declared synchronized?

No, the keyword synchronized marks method code so that it cant be run by more than one thread at a time.

Can you statically import a package?

No, you can only import classes statically.

StdInput.readInt („Geben Sie den ersten Wert ein: „);

StdInput Methode: Ergänzen Sie den Code, der den folgenden Text erzeugt: "Geben Sie den ersten Wert ein:" public class SummeBerechnen { public static void main(String[] args) { int operand1 = ... int result = 0; result = operand1 + 3; }//main }//class

print

System.out.print(...) System.out.println(...) ln prints in new line

print the ARRAY moreNames

System.out.print(Arrays.toString(moreNames)); toString must be a static method...

print (return) a command line input

System.out.println (args[0]);

Print to screen

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

21. What is a potential error that can occur when a file is opened for reading?

The file does not exist.

Method header

The first line of a method.

Class header

The first line of the class. It might say something like public class Hello {

Statements and expression

a way to manipulate/operate on the data

Consider the following code snippet. arrayOfInts[j] > arrayOfInts[j+1] Which operators does the code contain?

comparative operator "greater than" > arithmetic operator "plus" +

if (string1.equals(string2))...

compares equality of 2 strings

Software

computer instructions or data. Anything that can be stored electronically

==

equal to

What will be printed? System.out.println("roberto".substring(3, 7));

erto

eval

eval() evaluates expressions

class Object

every class in Java is either a direct or indirect subclass of what?

import java.util import javax.swing

example java api package imports

while (s.equals("v")) { }

execute block while string s equals value v

reason for abstract classes in java

java does not allow multiple subclasses

Object

the instance of a class containing data and the functions that manipulate the data

software

the intangible instructions and data that are necessary for operating a computer or another device

INCORRECT..Socket

the java.net.Socket... contain code... know how.. communicate server .. UDP

Lowercase

the non capital letters of the alphabet

class SuperDuper

line 3: private; line 8: protected;

LAN

local area network; network that is located in a geographically contiguous area such as a room; It is composed of personal computers and servers all connected with coaxial or fiber optic cables. Characteristics: bus, star, ring topology. Message broadcast on shared channel and all nodes receive.

boolean operator

logical operator. && || !=

How is the ternary operator structured?

logical-expression? expr1:expr2; expr1 gets executed if logical-expression is true, if not expr2 gets executed. If it is being set to a variable the value of what expression gets executed gets put into that variable.

-64 bits Range: -big to big No rules

long

double ampersand.

short circuit "and" operator

Math.sin(x)

sine of x (x in radians)

code that the programmer writes

source code

Parameter passing

specifying expressions to be actual parameter values for a method when it is called

Variable Declaration

stating the name of the variable coupled with its data type

register

storage cell that holds the operands of an arithmetic operation and when the operation is complete holds its result

charAt

stringname.charAt(positionStartingAtZero)

The ___ statement allows for any number of possible execution paths.

switch

the closest previous if clause that doesnt already have its own else clause

An else clause always goes with

A static method can have which of the following types of parameters? A) Only implicit parameters. B) Only explicit parameters. C) Both implicit and explicit parameters. D) A static method cannot have parameters.

Ans: B Section Ref: 8.6

Which of the following represents the hierarchy of GUI text components in the hierarchy of Swing components? A) JTextField and JTextComponent are subclasses of JTextArea. B) JTextArea and JTextComponent are subclasses of JTextField. C) JTextField and JTextArea are subclasses of JTextComponent. D) JTextField, JTextArea, and JTextComponent are subclasses of JPanel.

Ans: C Section Ref: 10.1

Java-Applet

Ein ...-... ist ein spezielles Java-Programm, das nur innerhalb eines Browsers ausgeführt werden kann und speziellen Sicherheitsaspekten unterliegt. Z.B. können Applets standardmäßig nicht auf Daten des betreffenden Rechners zugreifen.

integer

Ein Dateityp in Java für ganze Zahlen.

import

Enables the programmer to abbreviate the names of classes defined in a package.

What does the method .toString do from the class object?

Gives a string representation of an object. This is usually overridden and if not will print the area memory.

joke about hacking into a bank without abstraction

Go to my account's global context and type setBalance()

Internet Protocol

network layer in the Internet; the IP uses 32-bit addresses to identify different nodes.

byte input

nextByte()

What does overriding mean?

overriding is to create a unique implementation of a method inherited from a supertype or interface

How do you make a constant.

Make a variable with final and static modifiers.

How many types of memory areas are allocated by JVM?

Many types: Class(Method) Area, Heap, Stack, Program Counter Register, Native Method Stack

absolute value of x - y

Math.abs(x - y);

arc cos x

Math.acos(x);

random number between 0 and 1

Math.random();

sin x

Math.sin(x);

degrees to radians

Math.toRadians();

Can their be any duplicate cases in a switch statement?

No

to swap values of integers you need a...

place holder

can run on any computer

platform independent

>0

positive

private accessor: security vs freedom

private often cited as giving SECURITY...but most often, it gives freedom to change instance fields

an outline of what a program is expected to do

program specification

Running

The Process of execution.

What is the keyword native?

The native keyword is applied to a method to indicate that the method is implemented in native code using JNI.

6. The while loop is this type of loop. a. pretest b. posttest c. prefix d. postfix

a. pretest

int

data type integer

Boolean expression

any expression that evaluates to true or false

i = a.Length;

load element count of array a into integer i

char[]c=s.toCharArray();

load s into character array c

main loop

public static void main (String[] args)

the entry point for your application

public static void main(String [] args)

subclass extends the superclass

superclass / subclass relationship in java

Why is it a good idea to split your application into layers?

n tier design allows for further separation of concerns among parts/layers of our appplication - this provides the ability to reuse parts of the application in other programs by having loosely coupled classes/layers

int x = (int)a;

syntax to cast type (double a = 1.54;) into an int

an introductory comment should begin the program package names should be in camelCase comments should not reiterate what is clear from the code

name 3 examples of code conventions

final int VOLUME = 8

names constant integer

public Class Dog extends Animal implements Pet{}

syntax to create an Animal subclass called dog that has a pet interface

truth table

table used in logic to compute the functional values of logical expressions; this table has input columns that list all combination of true/false values and the corresponding outputs for those

for (initialization; condition; update) { statements }

terminating loop

difference between while loop and do while loop

x=10 do { System.out.println("X is equal to " +x); x++; } while (x<10) This will return "X is equal to 10", while while loop would not return any thing at all. (Do-while returns initialization, regardless of whether it meets while condition).

monitor called mon ... 10 threads... waiting pool

you cannot

CPU

"Central Processing Unit" The brain of the computer.

ampersand

"and" operator

vertical line

"or" operator

What is the value for the variable sum? int[][] sampleArray = new int[3][4]; for (int i = 0; i < 3; i++) { sampleArray[i][i+1] = 2; } int sum = 0; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { sum += sampleArray[i][j]; } }

4

cache memory

5 to 10 times faster than RAM, but smaller. When a computer uses something it'll use it again very soon -> move the data from regular RAM to cache

What is the instanceof operator?

Checks if one objects is a instance of another.

What is this automatically? 45e7

A double

-All programs start with a ? -Must have { and } -Identifier (name) begins with a CAPITAL letter EX: public class Westlake

Class

16. The -______- contains the method header and the method body.

Class Method

Data and method declarations

Class contains

Kontrollstrukturen

Der Oberbegriff für for- und while-Schleifen ist :..

double

Dies ist ein Dateityp in Java für Zahlen mit Nachkommastellen.

Digital vs Binary

Digital Binary 0 0 1 1 2 10 3 11 4 100 5 101 6 110 7 111 8 1000 9 1001 10 1010 11 1011 12 1100 13 1101 14 1111

3. A(n) -______- stores the data for an object.

Instance Variable

kilobyte

Maximum memory size is 2^10 memory bytes

Abstraction

Meaning we do not need to know the implementation details in order to use them

immutable

Means that once created, their values cannot be changed.

Self-governing

Means that variables contained in an object should be changed only within the object

9. A(n) -______- tells the computer to execute a method.

Method Call

Attribute

Property that descrives object

Encapsulation

Protective barrier that prevents code from being accessed from outside class

Accessor method

Provides read-only (getter)

Das Programm gibt die ganzen Zahlen von 34 bis 73 auf der Konsole aus: 34, 36, 38, ... 72

Was macht das folgende Programm?

Das Programm gibt die ganzen Zahlen von 34 bis 73 auf der Konsole aus: 34, 36, 38, ... 72

Was macht das folgende Programm? BILD FEHLT

curly braces

What follows a class?

the program won't run

What happens if you violate the rules?

Java filename and the class name

What has to be identical to what?

Coupling

An undesirable state in which two methods or processes rigidly depend on each other.

&&

And(both are true)

A class that cannot be instantiated is called a/an ____. A) Abstract class. B) Anonymous class. C) Concrete class. D) Non-inheritable.

Ans: A Section Ref: Special Topic 10.1

controlling class

What is the name of the class that contains the main method?

class declaration/class definition

What is the public class line called?

a semicolon

What punctuation is used at the end of every statement?

Oak

What was Java originally called?

Widening conversion

When Java converts a lower- ranked value to a higher - ranked type, it us called a -----

What is overloading?

When a method has the same name but different signature. EX: void m1() int m1(int a) void m1(int a, int b)

How are Servlets and JSP Pages related?

When a web server that has JSP support is asked for a JSP page, it checks to see if it has already compiled the page into a servlet. Thus, JSP pages become servlets and are transformed into pure Java and then compiled, loaded into the server and executed.

nextDouble

Which Scanner class method would you use to read a double as input

nextLine

Which Scanner class method would you use to read a string as input

72 = amount; profit = 129

Which of the following are not valid assignment statements?

Konsole

Wie heisst in Exclipse das Fenster, in dem Ein- und Ausgaben des Programms stattfinden?

public class Kreisumfang {}

Wie sieht die Programmzeile aus, die eine neue Klasse mit dem Namen "Kreisumfang" erstellt? (Alles was zwischen den geschweiften Klammern steht, gehört übrigens zur Klasse.)

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

Wie sieht die Zeile aus, die das Hauptprogramm "main" markiert? Diese Zeile steht übrigens innerhalb einer Klasse.

double PI = 3.145;

Wo ist der Fehler? int PI = 3.145;

public class Kugelflaeche {}

Wo ist der Fehler? public class Kugelfläche {}

int faktor1 = 3;

Wo ist der Fehler? int Faktor1 = 3;

public static void main(String args[])

Wo ist der Fehler? public static void Main (string args[])

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

Wo ist der Fehler? public static void Main (string args[])

Are StringBuffer/StringBuilder final classes?

Yes

Can an abstract class extend a concrete one?

Yes

Can an abstract class have a constructor?

Yes

Can array use all of the methods that object can?

Yes

Can you compare a byte with a float by using ==?

Yes

Can you compare an int with a double by ==?

Yes

Can you forget some parts of a for loop?

Yes

Can you have an array of objects?

Yes

Can you use short in a switch statement?

Yes

Do you have to initialize a local variable?

Yes

If an array list is of type integer and you try to set it as an array with the method .asList that has a type of int will it compile?

Yes

Is the instance block executed before the constructor?

Yes

Is this valid code? boolean b = false; while(b){ System.out.println("Hey"); }

Yes

write code... execute onlu.. curren thread owns multiple locks

Yes

Can we overload main() method?

Yes, You can have many main() methods in a class by overloading the main method.

Can a class be declared as final?

Yes, a class can be declared final; that is, the class cannot be sub-classed. This is done for security and design.

Can you have virtual functions in Java?

Yes, all functions in Java are virtual by default.

Is this valid? Object [] o = {"Song Book", 35.95, new Guitar(), 6};

Yes, it is fine to have subtypes as elements in an array of a supertype.

Are instance variables assigned a default value?

Yes, member or instance variables are always given a default value.

Can we execute a program without main() method?

Yes, one of the way is static block

Can we intialize blank final variable?

Yes, only in constructor if it is non-static. If it is static blank final variable, it can be initialized only in the static block.

Is Empty .java file name a valid source file name?

Yes, save your java file by .java only, compile it by javac .java and run by java yourclassname

Can we override the overloaded method?

Yes.

Will this line compile without errors? Object [ ] obj = new Object [7];

Yes.

Will this line compile without errors? Object obj = new Object ();

Yes.

Will this line compile without errors? Object obj [ ] = new Object [7];

Yes.

Will this line compile without errors? Object obj [ ] = {new Object [1], new Object [2]};

Yes.

Will this line compile without errors? Object obj [ ] = {new Object(), new Object()};

Yes.

Will this line compile without errors? double[ ][ ] numbers = {{1,2,3},{7,8},{4,5,6,9}};

Yes.

Will this line compile without errors? double[ ][ ][ ] numbers = new double[7][ ][ ];

Yes.

Can a constructor be declared private?

Yes. This can be used to control the creation of the object by other less restrictive methods.

"

\"

'

\'

\

\\

Backspace

\b

Tab

\t

11. This expression is executed by the for loop only once, regardless of the number of iterations. a. initialization expression b. test expression c. update expression d. pre-increment expression

a

5. This is a variable that controls the number of iterations performed by a loop. a. loop control variable b. accumulator c. iteration register variable d. repetition meter

a

Class

a class is a template in which state and behavior are defined for the instances of that class (objects)

What is a mutator?

a mutator is a method that changes the value of a field in a class - often called a 'setter'

protocol

a mutually agreed upon set of rules, conventions, and agreements for the efficient and orderly exchange of information

compiler

a program that translates code in a high-level language to machine instructions (such as bytecode for java)

class

a programmer defined data type. Blueprint from which individual objects are created. A class definition defines instance and class variable and methods. also specifies interfaces

class

a programmer-defined data type; the user can create this data type and make objects of this type

parameter

a reference or value that is passed to a method or subrouting

Class

a set of instructions that create an object

what is a try/catch?

a try/catch block is used to catch exceptions - if the code in the try block throws an exception the rest of the try block is skipped and the catch block is run

what is an abstract base class?

an abstract base class differs from a base class in that it cannot be instantiated - only used to enforce certain fields and methods

boolean expression

an expression that evaluates to either true or false

'this' refers to

an instance of the class. thus, 'this' cannot refer to static methods, which

Math.toRadians(x)

convert x degrees to radians (ie, returns x* p/180)

What is this()?

calls a constructor in the same class?

print vs println

carriage return

What is casting a variable?

casting is to override the compiler by declaring your variable as a certain (Type) - this can only be used to make an object higher in a class hierarchy a more specific subclass (i.e. (Integer)Number or (ArrayList)Collection)

\

char that comes after is exempted from compiler (ie printing "")

Write a class and write a tester for that class

class Dog { int size; String breed; String name; void bark() { System.out.println("ruff! Ruff!"); } } 2) write the tester (TestDrive) class class DogTestDrive { public static void main (String [] args) { Dog d=new Dog(); d.size=40; d.bark(); } }

Procedural programming

creating a program by using a step by step process to perform specific tasks

15. To open a file for reading, you use the following classes. a. File and Writer b. File and Output c. File and Input d. File and Scanner

d

12. This is a variable that keeps a running total. a. sentinel b. sum c. total d. accumulator

d. accumulator

4. What is each repetition of a loop known as? a. cycle b. revolution c. orbit d. iteration

d. iteration

instantiation

construction of an object of that class

Data Hiding

data hiding is the concept of maintaining private fields within a class - if they are not meant to be modified, don't provide a setter - if they aren't meant to be accessed don't provide a getter

double

data type decimal value

cast

explicitly converting a value from one type to a different type

control unit

fetches from memory the next instruction to be executed, decodes it, and executes it by issuing appropriate command to ALU, memory, or I/O

Where is a software object's state contained?

fields (Java) or variables (C++)

ReadLine()

function to get a line from InputStreamReader object

s.substring(b,e);

get sub string from s starting at position b ending at position e

accessor

gets a property

Arguments

give method more info about what to do

Memory Data Register

holds the information to be transferred/copy of information received

class Xyz

iAmPublic iAmPrivate iAmVolatile

if (cond) { } else { }

if "cond" blocks syntax

how to do: if (x != false) {}

if (!(false)) this will run fortunately. however if (l

if

if (Boolean expression) { Statements; } conditional statement

The most basic control flow statement supported by the Java programming language is the ___ statement.

if then

first line of program, HelloWorld

public class HelloWorld

Variables

public class Variables5 { public static void main(String args[]){ double tuna; tuna = 5.28; System.out.print("I want "); System.out.print(tuna); System.out.println(" movies"); } }

a programmer needs to create a logging method

public void logIt(String...msgs)

Build a void method

public void main

what access modifiers can be used for top level classes

public, abstract and final can be used for top level classes

time complexity

quantifies the amount of time taken by an algorithm to run; commonly expressed using big O notation

IS-A relationship

relationship to describe extends

HAS-A relationship

relationship to describe instance variables

void

return type in method declaration. You are not returning anything from the method or the class if it is in main method.

str.charAt(pos)

returns the character (char) at position pos (int) in the given string

str.length()

returns the number of characters in the given string (int)

str.substring(start, end)

returns the string starting at position (start) and ending at position (end-1) in the given string

syntax

rules that define how to form instructions in a particular programming language; grammer

Linking

the Action of Bringing in Already Written Code(Libraries) for Use in a New Program.

Compliling

the Action of Turning the Source Code into a Format the Computer Can Use

protocol stack

the Internet protocol hierarchy that has 5 layers (physical, data link, network, transport, application); also referred to as TCP/IP

Method Body

the code held bw the curly braces following the method

Inheritance

the concepts that one class can take on the fields, methods and nested classes of another object by using the extends keyword

return type of constructor

NONE...not even void

correct statement about RMI

all

correct statement about remote interface

all

Syntax

These are the rules that must be followed when writing a program.

Key words

These are words that have a special meaning in the programming language

array.length

gives the length of the array (no parentheses!)

expressions

have values

Integer value: 97

'a'

'A' is less than 'B'

How does the character 'A' compare to the character 'B'

Flow of Control

The order in which the statements of a Java program are executed

double PI = 3.145;

Verbessere die Fehler! double PI = 3,145

Testers

Programmers hand Program to these code breakers.

do(loop)

always execute once and keep executing while condition is true

Instantiating an object

class name object name = classname();

what is interface

collection of abstract methods

How does a program destroy an object that it creates?

set the value to null

Text

Im Eclipse Code wird die Farbe Blau verwendet für ...

What does String Buffer extend?

Object

Code

Program fragments

James Gosling

Who led the team?

WAN

wide area network that connects devices that are not in close proximity but rather are across town, across the country, or across the ocean. Characteristics: Store-and-forward, packet-switched technology. Message transmitted by packets. Failure of a single node doesn't bring down the entire network.

Cat, Washer,SwampThing

will compile... exception line 7...cannot be converted

transient

(adj) nhất thời

while

(i != TotalNum) { } // code in here

Map

an interface that maps keys to values - a map object can store the key value pairs

Boolean expression

true/false literals

not equal

!=

pattern

(n) mẫu,kiểu mẫu

What is casting?

- Casting is used to convert the value of one type to another.

what is deadlock

...

Operators

These are symbols or words that perform operations on one or more operands.

What will be printed? System.out.println("roberto".replaceAll("o","!").substring(1, 6));

!bert

Client

Code that uses an object

Method Call

A command to execute another method, causes all of the statements inside that method to be executed.

Literals

The following data 72 'A' "Hello World" 2.8712 Are all examples of

remainder

%

Modulus operator

% returns remainder

System.out.Printf("%3d", i*j)

% /number of spaces taken up/ Integer, variable

consistent

(adj) tình nhất quán, phù hợp

priority

(n) quyền ưu tiên

concatenation

(n) sự nối chuỗi

serialization

(n) sự tuần tự hóa

daemon threads

(n) thread ngầm

attribute

(n) thuộc tính

ceil

(n) trần

Who is loading the init() method of servlet?

- Web server

What does it mean for a method to take in an interface as a parameter.

A class that implements that interface must be passed.

abstract

A class that is...may not be instantiated(you may not call its constructor)

Gigabyte

A billion bytes. Can store music an video files.

Which code fragment constructs an arrray list named players that is initialized to contain the strings "Player 1" and "Player 2"? A) ArrayList<String> players = new ArrayList<String>(); players.set(0, "Player 1"); players.set(1, "Player 2"); B) ArrayList<String> players = new ArrayList<String>(); players.set(1, "Player 1"); players.set(2, "Player 2"); C) ArrayList<String> players = { "Player 1", "Player 2" }; D) ArrayList<String> players = new ArrayList<String>(); players.add("Player 1"); players.add("Player 2");

Ans: D Section Ref: Section 7.2 Array Lists

Program

Is a solving tool

Modifier

Java reserved word that names special characteristics of a programming language construct

JRE

Java runtime environment

Static methods

Method not associated with any object

Why Java does not support pointers?

Pointer is a variable that refers to the memory address. They are not used in java because they are unsafe(unsecured) and complex to understand.

ThreadGroup

This class represents a set of threads.

INCORRECT.. serialization

When an Object Output Stream

If an instance variable creates an object when will it be ran?

When the class is needed in main for the first time

2. What will the println statement in the following program segment display? int x = 5; System.out.println(++x); a. 5 b. 6 c. 0 d. None of these

b. 6

ternary operator

b? e1:e2 conditional (boolean) expression if b is true, e1 if b is false, e2

String[] a = {"ab","cd"};

declare array a of two strings "ab" and "cd"

Basic Calculator

import java.util.Scanner; public class BuildingABasicCalculator7 { public static void main(String[] args) { Scanner bucky = new Scanner(System.in); double fnum, snum, answer; System.out.println("Enter first num "); fnum = bucky.nextDouble(); System.out.println("\nEnter second num "); snum = bucky.nextDouble(); answer = fnum + snum; System.out.println("\nFnum and Snum added together equal"); System.out.println(answer); } }

User Input

import java.util.Scanner; public class GettingUserInput6 { public static void main(String args[]){ Scanner bucky = new Scanner(System.in); System.out.println(bucky.nextLine()); } }

Methods With Parameters- Class 1

import java.util.Scanner; public class UseMethodsWithParameters15 { public static void main(String[] args) { Scanner input = new Scanner(System.in); UseMethodsWithParameters15P2 UseMethodsWithParameters15P2Object = new UseMethodsWithParameters15P2(); System.out.println("Enter your name here: "); String name = input.nextLine(); UseMethodsWithParameters15P2Object.simpleMessage(name); } }

Example of Input

import java.util.Scanner; public class My Program { public class static void main class (String[ ] args) { Scanner scan=new Scanner(System.in); String lastname; System.out.print("Enter last name"); lastname=scan.next() Systm.out.printlin('You entered" +lastname);

4. The -______- is where the program begins execution.

main Method

set input variables

thisEnter = myScanner.next.Int();

What is the difference between & and &&?

& evaluates both sides. If the first one is false the second statement will be evaluated. && works differently. When the first expression is false it will not execute the second one. This is also known a short cut.

and

&&

logical operators

&&, and ! are

Integer value: 48

'0'

Integer value: 65

'A'

immutable

(adj) không thay đổi được, không sửa được

transitive

(adj)bắc cầu

restrictive

(adj)giới hạn

yielding

(adj)mềm dẻo, dễ uốn

intuitive

(adj)thuộc về trực giác

str.equals("test")

(boolean) returns true if the string "test" matches string str, false otherwise

Which lines will not compile? Integer luckyNumber = 66; System.out.println(luckyNumber.booleanValue()); System.out.println(luckyNumber.charValue()); System.out.println(luckyNumber.byteValue()); System.out.println(luckyNumber.shortValue()); System.out.println(luckyNumber.longValue()); System.out.println(luckyNumber.floatValue()); System.out.println(luckyNumber.doubleValue());

Lines two and three will not compile, because you cannot convert the Integer wrapper class to a boolean or char primitive. For the Integer class, the methods booleanValue and charValue do not exist.

LinkedList vs ArrayList

LinkedList compares favorably to ArrayList when adding and deleting objects from list a lot However, LinkedList is not as efficient at accessing ArrayList objects by index...when listening to video...he uses exact same methods on LinkedList as he did on ArrayList, so will have to check documentation (banas 12)

Which of the following are interfaces to ArrayList? List, Map, Queue, RandomAccess, and Set.

List and RandomAccess are interfaces to ArrayList.

Parameter list

Lists types of values that are passed, and their names

Which literal data types must be cast in order to work with an int data type?

Literals of type long, float, and double must be explicitly cast to an int to be used with a variable of the type int.

8. A variable that is declared inside a method and can only be used within that method is called a(n) -______- .

Local Variable

Runtime errors

Logic errors so severe that Java stops your programing from executing

Assertion

Logical statement that can be true or false

-All must have one (except apps) -Follows the class, where execution begins -Must h ave { and }

Main method

arc sin x

Math.asin(x);

cos x

Math.cos(x);

find the max

Math.max (x, y);

find the min

Math.min (x, y);

x^y

Math.pow (x, y);

random number between 0 and n

Math.random() * (n + 1);

square root of a

Math.sqrt (a);

radians to degrees

Math.toDegrees();

megabyte

Maximum memory size is 2^20 memory bytes

gigabyte

Maximum memory size is 2^30 memory bytes

Debugger

May be able to find Semantic/logic Errors. Used when error is detected.

Instance data

Memory space created for every class that is created

19. A(n) -______- appears inside the parentheses of a method header, and contains a data type and a name.

Method Definition

Difference between method Overloading and Overriding.

Method Overloading Method Overriding 1) Method overloading increases the readability of the program. Method overriding provides the specific implementation of the method that is already provided by its super class. 2) method overlaoding is occurs within the class. Method overriding occurs in two classes that have IS-A relationship. 3) In this case, parameter must be different. In this case, parameter must be same.

Tostring

Method automatically called when object is used as an operand

public

Method declaration. It means that method can be called from anywhere. Any thing declared as public can be accessed from anywhere.

static

Method declaration. You don't have to create instance of the class if it is in main method

Punctuation Error Examples

Missing Curly Braces Missing Semi Colons Malformed Comments

Block-Kommentare beginnen mit /* und enden mit */.

Mit welchen Zeichen beginnen und enden in Java Block-Kommentare?

einzeilige Kommentare beginnen mit //

Mit welchen Zeichen werden in Java einzeilige Kommentare eingeleitet?

-Cannot put a bigger box into a smaller box -Data type on RIGHT side of = has to be less than the type on the LEFT side EX: 64bits = 32bits <---CORRECT EX: 32bits = 64bits <--- WRONG

Mixing Data Types Rules

-Cannot put a decimal into an integer -Integers cannot hold decimal values EX: int = double <---WRONG EX: double = int <--- CORRECT

Mixing Data Types Rules

-short and char are not interchangeable -char is unsigned (only positive values), short has both positives and negatives

Mixing Data Types Rules

MVC

Model -View -Controller

%

Modulo(Mod)- Remainder after Integer division.

Can the access specifier for an overriding method allow more or less access than the overridden method?

More. The access specifier for an overriding method can allow more, but not less, access than the overridden method.

*=

Multiplies value of operand by whatever number is placed after

Return statement

Must be included when method returns value

13. A(n) -______- allows the application class to change the value stored in an instance variable.

Mutator Method

!

NOT Operator. Reverses the value of a boolean operand

What happens when you divide 0.0 by 0.0 or 0?

NaN(Not a Number)

\\

Name the escape sequence used for a backslash.

\n

Name the escape sequence used for a new line.

\'

Name the escape sequence used for a single quote.

\b

Name the escape sequence used for backspace.

\"

Name the escape sequence used for double quotes.

\t

Name the escape sequence used for tab/

gross

Namenskonventionen: In Java werden zusamengesetzte Wörter in einem Wort geschrieben. Der erste Buchstabe des neuen Wortteils wird jeweils ... geschrieben.

gross

Namenskonventionen: Werden in Java Klassen gross oder klein begonnen?

klein

Namenskonventionen: Werden in Java Methoden gross oder klein begonnen?

klein

Namenskonventionen: Werden in Java Variablen gross oder klein begonnen?

gross

Namenskonventionen: Wie werden in Java Konstanten geschrieben?

If a superclass implements an interface and a subclass implements the same interface is their a compilation error?

No

Is it legal to have the same method with the same parameters but a different return type?

No - The parameters have to be different.

The Java Programming Environment

No matter what environment you use, you will follow the same basic three steps. 1. Type in a program as a Java Class 2. Compile the program file. 3. Run the compiled version of the program.

Will this compile and if not why? Short ss = new Short(9);

No, 9 is automatically an int and their is no int constructor for short.

Can a top-level class be marked as protected?

No, a top-level class can only be marked public or default. The protected access is just for member variables and methods, and allows subclasses outside the superclass package to inherit the protected members.

Can you compare a boolean to an int?

No, booleans are true and false keywords and nothing else.

Can a private method be overridden?

No, but the can be re-declared in the subclass. This is not polymorphism.

Can you make a constructor final?

No, constructor can't be final.

Is constructor inherited?

No, constructor is not inherited.

Is it possible for an interface to be an object type in a polymorphic object?

No, interfaces can't be instantiated.

Can you call a non static method in main without using an instance of the class?

No, main is static and therefore cannot call non static variables or methods.

Can local variables use access modifiers?

No, since local variables are local they will not be seen outside of the class.

Is it legal for a non-static method to be called in a static one?

No, static methods and variables cannot be called in non static methods and vice versa.

Can you set a float to 1.0?

No, that would automatically make it a double.

Can we override static method?

No, you can't override the static method because they are the part of class not object.

Does each source file need a public class in it?

No.

Is delete,next,main,exit or null keyword in java?

No.

Can you use this() and super() both in a constructor?

No. Because super() or this() must be the first statement.

Will this line compile without errors? double[ ][ ][ ] numbers = new double[ ][ ][ ];

No. When the new operator is used, at least one array dimension in a multi-dimensional array must be given a size.

White Space

Not recognized by compiler Indent (ex 3 spaces) for each new function selection or loop.

Logic Error Examples

Nothing Happens Infinite Loop Program output is incorrect Dividing by zero (Error Message at Run Time) Errors May be intermittent

What happens if their is no default in a switch statement?

Nothing happens.

What is covariant return type?

Now, since java5, it is possible to override any method by changing the return type if the return type of the subclass overriding method is subclass type. It is known as covariant return type.

Signature

Number, type, and order of method's parameters

||

OR Operator. If any of the boolean operands is true, the condition becomes true

10. An instance method must be called on a(n) -______- .

Object

What is difference between object oriented programming language and object based programming language?

Object based programming languages follow all the features of OOPs except Inheritance. Examples of object based programming languages are JavaScript, VBScript etc.

Which class is the superclass for every class.

Object class.

Driver programs

Often used for testing, lead other ,more interesting parts of program

If break statements are not used in a switch, what will happen?

Once a case statement is entered, the code will continue to execute in each case below it, until it hits a break statement.

next()

One word String

JAVA Libraries

Over 2000 of these exist, sometimes called packages. Can have access to them by Java.lang (package is imported automatically) on top of first class.

During runtime, value assigned that exceeds positive bounds of a variable

Overflow error

Can overriding methods throw different exceptions than that of the super?

Overriding methods cannot throw any new or broader exception that is checked. Unchecked does not apply.

Overriding vs Overloading

Overriding when return type, name, parameters the same. Overloading when name the same but parameters different. (overloading is illegal when extending a superclass)

importable- an application can use existing classes from another package

Packages are ___.

Method

Prewritten code to accomplish a task

7. The memory location that stores a value sent to a method is called a(n) -______-.

Primitive Variable

Stores a specific type of value

Primitive data types

Will this compile? int ivar = 77; Integer integer = ivar;

Primitives and their wrapper classes are automatically converted back and forth with autoboxing and auto-unboxing.

What is a well defined class?

Public interface (clearly defined responsibility --single-responsibility principle--Cohesion: the defined responsibilities of the class are meaningful - they make sense -- Delegation: if a task falls outside the responsibility of that class, the task is delegated to another class) Private Implementation (Encapsulation: data-hiding - fields are private (only accessed by getters and setters) and methods not a part of the user interface are private)

set up main method

Public static void main (string[], args) {

Simple rules to live by

Put class and method headers on lines by themselves. Put no more than one statement on each line. Indent your program properly. When an opening brace appears, increase the indentation of the lines that follow it. When closing brace appears, reduce the indentation. Indent statements inside curly braces by a consistent number of spaces (4 spaces are common) Use blank lines to separate parts of the program.

package

Puts the code into a package — a collection of logically related definitions.

Random Access Memory

RAM; 3 characteristics: 1 - memory divided into cells and each cell has an address. 2 - All accesses to memory are at a specific address; must get complete cell. 3 - Time it takes to fetch/store a cell is the same for all cells.

RAM

Random Access Memory Used to store programs that are being executed, along with their data. (Does not retain its contents when computer is turned off.)

15. A(n) -______- stores the address of an object.

Reference Variable

Stores (points to) the memory address of an object

Reference variable

super

Refers to the superclass of the code in which the word super appears.

ClassNotFoundException is a subclass of?

ReflectiveOperationException

IllegalAccessException is a subclass of?

ReflectiveOperationException

NoSuchMethodException is a subclass of?

ReflectiveOperationException

RMI

Remote Method Invocation

while

Repeats some statements over and over again (as long as a condition is still true).

Fill in the blank. Import statements are ______.

Required in all versions of Java.

12. A(n) -______- sends a value back to the caller.

Return Statement

What does the method .compareTo do from the class String?

Returns a integer when comparing to strings. Ex: String s = new String("sam"); String s1 = new String("Sam"); s.compareTo(s1); ------- Returns 32 because S and s are 32 unicode codes away.

What does the method .getClass do from the class object?

Returns class name of an object.

What does the substring method written like this return - stringName.subString(3,3)?

Returns nothing

%=

Returns remainder of value of operand after divided by whatever number is placed after

What does the .indexOf() method return?

Returns the first occurrence of the char, or string. If a number is provided this is where the method starts looking for the specified string/char.

Running out of Java heap memory is an example of what?

Running out of heap memory results in a java.lang.OutOfMemoryError unchecked error.

What does a for loop with two semicolons do(for(;;))?

Runs infinitly

What happens if their is no main method?

Runtime Error.

When something goes wrong while the program is running. (Also known as exception)

Runtime error

declared scanner class

Scanner myScanner=new Scanner(System.in); System.out.println("Please enter #:");

byte

The byte data type is an 8-bit signed two's complement integer. It has a minimum value of -128 and a maximum value of 127 (inclusive). The byte data type can be useful for saving memory in large arrays, where the memory savings actually matters. They can also be used in place of int where their limits help to clarify your code; the fact that a variable's range is limited can serve as a form of documentation.

What gives Java its 'write once and run anywhere' nature?

The bytecode. Java is compiled to be a byte code which is the intermediate language between source code and machine code. This byte code is not platform specific and hence can be fed to any platform.

Arrays.copyOf(values, n)

The call Arrays.copyOf(values, n) allocates an array of length n, copies the frst n elements of values (or the entire values array if n > values.length) into it, and returns the new array.

multiple instances

The case when there are multiple objects from the same class instantiated at runtime.

char

The char data type is a single 16-bit Unicode character. It has a minimum value of '\u0000' (or 0) and a maximum value of '\uffff' (or 65,535 inclusive).

Suppose interface Inty defines 5 methods

The class will not compile if it's declared abstract The class may not be instantiated

What is classloader?

The classloader is a subsystem of JVM that is used to load classes and interfaces.There are many types of classloaders e.g. Bootstrap classloader, Extension classloader, System classloader, Plugin classloader etc.

string1.compareTo (string2) < 0

The compareTo method compares strings in lexicographic order.

What does continue do?

The continue statement skips the current iteration of a for, while, or do-while loop. The unlabeled form skips to the end of the innermost loop's body and evaluates the boolean expression that controls the loop. A labeled continue statement skips the current iteration of an outer loop marked with the given label.

Which statement is correct? ArrayList d1 = new ArrayList(); ArrayList d2 = new ArrayList<>(); ArrayList<> d3 = new ArrayList<>(); ArrayList<Double> d4 = new ArrayList<>(); ArrayList<Double> d5 = new ArrayList<Float>();

The declarations for d1, d2, and d4 are valid as they will compile.

What is the purpose of default constructor?

The default constructor provides the default values to the objects. The java compiler creates a default constructor only if there is no constructor in the class.

7. Which loop should you use in situations where you want the loop to repeat until theboolean expression is false , but the loop should execute at least once?

The do - while loop.

making your first object - The dot operator explained

The dot operator (,) give access to an object's state and behavior ( instance variables and methods). // make new object Dog d= new Dog(); //tell the dog to bark by using dot operator //om the variable d to call the bark() d.bark(); //set its size using the dot operator d.size=40;

double

The double data type is a double-precision 64-bit IEEE 754 floating point. Its range of values is beyond the scope of this discussion, but is specified in the Floating-Point Types, Formats, and Values section of the Java Language Specification. For decimal values, this data type is generally the default choice. As mentioned above, this data type should never be used for precise values, such as currency.

What is meant by controls and what are different types of controls in AWT?

- Controls are components that allow a user to interact with your application and the AWT supports the following types of controls: Labels, Push Buttons, Check Boxes, Choice Lists, Lists, Scrollbars, Text Components. These controls are subclasses of Component.

What are cookies and how will you use them?

- Cookies are a mechanism that a servlet uses to have a client hold a small amount of state-information associated with the user. a) Create a cookie with the Cookie constructor: public Cookie(String name, String value) b) A servlet can send a cookie to the client by passing a Cookie object to the addCookie() method of HttpServletResponse: public void HttpServletResponse. addCookie(Cookie cookie) c) A servlet retrieves cookies by calling the getCookies() method of HttpServletRequest: public Cookie[ ] HttpServletRequest. getCookie().

What is daemon thread and which method is used to create the daemon thread?

- Daemon thread is a low priority thread which runs intermittently in the back ground doing the garbage collection operation for the java runtime system. setDaemon() method is used to create a daemon thread.

What is the life cycle of a servlet?

- Each Servlet has the same life cycle: a) A server loads and initializes the servlet by init () method. b) The servlet handles zero or more client's requests through service() method. c) The server removes the servlet through destroy() method.

What is Internet address?

- Every computer connected to a network has an IP address. An IP address is a number that uniquely identifies each computer on the Net. An IP address is a 32-bit number.

What is meant by Inheritance and what are its advantages?

- Inheritance is the process of inheriting all the features from a class. The advantages of inheritance are reusability of code and accessibility of variables and methods of the super class by subclasses.

What are inner class and anonymous class?

- Inner class : classes defined in other classes, including those defined in methods are called inner classes. An inner class can have any accessibility including private. Anonymous class : Anonymous class is a class defined inside a method without a name and is instantiated and declared in the same place and cannot have explicit constructors.

What is interface and its use?

- 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. Interfaces are useful for: a)Declaring methods that one or more classes are expected to implement b)Capturing similarities between unrelated classes without forcing a class relationship. c)Determining an object's programming interface without revealing the actual body of the class.

What is a cloneable interface and how many methods does it contain?

- It is not having any method because it is a TAGGED or MARKER interface.

What is Domain Naming Service(DNS)?

- It is very difficult to remember a set of numbers(IP address) to connect to the Internet. The Domain Naming Service(DNS) is used to overcome this problem. It maps one particular IP address to a string of characters.

What is JDBC?

- JDBC is a set of Java API for executing SQL statements. This API consists of a set of classes and interfaces to enable programs to write pure Java Database applications.

What type of driver did you use in project?

- JDBC-ODBC Bridge driver (is a driver that uses native(C language) libraries and makes calls to an existing ODBC driver to access a database engine).

What are JSP ACTIONS?

- JSP actions use constructs in XML syntax to control the behavior of the servlet engine. You can dynamically insert a file, reuse JavaBeans components, forward the user to another page, or generate HTML for the Java plugin. Available actions include: jsp:include - Include a file at the time the page is requested. jsp:useBean - Find or instantiate a JavaBean. jsp:setProperty - Set the property of a JavaBean. jsp:getProperty - Insert the property of a JavaBean into the output. jsp:forward - Forward the requester to a newpage. Jsp: plugin - Generate browser-specific code that makes an OBJECT or EMBED

What is JSP?

- JSP is a dynamic scripting capability for web pages that allows Java as well as a few special tags to be embedded into a web file (HTML/XML, etc). The advantages are: a) The JSP assists in making the HTML more functional. Servlets on the other hand allow outputting of HTML but it is a tedious process. b) It is easy to make a change and then let the JSP capability of the web server you are using deal with compiling it into a servlet and running it.

What are JSP scripting elements?

- JSP scripting elements lets to insert Java code into the servlet that will be generated from the current JSP page. There are three forms: a) Expressions of the form <%= expression %> that are evaluated and inserted into the output, b) Scriptlets of the form<% code %>that are inserted into the servlet's service method, and c) Declarations of the form <%! Code %>that are inserted into the body of the servlet class, outside of any existing methods.

What is a Jar file?

- Jar file allows to efficiently deploying a set of classes and their associated resources. The elements in a jar file are compressed, which makes downloading a Jar file much faster than separately downloading several uncompressed files. The package java. util. zip contains classes that read and write jar files.

What is method overloading and method overriding?

- Method overloading: When a method in a class having the same method name with different arguments is said to be method overloading. Method overriding : When a method in a class having the same method name with same arguments is said to be method overriding.

What are methods and how are they defined?

- Methods are functions that operate on instances of classes in which they are defined. Objects can communicate with each other using methods and can call methods in other classes. Method definition has four parts. They are name of the method, type of object or primitive type the method returns, a list of parameters and the body of the method. A method's signature is a combination of the first three parts mentioned above.

What is multithreading and what are the methods for inter-thread communication and what is the class in which these methods are defined?

- Multithreading is the mechanism in which more than one thread run independent of each other within the process. wait (), notify () and notifyAll() methods can be used for inter-thread communication and these methods are in Object class. wait() : When a thread executes a call to wait() method, it surrenders the object lock and enters into a waiting state. notify() or notifyAll() : To remove a thread from the waiting state, some other thread must make a call to notify() or notifyAll() method on the same object.

Are there any global variables in Java, which can be accessed by other part of your program?

- No, it is not the main method in which you define variables. Global variables is not possible because concept of encapsulation is eliminated here.

What is an Object and how do you allocate memory to it?

- Object is an instance of a class and it is a software unit that combines a structured set of data with a set of operations for inspecting and manipulating that data. When an object is created using new operator, memory is allocated to it.

What is OOPs?

- Object oriented programming organizes a program around its data, i. e. , objects and a set of well defined interfaces to that data. An object-oriented program can be characterized as data controlling access to code.

What is the difference between process and thread?

- Process is a program in execution whereas thread is a separate path of execution in a program.

What is RMI and steps involved in developing an RMI object?

- Remote Method Invocation (RMI) allows java object that executes on one machine and to invoke the method of a Java object to execute on another machine. The steps involved in developing an RMI object are: a) Define the interfaces b) Implementing these interfaces c) Compile the interfaces and their implementations with the java compiler d) Compile the server implementation with RMI compiler e) Run the RMI registry f) Run the application

How can I delete a cookie with JSP?

- Say that I have a cookie called "foo, " that I set a while ago & I want it to go away. I simply: <% Cookie killCookie = new Cookie("foo", null); KillCookie. setPath("/"); killCookie. setMaxAge(0); response. addCookie(killCookie); %>

What is serialization and deserialization?

- Serialization is the process of writing the state of an object to a byte stream. Deserialization is the process of restoring these objects.

What is Server-Side Includes (SSI)?

- Server-Side Includes allows embedding servlets within HTML pages using a special servlet tag. In many servlets that support servlets, a page can be processed by the server to include output from servlets at certain points inside the HTML page. This is accomplished using a special internal SSINCLUDE, which processes the servlet tags. SSINCLUDE servlet will be invoked whenever a file with an. shtml extension is requested. So HTML files that include server-side includes must be stored with an . shtml extension.

What is Servlet chaining?

- Servlet chaining is a technique in which two or more servlets can cooperate in servicing a single request. In servlet chaining, one servlet's output is piped to the next servlet's input. This process continues until the last servlet is reached. Its output is then sent back to the client.

What is servlet?

- Servlets are modules that extend request/response-oriented servers, such as java-enabled web servers. For example, a servlet might be responsible for taking data in an HTML order-entry form and applying the business logic used to update a company's order database.

Why should we go for inter-servlet communication?

- Servlets running together in the same server communicate with each other in several ways. The three major reasons to use interservlet communication are: a) Direct servlet manipulation - allows to gain access to the other currently loaded servlets and perform certain tasks (through the ServletContext object) b) Servlet reuse - allows the servlet to reuse the public methods of another servlet. c) Servlet collaboration - requires to communicate with each other by sharing specific information (through method invocation)

What is session tracking and how do you track a user session in servlets?

- Session tracking is a mechanism that servlets use to maintain state about a series requests from the same user across some period of time. The methods used for session tracking are: a) User Authentication - occurs when a web server restricts access to some of its resources to only those clients that log in using a recognized username and password. b) Hidden form fields - fields are added to an HTML form that are not displayed in the client's browser. When the form containing the fields is submitted, the fields are sent back to the server. c) URL rewriting - every URL that the user clicks on is dynamically modified or rewritten to include extra information. The extra information can be in the form of extra path information, added parameters or some custom, server-specific URL change. d) Cookies - a bit of information that is sent by a web server to a browser and which can later be read back from that browser. e) HttpSession- places a limit on the number of sessions that can exist in memory. This limit is set in the session. maxresidents property.

What is the difference between set and list?

- Set stores elements in an unordered way but does not contain duplicate elements, whereas list stores elements in an ordered way but may contain duplicate elements.

What are the types of statements in JDBC?

- Statement: to be used createStatement() method for executing single SQL statement PreparedStatement — To be used preparedStatement() method for executing same SQL statement over and over. CallableStatement — To be used prepareCall() method for multiple SQL statements over and over.

What is stored procedure?

- Stored procedure is a group of SQL statements that forms a logical unit and performs a particular task. Stored Procedures are used to encapsulate a set of operations or queries to execute on database. Stored procedures can be compiled and executed with different parameters and results and may have any combination of input/output parameters.

What is synchronization?

- Synchronization is the mechanism that ensures that only one thread is accessing the resources at a time.

What is the difference between TCP/IP and UDP?

- TCP/IP is a two-way communication between the client and the server and it is a reliable and there is a confirmation regarding reaching the message to the destination. It is like a phone call. UDP is a one-way communication only between the client and the server and it is not a reliable and there is no confirmation regarding reaching the message to the destination. It is like a postal mail.

What is the difference between Reader/Writer and InputStream/Output Stream?

- The Reader/Writer class is character-oriented and the InputStream/OutputStream class is byte-oriented.

What are the advantages of the model over the event-inheritance model?

- The event-delegation model has two advantages over the event-inheritance model. They are: a)It enables event handling by objects other than the ones that generate the events. This allows a clean separation between a component's design and its use. b)It performs much better in applications where many events are generated. This performance improvement is due to the fact that the event-delegation model does not have to be repeatedly process unhandled events as is the case of the event-inheritance.

What is the difference between exception and error?

- The exception class defines mild error conditions that your program encounters. Exceptions can occur when trying to open the file, which does not exist, the network connection is disrupted, operands being manipulated are out of prescribed ranges, the class file you are interested in loading is missing. The error class defines serious error conditions that you should not attempt to recover from. In most cases it is advisable to let the program terminate when such an error is encountered.

How do servlets handle multiple simultaneous requests?

- The server has multiple threads that are available to handle requests. When a request comes in, it is assigned to a thread, which calls a service method (for example: doGet(), doPost() and service()) of the servlet. For this reason, a single servlet object can have its service methods called by many threads at once.

How many ways can we track client and what are they?

- The servlet API provides two ways to track client state and they are: a) Using Session tracking and b) Using Cookies.

What is difference between overloading and overriding?

- a) In overloading, there is a relationship between methods available in the same class whereas in overriding, there is relationship between a superclass method and subclass method. b) Overloading does not block inheritance from the superclass whereas overriding blocks inheritance from the superclass. c) In overloading, separate methods share the same name whereas in overriding, subclass method replaces the superclass. d) Overloading must have different method signatures whereas overriding must have same signature.

What is the difference between Integer and int?

- a) Integer is a class defined in the java. lang package, whereas int is a primitive data type defined in the Java language itself. Java does not automatically convert from one to the other. b) Integer can be used as an argument for a method that requires an object, whereas int can be used for calculations.

What are drivers available?

- a) JDBC-ODBC Bridge driver b) Native API Partly-Java driver c) JDBC-Net Pure Java driver d) Native-Protocol Pure Java driver

What are the different servers available for developing and deploying Servlets?

- a) Java Web Server b) JRun g) Apache Server h) Netscape Information Server i) Web Logic

What is the difference between JDBC and ODBC?

- a) OBDC is for Microsoft and JDBC is for Java applications. b) ODBC can't be directly used with Java because it uses a C interface. c) ODBC makes use of pointers which have been removed totally from Java. d) ODBC mixes simple and advanced features together and has complex options for simple queries. But JDBC is designed to keep things simple while allowing advanced capabilities when required. e) ODBC requires manual installation of the ODBC driver manager and driver on all client machines. JDBC drivers are written in Java and JDBC code is automatically installable, secure, and portable on all platforms. f) JDBC API is a natural Java interface and is built on ODBC. JDBC retains some of the basic features of ODBC.

What is the difference between String and String Buffer?

- a) String objects are constants and immutable whereas StringBuffer objects are not. b) String class supports constant strings whereas StringBuffer class supports growable and modifiable strings.

What is the difference between doPost and doGet methods?

- a) doGet() method is used to get information, while doPost() method is used for posting information. b) doGet() requests can't send large amount of information and is limited to 240-255 characters. However, doPost()requests passes all of its data, of unlimited length. c) A doGet() request is appended to the request URL in a query string and this allows the exchange is visible to the client, whereas a doPost() request passes directly over the socket connection as part of its HTTP request body and the exchange are invisible to the client.

What is the difference between applications and applets?

- a)Application must be run on local machine whereas applet needs no explicit installation on local machine. b)Application must be run explicitly within a java-compatible virtual machine whereas applet loads and runs itself automatically in a java-enabled browser. d)Application starts execution with its main method whereas applet starts execution with its init method. e)Application can run with or without graphical user interface whereas applet must run within a graphical user interface.

What is final, finalize() and finally?

- final : final keyword can be used for class, method and variables. A final class cannot be subclassed and it prevents other programmers from subclassing a secure class to invoke insecure methods. A final method can't be overridden. A final variable can't change from its initialized value. finalize() : finalize() method is used just before an object is destroyed and can be called just prior to garbage collection. finally : finally, a key word used in exception handling, creates a block of code that will be executed after a try/catch block has completed and before the code following the try/catch block. The finally block will execute whether or not an exception is thrown. For example, if a method opens a file upon exit, then you will not want the code that closes the file to be bypassed by the exception-handling mechanism. This finally keyword is designed to address this contingency.

What is finalize() method?

- finalize () method is used just before an object is destroyed and can be called just prior to garbage collection.

What is the lifecycle of an applet?

- init() method - Can be called when an applet is first loaded start() method - Can be called each time an applet is started. paint() method - Can be called when the applet is minimized or maximized. stop() method - Can be used when the browser moves off the applet's page. destroy() method - Can be called when the browser is finished with the applet.

What is a reflection package?

- java. lang. reflect package has the ability to analyze itself in runtime.

What modifiers may be used with top-level class?

- public, abstract and final can be used for top-level class.

What are different types of access modifiers?

- public: Any thing declared as public can be accessed from anywhere. private: Any thing declared as private can't be seen outside of its class. protected: Any thing declared as protected can be accessed by classes in the same package and subclasses in the other packages. default modifier : Can be accessed only to classes in the same package.

Explain the methods, rebind() and lookup() in Naming class?

- rebind() of the Naming class(found in java. rmi) is used to update the RMI registry on the server machine. Naming. rebind("AddSever", AddServerImpl); lookup() of the Naming class accepts one argument, the rmi URL and returns a reference to an object of type AddServerImpl.

How can I set a cookie in JSP?

- response. setHeader("Set-Cookie", "cookie string"); To give the response-object to a bean, write a method setResponse (HttpServletResponse response) - to the bean, and in jsp-file:<% bean. setResponse (response); %>

What are Predefined variables or implicit objects?

- simplified code in JSP expressions . They are request, response, out, session, application, config, pageContext, and page.

What is source and listener?

- source : A source is an object that generates an event. This occurs when the internal state of that object changes in some way. listener : A listener is an object that is notified when an event occurs. It has two major requirements. First, it must have been registered with one or more sources to receive notifications about specific types of events. Second, it must implement methods to receive and process these notifications.

What is the difference between this() and super()?

- this() can be used to invoke a constructor of the same class whereas super() can be used to invoke a super class constructor.

What is the primitive storage range of a byte?

-128 to 127

What is the difference between an interface and an abstract class?

-All methods in an interface are implicitly abstract. Abstract classes don't have to have abstract methods but interfaces do. -Interface variables are also final and abstract class variables don't have to be final. -An abstract class implements an interface and does not have to provide implementation for the interface methods.

variable

...

what are top level clases

...

what is inheritance

...

what types of memory do java have

...

final

.... features may not be changed

What are 5 method of the class object.

.equals, .toString, .clone, .finalize, .getClass

equals upper or lower case

.equalsIgnoreCase()

other scanner (static) object methods

.hasNextBoolean() .hasNextFloat() .hasNextDouble()

Byte code

.java code is compiled into this

Comments

// Comment in one line. //*Comment until first occurrence of slash */

Test extends Base ( gọi hàm tạo )

0 tham số và 2 tham số

What does element indexing start at?

0.

boolean

1 bit primitive that manipulates the two logic value T and F.

In the following code segment, how many times will an even number be sent to standard out? for(int x=0 ; x<10 ; x++){ if(x%2 == 0){ System.out.println("x: " + x + " - Even"); continue; } else{ System.out.println("x: " + x + " - Odd"); } x++; }

1 time

interfaces vs abstract class

1) abstract class and interface cannot be instantiated...a class implements an interface, or an interface extends an interface, but an interface cannot implement an interface. 2) an interface specifies a "contract", and all method stubs must be implemented (or at least overridden in subclass) 3) public and abstract are automatically added to every interface method, and abstract is implicitly (& automatically) added to entire interface. 4) in interface, NO method is allowed to have a body

byte

8 bits

Byte

8 bits. smallest unit of storage in memory

Which operator is used to compare two values, = or == ?

== = is an assignment operator

Syntax errors

A Non-proper, not allowable, sequence of character or words given a particular language. Listed at the bottom of screen when compilation is complete

Static Method

A block of Java statements that is given a name. They are units of procedural decomposition.

Bits

A byte is made up of eight

who implements an interface

A class implements an interface , thereby inheriting the abstract methods of the interface.

What is the difference between a class and an object

A class is a blueprint for an object. tells the virtual machine how to make an object. you might use a button class to make dozens of different buttons, each button might have its own color, size, shape, label,

Package

A collection of Java classes

If class B has method m1 and class A doesn't, what happens? A a = new B(); a.m1();

A compilation error. If class A has the method and class B doesn't the method will be called from class A, if class B overrides that method, class B's method will be called. Their will be a compilation error if A doesn't have that method.

Given: public void simpleTest () { int i; System.out.println(i); } What will occur?

A compiler error will occur since the value has not been initialized.

Native Compilers

A compiler that translates directly into machine language and creates a program that can be executed directly on the computer. The compile code to the lowest possible level.

Expression

A construct made up of variables, operators, and method invocations, which are constructed according to the syntax of the language, that evaluates to a single value.

use of constructors in new instances

A constructor is a special method whose purpose is to construct and initialize objects

When you pass a variable as an argument to a method call, what are you passing?

A copy of the value. You always get a copy of whatever is in the variable - either a primitive or a reference. So for objects, you get a copy of the reference.

When dividing what must the variable be put into?

A double because division automatically sets it to a double.

By default what is this considered - 12.21?

A double.

What is blank final variable?

A final variable, not initalized at the time of declaration, is known as blank final variable.

What does the finally keyword do?

A finally code block can be placed after a try catch block. The code in the finally block will always run whether or not an exception is thrown.

What does the term generic mean?

A generic type is a parameterized type - a type

block

A group of zero or more statements between balanced braces and can be used anywhere a single statement is allowed.

True

A left brace in a Java program is always followed by a right brace later in the program

Program

A list of instructions to be carried out by a computer

Program

A list of instructions to be carried out by a computer. Also called software.

Infinite Loop

A loop that never terminates

Variable

A memory location with a name and a type that stores a value

ResultSet

A public interface. A table of data representing a database result set, which is usually generated by executing a statement that queries the database.

Exception

A runtime error that prevents a program from being executed.

this

A self-reference — refers to the object in which the word this appears.

Decomposition

A separation into discernible parts, each of which is simpler than the whole.

Expression

A sequence of One or more identifiers and operator that evaluate a value.

algorithm

A sequence of steps that is unambiguous, executable, and terminating. a well ordered collection of unambiguous and effectively computable operations that when executed produces a result and halts in a finite amount of time

Expression

A simple value, or a set of operations that produces a value

Java

A simple, object-oriented, network-savvy, interpreted, robust, secure, architecture neutral, portable, high-performance, multi-threaded, dynamic language.

Token

A single element of input, java uses whitespaces to separate tokens

Transistors

A solid state device that has no mechanical or moving parts; the light switch of electricity flow

Operator

A special symbol that is used to indicate an operation to be performed on one or more values

Console Window

A special text-only window in which Java programs interact with the user.

What is static method?

A static method belongs to the class rather than object of a class. A static method can be invoked without the need for creating an instance of a class. static method can access static data member and can change the value of it.

Algorithm

A step-by-step description of how to accomplish a task.

Register

A storage cell that holds the outcome of an arithmetic operation

String Literals

A string of text surrounded by quotation marks that will send it as output. Must not be more than one line.

switch case vs if else

A switch compiles into a lookup table which is fundamentally different then the if/else statements. If the last statement in a if/else chain is the one you want you have to check all the previous if/else first. This is not the case with a switch

Operator

A symbol expressing a way to modify a value or values. Ex (+,=, etc.).

Kilobyte

A thousand bytes. Can store pages of text.

Class

A unit of code that is the basic building block of Java programs. In Java class names always begin with a capital letter. Java requires that the class name and file name always match. So if class name is "Hello", the file name is "Hello.java". Nothing can exist outside of a class!

Operand

A value being modified by an operator. Example, x, 10.

Object Reference

A value that denotes the location of an objection in memory. A variable whose type is a class contains a reference to an object of that class

Sentinel

A value that tells us to stop looping

field

A variable that belongs to the entire class (not just a method).

Local variable

A variable that has a scope from the point of declaration to then end of the block in which they are declared

Turing machine

A very simple model of a computing agent proposed by Alan Turing that is used in theoretical computer science to explore computability of problems

I/O

A way to get data into and out of our program

Difference between while loop and do/while loop?

A while loop runs as long as its given condition is true - do/while loops at least once and the until the condition is false

&&

AND Operator. If both boolean operands are true, the condition becomes true

. operator

Access fields

Sequential access

Accessing an array by searching the whole array

Direct access

Accessing an array through an arbitrary location

1. A(n) -______- allows the application class to retrieve the value of an instance variable.

Accessor Method Call

6. A(n) -______- is the value sent to a method.

Actual Parameter

What is difference between aggregation and composition?

Aggregation represents weak relationship whereas composition represents strong relationship. For example: bike has an indicator (aggregation) but bike has an engine (compostion).

Explain a class for an alarm clock

Alarm object have an instance variable to hold the alarmTime, and two methods for getting and setting the alarmTime

Can we treat all types of exceptions the same?

All exceptions can be caught by using the Exception or Throwable type.

What access control applies to interfaces?

All methods declared in an interface are implicitly public, so the public modifier can be omitted. An interface can contain constant declarations in addition to method declarations. All constant values defined in an interface are implicitly public, static, and final. Once again, these modifiers can be omitted.

What does the NEW keyword do?

Allocates new space in memory.

9. Why is it critical that accumulator variables are properly initialized?

An accumulator is used to keep a running total of numbers. In a loop, a value is usually added to the current value of the accumulator. If it is not properly initialized, it will not contain the correct total.

Where can an anonymous inner class be defined?

An anonymous class is an expression. So anywhere an expression is used.

StackTraceElement

An element in a stack trace, as returned by Throwable.getStackTrace(). Each element represents a single stack frame. All stack frames except for the one at the top of the stack represent a method invocation. The frame at the top of the stack represents the the execution point at which the stack trace was generated. Typically, this is the point at which the throwable corresponding to the stack trace was created.

Statement

An executable snippet of code that represents a complete command. Each statement is terminated by a semicolon.

object

An individual instance of a class. An object can only exist during runtime.

What is a field?

An instance variable

By default what is this considered - 12?

An int.

instance

An object.

Cumulative Algorithm

An operation in which the total is acquired incrementally using a loop

Chaining

An undesirable design in which a "chain" of several methods call each other without returning the overall flow of control to main.

Consider the following code snippet: Vehicle aVehicle = new Auto(4,"gasoline"); String s = aVehicle.toString(); Assume that the Auto class inherits from the Vehicle class, and neither class has an implementation of the toString() method. Which of the following statements is correct? A) The toString() method of the Object class will be used when this code is executed. B) The toString() method of the String class will be used when this code is executed. C) This code will not compile because there is no toString() method in the Vehicle class. D) This code will not compile because there is no toString() method in the Auto class.

Ans: A Section Ref: 10.7.1

Mutator methods exhibit which of the following types of side effect? A) Modification of the implicit parameter. B) Modification of an explicit parameter. C) Production of printed output. D) Acceptance of text input.

Ans: A Section Ref: 8.4

Which of the following types of side effects potentially violates the rule of minimizing the coupling of classes? A) Standard output. B) Modification of implicit parameters. C) Modification of explicit parameters. D) Modification of both implicit and explicit parameters.

Ans: A Section Ref: 8.4

Which of the following statements describes an assertion? A) A logical condition in a program that you believe to be true. B) A guarantee that the object is in a certain state after the method call is completed. C) A requirement that the caller of a method must meet. D) A set of criteria defined by the caller of a method.

Ans: A Section Ref: 8.5

Why is a static variable also referred to as a class variable? A) There is a single copy available to all objects of the class. B) It is encapsulated within the class. C) Each class has one and only one static variable. D) It is stored in the separate class area of each object.

Ans: A Section Ref: 8.7

Which of the following statements about abstract methods is true? A) An abstract method has a name, parameters, and a return type, but no code in the body of the method. B) An abstract method has parameters, a return type, and code in its body, but has no defined name. C) An abstract method has a name, a return type, and code in its body, but has no parameters. D) An abstract method has only a name and a return type, but no parameters or code in its body.

Ans: A Section Ref: 9.1

Which of the following is an event source? A) A JButton object. B) An event listener. C) An inner class. D) An event adapter.

Ans: A Section Ref: 9.7

What is the error in this array code fragment? double[] data; data[0] = 15.25; A) The array referenced by data has not been initialized. B) A two-dimensional array is required. C) An out-of-bounds error occurs. D) A cast is required.

Ans: A Section Ref: Section 7.1 Arrays

What is the type of a variable that references an array of integers? A) int[] B) integer() C) integer[] D) int()

Ans: A Section Ref: Section 7.1 Arrays

Wrapper objects can be used anywhere that objects are required instead of ____. A) primitive data types B) clone methods C) array lists D) generic classes

Ans: A Section Ref: Section 7.3 Wrappers and Auto-boxing

Rewrite the following traditional for loop header as an enhanced for loop, assuming that ArrayList<String> names has been initialized. for (int i = 0; i < names.size(); i++) { // process name } A) for (String s : names) B) for (int i = 0; i < names.size(); i++) C) for (s : names) D) for (names : String s)

Ans: A Section Ref: Section 7.4 The Enhanced for Loop

What is the purpose of this algorithm? double total = 0; for (double element : data) { total = total + element; } A) Computing the sum. B) Finding a value. C) Locating an element. D) Counting matches.

Ans: A Section Ref: Section 7.6 Common Array Algorithms

What is the purpose of this algorithm? for (BankAccount a : accounts) { if (a.getAccountNumber() == accountNumber) return a; } return null; A) Finding a value. B) Counting matches. C) Computing the sum. D) Inserting an element.

Ans: A Section Ref: Section 7.6 Common Array Algorithms

What is the purpose of this algorithm? int m = 0; for (BankAccount a : accounts) { if (a.getBalance() >= atLeast) m++; } A) Counting matches. B) Finding a value. C) Computing the sum. D) Locating an element.

Ans: A Section Ref: Section 7.6 Common Array Algorithms

Which of the following statements about a superclass is true? A) An abstract method may be used in a superclass when there is no good default method for the superclass that will suit all subclasses' needs. B) An abstract method may be used in a superclass to ensure that the subclasses cannot change how the method executes. C) An abstract method may be used in a superclass when the method must have identical implementations in the subclasses. D) An abstract method may not be used in a superclass.

Ans: A Section Ref: Special Topic 10.1

Consider the following code snippet: public interface Sizable { int LARGE_CHANGE = 100; int SMALL_CHANGE = 20; void changeSize(); } Which of the following statements is true? A) LARGE_CHANGE and SMALL_CHANGE are automatically public static final. B) LARGE_CHANGE and SMALL_CHANGE are instance variables C) LARGE_CHANGE and SMALL_CHANGE must be defined with the keywords private static final. D) LARGE_CHANGE and SMALL_CHANGE must be defined with the keywords public static final.

Ans: A Section Ref: Special Topic 9.1

A class that represents the most general entity in an inheritance hierarchy is called a/an ____. A) Default class. B) Superclass. C) Subclass. D) Inheritance class.

Ans: B Section Ref: 10.1

When designing a hierarchy of classes, features and behaviors that are common to all classes are placed in ____. A) every class in the hierarchy B) the superclass C) a single subclass D) all subclasses

Ans: B Section Ref: 10.1

To override a superclass method in a subclass, the subclass method ____. A) Must use a different method name. B) Must use the same method name and the same parameter types. C) Must use a different method name and the same parameter types. D) Must use a different method name and different parameter types.

Ans: B Section Ref: 10.3

In Java, every class declared without an extends clause automatically extends which class? A) this B) Object C) super D) root

Ans: B Section Ref: 10.7

General Java variable naming conventions would suggest that a variable named NICKEL_VALUE would most probably be declared using which of the following combinations of modifiers? A) public void final B) public static final double C) private static double D) private static

Ans: B Section Ref: 8.2

Which of the following is a good indicator that a class is overreaching and trying to accomplish too much? A) The class has more constants than methods B) The public interface refers to multiple concepts C) The public interface exposes private features D) The class is both cohesive and dependent.

Ans: B Section Ref: 8.2

Which of the following statements about a Java interface is NOT true? A) A Java interface defines a set of methods that are required. B) A Java interface must contain more than one method. C) A Java interface specifies behavior that a class will implement. D) All methods in a Java interface must be abstract.

Ans: B Section Ref: 9.1

You have a class which extends the JComponent class. In this class you have created a painted graphical object. Your code will change the data in the graphical object. What additional code is needed to ensure that the graphical object will be updated with the changed data? A) You must call the component object's paintComponent() method. B) You must call the component object's repaint() method. C) You do not have to do anything - the component object will be automatically repainted when its data changes. D) You must use a Timer object to cause the component object to be updated.

Ans: B Section Ref: Common Error 9.6

Why can't Java methods change parameters of primitive type? A) Java methods can have no actual impact on parameters of any type. B) Parameters of primitive type are considered by Java methods to be local variables. C) Parameters of primitive type are immutable. D) Java methods cannot accept parameters of primitive type.

Ans: B Section Ref: Quality Tip 8.3

Fill in the if condition that will only access the array when the index variable i is within the legal bounds. if (____________________) data[i] = value; A) 0 <= i < data.length() B) 0 <= i && i < data.length C) 0 <= i < data.length D) 0 <= i && i < data.length()

Ans: B Section Ref: Section 7.1 Arrays

The wrapper class for the primitive type double is ____________________. A) There is no wrapper class. B) Double C) doubleObject D) Doub

Ans: B Section Ref: Section 7.3 Wrappers and Auto-boxing

Which of the following is true regarding subclasses? A) A subclass inherits methods from its superclass but not instance variables. B) A subclass inherits instance variables from its superclass but not methods. C) A subclass inherits methods and instance variables from its superclass. D) A subclass does not inherit methods or instance variables from its superclass.

Ans: C Section Ref: 10.2

Consider the following code snippet: public class Coin { . . . public boolean equals(Coin otherCoin) { . . . } . . . } What is wrong with this code? A) A class cannot override the equals() method of the Object class. B) The equals method must be declared as private. C) A class cannot change the parameters of a superclass method when overriding it. D) There is nothing wrong with this code.

Ans: C Section Ref: 10.7.2

Which of the following questions should you ask yourself in order to determine if you have named your class properly? A) Does the class name contain 8 or fewer characters? B) Is the class name a verb? C) Can I visualize an object of the class? D) Does the class name describe the tasks that this class will accomplish?

Ans: C Section Ref: 8.1

Which of the following describes an immutable class? A) A class that has no accessor or mutator methods. B) A class that has no accessor methods, but does have mutator methods. C) A class that has accessor methods, but does not have mutator methods. D) A class that has both accessor and mutator methods.

Ans: C Section Ref: 8.3

Which of the following statements describes a precondition? A) A logical condition in a program that you believe to be true. B) A guarantee that the object is in a certain state after the method call is completed. C) A requirement that the caller of a method must meet. D) A set of criteria defined by the caller of a method.

Ans: C Section Ref: 8.5

Under which of the following conditions can you have local variables with identical names? A) If their scopes are nested. B) If they are of different data types. C) If their scopes do not overlap. D) If they both reference the same object.

Ans: C Section Ref: 8.8

Consider the following code snippet: class MouseClickedListener implements ActionListener { public void mouseClicked(MouseEvent event) { int x = event.getX(); int y = event.getY(); component.moveTo(x,y); } } What is wrong with this code? A) The mouseClicked method cannot access the x and y coordinates of the mouse. B) repaint() method was not called. C) The class has implemented the wrong interface. D) There is nothing wrong with this code.

Ans: C Section Ref: 9.11

Which of the following statements will compile without error? A) public interface AccountListener() { void actionPerformed(AccountEvent event); } B) public interface AccountListener() { void actionPerformed(AccountEvent); } C) public interface AccountListener { void actionPerformed(AccountEvent event); } D) public abstract AccountListener { void actionPerformed(AccountEvent event); }

Ans: C Section Ref: 9.7

____ are generated when the user presses a key, clicks a button, or selects a menu item. A) Listeners B) Interfaces. C) Events. D) Errors.

Ans: C Section Ref: 9.7

How do you specify what the program should do when the user clicks a button? A) Specify the actions to take in a class that implements the ButtonListener interface. B) Specify the actions to take in a class that implements the ButtonEvent interface . C) Specify the actions to take in a class that implements the ActionListener interface. D) Specify the actions to take in a class that implements the EventListener interface.

Ans: C Section Ref: 9.9

What is the type of a variable that references an array list of strings? A) ArrayList[String]() B) ArrayList<String>() C) ArrayList<String> D) ArrayList[String]

Ans: C Section Ref: Section 7.2 Array Lists

You access array list elements with an integer index, using the __________. A) () operator B) [] operator C) get method D) element method

Ans: C Section Ref: Section 7.2 Array Lists

What is the purpose of this algorithm? for (int i = 0; i < data.size(); i++) { data.set(i, i ); } A) Filling in initial values for an array. B) Counting matches in an array. C) Filling in initial values for an array list. D) Counting matches in an array list.

Ans: C Section Ref: Section 7.6 Common Array Algorithms

Which of the following is true regarding inheritance? A) When creating a subclass, all methods of the superclass must be overridden. B) When creating a subclass, no methods of a superclass can be overridden. C) A superclass can force a programmer to override a method in any subclass it creates. D) A superclass cannot force a programmer to override a method in any subclass it creates.

Ans: C Section Ref: Special Topic 10.1

The ____ reserved word in a method definition ensures that subclasses cannot override this method. A) abstract B) anonymous C) final D) static

Ans: C Section Ref: Special Topic 10.2

Consider the following code snippet: final RectangleComponent component = new RectangleComponent(); MouseListener listener = new MousePressListener(); component.addMouseListener(listener); ______________ frame.add(component); frame.setSize(FRAME_WIDTH, FRAME_HEIGHT); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); Which of the following statements completes this code? A) private static final int FRAME_WIDTH = 300; B) private static final int FRAME_HEIGHT = 400; C) Frame frame = new Frame(); D) JFrame frame = new JFrame();

Ans: D

To create a subclass, use the ____ keyword. A) inherits B) implements C) interface D) extends

Ans: D Section Ref: 10.2

The ____reserved word is used to deactivate polymorphism and invoke a method of the superclass. A) this B) my C) parent D) super

Ans: D Section Ref: 10.3

A method that has no implementation is called a/an ____ method. A) interface B) implementation C) overloaded D) abstract

Ans: D Section Ref: 9.1

Consider the following code snippet: public class Demo { public static void main(String[] args) { Point[] p = new Point[4]; p[0] = new Colored3DPoint(4, 4, 4, Color.BLACK); p[1] = new ThreeDimensionalPoint(2, 2, 2); p[2] = new ColoredPoint(3, 3, Color.RED); p[3] = new Point(4, 4); for (int i = 0; i < p.length; i++) { String s = p[i].toString(); System.out.println("p[" + i + "] : " + s); } return; } } This code is an example of ____. A) overloading B) callback C) early binding D) polymorphism

Ans: D Section Ref: 9.3

Which of the following statements about an inner class is true? A) An inner class may not be declared within a method of the enclosing scope. B) An inner class may only be declared within a method of the enclosing scope. C) An inner class can access variables from the enclosing scope only if they are passed as constructor or method parameters. D) The methods of an inner class can access variables declared in the enclosing scope.

Ans: D Section Ref: 9.8

Which of the following code statements creates a graphical button which has "Calculate" as its label ? A) Button JButton = new Button("Calculate"). B) button = new Button(JButton, "Calculate"). C) button = new JButton("Calculate"). D) JButton button = new JButton("Calculate").

Ans: D Section Ref: 9.9

When an array is created, all elements are initialized with ___. A) zero B) array elements are not initialized when an array is created C) null D) a fixed value that depends on the element type

Ans: D Section Ref: Section 7.1 Arrays

Which class manages a sequence of objects whose size can change? A) Array B) Object C) Sequence D) ArrayList

Ans: D Section Ref: Section 7.2 Array Lists

Which of the following is considered by the text to be the most important consideration when designing a class? A) Each class should represent an appropriate mathematical concept. B) Each class should represent a single concept or object from the problem domain. C) Each class should represent no more than three specific concepts. D) Each class should represent multiple concepts only if they are closely related.

Ans:B Section Ref: 8.1

private

Any thing declared as Private can't be seen outside of its class

protected

Any thing declared as protected can be accessed by a classes in the same package and subclasses in other packages.

argument

Any values the method needs to carry out its task, and are supplied in the method call.

Input

Anything typed by the user.

API

Application Programming Interface; a code library for building programs

18. A call to the toString method would appear in the -______-.

Application class

Scope

Area in program where variable can be referenced

exception types

ArithmeticException ClassNotFoundException IllegalArgumentException IndexOutOfBoundsException(s) InputMismatchException

What is the difference between an array and an array list?

Array lists can only store objects while arrays can store objects or primitives. Arrays have a fixed size while arraylists can change size.

ArrayList<String> friends = new ArrayList<String>();

ArrayList<typeParameter> variableName = new ArrayList<typeParameter>(); typeParameter cannot be a primitive type

=

Assignment Operator

20. A(n) -______- stores a value in a variable.

Assignment Statement

Given: 1//int a = 7; 2//static int ab = 9; 3//final static int abc = 6; 4//static void m1(){ 5//ab = 9 + 3; 6//a = a + 9; 7//abc++; } Where is the compilation error?

At Line 6, this is because a non-static variable is being accessed in a static method.

a thread's run() method

At line 2, ..stop running. It will resume running SOME TIME...

SomeException

B fail A suceed

4. Why are the statements in the body of a loop called conditionally executed statements?

Because they are only executed when a condition is true

Why method overloading is not possible by changing the return type in java?

Becauseof ambiguity.

while(true) { }

Block that can only be exited using break.

2. Why should you indent the statements in the body of a loop?

By indenting the statements, you make them stand out from the surrounding code. This helps you to identify at a glance the statements that are conditionally executed by a loop.

Method m1 has a declaration of void m1() and m2 has a method declaration of public static void m2(). m2 wants to call m2, how does m2 do that?

By making an instance of the class m1 is in and using that, or by changing its method declaration so it is not static.

How can objects be ready for garbage collection(name three ways)?

By setting an object to null, setting an object to another object or setting it to a NEW object.

A ext Objectl B ext A; C ext B, java.io.Externalizable

C must have no-args constructor

Does Java support multiple inheritance?

C++ allows an object to inherit from multiple classes. Java does not. However, Java does permit an object to implement multiple interfaces and inherit from a superclass, providing a limited form of multiple inheritance.

How do you make an object call a method and then cast?

Call the method and put parenthesis with the class type next to it. Ex: (B)aa.m1();

Public visibility

Can be seen from outside object

to convert data type

Casting

-put data type you want in parenthesis before data you want to convert EX: int x = (int) 12.3; //cast double value of 12.3 as int, now has a value of 12

Casting Rules

What are the different types of exception in Java?

Checked and unchecked exceptions. Checked exceptions are caught by the compiler while run time exceptions are ignored by the compiler and don't show up until run time.

Class

Class is a type of object

What are the access levels in order of most restrictive to least?

Class, Package, Sub class, and World.

InterruptedException

Class. Thrown when a thread is waiting, sleeping, or otherwise paused for a long time and another thread interrupts it using the interrupt method in class Thread.

17. Why should a program close a file when it's finished using it?

Closing a file writes any unsaved data remaining in the file buffer.

Java bytecodes

Code that can execute on many different machines.

// marks the single line ? /* block ? */

Comments

False

Comments that begin with // can be processed by javadoc

What is constructor?

Constructor is just like a method that is used to initialize the state of an object. It is invoked at the time of object creation.

Visibility modifiers

Control whether client can see what's inside an object

Interpretation

Converting a source code into common language (.class file)

Design Team

Creates Solution Code. Takes about 75% of Total Program/Solution Time

throw

Creates a new exception object and indicates that an exceptional situation (usually something unwanted) has occurred.

enum

Creates a newly defined type — a group of values that a variable can have.

extends

Creates a subclass — a class that reuses functionality from a previously defined class.

new

Creates an object from an existing class.

Instantiating objects

Creates space to store data values

3

Das Ergebnis des folgenden Ausdrucks ist double zahl = 3.8323467; zahl = (int)zahl;

2.8

Das Ergebnis des folgenden Ausdrucks ist: double i = 14 / 5;

2

Das Ergebnis des folgenden Ausdrucks ist: int i = 13 / 5;

2

Das Ergebnis des folgenden Ausdrucks ist: int i = 14 / 5;

4

Das Ergebnis des folgenden Ausdrucks ist: int i = 14 % 5;

how to store an object that you construct by storing it in a variable

Date birthday=new Date

17. Instance variables are found in the -______-.

Declaration Statement

--

Decrement operator - Decreases the value of operand by 1 --prefix is value after decrement postfix-- is value before decrement

-=

Decrement operator - Decreases value of operand by whatever number is placed after

2. A(n) -______- is called when an object is instantiated and there are no arguments to be sent.

Default Constructor

What is the difference between the default and protected access specifier?

Default does not allow sub class access. Both allow package access.

Eine Folge von Anweisungen, die für die Maschine in verständlicher Form ausformuliert wird.

Definieren Sie auf möglichst engem Raum, was eigentlich ein Programm ist.

int z = 6;

Deklarieren Sie eine Ganzzahl Variable mit dem Namen z und weisen Sie dieser den Wert 6 zu.

boolean

Der Dateityp für "true" und "false" heisst in Java ...

integer

Der Dateityp für Ganzzahlen heisst in Java ...

double

Der Dateityp für Gleitkommazahlen heisst in Java ...

char

Der Dateityp für Zeichen heisst in Java ...

Kontrollstruktur

Der Oberbegriff für for- oder while-Schleifen ist ...

Kontrollstrukturen

Der Oberbegriff für for- oder while-Schleifen ist ...

Programm

Der gesuchte Begriff bezeichnet eine Bearbeitungsvorschrift für einen Computer zur Lösung einer vorgegebenen Aufgabe. Diese wird in einer Programmiersprache formuliert.

Software

Der gesuchte Begriff ist umfassender als der Begriff Programm. Unter ... werden alle immateriellen Teile eines Computers verstanden. Das sind alle Programme, aber auch die zugehörigen Daten und Dokumentationen.

Attribute

Describes object's state of being

Syntax Template

Describes the basic form of a Java construct. Java has rules that determine its legal syntax or grammar.

Programmers

Design Team hands solution to these coders.

Object-oriented programming

Designing a program by discovering objects, their properties, and their relationships

Algorithmus

Die Bearbeitungsvorschrift zur Lösung einer Aufgabe wird auch ... genannt. Ein Programm ist also ein ..., dessen Anweisungsfolge in einer Programmiersprache formuliert ist.

Methode

Dies ist eine systematische Vorgehensweise, um bestimmte Aufgaben im Rahmen festgelegter Prinzipien zu lösen. Auch "Unterprogramm".

Vorteile von Java sind:

Einfachheit, Objektorientiertheit, Stabilität, Plattformunabhängigkeit, Portabilität, Sicherheit. Mitgelieferte Bibliotheken. Zentrale Standardisierung durch Sun.

When is an instance block executed?

Every Time an instance of the class it was created is made. Before the constructor.

Semicolon

Every complete statement ends with a

What happens when you divide 0 by 0?

Exception

How can exceptions be handled in Java?

Exceptions can either be thrown or handled using a try catch block.

21. True or False: The for loop is a posttest loop.

F

22. True or False: It is not necessary to initialize accumulator variables.

F

23. True or False: One limitation of the for loop is that only one variable may be initialized in the initialization expression.

F

26. True or False: To calculate the total number of iterations of a nested loop, add the number of iterations of all the loops.

F

Pseudo code

Fake Code. Every Programmer's way of Writing Down Steps in Soling a Problem.

If Integer xx = 10 and Integer yy = 10, is this true or false? xx==yy?

False

If null is on the left of the instanceof operator what will the answer always be?

False

True or False, octal literals can start with \x.

False

When designing a class that runs on a thread, extending Thread (as opposed to implementing Runnable) is the more flexible and usually preferred approach.

False

Persistence Broker, shown in the figure, uses JDBC.

False (Persistence Classes)

The getLocation method returns the location for the mouse event.

False (getPoint)

To execute a task repeatedly, specify the period in seconds.

False (milliseconds)

True or False - during arithmetic, when the operands or different types, the resulting type is always the widest of the two type.

False, the result of an arithmetic operation on any two primitive operands will be at least an int -- even if the operands are byte and short.

What is the ONLY modifier local variables can use?

Final, anything else will be a compilation error.

General Rule to fix Syntax Errors

Fix 1st error and any obvious errors,then recompile.

continue

Forces the abrupt end of the current loop iteration and begins another iteration.

11. In a method header, the -______- specifies the type of data the method will send back to the caller.

Formal Parameter

- Left alignment 0 show leading zeroes + show a plus sign for positive numbers ( enclose negative numbers in parentheses , show decimal separators ^ convert letters to uppercase

Format flags (printf)

d decimal integer f fixed floating-point e exponential floating-point (very large or very small values) g general floating-point s string

Format types (printf)

System.out.print("y ist" + y);

Geben Sie auf der Konsole den Inhalt der Variablen y aus: y ist 4.5! Danach soll keine Zeile weitergeschaltet werden.

Service methods

Have public visibility, invoked by client

Support methods

Help other methods of class do their jobs

HTTP

Hypertext Transfer Protocol; the protocol that defines communication between web browsers and web servers

What happens if a class has no modifier?

If a class has no modifier (the default, also known as package-private), it is visible only within its own package (packages are named groups of related classes)

What is method overriding?

If a subclass provides a specific implementation of a method that is already provided by its parent class, it is known as Method Overriding. It is used for runtime polymorphism and to provide the specific implementation of the method.

What access is the generated constructor given when one is not supplied?

If the class is public, than it is public. Otherwise the default constructor is default.

Church-Turing Thesis

If there exists an algorithm to do a symbol manipulation task, then there exists a Turing machine to do that task

What does casting have to do with interfaces?

If you define a reference variable whose type is an interface, any object you assign to it must be an instance of a class that implements the interface. As an example, here is a method for finding the largest object in a pair of objects, for any objects that are instantiated from a class that implements Relatable: public Object findLargest(Object object1, Object object2) { Relatable obj1 = (Relatable)object1; Relatable obj2 = (Relatable)object2; if ((obj1).isLargerThan(obj2) > 0) return object1; else return object2; } By casting object1 to a Relatable type, it can invoke the isLargerThan method.

What is final variable?

If you make any variable as final, you cannot change the value of final variable(It will be constant).

If you want to define an unchecked exception, your exception must extend (directly or indirectly) which class?

If you want to define an unchecked exception, your exception must extend the RuntimeException class.

A stream of binary numbers

If you were to look at a machine language program, you would see

eigenen Programmcode

Im Eclipse Code wird die Farbe Schwarz verwendet für ...

Using Underscore Characters in Numeric Literals

In Java SE 7 and later, any number of underscore characters (_) can appear anywhere between digits in a numerical literal.

Formal parameters

In header of method declaration

abstract

Indicates that the details of a class, a method, or an interface are given elsewhere in the code.

bytecode

Instructions for the Java virtual machine

If a byte is multiplied by a short and set to a value what must that value be?

Int

convert integer or any other type toString

Integer.toString(bigInt); Integer.parseInt(intString); -- this converts it back???

IDE

Integrated Development Environment Provides an all-in-one environment for creating, editing, compiling, and executing program files.

class

Introduces a class — a blueprint for an object.

interface

Introduces an interface, which is like a class, but less specific. (Interfaces are used in place of the confusing multiple-inheritance feature that's in C++.)

case

Introduces one of several possible paths of execution in a switch statement.

finally

Introduces the last will and testament of the statements in a try clause.

yes

Is Java case sensitive?

Index

Is an integer that describes the location of a value in a complete sequence; starts with (0)

What is static block?

Is used to initialize the static data member. It is excuted before main method at the time of classloading.

richtig

Ist die folgende Aussage "richtig" oder "falsch"? Java ist casesensitive. Das heisst, Gross-/Kleinschreibung ist wesentlich.

Why we cannot override static method?

It is because the static method is the part of class and it is bound with class whereas instance method is bound with object and static gets memory in class area and instance gets memory in heap.

What b before calling method m1() that returns an int? int b = m1();

It is one

What is the reference type of a polymorphic object instance?

It is the declaration of the instance. The stuff before the equals sign.

What is the object type of a polymorphic object instance and what does it have to be?

It is the initialization of the instance. The stuff after the equals sign. It has to be a child of the reference type.

What is the package with no name?

It is the package that is created by default if a class is not put in a package.

What does the method .finalize do from the class object?

It is used to make something ready for garbage collection.

What is overriding?

It is when a subclass uses the same name and same signature as a method in the parent class.

What is the keyword transient?

It marks a member variable not to be serialized when it is persisted to streams of bytes.

When instantiating a new instance of a class and you use final what does this mean?

It means you cannot allocate a new space in memory for that instance.

If a parent class has a constructor that takes parameters what must the child constructor do, if anything at all?

It must call that parents constructor with super().

What does the method .clone do from the class object?

It throws an exception which must be caught.

short s = (short)9; int i = 8; s+=i; Will this compile,if so what is the output?

It will compile because += and other operators like that do a cast. So s+=i; is s = (short)(s+i);

What happens if their is no break in a switch statement?

It will continue down the case statements until a break is found.

___ a set of java API

JDBC

Just In Time compiler

JIT

Java Virtual MachIne

JVM

Why main method is static?

JVM creats object first then call main() method that will lead to the problem of extra memory allocation.

What is JIT compiler?

Just-In-Time(JIT) compiler:It is used to improve the performance. JIT compiles parts of the byte code that have similar functionality at the same time, and hence reduces the amount of time needed for compilation.Here the term "compiler" refers to a translator from the instruction set of a Java virtual machine (JVM) to the instruction set of a specific CPU.

Per drag and drop in den Ordner src ziehen.

Klassen werden in Eclipse importiert, indem man ...

double

Larger real number (=/-) 10e-324 to 10e308.

Precedence

Level of importance of operations.

TestException

Line 46 ... enclosing method throws... Line 46... try block

What best describes the result of the following code segment? The ArrayList sampleArrayList has already been declared and initialized. int i = 63; sampleArrayList.add(i);

The int is converted to an Integer via auto boxing and then placed into the ArrayList. Primitives cannot be stored in an ArrayList. However, if they are placed into their primitive wrapper class they can be stored. Java will automatically make that conversion via its autoboxing feature if a primitive is placed into an ArrayList.

What is the default value of the local variables?

The local variables are not initialized to any default value, neither primitives nor object references.

long

The long data type is a 64-bit two's complement integer. The signed long has a minimum value of -263 and a maximum value of 263-1. In Java SE 8 and later, you can use the long data type to represent an unsigned 64-bit long, which has a minimum value of 0 and a maximum value of 264-1. Use this data type when you need a range of values wider than those provided by int. The Long class also contains methods like compareUnsigned, divideUnsigned etc to support arithmetic operations for unsigned long.

What happens when you call the .equals method for a StringBuilder?

The memory location is shown.

Hardware

The physical components that make up a computer. CPU, RAM, main board, hard drive are examples

Object-oriented

The primary mode of execution of objects with each other

"private" modifier

The private modifier specifies that the member can only be accessed in its own class.

Evaluation

The process of obtaining the value of an Expression

Iterative enhancement

The process of producing a program in stages, adding new functionality at each stage. A key feature of each iterative step is that you can test it to make sure that piece works before moving on.

"protected" modifier

The protected modifier specifies that the member can only be accessed within its own package (as with package-private) and, in addition, by a subclass of its class in another package.

inheritance (in Java)

The relationship between a more general superclass and a more specialized subclass

When implementing an interface's method that throws an exception what must the implemented exception throw?

The same exception or a subclass or no throw clause at all.

What must be the return type of a method overriding a subclass of another method from a superclass.

The same or a subclass of it. if the method was returning object the subclass method could return String.

short

The short data type is a 16-bit signed two's complement integer. It has a minimum value of -32,768 and a maximum value of 32,767 (inclusive). As with byte, the same guidelines apply: you can use a short to save memory in large arrays, in situations where the memory savings actually matters.

countryName = countryName.trim();

The trim method returns the string with all white space at the beginning and end removed.

Which method of the Stringbuilder class attempts to reduce storage used for the character sequence?

The trimToSize method attempts to reduce storage used for the character sequence.

14. Why must the value chosen for use as a sentinel be carefully selected?

The value chosen for a sentinel must be carefully selected because you want it to be unique enough that it will not be mistaken for a regular value in a list you are working with.

return value

The value that comes back from a method after it is run. In the following method: public int calculateMonth(String name), the return value is an integer.

state

The values of all of the variables in an object at a given time.

If class B has variable v and class A does to, what happens? A a = new B(); a.v();

The variable of the reference type will be called even if it overriden.

5. Describe the difference between the while loop and the do - while loop. ?

The while loop is a pretest loop and the do - while loop is a posttest loop.

6. Which loop should you use in situations where you want the loop to repeat until the boolean expression is false , and the loop should not execute if the test expression is false to begin with?

The while loop.

What does the word before the instanceof operator have to be and what does the word after?

The word before has to be an object. The word after has to be a superclass.

11. Describe a programming problem that would require the use of an accumulator. ?

There are many possible examples. A program that asks the user to enter a business's daily sales for a number of days, and then displays the total sales is one example

15. Describe a programming problem requiring the use of nested loops?

There are many possible examples. One example is a program that asks for the average temperature for each month, for a period of five years. The outer loop would iterate once for each year and the inner loop would iterate once for each month.

Is the following interface valid? public interface Marker { }

There is no requirement to contain constants or method signatures. Empty interfaces can be used as types and to mark classes without requiring any particular method implementations. For an example of a useful empty interface, see java.io.Serializable.

The following code creates one array and one string object. How many references to those objects exist after the code executes? Is either object eligible for garbage collection? ... String[] students = new String[10]; String studentName = "Peter Parker"; students[0] = studentName; studentName = null; ...

There is one reference to the students array and that array has one reference to the string Peter Smith. Neither object is eligible for garbage collection.

{}

These characters are used in Java to group together related bits of code. They could be used to group groups within groups just like parenthesis.

/**

These characters mark the beginning of a documentation comment

/*

These characters mark the beginning of a multi - line comment

//

These characters mark the beginning of a single - line comment

Syntax errors

They are the equivalent of bad grammar and are caught by the compiler.

When designing a class what should you think about

Think about things the object does , and things the object does

Vector

This class implements a growable array of objects. Like an array, it contains components that can be accessed using an integer index. However, the size of a this can grow or shrink as needed to accommodate adding and removing items after the this has been created.

Object

This class is the root of the class hierarchy. Every class has this as a superclass. All objects, including arrays, implement the methods of this class.

Hashtable

This class maps keys to values. Any non-null object can be used as a key or as a value. To successfully store and retrieve objects, the objects used as keys must implement the hashCode method and the equals method.

Context

This interface consists of a set of name-to-object bindings. It contains methods for examining and updating these bindings.

writeObject

This method is used to write an object to the stream. Any object, including Strings and arrays, is written with this method. Multiple objects or primitives can be written to the stream. The objects must be read back from the corresponding ObjectInputstream with the same types and in the same order as they were written.

notifyAll

This method wakes up ALL waiting threads; the scheduler decides which one will run

notify

This method wakes up a single thread which is waiting on the object's lock

CPU

This part of the computer fetches instructions, carries out the operations commanded by the instructions, and produces some outcome or resultant information.

boolean expression

This type of expression has a value of either true or false

Secondary storage

This type of memory can hold data for long periods of time - even when there is no power to the computer

Cast

This type of operator let's you manually convert a value, even if it means that a narrowing conversion will take place

Applet

This type of program is designed to be transmitted over the internet and run in a web browser

If a variable is cast to an invalid object, what is the effect?

This will cause a runtime exception to be thrown.

TCP

Transport Control Protocol; the two programs at the source and destination node need to establish a connection; that is, they must first inform each other of the impending message exchange, and they must describe the "quality of service" they want to receive. TCP uses the ARQ algorithm

A type 1 driver is called the JDBC-ODBC bridge.

True

All the classes java.util.TimerTask and java.uti.Timer provide methods for requesting that the JVM generate threads to run scheduled tasks.

True

If you delete the order and do not bill the customer, but still fail to return the items to the available inventory, your code fails to ensure transaction integrity.

True

Layout managers automate the positioning of the components within containers.

True

Locks are the Java concept for flag maintained by the operating system.

True

SQL should be contained in the persistence layer, shown in the figure.

True

Swing-bases applications extents the javax.swing.JFrame class.

True

The join method of the Thread class waits for the thread object to terminate.

True

The setColor method sets the color used for subsequent drawing and fill coloring.

True

The sleep method of the Thread class makes the thread pause for the specified number of milliseconds.

True

...implement the JDBC API

Type 1

How do you find the length of a String?

Use the .length() method.

Empty parentheses

Used if there are no parameters

Header block

Used to explain purpose of each method in class

System.out.println();

Used to send one line of output to the console window. What is in the parenthesis must be in quotes to print it. A blank line will be printed if there is nothing in the parenthesis.

StringBuilder

Utility Class part of java.lang ; methods: insert, append - single treaded environments

Initialization

Value given to a variable at declaration.

Assignment

Value given to a variable in execution statement.

Object

Value of a class type. Stores its state in fields and exposes its behavior through methods

Parameter

Value passed into method when invoked

Actual parameters

Values passed into method

Local data

Variable declared inside a method

False

Variable names may begin with a number

parameter

Variable passed to a method that provides more information for the method.

a = new double [z];

Verbessere die Fehler! double a[]; int z; a = new double a [z];

i <= 10

Verbessere die Fehler! for (int i = 1; 1 <=10, i ++) {int z = z + i}

if (gespielteZahlenE[y] == y) i = i - 1;

Verbessere die Fehler! if (gespielteZahlenE[y] = y) i = i - 1;

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

Verbessere die Fehler! public static void Main (String args())

int a = 5; double PI = 3.14;

Verbessere in den Lösungsfeldern die Fehler! int a = 5; int pi = 3.14

System.out.println(„Nein!");

Verbessern Sie im Lösungsfeld die Fehler! system.out.println (Nein!);

SQL keyword

WHERE

Zeichen

Was bedeutet der Dateityp "char"?

double wird für Variable verwendet, die auch Nachkomma Zahlen aufnehmen können.

Was bedeutet der Dateityp "double"?

integer wird für Variablen verwendet, die nur ganze Zahlen aufnehmen können.

Was bedeutet der Dateityp "integer"?

für ganz grosse Zahlen

Was bedeutet der Dateityp "long"?

i = i + 1;

Was bedeutet i++?

3

Was für ein "ergebnis" liefert das folgende Programm? int i, ergebnis = 0; for (i = 1; i < 4; i=i+1) { ergebnis = ergebnis + i; }//for

Downcast bedeutet, dass man zum Beispiel eine double Zahl in eine integer Zahl konvertiert. double z; int y; z = (int) y;

Was heisst in Java "downcasting"? Wie wird es gemacht?

3

Was ist der Inhalt der Variablen „result" nach dem Durchlauf der folgenden for-Schleife? int result = 0; for (int i = 1; i <= 3; i = i + 1) { result = result + 1; }//for

"Math.random" erzeugt eine Zufallszahl zwischen 0 und 1.

Was macht die Funktion "Math.random"?

11

Welches ist die grösstmögliche Zufallszahl z? double z = Math.random(); z = z * 12; z = (int) z;

0

Welches ist die kleinstmögliche Zufallszahl z? double z = Math.random(); z = z * 12; z = (int) z;

Mit: File - Save oder: File - Save all

Wenn in Eclipse ein Programm mit Rechtsklick - Run as ausgeführt ist, ist es automatisch auch gespeichert. Wie kann man das Speichern erzwingen, ohne das Programm auszuführen?

reserved words

What are blue words called?

classes

What are system and string?

polymorphism, inheritance, encapsulation

What are the three characteristics of an oop language?

Single line comment // C-Style /* */ used for multiple lines Doc-Style /** */ used for multiple lines and documentation

What are the three types of comments?

Oracle

What company bought out the original company?

Sun Microsystems

What company developed Java?

convert byte code into binary

What do JIT and JVM do?

input.output

What does a parallelogram symbolize in a flow chart?

a process to be carried out

What does a rectangle symbolize in a flow chart?

source code editor, compiler/interpreter, build automation tools, a debugger

What does an IDE normally consist of?

direction of the flow

What does an arrow symbolize in a flow chart?

start/end of the program

What does an oval symbolize in a flow chart?

quotes

What has to surround strings?

left justified

What is a minus sign used for?

library

What is a synonym for package?

execute

What is a synonym for run?

comment block

What is a synonyn for C-Style?

A class in the Java API

What is an ArrayList?

Integrated Development Environment Integrated Design Environment Integrated Debugging Environment

What is an IDE?

curly braces

What is put around related statements?

JCreator or JCreator Pro

What is the IDE that we use in class?

Java libraries

What is the Java API?

more control over how data is displayed

What is the benefit of the format method?

println moves to a new line

What is the difference between print and println?

.java

What is the file extension for source code?

name full date period code description

What is the four line heading made up of?

What does it mean when something is passed by reference?

When something is passed by reference, changes made to it will be changed. You are passing the reference of the object and therefore changing it.

instance of a class

When you construct an object from a class ex Dog jasmine=new Dog();

Window - Show View - Package Explorer

Wie blendet man in Eclipse den Package Explorer ein, der einem die Übersicht über die vorhandenen Klassen anzeigt?

Rechtsklick auf src New - class File - save

Wie erstellt man in Eclipse eine neue Klasse?

6

Wie gross ist r nach dem Durchlauf der folgenden Schleife? int r = 3; for (int i = 0; i < 3; i = i + 1) { r = r + 1; }//for

Editor

Wie heisst in Exclipse das Fenster, in dem der Code geschrieben wird?

Das Programm muss irgendwo stoppen und zum Beispiel auf eine Eingabe warten.

Wie kann man bei einer while(true)-Schleife verhindern, dass eine Endlos-Schleife entsteht und das Programm die Schleife ewig durchläuft, bis der PC „hängt"?

if (Bedingung) {Anweisungen} else {Anweisungen}

Wie lautet allgemein die Syntax einer if-else Anweisung? Mit Klammern!

System.out.println(„Die Variable k hat nach „ + n + „ Durchläufen den Wert" + k)

Wie lautet die Code-Zeile, um die folgende Ausgabe zu erhalten? Für n=50 und k=200 sollen dabei die Inhalte dieser Variablen wie folgt ausgegeben werden: Die Variable k hat nach 50 Durchläufen den Wert 200

System.out.print("Das Resultat ist: " + r);

Wie lautet die Programmzeile, die den folgenden Satz und den Inhalt der Variablen r (5) ausgibt? Das Resultat ist: 5

for(int i = 1; i <= f; i++) { Anweisungen }//for

Wie lautet die Syntax der for Anweisung? Mit Klammern!

while(true { }

Wie lautet die Syntax der while (true) Anweisung? Mit Klammern!

switch ( Ausdruck ) { case Wert1: Anweisung1; break; case Wert2: Anweisung2; break; case Wertn: Anweisungn; break; }

Wie lautet die korrekte Syntax der switch Anweisung? Mit Klammern!

if (Bedingung) {Anweisungen} else {Anweisungen}

Wie lautet die korrekte Syntax einer if - else Anweisung mit allen Klammern?

if (Bedingung) {Anweisungen}

Wie lautet die korrekte Syntax einer if Anweisung mit allen Klammern?

public static void Kreisflaeche() { }

Wie lautet die korrekte class-Zeile? Mit Klammern!

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

Wie lautet die korrekte main-Zeile? Mit Klammern!

Window - Open Perspective - Java

Wie stellt man Eclipse so ein, dass die Java Ansicht eingeblendet wird?

Rechtsklick: Run as - Java Application.

Wie wird in Eclipse eine Klasse kompiliert und gleichzeitig ausgeführt?

How is an instance block wrote?

With two brackets outside of the main method.

float

The float data type is a single-precision 32-bit IEEE 754 floating point. Its range of values is beyond the scope of this discussion, but is specified in the Floating-Point Types, Formats, and Values section of the Java Language Specification. As with the recommendations for byte and short, use a float (instead of double) if you need to save memory in large arrays of floating point numbers. This data type should never be used for precise values, such as currency. For that, you will need to use the java.math.BigDecimal class instead. Numbers and Strings covers BigDecimal and other useful classes provided by the Java platform.

What is the new method of the Locale class to Java SE 7?

The getUnicodeLocaleAttributes method was introduced to the Locale class in JDK 1.7 along with the getDefault, setDefault, getScript, getExtension, getExtensionKeys, getUnicodeLocalType, getUnicodeLocaleKeys, toLanguageTag, forLanguageTag, and getDisplay script. It's presented here to stress your need to be familiar with the Javadoc documentation of the Java API specification.

decision structure

The if statement is an example of a

way to genericize new Fragment();

(TO) createFragment() take constructor form and replace with function to genericize (refactor)...but either have to define function right there, or create abstract stub, making class abstract

What will be printed? System.out.println("roberto".replaceAll("o", "!").substring(1, 7));

!bert!

To invert the value of a boolean, which operator would you use?

"!" logical complement operator

Steps in Creating Pseudocode

1. Understand the Problem 2. Decide How to solve the problem 3. Write the Solution Using a logical sequence of statements

double PI =3.145;

1. Verbessern Sie die Fehler! double PI = 3,145;

3

1. Was ist der Inhalt der Variablen „result" nach dem Durchlauf der folgenden for-Schleife? int result = 0; for (int i = 1; i <= 3; i = i + 1) result = result + 1;

What is the difference between = and ==?

== is used for comparison and = is used for assignment.

2 main benefits of abstraction

1) good design, 2) (unintended) security in that hackers are not going to guess setCartesianCoordinates(integer x, integer y); but would rather first guess setX(integer x);

What is difference between static (class) method and instance method?

1)Object is not required to call static method. Object is required to call instance methods. 2)Non-static (instance) members cannot be accessed in static context (static method, static block and static nested class) directly. static and non-static variables both can be accessed in instance methods.

Which array initializations are illegal? 1// int[] arr = new int[]; 2//int []arr = new int[5]; 3// int[][] arr = [1][4]; 4// int arr[][] =new int [][2]; 5// int arr[][] = new int[2][]; 6//int arr = new int[2]; 7//int[][] arr = new[5]{1,2,3};

1,3,4,6,7

java.io.Serializable is a marker interface, also known as a tag interface. What is the unique attribute of marker interfaces?

A marker interface includes no methods or fields.

Local Variable

A variable declared inside a method that is accessible only in that method

All programs have at least two threads.

False

-Must start with a letter -Can contain letters, numbers, and underscore character -Cannot contain spaces -Cannot contain reserved (key) words

Identifiers (name) Rules

Variables

Identifiers used to store values that may change.

Name the variable NOTE: starts with lower case, new word starts with capital letter (numDays)

Identity

What is method overloading?

If a class have multiple methods by same name but different parameters, it is known as Method Overloading. It increases the readability of the program.

volatile

Imposes strict rules on the use of a variable by more than one thread at a time.

method

In System.out.print what is "print"?

object

In System.out.print what is "out"?

strictfp

Limits the computer's ability to represent extra large or extra small numbers when the computer does intermediate calculations on float and double values.

Which are valid array declarations? 1// arr[] int; 2// arr[] arr1; 3//arr[][5] arr2; 4//arr[][] arr4 = new arr[][];

Line 2, array declarations are not initialized yet.

static

One copy and everyone can see it

Vergleichsoperatoren

Operatoren wie > < <= ... heissen ...operatoren.

Associativity

Order of Operation for Equal Level Precedence. Most operator have left to right associativity.

Input and Output (I/O)

Output :System.out.println('hello World!"); Input from Scanner: Note scanner is a build in type.

Identifiers

Names of Variables. They are case sensitive. They can use digits 0-9,$, and underscore. Cannot start with a digit. Cannot contain spaces or other characters. Cannot use JAVA Keywords.

Can You use float in a switch statement?

No

Can a local variable be protected?

No

Can a short be passed to the append method in String Builder?

No

Can a static method be overridden without the static modifier and vise versa?

No

Can an abstract method be final?

No

Can an abstract method be static?

No

Can you use continue in a switch?

No

Can you use long in a switch statement?

No

If a class has a private constructor can their be an instance of that class(object) outside of the class?

No

Is it legal to use .super in static methods?

No - .this and .super cannot be used or a compilation error will happen.

Is it legal to use .this in static methods?

No - .this and .super cannot be used or a compilation error will happen.

Can a class be protected(Given it is not an inner class)?

No - Inner classes can be private or protected regular classes cannot.

Can you initialize an array like this - int arr2[] = {1,2,3,4}

No - You need the new keyword

Can you override Strings methods if yes why?

No because String is a final class.

float

Real Number.Range of Typically (=/-) 10e-45 to 10e38.

return SQL query result

ResultSet

;

Semicolon

Test Plan

Series of tests (ex. inputs) that have predetermined expected outputs. Program should be tested several times with different inputs, and under all potential conditions.

Instance variables

Set to 0 a = 0; b = 0; c = 0;

Postcondition

Should be true when method finished executing

Precondition

Should be true when method is called

print (return)

System.out.println();

how to pass an object to a method

System.out.println(new Date()):

print println format

What are the three basic methods?

Enumeration

This interface generates a series of elements, one at a time. Successive calls to the nextElement method return successive elements of the series.

Runnable

This interface should be implemented by any class whose instances are intended to be executed by a thread. The class must define a method of no arguments called run.

flag

This is a boolean variable that signals when soem conditions exists in the program

Variable

This is a named storage location in the computer's memory.

null statement

This is an empty statement that does nothing

nested if statement

This is an if statement that appears inside another if statement

new

This key word creates an object

Final

This key word is used to declare a named constant

When a Thread object is constructed with a Runnable object as input, the Thread object uses the run method of the Runnable object

True

only the Model layer, shown in the figure, operates on persistent data.

True

Escape sequences

Two-character sequences that are used to represent special characters They all begin with the backslash character. (\) \t tab character \n new line charachter \" quotation mark \\ backslash character

Stack overflow error

Typically this is caused when your recursive functions don't have the correct termination condition, so it ends up calling itself for ever.

Method overloading

Using same method name with different parameters lists for several methods

StringBuffer

Utility Class part of java.lang ; methods: insert, append - multy tread environments, synchronize use of a string among multiple treads

blank.

Value

in a statement that violates the rules of Java

Where does a syntax error occur

Can you declare the main method as final?

Yes, such as, public static final void main(String[] args){}.

What is a compound assignment operator?

You can also combine the arithmetic operators with the simple assignment operator to create compound assignments. For example, x+=1; and x=x+1; both increment the value of x by 1.

varargs construct

You can use a construct called varargs to pass an arbitrary number of values to a method. You use varargs when you don't know how many of a particular type of argument will be passed to the method. It's a shortcut to creating an array manually To use varargs, you follow the type of the last parameter by an ellipsis (three dots, ...), then a space, and the parameter name. The method can then be called with any number of that parameter, including none.

JOptionPane

You can use this class to display dialog boxes

const

You can't use this word in a Java program. The word has no meaning. Because it's a keyword, you can't create a const variable.

types of modifiers

access modifiers,

way to get private variables from another class

accessor methods

ACK

acknowledgement message that contains the sequence number of a correctly received packet; this lets the sender know the packet was received

actual parameter

actual value or reference that is passed to a method or subroutine -> gary.transfer(200); 200 is the actual parameter

add() remove()

add something to ArrayList remove something to ArrayList

What is JavaDoc?

a documentation generator from Oracle that can create API documentation in HTML from java source code using annotations.

What is an arrayList

a inherently ordered dynamic data structure that implements the List interface and extends AbstractList

Do loop

a loop that has 0 or more iterations of the loop body

while loop

a loop that has 1 or more iterations of the loop body

Initialize an array

anArray[0] = 100; or int[] anArray = { 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000 };

instance variable

any item of data that's associated with a particular object.

white space

any sequence of only space, tab, and newline characters

The term API stands for ___?

application programmer interface

data passed to a method for processing

arguments

ALU

arithmetic/logic unit. sub system that performs math and logical operations.

bit

binary digit; smallest unit of information, either 0 or 1; n bits has 2^n possible values

constructor

block statement created when an object is declared

How do you write an infinite loop using the for statement?

for ( ; ; ) { //do something }

for loop (use i and N)

for (int i = 0; i < N; i++) { }

"for loop" syntax

for (iterator initialization; iterator comparison; iterator incrementalization) {}

adjective name

for interfaces (modify a class, which is usually a noun) eg, public interface Drivable{}

Import statement for libraries

import others java.util

local variable

is a variable that is declared in the body of a method

If a method has a public access modifier and a subclass overrides that method, what must its access modifier be?

public. If it where default it could be either public or protected.

Math.sqrt(x)

square root of x

ObjectInputStream

this class deserializes primitive data and objects previously written using an ObjectOutputStream. ObjectOutputStream and this class can provide an application with persistent storage for graphs of objects when used with a FileOutputStream and FileInputStream respectively. this class is used to recover those objects previously serialized. Other uses include passing objects between hosts using a socket stream or for marshaling and unmarshaling arguments and parameters in a remote communication system.

the equals method

this determines whether two different String objects contain the same string.

using this(newHealth) within constructor

this goes up to the root class (Monster) and newHealth refers to it's field (class variable)

default

this section of a switch statement is branched to if none of the case expressions match the switch expression

Variable Assignment

to assign a value (using the assignment operator - " = ") to a variable name

Describe how to work with objects and variables

to work with objects, you first construct them and specify their initial state. Then you apply the methods to objects

5. The -______- always returns a reference to a String that contains the state of the object.

toString Method

primitive data type

total of 8, include 4 integer types and 2 floating point types. int 4, byte 1, short 2, long 8, double 8, float 4, char 2, boolean 1 bit. A value that's not a reference to an object.

code fragmanet, sbuf references.. sbuf.insert

true

stack and heap

two main memory locations for Java

.... native client library....

type 2

address

unique identifier for a cell, this is how memory is divided

how to get tread dump

unix command

__ method is used to wait for a client...

accept()

values[i] = 0;

access element of array at position i (count starts from 0)

Create an array

anArray = new int[10];

Get the length of an array

anArray.length

final keyword

code cannot be changed(overridden) by subclass

ArrayList<string> stringList = new ArrayList<string>();

code to declare a string array list called stringList

public class Triangle extends Shape

code to make triangle subclass from Shape superclass

source file contains a large number of import statements ( compilation )

compilation takes slightly more time

What is a constructor

constructors always have the same name as the class name. The constructor for the Date class is called Date.. to construct a Date object, you combine the constructor with the "new" operator as follows: new Date() -this expression constructs a new object.

Method

contains a collection of programming instructions that describe how to carry out a particular task; consists of a sequence of instructions that can access the internal data of an object

Memory Data Registrar (MDR)

contains the data value being fetched or stored

continue vs break in a while loop

continue jumps back up to while, break jumps down out of while loop.

guidelines

conventions

String s = "foo";

declare string s; set to foo

Scanner in = new Scanner(System.in);

declares Scanner "in"

String s = in.nextLine();

declares and inputs a line (a string of characters)

double d = in.nextDouble();

declares and inputs a real value (floating point #)

int i = in.nextInt();

declares and inputs integer value

Abstract keyword

denotes a class that cannot be instantiated and provides no implemntation for its member methods and fields - used to define certain behaviors and properties of subclasses

{}

denotes block

void

describes function that returns no value

private

describes property that can only be accessed locally

static

describes property that never changes

object-oriented programming

designing a program by discovering objects, their properties, and their relationships

StringBuffer

mutable character holder

StringBuilder

mutable java 5 character holder; not thread safe

What's wrong with the following program? public class SomethingIsWrong { public static void main(String[] args) { Rectangle myRect; myRect.width = 40; myRect.height = 50; System.out.println("myRect's area is " + myRect.area()); } }

myRect is declared, but it is not instantiated or initialized. area() is not a method of Rectangle. getArea() is the public method.

ArrayList methods

names.size() names.get(i); names.set(0, "Felicia Day"); this will REPLACE John Smith names.remove(3); copy: copiedAR.addAll(names); copy names ArrayList into copiedAR if (names.contains(paulYoung)) {} to check if two arrays are equal (containsAll elements of ) -- if (names.containAll(namesCopy)) {} //if the ArrayList names contains All elements in namesCopy .clear() .isEmpty() secondCopy = namesCopy.toArray(); //copy to secondCopy

<0

negative

String input

next() nextLine()

String input = in.next();

next() reads the next string; returns any charas that are not white space

double input

nextDouble()

float input

nextFloat()

int input

nextInt()

is private variable accessible within inherited subclass

no...access violation...and reason for accessor methods

The term "instance variable" is another name for...

non-static field - instance variables are specific to an object

Comments

nonexecutable statements in a program that can be used to document the purpose of the program or to track changes to the program

mass storage

nonvolatile storage, information can be saved between shutdowns. The storage of large amounts of data in a persisting and machine-readable fashion.

!=

not equal

!

not(makes true or false)

an instance is another way of saying ____?

object

AssertionError

object thrown when assertion is untrue

Java

program used to run .class files

URL referring to databases

protocol:subprotocol:datasourcename

a mixture of english and code

pseudocode

class and package access modifiers

public - member accessible within and outside package private - member accessible only to other members within class (NOT subclass!) protected - accessible within package and all of its subclasses (including subclasses in other packages)

What must the access modifier of a method that is implementing an interface be?

public - since all interface methods are automatically public methods that override it have to have the same or higher visibility rank.

default access modifier, type for variables within interfaces

public abstract

Methods in interfaces are automatically what?

public and abstract.

class declaration/definition

public class Greeting {} What is this?

Increment Operator

public class IncrementOperators9 { public static void main(String[] args) { int tuna = 5; int bass = 18; ++tuna; System.out.println("Tuna- " + tuna); System.out.println("Bass- " + bass++); int x; x = 5; x += 5; System.out.println("this is x- " + x); int y; y = 2; y *= 5; System.out.println("this is y- " + y); } }

Logical Operator

public class LogicalOperators11 { public static void main(String[] args) { int boy, girl; boy = 18; girl = 68; // && both have to be true, || one has to be true if (boy > 10 && girl < 60){ System.out.println("You can enter"); }else{ System.out.println("You can not enter"); } } }

Switch Statement

public class SwitchStatement12 { public static void main(String[] args) { int age; age = 30; switch (age){ case 1: System.out.println("you can crawl"); break; case 2: System.out.println("you can talk"); break; case 3: System.out.println("you can get in trouble"); break; default: System.out.println("I dont know how old you are"); break; } } }

Methods With Parameters- Class 2

public class UseMethodsWithParameters15P2 { public void simpleMessage(String name) { System.out.println("Hello " + name); } }

I/O buffer

small amount of memory inside the I/O controller

I/O buffer

small amount of memory that the I/O controller has

ancestor

(n) tổ tiên, ông bà

lurk

(n) ẩn, núp

framework

(n)khung,sườn,lõi

assertion

(n)sự khẳng định, thừa nhận

modifier

(n)từ bổ nghĩa

wrap

(v) gói, bọc

encounter

(v) gặp, chạm trán

terminate

(v)=finish

synchronize

(v)đồng bộ

assign userInput to a variable

(within if statement) int numberEntered = userInput.nextInt(); ...also Line, Boolean, Float

Defining Parameters

...

data access class

...

field

...

how do you use collection

...

object

...

Why should I bundle classes and interfaces into a package?

1. You and other programmers can easily determine that these types are related. 2. You and other programmers know where to find types that can provide related functions. 3. The names of your types won't conflict with the type names in other packages because the package creates a new namespace. 4. You can allow types within the package to have unrestricted access to one another yet still restrict access for types outside the package.

class Q6 ( Holder )

101 ( tăng 1 so vs held gốc )

What is the last index of the string TEXT?

3. The first letter starts with index 0.

Eine Folge von Anweisungen, die für die Maschine in verständlicher Form ausformuliert wird.

4.Definieren Sie auf möglichst engem Raum, was eigentlich ein Programm ist.

int b1 = 0b_0101_0101_0101_0101; int b2 = 0b_1010_1010_1010_1010; int b3 = b1 & b2; System.out.println("Value:" + b3); What will be the result?

A compilation error will occur because an underscore cannot be used after the b in the literal. The other underscores are allowed.

Identifier

A name given to an entity in a program, such as a class or method. Identifiers must start with a letter, underscore, or $. illegal identifiers two+two, hi there hi-there 2by4

Binary Number

A number composed of 0s and 1s, also known as base-2 number.

What is platform?

A platform is basically the hardware or software environment in which a program runs. There are two types of platforms software-based and hardware-based. Java provides software-based platform.

3. Describe the difference between pretest loops and posttest loops. ?

A pretest loop tests its test expression before each iteration. A posttest loop tests its test expression after each iteration.

Java Runtime

A program that executes compiled Java bytecodes.

Compiler

A program that translates a computer program written in one language into an equivalent program in another language (often, but not always, translating form a high-level language into machine language).

Method

A program unit that represents a particular action or computation. The next-smallest unit of code in Java, after classes. They represent a single action or calculation to be performed. Several methods can be defined with in a class.

what can be put in main to access a and staticAccess? public class A{ static int a = 13; static void staticAccess(){} public static void main(String args[]){ //Line 1 // Line 2 } }

A.a and A.staticAccess You can use the class name to call a static member.

;

All Java statements must end with it.

Hard Drive

Also called a hard disk. The place that a computer stores data permanently.

Logic errors

Also called bugs. When you write code that doesn't perform the task it is intended to perform.

ASCII

American Standard Code for Information Interchange, which encodes 128 characters from 8-bits (binary)

What is an accessor?

An accessor is a method that returns the value of a property of a dto - referred to as a 'getter'

What does API stand for?

An application-programming interface (API) is a set of programming instructions and standards for accessing a Web-based software application or Web tool

"enum" type

An enum type is a type whose fields consist of a fixed set of constants. Common examples include compass directions (values of NORTH, SOUTH, EAST, and WEST) and the days of the week.

Statement

An executable snippet of code that represents a complete command

Which of the following is true regarding subclasses? A) A subclass may call the superclass constructor by using the this reserved word. B) A subclass cannot call the superclass constructor. C) If a subclass does not call the superclass constructor, it must have a constructor with parameters. D) If a subclass does not call the superclass constructor, it must have a constructor without parameters.

Ans: D Section Ref: 10.4

Which of the following statements generally describes the scope of a variable? A) The ability of a variable to access other variables in the same program. B) The amount of data in bytes that the variable can contain. C) The range of data types that the variable can legally be cast into. D) The region of a program in which the variable can be accessed.

Ans: D Section Ref: 8.8

Which of the following is not a reason to place classes into a package? A) to avoid name clashes (most important) B) to organize related classes C) to show authorship of source code for classes D) to make it easier to include a set of frequently used but unrelated classes

Ans: D Section Ref: 8.9

ArrayList eg

ArrayList<String> names = new ArrayList(); names.add = "John Smith"; names.add = "Pete Wendell"; names.add = "Alicia James"; these are added just as they would be in an array, with John smith at index 0, pete at index 1... however, i can also do names.add(2, "Harvey Dent"); which must current 2 index to right...

A ext Objectl B ext A; C ext B, java.io.Serializable

B must have no-args constructor

Digital

Based on numbers that increase in discrete increments, such as the integers 0, 1, 2, 3, etc.

Byte

Basic Unit of storage. Can store one letter of the alphabet or Keyboard. (1 byte is 8 bits -256 combinations).

Class

Blueprint from which an object is created

int

By default, the int data type is a 32-bit signed two's complement integer, which has a minimum value of -231 and a maximum value of 231-1. In Java SE 8 and later, you can use the int data type to represent an unsigned 32-bit integer, which has a minimum value of 0 and a maximum value of 232-1. Use the Integer class to use int data type as an unsigned integer. See the section The Number Classes for more information. Static methods like compareUnsigned, divideUnsigned etc have been added to the Integer class to support the arithmetic operations for unsigned integers.

signature

Combination of identifiers, return value, name and parameters of a method. Example: public int calculateMonth(String name)

.... objects in a List to be sorted,..

Comparable interface and ít compareTo method

If two classes are not in the same class tree and an instanceof operator compares them what will be the output?

Compilation Error

What is the difference between constructor and method?

Constructor will be automatically invoked when an object is created whereas method has to be called explicitly. Constructor doesn't have return types and its name must be the same as the Class' When constructor is invoked, it may invoke the constructors of the super classes.(call stack)

Which access modifiers can be applied to constructors?

Constructors can have package-private, private, protected, and public access modifiers applied to them.

4

Das Ergebnis der folgenden Schleife ist: int result = 0; for (int i = 0; i < 5; i = i + 1) result = result + 1;

Methods

Define the object's behaviors

/=

Divides value of operand by whatever number is placed after

Void

Does not return a value

Static classes

Dont have instances

obtain a Connection to a Database

DriverManager

* / %

Ergänzen Sie die drei fehlenden arithmetischen Operatoren, die in Java für die Grundrechenarten verwendet werden: + - ...

a) z bleibt vom Typ double, auch nach einem downcast, so wird eine neue integer Variable nötig, die wir innerhalb der for-Schleife als Index des Arrays gebrauchen können. b) Wenn die aktuell gezogene Zahl schon einmal gezogen wurde, muss die Laufvariable i um eins vermindert werden, sodass eine weitere Zahl gezogen werden kann.

Erkläre! a) Weshalb wird eine neue Variable y nötig? b) Weshalb wird hier um 1 verkleinert? BILD FEHLT

-Begins with a \ -Always comes in pairs

Escape sequences

Address

Each byte is assigned a unique

element

Each item in an array

Advantages of Constants

Easier to Understand. Easier to Modify.

native

Enables the programmer to use code that was written in another language (one of those awful languages other than Java).

What are Encapsulation, Inheritance and Polymorphism?

Encapsulation is the mechanism that binds together code and data it manipulates and keeps both safe from outside interference and misuse. Inheritance is the process by which one object acquires the properties of another object. Polymorphism is the feature that allows one interface to be used for general class actions.

DASD

Every unit of information has a unique address but the time needed to access the information depends on its physical location and the current state of the device. Stands for direct access storage device.

Declared

Every variable must be declared,which sets aside memory for the storage location.

What does the substring method written like this return - stringName.subString(1)?

Everything from index 1 and up(Inclusive)

What does the substring method written like this return - stringName.subString(1,5)?

Everything in that string starting from index one and up to 5-1 or 4.

What does the substring method written like this return - stringName.subString(6,5)?

Exception

20. True or False: The do-while loop is a pretest loop.

F

False

If one of an operator's operands is a double, and the other operand is an int, Java will automatically convert the value of the double to an int.

Will this line compile without errors? Object [ ] obj = new Object [ ];

Incorrect because they do not assign a size to the array.

Will this line compile without errors? Object obj [ ] = new Object[ ] ;

Incorrect because they do not assign a size to the array.

Will this line compile without errors? Object [ ] obj = new Object ();

Incorrect because they have () instead of [] after the type.

++

Increment operator - Increases the value of operand by 1 can be both prefix and postfix ++prefix is value after increment postfix++ is value before increment

+=

Increment operator - Increases value of operand by whatever number is placed after

throws

Indicates that a method or constructor may pass the buck when an exception is thrown.

protected

Indicates that a variable or method can be used in subclasses from another package.

public

Indicates that a variable, class, or method can be used by any other Java code.

< >

Indicates that something needs to be filled in. For example,public class <name> means that a name for the class needs to be filled in.

What happens when a class final?

It cannot be extended?

What can't a method not do when it is final?

It cannot be overloaded.

memory address register

It is 32 bits. Used in memory write and read operations and not accessible by the programmer.

What is super in java?

It is a keyword that refers to the immediate parent class object.

If I don't provide any arguments on the command line, then the String array of Main method will be empty or null?

It is empty. But not null.

What is difference between JDK,JRE and JVM?

JVM is an acronym for Java Virtual Machine, it is an abstract machine which provides the runtime environment in which java bytecode can be executed. JRE stands for Java Runtime Environment. It is the implementation of JVM and physically exists. JDK is an acronym for Java Development Kit. It physically exists. It contains JRE + development tools.

Java virtual machine

JVM stands for

Java 7's Garbage-First (G1) garbage collector is planned as the long-term replacement of which collector?

Java 7's Garbage-First (G1) garbage collector is planned as the long-term replacement of the Concurrent Mark-Sweep (CMS) collector.

What is the JDK?

Java Development Kit.

JRE

Java Runtime Environment Distributed by Sun Microsystems

JVM

Java Virtual Machine A theoretical computer whose machine language is the set of Java bytecodes.

What is the JVM?

Java Virtual Machine.

JDK

Java development kit

Primitive types

Java variable -- Simple values stored directly in the memory location associated with the variable

break

Jumps out of a loop or switch.

synchronized

Keeps two threads from interfering with one another.

sie per drag and drop aus dem Ordner src auf den Memorystick zieht.

Klassen werden in Eclipse exportiert, indem man ...

hasMoreElements

Method of Enumeration. Tests if this enumeration contains more elements.

put

Method of Hashtable. Maps the specified key to the specified value in this hashtable.

remove

Method of Hashtable. Removes the key (and its corresponding value) from this hashtable.

containsKey

Method of Interface Map. Returns true if this map contains a mapping for the specified key.

start

Method of Thread. This method Causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread.

enumerate

Method of ThreadGroup. Copies into the specified array every active thread in this thread group.

run

Method. When an object implementing interface Runnable is used to create a thread, starting the thread causes the object's this method to be called in that separately executing thread.

-Segments of code that perform some action -Always followed by parenthesis EX: System.out.println("abc") <--- print is the ?

Methods

What are the two things classes have?

Methods and Variables.

What are the access specifiers in order of most restrictive to least?

Private, Default, Protected, and Public.

Logic.Semantic/Run-Time Errors

Program Complies, but Doesn't Produce the Expected Results

What if I write static public void instead of public static void?

Program compiles and runs properly.

What if the static modifier is removed from the signature of the main method?

Program compiles. But at runtime throws an error "NoSuchMethodError".

EVA

Programme arbeiten mit Daten, die häufig vom Benutzer eingegeben werden. Sie verarbeiten diese Daten und liefern Ergebnisdaten zurück. Dieser Datenfluss durch ein Programm (aber auch durch den Computer selbst) entspricht dem so genannten ...-Prinzip (Eingabe - Verarbeitung - Ausgabe).

declare a class

Public Class MemorizeThis {

How do you make an object cast first and then call a method?

Put the class in parenthesis next to the method and surround that in parenthesis. Ex: class B extends A{} A aa = new B(); ((B)aa.m1())

What does array.asList do?

Puts an array as an array list.

Comment

Text, ignored by the compiler, used to explain the code to the reader

If you print THIS in system.out.println, what will print?

That classes toString.

8. Which loop should you use when you know the number of required iterations?

The for loop.

What is the purpose of the Java garbage collection?

The garbage collection is used to discard any not used data.

Variable

The name (an identifier) given to a container that holds values in a Java program

Unary

The negation operator is

What is missing from the following multi-dimensional array declaration: int[][] array = int[10][10];

The new keyword is needed to establish memory allocation.

What is object cloning?

The object cloning is used to create the exact copy of an object.

What will be the initial value of an object reference which is defined as an instance variable?

The object references are all initialized to null in Java.

If you print an object what will be printed?

The objects toString method.

Flow of Control

The order in which the statements of a Java program are executed.

Scope

The part of a program in which a particular declaration is valid

Is this valid? short s = 1000s;

There is no s postfix.

braces {}

To create a block of statements, you enclose the statements in these

Halting Problem

To determine if a collection of Turing machine instructions together with any initial tape contents will ever halt if started on that tape

Why multiple inheritance is not supported in java?

To reduce the complexity and simplify the language, multiple inheritance is not supported in java in case of class.

Return

To send a value out as the result of a method that can be used in an expression in the program. Void methods do NOT return a value.

A subclass of Thread must provide an implementation of the run method because it implements the Runnable interface.

True

to display special characters

What is the purpose of escape sequences?

object oriented language

What kind of language is Java?

small home appliances

What was Java originally intended for?

short hand a = a + n;

a += n;

short hand a = a - n;

a -= n;

bit

a binary digit that is the smallest unit of information. 1 or 0.

truth table

a breakdown of logic functions by listing all possible values

Method Call

a command to execute another method

array

a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created.

Binary Number

a number composed of 0s and 1s (base-2 number)

explicit parameter

a parameter of a method other than the object on which the method is invoked. The parameter explicitly fed to a method through the parenthesis.

Interface

a reference type that provides a template for a contract bw one class and another. composed of method signatures which define the public interface of the implementing class

algorithm

a step by step description of how to accomplish a task

interface (in Java)

a type with no instance variables, only abstract methods and constants

JDBC 2-tierprocessing model

a user's command are delivered to the database

instance variable

a variable defined in a class for which every object of the class has its own value

method types allowed in abstract class

abstract (no body), or non-abstract...whereas interface defines ONLY abstract methods

short hand a = a - 1;

a--;

computing agent

an abstract entity that can carry out the steps of the algorithm. They 1) accept input, 2) Store information and retrieve from memory, 3) Take actions according to algorithm instructions, 4) Produce an output.

Private Keyword

an access modifier that only allows access to that member from the class in which it resides

argument

an actual parameter in a method call or one of the values combined by an operator

What is the heap?

an area of memory allocated for objects by the JVM

what is an array?

an array is a container object of fixed length that holds values of one type

transistor

an electrical switch with no moving parts

logic gate

an electronic device that operates on a collection of binary inputs to produce a binary output.

What is an object in Java

an instance of a class

What is an object?

an instance of a class

object

an instance of a class

parameter

an item of info specific to a method when the method is called

Iterator

an iterator is an object that visits each element in a collection once - order off iteration is not guaranteed (every type in the Collections Framework has an iterator)

Polymorphism

an object can take on multiple types, therefore having the capacity to be referred to in multiple ways

instance

an object of a particular class. Created using the new operator followed by the class name

What is a Collection?

an object that stores multiple elements in a single unit

assert(a==b);

assert assumption that integer a equals b

b = a[2];

assign b to second item in array a

if(i==1) { j=2; }

assign j the value 2 when i is equal to 1

initialize

assigning a value to a variable when it's created

ARQ algorithm

automatic repeat request; basis for all data link control protocols in current use -> a message is sent from A to B, A holds on the the message until an ACK is sent back from B

7. The do - while loop is this type of loop. a. pretest b. posttest c. prefix d. postfix

b

binary

base 2 positional numbering system composed of 1s and 0s

Object oriented programming

building programs by creating, controlling, and modifying one or more objects

concatination

but strings together

-8 bits Range: -128 to 127 No rules

byte

What are the only things you can use in switch statements?

byte, short, int, char, string and enum

What are all the primitives?

byte,short,int,long,float,double,char,boolean.

9. This type of loop has no way of ending and repeats until the program is interrupted. a. indeterminate b. interminable c. infinite d. timeless

c

default modifier

can be accessed only to classes in the same package

primitive data type

determines the values a variable can contain; int, byte, short, long, double, float, char, boolean

-16 bits unsigned Range: 0 to 65535 -Holds one letter -Value enclosed in ' ' -Outputs letter unless addition is in parenthesis

char

What methods would a class that implements the java.lang.CharSequence interface have to implement?

char charAt(int index) Returns the char value at the specified index. int length() Returns the length of this character sequence. CharSequence subSequence(int start, int end) Returns a new CharSequence that is a subsequence of this sequence. String toString() Returns a string containing the characters in this sequence in the same order as this sequence.

Braces

characters used to mark the beginning and end of blocks of code

in.hasNextDouble()

checks for numerical input; false if the next input is not a floating-point number

A blueprint for a software object is called a...

class

IOException

class for error in io

The ___ statement is similar to the while statement, but evaluates its expression at the ___ of the loop.

do while end

do { i++; //more code }while (i<max)

do/while loop

-64 bits Range: -big to big

double

declare and define a double, a, from command line argument

double a = Double.parseDouble(args[0]);

double b = a / b, but a is an int. Cast int to double

double b = (double) a / b;

declare and initialize primitive variables

double thisIsDouble; int thisEnter; thisIsADouble=0.0; thisEnter=0;

declare and initial double array, points, with length N

double[] points = new double [N];

Math.exp(x)

e^x

Arrays.toString(values) = [4,7,9...]

elements separated by commas with brackets

Hiding internal data from the outside world, and accessing it only through publicly exposed methods is known as data...

encapsulation

What does encapsulation mean?

encapsulation is a term that refers to the separation of the public interface and private implementation of an object - the objects inner implementation should be hidden from the user. hide data by using the private keyword on fields and methods that users do not need to know about

for (typeName variable: array/collection) { sum = sum + variable; }

enhanced for loop for arrays; adds each element of array to sum (declared before loop)

static variables

essentially global variables...when a member is declared static it can be accessed before any instance of its class is created and without reference to any object....static variables can be shared by multiple classes, but changing the static variable in one place changes it globally.

actual parameters

expression supplied by a formal parameter of a method by the caller. Value of the parameter.

implement an abstract class

extends public class Vehicle extends Crashable implements Drivable {}

CallableStatement

extends PreparedStatement. The interface used to execute SQL stored procedures. The JDBC API provides a stored procedure SQL escape syntax that allows stored procedures to be called in a standard way for all RDBMSs. This escape syntax has one form that includes a result parameter and one that does not. If used, the result parameter must be registered as an OUT parameter. The other parameters can be used for input, output or both. Parameters are referred to sequentially, by number, with the first parameter being 1.

a thread wants to make a second thread ineligible

false

Members

fields(data the class holds), methods

What is the only modifier that a local variable can be?

final

memory

function unit of a computer that stores and retrieves instructions and data

memory

functional unit of a computer that stores and retrieves the instructions and data being executed

overloading a method

giving more than one meaning to a method name

public static double cubeVolume (double sideLength)

header for method

encapsulation

hiding of implementation details

instruction register

holds a copy of the instruction fetched from the memory. It holds both the op code and the addresses

import java.util.Scanner

imports Scanner library

key word abstract

in abstract class keyword abstract must be use for all of its methods

Things an object knows about itself are called ?

instance variables

variables declared inside a class but outside any method

instance variables

G g = new G(); g.m();

instantiate object g of class G; run its method m

What is super()?

it calls the superclass constructor.

-es

java switch to run a program with assertions active

more eagle-eyed view of exception types

java.util.RunTimeException (developer responsible for catching these) java.util.Exception (compiler will warn about these errors anyway) common Exceptions, which are the 5 above types

Return

keyword that stops execution of the method,goes back to where you started

Racoon,SwampThing,Washer

line 7 will not compile ( phải ép kiểu )

variables declared inside a method or method parameter

local variables

/* */

long comments

public static void main(String[] args)

main method block syntax

INCORRECT..ServerSocket class

make new object avaiable... call its accept()

predefined variable

or implicit object

implicit object

or predefined variable

||

or(one or both are true)

data that's being displayed

output

A namespace that organizes classes and interfaces by functionality is called a ___.

package

package name

package firstApplication; What is this?

A variable declared within the opening and closing parenthesis of a method signature is called a ____.

parameter

explicit parameter

parameter of a method OTHER THAN THE OBJECT ON WHICH METHOD IS INVOKED

logic gate

performs a logical operation on one or more logic inputs and produces a single logic output

System.out.println("foo");

print foo on a line

System.out.print

prints statement

Scanner in = new Scanner(new File("input.txt");

reads input from a file (also declared in same line)

overriding a method

redefining a method in a subclass

java SentinelDemo < numbers.txt

redirects input

==,!=,>,<,>=,<=

relational operators; equal, not equal, greater than, less than, greater than/equal to, less than/equal to

s.replace("a","b");

replace instances of value "a" with "b" in string s

in.useDelimiter("[^A-Za-z]+");

restricts input to only letters, removes punctuation and numbers

return volume;

return statement that returns the result of a method and terminates the method call

str.indexOf(text)

returns the position (int) of the first occurrence of string (text) in string str (output -1 if not found)

What is scope?

scope is the concept of the access granted to a variable depending on where it is seen. class level variables can be 'seen' or accessed anywhere within their given class whereas variables declared in the body of a method cannot be accessed from other methods in the same class.

Consider the following code snippet. if (aNumber >= 0) if (aNumber == 0) System.out.println("first string"); else System.out.println("second string"); System.out.println("third string"); Exercise: What output do you think the code will produce if aNumber is 3?

second string third string

method

sequence of statements with a name. may have formal parameter and may return a value.

SASD

sequential access storage device does not require that all units of data be identifiable via unique addresses; to find the data, we must search sequentially, asking "Is this what I'm looking for?"

initialize

set a variable to a well-defined value when it is created (primitive data types)

Method Parameters

set in a method declaration - specify the number and type of arguments to be passed into the method

package

set of java programs together in same directory

What do real world objects contain?

state and behavior

Character.isDigit(ch)

statement (boolean), ch (char); allows you to check if ch is a digit or not

Character.isLetter(ch); Character.isUpperCase(ch); Character.isLowerCase(ch); Character.isWhiteSpace(ch);

statement (boolean), ch (char); allows you to check if ch is a letter/uppercase/lowercase/whitespace

while (condition) { statements }

statements = body of while loop; braces not needed for a single statement

assertions

statements to find error states by testing assumptions

What is static variable?

static variable is used to refer the common property of all objects (that is not unique for each object) . static variable gets memory only once in class area at the time of class loading.

mass storage

storage of large amount of data in machine readable form for access by a computer system

Reference types

store addressed of objects stored elsewhere in memory

false

the = operator and the == operator perform the same operation

condtion must be true....throw AssertionError

the application must be run... the args must have one or more...

Uppercase

the capital letters of the alphabet

portability

the computer program is independent of the details of each particular computer's machine language because each compiler takes care of the translation

Stored Program concept

the computers ability to store program instructions as binary in main memory for execution. Created by von Neumann

What does it mean if one class is derived from another?

the derived class extends from its ancestor class - inherits state and behavior

encapsulation

the hiding of implementation details and providing methods for data access

What does it mean to be loosely coupled?

the implementation of one class is not dependent on that of another - well defined classes with only one responsibility are easier to test and are not dependent on the implementations of other classes - by programming to the behavior of interfaces, the implementation behind the interface is irrelevant as any class that implements that interface can interact with those that are programmed to the behavior of the interface

address

the memory address of the values of which an operation will work

"final" modifier

use "final" to create a constant. The static modifier, in combination with the final modifier, is also used to define constants. The final modifier indicates that the value of this field cannot change. For example, the following variable declaration defines a constant named PI, whose value is an approximation of pi (the ratio of the circumference of a circle to its diameter): static final double PI = 3.141592653589793;

how to prevent overriding or inheritance

use of final before class declaration

superclass

used in inheritance, it is a class from which subclass inherits variables and methods

subclass

used in inheritance, it is a class that inherits variables and methods from its supper class

Relational or logical operators

used to compare primitive values

final keyword

used to denote a variable whose value is contant - can also be used in method declaration to assert that the method cannot be overridden by subclasses

instantiation

when instantiating a class, constructing an object of that class

variable = variable *X

variable *=X

25. True or False: In a nested loop, the inner loop goes through all of its iterations for every iteration of the outer loop.

T

switch

Tells the computer to follow one of many possible paths of execution (one of many possible cases), depending on the value of an expression.

assert

Tests the truth of a condition that the programmer believes is true.

if

Tests to see whether a condition is true. If it's true, the computer executes certain statements; otherwise, the computer executes other statements.

Comments

Text that programmers include in a program to explain their code. The compiler ignores comments. /* */ is one comment form ( everything in between is a comment) // a form used to indicate that the rest of the current line (everything to the right) is a comment

Output

Text that the computer prints to the console window.

What does it mean if a string is immutable?

That it cannot be changed once it is created.

Logic error

The "dangling else problem"

Byte code

The Java compiler generates___

What is the main difference between Java platform and other platforms?

The Java platform differs from most other platforms in the sense that it's a software-based platform that runs on top of other hardware-based platforms.It has two components: Runtime Environment, API(Application Programming Interface)

Executable

The Result of Compiling and Linking a Source Program; the ".exe" file that the Computer Can Run.

Copying Arrays

The System class has an arraycopy method that you can use to efficiently copy data from one array into another: public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length) The two Object arguments specify the array to copy from and the array to copy to. The three int arguments specify the starting position in the source array, the starting position in the destination array, and the number of array elements to copy.

Values

The ____ of an object's variables describe the object's state.

Method Overloading

The ability to define two or more different methods with the same name but different method signitures

Program Execution

The act of carrying out the instructions contained in a program.

File

The basic unit of storage on most computers. Every file has a name. A file name ends with an extension. Java files end with the extension .java

Precedence

The binding power of an operator which determines how to group parts of an expression

boolean

The boolean data type has only two possible values: true and false. Use this data type for simple flags that track true/false conditions. This data type represents one bit of information, but its "size" isn't something that's precisely defined.

What does break do?

The break statement has two forms: labeled and unlabeled. An unlabeled break statement terminates the innermost switch, for, while, or do-while statement, but a labeled break terminates an outer statement.

statements

change the state, ie change the value of a variable

source file contains a large number of import statements ( class loading )

class loading takes no additional time

Dog, Animal

compile and run

plus sign

concatenation operator

Math.toDegrees(x)

convert x radians to degrees (ie, returns x*180/p)

Math.cos(x)

cosine of x

break

exit block

A java monitor must either extend Thread....

false

a signed data type

false

suppose a method called finallyTest()

finally block will always exe

indexOf() size()

find out where something is in ArrayList get number of elements in ArrayList

-32 bits Range: -big to big -Must put an f at the end of the value EX: 98.6f; <--- f won't print

float

which line is not compiled

floater = ob

FLOPS

floating point operations per second. measure of computer's performance at brute force applications

flops

floating-point operations per second, this is used to see how many arithmetic operations a computer can do in a second (testing speed)

type of algorithm where you use shapes to outline

flowchart

else

following if else { Statements; } conditional statement

Applets

graphics in java

Lexical elements

groups of characters used in program code

Memory Address Register (MAR)

holds the address of the cell to be fetched or stored

packages

how are classes grouped in java?

super.method();

how to call a superclass method in a subclass

In the following program, explain why the value "6" is printed twice in a row: class PrePostDemo { public static void main(String[] args){ int i = 3; i++; System.out.println(i); // "4" ++i; System.out.println(i); // "5" System.out.println(++i); // "6" System.out.println(i++); // "6" System.out.println(i); // "7" } }

i++ is a postfix operator. 1 will be added to 1 after it's printed. ++i is a prefix operator. If it had been used, the println would have been "7"

outer:for...

i=1; j=0;

if else structure

if (thisEnter > 10) system.out.println("yep>10"); else system.out.println("nope<10"); and

Explain the following code sample: result = someCondition ? value1 : value2;

if someCondition is true then assign value1 to result else if someCondition is false then assign value2 to result

if (condition) { statements1 } else { statements2 }

if statement (else not required in all cases)

how to get error message

in catch statement catch(ArithmeticException e) {e.toString());} which gives the exception name + the description, while getMessage() only gives description

access modifiers

in method declaration: public, private, protected, default

++/--

increment/decrement; add 1 to/subtract 1 from the variable

Statements

instructions or commands within a method that make a program work

machine language

instructions that can be executed directly by the CPU

stored program concept

instructions to be executed by the computer are represented as binary values and stored in memory

-32 bits Range: -2,147,483,648 to 2,147,483,647 No rules

int

Declare and define integer a from double, b.

int a = (int) b;

declare and define command line integer argument, a

int a = Integer.parseInt (args[0]);

declare a as an int

int a;

length

int variable = stringname.length();

Primitive types

int, double, boolean, char

Primitive types

int, float, and boolean variables are examples of this

Declare an array

int[] anArray;

declare and initial int array, number, with length N

int[] number = new int [N];

IDE

integrated development environment. a programming environment that includes an editor, compiler, and debugger

IDE

integrated development environment; a programming environment that includes an editor, compiler, and debugger

A collection of methods with no implementation is called an ___.

interface

is interface a slass

interface is not a class

Serialize

involves saving the current state of an object to a stream, and restoring an equivalent object from that stream. The stream functions as a container for the object.

BufferedReader

io class for buffering reads

InputStreamReader

io class for reading input stream

yes

is Java platform independent

Infinite loop

loop that goes forever(while)

terabyte

maximum memory size is 2^40 memory bytes

MAC

medium access control: data link protocol sub-layer that determine how to arbitrate ownership of a shared communication line when multiple nodes want to send messages at the same time

object reference

memory location of an object

a set of related statements

method

A local variable stores temporary state; it is declared inside a ___.

method - for example a counter in a loop int i=0;

clone

method of Object. Creates and returns a copy of this object( Class Object).

Accessor method

method that accesses an object and returns some information about it, without changing the object

mutator method

method that changes the state of an object

Things an object can do are called?

methods

Where is a software object's behavior exposed?

methods (Java) or functions (C++)

Instance method

methods that are part of objects and can only b e called through an object

Mutator methods

methods that change the values of the field

prevent user input to other windows

modal dialog

substring

newStringName = stringName.substring(startPosition,stopPosition); returns defined part of string

short input

nextShort()

how is constructor definition different from a method

no return type...constructor includes access modifier, which is usually public, but can also (surprisingly) be private or default(no access modifier at all (?))

Integer.parseInt or Double.parseDouble

obtains the integer value of a string containing the digits

Method

one or more statements in a class performing a specific task within an object

op code

operation code; unique unsigned integer code assigned to each machine language operation recognized by hardware

boolean operator

operator that can be applied to boolean values: &&, ||, !

a group of related classes

package

Javac

program used to compile .java files into .class files.

How can this interface be correctly implemented? public interface TestInterface { public boolean errorState(); }

public class ClassX implements TestInterface{ public boolean errorState() { return false; } } An object can act as any interface it implements. and public class ClassX implements TestInterface{ private boolean errorState() { return false; } } An object can also act as any of its superclasses.

If Statement

public class IfStatement10 { public static void main(String[] args) { int test = 6; if (test == 9){ System.out.print("yes"); }else{ System.out.println("this is else"); } } }

Math Operators

public class MathOperators8 { public static void main(String[] args) { int girls,boys,people; girls = 11; boys = 3; people = girls % boys; System.out.println(people); } }

Multiple Classes- Class 1

public class UsingMultipleClasses14 { public static void main(String[] args) { UsingMultipleClasses14Part2 MultipleClasses2Object = new UsingMultipleClasses14Part2(); MultipleClasses2Object.simpleMessage(); } }

Multiple Classes- Class 2

public class UsingMultipleClasses14Part2 { public void simpleMessage(){ System.out.println("This is another class"); } }

define new class Vehicle that implements Drivable interface

public class Vehicle implements Drivable

While Loop

public class WhileLoop13 { public static void main(String[] args) { int counter = 0; while (counter < 10){ System.out.println(counter); counter++; } } }

Build a return method

public return

use of throws

public static void getAFile(String filename) throws IOException, FileNotFoundException{ FileInputStream file = new FileInputStream(filename); } and above in the main method, will set up try/catch blocks for suspect code

Main Method

public static void main(String[] args) { } Required to create an executable Java program.

List all the access modifiers in order from most visible to least?

public, protected, default, private.

Variables in interfaces are declared what automatically?

public, static and final.

thread states

ready, running, waiting and dead states

syntax

rules that define how to form instructions in a particular programming language

loop

sequence of instructions that is executed repeatedly

instruction set

set of all operations that can be executed by a processor

char newChar = (char)(mychr + x)

shift character by x numbers (use ASCII table values)

-16 bits Range: -32,768 to 32,767 No rules

short

computability

something that can be done by symbol manipulation algorithms,; Turing machines define the limits of these

I/O controller

special purpose computer that handles details of input and output and compensates for speed difference between I/O devices and other parts of the computer.

I/O controller

special-purpose computer whose responsibility is to handle the details of input/output and to compensate for any speed differences between I/O devices and other parts of the computer

parameter passing

specifying expressions to be arguments for a method when it is called

The term "class variable" is another name for ___.

static field - class variables are fixed and global across all instances of the class

a group of characters

string

/** Computes the volume of a cube. @param sideLength the side length of the cube @return the volume */

structure for commenting before methods (javadoc)

computer science

study of algorithms including their: mathematical and formal properties, hardware realizations, linguistic realizations, and application

arithmetic/Logic Unit (ALU)

subsystem that performs such mathematical and logical operations as addition, subtraction, and comparison for equality; registers, interconnections between components, and ALU circuitry

Common behavior can be defined in a ___ and inherited into a ___ using the ___ keyword.

superclass, subclass, extends

public interface Pet

syntax to create an interface called Pet

super.runReport();

syntax to run superclass' runReport() method

Math.tan(x)

tangent of x

Loop

tells java do things over and over

class

template for instantiating objects

Cache Memory

temporary storage area where frequently accessed data can be stored for rapid access. fast, expensive, small. First site of search.

throws FileNotFoundException

terminates main if FileNotFoundException occurs

Three

the conditional operator takes this many operands

throws keyword

the throws keyword is used to declare and throw exceptions as opposed to the throw keyword which is followed by a specific instance of an exception (throw new Exception();)

von neumann architecture

theoretic model of computer design that structures the origin of all modern computers. four subsystems: memory, in/output, ALU, control unit.

super keyword in Java

two uses 1) call a superclass constructor (since superclass/subclass constructors seem to be confusing business) 2) access a member of the superclass that has been hidden by a member of a subclass

...pure java...communicate with middleware server....

type 3

... pure java... implement the network protocol

type 4

stack

type of java memory. faster. primitive objects, depending on their context, maybe stored in stack or heap

heap

type of java memory. slower more dynamic. Complex objects are always stored in heap

boolean

type with possible values of true of false

double blah = (int) (blah + 3)

typecast; change variable type

valid identifiers

tất

Array Manipulations

useful operations provided by methods in the java.util.Arrays class, are: Searching an array for a specific value to get the index at which it is placed (the binarySearch method). Comparing two arrays to determine if they are equal or not (the equals method). Filling an array to place a specific value at each index (the fill method). Sorting an array into ascending order. This can be done either sequentially, using the sort method, or concurrently, using the parallelSort method introduced in Java SE 8. Parallel sorting of large arrays on multiprocessor systems is faster than sequential array sorting.

literals

values that are hard-coded into the program (integers and strings)

string Var = "Hello"

variable Var = Hello (*double quotes!)

char answer = 'y'

variable answer = y (*single quotes!)

formal parameter

variable in a method definition. initialized with an actual parameter when method is called.

local variable

variable whose scope is a block

romantics

very invested in cult of genius...write about michalangelo....seems to be pront to depression...forgets to take off boots... modern notion of genius invested in notion of intellectual originality...copyright law

method that doesn't return a value; it does something

void

For overriding a method in an interface that throws an exception of type IOException what must that method declaration be? Lets say that method was void m1() throws IOException

void m1() void m1() throws IOException void m1() throws FileNotFoundException

public static void boxString(String contents)

void methods return no value, but can produce output

INCORRECT..deserialization

we use readObject()... to deserialize

instance variables and methods

what are members of a class?

type name in angle brackets

what is a type parameter

when you don't want a class to be instantiated

what is an abstract class?

a reference variable of the object type linked together by the = operator

what is an object

changing an inherited method

what is overriding

package name + class name

what is the full class name

abstract and non-abstract

what kind of methods are allowed in an abstract class

default

what to do if not listed case

scope

when a variable can be accessed in the same block

false

when an if statement is nested in the else clause of another statement, the only time the inner if statement is executed is when the boolean expression of the outer if statement is true

true

when an if statement is nested in the if clause of another statement, the only time the inner if statement is executed is when the boolean expression of the outer if statement is true

on the stack inside the frame corresponding to the method where the methods were declared

where do all local variables live?

Reasons to use comments

where un-obvious coding is performed. next to a variable declaration. Beginning at the Program.

How do you write an infinite loop using the while statement?

while (true) { //do something }

socrates daemon

whispered the language of the gods into his ear before he did something incorrect vessel genies harnessed by divine madness infused by the goes that whips the individual into ecstatic states and pushes them into writing great things aristotle infused before birth == the problems -- written by student -- why is it that individuals of great capacity seem to be subject to melancholy? sanguine? extradorinary indiviuals have similary physiology ...side effects...maddness...irrationality its sad to think of how many geniuses have died on the african veldt

setup a constructor

within Monster class, create public Monster(int newHealth, int newAttack, int newMovement) {}

local vs instance variables

within a method(so w/in method's stack frame) vs not...a constructor IS NOT a method... instance variables live on the heap and are best set as parameters to the constructor in a single call...thus constructing object and its variable (initializing object's state) in one call

PrintWriter out = new PrintWriter("output.txt");

writes output to a file "output.txt"

x = a++ + b++

x tổng cũ, a,b tăng 1

compound assignments

x+=1

What is the last value that is sent to standard out for x in the given code segment? int x=0; do{ x=x+2; System.out.println("x: " + x); }while(--x<5);

x: 6 The do while statement will increment x by 2 each time through the loop, and then, before it checks the while condition, it will first decrement it by 1.

int[]x

x[24] = 0; x.length = 25;

Math.pow(x,y)

x^y (x>0, or x=0 and y>0, or x<0 and y is an integer)

19. True or False: The while loop is a pretest loop.

T

How do you pass data (including JavaBeans) to a JSP from a servlet?

- (1) Request Lifetime: Using this technique to pass beans, a request dispatcher (using either "include" or forward") can be called. This bean will disappear after processing this request has been completed. Servlet: request. setAttribute("theBean", myBean); RequestDispatcher rd = getServletContext(). getRequestDispatcher("thepage. jsp"); rd. forward(request, response); JSP PAGE:<jsp: useBean id="theBean" scope="request" class=". . . . . " />(2) Session Lifetime: Using this technique to pass beans that are relevant to a particular session (such as in individual user login) over a number of requests. This bean will disappear when the session is invalidated or it times out, or when you remove it. Servlet: HttpSession session = request. getSession(true); session. putValue("theBean", myBean); /* You can do a request dispatcher here, or just let the bean be visible on the next request */ JSP Page:<jsp:useBean id="theBean" scope="session" class=". . . " /> 3) Application Lifetime: Using this technique to pass beans that are relevant to all servlets and JSP pages in a particular app, for all users. For example, I use this to make a JDBC connection pool object available to the various servlets and JSP pages in my apps. This bean will disappear when the servlet engine is shut down, or when you remove it. Servlet: GetServletContext(). setAttribute("theBean", myBean); JSP PAGE:<jsp:useBean id="theBean" scope="application" class=". . . " />

What does it take to create and use and object?

- 2 classes. 1 class for the type of object (Dog, ClarmClock,Television) and another class to test your new class -the tester class is where you put the pain method and in that main() method you create access object of your new class type. -the test has 1 job: try out the methods and vairables of your new object class type

What are JSP Directives?

- A JSP directive affects the overall structure of the servlet class. It usually has the following form:<%@ directive attribute="value" %> However, you can also combine multiple attribute settings for a single directive, as follows:<%@ directive attribute1="value1? attribute 2="value2? . . . attributeN ="valueN" %> There are two main types of directive: page, which lets to do things like import classes, customize the servlet superclass, and the like; and include, which lets to insert a file into the servlet class at the time the JSP file is translated into a servlet

What is a Java Bean?

- A Java Bean is a software component that has been designed to be reusable in a variety of different environments.

What is a stream and what are the types of Streams and classes of the Streams?

- A Stream is an abstraction that either produces or consumes information. There are two types of Streams and they are: Byte Streams: Provide a convenient means for handling input and output of bytes. Character Streams: Provide a convenient means for handling input & output of characters. Byte Streams classes: Are defined by using two abstract classes, namely InputStream and OutputStream. Character Streams classes: Are defined by using two abstract classes, namely Reader and Writer.

What is a package?

- A package is a collection of classes and interfaces that provides a high-level layer of access protection and name space management.

What is the difference between superclass and subclass?

- A super class is a class that is inherited whereas sub class is a class that does the inheriting.

What is an I/O filter?

- An I/O filter is an object that reads from one stream and writes to another, usually altering the data in some way as it is passed from one stream to another.

What is an abstract class?

- An abstract class is a class designed with implementation gaps for subclasses to fill in and is deliberately incomplete.

What is adapter class?

- An adapter class provides an empty implementation of all methods in an event listener interface. Adapter classes are useful when you want to receive and process only some of the events that are handled by a particular event listener interface. You can define a new class to act listener by extending one of the adapter classes and implementing only those events in which you are interested. For example, the MouseMotionAdapter class has two methods, mouseDragged()and mouseMoved(). The signatures of these empty are exactly as defined in the MouseMotionListener interface. If you are interested in only mouse drag events, then you could simply extend MouseMotionAdapter and implement mouseDragged() .

How many ways can an argument be passed to a subroutine and explain them?

- An argument can be passed in two ways. They are passing by value and passing by reference. Passing by value: This method copies the value of an argument into the formal parameter of the subroutine. Passing by reference: In this method, a reference to an argument (not the value of the argument) is passed to the parameter.

What is an event and what are the models available for event handling?

- An event is an event object that describes a state of change in a source. In other words, event occurs when an action is generated, like pressing button, clicking mouse, selecting a list, etc. There are two types of models for handling events and they are: a) event-inheritance model and b) event-delegation model

What is an applet?

- Applet is a dynamic and interactive program that runs inside a web page displayed by a java capable browser.

What is the difference between Array and vector?

- Array is a set of related data type and static whereas vector is a growable array of objects and dynamic.

What is the difference between Assignment and Initialization?

- Assignment can be done as many times as desired whereas initialization can be done only once.

What is BDK?

- BDK, Bean Development Kit is a tool that enables to create, configure and connect a set of set of Beans and it can be used to test Beans without writing a code.

What is the use of bin and lib in JDK?

- Bin contains all tools such as javac, appletviewer, awt tool, etc., whereas lib contains API and all packages.

What are Class, Constructor and Primitive data types?

- Class is a template for multiple objects with similar features and it is a blue print for objects. It defines a type of object according to the data the object can hold and the operations the object can perform. Constructor is a special kind of method that determines how an object is initialized when created. Primitive data types are 8 types and they are: byte, short, int, long, float, double, boolean, char.

What are the types of JDBC Driver Models and explain them?

- There are two types of JDBC Driver Models and they are: a) Two tier model and b) Three tier model. Two tier model: In this model, Java applications interact directly with the database. A JDBC driver is required to communicate with the particular database management system that is being accessed. SQL statements are sent to the database and the results are given to user. This model is referred to as client/server configuration where user is the client and the machine that has the database is called as the server. Three tier model: A middle tier is introduced in this model. The functions of this model are: a) Collection of SQL statements from the client and handing it over to the database, b) Receiving results from database to the client and c) Maintaining control over accessing and updating of the above.

What is the class and interface in java to create thread and which is the most advantageous method?

- Thread class and Runnable interface can be used to create threads and using Runnable interface is the most advantageous method to create threads because thread class implements Runnable.

What are the states associated in the thread?

- Thread contains ready, running, waiting and dead states.

How to create and call stored procedures?

- To create stored procedures: Create procedure procedurename (specify in, out and in out parameters) BEGIN Any multiple SQL statement; END; To call stored procedures: CallableStatement csmt = con. prepareCall("{call procedure name(?,?)}"); csmt. registerOutParameter(column no. , data type); csmt. setInt(column no. , column name) csmt. execute();

What are Transient and Volatile Modifiers?

- Transient: The transient modifier applies to variables only and it is not stored as part of its object's Persistent state. Transient variables are not serialized. Volatile: Volatile modifier applies to variables only and it tells the compiler that the variable modified by volatile can be changed unexpectedly by other parts of the program.

What is URL?

- URL stands for Uniform Resource Locator and it points to resource files on the Internet. URL has four components: http://www. address. com:80/index.html, where http - protocol name, address - IP address or host name, 80 - port number and index.html - file path.

What is UNICODE?

- Unicode is used for internal representation of characters and strings and it uses 16 bits to represent each other.

What are Vector, Hashtable, LinkedList and Enumeration?

- Vector : The Vector class provides the capability to implement a growable array of objects. Hashtable : The Hashtable class implements a Hashtable data structure. A Hashtable indexes and stores objects in a dictionary using hash codes as the object's keys. Hash codes are integer values that identify objects. LinkedList: Removing or inserting elements in the middle of an array can be done using LinkedList. A LinkedList stores each object in a separate link whereas an array stores object references in consecutive locations. Enumeration: An object that implements the Enumeration interface generates a series of elements, one at a time. It has two methods, namely hasMoreElements() and nextElement(). HasMoreElemnts() tests if this enumeration has more elements and nextElement method returns successive elements of the series.

What is Garbage Collection and how to call it explicitly?

- When an object is no longer referred to by any variable, java automatically reclaims memory used by that object. This is known as garbage collection. System. gc() method may be used to call it explicitly.

What is deadlock?

- When two threads are waiting each other and can't precede the program is said to be deadlock.

When will you synchronize a piece of your code?

- When you expect your code will be accessed by different threads and these threads may change a particular data causing data corruption.

What is the difference between an argument and a parameter?

- While defining method, variables passed in the method are called parameters. While using those methods, values passed to those variables are called arguments.

What is connection pooling?

- With servlets, opening a database connection is a major bottleneck because we are creating and tearing down a new connection for every page request and the time taken to create connection will be more. Creating a connection pool is an ideal approach for a complicated servlet. With a connection pool, we can duplicate only the resources we need to duplicate rather than the entire servlet. A connection pool can also intelligently manage the size of the pool and make sure each connection remains valid. A number of connection pool packages are currently available. Some like DbConnectionBroker are freely available from Java Exchange Works by creating an object that dispenses connections and connection Ids on request. The ConnectionPool class maintains a Hastable, using Connection objects as keys and Boolean values as stored values. The Boolean value indicates whether a connection is in use or not. A program calls getConnection() method of the ConnectionPool for getting Connection object it can use; it calls returnConnection() to give the connection back to the pool.

What are wrapper classes?

- Wrapper classes are classes that allow primitive types to be accessed as objects.

Is it possible to communicate from an applet to servlet and how many ways and how?

- Yes, there are three ways to communicate from an applet to servlet and they are: a) HTTP Communication(Text-based and object-based) b) Socket Communication c) RMI Communication

Can you have an inner class inside a method and what variables can you access?

- Yes, we can have an inner class inside a method and final variables(local) can be accessed.

Is it possible to call servlet with parameters in the URL?

- Yes. You can call a servlet with parameters in the syntax as (?Param1 = xxx || m2 = yyy).

What is the difference between abstract class and interface?

- a) All the methods declared inside an interface are abstract whereas abstract class must have at least one abstract method and others may be concrete or abstract. b) In abstract class, key word abstract must be used for the methods whereas interface we need not use that keyword for the methods.Interface methods are by default public and abstract.Interfaces can have constants, which are always implicitly public,static, and final.Interfaces can extend one or more other interfaces

24. True or False: A variable may be defined in the initialization expression of the for loop.

T

"static" modifier

Sometimes, you want to have variables that are common to all objects. This is accomplished with the static modifier. Fields that have the static modifier in their declaration are called static fields or class variables. They are associated with the class, rather than with any object. Every instance of the class shares a class variable, which is in one fixed location in memory. Any object can change the value of a class variable, but class variables can also be manipulated without creating an instance of the class. Class variables are referenced by the class name itself (not an object name), as in Bicycle.numberOfBicycles This makes it clear that they are class variables rather than instance variables.

Whitespaces

Space, Tab, newline characters

Constructor

Special kind of method, build up an instance of a class

Constructor

Special method that has same name as class

things to do when refactoring (a class with redundancies)

SpecificClass whatever = new SpecificClass(); becomes a function SpecificClass whatever = createSpecificClass();

method

Specifies the actions of an object.

%[alignment][width]s

State the format for the format method.

source code, compiler, byte code, JVM/JIT, binary, words

State the path the computer takes to translate Java into words.

submit a query to a database

Statement object

-Must end with a ; (semicolon)

Statements

statement

Statements are roughly equivalent to sentences in natural languages. A statement forms a complete unit of execution.

What do static imports import?

Static variables and static methods.

play 2001.mid

StdAudio.play("2001.mid");

draw circle at (x, y) radius = r

StdDraw.circle(x, y, r);

draw filled circle at (x, y) radius = r

StdDraw.filledCircle(x, y, r);

draw a filled rectangle centered at (x, y) width = w height = h

StdDraw.filledRectangle(x, y, w, h);

draw line from (x, y) to (q, s)

StdDraw.line(x, y, q, s);

draw an image, starfield.jpg at (0, 0)

StdDraw.picture(0, 0, "starfield.jpg");

pen size to 0.05

StdDraw.setPenRadius(0.05);

set x and y window scale to -R , R

StdDraw.setXscale(-R , R); StdDraw.setYscale(-R, R);

draw "text" at (x, y)

StdDraw.text(x, y, "text");

boolean for empty

StdIn.isEmpty()

read double

StdIn.readDouble();

read an integer

StdIn.readInt();

std print

StdOut.println();

Main Memory

Storage Location of Data in a Computer.

Value: group of characters -Capitalize the S, enclose value in " "

String

declare and initialize string variables

String itemToCheck; itemToCheck = "";

nextLine()

String of words

declare and initial string array, names, with length N

String[] names = new String [N];

Multidimensional arrays

String[][] names = { {"Mr. ", "Mrs. ", "Ms. "}, {"Smith", "Jones"} };

Von Neumann architecture

Structure and organization of virtually all modern computers are based off this design. Consists of 3 major characteristics. 1 - Four major subsystems called memory, input/output, arithmetic/logic unit, and control unit. 2 - stored program concept. 3 - sequential execution of instructions

concatenate and output

System.out.println("this with "+ thisEnter);

"this" keyword

Within an instance method or a constructor, this is a reference to the current object — the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this. The most common reason for using the this keyword is because a field is shadowed by a method or constructor parameter. public class Point { public int x = 0; public int y = 0; //constructor public Point(int x, int y) { this.x = x; this.y = y; } } Each argument to the constructor shadows one of the object's fields — inside the constructor x is a local copy of the constructor's first argument. To refer to the Point field x, the constructor must use this.x.

Um gewisse Programmteile mehrfach durchlaufen zu können.

Wozu braucht man Kontrollstrukturen?

What are Wrapper classes?

Wrapper classes are objects of primitives. Every primitive has a wrapper class.

Can you use underscores in primitives not including char or boolean?

Yes

Does every object have their own copies of instance variables and non static method?

Yes

Is the String class final?

Yes

Can you assign an integer to a character?

Yes - Only if it is put as an integer like 5 not if it assigned a variable that stores an int.

Can an object have more than one type?

Yes - it can implement n-amount of interfaces as well as extend a class thereby taking on the type of many other classes

Can you make your own types of exceptions? If so,how? If not why?

You can create a custom exception classes by inheriting the Exception class

goto

You can't use this word in a Java program. The word has no meaning. Because it's a keyword, you can't create a goto variable.

True

You cannot change the value of a variable whose declaration uses the final key word

23. How do you open a file so that new data will be written to the end of the file's existing data?

You create an instance of the FileWriter class to open the file. You pass the name of the file (a string) as the constructor's first argument, and the boolean value true as the second argument. Then, when you create an instance of the PrintWriter class, you pass a reference to the FileWriter object as an argument to the PrintWriter constructor. The file will not be erased if it already exists and new data will be written to the end of the file.

"new" operator

You create an object from a class by using the new operator and a constructor. The new operator returns a reference to the object that was created. You can assign the reference to a variable or use it directly.

New line

\n

13. This is a special value that signals when there are no more items from a list of items to be processed. This value cannot be mistaken as an item from the list. a. sentinel b. flag c. signal d. accumulator

a

true

a class that has even one abstract method must be marked as an abstract class

INCORRECT..RMI server

a client acceeses remote object... only server name

Cohesion

a cohesive class is one whose defined responsibilities are meaningful - an OrderFactory class shouldn't be used to create an order as well as parse dates. - it should do one thing and do it well, delegating task outside of its responsibility to other classes

HashMap

a dynamic data structure filled with key value mappings - datatypes of the entries are specified in the declaration - keys are a Set - no duplicates

what does a finally block do?

a finally block is run after a try catch even if the try block caught an exception - used to execute code even if an exception is thrown

assembly language

a low level programming language that implements symbolic representation of the numeric machine codes.

Mutator method

a method that modifies the object on which the method is invoked

static method

a method with no implicit parameter (a method that is not invoked on an object)

constructor

a sequence of statements for initializing a newly instantiated object; the job of the constructor is to initialize the instance variables of an object

computer network

a set of independent computer systems connected by telecommunication links for the purpose of sharing information and resources

Debugging

a step by step method of testing a program and correcting programming errors

control unit

a subsystem of the processor that can 1. fetch next instructions 2. decode them 3. execute them

algorithm

a well ordered collection of unambiguous and effectively computable operations that when executed produces a result and halts in a finite amount of time

What is the difference between procedural and object-oriented programs?

a) In procedural program, programming logic follows certain procedures and the instructions are executed one after another. In OOP program, unit of program is object, which is nothing but combination of data and code. b) In procedural program, data is exposed to the whole program whereas in OOP program, it is accessible with in the object and which in turn assures the security of the code.

What are the steps involved for making a connection with a database or how do you connect to a database?

a) Loading the driver : To load the driver, Class. forName() method is used. Class. forName("sun. jdbc. odbc. JdbcOdbcDriver"); When the driver is loaded, it registers itself with the java. sql. DriverManager class as an available database driver. b) Making a connection with database: To open a connection to a given database, DriverManager. getConnection() method is used. Connection con = DriverManager. getConnection ("jdbc:odbc:somedb", "user", "password"); c) Executing SQL statements : To execute a SQL query, java. sql. statements class is used. createStatement() method of Connection to obtain a new Statement object. Statement stmt = con. createStatement(); A query that returns data can be executed using the executeQuery() method of Statement. This method executes the statement and returns a java. sql. ResultSet that encapsulates the retrieved data: ResultSet rs = stmt. executeQuery("SELECT * FROM some table"); d) Process the results : ResultSet returns one row at a time. Next() method of ResultSet object can be called to move to the next row. The getString() and getObject() methods are used for retrieving column values: while(rs. next()) { String event = rs. getString("event"); Object count = (Integer) rs. getObject("count");

Consider the following code snippet. int i = 10; int n = i++%5; a) What are the values of i and n after the code is executed? b) What are the final values of i and n if instead of using the postfix increment operator (i++), you use the prefix version (++i))?

a) i=11, n=0 b) i=11, n=1

Consider the following class: public class IdentifyMyParts { public static int x = 7; public int y = 3; } a) What are the class variables? b) What are the instance variables? c) What is the output from the following code: IdentifyMyParts a = new IdentifyMyParts(); IdentifyMyParts b = new IdentifyMyParts(); a.y = 5; b.y = 6; a.x = 1; b.x = 2; System.out.println("a.y = " + a.y); System.out.println("b.y = " + b.y); System.out.println("a.x = " + a.x); System.out.println("b.x = " + b.x); System.out.println("IdentifyMyParts.x = " + IdentifyMyParts.x);

a) x b) y c) a.y = 5 b.y = 6 a.x = 2 b.x = 2 IdentifyMyParts.x = 2

short hand a = a + 1;

a++;

14. To open a file for writing, you use the following class. a. PrintWriter b. FileOpen c. OutputFile d. FileReader

a. PrintWriter

8. The for loop is this type of loop. a. pretest b. posttest c. prefix d. postfix

a. pretest

What is wrong with the following interface? public interface SomethingIsWrong { void aMethod(int aValue){ System.out.println("Hi Mom"); } }

aMethod() should not have a method body. Remove the {Sytem.out.println("Hi Mom");} to fix it.

public class Outer

abce

abs

abs() absolute value

friends.add (i, "Cindy"); String name = friends.get(i); friends.set(i, "Harry"); friends.remove(0);

adds element to arrayList at pos i (w/out i will add element to end); obtains element at i; redefines element at i as "Harry"; removes element

StringBuffer sbuf

after line 2, .... eligible

correct statement about remote class

all

ASCII

american standard code for information interchange. an international standard for representing textual info. 8 bits/character. allows a total of 256 character to be represented

"interface" type

an interface is a reference type, similar to a class, that can contain only constants, method signatures, and nested types. There are no method bodies. Interfaces cannot be instantiated—they can only be implemented by classes or extended by other interfaces. An interface defines a protocol of communication between two objects. An interface declaration contains signatures, but no implementations, for a set of methods, and might also contain constant definitions. A class that implements an interface must implement all the methods declared in the interface. An interface name can be used anywhere a type can be used.

instance

an object of a particular class

What is arr1,arr2 and arr3? int[] arr,arr2[][],arr3;

arr is an array. arr2 is a triple array. arr3 is a triple array.

An ___ is a container object that holds a fixed number of values of a single type.

array

double[] values = new double[10]; double[] moreValues = {32, 54, 67.5};

array declaration and initialization

What is specialization?

as opposed to generalization - specialization refers to the hierarchy of a superclass and subclass in which the superclass is always more inclusive than the subclass - the farther down the hierarchical chain, the more

10. This type of loop always executes at least once. a. while b. do - while c. for d. any of these

b. do - while

binary

base-two numeral system; usually using 1s and 0s

What will be printed? System.out.println("roberto".replaceAll("o", "!").substring(2, 6));

bert

What will be printed? System.out.println("roberto".replaceAll("o", "!").substring(2, 7));

bert!

Block

between two curly braces

machine language

binary instructions that are decoded and executed by the control unit

{ double volume = sideLength * sideLength * sideLength; return volume; }

body of method

Value: true/false

boolean

declare a boolean variable, isAscending

boolean isAscending;

&&, ||, !

boolean operators; and, or, not

ethernet

broadband technology, originally designed to operate at 10 Mbps using coaxial cable; uses the bus topology for LAN

how to set up try catch for exceptions

catch most specific first catch (FileNotFoundException e) {System.out.println("file not found"} catch (IOException e) {...} catch (Exception e) {...}


संबंधित स्टडी सेट्स

Risk Assessment & The Four Steps

View Set

Chapter 17: Preoperative Nursing Management

View Set

Week 2 - #4 - IT Security - Defense Against Digital Arts

View Set

Ethics and Economy Final Study Guide

View Set

OSHA: Preventing Workplace Violence

View Set

Chapter 14 additional review & practice

View Set

Cell biology (1.2, 1.3, 1.4, 1.5, 1.6)

View Set

Interactive Animation: Stream Terrace Formation

View Set