0% found this document useful (0 votes)
15 views13 pages

Java Extra Notes

Java Eclipse Usage Notes

Uploaded by

Armando Tan
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
15 views13 pages

Java Extra Notes

Java Eclipse Usage Notes

Uploaded by

Armando Tan
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 13

http://introcs.cs.princeton.

edu/java/11cheatsheet/
https://www.jetbrains.com/idea/
Integers, Doubles, Casting (Ch. 1):
● Assignment Operator: “=”
● The largest acceptable integer is 231 – 1, that is, 2147483647
● binary ex:
○ 123 in binary = 1111011 = (1 × 26) + (1 × 25) + (1 × 24) + (1 × 23) + (0 × 22) + (1 × 21) + (1
× 2 0)
○ 4 in binary = 100 = (1 * 22) + (0 * 21) + (0 * 20)
● hexadeciamal digits = 0x, 1, 2, 3, 4, 5, 6, 7, 8, 9, a, b, c, d, e, f
○ a = 10, b = 11, c = 12, d = 13, e = 14, f = 15
● To perform an operation and specify the data type of the resulting value: you would put “(data
type)” in front of the operation// this is known as casting
○ ex: (int) 3.8 + 5 // this will result in 8
● You cannot declare a variable inside a method parameter/ inside a method
● IF you have an INTEGER method and it RETURNS a NEGATIVE NUMBER, you have exceeded
the data cap of the number, so you get an INTEGER ARITHMETIC OVERFLOW

Arithmetic Expressions, Pitfalls and Surprises , Declaring Variable Values,
Shortcuts (Chapter 2):
● You could say that you use PEMDAS to evaluate arithmetic expressions
● if a positive value / 0.0, it will equal Infinity
● if a negative value / 0.0, it will equal -Infinity
● if 0.0 / 0.0, it will equal Nan (Not a number)
● if a double value OR double cast (double) is present, the output will be a double
● Integer.MIN_VALUE = -2147483648
● Integer.MAX_VALUE = 2147483647
● evaluating or putting a cast on a float value, you will have a “loss of precision”
● IF you have 2 int’s in the the operation, they WILL ALWAYS RESOLVE to INT; no matter if you
divide it, multiply, etc. (SAME THING GOES FOR OTHER PRIMITIVE TYPES)
Strings, Converting Between Strings and Numbers (Chapter 3):
● If you want to check for a word in a String, use (String Name).contains
● When comparing strings, you use “.equals()” not “==”
● use “.compareTo()” to compare Strings
○ if a.compareTo(b):
■ it will give NEGATIVE if a comes before b in lexographical order
■ it will give NEUTRAL/0 if a and b are the same String
■ it will give POSITIVE if a comes after b
● Lexographical order includes Uppercase letters, a few punctuation marks, then lowercase letters
● “&&” uses lazy evaluation because if the first condition is false, the compiler won’t consider the
second condition
○ Don’t get tricked thinking that “||” uses that too because if the first condition is false, the
compiler has to look for a true in the second condition
● De Morgan’s Laws summarize the functions of “&&” and “||”
○ !(a && b) == (!a || !b) is true
○ !(a || b) == (!a && !b) is true
● you use “.IndexOf(“...”)” to find the first index that the specified substring is found in the String
● ex: m = p.substring(p.indexOf("V"),p.length());
○ It will find the index of the first instance of “V” in the String, find the substring from that
index to the end of the String, and make that substring the value of m.
○ You can use p.length in this situation because it is inclusive and will refer to all index that
comes before that point.
Booleans (Chapter 4):
● There are 6 different relational operators: <=, <, >=, >, !=, ==
● If you reference a specific index in a substring, you will also reference the rest of
the substring after that index.
○ String c = b.substring(1); // b = “Fred”
// c = “red”;
● A loop will only begin iterations when the deciding condition is true. Even if the
condition is met, if its false then it will not start
Arrays (Chapter 5):
● If an array is having its elements use the “.remove()”, watch for how the indexes
are moved over, taking up new positions
● You can't use "{"","",""}" to re-initialize a String array. You have to change each index at a time.
● For 2 dimensional array, syntax is (arrayname)[x][y];
x goes (1 left) from here, and
to the right

y goes (1 up) from here, and [0][0] [0][1]


down below

