Unit 2: Using Objects Flashcards
What is the keyword “new” ?
The “new” keyword is used to instantiate a new object.
Proper String instantiation
String myString = new String(“Hello, World!”);
Overloading
In Java, two or more methods may have the same name if they differ in parameters (different number of parameters, different types of parameters, or both). This is called overloading. Ex. public Rectangle(int rectWidth, int rectHeight) { width = rectWidth; height = rectHeight; }
public Rectangle(int sidelength) { width = sidelength; height = sidelength; }
What are parameters?
Data/arguments that are passed to a method.
Wrapper Classes
Wrapper classes provide a way to use primitive data types (int, boolean, etc..) as objects. ex. int myInt = 10; Integer myInteger = new Integer(myInt);
Integer.parse
This method is used to get the primitive data type of a certain String.
Ex. Integer.parseInt(“11”); // Returns the int value 11
Generating random numbers
The Math.random() method returns a random double from 0-1 excluding 1;
int randInt = (int) (Math.random() * (max - min) + min;
What is an instance method?
A piece of code called on a specific instance (an object) of the class.
What is a void method?
A void method is a method that does not have a return value. Usually, these contain a print statement or modify the variables within the object in some way.
What defines a non-void method?
Non-void methods have a return statement. The method returns a certain data type and can be used as a variable of that data type.
What is an Integer? What is its purpose?
A wrapper class that helps turn a primitive into an object and object into a primitive data type.
It can be used in lists and such because they only store data as objects, so the conversion from primitive to object is needed.
Static Methods
Belong to the class rather than an instance of a class, therefore can be called without using an object.
Instantiation
To create a new instance of an object.
ex.
Student Ryan = new Student();
What are the different string methods?
name. concat(“value”) - returns a new string with “value” appended at the end of name
name. replace(“a”, “p”) - returns a new string with all instances of “a” in name replaced with “p”
name. toUpperCase()- Returns name as Upper Case Letters
Can you change a string once it is created?
No! Strings are immutable, so they cannot be changed once they are created.
(If you wanted to change the value of a string, you would have to re-assign it!)
However, you can concatenate strings with one another to create a new string value!