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

Practical OCA java SE 8 programmer i certification guide (java basics)

108 304 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

Nội dung

Practical OCA Java SE Programmer I: Certification Guide Table of Contents Chapter Define the scope of variables Define structure of a class Package statement Import statement Comments Class declaration Class definition Variables Methods Constructors Interface definition Single and multiple classes in a single Java file Create executable Java applications with a main method; run a Java program from the command line; produce console output Running Java programs in both IDE and command line Import other Java packages to make them accessible in your code Defining class in a package Package tree and import statement Importing from the default package Static imports Java access modifiers Public access Protected Default Private Non-access modifiers Abstract class Abstract method Abstract interface Final non-access modifier Final interface Final variable Final method Static variables Static methods Access members from a null reference Compare and contrast the features and components of Java such as: platform independence, object orientation, encapsulation, etc Components of Java Platform-independence Object orientation Abstraction Encapsulation Inheritance Polymorphism Type safety Memory management Multithreading and concurrency Security Irrelevant features of Java Single-threaded JavaScript About the author My name is Marks Bhele and I have over 10 years of experience in the IT industry as a Developer I am currently working for a major bank as a Java Developer I also have extensive experience in programming using PHP I have years of lecturing experience I have lectured at a college for four years and two years at a high school I tried moving away from teaching; but the love I have for sharing my knowledge is unquenchable So I decided to juggle both teaching online and working as a Java Developer at the same time Who is this eBook for? This eBook is not an introduction to Java by any means It is assumed that the reader has had some Java programming experience or familiarity I wrote this eBook specifically for those who want to pursue OCA Java SE Programmer I Certification: Exam number 1Z0-808 I have covered all the exam objectives for the topic Java Basics as laid out on the Oracle website How to use this eBook? You need to run all the programs on your PC If you don’t, you will be wasting your time as the approach to this eBook is practical-oriented If you adopt this approach, you will benefit more from this eBook Please have the relevant software installed before doing anything Please install JDK and any IDE of your choice Contact author You can contact me on this email address: support@xecson.com Please use this email address to report any errors you find in this eBook Copyright Copyright © 2017 by Xecson (Pty) Ltd All rights reserved This eBook or any portion thereof may not be reproduced or used in any manner whatsoever without the express written permission of the publisher except for the use of brief quotations in a book review Java Basics Objectives Define the scope of variables Define the structure of a Java class Create executable Java applications with a main method; run a Java program from the command line, including console output Import other Java packages to make them accessible in your code Compare and contrast the features and components of Java such as platform-independence, object orientation, encapsulation, etc Define the scope of variables Exam Objective The scope of a variable refers to the accessibility of a variable at various points in your code You can have a variable in your program which might be inaccessible at certain points depending on what you are trying to achieve with the usage of the variable The main thing to look out for is the curly braces {} to be able to tell whether or not the variable is out of scope If the variable is referred to be out of scope; it simply means it is not accessible from the code below the closing ;} curly bracket If we say the variable is in scope; it means it is still accessible in your code We will now look at the code example in order to see how variable scope woks using the following: ü ü ü Method Loops Class Let’s now look at the method example A method signature has a method name, parenthesis, parameters and we complete a method definition by {} opening and closing curly braces Let’s see an example of a simple method which does nothing since there won’t be any executable statements: public void calculateNumbers(int num){ } I have a method name calculateNumbers() It receives an int parameter called num The variable num can only store integers Our method returns void; meaning nothing num variable can only and only be used inside this method; that is inside the curly braces We cannot access this variable outside the method This means, the variable will have run out of scope outside the method If we try to use it outside the curly braces; we will have a compile error as the variable is not known outside the method This variable is said to be local to this method We are now going to expand this example to have executable code inside the method We are going to declare a variable inside the method Here is an example: public void calculateNumbers(int num){ int sum = 10; } I have declared a variable sum of type integer This is a local variable It is local to the method calculateNumbers You cannot use this variable outside this method Remember this variable is in scope where the method braces begin {; and where they end} Below the closing curly brace, the variable runs out of scope Meaning it is not accessible anymore Please also note that you cannot use this variable in this method if it is not initialized, hence I initialized mine Instance variables are different because they have default values based on their data types; for instance int variable defaults to 0, boolean defaults to false, etc Let’s now add a twist to our code by using the sum variable in an if statement within our method public void calculateNumbers(int num){ int sum = 10; if(sum > 11){ int x = 11; } System.out.println(x); } I have an if statement checking if sum; which is 10; is greater than number 11 Then inside the if statement; meaning between its curly brackets {}, I declare a variable x and set it to 11 This is allowed Remember the existence of variable x begins inside the if statement’s curly brackets So variable x is in scope while it is used within the if statement’s curly brackets On trying to use the x variable outside the if statement’s curly brackets {}, I get a compile error as follows: Cannot find symbol variable x The line of code outside the if statement does not know about the existence of this variable Even though the variable is in the method and declared above the line using it, it is confined to be used inside the curly brackets in which it was declared I am sure you are wondering if we could use the variable sum inside our if statement and after our if statement! We can use sum inside our if statement Remember the scope of sum begins inside the opening curly bracket { of the method and ends when we close the curly bracket } of the method This code compiles successfully: public void calculateNumbers(int num){ int sum = 10; if(sum > 11){ int x = 11; sum = 12; } System.out.println(sum); } What if we have another set of curly brackets within the if statement; that is nested curly brackets? Let’s answer this by looking at the example in the code: public void calculateNumbers(int num){ int sum = 10; if(sum > 11){ { int z = 5; } System.out.println(z); } System.out.println(z); } In the nested curly braces, I declared a variable z and initialized it to In the curly brackets where variable z is declared, variable sum is accessible But outside curly brackets where variable z is declared; z is not accessible We get a compile error To access z outside the nested curly bracket, we would have to declare z outside these brackets and initialize it in the nested braces as follows: public void calculateNumbers(int num){ int sum = 10; int z = 0; if(sum > 11){ { int z = 5; } System.out.println(z); } System.out.println(z); } Now variable z is accessible outside the nested curly brackets Please note that we needed to initialize z on declaration; otherwise the statement coming after the if statement closing curly bracket was not going to compile public void calculateNumbers(int num){ int sum = 10; int z; // not initialized if(sum > 11){ { z = 5; } System.out.println(z); } System.out.println(z); //Compile error } This would be the error if z was not initialized: Variable z might not have been initialized Let’s now look at the variable scope using a loop We have the following types of loops: ü ü ü ü while for do…while enhanced for loop I won’t even explain how each type of these loops works Remember we are only concerned about the scope of the variables here I’ll use each of these loops to show you exactly that Let me show you an example of a while loop int num = 0; while(num < 10){ num++; } } This code compiles without any issues; because during declaration we did not initialize variable YEARS Final Method A final method defined in a super class cannot be overridden by the method in the derived class Remember we are talking about the methods existing both in super class and subclass having the same method names and same signatures We will tackle final methods in detail when we deal with polymorphism later in later chapters Let’s see an example of a final method package com.xecson; public class Book { final void read(){ System.out.println("Marks is reading the book"); } } This is a base class with the method read() Now let’s see how our derived class looks like package com.xecson; public class Magazine extends Book{ void read(){ System.out.println("She is reading a magazine"); } } This code doesn’t compile This is the error message: read() in Magazine cannot override read() in Book Overridden method is final Static variables A static variable is declared in either a class or interface We will focus on static variables defined in a class here as we have not tackled interfaces in detail as yet A static variable is also referred to as a class variable It does not belong to a specific instance of a class or object It is a shared variable across all the instances of a class Let’s see a static variable in action package com.xecson; public class TV { static double price = 200; void setPrice(double price){ this.price = price; } double getPrice(){ return price; } public static void main(String[] args) { TV instance1 = new TV(); System.out.println("Price is: " + instance1.getPrice()); } } In this class, I declared a static variable price and initialized it to 200 and it is of type double I also created a method to set price and another to get price And in our main method, I instantiated the class TV and our object reference variable is instance1 And then I invoked the getPrice() using our object reference The output of this program is as follows: Price is: 200.0 I’ll now create another instance of the TV class and set its price to 400 package com.xecson; public class TV { static double price = 200; void setPrice(double price){ this.price = price; } double getPrice(){ return price; } public static void main(String[] args) { TV instance1 = new TV(); TV instance2 = new TV(); instance2.setPrice(400); System.out.println("Price is: " + instance2.getPrice()); } } I now have created instance of TV and called it instance2 Remember we have instance1 with price set to 200 Now instance2 is set to 400 And when I print the value of instance2 I get this output Price is: 400.0 In this example, I only printed the price of instance2 Let us now print the prices of both instance1 and instance2 and see the result The code is as shown as follows: package com.xecson; public class TV { static double price = 200; void setPrice(double price){ this.price = price; } double getPrice(){ return price; } public static void main(String[] args) { TV instance1 = new TV(); TV instance2 = new TV(); instance2.setPrice(400); System.out.println("Price of instance1: " + instance1.getPrice()); System.out.println("Price of instance2: " + instance2.getPrice()); } } Let’s see our result Price of instance1: 400.0 Price of instance2: 400.0 Why isn’t it 200.0 and 400.0? Do you know why? Because when we changed the price for instance2 to 400, it was also changed for instance1 Remember a static variable is shared across the objects of a class So for a static variable, we will always have one value regardless of how many objects have been created or changed the value Note: A static variable is meant to be accessed using the class name and then the variable name If we access the static variable using an instance of a class, it is confusing because the variable does not belong to any specific object So we will now correct usage of object reference and use the class name The result will still be the same Remember you can use either object reference or class name to access a static variable The recommendation is to use class name to avoid confusion package com.xecson; public class TV { static double price = 200; void setPrice(double price){ this.price = price; } double getPrice(){ return price; } public static void main(String[] args) { //Setting the price to 400 Direct access to the static variable TV.price = 400; System.out.println("Price: " + TV.price); } } The result is the same: Price: 400.0 Class final variables are normally declared with static keyword because they are mostly shared across the objects of a class Static methods Static methods not belong to any object of a class We tend to define them as utility methods, because they are shared across objects of a class Here is an example of a static method: package com.xecson; public class Calculator { public static int add(int num1, int num2){ return (num1 + num2); } public static void main(String[] args) { System.out.println("Sum of + = " + Calculator.add(4, 5)); } } This is a simple class with a static method that does not belong to any object of a class To call this method, you not need to create an instance of a class This method receives two integer parameters; hence I called the method using the class name and also passed two integers when calling it The two integers are added together and their sum is returned The final result is: Sum of + = A static method can only access static members of a class It cannot access instance members of a class But an instance method can access both static and non static members of a class Let us see what happens when a static method is trying to access a non static member of a class package com.xecson; public class Flat { static int width = 100; int height = 50; int total = 0; static void addHeightAndWidth(){ total = height + width; } } I declared two instance variables namely: height and total I also declared one static variable width and a static method in order to calculate the total of width and height Remember we said you cannot access a non static variable from a static method height and total that we are going to use for our addition here are not static The moment I use either of the non-static variables in this static method I get an error: non-static variable cannot be referenced from a static context Remember we said you can access a static variable from a non-static (instance) method Let’s try this out and see what happens I am using the same code except that I’ll remove static in the function to see if I can access width; which is static from this non-static method called addHeightAndWidth() package com.xecson; public class Flat { static int width = 100; int height = 50; int total = 0; void addHeightAndWidth(){ total = height + width; } } The code compiles without any problems Access members from a null reference We will now try to see what happens when we try to access a static method from a null reference If the method you are trying to access is an instance method and the reference is null, you will get a runtime error called nullPointerException Let us see nullPointerException in action Remember we still have to tackle exceptions in the later chapters package com.xecson; public class Calculator { void printName(){ System.out.println("My name is Marks."); } public static void main(String[] args) { Calculator calc = null; calc.printName(); } } In this class, I defined an instance (non-static) method called printName() and all it does is to print my name Then in my main method; I declared an object reference calc of type Calculator I did not create an instance of this object reference, because I did not use the new keyword So the object reference has been set to null I am now calling an instance method from a null reference The result is as follows: Exception in thread "main" java.lang.NullPointerException Now let’s try and change our method to static method and call it again from a null reference and see how the program behaves package com.xecson; public class Calculator { static void printName(){ System.out.println("My name is Marks."); } public static void main(String[] args) { Calculator calc = null; calc.printName(); } } The result is as follows: My name is Marks What is happening here? For us to call the static method printName(), we did not need any object reference as the method belongs to all the objects of a class We could have easily called our static method with this line of code in our main method Calculator.printName(); Compare and contrast the features and components of Java such as: platform independence, object orientation, encapsulation, etc Exam Objective Components of Java Platform-independence: This refers to the fact that Java code can be executed on many platforms without recompiling the code This phenomenon is referred to as WORA; meaning – write once, run anywhere Java code is compiled into bytecode and then executed by the JVM Any machine with JVM installed on it can now execute bytecode regardless of the platform Object orientation: Java emulates real-life objects; defining their state and behavior All this is represented by classes, enums and interfaces Every object has a state and behavior In Java you need to instantiate your class so you can use it Abstraction: Java abstracts objects to hide the internal workings of the application and only exposes to the users the necessary components Take a TV for example; we not need to know as consumers how the TV displays pictures, how the picture is formed, how it determines whether or not the pictures should be black or color All we have to know is using buttons to turn TV on or off, change channels, etc So the internal workings of the TV are abstracted from consumers Encapsulation: Java classes encapsulate the state and behavior of the objects This protects them from unwanted access This is where we use access modifiers to control access to the state and the behaviors of the objects Inheritance: Java classes, interfaces can be inherited by their derived classes or interfaces to promote code reuse A derived class has access to the default, protected and public members of the base class Please note interfaces can also be inherited and then implemented by a class Polymorphism: Polymorphism in Java simple means many forms It is when the instances of the classes display different behaviors for the same method calls We will deal with this concept in detail in the later chapters Type safety: In Java, all variables should be declared before using them You need to specify the type of data the variable is expected to hold If you say the variable will store an integer, you cannot store a string there This check of whether or not the correct data type is stored in the declared variable is conducted at compile time Memory management: Java automatically reclaims memory from objects that are no longer in use It uses a garbage collector that checks; from time to time; to reclaim memory from unused objects This helps prevent memory leaks Java developers, unlike in C++, not have to worry about managing memory to avoid memory leaks as this is done automatically for them Multithreading and concurrency: These are for the advanced Java topics covered in OCP Java SE Programmer II exams and we won’t even try to explain what they are to avoid confusing you with irrelevant information at this stage Security: Java has built-in security features that control access to other resources And this again is an advanced java topic that is not covered in the OCA Java SE Programmer I exams Irrelevant features and components of Java Single-threaded: Java is a multi-threaded programming language Yes, you can have a single thread running; but this does not mean Java does not support multi-threading Javascript: Java and Javascript are totally two different programming languages They have nothing in common Javascript is used for making web pages interactive and also for frontend validation of forms on the web pages ... closing curly brace, the variable runs out of scope Meaning it is not accessible anymore Please also note that you cannot use this variable in this method if it is not initialized, hence I initialized... declaration Class definition Variables Methods Constructors Interface definition Single and multiple classes in a single Java file Create executable Java applications with a main method; run a Java. .. starts iteration Condition represents the comparison to see if the condition is true or false Update represents modification of value in the condition so that it can finally become false for

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

TỪ KHÓA LIÊN QUAN