[1][0] [1][1]
● ex: If h is a 2-dimensional array, what expression evaluates to the value of the
element that is in the last column of the last row?
○ h[ h.length - 1 ][ h[ 0 ].length - 1 ]
● The syntax [x][y] REALLY MATTERS
● In:
String[] p = { "A", "B", "C", "D", "E" };
String[] q = { p[ 0 ], p[ 1 ], p[ 2 ], p[ 3 ], p[ 4 ] };
String[] r = p;
p[ 3 ] = "Z";
//p[3] = “Z”, q[3] = “D”, r[3] = “Z”;
● Your experimentation in Exercise 49 should have made you suspect the following:
When an array referenced by one variable is assigned to another variable, then both
variables reference the same array. In the code above, once the assignment y = x
has occurred, the situation may be depicted as follows:
Such a suspicion is well-founded. Under such circumstances, any changes made to
the elements of the array are "seen by both variables". In fact, x and y are said to be aliases
— they are two different labels for one and the same thing.
● If a change happens in y, and “y=x”, then the change will also happen x.
● To find the length of an array: (array name).length
○ To find the length of an ArrayList: (arraylist name).size
● To find the length of a String: (String name).length()
● ex: String[] b;
b = { "a", "b", "c" }; // illegal
b = new String[] { "a", "b", "c" }; // legal
int[] z = new int[] { 1, 2, 3, 4, 5 }; // legal
int[] z = { 1, 2, 3, 4, 5 }; // legal

