Computer Programming 2 Java

Lakukan tugas rumah & ujian kamu dengan baik sekarang menggunakan Quizwiz!

Block

-A block is a compound statement that declares a local variable -It is the same as a list of statements enclosed in braces. -When you declare a variable within a block, you cannot use the variable outside the block. Declaring the variable outside the block will let you use the variable both outside and inside the block.

Overloading

-Overloading a method name means giving the same name to more than one method within a class. -If you overload a method name, java distinguishes them according to the number of parameters and the types of the parameters.

Exceptions

-A checked exception is one that must either caught and handled in a method or declared in a throws clause for the method -An unchecked, or run-time exception does not need to be caught in a catch block or declared in a throws clause. -The RunTimeException class is the ancestor class of all unchecked exceptions. -Besides Object, all Exceptions and Errors are descended from the Throwable class -An Exception-like class that represents conditions from which there is generally no reliable recovery is the Error class -

Methods and Arguments

-A method cannot change the value of an argument of a primitive type -A method cannot replace an argument object with another object -A method can change the state of an argument object

Class Interfaces

-A program component that contains the headings for a number of public methods. -An interface has no instance variables, constructors, or method definitions -When you write a class that defines methods declared in an interface, we say that the class implements the interface. -An interface is a reference type. Thus, you can write a method that has a parameter of an interface type. -You can define an interface based on another interface.

Constructors

-A special method that is called when you use the 'new' operation to create a new object. -Create and initialize new objects -Using 'new' calls a constructor -You cannot use an existing object to call a constructor i.e myPet.Pet("Fang", 1, 150.0); //Invalid! -A constructor can call another constructor by using the keyword 'this' -Any call to 'this' must be the first action taken by the constructor i.e this(initialName, 0 ,0);

Constructors in Subclasses

-A subclass does not inherit constructors from its superclass -Constructors in a subclass invoke constructors from the superclass -Use 'super' within a subclass as the name of a constructor in a superclass -Any call to 'super' must be first within a constructor

Polymorphism

-Allows you to make changes in the method definition for the subclasses and have those changes apply to the methods written in the superclass.

Abstract Classes

-An abstract class has a least one abstract method -an abstract method has no body -You cannot create an object of an abstract class.

Exception Handling

-An exception is an object that signals the occurrence of an unusual event during the execution of a program. -The process of creating this object,throwing an exception. -A try block contains the code for the basic algorithm when everything goes smoothly. It detects an exception. -A throw statement throws an exception -A catch block deals with a particular exception -A throws clause in an overriding method can declare fewer, but not more exceptions than the overridden method declares. -The order of catch blocks matters

ArrayList

-An instance of ArrayList can only store objects; it cannot contain values of a primitive type, such as int, double, or char. -To retrieve an element from an ArrayList: String temp = aList.get(index); -The method set can replace any existing element, but you cannot use set to put an element at just any index. The method set is used to change the value of existing elements, not to set them for the first time. -To set an element for the first time, you must use the method 'add' -The method 'size' returns the number of elements stored

Variables of a a Class Type

-Class types are reference types -Every variable, whether implemented as a primitive type or class type is implemented as a memory location. -If the variable has a primitive type, a data value is stored in the memory location assigned to the variable. -However, a variable of class type contains the memory address of the object named by the variable. The object itself is not stored in the variable, but rather some other location in memory. -The address of this other memory location is called a reference to the object.

The Class Object

-Every class inherits the methods toString and equals from object. -The inherited method toString takes no arguments. It is supposed to return all the data in an object packaged into a string. -The instanceOf operator checks an object's class Syntax: Object instanceOf Class_Name i.e otherObject instanceOf Student

Parameters

-Every formal parameter has a data type, and the argument that is plugged in for the parameter in a method invocation must match the type of the parameter. i.e public void doStuff(int years) -Several parameters are possible in a method.

Wrapper Classes

-If a method needs an argument of a class type, but we have a value of a primitive type, we need to convert the primitive value, such ass the int value 42, to an equivalent value of some class type that corresponds to the primitive type int. To make this conversion, java provides a wrapper class for each of the primitive types. Such classes define methods that can act of values of a primitive type.

Has-a relationship

-If class A has an object of class B as an instance variable, the relationship between A and B is "has a"

Wrapper Classes continued

-Integer is a wrapper class for the primitive type int -To convert an int value to an object of type integer: Integer n = new Integer(42); Simpler form: Integer n = 42; -To convert an object of type Integer to an int value: int i = n.intValue(); Simpler form: int i = n; -Wrapper classed for the primitive types long, float, double and char, are Long, Float, Double, and Character respectively.

Array Basics

-Items in an array have the same data type -the number of elements in an array is called the length, size, or capacity -A method can change the values in an array argument -Assigning one array to another results in one array having two names

Reference Type

-Just a type whose variables hold references--that is, memory addresses as opposed to actual values of objects.

