---
# System prepended metadata

title: 'Java SE 11 Developer - 1Z0-819 (Java SE: Programming Complete)'

---


#  Java SE 11 Developer - 1Z0-819 (Java SE: Programming Complete)

##    Chapter 1 - Introduction to Java

### Keywords to take a look on it


SINCE JAVA 1 =>  transient | native | volatile
SINCE JAVA 1.2 => strictfp
SINCE JAVA 9  => module | requires | transitive | 'exports to' | uses  | provides | with | 'opens to'
NO LONGER IN USE => goto | const


### Name Conventions

1. PACKAGE: Is a reverse of your company domain name, plus the naming system adopted within your company.
2. CLASS: Should be a noun, in mixed case with the first letter of each word capitalized.
3. VARIABLE: Should be in mixed case starting with a lowercase letter; further words start with capital letters. 
4. NAMES: Should not start with numeric characters (0-9), underscore _ or dollar $ symbols.
5. CONSTANT: Is typically written in uppercase with underscore symbols between words.
6. METHOD NAME: Should be a verb, in mixed case starting with a lowercase letter; further words start with capital letters.

**e.g.**



| Item | Convention |
| -------- | -------- |
| PACKAGE     | com.oracle.demos.animals     |
| CLASS     | ShepherdDog     |
| VARIABLE     | shepherdDog     |
| CONSTANT     | MIN_SIZE     |
| METHOD     | giveMePaw     |


**NOTE** => Java is case-sensitive; 'Dog' is not the same as 'dog'
**NOTE 2** => The use of the _ symbol as a first or only character in variable names produces a compiler warning on Java 8.
To Java 9 onward an error will be presented to this cases. 

### Basic Syntax Rules

1. All statements must be terminated with ;
2. Code blocks must be enclosed with {}
3. Indentations and spaces help readability, but are syntactically irrelevant.

**e.g.**

```
package com.oracle.demos.animals;

class Dog{
	void fetch() {
	   while (ball == null) {
	   		keepLooking();	   
	   }
	}	
	void makeNoise() {
	
		if(ball != null) {
			dropBall();		
		}else {
		 	bark();		
		}	
	}
}
```



### Define Java Class

```
package <package name>;
class <ClassName> {

}
```
**e.g.**
```
package com.oracle.demos.animals;
class Dog{
 	// the rest of this class code
}
```
NOTE => If package definition is missing, class would belong to a "default" package and would not be placed into any package folder.
However, this is not a recommended practice.


### Access Classes Across Packages

**e.g.**
```
package animals;
public class Dog{
}
```
importing it to another class:
```
package people;
import animals.dog;
public class Owner{
  Dog myDog;
}
```
**NOTE** => Imports are not present in a compiled code and an import statement has no effect on the runtime efficiency of the class.
It's a simple convenience to avoid prefixing class names with package names throughout your source code.

### Use Access Modifiers

* public: Visible to any other class.
* protected: Visible to classes that are in the same package or to subclasses.
* <default>: Visible only to classes in the same package.
* private: Visible only within the same class.

**NOTE** => <default> means that no access modified is explicitly set.
**NOTE 2** => Any nonprivate parts of your class should be kept as stable as possible, because changes of such code may adversely affect
any number of other classes that may be using your code.



### Create Main Application Class

The 'main' method is the entry point into your application.
* It is the starting point of program execution.
* The method name must be called main.
* it must be public. You are intend to invole this method from outside of this class.
* it must be static. Such methods can be invoked without creating an instance of this class.
* it must be void. it does not return a value.
* it must accept array of String objects as the only parameter. 

**e.g.**
```
package demos;
public static void main(String[] args) {
   // program execution starts here
}

```
**NOTE** => The name of this parameter "args" is irrelevant.


### Execute Java Program

**NOTE** => Since Java 11, it is also possible to run single-file source code as if it is as compiled class. 
JVM will interpret your code, but not compiled class file would be created.

**e.g.**

```
java /project/sources/demos/Whatever.java
```

### Comments and Documentation