● You can only use {...} to initialize data type arrays, not arrays of Strings and Objects
● For 2-dimen[sional arrays, “(array name).length” only finds the number of rows, not columns.
● When initializing a 2-dimensional array: int[ ] [ ] t = { { 1, 2, 3, 4 },
{ 5, 6, 7, 8 },
{ 9, 10, 11, 12 } };
// you need 2 brackets on each side
● Different ways to make array:
○ int [] x = new int[10];
○ int[] x;
x = new int[10]
○ int[] x = {1,2,3,4,5};
○ int x [];//it works, but you can’t really do much with it.
● If you try to access an uninitialized index in an array or arraylist, it will print out “null” since it is the
default String value
○ Default array values: int arrays give 0, double arrays give 0.0, boolean arrays give false,
String arrays give “null”
● If you try to access an index that is outside the range of the array, you will get an
ArrayIndexOutOfBounds Error
● Giving a variable a value, and then changing that value later is called “overwriting”
● Vectors: one dimensional array(normal array); Matrix: 2-dimensional array
● ex: int[] b = { 5, 4, 3, 2, 1 };
int t = 3;
b[ t ] = b[ t - 1 ];
b[ t + 1 ] = b[ t ] - 1;
int y = b[ 4 ];
int x = b[ y - 1 ] + 1;// x = 5
● enchanced loop - loop created with “:” operator
○ The specified operation will apply to all the index in the array

Conditional Statements, Blocks (Chapter 6)


● if you want your program to consider other conditions when your initial “if” statement is not met,
then use the “else” keyword
● A block is a set of code between two braces “{...}”
● “variable is already defined” Error- if you are declaring, not initializing, a variable that has
already been initialized and declared earlier in the program
● a variable declared inside a conditional body/ statement is not able to be used outside the loop
● Cannot Resolve Symbol Error- program execution is stopped when a variable THAT HAS NOT
BEEN DECLARED OR INITIALIZED is referenced in the program
● return (blablabla) ? 42 : 97;
○ This is the same as:
■ if (blablabla)
● return 42;
■ else
● return 97;
○ Also the same as:
■ int result;
■ if (blablabla)
● result = 42;
■ else result = 97;
● return result;

Iteration, Conditional Loops (Chapter 7)


● Watch your varibales to see if they are actually changed in each iterations, and if
there are any methods or operations being acted on the variable
● we use while loops and for loops mainly
● for loops are composed of 4 things: body, intialization, condition, update
○ body- code iterated in the loop

● while loops are composed of 3 things: loop statement, body, condition
○ body: what is to occur in each loop
○ condition: what happens to cause the loop
○ loop statement: this keyword tells what kind of loop
● ex of FOR loop condition: (int i = 0; i < t.length; i++)
● ex of WHILE loop condition: ( i < t.length)
● prime numbers are greater than 1 and have 2 divisors
● the number 1 is neither prime nor composite
● Incompaitble Type Error- a while loop doesnt use a boolean condition to iterate
● Even if your AND statement has both conditions to be met, if your condition is met with FALSE
STATEMENTS your loop will iterate. You must have your loop condition be TRUE AND ONLY
TRUE for it to be iterated
● infinite loop- loop that runs forever
1. String s = "SECRET";
2. String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
3. int i = 0;
4. while ( i < s.length() )
5. {
6. System.out.print( alphabet.indexOf( s.substring( i, i+1 ) ) );
7. System.out.print( " " );
8. i++;
9. }
0 1 2 3 4 5
19 5 3 18 5 20
18 4 2 17 4 19
-1 -1 2 -1 1 -1
None of these

10. What is the value of i after the following code is executed?


11. int i = 1;
12. while ( i < 10 )
13. {
14. int j = 10;
15. while ( j > i )
16. j--;
17.
18. i += j;
19. }

Methods (Chapter 11):


● In PRINT methods, you can concatenate Strings and Numbers
● Random Numbers:
○ If you want to get an amount of numbers from a random number generator within
x consecutive values:
■ type: “(int) (x) * Math.random();”
● Recursion:
○ Having a method body include a call to itself
○ This allows us to take the return value of a method and input it back into the
method itself
○ This allows to do a pseudo-reiteration, since we do it without for and while loops

● ? Operator:
○ Used in combination with ONE condition and TWO values
○ If the condition is true, then the first value is returned
○ If the condition is false, then the second value is returned
● Multi-Variable Declaration and Initialization:
○ As long as the varibles themselves are of the same type, you can just declare the
variable type, then the variable names seperated by commas, and send with a
semicolon.
○ You can then initialize those variables either below the declaration, or in the
declaration itself, in between the commas
■ ex: int i;
int j;
int k
String s1;
String s2;
■ int i, j, k;
String s1, s2;
■ You can even: // in between the commas
● int i, j = 4, k;
String s1, s2 = “no comment”;
Inheritance and Polymorphism:
● Uses for inheritance:
○ Objects from different subclasses can be stored in the same array.
○ Objects from different subclasses can be passed as arguments to a method
designed to accept objects of a superclass
○ Methods from a a superclass can often be reused in its subclasses without
duplication of code
○ Abstract classes at the top of the hierarchy can easily be extended in the project
or reused in other projects
● If you try to access a PRIVATE variable in a superclass from a subclass, you will fail
because it is private and inside another class
● If you DECLARE an abstract method in a superclass, you can ALWAYS DEFINE IT
inside a subclass
● On average, for-each loop and for loop are EQUALLY EFFICIENT
○ “for- each loop” works on BOTH arrays and arrayslists
● When you call a method in a subclass FROM A SUPERCLASS, you OVERRIDE it and
perform the function stated in the SUBCLASS
● When "extending" class definitions like this, it is important that the superstatement in the
extended class constructor should be the first statement in the constructor's body.
● Polymorphism: treating an object as an instance of the superclass of its true class
○ The object/ variable can be treated as the data type of any superclass
○ This has the effect of causing the variable to store an instance of the subclass
while being treated within the program as if it stored an instance of the
superclass.
● “deriving” and “extending” from a class are the same things
○ “deriving” is more like a subtype of “extending” because it means to create a new
class definition from an existing class
● Overriding Methods: When two methods have the same data return type, method
parameters/ signatures, and one method is declared in the superclass and the second in
the subclass: the return statements/ the functions of the method are changed between
the two methods
○ By redefining the method in another class, you change its function even though it
is called the same way. You can refer to the original function by using “super.” in
front of the method call when you are implementing it in the subclasses
● The instanceof operator behaves like a >, >=, <, <=, !=, etc. and will return a
BOOLEAN value.
○ You use this if you want to check if a variable/ object

Simple Objects (Chapter 12):


● We use “.equals” for objects, not “.compareTo”
● Public Classes:
○ The fact is that Java requires that every method definition must appear within a
class definition, and there is no exception for the static main method.
○ When ever you use the main method, Java inserts a constructor with nothing
inside of it, so nothing else is acted upon
○ MAIN methods have constructors with no arguments or body inside
○ Constructor Signature: (name of constructor) + “()”;
○ Instance Method: A method that changes an object’s behavior or value
○ Class Definition and Class Delcaration are the same thing.
● Compiler:
○ This translates your code into byte form and performs the actions that
correspond to certain sets
■ Garbage Collection: When the Java program recycles excess, unused
memory, after having the virtual machine inspect each of the values
stored in the memory. If one is not needed any longer, the program will
recycle.
○ The Java Virtual Machine will then execute the sequence outlined in the byte
code, after organizing it all into the sequence.
● Errors:
○ IllegalArgumentExpression: An attempt to cast a variable to a data type that does
not apply.
○ Syntax Error: Errors in the correct formulation of expressions and statements in
the programming language. For example, misspellings; missing braces,
parentheses, or brackets; missing semicolons.
○ ProgramsStructure Errors: missing return types, uninitialized variables
○ Data Type Errors: incompatible use of types, like String to double without casting
○ The program behaves incorrectly: The logic of the program is flawed. As a result,
it either does not run at all, it becomes stuck in an infinite loop, or it runs and
either performs the wrong actions or produces incorrect output, or both.
○ Invalid Error Declaration: The error generated when an attempt is made to create
an instance of a class when the class contructor’s name doesn’t match the name
of the class itself
● Exceptions:
○ ArithmeticException: dividing integers by 0
○ ClassCastException: cast a variable into a data type that doesn’t apply
○ ClassCastException: An attempt to cast a varibale into a non-applicable data
type
○ IllegalArgumentException: A method being used on an argument/ variable of an
incompatible type; part of the RunTimeException Class
○ NullPointerException: Reference to a null variable
○ RunTimeException: Instances that can be “thrown”, thus interrupting the program
execution. Usually used to show the user where they have a problem (such as an
attempt to divide an integer by zero) is detected or deliberately when a
programmer determines that an assertion has failed.
● *(java.lang.Object) is NOT an object itself, but the definition of an object
● *(java.util.Comparator) does not have method compare()
● *The this keyword refers to the instance of the object/variable at that point in
the program

Sorting: (look at Harvard Computer Science for sorting video)
○ Selection Sort:
■ Info:
● You only need a certain number of iterations to find the fewest or
the greatest
■ Steps:
● 1. Choose the direction you are sorting (descending or
ascending), find the LARGEST ELEMENT, SWAP it to put it at an
end (at the beginning if descending OR at the end for ascending),
● 2. We then look for the NEXT LARGEST and SWAP it right next
to the LARGEST element.
● 3. Repeat until finished
○ Insertion Sort: (2 kinds): uses a NEW array
■ 1st Kind: Pushes all elements to the side
● 1. We create another array of the same size, and take the FIRST
element of the 1st array and copy it into the 2nd array.
● 2a. If the NEXT element is GREATER THAN the FIRST element,
then input into the 2nd array to the RIGHT of the FIRST element.
○ 2b. If the NEXT element is LESS THAN the FIRST
element, then input into the 2nd array to the LEFT of the
FIRST element, by pushing the existing elements aside.
● 3. Repeat until finished
■ 2nd Kind: Pushes all element FROM A SINGLE INDEX aside
● 1. We create another array of the same size, and take the FIRST
element of the 1st array and copy it into the 2nd array.
● 2a. If the NEXT element is GREATER THAN the FIRST element,
then input into the 2nd array to the RIGHT of the FIRST element.
○ 2b. If the NEXT element is LESS THAN the FIRST
element,then we push the FIRST element to the RIGHT.
● 3. We then compare the element with the next element to the
LEFT
● 4. Repeat step 2 and 3 until finished
○ Merge Sort: Uses Recursion. For large arrays this represents a very significant
improvement in efficiency over selection sorts and insertion sorts. Looked at from
a different point of view, a merge sort running on a small personal computer will
easily beat a supercomputer running a selection sort on a large array of, say,
1,000,000 integers.
■ 1. Split the initial aray until you have arrays of length 2 when the length
was originally EVEN, or if the initial length is ODD then ONE array of
length 3 and the rest of length 2.
■ 2. Sort the sub arrays independently
■ 3. Merge them (make sure the number order isn’t messed up)
○ Quick Sort (adv):
■ 1. Choose an element of the array. (Now known as the pivot element)
■ 2. Make 2 sub-arrays: One with ALL of the numbers that are LESS than
the chosen element to the LEFT, and one with ALL the numbers that are
GREATER than the pivot element to the RIGHT. DONT INCLUDE THE
PIVOT ELEMENT IN EITHER OF THESE.
■ 3. Sort the sub-arrays individually.
■ 4. Join all 3 components together.
○ Tree Sort (adv):
○ Heap Sort (adv):
○ In-Place Sort: sort that operates directly on the source array.
● Merge sort VS Quick sort:
○ Even thought Quick sort does have the problem of unbalanced sub-arrays
resulting from a “bad” choice of pivot element, but it is on average faster than
merge sort.
● Binary Search:
○ IF the array is already sorted, binary search works best
○ How is works:
■ 1) Split the array into 2 halves
■ 2) Decide which half contains the wanted value, and forget the other
■ 3) Take this half, and split it in half again, then decide
■ 4) Repeat steps 2 & 3 until number is found
Miscellanious:
● Precedence Order- When two operators share an operand the operator with the higher
precedence goes first. For example, 1 + 2 * 3 is treated as 1 + (2 * 3), whereas 1 * 2 + 3
is treated as (1 * 2) + 3 since multiplication has a higher precedence than addition.
● Associativity- When an expression has two operators with the same precedence, the
expression is evaluated according to its associativity. For example x = y = z = 17 is
treated as x = (y = (z = 17)), leaving all three variables with the value 17, since
the = operator has right-to-left associativity (and an assignment statement evaluates to
the value on the right hand side). On the other hand, 72 / 2 / 3 is treated as (72 /
2) / 3 since the / operator has left-to-right associativity.
● “break” keyword is for when you want to exit a loop, and CAN return a value, during the
loop’s iteration/ duration
● Even if a statement has multiple RETURN statements, only one will actually be used to
return something back
● OverLOADING vs OverWRITING vs OverRIDING
○ Overloading- making a method take an input of different types of variables
■ These can be differenciated based only the names chosen, just not
recommended because you have to consider parameters
○ Overwriting- REPLACING the original method function with entirely new actions
○ Overriding- Still enacting the ORIGINAL function of the method, but then later
changing the function of the method
● Polymorphism- Subclasses of a class can define their own unique behaviors and yet
share some of the same functionality of the parent class.
○ This can mean overriding and overloading methods that already exist
● Interfaces: A collection of public static void methods, NO VARIABLES
○ Usually only used for organization

