java exam 2

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

If a class includes an abstract class

abstract class must be explicitly declared abstract even if it contains non-abstract methods

Math class

all static methods; Used to perform common math functions. Methods include: Abs(), Acos(), Asin(), Atan(), Cos(), Exp(), Log(), Log100(), Pow(), Round(), Sign(), Sin(), Sqrt(), Tan(). PI E.

scope

the part of a program in which a variable is accessible

Constructors and static methods cannot be declared abstract

true

subclasses must declare the missing pieces to become concrete classes, from which you can instantiate objects.

true

To access a class's instance variables and instance methods (non-static variables and methods), a static method must use a reference to an object of that class.

true ex:

private variables

variables that are visible only to the class they belong to; public class myTime { private int hour; private int minute; private int second; //These variables are declared as private, so in another class, when you create an object from the class myTime to modify these variables, you will not have an access and get an error. public class myTime2 { myTime mytime= new myTime(); mytime.hour=12; mytime.minute=13; mytime.second=14; //No Access, these instance variables are private. The solution is that you can use set and get methods. Because, they have an access to modify or get the values. Set and get methods are public, so you can call them in the class myTime2. Set and get methods are not static, so to call these methods, you need to create an object from the class myTime. Another solution is that, you can declare these variables as protected. Because all the classes in the same package will have access to use protected ones.

If a class has a default (no-argument) constructor and other different constructors

when you create an object from that class, you can supply values for the instance variables for the given object, or it is not necessary to supply values (because you have a no-argument constructor). •

If a class has a constructor

when you create an object from that class, you must supply values for the instance variables for the given object.

File Containing more than One Class

• A java file can contain more than one classes. However, this file can include only one public class. Otherwise an error occurs. • Non-public classes can be used only by other classes in the same package. Classes compiled into the same directory are in the same package. ex: public class ThisTest { ...... } class SimpleTime { private int hour; private int minute; private int second; public String toUniversalString () { return String.format("%02d:%02d:%02d", this.hour, this.minute, this.second); //this keyword is not necessary here, but you can use it. public String buildString() { return String.format("%s", this.toUniversalString()); } //you can explicitly use the keyword "this" to call the method. //if you do not use it, Java implicitly use the keyword "this" to call the method }

array

• Array objects are data structures (collection of data items) consisting of related data items of the same type. • An array is a group of variables containing values that all have the same type. • Arrays are objects, so they are considered reference types. • The elements of an array can be either primitive types or reference types. • The position of an element is called element's index or subscript. String [] b= new String [100], x= new String [27]; //declaring multiple arrays //square brackets must be placed after the type (before //the name) of array. String [] b = new String [100]; String b []= new String [100]; //declaring single arrays //square brackets can be placed after the type or after //the name of array.b b.length //gives the length of the array String [] b= {'a', 'b'}; //initializing an array NOTE: %02d -> 0 is a flag and it displays for values with fewer digits than the field width 2. For example: int result=5; System.out.printf("%02d", result); //Prints: 05

set method

set methods are also known as mutator methods.

final method

**final method in a superclass cannot be overridden in a subclass You should make a method final in Java if you think it's complete and its behavior should remain constant in sub-classes

Why do we need classes and methods?

1. it makes the program more manageable by modularizing it into classes & methods 2. can use existing classes & methods or ones you create for building blocks 3. avoid repeating code 4. easy to debug & maintain

Abstract classes

A class that cannot be instantiated (can't use new on it), because they're incomplete; It can only be extended and is used to define base classes.; they have to be inherited from to be used. normally contains one or more abstract methods

(class's) fields

A class's static variables + instance variables

ArrayIndexOutOfBoundsException

An exception thrown when an invalid array index is used. ex: public class ArrayException { public static void main (String [] args) { int [] responses= new int [5]; for (int answer=0; answer <=responses.length; answer++) { try { ++responses[answer]; //the length of the response is 5 but the indexes of the elements are between 0 and 4. //loop continues when it is 5 // but responses [5] does not exist, so an exception } catch (ArrayIndexOutOfBoundsException e) { System.out.print(e); } } }

What is a constant?

Any field declared with keyword final is constant; value can't be changed after field is initialized ex: Math.PI is a constant and modifiers are public, final, and static. It is public so that you can use it in other classes. It is final, so its value cannot change. It is static, so there is only one copy of it.

Multidimensional Arrays

Arrays can have 2 or more dimensions. For a 2 dimensional array, the first index is the row and 2nd is the column. (ex: myArray[2][3] is row 2 column 3. ex: int [][] b= {{1,2,3}, {4,5,6}}; 1 2 3 4 5 6 int [0][1]= 2; //row having 0 index, column having 1 index int [][] b= new int [3][4]; 3 rows 4 columns int [][] b= new int [2][]; //create two rows b[0]= new int [5]; //create 5 columns for the first row b [1]= new int [3]; //create 3 columns for the second row

Overloading Constructors

Constructors must have different parameters in order to be overloaded. ex: public class myTime { private int hour; private int minute; private int second; public myTime () { this (0, 0, 0); } //calls the constructor which requires three parameters and assigns "0" for each //parameters //default constructor or no-argument constructor public myTime (int hour, int minute, int second) { this.hour= hour; this.minute=minute; this.second=second; } public myTime (int hour) { this (hour, 0 ,0 ); //only hour is supplied. //calls the constructor which requires three parameters and assigns "0" for //minute and second. }

Argument Promotion

Converting an argument's value, if possible, to the type that the method expects to receive in its corresponding parameter. Type: Valid promotion: double None float double long float or double int long, float, or double char int, long, float, or double short int, long, float, or double (not char) byte short, int, long, float, or double (not char) boolean none ex: Math.sqrt(4) The method expects a double value. But an integer value is supplied. Java converts the int value 4 to the double value 4.0 before passing the value to method sqrt. So, no losing data. In case of data loss due to conversion, the Java compiler requires you to use a cast operator.

default constructor

If a class does not have any constructor, Java implicitly supplies a default constructor. You cannot supply any values for the created objects. You must use set methods to assign values for the instance variables. a constructor with no parameters; Each instance variable implicitly receives its default value. **This is the reason why instance variables are initialized to their default values.

interfaces

If there is not a relationship between classes, but they have common methods or fields, an interface can be declared. Notes: • an interface contains only constants & abstract methods. • all interface members must be public. • all methods declared in an interface are implicitly public and abstract. • all fields are implicitly public, static, and final. • a class can extend only one other class but can implement many interfaces. All declarations are correct: public class Bird extends Animal implements Movement Movement is the interface public class Bird implements Movement public class Bird implements Movement, Payable // implements more than one interfaces public class Bird extends Animal implements Movement, Payable

constructors

Special methods used for the creation of an Object.; can't be inherited **cannot be declared abstract

static method

Static methods are defined in an object but do not require instance data. Therefore, they can be called directly with the class name, such as Math.random(). **can't be overridden **cannot be declared abstract

Superclass

The parent class that behavior & properties are inherited from. The super class of all classes in Java is (eventually) the Object class, all classes are derived from it. • you cannot treat a superclass object as a subclass object. Because a superclass object is not an object of any of its subclasses. • If it is required, the program must first cast the superclass reference to a subclass reference through a technique known as downcasting.

string concatenation

The plus symbol (+), when used with Strings, stands for String concatenation. It merges Strings together into one. ex: double result= 12.3; System.out.println("Maximum is" + result); Every primitive value and object in Java can be represented as a String. When one of the + operator's operands is a String, the other is converted to a String. Result is converted to a String; then two are concatenated.

IllegalArgumentException

Thrown when a method receives an argument formatted differently than the method expects. public void setTime (...................) { //validate hour if (hour <0 || hour>=24) { throw new IllegalArgumentException ("my message"); //if an invalid input is received from the user, a message is displayed. }

Passing Arrays to Methods

When an argument to a method is an entire array or an individual array of a reference type, the called method receives a copy of the reference. However, when an argument to a method is an individual array element of a primitive type, the called method receives a copy of the element's value. Such primitive types are called scalars or scaler quantities. double [] myarray= {1.2, 1.3, 1.4}; modifyArray(myarray); //pass array reference modifyArray(double [2]); //attempt to modify myarray[2]

What is a static variable?

While creating a class, instance variables can be declared. Each object created from this class uses its own copy of every instance variable of the class; If a variable is a static variable, all the objects of that class share one copy of the static variable. ex: public class User { //instance variables private String username; private String password; //constructor public User (String username, String password) { this.username=username; this.password=password; } }//end class public class UserTest { public static void main (String [] args) { //Each object uses its own copy of //username and password. User user1= new User ("akare", "123456"); User user2= new User ("akarc", "12Etut"); }//end main }//end class Class variables also known as static variables are declared with the static keyword in a class, but outside a method, constructor or a block.

method overloading

Writing more than one method of the same name in a class, must have different parameters compiler distinguishes overloaded methods by their signatures- a combination of: • the method's name • the number of its parameters • the types of its parameters • the order of its parameters --but not its return type.

delegating constructor

a constructor that calls another constructor

enhanced for statement

allows you to iterate through array elements without using a counter. ex: int total=0; int [] myarray= {1, 2, 3}; for (int number: myarray) { total= total + number; } //in the loop, values of each element are assigned to //the variable number one by one until the loop //terminates. 1. Iteration: number=1 total=0+1=1; 2. Iteration number=2; total=1+2=3; 3. Iteration number=3; total= 3+3=6; Enhanced for statement can be used only to obtain array elements, it cannot be used to modify elements

abstract method

an instance method; is specified but not implemented in an abstract class. The subclasses must implement this method. **must be overridden in the subclasses

widening casting

done automatically; converting a smaller type to a larger type size byte -> short -> char -> int -> long -> float -> double ex: public class MyClass { public static void main(String[] args) { int myInt = 9; double myDouble = myInt; // Automatic casting: int to double System.out.println(myInt); // Outputs 9 System.out.println(myDouble); // Outputs 9.0 } }

polymorphism

enables you to write programs that process objects that share the same superclass, either directly or indirectly, as if they were all objects of the superclass. ex: public abstract class Animal { public abstract String move(); } public class Fish extends Animal { @Override public String move() { return String.format("Swim"); } } public class Bird extends Animal { @Override public String move() { return String.format("Fly"); } } public class Test { public static void main (String [] args) { Bird mybird= new Bird (); // an object from the class Bird Fish myfish= new Fish (); //an object from the class Fish Animal [] myanimal= new Animal [2]; //an array from the superclass myanimal [0]= mybird; //objects are assigned to array as elements myanimal [1]= myfish; for (Animal currentAnimal: myanimal) { currentAnimal.move(); } 1. Iteration= currentAnimal will be mybird so that it will call the move method from the class Bird. 2. Iteration= currentAnimal will be myfish so that it will call the move method from the class Fish.

get method

get method are also knows as accessor or query methods

inheritance heirarchy

hierarchy is read from bottom to the top; is-a-relationship represents inheritance.

Secure Random Generation

import java.security.SecureRandom; SecureRandom objects produce nondeterministic random numbers that cannot be predicted. you need to create an object: SecureRandom myRandom= new SecureRandom (); int randomnumbers= myRandom.nextInt(2); //Random numbers between 0 and 1 will be generated. int randomnumbers= 1+ myRandom.nextInt(2); //1 is the shifting value. Random numbers between //1 and 2 will be generated.

Class Arrays

import java.util.Arrays; methods: • Arrays.sort(myarray); • Arrays.fill (myarray, 7); //fills all the elements by 7 • Arrays.equals (myarray, myarray2); //compares two arrays whether they are identical Another method: • System.arraycopy(myarray, 0, myarray2, 0, myarray.length); • myarray is the array from which elements are to be copied. • 0 is the index that specifies the starting point in the range of elements to copy from the array. • myarray2 specifies the destination array that will store the copy • 0 is the index in the destination array where the first copied element should be stored. • the last argument specifies the number of elements to copy from the array in the first argument (myarray).

extends (keyword)

keyword used for inheritance ex: public class CommunityMember extends Object { //each class implicitly extends the class, Object //you can explicitly use "extends Object" ... public CommunityMember (String name, String surname) { //constructor this.name=name; this.surname=surname; } //method public double CalculatePayment () { ..... } } public class Employee extends CommunityMember { ... //constructor public Employee (String name, String surname, int age) { super (name, surname); //call the constructor from the superclass this.age=age; }

Variable-Length Argument Lists

methods that receive an unspecified number of arguments. A type followed by an ellipsis (...) in a method's parameter list indicates that the method receives a variable number of arguments of that particular type ex: public static double average (double ... numbers) { } //unspecified number of arguments //the method can get different number of parameters, but they must be double. average (d1, d2); average (d1, d2, d3); etc.

narrowing casting

must be done manually by placing the type in parentheses in front of the value: ex: public class MyClass { public static void main(String[] args) { double myDouble = 9.78; int myInt = (int) myDouble; // Manual casting: double to int System.out.println(myDouble); // Outputs 9.78 System.out.println(myInt); // Outputs 9 } }

instance methods

non-static method; can access all fields (static variables and instance variables) and methods of the class.

What is a static method?

not dependent on an object; called by specifying the class name.method name; can only directly manipulate static variables in the same class ex: Math.sqrt(65.0) Math - class name sqrt - method name

cast operator

performs an explicit type conversion; it is created by placing the desired result type in parentheses before the expression to be converted ex: numeric values from one type to another or to change an object reference to a compatible type enables conversions that would normally be disallowed by the compiler. a reference of any object can be cast to a reference of type Object

scope declarations

public class Scope { private static int x=1; //field that is accessible to all methods of this class public static void main (String [] args) { int x=5; System.out.print(x); //prints 5 useLocalVarible(); //prints 25 //prints 26 useField(); //prints 1 //prints 10 useLocalVarible(); //prints 25 //prints 26 useField(); //prints 10 //prints 100 /*method's local variable x shadows field x (the local parameter (x) in the main method has the same name as the field (x) of the class, so the field is hidden until the main block terminates execution*/ }//end main public static void useLocalVariable () { int x=25; System.out.print(x); x++; System.out.print(x); //initialized each time the method is called } public static void useField () { System.out.print(x); x= x*10; System.out.print(x); //modifies class Scope's field x }

main method

static method where execution starts in a Java program; Java Virtual Machine can invoke the main method without creating an instance of the class.

String.format

string method that can be used to build a formatted string. The method will return a string. ex: public String tomyString () { return String.format ("%d", hour); //this method returns a String format, but do not forget that it does not mean that you can only use %s placeholder in this format. You can use any type of placeholders such as %d or %f, but String.format converts the result into a String when the method is executed. } }

Inheritance

subclass objects inherit all properties & behaviors of superclass; subclass can inherit all non private members from superclass • Each class has only one superclass. • A superclass can have many subclasses. • Faculty is a direct superclass of administrator. • Employee and community member are indirect superclasses of Faculty. • Every subclass object is an object of its superclass. • A subclass inherits all the fields and methods of its superclass. • A subclass can add its own fields and methods. • A constructor cannot be inherited. • If the fields of the superclass are declared private, subclasses do not have access to modify them. But if they are declared protected, then subclasses have access to use them. However, if they are declared protected, all classes in the same package will have access to use them. This is not secure, so use set and get methods. **used to promote code re-usability

If a static method calls another static method in the same class, you do not need to specify the class's name to call the method.

true ex: public class UserTest { public static void main (String [] args) { User user1= new User ("akare", "123456"); User user2= new User ("akarc", "12Etut"); CheckUser (user1); CheckUser (user2); }//end main public static CheckUser (User myuser) { ...... }//end method }//end class "main" calls "CheckUser"

Pass-by-Value vs. Pass-by-Reference

two ways to pass arguments in method calls: • pass by value (a copy of the argument's value is passed to the called method) • pass by reference (the called method can access the argument's value in the caller directly and modify that data, it necessary. It improves performance by eliminating the need to copy possibly large amounts of data) **Java does not allow you to choose pass-by-value or pass-by-reference. All arguments are passed by value

super (keyword)

used to call a superclass's method in a subclass ex: super.earnings();

@Override

used to indicate that a method is intended to override an inherited method. ex: @Override //override superclass method public double CalculatePayment () { ..... } } public class Faculty extends Employee { ... } public class Administrator extends Faculty { ... } **you can use optional @Override annotation to indicate that the given method declaration should override an existing superclass method. This annotation helps the compiler catch a few common errors. @Override compares the method's signature with the superclass's method signatures. If there is not an exact match, the compiler issues an error message.


Set pelajaran terkait

Abeka Vocabulary, Spelling, Poetry V Quiz 3A

View Set

Criminology Chapter 1 Test, Criminology: A sociological understanding Chapter 5, Criminology Exam 1, Sociology Criminology 362 test1, Criminology Exam 1, Sociology 3600-Criminology Test 1, Sociology Criminology Exam 1, Sociology 362 Criminology TEST...

View Set

MBC105 Chapter 8: Understanding Medicaid Exam

View Set

Anatomy chapter 1 & 2 Test Based on Quizzes

View Set