Code Comments can be placed anywhere in your source code.
Documentation Comments: 
* May contain HTML markups
* May contain descriptive tags prefix with @ 
* Are used by the javadoc tool to generate documentation

**e.g.**


// single-line comment

/*
   multi-line comment   
*/ 

/**
*  The {@code Whatever} class
*  represents an example of 
*  documentation comment
*  @version 1.0
*  @author oracle
*/



---

##    Chapter 2 - Primitive Types, Operators, and Flow Control Statements

### Java Primitives

| Item | size | min value | max value |
| -------- | -------- |
| byte     | 8 bits     |-128 | 127 |
| short     | 16 bits     |-32,768 | 32,767 |
| int     | 32 bits     |-2,147,483,648 |2,147,483,647 |
| long     |  64 bits      |-9,223,372,036,854,780,000| 9,223,372,036,854,780,000|
| float     | 32 bits     |1.4E-45| 3.4028235E+38 |
| double     | 64 bits     |4.9E-324  | 1.7976931348623157E+308 |
| boolean     | -     |true | false |
| char     | 16 bits     |0 | 65,535|


### Declare and Initialize Primitive variables

Declaration and initialization syntax:

<type>  <variable name> = <value>;

Numeric values can be expressed as binary, octal, decimal and hex.
Assignment of one variable to another create a copy of a value.

e.g.
```
float e = 1.99E2F
char k = '\u0041', l = '\101'
```


### Assignment and Arithmetic Operators

=  + - * / %

| Operation     | Description|
| int a = 1     | Assignment (a is 1) |
| int b = a+4   | Addiction (b is 5)  |
| int c = b-2   | subtraction (c is 3)  |
| int d = c*b   | multiplication (d is 15)  |
| int e = d/c   | division (e is 5)  |
| int f = d%6   | modulus (f is 3)  |

NOTE: Order matters,  the expression (b = a++) means add value from a to b and only after increment a.



### Short-Circuit Evaluation

&& ||  => short-circuit evaluation
& | ^  => full evaluation


### Flow Control Using if/else Construct

The if code block is executed when the boolean expression yields true; otherwise else block is executed.
The else clause is optional

e.g.
```
int a = 2, b = 3;
if (a > b) {
	a--;
} else {
	if(a < b) {	
		a++;
	} else {
		b++;	
	}
}

```

NOTE: Compilation fails because a block containing more than one statement must be enclosed with {} 



### Ternary Operator

You can use ternary operator ?: instead of writing an if/else

<variable> = (<boolean expression) ? <value one> : <value two>

e.g.
```
int a = 2, b = 3;
int c = (a >= b) ? a : b; 

```


##    Chapter 3 - Text, Date, Time, and Numeric Objects

### String Initialization

String is a class (not a primitive). Its instances represent sequences of characters.

```
String address = "August Haven st, 20"
String b = new String("Hello")
```

NOTE: The method intern() returns a reference to an interned(single) copy of a String literal.
NOTE 2: chars using single quote '' and String double quotes ""

### String Operation
Once a string object is initialized, it cannot be changed.
Operations such as trim(), contact(), toLowerCase(), toUpperCase(),and so on would always return a new String, but would not modify the original String.

e.g. 
```
String word = ""
word = 1 + 1 + "u"; // word is 2u
word = "u" + 1 + 1; // word is u11
word = "u" + (1 + 1); // word is 2u
```
NOTE: Operations are made from left to right, if needed to point to arithmetic operations use parentheses
NOTE 2: String contains a sequence character indexed by integer and it starts from 0.


### Wrapper Classes for Primitives

|  Primitive   |  Wrapper Class   |
|byte |  Byte |
|short|  Short|
|int|     Integer|
|long|    Long|
|float|   Float|
|double|  Double|
|char|    Character|
|boolean| Boolean|

Wrapper class apply object-oriented capabilities to primitives.
e.g.
```
int a = 42;
Integer b = Interger.valueOf(a);  // int to Integer
int c = b.intValue();  // Integer to int 
```

### Representing Numbers Using BidDecimal Class

The java.math.BidDecimal class is useful in handling decimal numbers that require exact precision.