○ These need to be implemented, like the “implemented” keyword must be the
class declaration
○ You cannot declare variables inside interfaces, but INTERFACES can be
implemented INTO classes
○ You aren’t able to have “fields” in an interface
● Classes have 2 types: concrete and abstract
● Abstract class: A class made solely for other classes to extend.
○ Superclasses are many times made to be abstract
○ When an abstract class is subclassed, the subclass usually provides
implementations for all of the abstract methods in its parent class. However, if it
does not, then the subclass must also be declared abstract.
○ Abstract classes CANNOT EXTEND another abstract classes
○ Abstract classes do not necessarily need to have abstract methods
● Abstract Methods: These can ONLY be made in abstract classes. They are methods
declared without an implementation (without braces, and followed by a semicolon).
○ These are declared in one, then implemented in other classes
● The purpose of pre-conditions and post-conditions is to provide information to the
programmer about what the method is intended to do.
● Only when the search value is the first item in the array, and thus the first value
encountered in sequential search, will sequential be faster than binary.
● If you modify a primitive type parameter in Java in a method it will not change the value
of the variable in the calling method.
● The Integer class does implement compareTo which will return 0 when the int values in
the Integer wrapper objects are the same.
● Apparently, the toString() method will always be called if you print out a value.
● To override a method you create a method with the same name and parameter list as a
method you have inherited from a superclass.
● When overriding, you are defining a method with the same name and parameter list as
an inherited method.
● To initialize inherited private fields you can use the parent's constructor. Use super
followed by the parameter list as the first line of code in the constructor.
○ Use of the super() method means that you are using the method from the
superclass has a matching set of parameters
● If you use overwriting and call a method from a superclass from a method in the
subclass, you will call the method in the superclass. If that method in the superclass
calls for a method that was also overwritten in the subclass, it will call the subclass
version of the method.
● compareTo() can only be used on Strings and objects, not primitive variables
● The == operator checks if two object references refer to the same object.
● equals() checks if the object or String values are the same
● Overriding allows a child class to define a method with the same name and method
signature as a parent class. The child method will be called instead of the parent
method. This allows inheritance-based polymorphism since the method called at runtime
will depend on the type of the object.
● When software testing, it is impossible to test for all possible data
● Overloading is necessary is when two functions that perform the same essential
operation take a different number of parameters.
● (“a” + null) is equal to (a + “null”)
● The “+” can be used for concatenation, instead of arithmetic operations, if
the variable that is being initialized is a String, and is having the variable
values being added to it, even if the added values are integers or doubles.
Those values will be added as Strings
● You CANNOT use “int” as the type for an ArrayList

You might also like