├── .gitignore ├── Chapter_01 ├── Checkpoints_Ch_01.md ├── Exercise_01 │ └── Exercise_01_01.java ├── Exercise_02 │ └── Exercise_01_02.java ├── Exercise_03 │ └── Exercise_01_03.java ├── Exercise_04 │ └── Exercise_01_04.java ├── Exercise_05 │ └── Exercise_01_05.java ├── Exercise_06 │ └── Exercise_01_06.java ├── Exercise_07 │ └── Exercise_01_07.java ├── Exercise_08 │ └── Exercise_01_08.java ├── Exercise_09 │ └── Exercise_01_09.java ├── Exercise_10 │ └── Exercise_01_10.java ├── Exercise_11 │ └── Exercise_01_11.java ├── Exercise_12 │ └── Exercise_01_12.java └── Exercise_13 │ └── Exercise_01_13.java ├── Chapter_02 ├── Checkpoints_Ch_02.md ├── Exercise_01 │ └── Exercise_02_01.java ├── Exercise_02 │ └── Exercise_02_02.java ├── Exercise_03 │ └── Exercise_02_03.java ├── Exercise_04 │ └── Exercise_02_04.java ├── Exercise_05 │ └── Exercise_02_05.java ├── Exercise_06 │ └── Exercise_02_06.java ├── Exercise_07 │ └── Exercise_02_07.java ├── Exercise_08 │ └── Exercise_02_08.java ├── Exercise_09 │ └── Exercise_02_09.java ├── Exercise_10 │ └── Exercise_02_10.java ├── Exercise_11 │ └── Exercise_02_11.java ├── Exercise_12 │ └── Exercise_02_12.java ├── Exercise_13 │ └── Exercise_02_13.java ├── Exercise_14 │ └── Exercise_02_14.java ├── Exercise_15 │ └── Exercise_02_15.java ├── Exercise_16 │ └── Exercise_02_16.java ├── Exercise_17 │ └── Exercise_02_17.java ├── Exercise_18 │ └── Exercise_02_18.java ├── Exercise_19 │ └── Exercise_02_19.java ├── Exercise_20 │ └── Exercise_02_20.java ├── Exercise_21 │ └── Exercise_02_21.java ├── Exercise_22 │ └── Exercise_02_22.java └── Exercise_23 │ └── Exercise_02_23.java ├── Chapter_03 ├── Checkpoints_Ch_03.md ├── Exercise_01 │ └── Exercise_03_01.java ├── Exercise_02 │ └── Exercise_03_02.java ├── Exercise_03 │ └── Exercise_03_03.java ├── Exercise_04 │ └── Exercise_03_04.java ├── Exercise_05 │ └── Exercise_03_05.java ├── Exercise_06 │ └── Exercise_03_06.java ├── Exercise_07 │ └── Exercise_03_07.java ├── Exercise_08 │ └── Exercise_03_08.java ├── Exercise_09 │ └── Exercise_03_09.java ├── Exercise_10 │ └── Exercise_10_10.java ├── Exercise_11 │ └── Exercise_03_11.java └── Resources │ ├── check_point_03_08.png │ ├── check_point_03_31.svg │ ├── checkpoint_03_31.png │ ├── flowchart_checkpoint_03_08.activity.violet.html │ └── flowchart_checpoint_03_31.activity.violet.html ├── Chapter_04 ├── Checkpoints_Ch_04.md ├── Exercise_01 │ └── Exercise_04_01.java ├── Exercise_02 │ └── Exercise_04_02.java └── Exercise_04 │ └── Exercise_04_04.java ├── Chapter_05 ├── Checkpoints_Ch_05.md ├── Exercise_01 │ └── Exercise_05_01.java ├── Exercise_02 │ └── Exercise_05_02.java ├── Exercise_03 │ └── Exercise_05_03.java ├── Exercise_04 │ └── Exercise_05_04.java └── Exercise_05 │ └── Exercise_05_05.java ├── Chapter_06 ├── Checkpoints_Ch_06.md ├── Exercise_01 │ └── Exercise_06_01.java ├── Exercise_02 │ └── Exercise_06_02.java └── Exercise_04 │ └── Exercise_06_04.java ├── Chapter_07 ├── Checkpoints_Ch_07.md ├── Exercise_02 │ └── Exercise_07_02.java ├── Exercise_03 │ └── Exercise_07_03.java └── Exercise_19 │ └── Exercise_07_19.java ├── Chapter_08 ├── Checkpoints_Ch_08.md ├── Exercise_01 │ └── Exercise_08_01.java └── Exercise_02 │ └── Exercise_08_02.java ├── Chapter_09 ├── Checkpoints_Ch_09.md ├── Exercise_01 │ ├── Exercise_09_01.java │ ├── Rectangle.png │ └── Resources │ │ └── exercise_09_01.svg ├── Exercise_02 │ ├── Exercise_09_02.java │ ├── Resources │ │ └── UML_09_02.graphml │ └── UML_09_02.png ├── Exercise_03 │ └── Exercise_09_03.java ├── Exercise_04 │ └── Exercise_09_04.java ├── Exercise_05 │ └── Exercise_09_05.java ├── Exercise_06 │ ├── Exercise_09_06.java │ ├── Resources │ │ └── exercise_09_06.svg │ └── StopWatch.png └── Exercise_08 │ ├── UML_09_08.png │ └── resources │ └── UML_09_08.graphml ├── Chapter_10 ├── Checkpoints_Ch_10.md └── Exercise_01 │ └── BMI.java ├── Chapter_11 └── Check_Points_Ch11.md ├── Chapter_12 ├── Checkpoints_Ch_12.md └── Exercise_02 │ └── Exercise_12_02.java ├── Chapter_13 ├── Checkpoints_Ch_13.md └── Exercise_02 │ └── Exercise_13_02.java ├── Chapter_14 ├── Checkpoints_Ch_14.md └── Exercise_02 │ ├── Exercise_14_02.java │ └── res │ ├── o.gif │ └── x.gif ├── Chapter_15 ├── Checkpoints_Ch_15.md └── Exercise_02 │ └── Exercise_15_02.java ├── Chapter_16 └── Checkpoints_Ch_16.md ├── Chapter_17 └── Checkpoints_Ch_17.md ├── Chapter_18 └── Checkpoints_Ch_18.md ├── Chapter_19 └── Checkpoints_Ch_19.md ├── Chapter_20 └── Checkpoints_Ch_20.md ├── Chapter_21 └── Checkpoints_Ch_21.md ├── Chapter_22 └── Checkpoint_Ch_22.md ├── Chapter_23 └── Checkpoint_Ch_23.md ├── Chapter_24 └── Checkpoint_Ch_24.md ├── Chapter_25 └── Checkpoint_Ch_25.md ├── Chapter_26 └── Checkpoint_Ch_26.md ├── LICENSE └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | *.class 2 | 3 | # Mobile Tools for Java (J2ME) 4 | .mtj.tmp/ 5 | 6 | # Package Files # 7 | *.jar 8 | *.war 9 | *.ear 10 | 11 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 12 | hs_err_pid* 13 | The book/ 14 | -------------------------------------------------------------------------------- /Chapter_01/Checkpoints_Ch_01.md: -------------------------------------------------------------------------------- 1 | # Checkpoint Answers Chapter 1 # 2 | ## 1.1 ## 3 | A computer is said to be made up of hardware and software. 4 | 5 | Hardware are the different devices either installed in or connected to the computer. For example the drives, screen, keyboard, and motherboard. 6 | 7 | Software is a set of instructions that are interpreted and executed by the hardware. 8 | 9 | ## 1.2 ## 10 | Five major computer hardware components are 11 | 1. Processor 12 | 2. Memory 13 | 3. Hard drive 14 | 4. Screen 15 | 5. Keyboard 16 | 17 | ## 1.3 ## 18 | CPU stands for Central Processing Unit. 19 | 20 | ## 1.4 ## 21 | One unit used when measuring CPU speed is Hertz. 22 | 23 | ## 1.5 ## 24 | A bit is the basic unit of information in computing. A bit can only have one of two values. These values are commonly represented as 0 or 1. 25 | 26 | A byte is a unit of information in computing that most commonly consists of eight bits. 27 | 28 | ## 1.6 ## 29 | Memory is special hardware used for holding information while executing a software. RAM stands for Random Access Memory. The name RAM indicates that any part of the memory can be read and written in roughly the same amount of time. 30 | 31 | ## 1.7 ## 32 | Memory size is, at the time of writing, often measured in gigabyte (GB). 33 | 34 | ## 1.8 ## 35 | The unit to measure disk size is, at the time of writing, often measured in gigabyte (GB) or terabyte (TB). 36 | 37 | ## 1.9 ## 38 | The difference between memory and a storage device is usually that a memory will lose its content if the computer is powered off as opposed to a storage device where the memory is more or less permanent. 39 | 40 | ## 1.10 ## 41 | A CPU only understand instructions written in machine language. Each CPU family uses its own version of the machine language. 42 | ## 1.11 ## 43 | Assembly language is a low-level programming language in which there is a very strong correspondence between the language and the architecture's machine code. 44 | 45 | ## 1.12 ## 46 | An assembler translates assembly-language instructions into machine code. 47 | 48 | ## 1.13 ## 49 | The main difference between a high-level language and a low level language is that the former is platform independent and written in a more human friendly way. 50 | 51 | ## 1.14 ## 52 | A source program is a program written in a high-level language that needs further transformation before the computer can use it. 53 | 54 | ## 1.15 ## 55 | An interpreter translates small parts of source code, more or less line by line, into machine code that then are executed by the computer directly. 56 | 57 | ## 1.16 ## 58 | A compiler takes one or more files with high level source code and builds a machine language program that is stored in a file. This machine code file is then used at a later stage when the program shall run. 59 | 60 | ## 1.17 ## 61 | The difference between a compiler and interpreter is that an interpreter works with translation of source code to machine code in real time while the program is running. An compiler will be finished with the entire translation before the program runs. 62 | 63 | ## 1.18 ## 64 | An operating system (OS) is software that manages computer hardware and software resources and provides common services for computer programs. The operating system is an essential component of the system software in a computer system. Application programs usually require an operating system to function. 65 | 66 | Some currently popular operating systems are Windows, Linux, and Android. 67 | 68 | ## 1.19 ## 69 | An operating system is responsible for handling of input/output devices such as keyboard mouse and screen. An operating system will also often make it possible to run several programs at once by letting each program use the CPU in short intervals and giving each application some memory that the application is allowed to read and write. An operating system is often also responsible for security, preventing unauthorized access to the system. 70 | 71 | ## 1.20 ## 72 | Multiprogramming allows multiple programs to run simultaneously by sharing the same CPU. 73 | 74 | Multithreading allows a single program to execute multiple tasks at the same time. In a game so can for example one task be responsible for playing sounds. While another task updates the graphics. 75 | 76 | Multiprocessing, or parallel processing, uses two or more processors together to perform subtasks concurrently and then combine solutions of the subtasks to obtain a solution for the entire task. 77 | 78 | ## 1.21 ## 79 | Initial development of Java was done at Sun Microsystems and the work was lead by James Gosling. 80 | 81 | Java is currently owned and developed by a company called Oracle. 82 | 83 | ## 1.22 ## 84 | A Java applet is a small application which is written in Java and delivered to the users over the Web. The user launches the Java applet from a web page, and the applet is then executed within in a process separate from the web browser itself. 85 | 86 | ## 1.23 ## 87 | Java is often used when developing Android applications. 88 | 89 | ## 1.24 ## 90 | The Java language specification is a technical definition of the Java programming language’s syntax and semantics. 91 | 92 | ## 1.25 ## 93 | JDK is an acronym for Java Development toolKit. 94 | 95 | ## 1.26 ## 96 | IDE is an acronym for Integrated Development Environment. 97 | 98 | ## 1.27 ## 99 | NetBeans and Eclipse are two different integrated development environments that can be helpful when developing Java programs. 100 | ## 1.28 ## 101 | A keyword is a word that has special meaning to the compiler and can hence not be used for other purposes. 102 | 103 | Example of keywords are: 104 | - class 105 | - public 106 | - static 107 | - void 108 | 109 | ## 1.29 ## 110 | Java is case sensitive. 111 | 112 | All keywords are written in lower case. 113 | 114 | ## 1.30 ## 115 | A comment is text in the source code intended for the human developers to document and explain the code. 116 | 117 | The compiler will ignore all comments. 118 | 119 | A comment line is started by writing two slashes and will then continue until the end of the line. 120 | 121 | I paragraph comment can span over multiple lines. This type of comment starts with a slash followed by an asterisk and ends with an asterisk followed by a slash. 122 | 123 | ## 1.31 ## 124 | The following statement will display a string on the console: 125 | ```java 126 | System.out.println("A string that will appear on the console."); 127 | ``` 128 | ## 1.32 ## 129 | The output of the following code 130 | ```java 131 | public class Test { 132 | public static void main(String[] args) { 133 | System.out.println("3.5 * 4 / 2 - 2.5 is "); 134 | System.out.println(3.5 * 4 / 2 - 2.5); 135 | } 136 | } 137 | ``` 138 | will be 139 | ``` 140 | 3.5 * 4 / 2 - 2.5 is 141 | 4.5 142 | ``` 143 | 144 | ## 1.33 ## 145 | The Java source file-name extension is ".java". 146 | 147 | The Java bytecode file-name extension is ".class". 148 | 149 | ## 1.34 ## 150 | The input to a Java compiler is a source file that shall have the ".java" extension. 151 | 152 | The output of a Java compiler is a bytecode file that will have a ".class" extension. 153 | 154 | ## 1.35 ## 155 | The command used to compile a Java program in the console is "javac" followed by the name of the source file. 156 | 157 | ## 1.36 ## 158 | The command used to run a Java program in the console is "java" followed byte the name of bytecode file. Note that the ".class" extension shall not be included in the command. 159 | 160 | ## 1.37 ## 161 | JVM stands for Java Virtual Machine. This is a program that can translate bytecode into machine code and in this way run a Java program. 162 | 163 | ## 1.38 ## 164 | Java can not be run on any machine. 165 | 166 | There must be a JVM installed on a machine if a Java program shall be able to run. 167 | 168 | ## 1.39 ## 169 | A NoClassDefFoundError indicates a class file that does not exist. 170 | 171 | ## 1.40 ## 172 | A NoSuchMethodError can be a indication that the class to be executed does not have a proper main method. 173 | 174 | ## 1.41 ## 175 | The following code need to be reformatted according to the programming style and documentation guidelines. 176 | ```Java 177 | public class Test { 178 | // Main method 179 | public static void main(String[] args) 180 | { 181 | /** Display output */ 182 | System.out.println("Welcome to Java"); 183 | } 184 | } 185 | ``` 186 | 187 | The code is simple enough to read without the comments so these comments, that just crowd the code, can be removed. 188 | 189 | Lets also change to end-of-line style block braces throughout the entire code for consistency and because this is the style used in the Java API source code. 190 | 191 | The result after changes will be: 192 | ```Java 193 | public class Test { 194 | public static void main(String[] args) { 195 | System.out.println("Welcome to Java"); 196 | } 197 | } 198 | ``` 199 | 200 | ## 1.42 ## 201 | A syntax error is introduced when writing some code that does not follow the Java syntax rules. 202 | 203 | A runtime error will occur during program execution causing the program to terminate in an uncontrolled way because of some unforeseen event. 204 | 205 | I program with a logical error will compile and run but, does not behave as is should during execution. 206 | 207 | ## 1.43 ## 208 | Examples of syntax errors are misspelling of keywords, missing a terminating brace, or not ending a statement with a semicolon. 209 | 210 | Examples of runtime errors are not being able to handle incorrect user input. For example if a number is expected and the user writes "five" instead of 5. Or the user enters 0 and we use this to divide later on. 211 | 212 | Examples of logical errors are using the wrong formula for calculating something. Or not having full understanding of how some language feature actually works. 213 | 214 | ## 1.44 ## 215 | Forgetting to put a closing quotation mark on a string will raise a syntax error when compiling the code. 216 | 217 | ## 1.45 ## 218 | A program that needs to read integer, but the user enter strings will raise an runtime error, assuming we have not included special code to handle this situation. 219 | 220 | ## 1.46 ## 221 | Mistakenly using the wrong code, like calculating the area of a triangle instead of the area of a rectangle, introduces a logical error. 222 | 223 | ## 1.47 ## 224 | The following code have errors multiple errors: 225 | ```Java 226 | public class Welcome { 227 | public void Main(String[] args) { 228 | System.out.println('Welcome to Java!); 229 | } 230 | } 231 | ``` 232 | Lets fix the code. 233 | 234 | The name of the method "Main" is misspelled, should be "main". 235 | 236 | The keyword static is missing. 237 | 238 | The string in the print statement have a single apostrophe when there should be two quotation marks surrounding the string. 239 | 240 | A fully corrected version looks like this: 241 | ```Java 242 | public class Welcome { 243 | public static void main(String[] args) { 244 | System.out.println("Welcome to Java!"); 245 | } 246 | } 247 | ``` 248 | -------------------------------------------------------------------------------- /Chapter_01/Exercise_01/Exercise_01_01.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Exercise 1.1 from the book Introduction to Java Programming (10th). 3 | *

4 | * Write a program that displays "Welcome to Java", 5 | * "Welcome to Computer Science", and "Programming is fun". 6 | * 7 | * @author Henrik Samuelsson, henrik.samuelsson(at)gmail.com 8 | */ 9 | public class Exercise_01_01 { 10 | 11 | public static void main(String[] args) { 12 | System.out.println("Welcome to Java"); 13 | System.out.println("Welcome to Computer Science"); 14 | System.out.println("Programming is fun"); 15 | } 16 | 17 | } 18 | -------------------------------------------------------------------------------- /Chapter_01/Exercise_02/Exercise_01_02.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Exercise 1.2 from the book Introduction to Java Programming (10th). 3 | *

4 | * Exercise instructions:
5 | * Write a program that displays "Welcome to Java" five times. 6 | * 7 | * @author Henrik Samuelsson, henrik.samuelsson(at)gmail.com 8 | */ 9 | public class Exercise_01_02 { 10 | 11 | public static void main(String[] args) { 12 | System.out.println("Welcome to Java"); 13 | System.out.println("Welcome to Java"); 14 | System.out.println("Welcome to Java"); 15 | System.out.println("Welcome to Java"); 16 | System.out.println("Welcome to Java"); 17 | } 18 | 19 | } 20 | -------------------------------------------------------------------------------- /Chapter_01/Exercise_03/Exercise_01_03.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Exercise 1.3 from the book Introduction to Java Programming (10th). 3 | *

4 | * Write a program that displays the following pattern: 5 | * 6 | * J A V V A 7 | * J A A V V A A 8 | * J J AAAAA V V AAAAA 9 | * J J A A V A A 10 | * 11 | * @author Henrik Samuelsson, henrik.samuelsson(at)gmail.com 12 | */ 13 | 14 | public class Exercise_01_03 { 15 | 16 | public static void main(String[] args) { 17 | System.out.println(" J A V V A "); 18 | System.out.println(" J A A V V A A "); 19 | System.out.println("J J AAAAA V V AAAAA "); 20 | System.out.println(" J J A A V A A"); 21 | } 22 | 23 | } 24 | -------------------------------------------------------------------------------- /Chapter_01/Exercise_04/Exercise_01_04.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Exercise 1.4 from the book Introduction to Java Programming (10th). 3 | *