All primitive wrappers and BigDecimal are immutable and signed.

e.g.
```
BigDecimal price = BigDecimal.valueOf(12.99);
BigDecimal taxRate = BigDecimal.valueOf(0.2);
BigDecimal tax = price.multiply(taxRate);  // tax is 2.598
price = price.add(tax).setScale(2,RoundingMode.HALF_UP); // price is 15.59
```


### Local Date and Time

package: java.time 
Classes: LocalDate, LocalTime, and LocalDateTime

e.g.
```
LocalDate today = LocalDate.now();
LocalTime thisTime = LocalTime.now();
LocalDateTime currentDateTime = LocalDateTime.now();
LocalDate someDay = LocalDate.of(2019, Month.APRIL,1);
LocalTime someTime = LocalTime.of(10,6);
LocalDateTime otherDateTime = LocalDateTime.of(2019, Month.MARCH,31,23,59);
LocalDateTime someDateTime = someDay.atTime(someTime);
LocalDate whatWasTheDate = someDateTime.toLocalDate();

```

### Zoned Date and Time

Time zones can be applied to local date and time values.

e.g.
```
ZoneId london = ZoneId.of("Europe/London");
ZoneId la = ZoneId.of("America/Los_Angeles");
LocalDateTime someTime = LocalDateTime.of(2019,Month.APRIL,1,07,14);
ZonedDateTime londonTime = ZonedDateTime.of(someTime, london); // Set London LocalDateTime
ZonedDateTime laTime = ZonedDateTime.withZoneSameInstant(la); // Using London LocalDateTime get exactly moment on LA.  
```


##    Chapter 4 - Classes and Objects

### Modeling

-Classes describe attributes and operations
-Attributes indicate their type
-Operations describe parameters and return type
-arrows indicate the exact nature and type of relationships between classes, such as inheritance, association and so on. 


### Designing Classes
NOTE: UML diagrams to model program flow of control are Sequence Diagram and Activity Diagram

```
package <package name>;

import  <package name>.<OtherClassName>;

 <access modifier> class  <ClassName> {
 	// variables and methods
 }

```
e.g.
```
package demos.shop;

import java.math.BigDecimal;

public class Product {
	public BigDecimal getPrice() {	
		return price;
	}
	
	public void setPrice(double value) {
		price = BigDecimal.valueOf(value)
	
	}

}
```

### Creating Objects

The new operator creates an Object (an instance of a Class), allocating memory to story this object.
NOTE: Object reference means a typed variable that points to an object's location in memory
NOTE 2: An object must be an instance of a specific class.
e.g.
```
Product p1 = new Product();
p1.setPrice(1.99);
BigDecimal price = p1.getPrice();

```


### Define Instance Variables

- Variable is defined with its ***type***, which can be one of eight primitive types or any Class.
- Variable ***name*** is typically a noun written in lowercase.
- To protect data within the class, variables typically use ***private*** access modifier.
- Optionally, variables can be initialized(assigned a default value)

NOTE: Uninitialized object references are defaulted to ***null***


```
package <package name>;

import  <package name>.<OtherClassName>;

 <access modifier> class  <ClassName> {
    <access modifier>  <variable type>  <variable name>;
 	<access modifier>  <variable type>  <variable name> = <variable value>; // Optional Assignment of Value
 }

```

e.g.
```
package demos.shop;

import java.math.BigDecimal;
import java.time.LocalDate;

public class Product {
	private int id;
	private String name;
	private BigDecimal price;
	private LocalDate  bestBefore = LocalDate.now().plusDays(3);  // Optional Assignment of Value

}

```
### Define Constants
Data that is assigned once and cannot be changed

- The keyword ***final*** is used to mark a variable as a constant; once it is initialized, it cannot be changed.

e.g.
```
package demos.shop;

import java.math.BigDecimal;
import java.time.LocalDate;

public class Product {
	private final String name = "Tea";	

}

```

##    Chapter 5 - Improve Class Design

### Method overload

Method overloading is used to define more than one version of a method within a given class.


