java ceritification
abstract classes and interfaces
-both can contain public static final variables -Both can be extended using the extends keyword -both can contain static methods Neither can be instantiated directly
interface static method rules
-static method in interface is assumed to be public and will not compile if marked as private/protected -to reference static method, a reference to the name of the interface must be used hop.getAverageJumpHeight();
overwriting vs overloading
-they both involve redefining a method of the same name overloading uses different parameter or differnet different signatures overwrites method uses same parameter and signatures
what is the output of the following lines of code string str =" "; for(int i =0; i<10 ; i++) { str+=i + " "; } System.out.println(str);
1 2 3 4 5 6 7 8 9
abstract class defentition rules
1. An abstract class can not be instantiated directly 2. Abstract classes can have o to many abstract methods 3. abstract classes cannot be private or final 4. abstract class that extends another class inherits all of its abstract method as its own abstract methods 5. the first concrete class that extends an abstract class must provide an implementation for all of the inherited abstract methods does not have a method body
constructor definition rules
1. The first statement of every constructor is a call to another constructor within the class using this(), or a call to a constructor in the direct parent class using super(). 2. The super() call may not be used after the first statement of the constructor. 3. If no super() call is declared in a constructor, Java will insert a no-argument super() as the first statement of the constructor. 4. If the parent doesn't have a no-argument constructor and the child doesn't define any constructors, the compiler will throw an error and try to insert a default no-argument constructor into the child class. 5. If the parent doesn't have a no-argument constructor, the compiler requires an explicit call to a parent constructor in each child constructor.
order of initalization
1. if there is a superclass initialize it first 2.static variable declaration and static initalizer in order ther apper in the file 3. instatce variable declaration and instance initializer in the order that they appear in the file 4. the constuctor
what is the output of the following lines of code int three = 3; string four = "4"; System.out.println(1 + 2 + three + four)
64 becasue line 4 is a string variable
local variables
A variable defined within a block or method or constructor is called local variable.
which are the results from the following code(select all that apply) String number = "012345678"; System.out.println(number.substring(1,3)); System.out.println(number.substring(7,7)); System.out.println(number.substring(7)); a.1,2 b.123 c.7 d.78 e. a blank line
A, D, E
Which of the following is output by this code? String s = "Hello"; String t = new String(s); if("Hello".equald(s)) System.out.println("one"); if(t==s)System.out.println("two"); if(t.equals(s)) System.out.println("three "); if("Hello"==s)System.out.println("four"); if("Hello"==t)System.out.println("five"); a. one b.two c.three d.four e.five f.the code does not compile
A.one they are actually comparing the different chars and the chars are equal c.three - this correct because they are actually d.four- this will print a true because it is comparing 2 literals and this will end up evaluating to true
what is the result of the following lines of code StringBuilder sb = new StringBuilder(); sb.append("aaa").insert(1,"bb"),insert(4,"ccc"); System.out.print(sb); A.abbaaccc B.abbacca c.bbaaacc d.bbaaccca e.An exception is thrown f. the code does not compile
B
which of the following statements are true? a. An immutable object can be modified b. An immutable object cannot be modified c. An immutable object can be garbage collected d.An Immutable object cannot be garbage collected E. String is immutable. F.StringBuilder is immutable
B, C, E
default interface method rules
Default methods can only be created in the interface and not within a class or abstract class Default method must be marked with default keyword and provide default implementation(needs ot have a body) Default method is not assumed to the be static final or abstract as it may be used to overridden in classes that implement the interface defualt method is assumed to be publlic and ut will not compile if marked as privare or protected
what is the output of the following lines of code? String [ ] animals = {"dog","cat", "lizard","bird", "snake"}; Myloop: for(String Animal : animals){ if(animal.equals("cat")){ continue MyLoop; } System.out.println(animal); }
Dog lizard Bird snake
what is the output by the following code? public class Dog{ public ststic void main(String[] args) { int numDog=4; String dogtype="husky"; String anotherDog= numDogs+1; System.out.println(anotherDog +" "+ dogtype); System.out.println(numdogs + " " +1); }} A.4 1 b. c.5 D. 5 husky E.5 husky F.51husky G.The code does not compile.
G
immutable classes
Has no mutator methods can not be changed by an outside class Done by adding getters the values are set by the constructor they sometimes can contain a private method
array sorting crietria
In Order for the array to be searched it must be sorted, other wise you would get an unpredictable result
ArrayList tip
Int numbers = numbers.get(0);//null poniter exception int cant hold null
iterator
List<Integer> numbers = new ArrayList<>(); numbers.add(2); numbers.add(4); numbers.add(6); for(Iterator<Integer> iterator = ARRAY.iterator(); iterator.hasNext();) { Integer number = iterator.next(); System.out.println(ARRAY); iterator.remove(); }
for(Listiterator<Integer> listiterator = numbers.listIterator(
List<Integer> numbers = new ArrayList<>(); numbers.add(2); numbers.add(4); numbers.add(6); for(ListIterator<Integer> listIterator = numbers.listIterator(2); listIterator.hasPrevious(); ) { System.out.println(listIterator.previous()); listIterator.remove(); }
using date and time examtricks
LocalDate ld =LocalDate.of(2010,Month.April,1) ld.plusDays(10);//this is ignored System.out.println(ld);//output:2010-04-01 LocalTime lt = LocalTime.of(hour12,45); lt.plusadd(3);//Doesn't compile because this method doensnt exist for thelocal time
Array to Arraylist
String [ ] PetsArray = {"dog", "cat", "parrot"}; List<String> petList = Array.asList(petArray); petsList.set(0,"bird"); this take a regular Array, PetsArray, and turns it to an arrayList using the asList method this affects every thing it changes both the array and the arrayList the method add and remove is will thow a Abstract list exception
Null Pointer Exception
The NullPointerException is thrown by the JVM when there is a null reference where an object is required.
.equals()
This compares hash codes
constructor
Used to initialize instants variables
Java comments
We can have following comments in java /* text */ - The compiler ignores everything from /* to */. // text - The compiler ignores everything from // to the end of the line. /** documentation */
what is the output of the following code snippet int [] list = {10, 8,10,9}; for(int x : list){ System.out.println( X +";"); continue; } } a,10,8,10,9, b. 11,9 c, 8,10 d. the code will not compile because of line 3 e. the code will not compile because of line 6 f. the code will not compile because of line 7 g. the code will not compile because of line 8
a
what is the result of the following line of code? StringBuilder number = new StringBuilder("0123456789"); number.delete(2,8); numbers.append("-".insert(2,"+"); System.out.println(numbers); a. 01+89- b. 012+9- c.012+-9 d.123456789 e. An Exception is thrown f. the code does not compile
a
default construstor
a constructor that is automatically generated when you create a class if you don't create a constructor yourself
which of the following compile? a.public void jumpA(int...nums){} b. public void jumpB(String...values, int...nums){} c. public void jumpC(int..nums,String values){} d.public void jumpD(string..values,int...nums){} e. public void jumpE(String [ ] values, ...int nums){} f.public void jumpF)String..values,int[ ] nums){} g. public void jumpG(String [ ] values, int[ ] nums){}
a, b, c
Which of the folloning statment can be insterted in the blank line so that the code will compile successfully? public interface CanHop{} public class Frog Implements CanHop{ Public static void main(String [] args){ ___________Frog =new TurtleFrog(); } } public class CrazyFrog extends Frog{} public class TurtleFrog extends Frog{} a. Frog b. TurtleFrog c.Brazilian Horned Frog d.CanHop e. Object F. Long
a, b, d,e becasue the blank can be filled with any class ofr interface that is a superclass of frog
which of the following compiles?(choose all that apply a. final static void jump4(){} b. public final int void jump(){} c.private void int jump(){} d.static final method(){} e.void final method(){} f.void public jump(){}
a, d,
which of the following are valid lines of code to define a muitdemensional int array? a. int[][] array1= {{1,2,3},{},{1,2,3,4,5}}; b.int [][] array2= new array(){{1,2,3},{}1,23,4,5}}; c.int array3= {1,2,3},{0},{1,2,3,4,5}; d.int array5= new int [2][];
a,d
abstract classes vs interfaces
abstract classes you want to share code among several closely related classes(animal,-name,age...) you expect that classes that extend you abstract class have many common methods of fields or required access modifiers either than public (private, Protected) you want to declare non static or non-final field(name. age), this enable you to define method that can access and modify the state of object (getName, setName) interfaces You except that unrelated classes would implement your interface you want to specify the behavior for a specific data type but you are not concerned about who implements it behavior you want to separate different behavior
exceptions
all class acceptions must be handled or throw
class variables
also known as class variables
Interface
an interface can have methods and variables, but the methods declared in an interface are by default abstract (only method signature, no body).
viod methods
are allowed to have a return type along as it doesn't return anything
Arraylist
array list by naure accept any object, but when you the array list like List <String> list = new ArrayList<>(); the ArrayList will only accept what ever object is in <> Primitive can not be used with ArrayList
constructor chaining
associating one constructor with another by calling the "this()" keyword as if it was a function, so that the matching constructor is called first and allowed to execute and then any subsequent code is executed public Dog(String Name){ this(name, "husky"); } public dog(String Name, String Breed){ this(name, breed, 30)} public dog(String name, String Breed){ this.name = name; this.breed = breed; this.weight = weight; }
what modifiers are implicity applied to all interface methods(Choose all that apply)? a. Protected b. public c.static d.void e.abstract f.default
b
which of the following can replace line 2 to make this code compile? import java.utils.*; //INSERT CODE HERE public class Imports{ public void method (ArrayList<String>list){ sort(list); } } A. import static java.utils.Collections; B.import static java.utils.collections; C. import static java.utils.Collections.sort(ArrayList<String>); D.static import java.utils.collections; e.static import java.utils.collections*;
b
which arwe the results to the following lines of code String Letters="abcdef"; System.out.println(letters.length())_; System.out.println(letters.charAt(3)); System.out.println(letters.charAt(6)); A.5 b.6 C.c d.d e.an exception is thrown. f. the code doesnt compile
b, d, e
what is the output of the following lines of code? int count = 0; ROW_LOOP; for (int row=1; row<=3; row++) for(int col=1;col<=2;col++){ if(row*col % 2 ==0)continue ROW_LOOP; count++; } system.out.println(count); a.1 b.2 c.3 d.4 e.6 f. the code will not compile because of line 6
b.2
what is the output of the following lines of code? int [] list = {8,10}; for (int x:list){ System.out.print(x+","); break; } a. 8,10, b.8,10 c.8 d.. the code will not compile because of line 7 e. the code will not compile because of Line 8 f. the code contains an infinite loop and does not terminate
c
which of the following statments is true a. thje enhanced for loop can't be used with in a regular for loop b. the enhanced for loop cant be used with in a while loop c. the enhanced for loop can be used within a do-while loop d. the enhanced for loop can't be used within a switch construct e. all of the above
c
which of the following can fill in the blank in this code to make it compile? public class Dog{ ___________ void method(){} a.default b.final c.private d.Public e.String f.abc
c and d
which of these compile when replacing line 8? 7:char []c = new char[2]; 8://INSERT NEW CODE HERE a. int length = c.capacity; b.int length = c.capacity(); c.int length = c.length; d. int length = c.length; e. int length = c.size; F.int length = c.size; G. None of the above
c because the array has a length , not a method length, not a method size, etc
which of the following methods compile? a. public void runA(){return;} b.public void runB(){return null:} c.public void runC(){} d.public int runD(){return 9;} e. public int runE(){return 9.0;} public int runF(){return;} g.public int runG(){return null;}
c,d,g
Which of these arraydeclarations is not legal? a. int[] []scores =new int[5][]; b. object [][][]cubies = new object[3][0][5]; c.String beans[] = new beans[]; d. java.util.date[] dates[] = new java.utils.Date[2][]; e.int[][]types = new int[]; f.int[][] java = new int[][];
c,e,f
searching an arraylist
collections.binarySearch();
continue statement
continue statement finishes the execution of the current loop iteration optionalLabel: while(booleanExpression){ //body continue OptionalLabel; /\ |
what is the output of the following code class Test { public static void main String args[]){ int num = 120; switch (num){ default:System.out.println("default"); case 0: System.out.println("case1"): case 10*2-20:System.out.println("case2"); break; }}} A. default case1 case2 b.case1 case2 c.case2 d.Compilation error e. runtime error
d there is a compilation error because both of the switches are have the same value of 0
GIven the following mehtod, ehich of the folloeing method calls will return a 2>(choose all that apply) public int count (boolean b, boolean...b2){ return b2.length; } A. Count(); B.count(true); c.count(true,true); d.count(true, true, true); e.count(true,{true, true}); f.count(true,{true,true}); g.count(true, new boolean[2]);
d,e
default constructor
default construstor is a empty no arguement constructor that is generated automatically if there is no constructor
what is the output of the folling code? class animal{ public animal(int Age){ System.out.print("animal"); } } public class Hores extends Animal{ public Horse(){ System.out.print("horse"); } public static void main (string [] args){ new Animal(5); } } A. Horse b.Animal c.HorseAnimal E. the code will not compile Because of line 8 f. The Code will not compile Because of line 11
e beacuse there is not expilict super call
what is the outputof the following code? class java array{ public static void main (string [] args){ int [] arr1; int []arr2 = new int [3]; char[] arr3= {'a', 'b'}; arr1 = arr2; arr1 = arr3; System.out.println(arr1[0] +":" +arr1[1]);
e, this will not compile because of, arr1 = arr3;. this is because you can not pass a char array into an int array
what is the result of the following lines of code String s1 = "java"; String Builder s2 = new StringBuilder("java"); if(s1 == s2) System.out.println("1"); if(s1.equals(s2)) System.out.print("2"); a.1 b.2 c.12 d.no output is printed e.an exception id thrown f. the code does not compile
f because line 3 is comparing two different a String and a String Builder object
StringBuilder b ="rumble; b.append(4).deleteCharAt(3).delete(3,b.length()-1); System.out.print(b);
f. the code does not compile
what is the output of the following lines of code? String str1 = "abc"; String str2 = "ab"; String Str 3 = "str2" +"c" System.out.println(str1 ==str2); System.out.println(str1 == str3);
false true
the best options for iterating through a loop
for loop best when you need an index for each loop - best for when you just have to go through an read a list iterator- best if you need to iterate and remove elements at eh same time list iterator is the best candidate if you need to add, remove , a iterate through
Overwriting
happens when a you replace data from a method in a parent class with new data in a child class
string hello = "hello"; string hi = hello +"world"; hi = hello; System.out.println(hi + hello);
hellohello
Polymorphism
if a method tales a superclass of 3 objects, then any if those classes may be passed as a parameter to teh method a method that takes a parameter with type java.lang.object will take any reference all cast exception are com[filed at run time
method declaration donts
int 1expand (){} this will not compile because it is starting with a numerical value
data and time
java 8 local date-contain date only//LocalDate.now() local time-contains time only//LocalTime.now() local date/time- contains date and time//LocalDateTime.now() java 7 and ealier Calender calendar = Calendar.getInstance(); calender.set(2015calendar.january, 1); Date January = calendar.getTime(); System.out.println(january);
virtual methods/properties
method in which specific implemantation is not know until you run the code Methods designed to be overridden that have a base implementation; variables cannot be virtual.
instance variables
on-static variables and are declared in a class outside any method, constructor or block.
how to use a interface
public class bear extends animal implents Omnivore(){} the keyword in this case is implements is what allows you to use an interface
adding number in an immutable class
public double getReal(){ return real; } public double getImaginary(){ return imaginary(); } public complex plus (complex b){ double newReal = real + b.real: double newImaginary = imaginary + b.imaginary; return new complex(newReal, newImaginary); } public static Complex plus(Complex a, Complex b) { return a.plus(b); }
default interface method
public interface carnivore{ default void eatMeat(){ System.out.println("eating meat")}
immuatablity
refer to preventing caller from changing the immutability at all
Encapsulation
refers to the process of hiding the internal details of objects and their methods
what is the output of the following lines of code int number =10; int anothernumber = 20; System.out.println("result= " + number+ another number);
result = 1020 because this is string concatenation, if we want numerical concatenation then we need to add parentheses around the number variables (System.out.println("result= " + (number+ another number));
what are the values of s1, s2, and s3 String s1= "1"; String s2="s1.concat("2"); s2.concat("3");
s1= 1 s2= 12 this is because s2.concat("3") is nobeing called on anything ... it should be s2= s2.concat("3");
Down-casting
substituting a base class for a super class (go down the inheritance tree to children)
Up-casting
substituting a subclass for a base class (going from more specific to less specific in the inheritance tree)
super vs super()
super() -\ -is use to call Base class's(Parent class's) constructor must be at the beginning of the constructor super- can be used to parent class variables and methods
polymorphic parameters
the ability to pass instance of the subclasses or interface to the method - this can allow you to use one method for multiple children of the same parent class
what is the result of the following? int[] random = {6,-4,12,0,-10}; int x= 12; int y = Arrays.binarySearch(random, x); System.out.println(y); a.2. b.4 c.6 d. the result is undefined e. an exception is thrown f. the code doesn't compile
the result is undefined because the array must be sorted in order for it to return a meaningful result
Getters and setters
they get and set values
method chaining
this can only be done to method that return a variable
Array.asList();
this declares an array add adds it as a list returns a fixed size list
this vs this()
this method points to an objects own instance(me, myself, and I)
this.
this refers to a instance variable inside of the class. its like using I in a sentence required only when we have the same parameter name as our variable if you use this in a overloader construction then this has to be the first call the in a non commented constructor
System.out.println(str.substring(4,4);
this returns an empty string
converting a list to a array
to convert a list to an array of the same type you must do the following List <String> names = new ArrayList<>(); name.add("Tony"); name.add("jimmy"); name.add("anthony"); // creates the ArrayList String [ ] anotherStringArray = names.toArray(new String[names.size()]);
data encapsulation
to hide the implementation form users or hide data from your outside class. allows for code to be changed without changing the classes that relies on it
sorting an Arraylist
to sort an arraylist you use collections.sort()
iterating through a arrayList
you can not iterate and modify an array list using a for loop or a for each loop
Polymorphism
you can not pass a child in to a parent once an object has been assigned to a new reference only the method and variable assigned to that reference type are callable - you can not access portected elements through polymorphism - In java, all object is accessed through memory
what happens when you try to search an array that is not sorted?
you will get a negative number where it should be placed
what would be the output of the following lines of code? numberTable[0][0]=1; numberTable[0][1]=2; numberTable[0][2]=3; numberTable[0][3]=4;
you would get an exception because the array only has 3 columns 0 1 2. therefore the last line , number [0][3] would give us an exception because it is out of bounds