Local Variables

-Local variables are those declared within a method's body -The meaning of a local variable is confined to the method containing its declaration -One method's local variables have no meaning within another method. -Must be initialized before their values are used in an expression

Inheritance, Polymorphism, and Interfaces

-Private instance variables and private methods in a superclass are not inherited by a subclass; they cannot be reference directly by name within a subclass. -An object of a subclass can serve as an object of the superclass

Static Variables

-Shared by all objects of a class -Static variables that are not constant should be private.

Class Interface

-Tells programmers all they need to know to use the class in their programs -Describes the class's public view

Implementation

-The implementation of a class consists of all the private elements of the class definition, principally the private instance variables of the class, along with the definitions of both the public methods and private methods. -A class's implementation is hidden from public view

Static Methods

-Used when you need a method that has no relation to an object of any kind -When you define a static method, the method is still a member of a class, since you define it int a class, but the method can be invoked without using any object. -You normally invoke a static method by using the class name instead of an object name. -public static final: the word 'final' means the variable cannot change in value, it is a constant -A static method can reference a static variable, but not an instance variable -A non static method can reference a static variable -A static method can only call a static method

Calling a static Method

-When you call a static method, you write the class name instead of an object name. double feet = Dimensions.Converter.convertInchesToFeet(53.7);

Overriding versus Overloading

-When you override a method definition, the new method definition given in the subclass has the same name, return the, and the exact same number and types of parameters. -On the other hand, if the method in the subclass were to have the same name and the same return type, but a different number of parameters or a parameter of a different type from the method in the superclass, the method names would be overloaded. In such cases, the subclass would have both methods -Overriding a method redefines it in a subclass -A method overrides another if both have the same name, return type, and parameter list -When overriding a method definition, you cannot change the return type of the method. -A final method cannot be overridden -A final class cannot be a superclass

Correspondence between Formal Parameters and Arguments

-Within a method definition, formal parameters are given within parentheses after the method name. -In a method invocation, arguments are given within the parentheses after the method name. -Arguments must match parameters in number, order, and type

Finding Min

// finds min double min = x[0]; for( i = 0; i < x.length; i++); { if(number < min) { min = number; //System.out.println("Min = " + min); } }

Finding Max

//finds max double max = x[0]; for( i = 1; i < x.length; i++); { if (number > max) { max = number; //System.out.println("Max = " + max); } }

Find Average

//finds sum in order to calculate mean double sum = 0; for(i = 0; i < x.length; i++); { sum = sum + number; } //finds mean double mean = sum / x.length;

Copy versus Alias

A copy has the same exact information as another object but has a different address (points to something different in memory) vs alias points to the same reference to memory

Instance

An instance of a class is an object

Creating an Instance of ArrayList

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

The instance variable 'length' for a two dimensional array

For a 2d array b, the value of b.length is the number of rows, that is the integer in the first pair of brackets in the array's declaration. The value of b[i].length is the number of columns, that is the integer in the second pair of brackets in the array's declaration.

Java has three kinds of variables

Local, Instance, and Static

Loop to read values into an array

System.out.println("Enter 7 temperatures: "); for(int i = 0; i < 7; i++) temperature[i] = keyboard.nextDouble();

Loop to display the array values

System.out.println("The 7 Temperatures are: "); for(int i = 0; i < 7; i++) System.out.print(temperature[i] + " "); System.out.println();

Declaring and Creating a two-dimensional array

int [] [] table = new int [10][6];

Creating and Accessing Arrays

double [] temperature = new double[7];

Printing an array

for(int row = 0; row < ROWS; row++) for(int col = 0; col < COLS; col++) System.out.print(anArray[row][col]) System.out.println();

Recursion Example

public static boolean palindrome( char[] test, int i, int j ) { if(i == j || i > j) { return true; } else if(test[i] != test[j]) { return false; } else //if(test[i] == test[j]) { return palindrome(test,i+1,j-1); }

Recursion Example 2

public static void main(String[] args) { countDown(3); } public static void countDown(int num) { if(num <=0) { System.out.println(): } else { System.out.print(num); countDown(num -1); } }

Sorting Arrays: Selection Sort

public static void selectionSort(int [ ] A) { int i, j , min; int position; for(i = 0; i < A.length - 1;i++) { min = i; for(j = i+1; j<A.length;j++) if(A[j] < A[min]) { min = j; } position = A[i]; A[i] = A[min]; A[min] = position; } }


Set pelajaran terkait

Chapter 12 : Between competition & Monopoly

View Set

Intercultural Final (midterm answers)

View Set

A&P II- Exam 3: Connect (Lymphatic and Immunity)

View Set

ATI Nutrition Final Practice Test

View Set

AP Computer Science Chapter 12 Vocabulary

View Set

pharmacology: ch 17 drugs for treatment of respiratory disorders and allergic rhinitis

View Set