e.g.
```
package demos.shop;

import java.math.BigDecimal;

public class Product {
	private BigDecimal price;
	private BigDecimal discount = BigDecimal.ZERO;
	
	public void setPrice(double price) {
		this.price = BigDecimal.valueOf(price);
	}
	
	public void setPrice(BigDecimal price) {
		this.price = price;
	}
	
	public void setPrice(BigDecimal price, BigDecimal discount) {
		this.price = price;
		this.discount = discount;
	}	
	
}

```

### Variable Number of Arguments

The ***vararg*** feature enables a variable number of arguments of the same type.


e.g.
```
package demos.shop;

import java.math.BigDecimal;

public class Product {
	private BigDecimal price;
	private BigDecimal discount = BigDecimal.ZERO;
	
	public void setFiscalDetails(double... values) // double ... means use of vararg
	{  		
		switch (values.length) {
		
			case 3:
				tax = BigDecimal.valueOf(values[2]);
			case 2:
			    discount = BigDecimal.valueOf(values[1]);
			case1:
			    price = BigDecimal.valueOf(values[0]);		
		
		}				
	}	
}

```

### Define Constructors

NOTE: A constructor without an argument is created implicitly only if there is no other constructor with parameters.



### Reuse Constructors

A constructor can invoke another to reuse its logic
- Invocation of another constructor is performed by using the follow syntax:

this(<other constructor parameters>);

e.g.

```
package demos.shop;

import java.math.BigDecimal;

public class Product {
	private BigDecimal price;
	private String name;
	
	public Product(String name, double price) {	
		this(name);
		this.price = BigDecimal.valueOf(price);	
	}	
	
	public Product(String name) {	
		this.name = name;
		this.price = BigDecimal.ZERO;
	}	
}

```

### Define Immutability

Immutable objects present read-only data. (You cannot modify it after object construction)
NOTE: If one variable is defined as ***final*** the constructor won't allow a setter method to it.


### Enumerations


- Enum values are instances of this enum type.
- Enum values are implicitly public, static, and final.
- Enums can be used as : Variables types | value and Cases in the Switch constructs

NOTE: Enum values are not implicitly protected
NOTE2: Provides a fixed set of instances of a specific type

```
package <package name>;

public enum <enum name> {
   
   <VALUE1>, 
   <VALUE2>,
   <VALUE3>;
  
}

```

e.g.

```
package demos;
public enum Condition {
	HOT, WARM, COLD;
}

```
```
package demos;
public enum Condition {
	HOT("Warning HOT"), 
	WARM("Just right"), 
	COLD("Warning COLD!");	
	private String caution;
	private Condition(String condition) {	
		this.caution = caution;
	}
	public String getCaution() {
		return caution;
	}
	
}

```

### Java Memory Allocation

Java has the following memory contexts: stack and heap.

- Stack is a memory context of a thread, storing local method variables.
- Heap is a shared memory area, accessible from different methods and thread contexts.
- Stack can hold only primitives and object references
- Class and objects are stored in the heap

NOTE: Each thread has it own stack.
e.g.
```
public class Shop {
 public static void main(String[] args) {
  
  // stack
  int x = 10;
  
  // "Product p" is allocated on stack and "new Product" on heap
  Product p = new Product 
 }

}

```


### Java Memory Cleanup

Objects remain in the heap, so long as they are still referenced.

- An object reference is **null** until it is initialized.
- Assigning **null** does not destroy the object, just indicated the absence of reference.
- When a method returns, its local variables go out of scope and their values are destroyed.


Garbage collection is a background process that cleans unused memory within Java run time.
- Garbage collection is deferred.
- Object becomes eligible for garbage collection when there are no references pointing to it.

NOTE: Once an object becomes eligible does not mean that gonna be cleaned immediately


##    Chapter 6 - inheritance

the explicit **extends** clause describes which specific class should be extended instead of the Object class.

e.g.

```
public class Product extends Object {

}

```
### Object class

Contains generic behavior that are inherited by all Java classes, such as :

- ToString: method that creates text value for the object
- equals: method that compares a pair of objects.
- hashCode: method that generates int hash value for the object.
- clone: method that produces a replica of the object

