1. Trang chủ
  2. » Công Nghệ Thông Tin

Java quizmaster for beginners learn, test and improve your java skills in 105 quizzes , 117 assignments and many examples

311 96 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 311
Dung lượng 1,06 MB

Nội dung

Java Quizmaster for Beginners L E A R N , T E S T A N D I M P R O V E Y O U R J AVA S K I L L S I N 105 QUIZZES, 11 ASSIGNMENTS AND MANY CODE EXAMPLES Sar Maroof Don't explain Java to me, but show me how it works! Copyright © 2017 Sar Maroof All rights reserved ISBN: 978-1-975-78178-1 Table of contents Introduction Chapter 1—Data Types & Variables 16 Chapter 2— Operators Chapter 3—Conditional Statements 40 Chapter 4—Iteration (Loop) Statements 64 Chapter 5—Classes, Objects And Constructors 87 Chapter 6— Methods Chapter 7—Strings & Stringbuffer 121 Chapter 8—Packages & Access Modifiers 137 Chapter 9—Arrays & Arraylist 145 Chapter 10—Static Members 165 Chapter 11— Inheritance Chapter 12—Final Classes & The Final Keyword 199 Chapter 13—Abstract Classes 207 Chapter 14— Interfaces Chapter 15— Casting Chapter 16—Nested Classes 242 Chapter 17— Exceptions About the author Sar Maroof is graduated from HBO Amsterdam “higher professional education” when he had already a bachelor of science degree in Physics In his academic study, he also had the opportunity to study information technology He was a teacher when he decided to follow several professional trainings to start his career as a Java, web developer He has worked for many years for several big as well as small companies and later as a freelancer The combination of his experiences and skills as a teacher and a Java web developer inspired him to share his knowledge with enthusiastic younger generations through writing books He handles his own method of teaching programming by focusing on a practical way to learn it This method is quite obvious in his books namely Java quizmaster for beginners and Java assignment in practice About this book Thousands of words cannot describe a face better than a picture This principle also applies to learning programming When I followed several trainings, the focus was on theoretical explanations Each lesson contained many terms and technical words Because of my background and experience as a teacher, I wondered if that boring method was the best way to learn programming In reality, working as a programmer is quite different than what the most traditional trainings would teach you In fact, no one asks whether you know a particular term, but you will get hundreds of lines of code, and you must be able to deal with it You will be asked to build new features Sometimes you need to write Java classes or develop a program If you are not familiar with the code, the theory can very little for you The most efficient way is not to bother with theories in the beginning, but spend time to work with Java code Change the variables, statements and test the code over and over again to see what happens This book offers many complete executable small programs (quizzes) to practice programming from the very beginning Unfortunately, a computer doesn't explain how it comes with a specific result, and that is why this book provides a step by step explanation of the right answers to all the quizzes This method helps beginners to focus on testing the code When the result of executing the programs doesn't match their expectations, they start to think about solving the problem The good news is that as soon as you start to understand the code, you can't stop working with it Many programmers work in the evening or even in the night because it is a very creative and interesting work This book prepares students for what is expected from them and prevents them to memorize technical terms without understanding it I not mean that theory is not important, but focusing on all kinds of theories from the beginning is ineffective and slow If you start with programming, you will face many problems that require being solved In such cases, you will also learn a lot from theories, because it supports what you practice If you work as a programmer, you can expect a number of types of assignments It doesn't matter what kind of companies you work You can expect the following assignments: Understanding code that has been written by other programmers Building new features for existing software Detecting bugs and fixing them in an existing program Developing new programs from scratch For the last point, you usually need a few years’ experience Each chapter in this book begins with a brief explanation about a particular Java topic including one or more examples Then you start to work with quizzes To choose the correct answer, you need to understand the code That is similar to the first point of our list If you are unable to find the right answer, you can read the step-by-step explanation of the answer This is a very practical method to understand the process After each quiz, you will be asked to add a small piece of your own code to it to achieve a particular goal Sometimes you will be asked to investigate different variations to study other possible results In some quizzes, you will be warned why a certain change in the code can lead to an infinite loop or a problem From the fifth chapter, you will get an assignment which requires you to write a small program regards the whole chapter Programming is solving problems, and that is the most interesting method to learn it If you have a problem, you start to think about a solution, and that helps you to search for any information that can possibly help you to understand it It has also been taken into account that some Java-topics are not used so often, while others you see almost in every program On www.sarmaroof.com, you can find more information about this book and how to setup the code in Eclipse — Sar Maroof Required knowledge This book focuses on learning how to program by practicing with code There will be little theoretical explanation – just enough to solve the quizzes That is a challenge because it is not easy to write a tiny executable program about only one Java topic In every executable program, you see different topics All the programs demonstrate a particular Java topic This book divides the Java programming language into some subjects In each chapter, a number of small executable programs is offered regards that specific topic To make this possible, it is important to be familiar with the following basics It's not required that you understand all the points below properly because details will be covered later in this book The only thing you need to learn to start with is what the role of these points is for the program to compile and run Each chapter of this book begins with a brief explanation, after which the quizzes follow The codes are complete that you can test, compile, and run Java editor We use as Java editor, Eclipse including JDK (Java Development Kit) or higher Eclipse is a free Java IDE (integrated development environment) You can find and download Eclipse on the Internet The JDK tools are included, which is necessary when editing Java-programs The source codes of Java are files with the extension java The compiled bytecode files have the extension class Java is a platform-independent programming language, which is why you can run Java programs on every operating system Compiling programs Compiling is the translation of source code into machine language with the help of a tool (compiler) After compiling a source code, the program is directly executable Java classes and interfaces Java programs contain classes and interfaces These two concepts are covered in details later in this book You only need for now is to learn that a class in Java begins with a statement as class Myclass Myclass is the name of the class, and you can decide the name of the class Every class in Java is stored in a file with the name of the class The class Myclass should be stored in a file with the name of the class and the extension java The name of the file in our example is thus MyClass.java Each class name begins with the keyword class, and each interface name begins with the keyword interface Classes and interfaces also have members like variables and methods Methods are a block code between curly braces Example class MyClass { // code } The following interface must also be stored in a file with the name MyInterface.java Example interface MyInterface { // code } Statements Statements in Java are similar to sentences in natural languages, and they are executable units A statement is usually ended with a semicolon (;) Code block in Java Code in Java is within a start and an end brace This is called block of code Below are some examples of block codes try { int[] intArray = new int[5]; int z = intArray[6]; System.out.print("w"); } catch (ArithmeticException e) { System.out.print("x"); } catch (ArrayIndexOutOfBoundsException e) { System.out.print("y"); } finally { System.out.print("z"); } } public static void main(String[] args) { MyClass mc = new MyClass(); mc.method(); } } Select the correct answer: a This program writes "wz" to the standard output b This program writes "yz" to the standard output c This program writes "wyz" to the standard output d This program writes "xz" to the standard output e This program does not compile Explanation The statement "int z = intArray[6];" tries to access the sixth element of the array intArray, which doesn't exist This exception ArrayIndexOutOfBoundsException occurs and the statement System.out.print("y"), prints "y" to the standard output The finally-block is always executed The statement System.out.print("z"), prints "z" to the standard output The correct answer is b Assignments What happens if the finally-block is removed from the code? Compile and run the program to check out your expectation Quiz 3: Unchecked exceptions and the finally block What happens when the following program is compiled and run? public class MyClass { String str; public void method() { try { str.substring(1); System.out.print("s"); } catch (NullPointerException e) { System.out.print("x"); } catch (Exception e) { System.out.print("y"); } finally { System.out.print("z"); } } public static void main(String[] args) { MyClass mc = new MyClass(); mc.method(); } } Select the correct answer: a This program writes "xz" to the standard output b This program writes "syz" to the standard output c This program writes "yz" to the standard output d This program writes "z" to the standard output e This program does not compile Explanation The String str is a reference to an object, which is not created String str = null; By trying to access a substring of str, a NullPointerException occurs The statement System.out.print("x"), prints x to the standard output The finally block always executed The statement System.out.print("z"), prints z to the standard output The correct answer is a Assignments Assign the value of "Boris" to the variable str What would be the output of the program? Compile and run the code to test your expected result Quiz 4: Handling the exception of divided by zero What happens when the following program is compiled and run? public class MyClass { int x; public void method() { try { int i = / x; System.out.print("a"); } catch (NullPointerException n) { System.out.print("b"); } catch (ArithmeticException e) { System.out.print("d"); } finally { System.out.print("f"); } } public static void main(String[] args) { MyClass mc = new MyClass(); mc.method(); } } Select the correct answer: a This program writes "df" to the standard output b This program writes "ab" to the standard output c This program writes "bf" to the standard output d This program writes "f" to the standard output e This program does not compile Explanation The catch block NullPointerException doesn't catch the exception because dividing by zero is an ArithmeticException The catch block ArithmeticException is executed and prints “d” to the standard output The finally block is always executed, and it prints “f” to the standard output The correct answer is a Assignments Assign the value of 20 to the variable x What is the output if you compile and run the code? Execute the program to test your answer Quiz 5: Which exception is caught? What happens when the following program is compiled and run? public class MyClass { StringBuffer sb; int z; public void myMethod() { try { z = / 0; sb.append("s"); } catch (NullPointerException e) { System.out.print("n"); } catch (ArithmeticException ae) { System.out.print("a"); } } public static void main(String[] args) { MyClass mc = new MyClass(); mc.myMethod(); } } Select the correct answer: a This code writes n to the standard output b This code writes an to the standard output c This code writes a to the standard output d This code writes na to the standard output e This code cannot be compiled Explanation The two statements of the try block cause exceptions, but the first statement is first executed The first statement causes ArithmetcException , therefore, is the second catch-block is executed The statement System.out.print("a"); writes a to the standard output The correct answer is c Assignments What is the result of the execution of the program if the position of the statements within the try block is changed as following? sb.append("s"); z = 5/0; Compile and run the program to check out your answer Quiz 6: Throwing an exception What happens when the following program is compiled and run? public class MyClass { static String str = ""; static void calculate(int x, int y) { str += "A"; if (y == 0) { throw new ArithmeticException(); } int z = x / y; str += "B"; } public static void main(String[] args) { try { str += "C"; calculate(10, 0); str += "D"; } catch (ArithmeticException e) { str += "E"; } catch (ArrayIndexOutOfBoundsException ae) { str += "F"; } System.out.println(str); } } Select the correct answer: a This code writes ABE to the standard output b This code writes CAF to the standard output c This code writes CAE to the standard output d This code writes ABCD to the standard output e This code can not be compiled Explanation The statement str += "C"; inside the try-block adds the letter C to the String str The statement calculate(10, 0); calls the method calculate The statement str += "A" within the method calculate adds the letter A to the String str The statement if(y == 0) returns true and the exception ArithmeticException is thrown The catch block of the exception, ArithmeticException is caught The statement str += "E"; adds the letter E to the String str The correct answer is c Assignments What is written to the standard output if the statement throw new ArithmeticException(); is replaced with the statement throw new ArrayIndexOutOfBoundsException(); ? Compile and run the program to check Quiz 7: The keyword throw What happens when the following program is compiled and run? public class MyClass { public static void test(String str) { if (str == null) { throw new NullPointerException(); } else { throw new RuntimeException(); } } public static void main(String[] args) { try { System.out.print("A"); test(""); } catch (NullPointerException e) { System.out.print("B"); } catch (Exception e) { System.out.print("C"); } finally { System.out.print("D"); } } } Select the correct answer: a This code writes the AD to the standard output b This code writes ABCD to the standard output c This code writes AC to the standard output d This code writes ACD to the standard output e This code can not be compiled Explanation The statement System.out.print("A"); within the try-block writes A to the standard output The method test("") is invoked If the statement if(str == null) returns true, the exception NullPointerException is caught, otherwise a RuntimeException The parameter of the method test("") is not equal to null , therefore, the RuntimeException is thrown The catch block Exception is higher in the exception class hierarchy than the RuntimeException, which is why it is caught See diagram for the exception class hierarchy The statement System.out.print("C"); writes the letter C to the standard output The finally block is always executed, therefore, the letter D is also written to the standard output The correct answer is d Assignments What would be written to the standard output if the statement test(""); within the try-block is replaced by the statement test(null);? Compile and run the program to check out your answer Assignment chapter 17: Create your own exception class In the following program, a customized exception class is created with the name MyException The method getMovie(int movieIndex) is invoked in the main method, but the body of the method is missing Write the missing statements in the body of the method getMovie If the movieIndex is greater than 5, the program should write “the movie does not exist” Throw the exception MyException If a movieIndex exist, the program should write the title of the movie to the standard output For index the program writes The Godfather to the standard output For index the program writes Titanic to the standard output, and so on Test your program whether it works properly Replace in the catch block, the statement System.out.print(me.getMessage()); with the statement me.printStackTrace(); Run the program to see the difference between the methods getMessage and printStackTrace public class MyException extends Exception { public MyException(String message) { super(message); } } import java.util.ArrayList; public class Test { private static ArrayList movieList = new ArrayList(); public static void populateList() { movieList.add("The Godfather"); movieList.add("Titanic"); movieList.add("Dances with Wolves"); movieList.add("The Pianist"); movieList.add("Wall Street"); movieList.add("Amadeus"); } public static String getMovie(int movieIndex) throws MyException { // the body } public static void main(String args[]) { populateList(); try { String movie = getMovie(5); System.out.print("The movie title is: " + movie); } catch (MyException me) { System.out.print(me.getMessage()); } } } Index abstract, 207 access modifiers, 137 accessors, 15 API documentation, 121 array, 145 ArrayList, 151 arrays See array boolean, 17 break statement, 44, 66 break statement, 44 byte, 16 casting, 230 catch block, 254 char, 17 class, 7, 87 class, class variables, 18, 107, 108, 165 comment, 11 compile, constants, 43 constructor, 89 continue statement, 67 encapsulation, 15 errors, 263 escape sequences, 13 exceptions, 252 final class, 199 final method, 199 finally, 259 float, 17 for loop, 64 if statements, 40 if/else statements, 41 if-/else-if statements, 42 if-block, 41 import, 137, 138 inheritance, 15, 177 inner class, 243, 244 instance variables, 107, 165 Instance variables, 18 integer, 16 interface, 8, 220 iteration statements, 64 label, 68 long, 16 loops, 64 method, 87, 102 method overloading, 15, 183 mutator, 15 class, 242 nested class, 242 object, 87 operand, 24 operators, 24 OR, 25 overloading, 15 overloading methods, 183 overriding, 15 package, 137 parameters, 104 plus, 11 polymorphism, 15 primary variable, 17 private, 138 protected, 137 public, 9, 137 RunTimeException, 253 short, 16 sort, 107, 148 standard output, 10 statement, static, 11, 12, 108, 165 static methods, 166 static nested class, 242, 243 string, 121 StringBuffer, 121, 124 substring, 122 super, 178, 180 switch statement, 43 this, 91, 92, 167 throw, 252, 260 throwable, 252 throws, 252, 260 toString, 125 toUpperCase, 122 trim, 122 try, 254 try-catch-block See try variable, 16 while loop, 65 wrapper classes, 108 .. .Java Quizmaster for Beginners L E A R N , T E S T A N D I M P R O V E Y O U R J AVA S K I L L S I N 105 QUIZZES, 11 ASSIGNMENTS AND MANY CODE EXAMPLES Sar Maroof Don't explain Java to me, but... This code writes "8 0, 0, 3. 5, 0. 0, 0.0" to the standard output b This code writes "8 0, 0, 3. 5, 0, 0" to the standard output c This code writes "8 0, 0, 3. 5, 0. 0, 0" to the standard output Explanation... There are primitive data types in Java, which can be declared by programmers Those types are: byte, short, int, long, float, double, char and boolean, which are divided into categories as shown below

Ngày đăng: 05/03/2019, 08:38

TỪ KHÓA LIÊN QUAN

TÀI LIỆU CÙNG NGƯỜI DÙNG

TÀI LIỆU LIÊN QUAN

w