4 | * A quick and dirty solution to this exercise. 5 | * 6 | * @author Henrik Samuelsson, henrik.samuelsson(at)gmail.com 7 | */ 8 | 9 | public class Exercise_01_04 { 10 | 11 | public static void main(String[] args) { 12 | System.out.println("a\ta^2\ta^3"); 13 | System.out.println("1\t1\t1"); 14 | System.out.println("2\t4\t8"); 15 | System.out.println("3\t9\t27"); 16 | System.out.println("4\t16\t64"); 17 | } 18 | 19 | } 20 | -------------------------------------------------------------------------------- /Chapter_01/Exercise_05/Exercise_01_05.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Exercise 1.5 from the book Introduction to Java Programming (10th). 3 | * 4 | * @author Henrik Samuelsson, henrik.samuelsson(at)gmail.com 5 | */ 6 | public class Exercise_01_05 { 7 | 8 | public static void main(String[] args) { 9 | System.out.println( ( 9.5 * 4.5 - 2.5 * 3 ) / ( 45.5 - 3.5 ) ); 10 | } 11 | 12 | } 13 | -------------------------------------------------------------------------------- /Chapter_01/Exercise_06/Exercise_01_06.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Exercise 1.6 from the book Introduction to Java Programming (10th). 3 | * 4 | * @author Henrik Samuelsson, henrik.samuelsson(at)gmail.com 5 | */ 6 | 7 | public class Exercise_01_06 { 8 | 9 | public static void main(String[] args) { 10 | System.out.println( 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 ); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /Chapter_01/Exercise_07/Exercise_01_07.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Exercise 1.7 from the book Introduction to Java Programming (10th). 3 | *

4 | * Approximate calculation of pi. 5 | * 6 | * @author Henrik Samuelsson, henrik.samuelsson(at)gmail.com 7 | */ 8 | 9 | public class Exercise_01_07 { 10 | 11 | public static void main(String[] args) { 12 | System.out.println( 4.0 * ( 1.0 - 1.0 / 3.0 + 1.0 / 5.0 - 1.0 / 7.0 + 13 | 1.0 / 9.0 - 1.0 / 11.0 ) ); 14 | System.out.println( 4.0 * ( 1.0 - 1.0 / 3.0 + 1.0 / 5.0 - 1.0 / 7.0 + 15 | 1.0 / 9.0 - 1.0 / 11.0 + 1.0 / 13.0) ); 16 | } 17 | 18 | } 19 | -------------------------------------------------------------------------------- /Chapter_01/Exercise_08/Exercise_01_08.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Exercise 1.8 from the book Introduction to Java Programming (10th). 3 | *

4 | * Write a program that displays the area and perimeter of a circle that has a 5 | * radius of 5.5. 6 | * 7 | * @author Henrik Samuelsson, henrik.samuelsson(at)gmail.com 8 | */ 9 | 10 | public class Exercise_01_08 { 11 | 12 | public static void main(String[] args) { 13 | System.out.println( 2.0 * 5.5 * 3.14 ); 14 | System.out.println( 5.5 * 5.5 * 3.14 ); 15 | } 16 | 17 | } 18 | -------------------------------------------------------------------------------- /Chapter_01/Exercise_09/Exercise_01_09.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Exercise 1.9 from the book Introduction to Java Programming (10th). 3 | *

4 | * Write a program that displays the area and perimeter of a rectangle with 5 | * the width of 4.5 and height of 7.9. 6 | * 7 | * @author Henrik Samuelsson, henrik.samuelsson(at)gmail.com 8 | */ 9 | 10 | public class Exercise_01_09 { 11 | 12 | public static void main(String[] args) { 13 | System.out.println( 4.5 + 7.9 + 4.5 + 7.9 ); // perimeter 14 | System.out.println( 4.5 * 7.9 ); // area 15 | } 16 | 17 | } 18 | -------------------------------------------------------------------------------- /Chapter_01/Exercise_10/Exercise_01_10.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Exercise 1.10 from the book Introduction to Java Programming (10th). 3 | * 4 | * @author Henrik Samuelsson, henrik.samuelsson(at)gmail.com 5 | */ 6 | public class Exercise_01_10 { 7 | 8 | public static void main(String[] args) { 9 | // 14 / 1.6 to convert km to miles 10 | // 45 minutes and 30 seconds equals 45.5 minutes 11 | // 45.5 / 60 to convert minutes to hours 12 | // finally divide miles / hours to get the average speed 13 | System.out.println( ( 14.0 / 1.6 ) / ( 45.5 / 60 ) ); 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /Chapter_01/Exercise_11/Exercise_01_11.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Exercise 1.11 from the book Introduction to Java Programming (10th). 3 | * 4 | * @author Henrik Samuelsson, henrik.samuelsson(at)gmail.com 5 | */ 6 | 7 | public class Exercise_01_11 { 8 | 9 | public static void main(String[] args) { 10 | // 312032486 is the initial population 11 | // 365 * 24 * 60 * 60 is the number of seconds in a year 12 | System.out.println( 312032486 + ( 13 | 365 * 24 * 60 * 60 / 7 // births 14 | - 365 * 24 * 60 * 60 / 13 // deaths 15 | + 365 * 24 * 60 * 60 / 45 // immigrants 16 | ) * 1); // year count 17 | System.out.println( 312032486 + ( 18 | + 365 * 24 * 60 * 60 / 7 // births 19 | - 365 * 24 * 60 * 60 / 13 // deaths 20 | + 365 * 24 * 60 * 60 / 45 // immigrants 21 | ) * 2); // year count 22 | System.out.println( 312032486 + ( 23 | + 365 * 24 * 60 * 60 / 7 // births 24 | - 365 * 24 * 60 * 60 / 13 // deaths 25 | + 365 * 24 * 60 * 60 / 45 // immigrants 26 | ) * 3); // year count 27 | System.out.println( 312032486 + ( 28 | + 365 * 24 * 60 * 60 / 7 // births 29 | - 365 * 24 * 60 * 60 / 13 // deaths 30 | + 365 * 24 * 60 * 60 / 45 // immigrants 31 | ) * 4); // year count 32 | System.out.println( 312032486 + ( 33 | + 365 * 24 * 60 * 60 / 7 // births 34 | - 365 * 24 * 60 * 60 / 13 // deaths 35 | + 365 * 24 * 60 * 60 / 45 // immigrants 36 | ) * 5); // year count 37 | } 38 | 39 | } 40 | -------------------------------------------------------------------------------- /Chapter_01/Exercise_12/Exercise_01_12.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Exercise 1.12 from the book Introduction to Java Programming (10th). 3 | * 4 | * @author Henrik Samuelsson, henrik.samuelsson(at)gmail.com 5 | */ 6 | 7 | public class Exercise_01_12 { 8 | 9 | public static void main(String[] args) { 10 | System.out.println( ( 24.0 / 1.6 ) // distance in km 11 | / ( 1 + 40.0 / 60.0 + 35.0 / 3600.0 ) ); // time in hours 12 | } 13 | 14 | } 15 | -------------------------------------------------------------------------------- /Chapter_01/Exercise_13/Exercise_01_13.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Exercise 1.13 from the book Introduction to Java Programming (10th). 3 | * 4 | * @author Henrik Samuelsson, henrik.samuelsson(at)gmail.com 5 | */ 6 | 7 | public class Exercise_01_13 { 8 | 9 | public static void main(String[] args) { 10 | // a = 3.4, b = 50.2, c = 2.1, d = 0.55, e = 44.5, f = 5.9 11 | 12 | // calculate and print x 13 | System.out.println( ( 44.5 * 0.55 - 50.2 * 5.9 ) 14 | / ( 3.4 * 0.55 - 50.2 * 2.1 ) ); 15 | 16 | // calculate and print y 17 | System.out.println( ( 3.4 * 5.9 - 44.5 * 2.1 ) 18 | / ( 3.4 * 0.55 - 50.2 * 2.1 ) ); 19 | } 20 | 21 | } 22 | -------------------------------------------------------------------------------- /Chapter_02/Exercise_01/Exercise_02_01.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | /** 4 | * Exercise 2.1 from the book Introduction to Java Programming (10th). 5 | * 6 | * @author Henrik Samuelsson, henrik.samuelsson(at)gmail.com 7 | */ 8 | 9 | public class Exercise_02_01 { 10 | 11 | public static void main(String[] args) { 12 | double degreeCelcius; 13 | double degreeFahrenheit; 14 | 15 | Scanner input = new Scanner(System.in); 16 | System.out.print("Enter a degree in Celsius: "); 17 | degreeCelcius = input.nextDouble(); 18 | degreeFahrenheit = (9.0 / 5) * degreeCelcius + 32; 19 | System.out.print(degreeCelcius + " Celcius is " + degreeFahrenheit 20 | + " Fahrenheit"); 21 | } 22 | 23 | } 24 | -------------------------------------------------------------------------------- /Chapter_02/Exercise_02/Exercise_02_02.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | /** 4 | * Exercise 2.2 from the book Introduction to Java Programming (10th). 5 | * 6 | * @author Henrik Samuelsson, henrik.samuelsson(at)gmail.com 7 | */ 8 | 9 | public class Exercise_02_02 { 10 | 11 | public static void main(String[] args) { 12 | double radius; 13 | double length; 14 | double area; 15 | double volume; 16 | 17 | // get input from user 18 | Scanner input = new Scanner(System.in); 19 | System.out.print("Enter the radius and length of a cylinder: "); 20 | radius = input.nextDouble(); 21 | length = input.nextDouble(); 22 | 23 | // calculate area and volume 24 | area = radius * radius * Math.PI; 25 | volume = area * length; 26 | 27 | // present the results 28 | System.out.println("The area is " + area); 29 | System.out.println("The volume is " + volume); 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /Chapter_02/Exercise_03/Exercise_02_03.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | /** 4 | * Exercise 2.3 from the book Introduction to Java Programming (10th). 5 | * 6 | * @author Henrik Samuelsson, henrik.samuelsson(at)gmail.com 7 | */ 8 | 9 | public class Exercise_02_03 { 10 | 11 | public static void main(String[] args) { 12 | double feet; 13 | double meters; 14 | 15 | // get input from user 16 | Scanner input = new Scanner(System.in); 17 | System.out.print("Enter a value for feet: "); 18 | feet = input.nextDouble(); 19 | 20 | // convert feet into meters 21 | meters = feet * 0.305; 22 | 23 | // present the result 24 | System.out.println(feet + " feet is " + meters + " meters."); 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /Chapter_02/Exercise_04/Exercise_02_04.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | /** 4 | * Exercise 2.4 from the book Introduction to Java Programming (10th). 5 | * 6 | * @author Henrik Samuelsson, henrik.samuelsson(at)gmail.com 7 | */ 8 | 9 | public class Exercise_02_04 { 10 | 11 | public static void main(String[] args) { 12 | double pounds; 13 | double kilograms; 14 | 15 | // get input from user 16 | Scanner input = new Scanner(System.in); 17 | System.out.print ("Enter a number in pounds: "); 18 | pounds = input.nextDouble(); 19 | 20 | // convert pounds into kilograms 21 | kilograms = pounds * 0.454; 22 | 23 | // present the result 24 | System.out.println(pounds + " pounds is " + kilograms + " kilograms"); 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /Chapter_02/Exercise_05/Exercise_02_05.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | /** 4 | * Exercise 2.5 from the book Introduction to Java Programming (10th). 5 | * 6 | * @author Henrik Samuelsson, henrik.samuelsson(at)gmail.com 7 | */ 8 | 9 | public class Exercise_02_05 { 10 | 11 | public static void main(String[] args) { 12 | double subtotal; 13 | int subtotalInCents; 14 | int gratuityRate; 15 | int totalInCents; 16 | int gratuityInCents; 17 | 18 | // get input from user 19 | Scanner input = new Scanner(System.in); 20 | System.out.print ("Enter the subtotal and a gratuity rate: "); 21 | subtotal = input.nextDouble(); 22 | gratuityRate = input.nextInt(); 23 | 24 | // calculate gratuity and total in cents 25 | subtotalInCents = (int)(subtotal * 100); 26 | gratuityInCents = (int)(subtotal * gratuityRate); 27 | totalInCents = subtotalInCents + gratuityInCents; 28 | 29 | // present the result in dollars and cents 30 | System.out.println("The gratuity is $" + 31 | gratuityInCents / 100 + "." + gratuityInCents % 100 + 32 | " and total is $" + 33 | totalInCents / 100 + "." + totalInCents % 100); 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /Chapter_02/Exercise_06/Exercise_02_06.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | /** 4 | * Exercise 2.6 from the book Introduction to Java Programming (10th). 5 | * 6 | * @author Henrik Samuelsson, henrik.samuelsson(at)gmail.com 7 | */ 8 | 9 | public class Exercise_02_06 { 10 | 11 | public static void main(String[] args) { 12 | int number; 13 | int sum = 0; 14 | 15 | // get input from user 16 | Scanner input = new Scanner(System.in); 17 | System.out.print ("Enter a number between 0 and 1000: "); 18 | number = input.nextInt(); 19 | 20 | // extract and sum up the digits 21 | sum += number % 10; 22 | number = number / 10; 23 | sum += number % 10; 24 | number = number / 10; 25 | sum += number; 26 | 27 | // present the result 28 | System.out.println("The sum of the digits is " + sum); 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /Chapter_02/Exercise_07/Exercise_02_07.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | /** 4 | * Exercise 2.7 from the book Introduction to Java Programming (10th). 5 | * 6 | * @author Henrik Samuelsson, henrik.samuelsson(at)gmail.com 7 | */ 8 | 9 | public class Exercise_02_07 { 10 | 11 | public static void main(String[] args) { 12 | int minutes; 13 | int days; 14 | int years; 15 | 16 | // get input from user 17 | Scanner input = new Scanner(System.in); 18 | System.out.print ("Enter the number of minutes: "); 19 | minutes = input.nextInt(); 20 | 21 | // the modulo operation will remove the years 22 | // the following division will convert from from minutes to days 23 | days = minutes % (60 * 24 * 365) / (60 * 24); 24 | 25 | // division that will truncate away the days and convert remainder 26 | // from minutes to years 27 | years = minutes / (60 * 24 * 365); 28 | 29 | // present the result 30 | System.out.println(minutes + " minutes is approximately " + years + 31 | " years and " + days + " days" ); 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /Chapter_02/Exercise_08/Exercise_02_08.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | /** 4 | * Exercise 2.8 from the book Introduction to Java Programming (10th). 5 | * 6 | * @author Henrik Samuelsson, henrik.samuelsson(at)gmail.com 7 | */ 8 | 9 | public class Exercise_02_08 { 10 | 11 | public static void main(String[] args) { 12 | // obtain the time zone offset from user 13 | Scanner input = new Scanner(System.in); 14 | System.out.print ("Enter the time zone offset to GMT: "); 15 | long offset = input.nextLong(); 16 | 17 | // obtain the total milliseconds since midnight, Jan 1, 1970 18 | long totalMilliseconds = System.currentTimeMillis(); 19 | 20 | // obtain the total seconds since midnight, Jan 1, 1970 21 | long totalSeconds = totalMilliseconds / 1000; 22 | 23 | // compute the current second in the minute in the hour 24 | long currentSecond = totalSeconds % 60; 25 | 26 | // obtain the total minutes 27 | long totalMinutes = totalSeconds / 60; 28 | 29 | // compute the current minute in the hour 30 | long currentMinute = totalMinutes % 60; 31 | 32 | // obtain the total hours 33 | long totalHours = totalMinutes / 60; 34 | 35 | // compute the current hour 36 | long currentHour = totalHours % 24; 37 | 38 | // adjust the current hour using the offset 39 | currentHour += offset; 40 | 41 | // display results 42 | System.out.println("Current time is " + currentHour + ":" 43 | + currentMinute + ":" + currentSecond); 44 | } 45 | 46 | } 47 | -------------------------------------------------------------------------------- /Chapter_02/Exercise_09/Exercise_02_09.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | /** 4 | * Exercise 2.9 from the book Introduction to Java Programming (10th). 5 | * 6 | * @author Henrik Samuelsson, henrik.samuelsson(at)gmail.com 7 | */ 8 | 9 | public class Exercise_02_09 { 10 | 11 | public static void main(String[] args) { 12 | double v0, v1, t, a; 13 | 14 | // get input from user 15 | Scanner input = new Scanner(System.in); 16 | System.out.print ("Enter v0, v1 and t: "); 17 | v0 = input.nextDouble(); 18 | v1 = input.nextDouble(); 19 | t = input.nextDouble(); 20 | 21 | // calculate average acceleration 22 | a = (v1 - v0) / t; 23 | 24 | // present the result 25 | System.out.println("The average acceleration is " + a); 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /Chapter_02/Exercise_10/Exercise_02_10.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | /** 4 | * Exercise 2.10 from the book Introduction to Java Programming (10th). 5 | * 6 | * @author Henrik Samuelsson, henrik.samuelsson(at)gmail.com 7 | */ 8 | 9 | public class Exercise_02_10 { 10 | 11 | public static void main(String[] args) { 12 | // amount of water 13 | double m; 14 | // initial and final temperature of the water 15 | double t0, t1; 16 | // energy needed to warm 1 kg water 1 degree 17 | final int F = 4184; 18 | // total energy needed to warm the water 19 | double q; 20 | 21 | // get input from user 22 | Scanner input = new Scanner(System.in); 23 | System.out.print ("Enter the amount of water in kilograms: "); 24 | m = input.nextDouble(); 25 | System.out.print ("Enter the initial temperature: "); 26 | t0 = input.nextDouble(); 27 | System.out.print ("Enter the final temperature: "); 28 | t1 = input.nextDouble(); 29 | 30 | // calculate the energy needed to warm the water 31 | q = m * (t1 - t0) * F; 32 | 33 | // present the result 34 | System.out.println("The energy needed is " + q); 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /Chapter_02/Exercise_11/Exercise_02_11.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | /** 4 | * Exercise 2.11 from the book Introduction to Java Programming (10th). 5 | *

6 | * @note Did not get the exact same answer as in the book. This is likely 7 | * because of some rounding error. 8 | * 9 | * @author Henrik Samuelsson, henrik.samuelsson(at)gmail.com 10 | */ 11 | 12 | public class Exercise_02_11 { 13 | 14 | public static void main(String[] args) { 15 | int years, population; 16 | double births, deaths, immigrants; 17 | final int START_POPULATION = 312032486; 18 | final double SECONDS_IN_YEAR = 31536000; 19 | final int BIRTH_FACTOR = 7; 20 | final int DEATH_FACTOR = 13; 21 | final int IMMIGRANT_FACTOR = 45; 22 | 23 | // get input from user 24 | Scanner input = new Scanner(System.in); 25 | System.out.print ("Enter the numbers of years: "); 26 | years = input.nextInt(); 27 | 28 | // do some population calculations based on user input 29 | births = years * SECONDS_IN_YEAR / BIRTH_FACTOR; 30 | deaths = years * SECONDS_IN_YEAR / DEATH_FACTOR; 31 | immigrants = years * SECONDS_IN_YEAR / IMMIGRANT_FACTOR; 32 | population = (int) (START_POPULATION + births - deaths + immigrants); 33 | 34 | // display the population 35 | System.out.println("The population in " + years + " years is " + 36 | population); 37 | } 38 | 39 | } 40 | -------------------------------------------------------------------------------- /Chapter_02/Exercise_12/Exercise_02_12.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.Scanner; 3 | 4 | /** 5 | * Exercise 2.12 from the book Introduction to Java Programming (10th). 6 | * 7 | * @author Henrik Samuelsson, henrik.samuelsson(at)gmail.com 8 | */ 9 | 10 | public class Exercise_02_12 { 11 | 12 | public static void main(String[] args) { 13 | double acceleration, velocity, runwayLength; 14 | 15 | // get input from user 16 | Scanner input = new Scanner(System.in); 17 | System.out.print ("Enter speed and acceleration: "); 18 | velocity = input.nextDouble(); 19 | acceleration = input.nextDouble(); 20 | 21 | // calculate the runway length 22 | runwayLength = velocity * velocity / (2 * acceleration); 23 | 24 | // display the result 25 | System.out.println("The minimum runway length for this airplane is " 26 | + runwayLength); 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /Chapter_02/Exercise_13/Exercise_02_13.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | /** 4 | * Exercise 2.13 from the book Introduction to Java Programming (10th). 5 | * 6 | * @author Henrik Samuelsson, henrik.samuelsson(at)gmail.com 7 | */ 8 | 9 | public class Exercise_02_13 { 10 | 11 | public static void main(String[] args) { 12 | double monthlyDeposit; 13 | double Savings = 0; 14 | 15 | // get monthly deposit from user 16 | Scanner input = new Scanner(System.in); 17 | System.out.print("Enter the monthly saving amount: "); 18 | monthlyDeposit = input.nextDouble(); 19 | 20 | // calculate amount after six months 21 | Savings = (monthlyDeposit + Savings) * (1 + 0.00417); 22 | Savings = (monthlyDeposit + Savings) * (1 + 0.00417); 23 | Savings = (monthlyDeposit + Savings) * (1 + 0.00417); 24 | Savings = (monthlyDeposit + Savings) * (1 + 0.00417); 25 | Savings = (monthlyDeposit + Savings) * (1 + 0.00417); 26 | Savings = (monthlyDeposit + Savings) * (1 + 0.00417); 27 | 28 | // get rid of excess decimals 29 | Savings = ((int) (Savings * 100)) / 100.0; 30 | 31 | // present the result 32 | System.out.println("After the sixth month, the account value is $" + 33 | Savings); 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /Chapter_02/Exercise_14/Exercise_02_14.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | /** 4 | * Exercise 2.14 from the book Introduction to Java Programming (10th). 5 | * 6 | * @author Henrik Samuelsson, henrik.samuelsson(at)gmail.com 7 | */ 8 | 9 | public class Exercise_02_14 { 10 | 11 | public static void main(String[] args) { 12 | double height; 13 | double weight; 14 | double bmi; 15 | 16 | // get weight and height from the user 17 | Scanner input = new Scanner(System.in); 18 | System.out.print("Enter weight in pounds: "); 19 | weight = input.nextDouble(); 20 | System.out.print("Enter height in inches: "); 21 | height = input.nextDouble(); 22 | 23 | // convert weight to kilograms 24 | weight = weight * 0.45359237; 25 | // convert height to meters 26 | height = height * 0.0254; 27 | // calculate BMI 28 | bmi = weight / (height * height); 29 | 30 | // display the calculated BMI to the user 31 | System.out.print("BMI is " + bmi); 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /Chapter_02/Exercise_15/Exercise_02_15.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | /** 4 | * Exercise 2.15 from the book Introduction to Java Programming (10th). 5 | * 6 | * @author Henrik Samuelsson, henrik.samuelsson(at)gmail.com 7 | */ 8 | 9 | public class Exercise_02_15 { 10 | 11 | public static void main(String[] args) { 12 | double x1, x2, y1, y2, distance; 13 | 14 | // get input from user 15 | Scanner input = new Scanner(System.in); 16 | System.out.print ("Enter x1 and y1: "); 17 | x1 = input.nextDouble(); 18 | y1 = input.nextDouble(); 19 | System.out.print ("Enter x2 and y2: "); 20 | x2 = input.nextDouble(); 21 | y2 = input.nextDouble(); 22 | 23 | // calculate the distance between the points 24 | distance = Math.pow(Math.pow(x2-x1, 2) + Math.pow(y2-y1, 2), 0.5); 25 | 26 | // display the result of the calculation 27 | System.out.println("The distance between the two points is " 28 | + distance); 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /Chapter_02/Exercise_16/Exercise_02_16.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | /** 4 | * Exercise 2.16 from the book Introduction to Java Programming (10th). 5 | * 6 | * @note Got the answer 78.59180539343781 when testing with input 5.5. The 7 | * answer according to the book should have been 78.5895. I do not know 8 | * what caused this mismatch, seems to big to be a rounding error. 9 | * 10 | * @author Henrik Samuelsson, henrik.samuelsson(at)gmail.com 11 | */ 12 | 13 | public class Exercise_02_16 { 14 | 15 | public static void main(String[] args) { 16 | double side, area; 17 | 18 | // get input from user 19 | Scanner input = new Scanner(System.in); 20 | System.out.print ("Enter the side: "); 21 | side = input.nextDouble(); 22 | 23 | // calculate the area 24 | area = 3 * Math.pow(3.0, 0.5) / 2 * Math.pow(side, 2); 25 | 26 | // display the result of the calculation 27 | System.out.println("The area of the hexagon is " + area); 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /Chapter_02/Exercise_17/Exercise_02_17.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | /** 4 | * Exercise 2.17 from the book Introduction to Java Programming (10th). 5 | * 6 | * @note The degree character is displayed by inserting the unicode for this 7 | * character which is 00B0. 8 | * 9 | * @author Henrik Samuelsson, henrik.samuelsson(at)gmail.com 10 | */ 11 | 12 | public class Exercise_02_17 { 13 | 14 | public static void main(String[] args) { 15 | double temperature, windSpeed, windChillIndex; 16 | 17 | // get input from user 18 | Scanner input = new Scanner(System.in); 19 | System.out.print ("Enter the temperature in Fahrenheit between " 20 | + "-58\u00B0F and 41\u00B0F: "); 21 | temperature = input.nextDouble(); 22 | System.out.print ("Enter the wind speed (>=2) in miles per hour: "); 23 | windSpeed = input.nextDouble(); 24 | 25 | // calculate the wind chill corrected temperature 26 | windChillIndex = 35.74 + 0.6215 * temperature 27 | - 35.75 * Math.pow(windSpeed, 0.16) 28 | + 0.4275 * temperature * Math.pow(windSpeed, 0.16); 29 | 30 | // display the result 31 | System.out.println("The wind chill index is " + windChillIndex); 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /Chapter_02/Exercise_18/Exercise_02_18.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | /** 4 | * Exercise 2.18 from the book Introduction to Java Programming (10th). 5 | * 6 | * @author Henrik Samuelsson, henrik.samuelsson(at)gmail.com 7 | */ 8 | 9 | public class Exercise_02_18 { 10 | 11 | public static void main(String[] args) { 12 | int a, b, p; 13 | a = 1; 14 | b = 2; 15 | 16 | System.out.println("a\tb\tpow(a, b)"); 17 | 18 | p = (int) Math.pow(a, b); 19 | System.out.println(a + "\t" + b + "\t" + p); 20 | a++; 21 | b++; 22 | 23 | p = (int) Math.pow(a, b); 24 | System.out.println(a + "\t" + b + "\t" + p); 25 | a++; 26 | b++; 27 | 28 | p = (int) Math.pow(a, b); 29 | System.out.println(a + "\t" + b + "\t" + p); 30 | a++; 31 | b++; 32 | 33 | p = (int) Math.pow(a, b); 34 | System.out.println(a + "\t" + b + "\t" + p); 35 | a++; 36 | b++; 37 | 38 | p = (int) Math.pow(a, b); 39 | System.out.println(a + "\t" + b + "\t" + p); 40 | a++; 41 | b++; 42 | } 43 | 44 | } 45 | 46 | -------------------------------------------------------------------------------- /Chapter_02/Exercise_19/Exercise_02_19.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | /** 4 | * Exercise 2.19 from the book Introduction to Java Programming (10th). 5 | * 6 | * @note I did not understand the suggested formula, for calculating the area of 7 | * a triangle, in the book. So I searched for a formula online and found 8 | * this site: 9 | * http://www.mathopenref.com/coordtrianglearea.html 10 | * There was another formula that I ended up using. 11 | * 12 | * @author Henrik Samuelsson, henrik.samuelsson(at)gmail.com 13 | */ 14 | 15 | public class Exercise_02_19 { 16 | 17 | public static void main(String[] args) { 18 | double x1, x2, x3, y1, y2, y3; 19 | double area; 20 | 21 | // query the user for data about the three points 22 | Scanner input = new Scanner(System.in); 23 | System.out.print ("Enter three points for a triangle: "); 24 | x1 = input.nextDouble(); 25 | y1 = input.nextDouble(); 26 | x2 = input.nextDouble(); 27 | y2 = input.nextDouble(); 28 | x3 = input.nextDouble(); 29 | y3 = input.nextDouble(); 30 | 31 | // calculate the area of the triangle 32 | area = Math.abs((x1 * (y2 - y3) + x2 * (y3 - y1) + x3 * (y1 - y2)) / 2); 33 | 34 | // display the result 35 | System.out.println("The area of the triangle is " + area); 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /Chapter_02/Exercise_20/Exercise_02_20.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | /** 4 | * Exercise 2.20 from the book Introduction to Java Programming (10th). 5 | * 6 | * @author Henrik Samuelsson, henrik.samuelsson(at)gmail.com 7 | */ 8 | 9 | public class Exercise_02_20 { 10 | 11 | public static void main(String[] args) { 12 | double balance, interestRate, interest; 13 | 14 | // get input from user 15 | Scanner input = new Scanner(System.in); 16 | System.out.print ("Enter balance and interest rate (e.g., 3 for 3%): "); 17 | balance = input.nextDouble(); 18 | interestRate = input.nextDouble(); 19 | 20 | // calculate the interest 21 | interest = balance * (interestRate / 1200); 22 | 23 | // display the result of the calculation 24 | System.out.println("The interest is " + interest); 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /Chapter_02/Exercise_21/Exercise_02_21.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | /** 4 | * Exercise 2.21 from the book Introduction to Java Programming (10th). 5 | * 6 | * @author Henrik Samuelsson, henrik.samuelsson(at)gmail.com 7 | */ 8 | 9 | public class Exercise_02_21 { 10 | 11 | public static void main(String[] args) { 12 | double futureValue, investment, interest, years; 13 | 14 | // get input from user 15 | Scanner input = new Scanner(System.in); 16 | System.out.print ("Enter investment amount: "); 17 | investment = input.nextDouble(); 18 | System.out.print ("Enter annual interest rate in percentage: "); 19 | interest = input.nextDouble(); 20 | System.out.print ("Enter number of years: "); 21 | years = input.nextDouble(); 22 | 23 | // calculate the future value of investment 24 | futureValue = investment * Math.pow(1 + interest / 1200, years * 12); 25 | 26 | // display the result of the calculation 27 | System.out.println("Accumulated value is $" + futureValue); 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /Chapter_02/Exercise_22/Exercise_02_22.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | /** 4 | * Exercise 2.22 from the book Introduction to Java Programming (10th). 5 | * 6 | * @author Henrik Samuelsson, henrik.samuelsson(at)gmail.com 7 | */ 8 | 9 | public class Exercise_02_22 { 10 | 11 | public static void main(String[] args) { 12 | // create a Scanner 13 | Scanner input = new Scanner(System.in); 14 | 15 | // receive the amount 16 | System.out.print("Enter an amount in cents, for example to enter the " 17 | + "amount $11.56 write 1156: "); 18 | int amount = input.nextInt(); 19 | 20 | // find the number of one dollars 21 | int numberOfOneDollars = amount / 100; 22 | amount = amount % 100; 23 | 24 | // find the number of quarters in the remaining amount 25 | int numberOfQuarters = amount / 25; 26 | amount = amount % 25; 27 | 28 | // find the number of dimes in the remaining amount 29 | int numberOfDimes = amount / 10; 30 | amount = amount % 10; 31 | 32 | // find the number of nickels in the remaining amount 33 | int numberOfNickels = amount / 5; 34 | amount = amount % 5; 35 | 36 | // find the number of pennies in the remaining amount 37 | int numberOfPennies = amount; 38 | 39 | // display results 40 | System.out.println("Your amount in cents " + amount + " consists of"); 41 | System.out.println(" " + numberOfOneDollars + " dollars"); 42 | System.out.println(" " + numberOfQuarters + " quarters "); 43 | System.out.println(" " + numberOfDimes + " dimes"); 44 | System.out.println(" " + numberOfNickels + " nickels"); 45 | System.out.println(" " + numberOfPennies + " pennies"); 46 | } 47 | 48 | } 49 | -------------------------------------------------------------------------------- /Chapter_02/Exercise_23/Exercise_02_23.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | /** 4 | * Exercise 2.23 from the book Introduction to Java Programming (10th). 5 | * 6 | * @author Henrik Samuelsson, henrik.samuelsson(at)gmail.com 7 | */ 8 | 9 | public class Exercise_02_23 { 10 | 11 | public static void main(String[] args) { 12 | double drivingDistance, milesPerGallon, pricePerGallon, costOfDriving; 13 | 14 | // get input from user 15 | Scanner input = new Scanner(System.in); 16 | System.out.print("Enter the driving distance: "); 17 | drivingDistance = input.nextDouble(); 18 | System.out.print("Enter miles per gallon: "); 19 | milesPerGallon = input.nextDouble(); 20 | System.out.print("Enter price per gallon: "); 21 | pricePerGallon = input.nextDouble(); 22 | 23 | // calculate the cost of driving 24 | costOfDriving = drivingDistance * pricePerGallon / milesPerGallon; 25 | 26 | // get rid of excess decimals before presenting the result 27 | costOfDriving = ((int) (costOfDriving * 100)) / 100.0; 28 | 29 | // display the result 30 | System.out.println("The cost of driving is $" + costOfDriving); 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /Chapter_03/Checkpoints_Ch_03.md: -------------------------------------------------------------------------------- 1 | # Checkpoint Answers Chapter 3 # 2 | ## 3.1 ## 3 | Examples of relational operators are: 4 | ``` 5 | < less than 6 | <= less than or equal to 7 | > greater than 8 | >= greater than or equal to 9 | == equal to 10 | != not equal to 11 | ``` 12 | 13 | ## 3.2 ## 14 | Below are some Boolean expressions with comments about the resulting values. 15 | ``` 16 | x = 1 17 | (x > 0) // true 18 | (x < 0) // false 19 | (x != 0) // true 20 | (x >= 0) // true 21 | (x != 1) // false 22 | ``` 23 | 24 | ## 3.3 ## 25 | It is now allowed to cast from an boolean to an int in Java, neither is it allowed to cast from an int to an boolean. 26 | 27 | This means that the following program will not compile. 28 | ```Java 29 | public class CheckPoint_03_03 { 30 | 31 | public static void main(String[] args) { 32 | boolean b = true; 33 | i = (int)b; // error 34 | 35 | int i = 1; 36 | boolean b = (boolean)i; // error 37 | } 38 | 39 | } 40 | 41 | ``` 42 | ##3.4## 43 | An if statement that assigns 1 to x if y is greater than 0: 44 | ```Java 45 | if(y > 0) 46 | x = 1; 47 | ``` 48 | ##3.5## 49 | An if statement that increases pay by 3% if score is greater than 90: 50 | ```Java 51 | if(score > 90) 52 | pay *= 1.03; 53 | ``` 54 | 55 | ##3.6## 56 | An if statement that increases pay by 3% if score is greater than 90 and otherwise increases pay by 1%. 57 | ```Java 58 | if(score > 90) 59 | pay *= 1.03; 60 | else 61 | pay *= 1.01; 62 | ``` 63 | 64 | ##3.7## 65 | **(a)** 66 | There is a logical error in this code for this checkpoint. The output will when number is 30 be: 67 | ``` 68 | 30 is even. 69 | 30 is odd. 70 | ``` 71 | When number is 35 so will the output be: 72 | ``` 73 | 35 is odd. 74 | ``` 75 | **(b)** 76 | The second version of the code is corrected and will when number is 30 output: 77 | ``` 78 | 30 is even. 79 | ``` 80 | When number is 35 so will the output, as in the first verison, be: 81 | ``` 82 | 35 is odd. 83 | ``` 84 | 85 | ##3.8## 86 | There will be no output if x = 3 and y = 2. 87 | 88 | The ouput will be `z is 7` if x = 3 and y = 4. 89 | 90 | The ouput will be `x is 2` if x = 2 and y = 2. 91 | 92 | ![](https://github.com/HenrikSamuelsson/Introduction_to_Java_Programming/blob/master/Chapter_03/Resources/check_point_03_08.png) 93 | 94 | ##3.9## 95 | There will be no output if x = 2 and y = 3. 96 | 97 | The ouput will be `x is 3` if x = 3 and y = 2. 98 | 99 | The ouput will be `z is 6` if x = 3 and y = 3. 100 | 101 | ##3.10## 102 | The problem with the code in this checkpoint is that only D or F will be printed. D will be printed whenever score is 60 or more, F is printed if score is less than 60. 103 | 104 | The score comparisons shall be done in descending order for this code to work as intended. 105 | 106 | ##3.11## 107 | a, b, and c are equivalent. 108 | 109 | b and c are correctly indented. 110 | 111 | ##3.12## 112 | ```Java 113 | boolean newLine = count % 10 == 0; 114 | ``` 115 | 116 | ##3.13## 117 | Both a and b are correct and will do the same thing. The code in b is the preferred way because it shows that the statements are related. 118 | 119 | ##3.14## 120 | **(a)** 121 | This code will always check for both even numbers and numbers that is a multiple of 5. 122 | 123 | The output when using number 14, 15, and 30 will be: 124 | ``` 125 | 14 is even 126 | 15 is a multiple of 5 127 | 30 is even 128 | 30 is a multiple of 5 129 | ``` 130 | 131 | **(b)** 132 | This code will check if a number is even. If the number is odd so will an additional check be done that checks if the number is a multiple of 5. 133 | 134 | The out put when using number 14, 15, and 30 will be: 135 | ``` 136 | 14 is even 137 | 15 is a multiple of 5 138 | 30 is even 139 | ``` 140 | 141 | ##3.15## 142 | Math.random() will generate a random double value between 0.0 and 1.0, excluding 1.0. 143 | 144 | Examples of possible values when using Math.random() are 0.5, 0.0, 0.234. 145 | 146 | ##3.16## 147 | **(a)** 148 | Generates an int in the 0 to 19 interval: 149 | ``` 150 | int a = (int)(Math.random() * 20); 151 | ``` 152 | 153 | **(b)** 154 | Generates an int in the 10 to 19 interval: 155 | ``` 156 | int b = 10 + (int)(Math.random() * 10); 157 | ``` 158 | 159 | **(c)** 160 | Generates an int in the 10 to 50 interval: 161 | ``` 162 | int c = 10 + (int)(Math.random() * 41); 163 | ``` 164 | 165 | **(d)** 166 | Generates an int that is 0 or 1: 167 | ``` 168 | int d = (int)(Math.random() * 2); 169 | ``` 170 | 171 | ##3.17## 172 | The two statements in this checkpoint are equal. The first one is better since it is shorter. 173 | 174 | ##3.18## 175 | ```Java 176 | x = 1 177 | 178 | (true) && (3 > 4) // false 179 | !(x > 0) && (x > 0) // false 180 | (x > 0) || (x < 0) // true 181 | 182 | (x != 0) || (x == 0) // true 183 | (x >= 0) || (x < 0) // true 184 | (x != 1) == !(x == 1) // true 185 | ``` 186 | 187 | ##3.19## 188 | **(a)** 189 | ```Java 190 | (num > 1) && (num < 100) 191 | ``` 192 | **(b)** 193 | ```Java 194 | (num > 1) && (num < 100) || (num < 0) 195 | ``` 196 | 197 | ##3.20## 198 | **(a)** 199 | ```Java 200 | (x - 5 < 4.5) && (-(x - 5) < 4.5) 201 | ``` 202 | **(b)** 203 | ```Java 204 | (x - 5 > 4.5) || (-(x - 5) > 4.5) 205 | ``` 206 | 207 | ##3.21## 208 | Assume that x and y are int type variables. 209 | 210 | Examples of legal Java expressions: 211 | ```Java 212 | x /= y 213 | ``` 214 | 215 | Examples of illegal Java expressions. 216 | ```Java 217 | x > y > 0 218 | x = y && y 219 | x or y 220 | x and y 221 | (x != 0) || (x = 0) 222 | ``` 223 | 224 | ##3.22## 225 | Yes. 226 | 227 | ##3.23## 228 | Call the following expression p: 229 | ``` 230 | x >= 50 && x <= 100 231 | ``` 232 | p is false when x is 45 233 | p is true when x is 67 234 | p is false when x is 101 235 | 236 | ##3.24## 237 | The output will be 238 | ``` 239 | (x < y && y < z) is true 240 | (x < y || y < z) is true 241 | !(x < y) is false 242 | (x + y < z) is true 243 | (x + y > z) is false 244 | ``` 245 | 246 | ##3.25## 247 | Boolean expression that evaluates to true if age is greater than 13 and less than 18. 248 | ```Java 249 | age > 13 && age < 18 250 | ``` 251 | 252 | ##3.26## 253 | Boolean expression that evaluates to true if weight is greater than 50 pounds or height is greater than 60 inches. 254 | ```Java 255 | weight > 50 || height > 60 256 | ``` 257 | 258 | ##3.27## 259 | Write a Boolean expression that evaluates to true if weight is greater than 50 pounds and height is greater than 60 inches. 260 | ```Java 261 | weight > 50 && height > 60 262 | ``` 263 | 264 | ##3.28## 265 | Write a Boolean expression that evaluates to true if either weight is greater than 50 pounds or height is greater than 60 inches, but not both. 266 | ```Java 267 | (weight > 50 && !(height > 60)) || (!(weight > 50) && height > 60) 268 | ``` 269 | My opinion is that the other answer, that can be found on the book web site, is wrong on this one. 270 | 271 | ##3.29## 272 | The following data types are allowed to be used as a switch variable: 273 | - char 274 | - byte 275 | - short 276 | - int 277 | - String 278 | 279 | Omitting a break statement will cause a fall-through causing the code in the next case to be to executed. 280 | 281 | A switch statement can be converted to an equivalent if statement. 282 | 283 | A switch statement can make the code easier to read comparing to using deeply nested if statements. 284 | 285 | ##3.30## 286 | ```Java 287 | public class CheckPoint_03_03 { 288 | 289 | public static void main(String[] args) { 290 | int x, y; 291 | 292 | x = 3; 293 | y = 3; 294 | switch (x + 3) { 295 | case 6: 296 | y = 1; 297 | default: 298 | y += 1; 299 | } 300 | System.out.println("After switch statement y = " + y); 301 | 302 | // rewrite switch to an equivalent if-else variant 303 | y = 3; // set y to original value 304 | if(x + 3 == 6) 305 | y = 1; 306 | y += 1; 307 | System.out.println("After if statement y = " + y); 308 | } 309 | 310 | } 311 | ``` 312 | y is 2 after the switch statement. 313 | 314 | ##3.31## 315 | ```Java 316 | public class CheckPoint_03_31 { 317 | 318 | public static void main(String[] args) { 319 | int x = 1, a = 3; 320 | 321 | // first version with an if-else statement 322 | if (a == 1) 323 | x += 5; 324 | else if (a == 2) 325 | x += 10; 326 | else if (a == 3) 327 | x += 16; 328 | else if (a == 4) 329 | x += 34; 330 | 331 | System.out.println("After if-else x = " + x); 332 | 333 | x = 1; // set x to original value before switch statement 334 | 335 | // second version with a switch statement 336 | switch (a) { 337 | case 1: 338 | x += 5; 339 | break; 340 | case 2: 341 | x += 10; 342 | break; 343 | case 3: 344 | x += 16; 345 | break; 346 | case 4: 347 | x += 34; 348 | break; 349 | } 350 | 351 | System.out.println("After switch x = " + x); 352 | } 353 | 354 | } 355 | ``` 356 | x is 17 after the switch statement. 357 | 358 | A flowchart for the switch statement is shown below. 359 | 360 | ![](https://github.com/HenrikSamuelsson/Introduction_to_Java_Programming/blob/master/Chapter_03/Resources/checkpoint_03_31.png?raw=true) 361 | 362 | ##3.32## 363 | ```Java 364 | switch (day) { 365 | case 0: 366 | System.out.println("Sunday"); 367 | break; 368 | case 1: 369 | System.out.println("Monday"); 370 | break; 371 | case 2: 372 | System.out.println("Tuesday"); 373 | break; 374 | case 3: 375 | System.out.println("Wednesday"); 376 | break; 377 | case 4: 378 | System.out.println("Thursday"); 379 | break; 380 | case 5: 381 | System.out.println("Friday"); 382 | break; 383 | case 6: 384 | System.out.println("Saturday"); 385 | break; 386 | } 387 | ``` 388 | 389 | ##3.33## 390 | The output will be: 391 | ``` 392 | sorted 393 | ``` 394 | 395 | ##3.34## 396 | ```Java 397 | ticketPrice = ages >= 16 ? 20 : 10; 398 | ``` 399 | 400 | ##3.35## 401 | **(a)** 402 | ```Java 403 | if (x > 10) 404 | score = 3 * scale; 405 | else 406 | score = 4 * scale; 407 | ``` 408 | **(b)** 409 | ```Java 410 | if (income > 10000) 411 | tax = income * 0.2; 412 | else 413 | tax = income * 0.17 + 1000; 414 | ``` 415 | **(c)** 416 | ```Java 417 | if (number % 3 == 0) 418 | System.out.println(i); 419 | else 420 | System.out.println(j); 421 | ``` 422 | 423 | ##3.36## 424 | ```Java 425 | 1 == (int) (Math.random() * 2) ? 1 : -1; 426 | ``` 427 | 428 | ##3.37## 429 | The precedence of the the Boolean operators is (listed from high to low): 430 | - NOT `!` 431 | - XOR `^` 432 | - AND `&&` 433 | - OR `||` 434 | 435 | The expression `true || true && false` will be evaluated as follows. 436 | ``` 437 | true || (true && false) 438 | true || false 439 | true 440 | ``` 441 | The expression `true && true || false` will be evaluated as follows. 442 | ``` 443 | (true && true) || false 444 | true || false 445 | true 446 | ``` 447 | 448 | ##3.38## 449 | It is true that all the binary operators except =, +=, -=, *=, /=, %= are left associative. 450 | 451 | ##3.39## 452 | ``` 453 | 2 * 2 - 3 > 2 && 4 – 2 > 5 454 | 4 - 2 > 2 && 4 - 2 > 5 455 | 2 > 2 && 2 > 5 456 | false && false 457 | false 458 | ``` 459 | 460 | ``` 461 | 2 * 2 - 3 > 2 || 4 – 2 > 5 462 | 4 - 3 > 2 || 4 – 2 > 5 463 | 1 > 2 || 2 > 5 464 | false || false 465 | false 466 | ``` 467 | 468 | ##3.40## 469 | `(x > 0 && x < 10)` is the same as `((x > 0) && (x < 10))` 470 | 471 | `(x > 0 || x < 10)` is the same as `((x > 0) || (x < 10))` 472 | 473 | `(x > 0 || x < 10 && y < 0)` is the same as `(x > 0 ||(x < 10 && y < 0))` 474 | -------------------------------------------------------------------------------- /Chapter_03/Exercise_01/Exercise_03_01.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | /** 4 | * Exercise 3.1 from the book Introduction to Java Programming (10th). 5 | * 6 | * @author Henrik Samuelsson, henrik.samuelsson(at)gmail.com 7 | */ 8 | 9 | public class Exercise_03_01 { 10 | 11 | public static void main(String[] args) { 12 | double a, b, c; 13 | double discriminant; 14 | double r1, r2; 15 | 16 | // get input from user 17 | Scanner input = new Scanner(System.in); 18 | System.out.print ("Enter a, b, c: "); 19 | a = input.nextDouble(); 20 | b = input.nextDouble(); 21 | c = input.nextDouble(); 22 | 23 | // calculate the discriminant 24 | discriminant = Math.pow(Math.pow(b, 2) - 4 * a * c, 0.5); 25 | 26 | // calculate and display roots based on the value of the discriminant 27 | if (discriminant > 0) { 28 | r1 = (-b + discriminant) / (2 * a); 29 | r2 = (-b - discriminant) / (2 * a); 30 | System.out.println("The equation has two roots " + r1 + " and " 31 | + r2); 32 | } else if (discriminant == 0) { 33 | r1 = -b / (2 * a); 34 | System.out.println("The equation has one root " + r1); 35 | } else { 36 | System.out.println("The equation has no real roots"); 37 | } 38 | } 39 | 40 | } 41 | -------------------------------------------------------------------------------- /Chapter_03/Exercise_02/Exercise_03_02.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | /** 4 | * Exercise 3.2 from the book Introduction to Java Programming (10th). 5 | * 6 | * @author Henrik Samuelsson, henrik.samuelsson(at)gmail.com 7 | */ 8 | 9 | public class Exercise_03_02 { 10 | 11 | public static void main(String[] args) { 12 | int number1 = (int) (System.currentTimeMillis() % 10); 13 | int number2 = (int) (System.currentTimeMillis() / 3 % 10); 14 | int number3 = (int) (System.currentTimeMillis() / 7 % 10); 15 | 16 | // create a scanner 17 | Scanner input = new Scanner(System.in); 18 | 19 | System.out.print("What is " + number1 + " + " + number2 + " + " 20 | + number3 + "? "); 21 | 22 | int answer = input.nextInt(); 23 | 24 | System.out.println(number1 + " + " + number2 + " + " + number3 + " = " 25 | + answer + " is " + (number1 + number2 + number3 == answer)); 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /Chapter_03/Exercise_03/Exercise_03_03.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | /** 4 | * Exercise 3.3 from the book Introduction to Java Programming (10th). 5 | * 6 | * @author Henrik Samuelsson, henrik.samuelsson(at)gmail.com 7 | */ 8 | 9 | public class Exercise_03_03 { 10 | 11 | public static void main(String[] args) { 12 | double a, b, c, d, e, f, x, y; 13 | 14 | // get input from user 15 | Scanner input = new Scanner(System.in); 16 | System.out.print ("Enter a, b, c, d, e, f: "); 17 | a = input.nextDouble(); 18 | b = input.nextDouble(); 19 | c = input.nextDouble(); 20 | d = input.nextDouble(); 21 | e = input.nextDouble(); 22 | f = input.nextDouble(); 23 | 24 | // use Cramers rule to solve the system of linear equations 25 | if (a * d - b * c == 0) { 26 | System.out.println("The equation has no solution"); 27 | } else { 28 | x = (e * d - b * f) / (a * d - b * c); 29 | y = (a * f - e * c) / (a * d - b * c); 30 | System.out.println("x is " + x + " and y is " + y); 31 | } 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /Chapter_03/Exercise_04/Exercise_03_04.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | /** 4 | * Exercise 3.4 from the book Introduction to Java Programming (10th). 5 | * 6 | * @author Henrik Samuelsson, henrik.samuelsson(at)gmail.com 7 | */ 8 | 9 | public class Exercise_03_04 { 10 | 11 | public static void main(String[] args) { 12 | int monthNumber; 13 | String monthName; 14 | 15 | // generate a random number between 1 and 12 16 | monthNumber = 1 + (int) (Math.random() * 12); 17 | 18 | // look up the name of month 19 | switch (monthNumber) { 20 | case 1: 21 | monthName = "January"; 22 | break; 23 | case 2: 24 | monthName = "February"; 25 | break; 26 | case 3: 27 | monthName = "Mars"; 28 | break; 29 | case 4: 30 | monthName = "April"; 31 | break; 32 | case 5: 33 | monthName = "May"; 34 | break; 35 | case 6: 36 | monthName = "June"; 37 | break; 38 | case 7: 39 | monthName = "July"; 40 | break; 41 | case 8: 42 | monthName = "August"; 43 | break; 44 | case 9: 45 | monthName = "September"; 46 | break; 47 | case 10: 48 | monthName = "October"; 49 | break; 50 | case 11: 51 | monthName = "November"; 52 | break; 53 | case 12: 54 | monthName = "December"; 55 | break; 56 | default: 57 | monthName = "Error illegal month number"; 58 | } 59 | 60 | // display the name of the generated month 61 | System.out.println(monthName); 62 | } 63 | 64 | } 65 | -------------------------------------------------------------------------------- /Chapter_03/Exercise_05/Exercise_03_05.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | /** 4 | * Exercise 3.5 from the book Introduction to Java Programming (10th). 5 | * 6 | * @author Henrik Samuelsson, henrik.samuelsson(at)gmail.com 7 | */ 8 | 9 | public class Exercise_03_05 { 10 | 11 | public static void main(String[] args) { 12 | final int DAYS_IN_A_WEEK = 7; 13 | 14 | // create a Scanner 15 | Scanner input = new Scanner(System.in); 16 | 17 | // query the user for the start day 18 | System.out.print("Enter today's day: "); 19 | int startDayNumber = input.nextInt(); 20 | 21 | // translate day number to the actual name of the day 22 | String startDayName; 23 | 24 | switch (startDayNumber) { 25 | case 0: 26 | startDayName = "Sunday"; 27 | break; 28 | case 1: 29 | startDayName = "Monday"; 30 | break; 31 | case 2: 32 | startDayName = "Tuesday"; 33 | break; 34 | case 3: 35 | startDayName = "Wednesay"; 36 | break; 37 | case 4: 38 | startDayName = "Thursday"; 39 | break; 40 | case 5: 41 | startDayName = "Friday"; 42 | break; 43 | case 6: 44 | startDayName = "Saturday"; 45 | break; 46 | default: 47 | startDayName = "ERROR"; 48 | } 49 | 50 | // query the user for the number of elapsed days since the start day 51 | System.out.print("Enter the number of days elapsed since today: "); 52 | int daysPassed = input.nextInt(); 53 | 54 | // calculate the number of the future day 55 | int endDayNumber = (startDayNumber + daysPassed) % DAYS_IN_A_WEEK; 56 | 57 | // translate day number to the actual name of the day 58 | String endDayName; 59 | 60 | switch (endDayNumber) { 61 | case 0: 62 | endDayName = "Sunday"; 63 | break; 64 | case 1: 65 | endDayName = "Monday"; 66 | break; 67 | case 2: 68 | endDayName = "Tuesday"; 69 | break; 70 | case 3: 71 | endDayName = "Wednesday"; 72 | break; 73 | case 4: 74 | endDayName = "Thursday"; 75 | break; 76 | case 5: 77 | endDayName = "Friday"; 78 | break; 79 | case 6: 80 | endDayName = "Saturday"; 81 | break; 82 | default: 83 | endDayName = "ERROR"; 84 | 85 | } 86 | 87 | // display results 88 | System.out.println("Today is " + startDayName + " and the future day " 89 | + "is " + endDayName); 90 | } 91 | 92 | } 93 | -------------------------------------------------------------------------------- /Chapter_03/Exercise_06/Exercise_03_06.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | /** 4 | * Exercise 3.6 from the book Introduction to Java Programming (10th). 5 | * 6 | * @author Henrik Samuelsson, henrik.samuelsson(at)gmail.com 7 | */ 8 | 9 | public class Exercise_03_06 { 10 | 11 | public static void main(String[] args) { 12 | Scanner input = new Scanner(System.in); 13 | 14 | // prompt the user to enter weight in pounds 15 | System.out.print("Enter weight in pounds: "); 16 | double weight = input.nextDouble(); 17 | 18 | // prompt the user to enter height in feet 19 | System.out.print("Enter feet: "); 20 | double feet = input.nextDouble(); 21 | 22 | // prompt the user to enter height in inches 23 | System.out.print("Enter inches: "); 24 | double inches = input.nextDouble(); 25 | 26 | final double KILOGRAMS_PER_POUND = 0.45359237; // constant 27 | final double METERS_PER_FOOT = 0.3048; // constant 28 | final double METERS_PER_INCH = 0.0254; // constant 29 | 30 | // compute BMI 31 | double weightInKilograms = weight * KILOGRAMS_PER_POUND; 32 | double heightInMeters = feet * METERS_PER_FOOT 33 | + inches * METERS_PER_INCH; 34 | double bmi = weightInKilograms / (heightInMeters * heightInMeters); 35 | 36 | // display result 37 | System.out.println("BMI is " + bmi); 38 | if (bmi < 18.5) 39 | System.out.println("Underweight"); 40 | else if (bmi < 25) 41 | System.out.println("Normal"); 42 | else if (bmi < 30) 43 | System.out.println("Overweight"); 44 | else 45 | System.out.println("Obese"); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /Chapter_03/Exercise_07/Exercise_03_07.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | /** 4 | * Exercise 3.7 from the book Introduction to Java Programming (10th). 5 | * 6 | * @author Henrik Samuelsson, henrik.samuelsson(at)gmail.com 7 | */ 8 | 9 | public class Exercise_03_07 { 10 | 11 | public static void main(String[] args) { 12 | // create a Scanner 13 | Scanner input = new Scanner(System.in); 14 | 15 | // receive the amount 16 | System.out.print("Enter an amount in double, for example 11.56: "); 17 | double amount = input.nextDouble(); 18 | 19 | int remainingAmount = (int) (amount * 100); 20 | 21 | // find the number of one dollars 22 | int numberOfOneDollars = remainingAmount / 100; 23 | remainingAmount = remainingAmount % 100; 24 | 25 | // find the number of quarters in the remaining amount 26 | int numberOfQuarters = remainingAmount / 25; 27 | remainingAmount = remainingAmount % 25; 28 | 29 | // find the number of dimes in the remaining amount 30 | int numberOfDimes = remainingAmount / 10; 31 | remainingAmount = remainingAmount % 10; 32 | 33 | // find the number of nickels in the remaining amount 34 | int numberOfNickels = remainingAmount / 5; 35 | remainingAmount = remainingAmount % 5; 36 | 37 | // find the number of pennies in the remaining amount 38 | int numberOfPennies = remainingAmount; 39 | 40 | // display results 41 | System.out.println("Your amount " + amount + " consists of"); 42 | if (numberOfOneDollars == 1) 43 | System.out.println(" " + numberOfOneDollars + " dollar"); 44 | else if (numberOfOneDollars > 1) 45 | System.out.println(" " + numberOfOneDollars + " dollars"); 46 | if (numberOfQuarters == 1) 47 | System.out.println(" " + numberOfQuarters + " quarter "); 48 | else if (numberOfQuarters > 1) 49 | System.out.println(" " + numberOfQuarters + " quarters "); 50 | if (numberOfDimes == 1) 51 | System.out.println(" " + numberOfDimes + " dime"); 52 | else if (numberOfDimes > 1) 53 | System.out.println(" " + numberOfDimes + " dimes"); 54 | if (numberOfNickels == 1) 55 | System.out.println(" " + numberOfNickels + " nickel"); 56 | else if (numberOfNickels > 1) 57 | System.out.println(" " + numberOfNickels + " nickels"); 58 | if (numberOfPennies == 1) 59 | System.out.println(" " + numberOfPennies + " penny"); 60 | else if (numberOfPennies > 1) 61 | System.out.println(" " + numberOfPennies + " pennies"); 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /Chapter_03/Exercise_08/Exercise_03_08.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | /** 4 | * Exercise 3.8 from the book Introduction to Java Programming (10th). 5 | * 6 | * @author Henrik Samuelsson, henrik.samuelsson(at)gmail.com 7 | */ 8 | 9 | public class Exercise_03_08 { 10 | 11 | public static void main(String[] args) { 12 | 13 | Scanner input = new Scanner(System.in); 14 | 15 | System.out.print("Enter three integers: "); 16 | int n1 = input.nextInt(); 17 | int n2 = input.nextInt(); 18 | int n3 = input.nextInt(); 19 | 20 | if (n1 > n2) { 21 | int temp = n2; 22 | n2 = n1; 23 | n1 = temp; 24 | } 25 | 26 | if (n2 > n3) { 27 | int temp = n3; 28 | n3 = n2; 29 | n2 = temp; 30 | } 31 | 32 | if (n1 > n2) { 33 | int temp = n2; 34 | n2 = n1; 35 | n1 = temp; 36 | } 37 | 38 | System.out.println("The sorted numbers are "+ n1 + " " + n2 + " " + n3); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /Chapter_03/Exercise_09/Exercise_03_09.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | /** 4 | * Exercise 3.9 from the book Introduction to Java Programming (10th). 5 | * 6 | * @author Henrik Samuelsson, henrik.samuelsson(at)gmail.com 7 | */ 8 | 9 | public class Exercise_03_09 { 10 | 11 | public static void main(String[] args) { 12 | 13 | // create a scanner 14 | Scanner input = new Scanner(System.in); 15 | 16 | System.out.print("Enter the first 9 digits of an ISBN as integer: "); 17 | int isbn9 = input.nextInt(); 18 | 19 | // split the big integer into 9 digits 20 | int d9 = isbn9 % 10; 21 | isbn9 = isbn9 / 10; 22 | int d8 = isbn9 % 10; 23 | isbn9 = isbn9 / 10; 24 | int d7 = isbn9 % 10; 25 | isbn9 = isbn9 / 10; 26 | int d6 = isbn9 % 10; 27 | isbn9 = isbn9 / 10; 28 | int d5 = isbn9 % 10; 29 | isbn9 = isbn9 / 10; 30 | int d4 = isbn9 % 10; 31 | isbn9 = isbn9 / 10; 32 | int d3 = isbn9 % 10; 33 | isbn9 = isbn9 / 10; 34 | int d2 = isbn9 % 10; 35 | isbn9 = isbn9 / 10; 36 | int d1 = isbn9 % 10; 37 | isbn9 = isbn9 / 10; 38 | 39 | // calculate the checksum 40 | int d10 = (d1 * 1 + d2 * 2 + d3 * 3 + d4 * 4 + d5 * 5 + d6 * 6 + d7 * 7 41 | + d8 * 8 + d9 * 9) % 11; 42 | 43 | // print all the numbers in the isbn 44 | System.out.print("The ISBN-10 number is "); 45 | System.out.print(d1); 46 | System.out.print(d2); 47 | System.out.print(d3); 48 | System.out.print(d4); 49 | System.out.print(d5); 50 | System.out.print(d6); 51 | System.out.print(d7); 52 | System.out.print(d8); 53 | System.out.print(d9); 54 | if (d10 == 10) 55 | System.out.println("X"); 56 | else 57 | System.out.println(d10); 58 | } 59 | 60 | } 61 | -------------------------------------------------------------------------------- /Chapter_03/Exercise_10/Exercise_10_10.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HenrikSamuelsson/Introduction_to_Java_Programming/c4ba17abcdde14585c3c7930f167a53cf7ec6bfe/Chapter_03/Exercise_10/Exercise_10_10.java -------------------------------------------------------------------------------- /Chapter_03/Exercise_11/Exercise_03_11.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | /** 4 | * Exercise 3.11 from the book Introduction to Java Programming (10th). 5 | *

6 | * Find the number of days in a month. 7 | *

8 | * Could use the Calendar class to solve this exercise with just a few lines of 9 | * code but we are still early in the book so will use a more basic naive 10 | * approach. 11 | * 12 | * @author Henrik Samuelsson, henrik.samuelsson(at)gmail.com 13 | */ 14 | 15 | public class Exercise_03_11 { 16 | 17 | public static void main(String[] args) { 18 | int month; 19 | int year; 20 | int daysInMonth; 21 | String monthName; 22 | 23 | // get the month and the year from the user. 24 | Scanner input = new Scanner(System.in); 25 | System.out.print("Enter number representing a month: "); 26 | month = input.nextInt(); 27 | System.out.print("Enter number representing a year: "); 28 | year = input.nextInt(); 29 | 30 | // process the input 31 | switch (month) { 32 | case 1: 33 | daysInMonth = 31; 34 | monthName = "January"; 35 | break; 36 | case 2: 37 | // February so need to check for leap years 38 | if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) 39 | daysInMonth = 29; 40 | else 41 | daysInMonth = 28; 42 | monthName = "February"; 43 | break; 44 | case 3: 45 | daysInMonth = 31; 46 | monthName = "March"; 47 | break; 48 | case 4: 49 | daysInMonth = 30; 50 | monthName = "April"; 51 | break; 52 | case 5: 53 | daysInMonth = 31; 54 | monthName = "May"; 55 | break; 56 | case 6: 57 | daysInMonth = 30; 58 | monthName = "June"; 59 | break; 60 | case 7: 61 | daysInMonth = 31; 62 | monthName = "July"; 63 | break; 64 | case 8: 65 | daysInMonth = 31; 66 | monthName = "August"; 67 | break; 68 | case 9: 69 | daysInMonth = 30; 70 | monthName = "September"; 71 | break; 72 | case 10: 73 | daysInMonth = 31; 74 | monthName = "October"; 75 | break; 76 | case 11: 77 | daysInMonth = 30; 78 | monthName = "November"; 79 | break; 80 | case 12: 81 | daysInMonth = 31; 82 | monthName = "December"; 83 | break; 84 | default: 85 | System.out.println("The month number is invalid!"); 86 | return; // exit program 87 | } 88 | 89 | // display results 90 | System.out.println(monthName + " " + year + " had " + daysInMonth 91 | + " days."); 92 | } 93 | 94 | } 95 | -------------------------------------------------------------------------------- /Chapter_03/Resources/check_point_03_08.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HenrikSamuelsson/Introduction_to_Java_Programming/c4ba17abcdde14585c3c7930f167a53cf7ec6bfe/Chapter_03/Resources/check_point_03_08.png -------------------------------------------------------------------------------- /Chapter_03/Resources/checkpoint_03_31.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HenrikSamuelsson/Introduction_to_Java_Programming/c4ba17abcdde14585c3c7930f167a53cf7ec6bfe/Chapter_03/Resources/checkpoint_03_31.png -------------------------------------------------------------------------------- /Chapter_04/Checkpoints_Ch_04.md: -------------------------------------------------------------------------------- 1 | # Checkpoint Answers Chapter 4 # 2 | ##4.1## 3 | **(a)** 4 | ``` 5 | Math.sqrt(4) // 2.0 6 | ``` 7 | **(b)** 8 | ``` 9 | Math.sin(2 * Math.PI) // -2.4492935982947064E-16 10 | ``` 11 | **(c)** 12 | ``` 13 | Math.cos(2 * Math.PI) // 1.0 14 | ``` 15 | **(d)** 16 | ``` 17 | Math.pow(2, 2) // 4.0 18 | ``` 19 | **(e)** 20 | ``` 21 | Math.log(Math.E) // 1.0 22 | ``` 23 | **(f)** 24 | ``` 25 | Math.exp(1) // 2.718281828459045 26 | ``` 27 | **(g)** 28 | ``` 29 | Math.max(2, Math.min(3, 4)) // 3 30 | ``` 31 | **(h)** 32 | ``` 33 | Math.rint(-2.5) // -2.0 34 | ``` 35 | **(i)** 36 | ``` 37 | Math.ceil(-2.5) // -2.0 38 | ``` 39 | **(j)** 40 | ``` 41 | Math.floor(-2.5) // -3.0 42 | ``` 43 | **(k)** 44 | ``` 45 | Math.round(-2.5f) // -2 46 | ``` 47 | **(l)** 48 | ``` 49 | Math.round(-2.5) // -2 50 | ``` 51 | **(m)** 52 | ``` 53 | Math.rint(2.5) // 2.0 54 | ``` 55 | **(n)** 56 | ``` 57 | Math.ceil(2.5) // 3.0 58 | ``` 59 | **(o)** 60 | ``` 61 | Math.floor(2.5) // 2.0 62 | ``` 63 | **(p)** 64 | ``` 65 | Math.round(2.5f) // 3 66 | ``` 67 | **(q)** 68 | ``` 69 | Math.round(2.5) // 3 70 | ``` 71 | **(r)** 72 | ``` 73 | Math.round(Math.abs(-2.5)) // 3 74 | ``` 75 | 76 | ##4.2## 77 | The argument for trigonometric methods is an angle in radians. 78 | 79 | ##4.3## 80 | ```Java 81 | // convert 47 degrees to radians 82 | double angle = Math.toRadians(47); 83 | ``` 84 | 85 | ##4.4## 86 | ```Java 87 | // convert pi / 7 radians to degrees 88 | double angle = Math.toDegrees(Math.PI / 7); 89 | ``` 90 | 91 | ##4.5## 92 | **(a)** 93 | ```Java 94 | int i = 34 + (int)(Math.random() * 22); 95 | ``` 96 | **(b)** 97 | ```Java 98 | int j = (int)(Math.random() * 1000); 99 | ``` 100 | **(c)** 101 | ```Java 102 | double k = 5.5 + (int)(Math.random() * 50); 103 | ``` 104 | 105 | ##4.6## 106 | There is one package that is automatically imported into any Java program, this package is called java.lang. 107 | 108 | One of the classes that belongs to the java.lang package is the Math class. This means that the Math methods can be used directly without the need for explicit import. 109 | 110 | ##4.7## 111 | ```Java 112 | Math.log(Math.exp(5.5)); // evaluates to 5.5 113 | ``` 114 | ```Java 115 | Math.exp(Math.log(5.5)); // evaluates to 5.5 116 | ``` 117 | ```Java 118 | Math.asin(Math.sin(Math.PI / 6)); // evaluates to 0.5235987755982988 = pi / 6 119 | ``` 120 | ```Java 121 | Math.sin(Math.asin(Math.PI / 6)); // evaluates to 0.5235987755982988 = pi / 6 122 | ``` 123 | ##4.8## 124 | ```Java 125 | System.out.println((int)'1'); // prints 49 126 | System.out.println((int)'A'); // prints 65 127 | System.out.println((int)'B'); // prints 66 128 | System.out.println((int)'a'); // prints 97 129 | System.out.println((int)'b'); // prints 98 130 | ``` 131 | ```Java 132 | System.out.println((char)40); // prints ( 133 | System.out.println((char)59); // prints ; 134 | System.out.println((char)79); // prints O 135 | System.out.println((char)85); // prints U 136 | System.out.println((char)90); // prints Z 137 | ``` 138 | ```Java 139 | System.out.println((char)0x40); // prints @ 140 | System.out.println((char)0x5A); // prints Z 141 | System.out.println((char)0x71); // prints q 142 | System.out.println((char)0x72); // prints r 143 | System.out.println((char)0x7A); // prints z 144 | ``` 145 | 146 | ##4.9## 147 | Examples of correct character literals: 148 | ```Java 149 | 'l' 150 | '\u3fFa' 151 | '\b' 152 | '\t' 153 | ``` 154 | Example of incorrect character literal, because the Unicode representation is too long: 155 | ```Java 156 | '\u345dE' 157 | ``` 158 | 159 | ##4.10## 160 | ```Java 161 | System.out.println('\\'); // prints \ 162 | System.out.println('"'); // prints " 163 | ``` 164 | 165 | ##4.11## 166 | ```Java 167 | int i = '1'; 168 | ``` 169 | equals 170 | ```Java 171 | int i = 49; 172 | ``` 173 | because the ASCII code for 1 is 49, i will hence become 49. 174 | 175 | ```Java 176 | int j = '1' + '2' * ('4' - '3') + 'b' / 'a'; 177 | ``` 178 | equals 179 | ```Java 180 | int j = 49 + 50 * (52 - 51) + 98 / 97; 181 | ``` 182 | that evaluates to j becoming 100. 183 | 184 | ```Java 185 | int k = 'a'; 186 | ``` 187 | equals 188 | ```Java 189 | int k = 97; 190 | ``` 191 | because the ASCII code for a is 97, k will hence become 97. 192 | 193 | ```Java 194 | char c = 90; 195 | ``` 196 | equals 197 | ```Java 198 | char c = 'Z'; 199 | ``` 200 | because the 90 equals Z in the ASCII table, c will hence hold the value Z. 201 | 202 | ##4.12## 203 | Some examples that illustrate casting. 204 | ```Java 205 | // i will be set to 65 206 | char c = 'A'; 207 | int i = (int)c; 208 | ``` 209 | ```Java 210 | // i will be set to 1000 211 | float f = 1000.34f; 212 | int i = (int)f; 213 | ``` 214 | ```Java 215 | // i will be set to 1000 216 | double d = 1000.34; 217 | int i = (int)d; 218 | ``` 219 | ```Java 220 | // c will be set to 'a' 221 | int i = 97; 222 | char c = (char)i; 223 | ``` 224 | 225 | ##4.13## 226 | ```Java 227 | public class Test { 228 | 229 | public static void main(String[] args) { 230 | char x = 'a'; 231 | char y = 'c'; 232 | 233 | // prints b 234 | System.out.println(++x); 235 | 236 | // prints c because the increment is done after usage 237 | System.out.println(y++); 238 | 239 | // prints -2 beacuse there is an auto conversion to int before the subraction 240 | System.out.println(x - y); 241 | } 242 | 243 | } 244 | ``` 245 | 246 | ##4.14## 247 | ```Java 248 | // c will become a lower case character in the range a to z 249 | char c = (char)(97 + Math.random() * 26); 250 | ``` 251 | 252 | ##4.15## 253 | ```Java 254 | System.out.println('a' < 'b'); // true 255 | System.out.println('a' <= 'A'); // false 256 | System.out.println('a' > 'b'); // false 257 | System.out.println('a' >= 'A'); // true 258 | System.out.println('a' == 'a'); // true 259 | System.out.println('a' != 'b'); // true 260 | ``` 261 | 262 | ##4.16## 263 | ```Java 264 | String s1 = "Welcome to Java"; 265 | String s2 = "Programming is fun"; 266 | String s3 = "Welcome to Java"; 267 | ``` 268 | Assuming the above lines will cause the following expressions to become the value indicated in the comments. 269 | ```Java 270 | s1 == s2 // false 271 | ``` 272 | ```Java 273 | s2 == s3 // false 274 | ``` 275 | ```Java 276 | s1.equals(s2) // false 277 | ``` 278 | ```Java 279 | s1.equals(s3) // true 280 | ``` 281 | ```Java 282 | s1.compareTo(s2) // a positive int 283 | ``` 284 | ```Java 285 | s2.compareTo(s3) // a negative int 286 | ``` 287 | ```Java 288 | s2.compareTo(s2) // 0 289 | ``` 290 | ```Java 291 | s1.charAt(0) // W 292 | ``` 293 | ```Java 294 | s1.indexOf('j') // -1 295 | ``` 296 | ```Java 297 | s1.indexOf("to") // 8 298 | ``` 299 | ```Java 300 | s1.lastIndexOf('a') // 14 301 | ``` 302 | ```Java 303 | s1.lastIndexOf("o", 15) // 9 304 | ``` 305 | ```Java 306 | s1.length() // 15 307 | ``` 308 | ```Java 309 | s1.substring(5) // me to Java 310 | ``` 311 | ```Java 312 | s1.substring(5, 11) // me to 313 | ``` 314 | ```Java 315 | s1.startsWith("Wel") // true 316 | ``` 317 | ```Java 318 | s1.endsWith("Java") // true 319 | ``` 320 | ```Java 321 | s1.toLowerCase() // welcome to java 322 | ``` 323 | ```Java 324 | s1.toUpperCase() // WELCOME TO JAVA 325 | ``` 326 | ```Java 327 | s1.concat(s2) // Welcome to JavaProgramming is fun 328 | ``` 329 | ```Java 330 | s1.contains(s2) // false 331 | ``` 332 | ```Java 333 | "\t Wel \t".trim() // Wel 334 | ``` 335 | 336 | ##4.17## 337 | Suppose that s1 and s2 are two strings. 338 | 339 | The following are all examples of correct string manipulations in Java. 340 | ```Java 341 | String s = "Welcome to Java"; 342 | String s3 = s1 + s2; 343 | s1 == s2 344 | s1.compareTo(s2); 345 | int i = s1.length(); 346 | ``` 347 | On the other hands so are the following all incorrect. 348 | ```Java 349 | String s3 = s1 - s2; 350 | s1 >= s2 351 | char c = s1(0); 352 | char c = s1.charAt(s1.length()); 353 | ``` 354 | 355 | ##4.18## 356 | ```Java 357 | public class CheckPoint_04_18 { 358 | 359 | public static void main(String[] args) { 360 | System.out.print("a)\t"); System.out.println("1" + 1); 361 | System.out.print("b)\t"); System.out.println('1' + 1); 362 | System.out.print("c)\t"); System.out.println("1" + 1 + 1); 363 | System.out.print("d)\t"); System.out.println("1" + (1 + 1)); 364 | System.out.print("e)\t"); System.out.println('1' + 1 + 1); 365 | 366 | } 367 | 368 | } 369 | ``` 370 | Above program will output: 371 | ``` 372 | a) 11 373 | b) 50 374 | c) 111 375 | d) 12 376 | e) 51 377 | ``` 378 | 379 | ##4.19## 380 | ```Java 381 | public class CheckPoint_04_19 { 382 | 383 | public static void main(String[] args) { 384 | String a = 1 + "Welcome " + 1 + 1; 385 | String b = 1 + "Welcome " + (1 + 1); 386 | String c = 1 + "Welcome " + ('\u0001' + 1); 387 | String d = 1 + "Welcome " + 'a' + 1; 388 | 389 | System.out.println(a); 390 | System.out.println(b); 391 | System.out.println(c); 392 | System.out.println(d); 393 | } 394 | 395 | } 396 | ``` 397 | Above program will output: 398 | ``` 399 | 1Welcome 11 400 | 1Welcome 2 401 | 1Welcome 2 402 | 1Welcome a1 403 | ``` 404 | 405 | ##4.20## 406 | **(a)** 407 | ```Java 408 | boolean isEqual = s1.equals(s2); 409 | ``` 410 | **(b)** 411 | ```Java 412 | boolean isEqual = s1.equalsIgnoreCase(s2); 413 | ``` 414 | **(c)** 415 | ```Java 416 | int x = s1.compareTo(s2); 417 | ``` 418 | **(d)** 419 | ```Java 420 | int x = s1.compareToIgnoreCase(s2); 421 | ``` 422 | **(e)** 423 | ```Java 424 | boolean b = s1.startsWith("AAA"); 425 | ``` 426 | **(f)** 427 | ```Java 428 | boolean b = s1.endsWith("AAA"); 429 | ``` 430 | **(g)** 431 | ```Java 432 | int x = s1.length(); 433 | ``` 434 | **(h)** 435 | ```Java 436 | char x = s1.charAt(0); 437 | ``` 438 | **(i)** 439 | ```Java 440 | String s3 = s1 + s2; 441 | ``` 442 | **(j)** 443 | ```Java 444 | String s3 = s1.substring(1); 445 | ``` 446 | **(k)** 447 | ```Java 448 | String s3 = s1.substring(1, 5); 449 | ``` 450 | **(l)** 451 | ```Java 452 | String s3 = s1.toLowerCase(); 453 | ``` 454 | **(m)** 455 | ```Java 456 | String s3 = s1.toUpperCase(); 457 | ``` 458 | **(n)** 459 | ```Java 460 | String s3 = s1.trim(); 461 | ``` 462 | **(o)** 463 | ```Java 464 | int x = s1.indexOf('e'); 465 | ``` 466 | **(p)** 467 | ```Java 468 | int x = s1.lastIndexOf("abc"); 469 | ``` 470 | 471 | ##4.21## 472 | We will get the answer by adding the first numbers in Set1, Set3, and Set4: 473 | ``` 474 | 1 + 4 + 8 = 13 475 | ``` 476 | 477 | ##4.22## 478 | The format specifier for outputting a boolean is %b. 479 | 480 | The format specifier for outputting a character is %c. 481 | 482 | The format specifier for outputting a decimal is %d. 483 | 484 | The format specifier for outputting a boolean is %f. 485 | 486 | The format specifier for outputting a string is %s. 487 | 488 | ##4.23## 489 | **(a)** 490 | ```Java 491 | System.out.printf("%5d %d\n", 1, 2, 3); 492 | ``` 493 | Erroneous code because there are three items to be printed but only two format specifiers. 494 | 495 | **(b)** 496 | ```Java 497 | System.out.printf("%5d %f", 1); 498 | ``` 499 | Erroneous code because there are two format specifiers but only one item to be printed. 500 | 501 | **(c)** 502 | ```Java 503 | System.out.printf("%5d %f\n", 1, 2); 504 | ``` 505 | Erroneous code because an int item is combined with a float format specifier. 506 | 507 | **(d)** 508 | ```Java 509 | System.out.printf("%.2f\n%0.3f\n", 1.23456, 2.34); 510 | ``` 511 | Erroneous because second format specifier tries to set the width to zero and this is not allowed. 512 | 513 | **(e)** 514 | ```Java 515 | System.out.printf("%08s\n", "Java"); 516 | ``` 517 | Erroneous because of the 0 in the format specifiers that need to be removed. 518 | 519 | ##4.24## 520 | ```Java 521 | public class CheckPoint_04_24 { 522 | 523 | public static void main(String[] args) { 524 | System.out.println("(a)"); 525 | System.out.printf("amount is %f %e\n", 32.32, 32.32); 526 | System.out.println(); 527 | 528 | System.out.println("(b)"); 529 | System.out.printf("amount is %5.2f%% %5.4e\n", 32.327, 32.32); 530 | System.out.println(); 531 | 532 | System.out.println("(c)"); 533 | System.out.printf("%6b\n", (1 > 2)); 534 | System.out.println(); 535 | 536 | System.out.println("(d)"); 537 | System.out.printf("%6s\n", "Java"); 538 | System.out.println(); 539 | 540 | System.out.println("(e)"); 541 | System.out.printf("%-6b%s\n", (1 > 2), "Java"); 542 | System.out.println(); 543 | 544 | System.out.println("(f)"); 545 | System.out.printf("%6b%-8s\n", (1 > 2), "Java"); 546 | System.out.println(); 547 | 548 | System.out.println("(g)"); 549 | System.out.printf("%,5d %,6.1f\n", 312342, 315562.932); 550 | System.out.println(); 551 | 552 | System.out.println("(h)"); 553 | System.out.printf("%05d %06.1f\n", 32, 32.32); 554 | } 555 | 556 | } 557 | ``` 558 | Above program will print the following (note that it was run on computer with Swedish locale settings for displaying numbers, might differ a bit on machines in other countries). 559 | ```Java 560 | (a) 561 | amount is 32,320000 3,232000e+01 562 | 563 | (b) 564 | amount is 32,33% 3,2320e+01 565 | 566 | (c) 567 | false 568 | 569 | (d) 570 | Java 571 | 572 | (e) 573 | false Java 574 | 575 | (f) 576 | falseJava 577 | 578 | (g) 579 | 312 342 315 562,9 580 | 581 | (h) 582 | 00032 0032,3 583 | ``` 584 | -------------------------------------------------------------------------------- /Chapter_04/Exercise_01/Exercise_04_01.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | /** 4 | * Exercise 4.1 from the book Introduction to Java Programming (10th). 5 | *

6 | * Geometry: area of a pentagon. 7 | * 8 | * @author Henrik Samuelsson, henrik.samuelsson(at)gmail.com 9 | */ 10 | 11 | public class Exercise_04_01 { 12 | 13 | public static void main(String[] args) { 14 | // get data about the pentagon from the user 15 | System.out.print("Enter the length from the center to a vertex: "); 16 | Scanner input = new Scanner(System.in); 17 | double r = input.nextDouble(); 18 | 19 | // calculate the area of the pentagon 20 | double s = 2 * r * Math.sin(Math.PI / 5); 21 | double area = (5 * s * s) / (4 * Math.tan(Math.PI / 5)); 22 | 23 | // format and present the result 24 | System.out.printf("The area of the pentagon is %.2f", area); 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /Chapter_04/Exercise_02/Exercise_04_02.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | /** 4 | * Exercise 4.2 from the book Introduction to Java Programming (10th). 5 | *

6 | * Geometry: great circle distance. 7 | *

8 | * Note that the solution is not exactly as in the book, the user will there 9 | * input the coordinates separated by a comma. My solution assumes that that 10 | * the data is separated by a blank space. 11 | * 12 | * @author Henrik Samuelsson, henrik.samuelsson(at)gmail.com 13 | */ 14 | 15 | public class Exercise_04_02 { 16 | 17 | public static void main(String[] args) { 18 | double lat1, lon1, lat2, lon2; // coordinates for two points 19 | final double R = 6_371.01; // radius of the earth 20 | double d; // distance between the two points 21 | 22 | // get the coordinates for the two points from the user 23 | Scanner input = new Scanner(System.in); 24 | System.out 25 | .println("Enter point 1 (latitude and longitude) in degrees: "); 26 | lat1 = input.nextDouble(); 27 | lon1 = input.nextDouble(); 28 | System.out 29 | .println("Enter point 2 (latitude and longitude) in degrees: "); 30 | lat2 = input.nextDouble(); 31 | lon2 = input.nextDouble(); 32 | 33 | // the values are currently i degrees will need to convert them to 34 | // radians to be able to us them in the trigonometric math methods 35 | lat1 = Math.toRadians(lat1); 36 | lon1 = Math.toRadians(lon1); 37 | lat2 = Math.toRadians(lat2); 38 | lon2 = Math.toRadians(lon2); 39 | 40 | // calculate the distance between the two point by the use of the 41 | // formula provided in the exercise description 42 | d = R 43 | * Math.acos(Math.sin(lat1) * Math.sin(lat2) + Math.cos(lat1) 44 | * Math.cos(lat2) * Math.cos(lon1 - lon2)); 45 | 46 | // print the result of the calculations 47 | System.out 48 | .println("The distance between the two points is " + d + "km"); 49 | } 50 | 51 | } 52 | -------------------------------------------------------------------------------- /Chapter_04/Exercise_04/Exercise_04_04.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | /** 4 | * Exercise 4.4 from the book Introduction to Java Programming (10th). 5 | *

6 | * Geometry: area of a hexagon. 7 | * 8 | * @author Henrik Samuelsson, henrik.samuelsson(at)gmail.com 9 | */ 10 | 11 | public class Exercise_04_04 { 12 | 13 | public static void main(String[] args) { 14 | Double side; // length of a side in the hexagon 15 | Double area; // the area of a hexagon 16 | 17 | // query the user for the length of the sides in the hexagon 18 | Scanner input = new Scanner(System.in); 19 | System.out.print("Enter the side: "); 20 | side = input.nextDouble(); 21 | 22 | // calculate the area of the hexagon using the formula provided in the 23 | // exercise instructions 24 | area = (6 * side * side ) / ( 4 * Math.tan(Math.PI/6)); 25 | 26 | // print the results of the calculation 27 | System.out.printf("The area of the hexagon is %.2f", area); 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /Chapter_05/Checkpoints_Ch_05.md: -------------------------------------------------------------------------------- 1 | # Checkpoint Answers Chapter 5 # 2 | ## 5.1 ## 3 | The condition count < 100 is always true at point A. 4 | 5 | The condition count < 100 can be both true and false at point B. 6 | 7 | The condition count < 100 is always false at point C. 8 | 9 | ## 5.2 ## 10 | The problem with initializing guess to zero is that the number that shall be guessed will sometimes be zero. This will cause the while to not even run one iteration and the player will never get to guess the number. 11 | 12 | ## 5.3 ## 13 | **(a)** 14 | The loop body will be run an infinite number of times. There will be no output because i is 1 all the time. 15 | 16 | **(b)** 17 | The loop body will be run an infinite number of times. There will be no output because i is 1 all the time. 18 | 19 | **(c)** 20 | The loop body will be run nine times and the output will be: 21 | ```Java 22 | 3 23 | 5 24 | 7 25 | 9 26 | ``` 27 | 28 | ## 5.4 ## 29 | The variable max will hold the largest number entered and number will hold the last number entered so the output will be: 30 | ```Java 31 | max is 5 32 | number 0 33 | ``` 34 | 35 | ## 5.5 ## 36 | This program will start with x equal to 80000000 and x is then increased by one again and again until it overflows after reaching 2147483647, x will be -2147483648 after the overflow. The while loop will now terminate and the output will be: 37 | ```Java 38 | x is -2147483648 39 | ``` 40 | 41 | ## 5.6 ## 42 | The program in this checkpoint will take numbers as input and keep track of the biggest number in the variable called "max". The last entered number is stored in the variable called "number". 43 | 44 | The output when running the program with the input 45 | ``` 46 | 2 3 4 5 0 47 | ``` 48 | will be: 49 | ``` 50 | max is 5 51 | number 0 52 | ``` 53 | 54 | ## 5.7 ## 55 | A do-while loop will always execute the body of the loop at least one time, this is not true for a while loop. 56 | 57 | The code from the checkpoint rewritten using a do-while loop: 58 | ```Java 59 | Scanner input = new Scanner(System.in); 60 | int sum = 0; 61 | int number; 62 | do { 63 | System.out.println("Enter an integer (the input ends if it is 0)"); 64 | number = input.nextInt(); 65 | sum += number; 66 | } while (number != 0); 67 | ``` 68 | 69 | ##5.8 ## 70 | ```Java 71 | for (int i = 0; i < 10; ++i) { 72 | sum += i; 73 | } 74 | ``` 75 | ```Java 76 | for (int i = 0; i < 10; i++) { 77 | sum += i; 78 | } 79 | ``` 80 | The above two loops will result in the same value in sum. This is so because the control variable i will have identical value, when used in the loop-continuiation-condition, regardless of ++i or i++ is used to increment i. 81 | 82 | ##5.9## 83 | The three parts usually present in a for loop control section are 84 | 1. Initial action used to initialize control variables. 85 | 2. Loop continuation condition that controls if the body of the loop will run or not, will usually be based on the control variables. 86 | 3. After iteration action which usually will alter the value of the control variable. 87 | 88 | A loop that prints the numbers for 1 to 100: 89 | ```Java 90 | for (i = 1; i <= 100; i++) { 91 | System.out.println(i); 92 | } 93 | ``` 94 | 95 | ##5.10## 96 | ```Java 97 | import java.util.Scanner; 98 | 99 | public class CheckPoint_05_10 { 100 | 101 | public static void main(String[] args) { 102 | Scanner input = new Scanner(System.in); 103 | int number, sum = 0, count; 104 | for (count = 0; count < 5; count++) { 105 | number = input.nextInt(); 106 | sum += number; 107 | } 108 | System.out.println("sum is " + sum); 109 | System.out.println("count is " + count); 110 | } 111 | 112 | } 113 | ``` 114 | The program in this checkpoint will sum integers until the control variable in the loop reaches the value five 5. This means that if the input to the program is 115 | ``` 116 | 2 3 4 5 0 117 | ``` 118 | so will the output be 119 | ``` 120 | sum is 14 121 | count is 5 122 | ``` 123 | 124 | ##5.11## 125 | The loop in this check point will iterate indefinitely and repeat the execution of the instructions in the body on each iteration. 126 | 127 | ##5.12## 128 | A variable that is declared in a for loop control section can not be used after the loops exists. 129 | 130 | ##5.13## 131 | A for loop, a while loop, and a do-while loop, that all do the same thing. 132 | ```Java 133 | long sum = 0; 134 | for (int i = 0; i <= 1000; i++) 135 | sum = sum + i; 136 | ``` 137 | ```Java 138 | long sum = 0; 139 | int i = 0; 140 | while (i <= 1000) { 141 | sum += i; 142 | i++; 143 | } 144 | ``` 145 | ```Java 146 | long sum = 0; 147 | int i = 0; 148 | do { 149 | sum += i 150 | i++; 151 | } while (i <= 1000); 152 | ``` 153 | 154 | ##5.14## 155 | **(a)** 156 | n iterations 157 | **(b)** 158 | n + 1 iterations 159 | **(c)** 160 | n - 5 iterations 161 | **(d)** 162 | (n-5)/3 iterations, rounded upwards if n-5 is not divisible by 3. 163 | 164 | n equal to 12 will for example result in 165 | ``` 166 | (12 - 5) / 3 = 7 / 3 = 2.33 167 | ``` 168 | which shall be rounded upwards resulting in 3 loop iterations. 169 | 170 | ##5.15## 171 | A for loop can be converted into a while loop. 172 | 173 | Some benefits of for loops are: 174 | - For certain type of problem, a for loop can be easier to construct and easier to read than the corresponding while loop. 175 | - It is a very good (perhaps the best) choice for counting loops. 176 | - All the control variables are nicely collected into one place when using for loops. 177 | 178 | ##5.16## 179 | A while loop can always be converted into a for loop. 180 | 181 | Below follows an illustration where a given while loop have been converted into a corresponding for loop. 182 | ```Java 183 | int i = 1; 184 | int sum = 0; 185 | while (sum < 10000) { 186 | sum = sum + i; 187 | i++; 188 | } 189 | ``` 190 | ```Java 191 | sum = 0; 192 | for (int i=1; sum < 1000; i++) { 193 | sum = sum + i; 194 | } 195 | ``` 196 | ##5.17## 197 | Fixed version of the code in this checkpoint follows. Had to guess a little on some of the fixes since there was no specification and instead just a piece of semi-random nonsense code. 198 | ```Java 199 | public class Test { 200 | public static void main(String[] args) { // missing static 201 | int sum = 0; // sum was not defined in original code 202 | for (int i = 0; i < 10; i++) // removed a semicolon here 203 | sum += i; 204 | 205 | int j = 10; // j was not defined 206 | int i = 5; // i was not defined 207 | if (i < j) // removed a semicolon 208 | System.out.println(i); // added missing semicolon 209 | else 210 | System.out.println(j); 211 | 212 | while (j < 10) // removed semicolon 213 | { 214 | j++; 215 | } 216 | 217 | do { 218 | j++; 219 | } while (j < 10); // added semicolon 220 | } 221 | } 222 | ``` 223 | 224 | ##5.18## 225 | **(a)** 226 | The problem with this code is a missing semicolon after the do-while loop at row 8. 227 | **(b)** 228 | The problem with this code is that the semicolon at line 3 shall be removed. 229 | 230 | ##5.19## 231 | When i is 0, the println statement is executed 0 times. 232 | When i is 1, the println statement is executed 1 time. 233 | When i is 2, the println statement is executed 2 times. 234 | . 235 | . 236 | . 237 | When i is 9, the println statement is executed 9 times. 238 | 239 | So, the total is 240 | ``` 241 | 0 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 = 45 242 | ``` 243 | 244 | ##5.20## 245 | **(a)** 246 | Output: 247 | ``` 248 | 0 0 1 0 1 2 0 1 2 3 249 | ``` 250 | **(b)** 251 | Output: 252 | ``` 253 | **** 254 | **** 255 | 2 **** 256 | 3 2 **** 257 | 4 3 2 **** 258 | ``` 259 | **(c)** 260 | Output: 261 | ``` 262 | 1xxx2xxx4xxx8xxx16xxx 263 | 1xxx2xxx4xxx8xxx 264 | 1xxx2xxx4xxx 265 | 1xxx2xxx 266 | 1xxx 267 | ``` 268 | **(d)** 269 | Output: 270 | ``` 271 | 1G 272 | 1G3G 273 | 1G3G5G 274 | 1G3G5G7G 275 | 1G3G5G7G9G 276 | ``` 277 | 278 | ##5.21## 279 | The suggested optimization is incorrect since it will not spot the gcd when entering two identical numbers. 280 | 281 | ##5.22## 282 | The code will not compile if we remove the cast. This is because the code is semi dangerous since information might be lost when we convert an int to a char. An int can hold a wider range of numbers than a char. 283 | 284 | But no information will be lost in this case because the numbers are always small enough to fit in a char. 285 | 286 | So there is no problem with our code but we still need to make a cast to a char to indicate to compiler that we are aware of what we are doing. 287 | 288 | ##5.23## 289 | The loop will in each iteration divide the variable "decimal" by 16. The result will be truncated since this is how integer division works in Java. The execution stops when "decimal" is 0. 290 | 291 | Assume that "decimal" starts at 245: 292 | ``` 293 | 245 / 16 = 15 294 | 15 / 16 = 0 295 | ``` 296 | There will hence be 2 iterations in this case. 297 | 298 | Assume that "decimal" starts at 3245: 299 | ``` 300 | 3245 / 16 = 202 301 | 202 / 16 = 12 302 | 12 / 16 = 0 303 | ``` 304 | There will hence be 3 iterations in this case. 305 | 306 | ##5.24## 307 | The keyword break can be used in a loop to exit the loop. 308 | 309 | The keyword continue is used in a loop to terminate the current iteration and move execution directly to the loop control section. 310 | 311 | The keyword break is used in the following code: 312 | ```Java 313 | int balance = 10; 314 | while (true) { 315 | if (balance < 9) 316 | break; 317 | balance = balance - 9; 318 | } 319 | 320 | System.out.println("Balance is " + balance); 321 | ``` 322 | Balance will become 1 after the first iteration. This causes a break out of the loop and the output will be: 323 | ``` 324 | Balance is 1 325 | ``` 326 | The keyword continue is used in the following code: 327 | ```Java 328 | int balance = 10; 329 | while (true) { 330 | if (balance < 9) 331 | continue; 332 | balance = balance - 9; 333 | } 334 | 335 | System.out.println("Balance is " + balance); 336 | ``` 337 | The loop in this second example will never end because continue is mistakenly used instead of break. 338 | 339 | ##5.25## 340 | The problem with the while loop version (see the book) is that the varible called "i" will not be incremented as it should when it is divisible by three. This is because the continune will cause an jump to the beginning of the loop. 341 | 342 | We need to add the increment of "i" in one extra place: 343 | ```Java 344 | int i = 0; 345 | while (i < 4) { 346 | if (i % 3 == 0) { 347 | i++; 348 | continue; 349 | } 350 | sum += i; 351 | i++; 352 | } 353 | ``` 354 | 355 | ##5.26## 356 | The program TestBreak in Listing 5.12 rewritten so that the break is no longer used: 357 | ```Java 358 | public class TestBreak { 359 | 360 | public static void main(String[] args) { 361 | int sum = 0; 362 | int number = 0; 363 | 364 | while (number < 20 && sum < 100) { 365 | number++; 366 | sum += number; 367 | } 368 | 369 | System.out.println("The number is " + number); 370 | System.out.println("The sum is " + sum); 371 | } 372 | 373 | } 374 | ``` 375 | 376 | The program TestContinue in Listing 5.13 rewritten so that the continue is no longer used: 377 | ```Java 378 | public class TestContinue { 379 | 380 | public static void main(String[] args) { 381 | int sum = 0; 382 | int number = 0; 383 | 384 | while (number < 20) { 385 | number++; 386 | if (number != 10 && number != 11) 387 | sum += number; 388 | } 389 | 390 | System.out.println("The sum is " + sum); 391 | } 392 | 393 | } 394 | ``` 395 | 396 | ##5.27## 397 | **(a)** 398 | The second print statement will be executed after the break. The output will be: 399 | ``` 400 | 1 401 | 2 402 | 1 403 | 2 404 | 2 405 | 3 406 | ``` 407 | 408 | **(b)** 409 | The increment of j will be executed after the continue. The output will be: 410 | ``` 411 | 1 412 | 2 413 | 1 414 | 2 415 | 2 416 | 3 417 | ``` 418 | 419 | -------------------------------------------------------------------------------- /Chapter_05/Exercise_01/Exercise_05_01.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | /** 4 | * Exercise 5.1 from the book Introduction to Java Programming (10th). 5 | * 6 | * @author Henrik Samuelsson, henrik.samuelsson(at)gmail.com 7 | */ 8 | 9 | public class Exercise_05_01 { 10 | 11 | public static void main(String[] args) { 12 | int userInput; 13 | int numberOfNegatives = 0; 14 | int numberOfPositives = 0; 15 | double total = 0; 16 | double average = 0; 17 | 18 | // create a scanner 19 | Scanner input = new Scanner(System.in); 20 | 21 | // get input from user repeatedly 22 | System.out.print("Enter an integer, the input ends if it is 0: "); 23 | userInput = input.nextInt(); 24 | while (userInput != 0) { 25 | if(userInput > 0) 26 | numberOfPositives++; 27 | else 28 | numberOfNegatives++; 29 | total += userInput; 30 | userInput = input.nextInt(); 31 | } 32 | 33 | // have all user input now, calculate the average 34 | average = total / (numberOfNegatives + numberOfPositives); 35 | 36 | // present the result 37 | System.out.println("The number of positives is " + numberOfPositives); 38 | System.out.println("The number of negatives is " + numberOfNegatives); 39 | System.out.println("The total is " + total); 40 | System.out.println("The average is " + average); 41 | } 42 | 43 | } 44 | -------------------------------------------------------------------------------- /Chapter_05/Exercise_02/Exercise_05_02.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | /** 4 | * Exercise 5.2 from the book Introduction to Java Programming (10th). 5 | * 6 | * @author Henrik Samuelsson, henrik.samuelsson(at)gmail.com 7 | */ 8 | 9 | public class Exercise_05_02 { 10 | 11 | public static void main(String[] args) { 12 | final int NUMBER_OF_QUESTIONS = 10; // number of questions 13 | int correctCount = 0; // count the number of correct answers 14 | int count = 0; // count the number of questions 15 | long startTime = System.currentTimeMillis(); 16 | String output = ""; // output string is initially empty 17 | Scanner input = new Scanner(System.in); 18 | 19 | while (count < NUMBER_OF_QUESTIONS) { 20 | // generate two random single-digit integers between 1 and 15 21 | int number1 = (int) (Math.random() * 15) + 1; 22 | int number2 = (int) (Math.random() * 15) + 1; 23 | 24 | // prompt the student to answer “What is number1 + number2?” 25 | System.out.print("What is " + number1 + " + " + number2 + "? "); 26 | int answer = input.nextInt(); 27 | 28 | // grade the answer and display the result 29 | if (number1 + number2 == answer) { 30 | System.out.println("You are correct!"); 31 | correctCount++; 32 | } else 33 | System.out.println("Your answer is wrong.\n" + number1 + " + " 34 | + number2 + " should be " + (number1 + number2)); 35 | 36 | // Increase the count 37 | count++; 38 | 39 | output += "\n" + number1 + "+" + number2 + "=" + answer 40 | + ((number1 + number2 == answer) ? " correct" : " wrong"); 41 | } 42 | 43 | long endTime = System.currentTimeMillis(); 44 | long testTime = endTime - startTime; 45 | 46 | System.out.println("Correct count is " + correctCount 47 | + "\nTest time is " + testTime / 1000 + " seconds\n" + output); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /Chapter_05/Exercise_03/Exercise_05_03.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Exercise 5.3 from the book Introduction to Java Programming (10th). 3 | *

4 | * Conversion from kilograms to pounds. 5 | * 6 | * @author Henrik Samuelsson, henrik.samuelsson(at)gmail.com 7 | */ 8 | 9 | public class Exercise_05_03 { 10 | 11 | public static void main(String[] args) { 12 | 13 | // print the heading of the table 14 | String kilograms = "Kilograms"; 15 | String pounds = "Pounds"; 16 | System.out.printf("%-10s %10s %n", kilograms, pounds); 17 | 18 | // print the data in the table by the use of a loop 19 | // will left-justify the kilograms and right-justify the pounds 20 | for (int i = 1; i < 200; i = i + 2) { 21 | System.out.printf("%-10.0f %10.1f %n", (double) i, i * 2.2); 22 | } 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /Chapter_05/Exercise_04/Exercise_05_04.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Exercise 5.4 from the book Introduction to Java Programming (10th). 3 | *

4 | * Conversion from miles to kilometers. 5 | * 6 | * @author Henrik Samuelsson, henrik.samuelsson(at)gmail.com 7 | */ 8 | 9 | public class Exercise_05_04 { 10 | 11 | public static void main(String[] args) { 12 | // print the heading of the table 13 | String miles = "Miles"; 14 | String km = "Kilometers"; 15 | System.out.printf("%-10s %-10s %n", miles, km); 16 | 17 | // print the data in the table by the use of a loop 18 | for (int i = 1; i <= 10; i++) { 19 | System.out.printf("%-10.0f %-10.3f %n", (double) i, i * 1.609); 20 | } 21 | } 22 | 23 | } 24 | -------------------------------------------------------------------------------- /Chapter_05/Exercise_05/Exercise_05_05.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Exercise 5.5 from the book Introduction to Java Programming (10th). 3 | *

4 | * Conversion from kilograms to pounds and pounds to kilograms. 5 | * 6 | * @author Henrik Samuelsson, henrik.samuelsson(at)gmail.com 7 | */ 8 | 9 | public class Exercise_05_05 { 10 | 11 | public static void main(String[] args) { 12 | // print the heading of the table 13 | String kg = "Kilograms"; 14 | String p = "Pounds"; 15 | System.out.printf("%-10s %-6s | %-10s %-10s %n", kg, p, p, kg); 16 | 17 | // print the data in the table by the use of a loop 18 | for (int i = 1, j = 20; i < 200; i += 2, j += 5) { 19 | System.out.printf("%-10.0f %6.1f | %-10.0f %9.2f %n", 20 | (double) i, i * 2.2, (double) j, j / 2.2); 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Chapter_06/Checkpoints_Ch_06.md: -------------------------------------------------------------------------------- 1 | # Checkpoint Answers Chapter 6 # 2 | ## 6.1 ## 3 | Some of the benefits of using methods are: 4 | - Faster development time by reuse of code 5 | - Reduces complexity of the code 6 | - Makes the code easier to maintain 7 | 8 | ## 6.2 ## 9 | A number of properties about a given method need to be decided before it can be defined: 10 | - What modifiers are suitable 11 | - The type of the value, if any, that shall be returned 12 | - The name of the method 13 | - What parameters are needed as data for the method to be able to do its work 14 | - What the method is intended to do and how it shall do it 15 | 16 | When all of the above decisions have been made so can the method be defined. An example of a method definition looks like this: 17 | ```Java 18 | public static int max(int num1, int num2) { 19 | if (num1 > num2) 20 | return num1; 21 | else 22 | return num2; 23 | } 24 | ``` 25 | The keywords public and static are examples of modifiers. The following int indicates that the method will return an int after being executed. The name of the method is max and it takes two int's as data parameters. 26 | 27 | The part between the braces is the body of the loop and it this part that does the actual work. In this case so will it be checked which of the parameters that is biggest and the value of this parameter is returned to the caller of the method. 28 | 29 | A method is invoked by using the name of the method combined with the same number and type of actual parameter values as in the definition of the method. 30 | 31 | An invocation of the max method can for example look like this: 32 | ```Java 33 | int biggestNumber = max(15, 42); 34 | ``` 35 | ## 6.3 ## 36 | The body of the max method can be shortened by the use of the conditional operator. 37 | ```Java 38 | return ( num1 > num2 ) ? num1 : num2; 39 | ``` 40 | ## 6.4 ## 41 | A call to a method with a void return type is always a statement itself. A call to a value-returning method can also be a statement by itself. 42 | ## 6.5 ## 43 | The return type of the main method is void. 44 | ## 6.6 ## 45 | Omitting a return statement in a value-returning method will cause a syntax error. 46 | 47 | It is possible to have a return statement in a void function, this will end the execution of the method. 48 | 49 | It is a syntax error to have a void function return a value. 50 | ## 6.7 ## 51 | The term parameter is used to refer to the list of variables in a method declaration. 52 | 53 | The term argument refers to the actual values that are passed in when the method is invoked. 54 | 55 | A method signature is made up of the name and the parameter list of a given method. Note that the return type is not part of the method signature. 56 | ## 6.8 ## 57 | **(a)** 58 | ```Java 59 | public static double getCommission(double SalesAmount, double commissionRate) 60 | ``` 61 | **(b)** 62 | ```Java 63 | public static void displayCalendar(int mont, int year) 64 | ``` 65 | **(c)** 66 | ```Java 67 | public static double squareRoot(double num) 68 | ``` 69 | **(d)** 70 | ```Java 71 | public static boolean isEven(int num) 72 | ``` 73 | **(e)** 74 | ```Java 75 | public static void displayMessage(String message, int count) 76 | ``` 77 | **(f)** 78 | ```Java 79 | public static double monthlyPayment(double loanAmount, int years, double interestRate) 80 | ``` 81 | **(g)** 82 | ```Java 83 | public static char toUpperCase(char letter) 84 | ``` 85 | ## 6.9 ## 86 | ```Java 87 | public class Test { 88 | public static method1(int n, m) { 89 | n += m; 90 | method2(3.4); 91 | } 92 | 93 | public static int method2(int n) { 94 | if (n > 0) 95 | return 1; 96 | else if (n == 0) 97 | return 0; 98 | else if (n < 0) 99 | return -1; 100 | } 101 | } 102 | ``` 103 | There are multiple errors in the above code. 104 | 105 | The return type for method1 is missing, it shall be void. 106 | 107 | The type of the second parameter in method1 is missing, it shall most likely be of type int. 108 | 109 | The second method, named method2, is in method1 invoked with a double argument but the parameter of method2 is of typ int. This causes an syntax error, this can be fixed by changing the method signature of method2. 110 | 111 | The compiler will think that it is possible for method2 to not return any value in some situations. Remove the last if to make the code compile without changing the behavior. 112 | 113 | A fully corrected code look like this: 114 | ```Java 115 | public class Test { 116 | public static void method1(int n, int m) { 117 | n += m; 118 | method2(3.4); 119 | } 120 | 121 | public static int method2(double n) { 122 | if (n > 0) 123 | return 1; 124 | else if (n == 0) 125 | return 0; 126 | else 127 | return -1; 128 | } 129 | } 130 | ``` 131 | ## 6.10 ## 132 | ```Java 133 | public class Test { 134 | public static double method(double i, double j) { 135 | while (i < j) { 136 | j--; 137 | } 138 | 139 | return j; 140 | } 141 | } 142 | ``` 143 | ## 6.11 ## 144 | The arguments passed to a method must be passed in the same order as in the method signature and the types of all argument must be compatible to the formal parameters in the method signature. 145 | 146 | An argument can have the same name as a formal parameter, this is for example a valid program: 147 | ```Java 148 | public class CheckPoint_06_11 { 149 | 150 | public static void main(String[] args) { 151 | int i = 5; 152 | int j = 10; 153 | printSum(i, j); 154 | } 155 | 156 | public static void printSum(int i, int j) { 157 | System.out.println(i + j); 158 | } 159 | 160 | } 161 | ``` 162 | ## 6.12 ## 163 | There is a mistake when calling the method. The order of the two parameters have been mixed up. 164 | 165 | Another mistake is in the the body of nPrintln where n is declared even though n is used as an name for one of the formal parameters. 166 | ## 6.13 ## 167 | By definition, pass by value means you are making a copy in memory of the actual parameter's value that is passed in. All work done in the method is then done on this copy. 168 | 169 | **(a)** 170 | Output is: 171 | ``` 172 | 0 173 | ``` 174 | It is only the local copy that is altered by the method, the original is left unchanged. 175 | 176 | **(b)** 177 | Output is: 178 | ``` 179 | 2 180 | 2 4 181 | 2 4 8 182 | 2 4 8 16 183 | 2 4 8 16 32 184 | 2 4 8 16 32 64 185 | ``` 186 | 187 | **(c)** 188 | Output is: 189 | ``` 190 | Before the call, variable times is 3 191 | n = 3 192 | Welcome to Java! 193 | n = 2 194 | Welcome to Java! 195 | n = 1 196 | Welcome to Java! 197 | After the call, variable times is 3 198 | ``` 199 | What happens is that the value of the variable times is copied to n. The value of n is then changed but the value of times stays unchanged. 200 | 201 | **(d)** 202 | Output is: 203 | ``` 204 | 205 | 1 206 | 2 1 207 | 2 1 208 | 4 2 1 209 | i is 5 210 | ``` 211 | ## 6.14 ## 212 | Stack content just before the max-method is invoked: 213 | ``` 214 | | | 215 | | max 0 | 216 | ------------- 217 | ``` 218 | 219 | Stack content just entering the max-method, we use more stack now because max need to store some data: 220 | ``` 221 | | | 222 | | max 0 | 223 | | value2 2 | 224 | | value1 1 | 225 | ------------- 226 | | max 0 | 227 | ------------- 228 | ``` 229 | 230 | Stack content just before return from the max-method, that now have done some writing in the memory: 231 | ``` 232 | | | 233 | | max 0 | 234 | | value2 2 | 235 | | value1 1 | 236 | ------------- 237 | | max 0 | 238 | ------------- 239 | ``` 240 | 241 | Stack content after return from the max-method, the memory needed by the max-method is now free again: 242 | ``` 243 | | | 244 | | max 0 | 245 | ------------- 246 | ``` 247 | ## 6.15 ## 248 | Method overloading in Java occurs when two or more methods in the same class have the exact same name but different parameters. 249 | 250 | It is allowed to have identical method names, as long as the parameter types are sufficintly different. 251 | 252 | It is not allowed to have overloaded methods where the difference is just based on return types or modifiers. 253 | 254 | # 6.16 # 255 | Both methods defined in this check point have the exact same signature, this is not allowed since there is no way to know which of the methods to invoke. 256 | 257 | # 6.17 # 258 | **(a)** 259 | The second method will be invoked in this case. 260 | 261 | **(b)** 262 | The second method will be invoked in this case. 263 | 264 | **(c)** 265 | The first method will be invoked in this case. 266 | 267 | # 6.18 # 268 | A local variable in Java is a variable that is declared within the body of a method. This variable can be used variable only within that method. Other methods in the class are not even aware that the variable exists. 269 | 270 | # 6.19 # 271 | The scope of a local variable starts from its declaration and continues to the end of the block that contains the variable. 272 | -------------------------------------------------------------------------------- /Chapter_06/Exercise_01/Exercise_06_01.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Exercise 6.1 from the book Introduction to Java Programming (10th). 3 | * 4 | * @author Henrik Samuelsson, henrik.samuelsson(at)gmail.com 5 | */ 6 | 7 | public class Exercise_06_01 { 8 | 9 | public static void main(String[] args) { 10 | for (int nr = 1; nr <= 100; nr++) { 11 | System.out.printf("%5d ", getPentagonalNumber(nr)); 12 | if (nr % 10 == 0) 13 | System.out.println(""); 14 | } 15 | } 16 | 17 | public static int getPentagonalNumber(int n) { 18 | return n * (3 * n - 1) / 2; 19 | } 20 | 21 | } 22 | -------------------------------------------------------------------------------- /Chapter_06/Exercise_02/Exercise_06_02.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | /** 4 | * Exercise 6.2 from the book Introduction to Java Programming (10th). 5 | * 6 | * @author Henrik Samuelsson, henrik.samuelsson(at)gmail.com 7 | */ 8 | 9 | public class Exercise_06_02 { 10 | 11 | public static void main(String[] args) { 12 | Scanner input = new Scanner(System.in); 13 | System.out.print("Enter an integer: "); 14 | long in = input.nextLong(); 15 | int sum = sumDigits(in); 16 | System.out.println("The sum of the digits in " + in + " is " + sum); 17 | } 18 | 19 | public static int sumDigits(long n) { 20 | int sum = 0; 21 | while (n != 0) { 22 | sum += n % 10; 23 | n /= 10; 24 | } 25 | return sum; 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /Chapter_06/Exercise_04/Exercise_06_04.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | /** 4 | * Exercise 6.4 from the book Introduction to Java Programming (10th). 5 | * 6 | * @author Henrik Samuelsson, henrik.samuelsson(at)gmail.com 7 | */ 8 | 9 | public class Exercise_06_04 { 10 | 11 | public static void main(String[] args) { 12 | Scanner input = new Scanner(System.in); 13 | System.out.print("Enter an integer to be reversed: "); 14 | int in = input.nextInt(); 15 | reverse(in); 16 | } 17 | 18 | public static void reverse(int number) { 19 | int reversedNumber = 0; 20 | do { 21 | reversedNumber = reversedNumber * 10 + number % 10; 22 | number = number / 10; 23 | } while (number != 0); 24 | System.out.println(reversedNumber); 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /Chapter_07/Checkpoints_Ch_07.md: -------------------------------------------------------------------------------- 1 | # Checkpoint Answers Chapter 7 # 2 | ## 7.1 ## 3 | An array reference variable is declared by the use of brackets. For example, the following code declares a variable myList that references an array of double elements. 4 | ```Java 5 | double[] myList; 6 | ``` 7 | An array reference variable is used as a handle to access the content of the array, but just creating this variable will not allocate any space in memory for the array. Memory for the array is allocated by using the keyword new. If we need to be able to store 10 doubles so shall we write like in the following code. 8 | ```Java 9 | myList = new double[10]; 10 | ``` 11 | If we know the values that shall go in the array before it is created so is it also possible to use a shorthand notation. This is called an array initializer that will allocate memory and create the array reference. 12 | ```Java 13 | double[] myList = {1.9, 2.4, 3.4, 3.5, 1.0, 5.7, 3.1, 1.1, 8.7, 4.6}; 14 | ``` 15 | ## 7.2 ## 16 | The memory needed for an array is allocated when the array is created, by the use of the new keyword or using an array initializer. 17 | ## 7.3 ## 18 | The code in this check point will output: 19 | ``` 20 | x is 60 21 | The size of numbers is 30 22 | ``` 23 | The size of an array can not be changed after it is set. 24 | ## 7.4 ## 25 | **(a)** 26 | True 27 | 28 | **(b)** 29 | False 30 | 31 | **(c)** 32 | True 33 | 34 | **(d)** 35 | False 36 | ## 7.5 ## 37 | The following are both valid ways to define an array: 38 | ```Java 39 | double d[] = new double[30]; 40 | float f[] = {2.3, 4.5, 6.6}; 41 | ``` 42 | ## 7.6 ## 43 | Each element in an array is associated with an index that can be used for accessing the element. 44 | 45 | Example: 46 | ```Java 47 | int i[] = {1, 5, 8, 2}; 48 | int myInt = i[1]; // myInt becomes 5 49 | ``` 50 | ## 7.7 ## 51 | The type of an array index is int. 52 | 53 | The lowest index of an array is 0. 54 | 55 | The third element of an array named a is represented by `a[2]`. 56 | ## 7.8 ## 57 | **(a)** 58 | ```Java 59 | double[] listA = new double[10]; 60 | ``` 61 | 62 | **(b)** 63 | ```Java 64 | listB[listB.length() - 1] = 5.5; 65 | ``` 66 | 67 | **(c)** 68 | ```Java 69 | System.out.println(listC[0] + listC[1]); 70 | ``` 71 | 72 | **(d)** 73 | ```Java 74 | int sum = 0; 75 | for (int e : listD) { 76 | sum += e; 77 | } 78 | ``` 79 | 80 | **(e)** 81 | ```Java 82 | int min = listE[0]; 83 | for (int e : listE) { 84 | if (e < min) { 85 | min = e; 86 | } 87 | } 88 | ``` 89 | 90 | **(f)** 91 | ```Java 92 | System.out.println(listF[(int)(Math.random()listF.length)]); 93 | ``` 94 | 95 | **(g)** 96 | ```Java 97 | double[] ListG = {3.5, 5.5, 4.52, 5.6}; 98 | ``` 99 | ## 7.9 ## 100 | Attempts to access an array element with an invalid index will cause an ArrayIndexOutOfBoundsException to be thrown. 101 | ## 7.10 ## 102 | The creation of the array is wrong, the line 103 | ```Java 104 | double[100] r; 105 | ``` 106 | should be 107 | ```Java 108 | double[] r = new double[100]; 109 | ``` 110 | 111 | The usage of length in the header of the for loop should be 112 | ```Java 113 | r.length 114 | ``` 115 | 116 | There is a semicolon after the for loop that shall be removed. 117 | 118 | The array assignment expression uses parentheses where it should be square brackets. 119 | 120 | The call to the random function misses parentheses. 121 | 122 | A completely corrected program looks like this: 123 | ```Java 124 | public class Test { 125 | public static void main(String[] args) { 126 | double[] r = new double[100]; 127 | 128 | for (int i = 0; i < r.length; i++) 129 | r[i] = Math.random() * 100; 130 | } 131 | } 132 | ``` 133 | 134 | ## 7.11 ## 135 | The first loop will in the first iteration copy the value of `list[0]` to `list[1]`. Which means that both `list[0]` and `list[1]` will be 1. The second iteration will the copy the value of `list[1]` to `list[2]`. This continues and by the end of the first loop so will the every value in list be set to 1. 136 | 137 | The second loop just prints the content of the array, the output will hence be 138 | ``` 139 | 1 1 1 1 1 1 140 | ``` 141 | 142 | ## 7.12 ## 143 | No the new version of the code, presented in the check point, will not work since it would be possible to get the same card more than once. 144 | 145 | ## 7.13 ## 146 | The following code will copy the content of the array called "source" to the other array called "target". 147 | ```Java 148 | int[] source = {3, 4, 5}; 149 | int[] target = new int[3]; 150 | System.arraycopy(source, 0, target, 0, source.length); 151 | ``` 152 | 153 | ## 7.14 ## 154 | The following code will not really resize the array. 155 | ```Java 156 | int[] myList; 157 | myList = new int[10]; 158 | 159 | . 160 | . 161 | . 162 | 163 | // Sometime later you want to assign a new array to myList 164 | myList = new int[20]; 165 | ``` 166 | What happens it that the reference is moved so that it references another part of the memory, that is big enough to hold 20 elements. This means that the 10 first elements will no longer be the same unless they are somehow copied. 167 | 168 | ## 7.15 ## 169 | The problem is that the content is swapped two times so wo will end up with the same order of elements as we started with. 170 | 171 | The trick to fix the problem is to stop the for loop when we have reached the midpoint of the array. A fixed version looks like this. 172 | ```Java 173 | int[] list = {1, 2, 3, 5, 4}; 174 | for (int i = 0, j = list.length - 1; i < list.length / 2; i++, j--) { 175 | // Swap list[i] with list[j] 176 | int temp = list[i]; 177 | list[i] = list[j]; 178 | list[j] = temp; 179 | } 180 | ``` 181 | 182 | ## 7.16 ## 183 | Arrays are passed as references when used as arguments to methods. This reduces the amount of information that needs to be passed. Note that this means that if the method changes the content of the array so will this also affect corresponding array content existing outside of the method block. 184 | 185 | ## 7.17 ## 186 | **(a)** 187 | ```Java 188 | public class Test { 189 | public static void main(String[] args) { 190 | int number = 0; 191 | int[] numbers = new int[1]; 192 | m(number, numbers); 193 | System.out.println("number is " + number + " and numbers[0] is " 194 | + numbers[0]); 195 | } 196 | 197 | public static void m(int x, int[] y) { 198 | x = 3; 199 | y[0] = 3; 200 | } 201 | } 202 | ``` 203 | The program from above will output: 204 | ``` 205 | number is 0 and numbers[0] is 3 206 | ``` 207 | 208 | **(b)** 209 | ```Java 210 | public class Test { 211 | public static void main(String[] args) { 212 | int[] list = { 1, 2, 3, 4, 5 }; 213 | reverse(list); 214 | for (int i = 0; i < list.length; i++) 215 | System.out.print(list[i] + " "); 216 | } 217 | 218 | public static void reverse(int[] list) { 219 | int[] newList = new int[list.length]; 220 | for (int i = 0; i < list.length; i++) 221 | newList[i] = list[list.length - 1 - i]; 222 | list = newList; 223 | } 224 | } 225 | ``` 226 | The program from above will output: 227 | ``` 228 | 1 2 3 4 5 229 | ``` 230 | The reason that the output is not reversed is that the reference called "list" used inside the reverse method is a copy of the "list" in the main method, these two references are not the same even tough they have the same name. 231 | 232 | "list" inside reverse will reference memory where the content is in deed reversed when we reach the end of method. But the other "list" in main will still reference another chunk of memory whit unaltered content. 233 | 234 | ## 7.18 ## 235 | TODO - Skipping this one because it means to much work right now. 236 | 237 | ## 7.19 ## 238 | Each of the following code snippets are incorrect. 239 | 240 | ```Java 241 | public static void print(String... strings, double... numbers) 242 | ``` 243 | The problem with above code is that it is only allowed to have a single variable-length parameter. 244 | 245 | ```Java 246 | public static void print(double... numbers, String name) 247 | ``` 248 | The problem with the above is that a variable-length parameter is only allowed to be placed last int the parameter list. 249 | 250 | ```Java 251 | public static double... print(double d1, double d2) 252 | ``` 253 | The problem with the above code is that it is not allowed to return a variable-length type from a method. 254 | 255 | ## 7.20 ## 256 | The printMax method from Listing 7.5 can be invoked like this 257 | ```Java 258 | printMax(1, 2, 2, 1, 4); 259 | printMax(new double[]{1, 2, 3}); 260 | ``` 261 | but not like this 262 | ```Java 263 | printMax(new int[]{1, 2, 3}); 264 | ``` 265 | because the types does not match and there is no automatic conversion in this case. 266 | 267 | ## 7.21 ## 268 | Replace 269 | ```Java 270 | (low + high) / 2 271 | ``` 272 | with 273 | ```Java 274 | (-low + high) / 2 + low 275 | ``` 276 | 277 | ## 7.26 ## 278 | The java.util.Arrays.sort method is overloaded so that it can be used to sort arrays of any primitive type except boolean. This sort method will not create a new method, the elements will be sorted into the array that is given as argument to the method. 279 | 280 | ## 7.29 ## 281 | These are all valid ways to declare the main method 282 | ```Java 283 | public static void main(String[] args) 284 | public static void main(String args[]) 285 | public static void main(String[] x) 286 | public static void main(String x[]) 287 | ``` 288 | The name of the parameter does not matter and there are two ways of placing the square brackets when declaring an array in Java. 289 | 290 | This is not a valid ways to declare main since the public access modifier must be applied to make the method visible to the world 291 | ```Java 292 | static void main(String x[]) 293 | ``` 294 | 295 | ## 7.30 ## 296 | **(1)** 297 | ``` 298 | Number of strings is 4 299 | I 300 | have 301 | a 302 | dream 303 | ``` 304 | 305 | **(2)** 306 | ``` 307 | Number of strings is 1 308 | 1 2 3 309 | ``` 310 | 311 | **(3)** 312 | ``` 313 | Number of strings is 0 314 | ``` 315 | -------------------------------------------------------------------------------- /Chapter_07/Exercise_02/Exercise_07_02.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | /** 4 | * Exercise 7.2 from the book Introduction to Java Programming (10th). 5 | *

6 | * Reverse the numbers entered. 7 | * 8 | * @author Henrik Samuelsson, henrik.samuelsson(at)gmail.com 9 | */ 10 | public class Exercise_07_02 { 11 | 12 | public static void main(String[] args) { 13 | final int NUMBER_COUNT = 10; 14 | int[] numbers = new int[NUMBER_COUNT]; 15 | 16 | Scanner input = new Scanner(System.in); 17 | 18 | // get the numbers from the user 19 | for (int i = 0; i < NUMBER_COUNT; i++) { 20 | numbers[i] = input.nextInt(); 21 | } 22 | 23 | // print all the numbers in reverse 24 | for (int i = NUMBER_COUNT; i > 0; i--) { 25 | System.out.print(numbers[i - 1] + " "); 26 | } 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /Chapter_07/Exercise_03/Exercise_07_03.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | /** 4 | * Exercise 7.3 from the book Introduction to Java Programming (10th). 5 | * 6 | * @author Henrik Samuelsson, henrik.samuelsson(at)gmail.com 7 | */ 8 | 9 | public class Exercise_07_03 { 10 | final static int MAX = 100; 11 | 12 | public static void main(String[] args) { 13 | int[] inputStorage = new int[MAX]; 14 | int userInput; 15 | Scanner inputScanner = new Scanner(System.in); 16 | 17 | System.out.print("Enter the integers between 1 and " + MAX + ": "); 18 | userInput = inputScanner.nextInt(); 19 | while (userInput != 0) { 20 | inputStorage[userInput - 1]++; 21 | userInput = inputScanner.nextInt(); 22 | } 23 | 24 | for (int i = 0; i < 100; i++) { 25 | if (inputStorage[i] == 1) 26 | System.out.println(i + 1 + " occurs 1 time"); 27 | else if (inputStorage[i] > 1) 28 | System.out.println(i + 1 + " occurs " + inputStorage[i] 29 | + " times"); 30 | } 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /Chapter_07/Exercise_19/Exercise_07_19.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | /** 4 | * Exercise 7.19 from the book Introduction to Java Programming (10th). 5 | * 6 | * @author Henrik Samuelsson, henrik.samuelsson(at)gmail.com 7 | */ 8 | 9 | public class Exercise_07_19 { 10 | 11 | public static void main(String[] args) { 12 | // create a scanner to be used for getting input 13 | Scanner input = new Scanner(System.in); 14 | 15 | // get number of elements in the list from the user 16 | System.out.print("Enter list: "); 17 | int listSize = input.nextInt(); 18 | 19 | // create an array for storing list numbers 20 | int[] list = new int[listSize]; 21 | 22 | // get numbers from the user and put them in the list 23 | for (int i = 0; i < listSize; i++) { 24 | list[i] = input.nextInt(); 25 | } 26 | 27 | if (isSorted(list)) { 28 | System.out.println("The list is sorted"); 29 | } else { 30 | System.out.println("The list is not sorted"); 31 | } 32 | } 33 | 34 | public static boolean isSorted(int[] list) { 35 | for (int i = 0; i < list.length - 1; i++) { 36 | if( list[i] > list[i + 1]) { 37 | return false; 38 | } 39 | } 40 | return true; 41 | } 42 | 43 | } 44 | -------------------------------------------------------------------------------- /Chapter_08/Checkpoints_Ch_08.md: -------------------------------------------------------------------------------- 1 | # Checkpoint Answers Chapter 8 # 2 | ## 8.1 ## 3 | A two-dimensional array that hold int values and is of size 4-by-5 is created like this: 4 | ```Java 5 | int[][] matrix = new int[4][5]; 6 | ``` 7 | 8 | ## 8.2 ## 9 | The rows in a two-dimensional array can have different lengths, arrays with this property is known as ragged arrays. 10 | 11 | ## 8.3 ## 12 | ```Java 13 | int[][] array = new int[5][6]; 14 | int[] x = {1, 2}; 15 | array[0] = x; 16 | System.out.println("array[0][1] is " + array[0][1]); 17 | ``` 18 | The above code will set array[0][0] to 1 and array[0][1] to 2. So the output will be: 19 | ``` 20 | array[0][1] is 2 21 | ``` 22 | 23 | ## 8.4 ## 24 | Examples of valid statements: 25 | ```Java 26 | int[][] y = new int[3][]; 27 | int[][] z = {{1, 2}}; 28 | int[][] m = {{1, 2}, {2, 3}}; 29 | ``` 30 | Examples of invalid statements: 31 | ```Java 32 | int[][] r = new int[2]; 33 | int[] x = new int[]; 34 | int[][] n = {{1, 2}, {2, 3}, }; 35 | ``` 36 | 37 | ## 8.5 ## 38 | ```Java 39 | int[][] array = {{1, 2}, {3, 4}, {5, 6}}; 40 | for (int i = array.length - 1; i >= 0; i——) { 41 | for (int j = array[i].length - 1; j >= 0; j——) 42 | System.out.print(array[i][j] + " "); 43 | System.out.println(); 44 | } 45 | ``` 46 | The above code setups a two dimensional array with 3 rows and 2 columns. It will then print the content of the array "in reverse". The output will be: 47 | ``` 48 | 6 5 49 | 4 3 50 | 2 1 51 | ``` 52 | 53 | ## 8.6 ## 54 | ```Java 55 | int[][] array = { { 1, 2 }, { 3, 4 }, { 5, 6 } }; 56 | int sum = 0; 57 | for (int i = 0; i < array.length; i++) 58 | sum += array[i][0]; 59 | System.out.println(sum); 60 | ``` 61 | The above code setups a two dimensional array with 3 rows and 2 columns. The sum of all the elements in the first column will then be calculated (1 + 3 + 5) and the result is printed. The output will hence be: 62 | ``` 63 | 9 64 | ``` 65 | 66 | ## 8.7 ## 67 | The method called m1 will take a two dimensional array as input and check the number of rows and columns. The result of the check is returned in an array where the row count is placed first and then follows the column count. 68 | 69 | The method is tested with a 2 by 4 array so the output will be: 70 | ``` 71 | 2 72 | 4 73 | ``` 74 | 75 | ## 8.8 ## 76 | A declaration of a three dimensional array: 77 | ```Java 78 | int[][][] a = new int[4][6][5]; 79 | ``` 80 | 81 | ## 8.9 ## 82 | Assume that we have the following declaration: 83 | ```Java 84 | int[][][] x = new char[12][5][2]; 85 | ``` 86 | 87 | This array will in total hold 120 elements because 12 times 5 times 2 is 120. 88 | 89 | The value of 90 | ```Java 91 | x.length 92 | ``` 93 | will be 12 because the outermost array can hold 12 elements. 94 | 95 | The value of 96 | ```Java 97 | x[2].length 98 | ``` 99 | will be 5 because this refers to the array in the "second dimension". 100 | 101 | The value of 102 | ```Java 103 | x.length[0][0] 104 | ``` 105 | will be 2 because this is a reference to the "third dimension" and these are all arrays of size 2. 106 | 107 | ## 8.10 ## 108 | ```Java 109 | int[][][] array = {{{1, 2}, {3, 4}}, {{5, 6}, {7, 8}}}; 110 | System.out.println([0][0][0]); 111 | System.out.println([1][1][1]); 112 | ``` 113 | The above code will declare an three-dimensional array of size 2-by-2-by-2. The "first" and "last" elements in the array are then printed, so the output will be: 114 | ``` 115 | 1 116 | 8 117 | ``` 118 | -------------------------------------------------------------------------------- /Chapter_08/Exercise_01/Exercise_08_01.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | /** 4 | * Exercise 8.1 from the book Introduction to Java Programming (10th). 5 | * 6 | * @author Henrik Samuelsson, henrik.samuelsson(at)gmail.com 7 | */ 8 | 9 | public class Exercise_08_01 { 10 | 11 | public static void main(String[] args) { 12 | final int ROWS = 3; 13 | final int COLUMNS = 4; 14 | double[][] testArray = new double[ROWS][COLUMNS]; 15 | 16 | // get data for the array from the user 17 | Scanner input = new Scanner(System.in); 18 | System.out.println("Enter a " + ROWS + "-by-" + COLUMNS 19 | + " matrix row by row:"); 20 | for (int rowIndex = 0; rowIndex < ROWS; rowIndex++) { 21 | for (int columnIndex = 0; columnIndex < COLUMNS; columnIndex++) { 22 | testArray[rowIndex][columnIndex] = input.nextDouble(); 23 | } 24 | } 25 | 26 | // calculate and print the sum for all the columns 27 | for (int columnIndex = 0; columnIndex < COLUMNS; columnIndex++) { 28 | System.out.println("Sum of the elemnts at column " + columnIndex 29 | + " is " + sumColumn(testArray, columnIndex)); 30 | } 31 | 32 | } 33 | 34 | public static double sumColumn(double[][] m, int columnIndex) { 35 | double sum = 0; 36 | for (int rowIndex = 0; rowIndex < m.length; rowIndex++) { 37 | sum += m[rowIndex][columnIndex]; 38 | } 39 | return sum; 40 | } 41 | 42 | } 43 | -------------------------------------------------------------------------------- /Chapter_08/Exercise_02/Exercise_08_02.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | /** 4 | * Exercise 8.2 from the book Introduction to Java Programming (10th). 5 | * 6 | * @author Henrik Samuelsson, henrik.samuelsson(at)gmail.com 7 | */ 8 | 9 | public class Exercise_08_02 { 10 | 11 | public static void main(String[] args) { 12 | final int ROWS = 4; 13 | final int COLUMNS = 4; 14 | double[][] testArray = new double[ROWS][COLUMNS]; 15 | 16 | // get data for the array from the user 17 | Scanner input = new Scanner(System.in); 18 | System.out.println("Enter a " + ROWS + "-by-" + COLUMNS 19 | + " matrix row by row:"); 20 | for (int rowIndex = 0; rowIndex < ROWS; rowIndex++) { 21 | for (int columnIndex = 0; columnIndex < COLUMNS; columnIndex++) { 22 | testArray[rowIndex][columnIndex] = input.nextDouble(); 23 | } 24 | } 25 | 26 | // calculate and print the sum of the elements in the major diagonal 27 | System.out.println("Sum of the elemnts in the major diagonal is " 28 | + sumMajorDiagonal(testArray)); 29 | 30 | } 31 | 32 | public static double sumMajorDiagonal(double[][] m) { 33 | double sum = 0; 34 | for (int index = 0; index < m.length; index++) { 35 | sum += m[index][index]; 36 | } 37 | return sum; 38 | } 39 | 40 | } 41 | -------------------------------------------------------------------------------- /Chapter_09/Exercise_01/Exercise_09_01.java: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | * Exercise 9.1 from the book Introduction to Java Programming (10th). 4 | * 5 | * @author Henrik Samuelsson, henrik.samuelsson(at)gmail.com 6 | */ 7 | 8 | public class Exercise_09_01 { 9 | 10 | public static void main(String[] args) { 11 | Rectangle r1 = new Rectangle(4, 40); 12 | Rectangle r2 = new Rectangle(3.5, 35.9); 13 | 14 | System.out.println("Properties for r1:"); 15 | System.out.println("width = " + r1.width); 16 | System.out.println("height = " + r1.height); 17 | System.out.println("area = " + r1.getArea()); 18 | System.out.println("perimeter = " + r1.getPerimeter()); 19 | 20 | System.out.println(""); 21 | 22 | System.out.println("Properties for r2:"); 23 | System.out.println("width = " + r2.width); 24 | System.out.println("height = " + r2.height); 25 | System.out.println("area = " + r2.getArea()); 26 | System.out.println("perimeter = " + r2.getPerimeter()); 27 | } 28 | 29 | } 30 | 31 | class Rectangle { 32 | double width; 33 | double height; 34 | 35 | /** Constructs a rectangle with height and width set to 1. */ 36 | Rectangle() { 37 | width = 1; 38 | height = 1; 39 | } 40 | 41 | /** Constructs a rectangle with specified width and height. */ 42 | Rectangle(double width, double height) { 43 | this.width = width; 44 | this.height = height; 45 | } 46 | 47 | /** Return the area of this rectangle. */ 48 | double getArea() { 49 | return width * height; 50 | } 51 | 52 | /** Return the perimeter of this rectangle. */ 53 | double getPerimeter() { 54 | return width * 2 + height * 2; 55 | } 56 | 57 | } 58 | -------------------------------------------------------------------------------- /Chapter_09/Exercise_01/Rectangle.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HenrikSamuelsson/Introduction_to_Java_Programming/c4ba17abcdde14585c3c7930f167a53cf7ec6bfe/Chapter_09/Exercise_01/Rectangle.png -------------------------------------------------------------------------------- /Chapter_09/Exercise_02/Exercise_09_02.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Exercise 9.2 from the book Introduction to Java Programming (10th). 3 | *

4 | * The Stock class 5 | *

6 | * A class that handle stocks, with for example name and price of the stock. 7 | */ 8 | public class Exercise_09_02 { 9 | public static void main(String[] args) { 10 | Stock stock = new Stock("ORCL", "Oracle Corporation"); 11 | stock.setPreviousClosingPrice(34.5); 12 | 13 | // Set current price 14 | stock.setCurrentPrice(34.35); 15 | 16 | // Display stock info 17 | System.out.println("Previous Closing Price: " 18 | + stock.getPreviousClosingPrice()); 19 | System.out.println("Current Price: " + stock.getCurrentPrice()); 20 | System.out.println("Price Change: " + stock.getChangePercent() * 100 21 | + "%"); 22 | } 23 | } 24 | 25 | class Stock { 26 | String symbol; 27 | String name; 28 | double previousClosingPrice; 29 | double currentPrice; 30 | 31 | public Stock() { 32 | } 33 | 34 | public Stock(String newSymbol, String newName) { 35 | symbol = newSymbol; 36 | name = newName; 37 | } 38 | 39 | public double getChangePercent() { 40 | return (currentPrice - previousClosingPrice) / previousClosingPrice; 41 | } 42 | 43 | public double getPreviousClosingPrice() { 44 | return previousClosingPrice; 45 | } 46 | 47 | public double getCurrentPrice() { 48 | return currentPrice; 49 | } 50 | 51 | public void setCurrentPrice(double newCurrentPrice) { 52 | currentPrice = newCurrentPrice; 53 | } 54 | 55 | public void setPreviousClosingPrice(double newPreviousClosingPrice) { 56 | previousClosingPrice = newPreviousClosingPrice; 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /Chapter_09/Exercise_02/Resources/UML_09_02.graphml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | Stock 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | ~ symbol: String 45 | ~ name: String 46 | ~ previousClosingPrice: double 47 | ~ currentPrice: double 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | + Stock() 62 | + Stock(String newSymbol, String newName) 63 | + getChangePercent(): double 64 | + getPreviousClosingPrice(): double 65 | + getCurrentPrice(): double 66 | + setCurrentPrice(double newCurrentPrice): void 67 | + setPreviousClosingPrice(double newPreviousClosingPrice): void 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | -------------------------------------------------------------------------------- /Chapter_09/Exercise_02/UML_09_02.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HenrikSamuelsson/Introduction_to_Java_Programming/c4ba17abcdde14585c3c7930f167a53cf7ec6bfe/Chapter_09/Exercise_02/UML_09_02.png -------------------------------------------------------------------------------- /Chapter_09/Exercise_03/Exercise_09_03.java: -------------------------------------------------------------------------------- 1 | import java.util.Date; 2 | 3 | /** 4 | * Exercise 9.3 from the book Introduction to Java Programming (10th). 5 | * 6 | * @author Henrik Samuelsson, henrik.samuelsson(at)gmail.com 7 | */ 8 | 9 | public class Exercise_09_03 { 10 | 11 | public static void main(String[] args) { 12 | Date d = new Date(); 13 | long time = 10_000; 14 | final long MAX_TIME = 10_000_0000_000L; 15 | while (time <= MAX_TIME) { 16 | d.setTime(time); 17 | System.out.println(d.toString()); 18 | time *= 10; 19 | } 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /Chapter_09/Exercise_04/Exercise_09_04.java: -------------------------------------------------------------------------------- 1 | import java.util.Random; 2 | 3 | /** 4 | * Exercise 9.4 from the book Introduction to Java Programming (10th). 5 | * 6 | * @author Henrik Samuelsson, henrik.samuelsson(at)gmail.com 7 | */ 8 | 9 | public class Exercise_09_04 { 10 | 11 | public static void main(String[] args) { 12 | Random rand = new Random(1000); 13 | for(int i = 0; i < 50; i++) 14 | System.out.println(rand.nextInt(100)); 15 | } 16 | 17 | } 18 | -------------------------------------------------------------------------------- /Chapter_09/Exercise_05/Exercise_09_05.java: -------------------------------------------------------------------------------- 1 | import java.util.GregorianCalendar; 2 | 3 | /** 4 | * Exercise 9.5 from the book Introduction to Java Programming (10th). 5 | *

6 | * Note that the month count is for some reason starting at 0 as opposed 7 | * to the year and day of month. This means that the month will be seem to be 8 | * off by one in the output. 9 | * 10 | * @author Henrik Samuelsson, henrik.samuelsson(at)gmail.com 11 | */ 12 | 13 | public class Exercise_09_05 { 14 | 15 | public static void main(String[] args) { 16 | GregorianCalendar gc = new GregorianCalendar(); 17 | 18 | // display the current year, month and day 19 | System.out.print(gc.get(GregorianCalendar.YEAR) + " " + 20 | gc.get(GregorianCalendar.MONTH) + " " + 21 | gc.get(GregorianCalendar.DAY_OF_MONTH) + "\n"); 22 | 23 | // change the time and display year, month and day 24 | gc.setTimeInMillis(1234567898765L); 25 | System.out.print(gc.get(GregorianCalendar.YEAR) + " " + 26 | gc.get(GregorianCalendar.MONTH) + " " + 27 | gc.get(GregorianCalendar.DAY_OF_MONTH) + "\n"); 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /Chapter_09/Exercise_06/Exercise_09_06.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Exercise 9.6 from the book Introduction to Java Programming (10th). 3 | * 4 | * @author Henrik Samuelsson, henrik.samuelsson(at)gmail.com 5 | */ 6 | 7 | import java.util.Random; 8 | 9 | public class Exercise_09_06 { 10 | 11 | public static void main(String[] args) { 12 | final int DATA_AMOUNT = 100_000; 13 | int[] data = new int[DATA_AMOUNT]; 14 | StopWatch stopWatch = new StopWatch(); 15 | 16 | // generate some random data for our data array 17 | Random rand = new Random(); 18 | for (int i = 0; i < DATA_AMOUNT; i++) { 19 | data[i] = rand.nextInt(); 20 | } 21 | 22 | // sort the data and measure the time that the sorting takes 23 | stopWatch.start(); 24 | java.util.Arrays.sort(data); 25 | stopWatch.stop(); 26 | 27 | // display the result 28 | System.out.println(stopWatch.getElapsedTime()); 29 | } 30 | 31 | } 32 | 33 | class StopWatch { 34 | private long startTime; 35 | private long endTime; 36 | 37 | /** Constructs a stop watch with start time set to the current time. */ 38 | StopWatch() { 39 | startTime = System.currentTimeMillis(); 40 | } 41 | 42 | /** Sets the start time. */ 43 | void start() { 44 | startTime = System.currentTimeMillis(); 45 | } 46 | 47 | /** Sets the end time. */ 48 | void stop() { 49 | endTime = System.currentTimeMillis(); 50 | } 51 | 52 | /** Calculates the elapsed time between start and stop. */ 53 | long getElapsedTime() { 54 | return endTime - startTime; 55 | } 56 | 57 | } -------------------------------------------------------------------------------- /Chapter_09/Exercise_06/StopWatch.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HenrikSamuelsson/Introduction_to_Java_Programming/c4ba17abcdde14585c3c7930f167a53cf7ec6bfe/Chapter_09/Exercise_06/StopWatch.png -------------------------------------------------------------------------------- /Chapter_09/Exercise_08/UML_09_08.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HenrikSamuelsson/Introduction_to_Java_Programming/c4ba17abcdde14585c3c7930f167a53cf7ec6bfe/Chapter_09/Exercise_08/UML_09_08.png -------------------------------------------------------------------------------- /Chapter_09/Exercise_08/resources/UML_09_08.graphml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | Fan 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | + SLOW : int = 1 43 | + MEDIUM : int = 2 44 | + FAST : int = 3 45 | - speed : int = SLOW 46 | - on : boolean = false 47 | - radius : double = 5 48 | - color : String = blue 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | +Fan() 63 | +getSpeed() : int 64 | +setSpeed(int) : void 65 | +isOn() : boolean 66 | +turnOn() : void 67 | +turnOff() : void 68 | +getRadius() : double 69 | +setRadius(double) : void 70 | +getColor() : String 71 | +setColor(int) : String 72 | +toString() : String 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | -------------------------------------------------------------------------------- /Chapter_10/Checkpoints_Ch_10.md: -------------------------------------------------------------------------------- 1 | # Checkpoint Answers Chapter 10 # 2 | ## 10.1 ## 3 | The Loan class would not be made immutable just by removing the setter methods. The getLoanDate method would still return a reference to an object and this reference could be used to change parts of the Loan class. 4 | 5 | ## 10.2 ## 6 | The BMI class is immutable. There are no setter methods, and there is only possible to get references to String objects which is a type of object that is immutable. 7 | 8 | ## 10.3 ## 9 | The relationship among classes is often divided into four different groups based on characteristics of the relation. The name of these groups are: 10 | 1. Inheritance 11 | 2. Aggregation 12 | 3. Association 13 | 4. Composition 14 | 15 | ## 10.4 ## 16 | Aggregation implies a relationship where the child can exist independently of the parent. Example: Class (parent) and Student (child). Delete the Class and the Students still exist. 17 | 18 | Composition implies a relationship where the child cannot exist independent of the parent. Example: House (parent) and Room (child). Rooms don't exist separate to a House. 19 | 20 | Association is a weaker form of relationship that indicates that a class uses another class by parameter or return type. 21 | 22 | ## 10.5 ## 23 | The UML notation for aggregation is an unfilled diamond symbol at the owner (aggregation) class. Composition is indicated in the same way but with a filled diamond symbol. 24 | 25 | ## 10.6 ## 26 | Aggregation and composition are closely related. Hence so are they usually not differentiated in the book. Both are called composition for simplicity. 27 | 28 | ## 10.7 ## 29 | A wrapper class is one of eight classes provided in the java.lang package to provide object methods for the eight primitive types. Wrapper classes are used to represent primitive values when an Object is required. All of the primitive wrapper classes in Java are immutable. 30 | 31 | ## 10.10 ## 32 | An Integer is created that will have the value 3. The value is then printed so 3 will be printed. The value 3 is then compared to 4 which will return -1. The result of the comparison is then also printed. 33 | 34 | The printed output will hence be: 35 | ``` 36 | 3 37 | -1 38 | ``` 39 | 40 | ## 10.11 ## 41 | No extra parameter means that the number will be interpreted as a decimal number. Extra parameter in the form of 10 also means that decimal interpretation. Extra parameter in the form of 16 means that the number will be interpreted as being written with hexadecimal base. 42 | ``` 43 | 10 44 | 10 45 | 16 46 | 11 47 | 11 48 | 17 49 | ``` 50 | 51 | ## 10.12 ## 52 | Autoboxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes. 53 | 54 | The opposite automatic conversion of an object of a wrapper type to its corresponding primitive value is called unboxing. 55 | 56 | The following are all valid examples of autoboxing and unboxing: 57 | ``` 58 | Integer x = 3 + new Integer(5); 59 | Integer x = 3; 60 | Double x = 3.0; 61 | int x = new Integer(3); 62 | int x = new Integer(3) + new Integer(4); 63 | ``` 64 | This example is not valid because the types does not match up in the correct way: 65 | ``` 66 | Double x = 3; 67 | ``` 68 | But it can be fixed by introduction of a cast: 69 | ``` 70 | Double x = (double) 3; 71 | ``` 72 | 73 | ## 10.13 ## 74 | A cast will be used to convert the double into an int int the first print, the decimal part will be truncated away. 75 | 76 | 3.5 is less than 4.5 so the compareTo method will return -1. 77 | 78 | The output will hence be: 79 | ``` 80 | 3 81 | -1 82 | ``` 83 | 84 | ## 10.14 ## 85 | The output will be: 86 | ``` 87 | x is 3 88 | y is 7 89 | z is 10 90 | ``` 91 | 92 | ## 10.15 ## 93 | Assume the we create strings in the following way: 94 | ```Java 95 | String s1 = "Welcome to Java"; 96 | String s2 = s1; 97 | String s3 = new String("Welcome to Java"); 98 | String s4 = "Welcome to Java"; 99 | ``` 100 | The results of the following expressions is indicated by comments in the code. 101 | ```Java 102 | s1 == s2 // true, both variables will reference the same object 103 | s1 == s3 // false, same content but not the same objects 104 | s1 == s4 // true, an interned string 105 | s1.equals(s3) // true 106 | s1.equals(s4) // true 107 | "Welcome to Java".replace("Java", "HTML") // Welcome to HTML 108 | s1.replace("o", "T") // WelcTme tT Java 109 | s1.replaceAll("o", "T") // WelcTme tT Java 110 | s1.replaceFirst("o", "T") // WelcTme to Java 111 | s1.toCharArray() // an array holding the characters in the string "Welcome to Java" 112 | ``` 113 | 114 | ## 10.14 ## 115 | There are two ways to create a String: 116 | ```Java 117 | String s = "Welcome to Java"; 118 | ``` 119 | ```Java 120 | String s = new String("Welcome to Java"); 121 | ``` 122 | The first one is better because it creates an interned String that will be shared if more strings with the same value are created later on. This will save memory and be faster because using the new operator is expensive. 123 | 124 | ## 10.26 ## 125 | The main difference between StringBuffer and StringBuilder is that StringBuffer is synchronized and StringBuilder is not. 126 | 127 | This means that StringBuilder will be faster but it can not be used if two or more threads needs to share it. 128 | 129 | -------------------------------------------------------------------------------- /Chapter_10/Exercise_01/BMI.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Exercise 10.2 from the book Introduction to Java Programming (10th). 3 | *

4 | * The code that this exercise is based on can be found in the book. An extra 5 | * constructor have been added that makes it possible to specify the height in 6 | * feet and inches. 7 | * 8 | * @author Henrik Samuelsson, henrik.samuelsson(at)gmail.com 9 | */ 10 | 11 | public class BMI { 12 | 13 | private String name; 14 | private int age; 15 | private double weight; // in pounds 16 | private double height; // in inches 17 | public static final double KILOGRAMS_PER_POUND = 0.45359237; 18 | public static final double METERS_PER_INCH = 0.0254; 19 | public static final double INCH_PER_FEET = 12; 20 | 21 | public BMI(String name, int age, double weight, double height) { 22 | this.name = name; 23 | this.age = age; 24 | this.weight = weight; 25 | this.height = height; 26 | } 27 | 28 | public BMI(String name, double weight, double height) { 29 | this(name, 20, weight, height); 30 | } 31 | 32 | public BMI(String name, int age, double weight, double feet, double inches) { 33 | this(name, age, weight, feet * INCH_PER_FEET + inches); 34 | } 35 | 36 | public double getBMI() { 37 | double bmi = weight * KILOGRAMS_PER_POUND 38 | / ((height * METERS_PER_INCH) * (height * METERS_PER_INCH)); 39 | return Math.round(bmi * 100) / 100.0; 40 | } 41 | 42 | public String getStatus() { 43 | double bmi = getBMI(); 44 | if (bmi < 18.5) 45 | return "Underweight"; 46 | else if (bmi < 25) 47 | return "Normal"; 48 | else if (bmi < 30) 49 | return "Overweight"; 50 | else 51 | return "Obese"; 52 | } 53 | 54 | public String getName() { 55 | return name; 56 | } 57 | 58 | public int getAge() { 59 | return age; 60 | } 61 | 62 | public double getWeight() { 63 | return weight; 64 | } 65 | 66 | public double getHeight() { 67 | return height; 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /Chapter_11/Check_Points_Ch11.md: -------------------------------------------------------------------------------- 1 | # Checkpoint Answers Chapter 11 # 2 | ## 11.1 ## 3 | A subclass is usually not a subset of a superclass. Subclasses will usually add functionality and details that are not present in the superclass thus extending the superclass. 4 | 5 | ## 11.2 ## 6 | The keyword extends is used when defining a subclass. 7 | 8 | For example: 9 | ```Java 10 | public class MountainBike extends Bicycle { 11 | 12 | // ... 13 | // ... 14 | // ... 15 | 16 | } 17 | ``` 18 | 19 | ## 11.3 ## 20 | Single inheritance means that a class may only inherit from one particular class. 21 | 22 | Multiple inheritance is a feature of some object-oriented computer programming languages in which an class can inherit characteristics and features from more than one parent class. 23 | 24 | Multiple inheritance is not supported by the Java programming language. 25 | 26 | ## 11.4 ## 27 | a) 28 | A's no-arg constructor is invoked 29 | b) 30 | There will be an error in compiling because the parent class A doesn't have a no-arg constructor 31 | 32 | ## 11.5 ## 33 | The syntax for calling a superclass constructor that takes no parameters is: 34 | ```Java 35 | super(); 36 | ``` 37 | The syntax with parameters is: 38 | ```Java 39 | super(parameter list); 40 | ``` 41 | This will cause a call to a constructor with matching parameter list in the superclass. 42 | 43 | Invocation of a superclass constructor must be on the first line in the subclass constructor. 44 | 45 | It is possible to omit the explicit call of a superclass constructor. The compiler will in this case insert a call to the no-argument superclass constructor. 46 | 47 | ## 11.6 ## 48 | The no-arg constructor of a superclass will not be called if another constructor is called explicitly by the subclass. 49 | 50 | ## 11.7 ## 51 | It is not possible to override a method that is declared private in the superclass. 52 | 53 | ## 11.8 ## 54 | It is not possible to override a static method defined in a superclass. 55 | 56 | It is still possible to have another static method, with the same name, in a subclass but this method will not override the method in the superclass, it will hide it. 57 | 58 | This is a bit tricky read more [here](http://docs.oracle.com/javase/tutorial/java/IandI/override.html "here"). 59 | 60 | ## 11.9 ## 61 | The keyword super is used to explicitly invoke the constructor of a superclass. 62 | 63 | ## 11.10 ## 64 | The keyword super in combination with the dot operator is used to invoke an overridden superclass method from a subclass. 65 | ```Java 66 | super.method() 67 | ``` 68 | 69 | ## 11.11 ## 70 | A corrected version of the code for this checkpoint looks like this: 71 | ```Java 72 | public class Circle { 73 | private double radius; 74 | 75 | public Circle(double radius) { 76 | this.radius = radius; 77 | } 78 | 79 | public double getRadius() { 80 | return radius; 81 | } 82 | 83 | public double getArea() { 84 | return radius * radius * Math.PI; 85 | } 86 | } 87 | 88 | class B extends Circle { 89 | private double length; 90 | 91 | B(double radius, double length) { 92 | super(radius); 93 | this.length = length; 94 | } 95 | 96 | @Override 97 | public double getArea() { 98 | return super.getArea() * length; 99 | } 100 | } 101 | ``` 102 | 103 | ## 11.12 ## 104 | Method overloading means making multiple versions of a method based on differences in the signature. 105 | 106 | Method overriding means defining a new version of a method in a subclass of a superclass. Overridden methods have the same signature and return type as the original. 107 | 108 | ## 11.13 ## 109 | A method in a subclass that have the same signature, and same return type, as a method in its superclass is said to be overriden. 110 | 111 | ## 11.14 ## 112 | Having methods with the same signature but different return types in a subclass and its superclass is not allowed and will cause a syntax error. 113 | 114 | ## 11.15 ## 115 | A method in a subclass that have the same name as a method in its superclass but with different parameter types is said to be overloaded. 116 | 117 | ## 11.16 ## 118 | Using the @Override annotation will take advantage of the compiler checking that makes sure that there is an actual overriding of an existing method. This check will catch mistakes of misspelling a method name or not correctly matching the parameters. 119 | 120 | Another benefit is that this annotation functions as documentation, making the intention of the code easier to understand. 121 | 122 | ## 11.17 ## 123 | A good definition of polymorphism can be found in [The Java Tutorials](https://docs.oracle.com/javase/tutorial/java/IandI/polymorphism.html "The Java Tutorials"). 124 | > The dictionary definition of polymorphism refers to a principle in biology in which an organism or species can have many different forms or stages. This principle can also be applied to object-oriented programming and languages like the Java language. Subclasses of a class can define their own unique behaviors and yet share some of the same functionality of the parent class. 125 | 126 | When an method is overridden in subclass so is it up to the JVM to figure out at runtime which specific method to invoke. This concept is called dynamic binding. 127 | 128 | ## 11.18 ## 129 | Method matching is the process of deciding what version of an overloaded method to invoke. This is done at compile time by the compiler and the choice is based on the signature of the overloaded methods. 130 | 131 | Method binding is the process of finding the method to invoke when using inheritance. A method may be implemented in several classes part of an inheritance chain. The JVM dynamically binds the implementation of the method at runtime, decided by the actual class of the object referenced by the variable. 132 | 133 | ## 11.19 ## 134 | It is (of course) possible to assign an array of type Object like this: 135 | ```Java 136 | Object o = new Object[50]; 137 | ``` 138 | Since all other classes inherits from Object so is it also possible to do assignments of the following kind: 139 | ```Java 140 | Object[] o = new Integer[50]; 141 | ``` 142 | ```Java 143 | Object[] o = new String[50]; 144 | ``` 145 | It is on the other hand not possible to assign an primitive type to an Object variable this means that the following code will not compile. 146 | ```Java 147 | Object[] o = new int[50]; // Type mismatch: cannot convert from int[] to Object[] 148 | ``` 149 | 150 | ## 11.24 ## 151 | The following statement is true. 152 | > You can always successfully cast an instance of a subclass to a superclass. 153 | 154 | The following statement is false. 155 | > You can always successfully cast an instance of a superclass to a subclass. 156 | 157 | ## 11.25 ## 158 | **(a)** 159 | ```Java 160 | (circle instanceof GeometricObject) // true 161 | (object instanceof GeometricObject) // true 162 | (circle instanceof Circle) // true 163 | (object instanceof Circle) // false 164 | ``` 165 | 166 | **(b)** 167 | The code will compile because cast from subclass to superclass is always allowed. 168 | 169 | **(c)** 170 | The code will compile but there will be runtime exception when executing the program. 171 | 172 | ## 11.28 ## 173 | Every object have both a toString and an equals method because these methods are defined in the class Object and all classes inherits from this class. 174 | 175 | Examples of how to invoke these methods: 176 | ```Java 177 | object1.equals(object2) 178 | ``` 179 | ```Java 180 | object1.toString() 181 | ``` 182 | 183 | The default versions of these methods are rather crude and should often be overridden in the subclass to get more useful versions. 184 | 185 | ## 11.30 ## 186 | **(a)** 187 | Creation of an ArrayList for storing double values: 188 | ```Java 189 | ArrayList doubleList = new ArrayList<>(); 190 | ``` 191 | 192 | **(b)** 193 | Append an on object to a list: 194 | ```Java 195 | doubleList.add(5.0); 196 | ``` 197 | 198 | **(c)** 199 | Insert an object at the beginning of the list: 200 | ```Java 201 | doubleList.add(0, 1.0); // index 0 is the start of the list 202 | ``` 203 | 204 | **(d)** 205 | Number of objects in the list: 206 | ```Java 207 | doubleList.size(); 208 | ``` 209 | 210 | **(e)** 211 | Removal of a given object in the list: 212 | ```Java 213 | doubleList.remove(5.0); // removes the first occurence found of 5.0 in the list 214 | ``` 215 | 216 | **(f)** 217 | Removal of the last element in the list: 218 | ```Java 219 | doubleList.remove(doubleList.size() - 1); 220 | ``` 221 | 222 | **(g)** 223 | Check whether a given element is in the list: 224 | ```Java 225 | doubleList.contains(1.0); // checks if the number 1.0 is in the list 226 | ``` 227 | 228 | **(h)** 229 | Retrieve an object at a specified index in the list: 230 | ```Java 231 | doubleList.get(0); // returns what the first element in the list is 232 | ``` 233 | 234 | ## 11.31 ## 235 | There are multiple issuses with the below code. 236 | ```Java 237 | ArrayList list = new ArrayList<>(); 238 | list.add("Denver"); 239 | list.add("Austin"); 240 | list.add(new java.util.Date()); 241 | String city = list.get(0); 242 | list.set(3, "Dallas"); 243 | System.out.println(list.get(3)); 244 | ``` 245 | A Date object is attempted to be added to the ArrayList, this will not work because the list is setup to hold String objects. 246 | 247 | Index 3 is attempted to be set to Dallas but it will not be possible since the list only holds two elements when this statement is executed at runtime. 248 | 249 | An attempt to get the element at index 3 is done. This will not work because there is no element at this location when this statement is executed at runtime. 250 | 251 | ## 11.33 ## 252 | What happens is that the method with the signature 253 | ```Java 254 | remove(int index) 255 | ``` 256 | is called with the argument 1. This will remove the value at index 1, the value 2 is stored here so this will be removed. 257 | 258 | If instead the value 1 shall found int the list and be removed so can the method with the signature 259 | ```Java 260 | remove(Object) 261 | ``` 262 | be called by writing like this 263 | ```Java 264 | remove(new Integer(1)); 265 | ``` 266 | 267 | ## 11.34 ## 268 | ```Java 269 | ArrayList list = new ArrayList<>(); 270 | list.add(1); 271 | ``` 272 | The above code will not work because the add function takes an Double Object as argument but an int is provided. There is no auto boxing from int to Double so the code will not compile. 273 | 274 | The code can be fixed by writing like this 275 | ```Java 276 | list.add(1.0); 277 | ``` 278 | or like this 279 | ```Java 280 | list.add(new Double(1)); 281 | ``` 282 | 283 | ## 11.35 ## 284 | The asList method does not support primitive types and there is no autoboxing for arrays. This is why the code from the book does not work. A corrected version is shown below. 285 | ```Java 286 | Integer[] array = {3, 5, 95, 4, 15, 34, 3, 6, 5}; 287 | ArrayList list = new ArrayList<(Arrays.asList(array)); 288 | ``` 289 | 290 | ## 11.36 ## 291 | The max method in the Collections class can not be used with an array as argument. The array need to be converted to an ArrayList that is an type allowed to be used as an argument. 292 | ```Java 293 | Integer[] array = {3, 5, 95, 4, 15, 34, 3, 6, 5}; 294 | ArrayList list = new ArrayList<(Arrays.asList(array)); 295 | System.out.println(java.util.Collections.max(list)); 296 | ``` 297 | 298 | ## 11.37 ## 299 | A class can by default access another class in the same package, but classes outside of the package will not be able to access it by default. This means that if this is the desired level of visibility so shall the accessibility modifier simply be omitted. 300 | 301 | ## 11.38 ## 302 | The keyword protected is used as an accessibility modifier to setup so that a class in a different package cannot access the class, but its subclasses in any package can access it. 303 | 304 | ## 11.39 ## 305 | If the question marks are replaced by blanks, can class B be compiled? Yes, default access means visibility between classes in the same package. 306 | 307 | If the question marks are replaced by private, can class B be compiled? No, private means that the int called i and the method called m can only be used from within the class. 308 | 309 | If the question marks are replaced by protected, can class B be compiled? Yes, B inherits from A so B can used protected members from A. 310 | 311 | ## 11.40 ## 312 | If the question marks are replaced by blanks, can class B be compiled? No, B is not in the same package as A so if i and m from class A will not be visible to B if default access is set. 313 | 314 | If the question marks are replaced by private, can class B be compiled? No, i and m will not be visible outside of class A if they are set to private. 315 | 316 | If the question marks are replaced by protected, can class B be compiled? Yes, B inherits from A so there is no problem to access protected variables in A. 317 | 318 | ## 11.41 ## 319 | The keyword final is used to prevent classes from being extended. It is also used to prevent methods form being overridden. 320 | 321 | ## 11.42 ## 322 | **(a)** 323 | True. 324 | 325 | **(b)** 326 | False, only true if the subclass extends the class with the protected members. 327 | 328 | **(c)** 329 | True. 330 | 331 | **(d)** 332 | True. 333 | 334 | **(e)** 335 | False. 336 | 337 | **(f)** 338 | False. 339 | 340 | 341 | -------------------------------------------------------------------------------- /Chapter_12/Exercise_02/Exercise_12_02.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Exercise 12.2 from the book Introduction to Java Programming (10th). 3 | *

4 | * InputMismatchException 5 | *

6 | * Sums two given integers. An exception will be thrown if the user does 7 | * not enter integers. This exception is caught and the user is again instructed 8 | * to enter integers. 9 | */ 10 | 11 | import java.util.Scanner; 12 | 13 | public class Exercise_12_02 { 14 | public static void main(String[] args) { 15 | Scanner input = new Scanner(System.in); 16 | 17 | boolean done = false; 18 | int number1 = 0; 19 | int number2 = 0; 20 | 21 | System.out.print("Enter two integers: "); 22 | 23 | while (!done) { 24 | try { 25 | number1 = input.nextInt(); 26 | number2 = input.nextInt(); 27 | done = true; 28 | } catch (Exception ex) { 29 | ex.printStackTrace(); 30 | System.out.println("Incorrect input please try again."); 31 | System.out.print("Enter two integers: "); 32 | input.nextLine(); // Discard input 33 | } 34 | } 35 | 36 | System.out.println("Sum is " + (number1 + number2)); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /Chapter_13/Checkpoints_Ch_13.md: -------------------------------------------------------------------------------- 1 | # Checkpoint Answers Chapter 13 # 2 | ## 13.1 ## 3 | **(a)** 4 | ```Java 5 | class A { 6 | abstract void unfinished() { 7 | } 8 | } 9 | ``` 10 | Not legal code because an abstract method have a body. Another problem is that A is not abstract but it contains an abstract method. 11 | 12 | **(b)** 13 | ```Java 14 | public class abstract A { 15 | abstract void unfinished(); 16 | } 17 | ``` 18 | Not legal because the first use of the abstract keyword is misplaced, shall be placed before the keyword class. 19 | 20 | **(c)** 21 | ```Java 22 | class A { 23 | abstract void unfinished(); 24 | } 25 | ``` 26 | Not legal, the class must be abstract if the method shall be abstract. 27 | 28 | **(d)** 29 | ```Java 30 | abstract class A { 31 | protected void unfinished(); 32 | } 33 | ``` 34 | Not legal since there is no body for the non abstract method. 35 | 36 | **(e)** 37 | ```Java 38 | abstract class A { 39 | abstract void unfinished(); 40 | } 41 | ``` 42 | Legal code. 43 | 44 | **(f)** 45 | ```Java 46 | abstract class A { 47 | abstract int unfinished(); 48 | } 49 | ``` 50 | Legal code. 51 | 52 | ## 13.2 ## 53 | Abstract classes prevents a developer from instantiating the base class, because a developer has marked it as having missing functionality. 54 | 55 | It also provides compile-time safety so that you can ensure that any classes that extend your abstract class provide the bare minimum functionality to work, and you don't need to worry about putting stub methods that inheritors somehow have to magically know that they have to override a method in order to make it work. 56 | 57 | Read more at: [StackExchange - Why should I declare a class as an abstract class?](http://programmers.stackexchange.com/questions/96947/why-should-i-declare-a-class-as-an-abstract-class) 58 | 59 | ## 13.3 ## 60 | **(a)** 61 | An abstract class can be used just like a non-abstract class except that you cannot use the new operator to create an instance from the abstract class. 62 | 63 | **(b)** 64 | An abstract class can be extended. 65 | 66 | **(c)** 67 | A subclass of a non-abstract superclass can be abstract. 68 | 69 | **(d)** 70 | A subclass can override a concrete method in a superclass to define it as abstract. 71 | 72 | **(e)** 73 | An abstract method cannot be static. 74 | 75 | ## 13.4 ## 76 | There will be an attempt, at runtime, to create a Double object out of an Number object. But this will not work because the Number object is in based on an Integer object. 77 | 78 | ## 13.5 ## 79 | The code from this checkpoint will fail at runtime because a Double object is attempted to be stored where an Integer object is supposed to be stored. 80 | 81 | ## 13.6 ## 82 | ```Java 83 | public class Test { 84 | public static void main(String[] args) { 85 | Number x = 3; 86 | System.out.println(x.intValue()); 87 | System.out.println(x.doubleValue()); 88 | } 89 | } 90 | ``` 91 | The above code will output: 92 | ``` 93 | 3 94 | 3.0 95 | ``` 96 | 97 | ## 13.7 ## 98 | The problem with the code in this checkpoint is that x is of type Number and the method compareTo(Integer) is undefined for the type Number. 99 | 100 | ## 13.8 ## 101 | This checkpoint is about the same code that was discussed in checkpoint 13.7. The problem with the code is now tried to be fixed with a cast. There is however a mistake made when introducing the cast. A corrected working version can be seen below. 102 | ```Java 103 | public class Test { 104 | public static void main(String[] args) { 105 | Number x = new Integer(3); 106 | System.out.println(x.intValue()); 107 | System.out.println(((Integer) x).compareTo(new Integer(4))); 108 | } 109 | } 110 | ``` 111 | ## 13.9 ## 112 | It is not possible to create an Calendar object using the Calendar class. This is so because Calendar is an abstract class. 113 | 114 | ## 13.10 ## 115 | The add method in the Calendar class is abstract. 116 | 117 | ## 13.11 ## 118 | A calendar set to the current time can be created in the following way. 119 | ```Java 120 | Calendar calendar = new GregorianCalendar(); 121 | ``` 122 | 123 | ## 13.12 ## 124 | ```Java 125 | // c is a Calendar instance 126 | c.get(Calendar.YEAR) // get the year 127 | c.get(Calendar.MONTH) // get the month 128 | c.get(Calendar.DATE) // get the date 129 | c.get(Calendar.HOUR) // get the hour 130 | c.get(Calendar.MINUTE) // get the minute 131 | c.get(Calendar.SECOND) // get the second 132 | ``` 133 | 134 | ## 13.13 ## 135 | Suppose A is an interface. It is then **not** possible to create an instance using `new A()`. 136 | 137 | ## 13.14 ## 138 | Suppose A is an interface. It is then possible to declare a reference variable x with type A. 139 | ```Java 140 | A x; // valid code 141 | ``` 142 | 143 | ## 13.15 ## 144 | **(a)** 145 | ```Java 146 | interface A { 147 | void print() { }; 148 | } 149 | ``` 150 | The above interface is not correct because the (implicitly) abstract member method have an body. 151 | 152 | **(b)** 153 | ```Java 154 | abstract interface A extends I1, I2 { 155 | abstract void print() {}; 156 | } 157 | ``` 158 | The above interface is not correct for exactly the same reason as in (a). Note A can extend I1 and I2 assuming that these are them self interfaces. 159 | 160 | **(c)** 161 | ```Java 162 | abstract interface A { 163 | print(); 164 | } 165 | ``` 166 | The above interface is not correct because the return type of the method is missing. 167 | 168 | **(d)** 169 | ``` 170 | interface A { 171 | void print(); 172 | } 173 | ``` 174 | The above is a valid interface. 175 | 176 | ## 13.16 ## 177 | The problem with the code is that the public specifier is missing. The class B shall look like this: 178 | ```Java 179 | public class B implements A { 180 | public void m1() { 181 | System.out.println("m1"); 182 | } 183 | } 184 | ``` 185 | All methods defined in an interface are public. This means that when a class implements the interface so must all methods be declared public. The visibility cannot be reduced afterwards. 186 | 187 | ## 13.17 ## 188 | If a class implements Comparable so can the object of the class invoke the compareTo method. 189 | 190 | ## 13.18 ## 191 | The correct method header for the compareTo method in the String class is: 192 | ```Java 193 | public int compareTo(String o) 194 | ``` 195 | 196 | ## 13.19 ## 197 | ```Java 198 | Integer n1 = new Integer(3); 199 | Object n2 = new Integer(4); 200 | System.out.println(n1.compareTo(n2)); 201 | ``` 202 | The above code will not compile because the method compareTo(Integer) in the type Integer is not applicable for the arguments (Object). 203 | 204 | ## 13.20 ## 205 | By implementing the Comparable interface for a class so can objects of the class be passed to a method that requires a Comparable type. This would not be possible by just implementing a member method called compareTo. 206 | 207 | ## 13.21 ## 208 | The code in this checkpoint will not work because the class tries to use the sort method but this will only work if the compareTo method from the Comparable interface is present. Having the class Person implement the Comparable interface would fix the problem. 209 | 210 | ## 13.22 ## 211 | A precondition for for invocation of the `clone()` method to clone an object is that the class of the object implement the interface `java.long.Cloneable`. 212 | 213 | The `Date` class implements `Cloneable`. 214 | 215 | ## 13.24 ## 216 | The object called `date1` is a shallow copy of the object `date`. The object called `date2` is on the other hand a deep copy of `date`. 217 | 218 | This means that `date == date1` will evaluate to true but `date == date2` will evaluate to false. 219 | 220 | `date.equals(date2)` will evaluate to true. 221 | 222 | The output of the code in this checkpoint will hence be: 223 | ``` 224 | true 225 | false 226 | true 227 | ``` 228 | 229 | ## 13.25 ## 230 | `list1` is just a shallow copy of `list` so any changes made to `list` will affect the content of `list1`. 231 | 232 | `list2` is a deep copy of `list` constructed by cloning `list`. Following changes of `list` will hence not affect `list2`. 233 | 234 | Output when running the code from this checkpoint will be: 235 | ``` 236 | true 237 | false 238 | list is [New York, Atlanta] 239 | list1 is [New York, Atlanta] 240 | list2.get(0) is New York 241 | list2.size() is 1 242 | ``` 243 | 244 | ## 13.26 ## 245 | The problem is that `clone()` is not visible when y shall be defined. 246 | 247 | Override `clone()` and make it public, and have the class `GeometricObject` implement `Java.lang.Cloneable` to fix this problem. 248 | 249 | ## 13.27 ## 250 | One major advantage with interfaces is that a class can can only inherit from one superclass but it can extend multiple interfaces. 251 | 252 | Say that we have the interfaces: 253 | - AirConditioning 254 | - Light 255 | - Door 256 | - Lock 257 | - Radio 258 | - Speedometer 259 | 260 | Then assume that we have the classes House, Car, Bicycle. All these classes could then possible implement several of the above interfaces but likely not all. A Bicycle will for example probably have a lights and a lock but not a door. 261 | 262 | Interfaces makes it possibly to bind things that are less tightly bound to an Object. Things that can be applied in multiple different situations. 263 | 264 | ## 13.28 ## 265 | An abstract class is a class that is declared with the keyword abstract, it may or may not include abstract methods. Abstract classes cannot be instantiated, but they can be sub-classed. 266 | 267 | An interface is a collection of abstract methods. A class implements an interface, thereby inheriting the abstract methods of the interface. 268 | 269 | Stole this part from the [The Java Tutorials - Abstract Method and Classes](https://docs.oracle.com/javase/tutorial/java/IandI/abstract.html) that discusses the differenses between intefacees and abstract classes. 270 | > Abstract classes are similar to interfaces. You cannot instantiate them, and they may contain a mix of methods declared with or without an implementation. However, with abstract classes, you can declare fields that are not static and final, and define public, protected, and private concrete methods. With interfaces, all fields are automatically public, static, and final, and all methods that you declare or define (as default methods) are public. In addition, you can extend only one class, whether or not it is abstract, whereas you can implement any number of interfaces. 271 | 272 | ## 13.29 ## 273 | **(a)** 274 | An interface is compiled into a separate bytecode file. 275 | **(b)** 276 | An interface can not have static methods. 277 | **(c)** 278 | An interface can extend one or more interfaces. 279 | **(d)** 280 | An interface cannot extend an abstract class. 281 | **(e)** 282 | An abstract class can extend an interface. 283 | 284 | ## 13.30 ## 285 | A rational number with the value -2 / 6 = -1 / 3 is created. The numerator is -1 and the denominator is 3. The integer representation will be truncated to 0. The double representation will be -0.333333333... 286 | 287 | The output of the code in this checkpoint will be: 288 | ``` 289 | -1 290 | 3 291 | 0 292 | 0.333333333333 293 | ``` 294 | ## 13.31 ## 295 | The problem is that r2 is of type Object and this type of class does not have a method called compareTo. 296 | 297 | ## 13.32 ## 298 | The problem is that the parameter for the compareTo method is of the wrong type. Shall be of type Rational but r1 is of type Object. 299 | 300 | 301 | 302 | -------------------------------------------------------------------------------- /Chapter_13/Exercise_02/Exercise_13_02.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | 3 | /** 4 | * Exercise 13.2 from the book Introduction to Java Programming (10th). 5 | *

6 | * Shuffle ArrayList 7 | *

8 | * Method that shuffles an ArrayList of numbers and a main method to test the 9 | * shuffle method. 10 | */ 11 | 12 | public class Exercise_13_02 { 13 | 14 | public static void main(String[] args) { 15 | ArrayList list = new ArrayList(); 16 | 17 | list.add(14); 18 | list.add(24); 19 | list.add(4); 20 | list.add(42); 21 | list.add(5); 22 | 23 | shuffle(list); 24 | 25 | for (int i = 0; i < list.size(); i++) 26 | System.out.print(list.get(i) + " "); 27 | } 28 | 29 | public static void shuffle(ArrayList list) { 30 | for (int i = 0; i < list.size() - 1; i++) { 31 | int index = (int) (Math.random() * list.size()); 32 | Number temp = list.get(i); 33 | list.set(i, list.get(index)); 34 | list.set(index, temp); 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /Chapter_14/Checkpoints_Ch_14.md: -------------------------------------------------------------------------------- 1 | # Checkpoint Answers Chapter 14 # 2 | ## 14.1 ## 3 | The initial version of the GUI library was known as the Abstract Windows Toolkit (AWT). Maps Java code to each operating system's real GUI system. Limited to lowest common denominator among the supported system's. 4 | 5 | After AWT came another version called Swing. Paints all GUI components by itself instead of relying on the underlying operating system. 6 | 7 | Swing is now being replaced by a third version called JavaFX. JavaFX aims to be better suited for today's systems with for example multi-touch support. 8 | 9 | ## 14.2 ## 10 | Some reasons for that this book does not teach AWT or Swing: 11 | 1. JavaFX is considered to be the easiest to learn for beginners. 12 | 2. JavaFX is well designed, based around solid object oriented thinking. 13 | 3. JavaFX is the GUI library is the one that is being actively developed by Oracle. Swing will not get any further updates. 14 | 15 | ## 14.3 ## 16 | A JavaFX main class is defined by extending the Application class. 17 | ```Java 18 | public class MyJavaFX extends Application 19 | ``` 20 | The signature of the start method in the application class is: 21 | ```Java 22 | public void start(Stage primaryStage) 23 | ``` 24 | A Stage is a construct that functions as a base window for JavaFX content. An application can have multiple Stages. 25 | 26 | A Stage object called primary stage is automatically created by the JVM when the application is launched. 27 | 28 | A Stage object is displayed by invoking the show method. 29 | ```Java 30 | Stage stage = new Stage(); 31 | 32 | // ... 33 | // setup of the stage here 34 | // ... 35 | 36 | stage.show(); 37 | ``` 38 | It is possible to prevent the user from resizing a stage. 39 | ```Java 40 | stage.setResizable(false); 41 | ``` 42 | 43 | The instruction `Application.launch(args)` is needed in development environments with limited support for JavaFX. This can be replaced by `launch(args)`, because the JavaFX main class is a subtype of Application. 44 | 45 | ## 14.4 ## 46 | The output of the program in this exercise is: 47 | ``` 48 | launch application 49 | Test constructor is invoked 50 | start method is invoked 51 | ``` 52 | 53 | ## 14.5 ## 54 | There are some different constructors that can be used to create a Scene. 55 | 56 | Creation of a Scene for a specific root Node. 57 | ```Java 58 | Scene(Parent root) 59 | ``` 60 | 61 | Creation of a Scene for a specific root Node with a specific size. 62 | ```Java 63 | Scene(Parent root, double width, double height) 64 | ``` 65 | 66 | See the documentation for more examples of constructors for creation of Scene instanses. 67 | 68 | A Scene is set on a Stage by invoking a member method called: 69 | ``` 70 | setScene(Scene value) 71 | ``` 72 | 73 | A circle is placed in a Scene by first placing the circle in a pane. This pane can then be placed in the Scene. 74 | 75 | ## 14.6 ## 76 | A pane is a form of container for content called nodes. 77 | 78 | A node is a component that have a visual representation and can hence be displayed in a GUI. 79 | 80 | A node can be placed into a pane: 81 | ```Java 82 | pane.getChildren().add(node) 83 | ``` 84 | 85 | It is not possible to place a Shape or ImageView into a Scene. These must be placed on for example a pane and this pane can then be placed in the Scene. 86 | 87 | A control or a pane can be place into a scene when constructing a Scene using `new Scene(Parent, width, height)` or `new Scene(Parent)`. Parent is the superclass for Control and Pane. 88 | 89 | ## 14.7 ## 90 | There are several constructor variants that can be used to create a Circle. 91 | ```Java 92 | Circle() // creates an empty instance 93 | Circle(double radius) // specified radius 94 | Circle(double centerX, double centerY, double radius) // specified position and radius 95 | Circle(double x, double y, double r, Paint fill) // specified position, radius and fill 96 | Circle(double radius, Paint fill) // specified radius and fill 97 | ``` 98 | The methods for setting the center of a Circle instance is: 99 | ```Java 100 | void setCenterY(double value) 101 | ``` 102 | The method for setting the radius of a Circle instance is: 103 | ```Java 104 | void setRadius(double value) 105 | ``` 106 | The method for setting the stroke color of a Circle instance is: 107 | ```Java 108 | public final void setStroke(Paint value) 109 | ``` 110 | The method for setting the fill color of a Circle instance is: 111 | ```Java 112 | public final void setFill(Paint value) 113 | ``` 114 | ## 14.8 ## 115 | A binding property is used to bind with a source object. Any changes to the source will be reflected in the bound target. 116 | 117 | A binding property is an instance of of the interface Property. 118 | 119 | A source object is an instance of the inteface ObservableValue. 120 | 121 | The binding object types for int, long, float, double, and boolean are IntegerProperty, LongProperty, DoubleProperty, and BooleanProperty. 122 | 123 | The classes Integer and Double are not subtypes of ObservableValue. Hence, they cannot be used as a source object in a binding. 124 | 125 | ## 14.9 ## 126 | The naming convention that shall be used is as follows. 127 | 128 | The getter method is: 129 | ```Java 130 | public int getAge() 131 | ``` 132 | 133 | The setter method is: 134 | ```Java 135 | public void setAge(int age) 136 | ``` 137 | 138 | The property getter is 139 | ```Java 140 | public IntegerProperty ageProperty() 141 | ``` 142 | 143 | ## 14.12 ## 144 | The border color of a node can be set by the use of a style. Here is an example of how to set the border color to red. 145 | ```Java 146 | node.setStyle("-fx-border: red"); 147 | ``` 148 | In i similar way so can the text color of some element be set to a color of choice. 149 | ```Java 150 | text.setStyle("-fx-fill: red"); 151 | ``` 152 | 153 | ## 14.13 ## 154 | Elements such as pane, text, or button can be rotated. 155 | 156 | Rotation of a button 15 degrees counterclockwise is done in the following way. 157 | ```Java 158 | button.setRotate(-15); 159 | ``` 160 | 161 | ## 14.14 ## 162 | There are various constructors or static methods that can be used to create a Color. The following constructor creates a Color with the specified red, green, blue, and opacity values. 163 | ```Java 164 | Color(double red, double green, double blue, double opacity) 165 | ``` 166 | The following attempt to create a Color is incorrect because all parameters shall be in the range from 0.0 to 1.0. 167 | ```Java 168 | new Color(1.2, 2.3, 3.5, 4) // error 169 | ``` 170 | Higher values supplied to the above constructor means lighter colors so when creating two colors, `c1 = new Color(0, 0, 0, 1)` and `c2 = new Color(1, 1, 1, 1)` so will c2 be lihter than c1. 171 | 172 | Invoking `c.darker()` will not change the color value in c, instead so will a new darker color object, based on c, be returned. 173 | 174 | ## 14.15 ## 175 | A Color object with a random color can be created in the following way. 176 | ```Java 177 | new Color(Math.random(), Math.random(), Math.random(), 1) 178 | ``` 179 | ## 14.16 ## 180 | Setting the fill color of a circle can be achieved with either the setFill method or the setStyle method. 181 | ```Java 182 | c.setFill(Color.BLUE) 183 | c.setStyle("-fx-fill: blue") 184 | ``` 185 | ## 14.17 ## 186 | Creation of a Font object with font name Courier, size 20, and weight bold. 187 | ```Java 188 | font("Courier", FontWeight.BOLD, 20) 189 | ``` 190 | 191 | ## 14.18 ## 192 | The available fonts on a system can be found with `Font.getFamilies()` that return a list of strings for font names. 193 | 194 | ## 14.19 ## 195 | An Image is created from a URL like this. 196 | ```Java 197 | new Image(URL) 198 | ``` 199 | An Image is created from a file name in a similar way. 200 | ```Java 201 | new Image(filename) 202 | ``` 203 | 204 | ## 14.20 ## 205 | An ImageView can be created from an Image, or directly from a file or a URL. 206 | ```Java 207 | new ImageView(image) 208 | ``` 209 | 210 | ## 14.21 ## 211 | An Image can be set to multiple ImagViews, but one ImageView can only be displayed on time. 212 | 213 | ## 14.22 ## 214 | The pane types Pane, StackPane, FlowPane, GridPane, BorderPane, HBox and VBox have identical methodology for adding nodes. 215 | ```Java 216 | pane.getChildren.add(node) 217 | ``` 218 | The BorderPane is a special case, the methods setTop, setBottom, setLeft, setRight, and setCenter shall be used when adding nodes to this type of pane. 219 | 220 | A node is removed from a pane in the following way. 221 | ```Java 222 | pane.getChildren().remove(node) 223 | ``` 224 | ## 14.28 ## 225 | Example code that shows how to rotate a text. 226 | ```Java 227 | Text text = new Text("Checkpoint 14.28"); 228 | StackPane pane = new StackPane(); 229 | pane.getChildren().add(text); 230 | text.setRotate(15); 231 | ``` 232 | -------------------------------------------------------------------------------- /Chapter_14/Exercise_02/Exercise_14_02.java: -------------------------------------------------------------------------------- 1 | import javafx.application.Application; 2 | import javafx.geometry.Insets; 3 | import javafx.geometry.Pos; 4 | import javafx.scene.Scene; 5 | import javafx.scene.image.Image; 6 | import javafx.scene.image.ImageView; 7 | import javafx.scene.layout.GridPane; 8 | import javafx.stage.Stage; 9 | 10 | /** 11 | * Exercise 14.2 from the book Introduction to Java Programming (10th). 12 | *

13 | * Tic-tac-toe board. 14 | * 15 | * @author Henrik Samuelsson, henrik.samuelsson(at)gmail.com 16 | */ 17 | 18 | public class Exercise_14_02 extends Application{ 19 | @Override 20 | public void start(Stage primaryStage) { 21 | Image imageX = new Image("res/x.gif"); 22 | Image imageO = new Image("res/o.gif"); 23 | 24 | // create a grid pane to draw the graphics on 25 | GridPane pane = new GridPane(); 26 | pane.setAlignment(Pos.CENTER); 27 | 28 | // add some padding around the pane 29 | pane.setPadding(new Insets(50, 50, 50, 50)); 30 | 31 | // generate and draw random data for the board 32 | for (int row = 0; row < 3; row++) { 33 | for (int col = 0; col < 3; col++) { 34 | int randomGraphic = (int)(Math.random() * 3); 35 | if (randomGraphic == 0) { 36 | pane.add(new ImageView(imageX), col, row); 37 | } else if (randomGraphic == 1) { 38 | pane.add(new ImageView(imageO), col, row); 39 | } 40 | } 41 | } 42 | 43 | // standard JavaFX components needed to display the board 44 | Scene scene = new Scene(pane); 45 | primaryStage.setTitle("Exercise 14.2"); 46 | primaryStage.setScene(scene); 47 | primaryStage.show(); 48 | 49 | } 50 | 51 | public static void main(String[] args) { 52 | launch(args); 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /Chapter_14/Exercise_02/res/o.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HenrikSamuelsson/Introduction_to_Java_Programming/c4ba17abcdde14585c3c7930f167a53cf7ec6bfe/Chapter_14/Exercise_02/res/o.gif -------------------------------------------------------------------------------- /Chapter_14/Exercise_02/res/x.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HenrikSamuelsson/Introduction_to_Java_Programming/c4ba17abcdde14585c3c7930f167a53cf7ec6bfe/Chapter_14/Exercise_02/res/x.gif -------------------------------------------------------------------------------- /Chapter_15/Checkpoints_Ch_15.md: -------------------------------------------------------------------------------- 1 | # Checkpoint Answers Chapter 15 # 2 | ## 15.1 ## 3 | An event source object is an object that can fire an event. 4 | 5 | An event object holds information about an event. 6 | 7 | The relationship between a source object and an event is that the event is an object created by the source. 8 | 9 | ## 15.2 ## 10 | Button is a subclass of Node, therefore, it can fire all the events that Node can fire. Among the event that can be fired are MouseEvent, KeyEvent, and ActionEvent. 11 | 12 | ## 15.24 ## 13 | A timer is setup that will launch a redraw of the ball every 50 ms. The ball is moved a small distance on each redraw. 14 | 15 | ## 15.25 ## 16 | The direction of the ball is reversed by multiplying the control variables dx and dy by -1. 17 | 18 | ## 15.26 ## 19 | Pressing the mouse button while on the ball pane will cause the animation to pause. The animation is paused until the mouse button is released. 20 | 21 | ## 15.27 ## 22 | ```Java 23 | ballPane.requestFocus(); 24 | ``` 25 | The above line of code is taken from the BounceBallControl class in the book. The purpose of this line is to set focus on this node and that this node's top-level ancestor become the focused window. This is necessary for receiving events when the arrow up-key and arrow down-key are pressed. 26 | 27 | ## 15.28 ## 28 | ```Java 29 | animation.setCycleCount(Timeline.INDEFINITE); 30 | ``` 31 | The above line of code is taken from the BallPane class in the book. It sets the Timeline animation to be repeated for an indefinite number of times. Without this line so would the animation only be repeated once. 32 | -------------------------------------------------------------------------------- /Chapter_15/Exercise_02/Exercise_15_02.java: -------------------------------------------------------------------------------- 1 | import javafx.application.Application; 2 | import javafx.geometry.Pos; 3 | import javafx.scene.Scene; 4 | import javafx.scene.control.Button; 5 | import javafx.scene.layout.BorderPane; 6 | import javafx.scene.layout.StackPane; 7 | import javafx.scene.paint.Color; 8 | import javafx.scene.shape.Rectangle; 9 | import javafx.stage.Stage; 10 | 11 | /** 12 | * Exercise 15.2 from the book Introduction to Java Programming (10th). 13 | *

14 | * Rotate a rectangle 15 | */ 16 | 17 | public class Exercise_15_02 extends Application { 18 | private double angle = 0; 19 | 20 | @Override 21 | // Override the start method in the Application class 22 | public void start(Stage primaryStage) { 23 | StackPane stackPane = new StackPane(); 24 | Rectangle rectangle = new Rectangle(30, 30, 30, 60); 25 | rectangle.setFill(Color.WHITE); 26 | rectangle.setStroke(Color.BLACK); 27 | stackPane.getChildren().add(rectangle); 28 | 29 | // Create a button 30 | Button btRotate = new Button("Rotate"); 31 | btRotate.setOnAction(e -> { 32 | angle += 15; 33 | rectangle.setRotate(angle); 34 | }); 35 | 36 | BorderPane pane = new BorderPane(); 37 | pane.setCenter(stackPane); 38 | pane.setBottom(btRotate); 39 | BorderPane.setAlignment(btRotate, Pos.TOP_CENTER); 40 | 41 | // Create a scene and place it in the stage 42 | Scene scene = new Scene(pane, 210, 150); 43 | primaryStage.setTitle("Exercise_15_02"); // Set the stage title 44 | primaryStage.setScene(scene); // Place the scene in the stage 45 | primaryStage.show(); // Display the stage 46 | } 47 | 48 | /** 49 | * The main method is only needed for the IDE with limited JavaFX support. 50 | * Not needed for running from the command line. 51 | */ 52 | public static void main(String[] args) { 53 | launch(args); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /Chapter_16/Checkpoints_Ch_16.md: -------------------------------------------------------------------------------- 1 | # Checkpoint Answers Chapter 16 # 2 | ## 16.1 ## 3 | A label with a node but without a text is created in a two step process. First create Label with the no-arg constructor, then set the labels graphic property to a node. 4 | 5 | ## 16.2 ## 6 | The following code shows how to adjust the label so that it is placed on the right of its node. 7 | ```Java 8 | label.setContentDisplay(ContentDisplay.LEFT); 9 | ``` 10 | 11 | ## 16.3 ## 12 | Usage of `\n` makes it possible to divide a label text into multiple lines. 13 | 14 | ## 16.4 ## 15 | It is possible to underline a text in a label by setting an underline property. 16 | ```Java 17 | label.setunderLine(true); 18 | ``` 19 | 20 | ## 16.5 ## 21 | A button with a text (Left) and a node (in this case an image) is created in the following way. 22 | ```Java 23 | Button btLeft = new Button("Left", new ImageView("left.gif")); 24 | ``` 25 | The class Button is a subclass of Labeled so Button can invoke all the methods in Labeled. 26 | 27 | ## 16.6 ## 28 | The `getPane()` method and the member `Text` in Listing 16.2 are declared as protected because they are intended to be used in subclasses later on in the book. 29 | 30 | ## 16.7 ## 31 | The method `setOnAction(handler)` is used to set a handler for processing a button-clicked action. 32 | 33 | -------------------------------------------------------------------------------- /Chapter_17/Checkpoints_Ch_17.md: -------------------------------------------------------------------------------- 1 | # Checkpoint Answers Chapter 17 # 2 | ## 17.1 ## 3 | A text file can be thought of as a sequence of characters and a binary file can be thought of as a sequence of bits. 4 | 5 | Take for example the number 199 that will in a text file be stored as '1','9','9' but with each character coded according to some standard such as the Unicode standard or the ASCII standard. 6 | 7 | If 199 is stored as binary so will it instead be stored in some form of hex format possibly as 0xC7. 8 | 9 | ## 17.2 ## 10 | Common classes to use when reading or writing file data are Scanner and PrintWriter. 11 | ```Java 12 | // Reading from temp.txt 13 | Scanner input = new Scanner(new File("temp.txt")); 14 | System.out.println(input.nextLine()); 15 | input.close(); 16 | ``` 17 | ```Java 18 | // Writing to temp.txt 19 | PrintWriter output = new PrintWriter("temp.txt"); 20 | output.print("Java 101"); 21 | output.close(); 22 | ``` 23 | 24 | ## 17.22 ## 25 | A File object is used to check if a file exists. 26 | ```Java 27 | File sourceFile = new File("temp.bin"); 28 | if (sourceFile.exists()) 29 | System.out.println("File temp.bin exists."); 30 | else 31 | System.out.println("File temp.bin does not exist."); 32 | ``` 33 | 34 | ## 17.23 ## 35 | The read method will return -1 when the end of a file is reached. 36 | ```Java 37 | if (r = input.read()) == -1) 38 | System.out.println("No more data to read in the file."); 39 | ``` 40 | -------------------------------------------------------------------------------- /Chapter_18/Checkpoints_Ch_18.md: -------------------------------------------------------------------------------- 1 | # Checkpoint Answers Chapter 18 # 2 | ## 18.1 ## 3 | A recursive method is the one that calls itself. 4 | 5 | An infinite recursion is the one that never stops. This is an error usually caused by a missing base case or by a faulty inductive step. -------------------------------------------------------------------------------- /Chapter_19/Checkpoints_Ch_19.md: -------------------------------------------------------------------------------- 1 | # Checkpoint Answers Chapter 19 # 2 | ## 19.1 ## 3 | **(a)** 4 | The below code will compile, but will fail at runtime. 5 | ```Java 6 | ArrayList dates = new ArrayList(); 7 | dates.add(new Date()); 8 | dates.add(new String()); 9 | ``` 10 | 11 | **(b)** 12 | The below code will not compile. The compiler will spot that a String is added to a list of Date objects. 13 | ```Java 14 | ArrayList dates = 15 | new ArrayList<>(); 16 | dates.add(new Date()); 17 | dates.add(new String()); 18 | ``` 19 | ## 19.4 ## 20 | The generic definition for `java.lang.Comparable` in the Java API. 21 | ```Java 22 | package java.lang; 23 | 24 | public interface Comparable { 25 | public int compareTo(T o) { } 26 | } 27 | ``` 28 | 29 | ## 19.6 ## 30 | A generic class can have multiple generic parameters. 31 | 32 | ## 19.8 ## 33 | A generic method is declared by placing the generic type immediately after the keyword static in the method. 34 | 35 | Example: 36 | ```Java 37 | public static void print(T[] list) { 38 | for (int i = 0; i < list.length; i++) 39 | System.out.print(list[i] + " "); 40 | System.out.println(); 41 | } 42 | ``` 43 | A generic method can be invoked just like a regular method. The compiler will figure out the actual type. 44 | 45 | Example: 46 | ```Java 47 | String[] strings = {"London", "Paris", "New York", "Austin"}; 48 | print(strings); 49 | ``` 50 | 51 | ## 19.9 ## 52 | A bounded generic type specifies that the accepted generic types must be subclasses of a given class. 53 | 54 | -------------------------------------------------------------------------------- /Chapter_20/Checkpoints_Ch_20.md: -------------------------------------------------------------------------------- 1 | # Checkpoint Answers Chapter 20 # 2 | ## 20.1 ## 3 | A data structure is a particular way of organizing data in a computer so that it can be used efficiently. Data structures can implement one or more particular abstract data types, which are the means of specifying the contract of operations and their complexity. In comparison, a data structure is a concrete implementation of the contract provided by an abstract data type. 4 | -------------------------------------------------------------------------------- /Chapter_21/Checkpoints_Ch_21.md: -------------------------------------------------------------------------------- 1 | # Checkpoint Answers Chapter 21 # 2 | ## 21.10 ## 3 | A HashSet is a good choice when needing to store unordered non-duplicate elements. 4 | -------------------------------------------------------------------------------- /Chapter_22/Checkpoint_Ch_22.md: -------------------------------------------------------------------------------- 1 | # Checkpoint Answers Chapter 22 # 2 | ## 22.1 ## 3 | The constant factor is ignored in big O notation, because it has no impact on the growth rate of the time complexity function. 4 | 5 | A non-dominating term is ignored in Big O notation, because as the input size grows, the dominating term grows much faster than the non-dominating term. Ignoring the non-dominating term will introduce an error in the estimation but keeps things much cleaner. 6 | 7 | ## 22.2 ## 8 | **(a)** 9 | O(n^3) 10 | 11 | **(b)** 12 | O(n^3) 13 | 14 | **(c)** 15 | O(n^3) 16 | 17 | **(d)** 18 | O(2^n) 19 | 20 | **(e)** 21 | O(n^2 * 2^n) 22 | 23 | -------------------------------------------------------------------------------- /Chapter_23/Checkpoint_Ch_23.md: -------------------------------------------------------------------------------- 1 | # Checkpoint Answers Chapter 23 # 2 | ## 23.1 ## 3 | Insertion sort works the same way as one would sort a hand of cards, i.e. starting with an empty left hand and the cards in the deck face down on the table. One card at a time is then dealt from the table and inserted into the correct position in the left hand. To find the correct position for a card, it is compared with each of the cards already in the hand, from right to left. 4 | 5 | The time complexity for insertion sort is O(n^2). 6 | 7 | ## 23.4 ## 8 | Bubble sort will repeatedly step through the list to be sorted, compares each pair of adjacent items and swaps them if they are in the wrong order. The pass through the list is repeated until no swaps are needed, which indicates that the list is sorted. 9 | 10 | The time complexity for a bubble sort is O(n^2). 11 | 12 | ## 23.7 ## 13 | Quicksort is a divide and conquer algorithm. Quicksort first divides a large array into two smaller sub-arrays: the low elements and the high elements. Quicksort can then recursively sort the sub-arrays. 14 | 15 | The steps are: 16 | 17 | 1. Pick an element, called a pivot, from the array. 18 | 2. Reorder the array so that all elements with values less than the pivot come before the pivot, while all elements with values greater than the pivot come after it (equal values can go either way). After this partitioning, the pivot is in its final position. This is called the partition operation. 19 | 3. Recursively apply the above steps to the sub-array of elements with smaller values and separately to the sub-array of elements with greater values. 20 | 21 | The time complexity for a merge sort is O(nlogn). 22 | 23 | ## 23.14 ## 24 | The return value will be null when invoking the remove method if the heap is empty. 25 | 26 | ## 23.21 ## 27 | Bucket sort is not suitable for sorting strings. 28 | -------------------------------------------------------------------------------- /Chapter_24/Checkpoint_Ch_24.md: -------------------------------------------------------------------------------- 1 | # Checkpoint Answers Chapter 24 # 2 | ## 24.1 ## 3 | MyList extends Iterable which means that if we have list that is an instance of MyList, so can we get an iterator for list using list.iterator(). 4 | -------------------------------------------------------------------------------- /Chapter_25/Checkpoint_Ch_25.md: -------------------------------------------------------------------------------- 1 | # Checkpoint Answers Chapter 25 # 2 | ## 25.4 ## 3 | The time complexity of inserting an element to a binary tree is O(n). 4 | 5 | ## 25.8 ## 6 | The time complexity of deleting an element from a binary tree is O(n). 7 | 8 | ## 25.10 ## 9 | The displayTree method will be invoked 0 time if the tree is empty. 10 | 11 | The displayTree method will be invoked 100 times if the tree has 100 nodes. 12 | -------------------------------------------------------------------------------- /Chapter_26/Checkpoint_Ch_26.md: -------------------------------------------------------------------------------- 1 | # Checkpoint Answers Chapter 26 # 2 | ## 26.1 ## 3 | AVL trees are a form of BST tree but always well-balanced. In an AVL tree, the difference between the heights of two subtrees for every node is 0 or 1. 4 | 5 | The balance factor of a node is the height of its right subtree minus the height of its left subtree. 6 | 7 | A node is said to be balanced if its balance factor is -1, 0, or 1. 8 | 9 | A node is said to be left-heavy if its balance factor is -1. 10 | 11 | A node is said to be right-heavy if its balance factor is +1. 12 | 13 | ## 26.4 ## 14 | AVLTreeNode defines the data field `height`, that stores the height of the node. 15 | 16 | AVLTreeNode inherits from TreeNode so it will also have the data fields `left` and `right`, that points to the left and right subtree. 17 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2015 Henrik Samuelsson 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | 23 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Introduction to Java Programming # 2 | My exercise solutions and notes related to the book Introduction to Java Programming. 3 | 4 | ## Book Details ## 5 | Title: Introduction to Java Programming 6 | Subtitle: Comprehensive Version 10th Edition 7 | Author: Y. Daniel Liang 8 | Publication date: 25 January 2014 9 | ISBN 10: 0133813460 10 | ISBN 13: 9780133813463 11 | 12 | ![alt text](http://www.cs.armstrong.edu/liang/image/intro10eComprehensive.jpg "Book cover") 13 | --------------------------------------------------------------------------------