NOTE: Only the methods toString(), hashCode() and wait() are public on Object super class.
NOTE2: **wait**, **notify**, and **notifyAll** methods control threads.

### Define Final Classes and Methods

The final keyword can be used to limit class extensibility
- Class cannot extend a class that is marked with the **final** keyword.
- The subclass cannot override a superclass method that is marked with the **final** keyword.

e.g.

```
public class Product {
	public final void processPayment() {
		// method can not be overridden by subclass
	}	
	
public final class Food extends Product {
	// class can not be extended
}	

```

##    Chapter 7 - Interfaces


An interface defines a set of features that can be applied to various other classes

NOTE: By default with absence of access modified all items are public and abstract (without body) 
NOTE: A class must override **default interface method** only if it conflicts with another default method.
NOTE: Interfaces can contain concrete methods but only if they are private, default or static
NOTE: A default method can be defined only in an interface.
NOTE: Interfaces solve the multiple inheritance problem.
NOTE: A class can implement as many interfaces as required
NOTE: An interface works with the instanceof operator.
NOTE: Both interface and class references can be cast to either type

```
public interface <InterfaceName> {
	<constants>
	<abstract methods>
	<default methods>
	<private methods>
	<static methods>

}
```
e.g.
```
public interface Perishable {
	public static final Period MAX_PERIOD = Period.ofDays(5);
	void perish();
	boolean isPerished();
	
	public default boolean verifyPeriod(Period p) {
		return comparePeriod(p) < 0;
	}
	
	private int comparePeriod(Period p) {
		return p.getDays() - MAX_PERIOD.getDays();		
	}
	
	public static int getMaxPeriodDays() {
		return MAX_PERIOD.getDays();
	}
}
```

### Functional Interfaces

- Functional interface is an interface that defines a single abstract operation(Function)

e.g.
```
public interface Perishable {
	void perish();	
}
```
### Generics

- It allows variables and methods to operate on objects of various types while providing compile-time safety.


e.g.

Without Generics
```
public class Some {
	private Object value;
	
	public Object getValue(){
		return value;
	}	
	public void setValue (Object value) {	
		this.value = value
	}	
}
```

With Generics
```
public class Some<T> {
	private T value;
	
	public T getValue(){
		return value;
	}	
	public void setValue (T value) {	
		this.value = value
	}	
}
```

NOTE: Other markers can be used: T (type), V (value), K (key), and any other marker you like, which could be a word or even a single letter.
NOTE: Generics allow resolving specific type during compilation



##    Chapter 8 - Arrays and Loops

### Arrays

An array in a fixed-length collection of elements of the same type indexed by int.
NOTE: An array of object references is filled with null values.
NOTE: An array of primitive values is filled with 0 values (false values if it is of boolean type)
NOTE: Java arrays Cannot be resized

e.g.
```
int[] primes; // or  int primes[];
Product[] products; // or Product products[];

// initialization
primes = new int[4]; 
products = new Product[3];

// adding values

primes[1] = 3;
products[0] = new Food("Cake")

```

### Loops

Contain the following parts: 
- Declaration of the iterator
- Termination condition
- iterator (typically increment or decrement)
- Loop body

NOTE: the difference between **while** and **do-while** is small, if the condition on while false immediately we never enter the loop body. Otherwise the **do-while** runs because the condition is checked before the logic runs.

e.g.
```
int i = 0

while(i < 10) { 
 	//interative logic
 	i++
}
```
```
int i = 0
do { 
 	//interative logic
 	i++
} while(i < 10)

```
```

for (int i = 0; i < 10; i ++){
//interative logic
}

```


### Processing arrays by Using loops

e.g.
```
int[] values = {1,2,3};
StringBuilder txt = new StringBuilder();

for(int i = 0; i < values.length; i++) {

	int value = values[i];
	txt.append(value);
}

for (int value: values) {
	txt.append(value);
}

```

### Complex for loops

The positional nature of a for makes it possible to:
-  define multiple iterators separated by ","
- Write a loop without a body if its **iterator** section also contains required actions;

e.g.
```
int[] values = {1,2,3,4,5,6,7,8,9}; 
int sum = 0;

for(int i = 0; i < values.length; sum+= i++);

```
```
int[][] matrix = {{1,2,3},{4,5,6},{7,8,9}}; 

for(int i = 0, j = 2; !(i == 3 || j== -1); i++, j--){
	int value = matrix[i][j]
}
```


### Break and Continue

Breaking out of loops and skipping loop cycles:

- continue: operator skips the current loop cycle.
- continue <label> skips the labeled loop cycle.
- break terminates the current loop.
- break <label> terminates the labeled loop.

e.g.
```
char[][] matrix = {{'A','B','C','D','E'},
				   {'F','G','H','I','J'},
				   {'L','M','N','O','P'},
				   {'Q','R','S','T','U'},
				   {'V','W','X','Y','Z'}};

StringBuilder txt = StringBuilder();
outerLoopLabel:
for(char[] row : matrix) {
  for(char value: row) { 
	if(value == 'C') { continue; }
	if(value == 'H') { continue outerLoopLabel; }
	if(value == 'N') { break; }
	if(value == 'S') { break outerLoopLabel; }
	txt.append(value);	
  }
  txt.append('\n');
}
```


##    Chapter 9 - Collections

Collection API interfaces:

- Iterable<T> is a top-level interface that allows any collection to be used in a forEach loop.
- Collection<E> interface extends **Iterable** and describes generic collection capabilities, such as adding and removing elements.
- List<E> interface extends **Collection** and describes a list of elements indexed by int.
- Set<E> interface extends **Collection** and describes a set unique elements.
- SortedSet<E> interface extends **Set** to add ordering ability.
- Deque<E> interface extends **Collection** and describes a double-ended queue, providing FIFO and LIFO behaviors.
- Map<K,V> interface contains a **Set** of unique keys and a **Collection** of values.

Collection API classes:

- ArrayList<E> implements **List** interface.
- HashSet<E> implements **Set** 
- TreeSet<E> implements **SortedSet**.
- ArrayDeque<E> implements **Deque** interface.
- HashMap<K,V> implements **Map** interface.

NOTE: You can not use primitives with Collections API you must use objects.
NOTE: **Vector** and **Hashtable** collections legacy classes are thread-safe (syncronized)

### Prevent Collections Corruption

- Unmodifiable(fast, but read-only)

e.g.

```
Set<Product> readOnlySet = Collections.unmodifiableSet(set);
```

- Synchronized(slow and unscalable) 

e.g.

```
Map<Product, Integer> syncMap = Collections.synchronizedMap(map);
```

- Copy-on-write (fast, but consumes memory)

e.g.

```
List<Product> copyOnWriteList = new CopyOnWriteArrayList<>(list);
```

### List Object

- No-arg constructor, creating a list of initial capacity of 10 elements.
- Constructor with specific initial capacity.
- Any other **Collection** to populate this list with initial values.
- A Fixed-sized **List** can be created using var-arg method **Arrays.asList(<T> ...)**
- A read-only instance of **List** can be created using var-arg method **List.of(<T> ...)**
- ArrayList will auto-expand its internal storage, when more elements are added to it.

NOTE: **List** do not allow jump index positions if it does not exist.

e.g.

```
Product p1 = new Food("Cake");
Product p2 = new Drink("Tea");
Set<Product> set1 = new HashSet<>();
set1.add(p1);
set1.add(p2);

List<Product> list1 = new ArraList<>();
List<Product> list2 = new ArraList<>(20);
List<Product> list3 = new ArraList<>(set1);
List<Product> list4 = Arrays.asList(p1,p2);
List<Product> list5 = List.of(p1,p2);

```

### Set Object

- No-arg constructor, creating a list of initial capacity of 16 elements.
- Constructor with specific initial capacity.
- Constructor with specific initial capacity and load factor (default is 0.75)
- Any other **Collection** to populate this list with initial values.
- HashSet will auto-expand its internal storage, when more elements are added to it.
- A read-only instance of **Set** can be created using var-arg method **Set.of(<T> ...)**

NOTE: The load factor is responsible to measure of how full the hash table is allowed to get before its capacity is automatically increased.

e.g.

```
Product p1 = new Food("Cake");
Product p2 = new Drink("Tea");
List<Product> list = new ArraList<>();
list.add(p1);
list.add(p2);

Set<Product> productSet = new HashSet<>();
Set<Product> productSet1 = new HashSet<>(20);
Set<Product> productSet2 = new HashSet<>(20, 0.85);
Set<Product> productSet3 = new HashSet<>(list);
Set<Product> productSet4 = Set.of(p1,p2);

```

### Deque Object

NOTE: You can not offerLast or OfferFirst a **null** value, it's not allowed.
NOTE: peekFirst get the element without remove it.
NOTE: pollFirst or PollLast will get and remove the element from Deque.

---

#    Quiz

## 1. Introduction to Java

**A. Java uses ____ to structure the code, and ____ for individual instances.**

**Answer:**
- classes, objects

**B. Source code is saved in ____ files, and code is compiled into ____ files.**

**Answer:**
- .java, .class

**C. Which statements are true about Java? (Choose two)**

**Answer:**
- Java is an object-oriented programming language.
- Java source code is plain text.

**D. Which is an invalid variable name?**

**Answer:**
- 4ScoreAnd8Years

---

## 2. Primitive Types, Operators, and Flow Control Statements

**A. Why would you use the ternary operator ?: instead of writing an if/else construct?**

**Answer:**
- If you only need to assign a value based on a condition

**B. Which is the correct way to declare and initialize a variable?**

**Answer:**
- boolean x = 4>5;

**C. What is the correct evaluation of this expression: 8*8/2+2-3*2?**

**Answer:**
- 28;

**D. Examine the following code:**
```
int x = 1, y = 1, z = 0; 
if (x == y | x < ++y) { 
	z = x+y; 
}
else{
	z = 1;
}
System.out.println(z);
```
What would be printed? 

**Answer:**
- 3

**E. Which is not a Java primitive type?**

**Answer:**
- String

---

## 3. Text, Date, Time, and Numeric Objects

**A. Which statement is not true about Strings in Java?**

**Answer:**
- Strings allow you to append text.

**B. What must you use to apply object-oriented capabilities to primitives?**

**Answer:**
- Wrapper classes.

**C. Which statements are true about StringBuilder? (Choose three)**

**Answer:**
- StringBuilder objects are mutable.
- You can instantiate a StringBuilder with a predefined content or capacity.
- StringBuilder objects automatically expand capacity as needed.

**D. Which statement is NOT true about Formatter classes?**

**Answer:**
- They work with only objects, but not primitives.

---

## 4. Classes and Objects

**A. Which statements are true about a Class diagram? (Choose two).**

**Answer:**
- It documents access modifiers.
- It shows how one class is related to another.

**B. Which statements are true about methods? (Choose two)**

**Answer:**
- Methods may describe a comma-separated list of parameters.
- Method body is enclosed with "{" and "}" symbols.

**C. Which statement is true?**

**Answer:**
- An object must be an instance of a specific class.

**D. What is an object reference?**

**Answer:**
- A typed variable that points to an object's location in memory

**E. Which UML diagrams are used to model program flow of control? (Choose two)**

**Answer:**
- Sequence diagram
- Activity diagram

---

## 5. Improved Class Design

**A. Which two statements are true about enum?**

**Answer:**
- Enum values are instances of this enum type.
- It provides a fixed set of instances of a specific type.

**B. Which statements are true? (Choose two)**

**Answer:**
- Objects are allocated in the heap.
- Each thread has its own stack.

**C. Which statements are true about a constructor method? (Choose two)**

**Answer:**
- It is a special method that initializes the object.
- It must be named after the class.

**D. Which are rules for method overloading? (Choose two)**

**Answer:**
- Must have a different number or types of parameters, or both
- Must have the same return type


**E. Information contained within an object should normally be "hidden" inside it. What is this called?**

**Answer:**
- Encapsulation

---

## 6. Inheritance

**A.  Examine the following code:**
```
public void order(Product product) {
	if ( /* condition */ ) {
		LocalDate bestBefore = ((Food)product).getBestBefore();
	}
}
```
Which IF condition should be used to verify the object type before casting the reference?

**Answer:**
- (product instanceof Food)

**B. Which are public methods of the Object class? (Choose three)**

**Answer:**
- wait()
- hashCode()
- toString()

**C. Which is NOT a rule of reference type casting?**

**Answer:**
- Casting is possible between objects of sibling types

**D. Which statements are true? (Choose two)**

**Answer:**
- The Object class is the ultimate parent of any other class in Java.
- The Object class defines common, generic operations that all other Java classes inherit and reuse.

**E. Which statements are true about the abstract keyword? (Choose two)**

**Answer:**
- The Abstract class cannot be directly instantiated.
- Concrete subclasses must override all abstract methods of their abstract parent.

---

## 7. Interfaces

**A. Which statements are true? (Choose three)**

**Answer:**
- Interfaces help solve the multiple inheritance problem
- A class can implement as many interfaces as required.
- A default method can be defined only in an interface.

**B. Which statements are true? (Choose two)**

**Answer:**
- An interface works with the instanceof operator.
- Both interface and class references can be cast to either type.

**C. What is an interface that defines a single abstract operation called?**

**Answer:**
- Functional

**D. Interfaces can contain concrete methods, but only if they are ___. (Choose three)**

**Answer:**
- Private
- Static
- Default

**E. Which action do Generics allow?**

**Answer:**
- Resolving specific type during compilation

---

## 8. Arrays and Loops

**A. When processing an array in a loop, use array ____ to determine the boundary for the termination condition:**

**Answer:**
- length

**B. Which statements are true about an array? (Choose four)**

**Answer:**
- Is an object itself
- An array of primitive values is filled with 0 values (false values if it is of boolean type).
- It is a fixed-length collection of elements of the same type indexed by int.
- After an array is created, its length cannot be changed.

**C. Examine the following code:**
```
String[] names = {"Mary","Jane","Ann","Tom"}; 
Arrays.sort(names);
int x = Arrays.binarySearch(names,"Ann");
System.out.println(x);
```
What is the value of x?

**Answer:**
- 0

**D. When breaking out of loops and skipping loop cycles, ____ skips the current loop and ____ terminates the current loop.**

**Answer:**
- continue, break

**E. Examine the following code:**
```
String[] names = {"Mary","Jane","Ann","Tom"}; 
Arrays.sort(names);
int x = Arrays.binarySearch(names,"Ann");
System.out.println(x);
```

What will be the output?

**Answer:**
- Elizabeth Mary Jane Jo

---

## 9. Collections

**A. Examine the following code:**
```
Map<Integer, String> items = new HashMap<>();
items.put(Integer.valueOf(1),"Tea"); 
items.put(Integer.valueOf(2),"Cake");
```
Which statements are true? (Choose two)

**Answer:**
- items.put(Integer.valueOf(1),"Coffee"); will replace "Tea" with "Coffee"
- items.put(Integer.valueOf(3),"Cake"); will create an additional element with "Cake" as value.


**B. Which statements are NOT true about the Java Collection API? (Choose two)**

**Answer:**
- All Collections provide thread-safe operations
- All Collections are implemented internally by using arrays.


**C. Which statement is true about Set?**

**Answer:**
- Add and Remove methods will return false values when attempting to add a duplicate or remove an absent element.

**D. Examine the following code:**
```
String[] arr = {"Tea","Cake"};
List<String> texts = Arrays.asList(arr);
```
Which statements are true? (Choose two)

**Answer:**
- You can replace Tea with Coffee in texts.
- You can replace Tea with Coffee in arr.


**E. Which statements are true about Deque? (Choose three)**

**Answer:**
- offerFirst(T) and offerLast(T) insert elements at the head and the tail of the deque.
- Implementations of ArrayDeque will auto-expand.
- Null values are not allowed.



