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

Practical OCA java SE 8 programmer i certification guide (working with java data types)

84 118 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 84
Dung lượng 473,54 KB

Nội dung

Practical OCA Java SE Programmer I: Certification Guide Table of Contents Chapter Declare and initialize variables (including casting of primitive data types) Primitive variables char data type int data types byte short int long number systems decimal binary octal hexadecimal combined number system manipulation floating point number data types float double boolean data type Introduction of underscores to our literal values Identifiers Identifier rules Differentiate between object reference variables and primitive variables Differences between object reference and primitive variables Know how to read or write to object fields Explain an Object's Lifecycle (creation, "dereference by reassignment" and garbage collection) Introduction to garbage collection Object creation dereference by reassignment garbage collection Develop code that uses wrapper classes such as Boolean, Double, and Integer Introduction to Wrapper classes Assignment Constructor Static method Retrieving primitive values from the wrapper classes Parsing a string value to a primitive value Constructor and valueOf method Compare objects of wrapper classes Auto-boxing and un-boxing 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 Working with Java Data Types 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 Working with Java Data Types Objectives Declare and initialize variables (including casting of primitive data types) Differentiate between object reference variables and primitive variables Know how to read or write to object fields Explain an Object's Lifecycle (creation, "dereference by reassignment" and garbage collection) Develop code that uses wrapper classes such as Boolean, Double, and Integer Declare and initialize variables (including casting of primitive data types) Exam Objective Primitive variables In Java, we have simple data types that are used to declare variables We have the following data types and we will look into them individually to understand how they are used: ü ü ü ü ü ü char byte short int long float ü double ü boolean Please note that these simple data type names are java keywords Each data type is meant to hold a specific kind of data If a variable is assigned incorrect kind of data to hold; we will get a compile error Let’s now look at each data type individually and understand how it is manipulated char data type This data type has a char keyword representing character(s) The char data type is an unsigned integer data type; meaning it can only hold data without negative numbers We will explain later why we talk about numbers whereas this data type is meant only for characters This data type can store a single 16-bit Unicode character That means it can store any character including Chinese letters, French letters and etc The data type is unsigned and it has a corresponding wrapper class called Character which we will explain later Java is a strongly typed language This means all variables must be declared before they are used You specify the data type, the identifier and the value the variable should hold Let’s now declare a variable of type char and initialize it to a value char ch = 'F'; I have declared a variable ch of type char and initialized it to F This is a valid code But please note that we use single quotes around our literal value A literal is a fixed value that doesn’t need further calculations in order for it to be assigned to any variable Remember that a character is a single value inside single quotes We can even have a number made a character For example: char n = '5'; The code is valid, because we put single quotes around the number Let us now try and put more than one character in a variable of type char For instance: char n = 'Marks'; The code fails to compile because, a char type expects a single value inside single quotes Let’s go back to our example where declared variable ch char ch = 'F'; We declared data type char and identifier ch as our variable name and then initialized ch to value F This is how we declare a variable and initialize it Initialization doesn’t have to be done on the same line This code is equivalent to the one we have just seen: char ch; ch = 'F'; We declare the variable first and then assign a value to it on the next line Let us try and put double quotes around a char value and see what happens: char ch = "F"; We get a compile error as this is not allowed The error is as follows: Incompatible types: String cannot be converted to char Remember when we started off this chapter, I mentioned that char type is an unsigned integer type That indicates to me that we can store a positive integer in a char variable Let’s try this and see what happens: char ch = 130; Please note when we assign a number to ch variable, it should not be surrounded by single quotes The result from running this code is ? (a question mark) This is interesting char ch = 115; This code gives me s as the result So what is happening here? char data type is stored internally as an unsigned integer value; that is only positive numbers char ch = 97; stores value a char ch = 122; store value z 98 = b, 99 = c……y = 121, etc We said char data type stores unsigned integer values; that is only positive numbers Let’s see what happens when we try to store negative numbers char ch = -97; This code throws a syntax error Code fails to compile We cannot assign signed integers; only unsigned integers can be assigned But we can actually force this negative value into our ch variable For this to happen, we need to casting; meaning we convert from one data type to another When we cast, we put the data type we are converting into before the value we intend converting But be careful of casting as you might get unexpected results Remember positive 97 represents letter a Let us now see what we get when we cast this negative number: char ch = (char)-97; The result was unexpected as I pointed out earlier on Here is the result: ? (char) simply means convert value -97 to character value This is casting in action Casting should be done between compatible types We will learn more about casting in the next sections of this chapter When you declare variables, you can declare as many as you want on one line and then initialize them at the same time on the same line Or alternatively, you can declare some and initialize them immediately and initialize others later Let us look at the examples: char a, b, c, d, e; char a, b = 'b', c, d, e = 'e'; char a = 'a', b = 'b', c = 'c', d = 'd', e = 'e'; char a; //line char b; //line char c; //line char d; //line char e; //line 35 On the first line, we declared variables without initializing them This means initialization should happen before we can use these variables On the second line, we declared variables and initialized only one variable This means other variable should be initialized somewhere before they can be used On line three, we declared our variables and initialized all of them On the lines with comments ranging from line to line 5; I declared variables separately which are not initialized Before using these variables, you would need to initialize them first Note: This kind of declaration and initialization on the first three lines works only if the variables are of the same data type This applies to all the other primitive types that we still have to tackle int data types The data type int is a singed data type; meaning it takes both positive and negative numbers Integer data type has sub categories namely: bye, short, long The difference between these four type of integers (that is: int, byte, short and long) is the size Each of them can store a different range of values I’ll tackle them from the smallest; in terms of size; to the biggest range of values The reason we have different sizes for integers is because, we store numbers based on our needs If I have a need for small numbers, I’ll use a smaller integer data type If I have a need to store long numbers, I’ll use a bigger integer data type, etc byte integer data type The range for this integer type is bits The range of values you can store here is between -127 to 128 Let us now declare a variable of type byte byte num = 90; I declared a simple variable of type byte and assigned 90 to it Remember this is the only integer data type of which you need to remember its range of values for the exam That is -127 to 128 You don’t have to memorize the range of values for other integer data types; that is short, long and int I am now going to declare a variable with a range bigger than 128 and see what happens: byte num = 200; This line of code doesn’t compile Remember the range of values for a byte variable? That is the reason the code fails to compile Let’s try another example that is out of range: byte num = -130; This line of code fails to compile The value assigned to the variable is out of range We are now going to declare two byte variables and add their values together to get a sum Since we work we byte data type, I’ll have the variable storing sum declared as of data type byte as well byte num1 = 20; byte num2 = 70; byte sum = num1 + num2; I have declared variable num1, num2 and sum and they are all of data type corresponding to this String literal value To achieve this, we use a special method that starts with the word parse followed by the wrapper class we are parsing the string from All the wrapper classes can use this method with the exception of Character class Let’s see the examples of this: Boolean bool = new Boolean(Boolean.parseBoolean("true")); Byte byteNum = new Byte((byte)Byte.parseByte("24")); Short shortNum = new Short((short)Short.parseShort("356")); Integer intNum = new Integer(Integer.parseInt("908")); Long longNum Float floatNum = new Long(Long.parseLong("80390")); = new Float(Float.parseFloat("90.67F")); Double doubleNum = new Double(Double.parseDouble("34.6")); What I have done here is convert the string literal values that we passed to the constructors to their primitive value counterparts Let’s now single out Integer wrapper class for the example I am about to show you I’ll retrieve the integer primitive value from the Integer object as follows: Integer intNum = new Integer(Integer.parseInt("908")); int num = intNum.intValue(); // retrieving here System.out.println("Value is: " + num); The result of this piece of code is: Value is: 908 There is nothing fancy with this code as we have seen it before Now let’s try another example where we pass another string to our constructor But this string will have a strange value Let’s see: Integer intNum = new Integer(Integer.parseInt("908_FG")); int num = intNum.intValue(); System.out.println("Value is: " + num); It is the code we have just seen Only the string in the constructor has changed Does this compile? Yes, it does Why? Remember in our constructor, we passed a string literal This string literal is then given to our parsing method to convert it to integer primitive value Unfortunately when we run this program, it crashes because the parseInt() method does not know how to convert 908_FG to a number It is just not possible as this is not a valid number So an exception called NumberFormatException is thrown Be careful of passing invalid literal values to the numeric wrapper classes parse method Let’s look at another example: Long longNum = new Long(Long.parseLong("90.80")); long num = longNum.longValue(); System.out.println("Value is: " + num); I have created an object of wrapper class Long In its constructor, I passed a string literal value to be parsed to primitive value long When parsing this string to its primitive value, there is a problem The value is actually of type double and a double cannot be converted to a long type Again an exception NumberFormatException is thrown Let’s now try parsing a string literal of a Boolean object to its primitive value Boolean boolObj = new Boolean(Boolean.parseBoolean("true")); boolean boolValue = boolObj.booleanValue(); System.out.println("Value is: " + boolValue); The ouput of this code is: Value is: true This code works fine because we passed a valid string literal to our parse method In the parse methods where you pass a string literal, you can pass it in any case; that is lowercase or uppercase or a combination of both For instance; TRUE, tRuE, will work fine as the method doesn’t consider the case sensitivity of what is passed to the method What happens if we pass invalid string literal to the parse method of the Boolean wrapper object? With numeric wrapper classes, we would get a NumberFormatException exception Will this be the case here? Let’s see using an example: Boolean boolObj = new Boolean(Boolean.parseBoolean("true3")); boolean boolValue = boolObj.booleanValue(); System.out.println("Value is: " + boolValue); The output of this code is as follows: Value is: false Let me unpack what is happening here I created an object of wrapper class Boolean and also tried to parse the string literal passed to the parse method of Boolean wrapper class The string literal passed is invalid We were expecting either true or false Strangely no exception is thrown With parseBoolean() method, instead of throwing an exception for invalid data; the string literal is defaulted to false That’s it; hence the value printed is false Constructor and valueOf method Both the constructor and the valueOf() method are used to create a wrapper class object But there is a difference in terms of how they create the object I’ll focus more on the valueOf() method, because I want to highlight what happens when we create an object in relation to this method Objects created for the Byte, Short, Integer and Long classes cache objects with the values in the range of -128 to 127 Also Character class caches objects with values in the range of to 127 Float and Double objects not cache any values With regard to the Boolean class, objects are cached and accessed directly For instance; Boolean.TRUE and Boolean.FALSE Let’s now have an example to see the effect caching has on the values Long num1 = Long.valueOf(100); Long num2 = Long.valueOf(100); if(num1 == num2){ System.out.println("Values are equal."); }else{ System.out.println("Values are not equal."); } The result of this program is: Values are equal Both num1 and num2 refer to the same cached objects; hence they are equal Let’s see what happens when we compare object references that point to objects that are out of the range; that is -128 to 127 Long num1 = Long.valueOf(500); Long num2 = Long.valueOf(500); if(num1 == num2){ System.out.println("Values are equal."); }else{ System.out.println("Values are not equal."); } The result of this program is: Values are not equal The object references are pointing to different objects; hence the message that values are not equal Compare objects of wrapper classes We can compare objects of wrapper classes by using these two mechanisms: ü == comparison operator ü Equals() method Let’s now see how the equals() method works When we want to compare the primitive values stored in the wrapper instances, we use this method to achieve that When we want to check if object references of the wrapper classes refer to the same object, we use the == comparison operator We will now have a few examples to see these in action Integer int1 = new Integer(16); Integer int2 = new Integer(16); if(int1 == int2){ System.out.println("int1 and int2 refer to the same object."); }else{ System.out.println("int1 and int2 not refer to the same object."); } The result of this program is as follows: int1 and int2 not refer to the same object I have declared two instances of the Integer wrapper class and passed 16 to the constructor Remember the keyword new creates an instance of an object I then checked if both object references point to the same object The result shows that they not point to the same object Because we created the instances of these wrapper classes using new keyword, they cannot point to the same object Hence out equality comparison returns false Let’s now create instances of the Integer wrapper class using valueOf() method and see what happens Integer int1 = Integer.valueOf(16); Integer int2 = Integer.valueOf(16); if(int1 == int2){ System.out.println("int1 and int2 refer to the same object."); }else{ System.out.println("int1 and int2 not refer to the same object."); } The result of this program is as follows: int1 and int2 refer to the same object Here I have created instances of the wrapper class using a static method valueOf(), not using the new keyword Remember that values in the range of -128 to 127 are cached? So what is happening here is that, this method returns a cached copy for int 16 What happens if we change the values passed to over the range of values that are cached? Let’s see: Integer int1 = Integer.valueOf(750); Integer int2 = Integer.valueOf(750); if(int1 == int2){ System.out.println("int1 and int2 refer to the same object."); }else{ System.out.println("int1 and int2 not refer to the same object."); } The result of this program is as follows: int1 and int2 not refer to the same object What is happening here is that if the values passed are out of range for cacheable values, separate objects are created Let’s have one more example: Integer int1 = 16; Integer int2 = 16; if(int1 == int2){ System.out.println("int1 and int2 refer to the same object."); }else{ System.out.println("int1 and int2 not refer to the same object."); } The result of this program is as follows: int1 and int2 refer to the same object The values here are auto-boxed, meaning they are implicitly converted to Integer objects The cached copy of the values is returned; hence the object references point to the same object I want us now to apply equality comparison among the objects that have been created using different methods Let’s create objects using a constructor and valueOf() method and compare if the object references point to the same object or not Integer int1 = new Integer(16); Integer int2 = Integer.valueOf(16); if(int1 == int2){ System.out.println("int1 and int2 refer to the same object."); }else{ System.out.println("int1 and int2 not refer to the same object."); } The result of this program is as follows: int1 and int2 not refer to the same object Remember new keyword creates a new object and despite the fact that the values passed are in the range of cacheable values, the equality comparison returns false as evidenced by the result printed I am now going to create instances of the wrapper classes using both versions; that is valueOf() method and auto-boxing with the values in the range of the cacheable values Integer int1 = Integer.valueOf(16); Integer int2 = 16; if(int1 == int2){ System.out.println("int1 and int2 refer to the same object."); }else{ System.out.println("int1 and int2 not refer to the same object."); } The result of this program is as follows: int1 and int2 refer to the same object Both instances refer to the same object We have used values that are cacheable Had we used values outside the range of -128 to 127, the equality comparison would have returned false I am now going to have an example of instances whose values are auto-boxed and see how they behave: Integer int1 = 16; Integer int2 = 16; if(int1 == int2){ System.out.println("int1 and int2 refer to the same object."); }else{ System.out.println("int1 and int2 not refer to the same object."); } The result of this program is as follows: int1 and int2 refer to the same object Both values are in the range of values that are cached, hence the equality comparison returns true If we change the values to 700 for instance; the equality comparison would return false Let’s now turn our attention to the equals() method Remember with == comparison operator, we were checking if the object references were pointing to the same object or not With the equals() method, we check if the values pointed to by our object references are the same or not Integer int1 = new Integer(16); Integer int2 = new Integer(16); if(int1.equals(int2)){ System.out.println("int1 and int2 have the same values."); }else{ System.out.println("int1 and int2 not have the same values."); } The result is as follows: int1 and int2 have the same values Both values stored in the objects are the same Here is another example: Integer int1 = 16; Integer int2 = 16; if(int1.equals(int2)){ System.out.println("int1 and int2 have the same values."); }else{ System.out.println("int1 and int2 not have the same values."); } The result is as follows: int1 and int2 have the same values Here is another example: Integer int1 = Integer.valueOf(16); Integer int2 = Integer.valueOf(16); if(int1.equals(int2)){ System.out.println("int1 and int2 have the same values."); }else{ System.out.println("int1 and int2 not have the same values."); } The result is as follows: int1 and int2 have the same values Please note that when doing equality comparison of the instances of the wrapper classes, you need to use instances of the same wrapper classes Let’s now see what happens if our equality comparison is based on instances of different wrapper classes Integer int1 = 16; Long long2 = 16L; if(int1.equals(long2)){ System.out.println("int1 and long2 have the same values."); }else{ System.out.println("int1 and long not have the same values."); } The result is as follows: int1 and long not have the same values The values stored by in these objects are the same; but because we are doing equality comparison on different wrapper classes, the equality comparison returns false What happens when we use == comparison operator on instances of different wrapper classes? Integer int1 = 16; Long long2 = 16L; if(int1 == long2){ System.out.println("int1 and long2 have the same values."); }else{ System.out.println("int1 and long not have the same values."); } The result is that the code does not compile We cannot == comparison on instances of different wrapper classes Auto-boxing and un-boxing Remember I said auto-boxing is the implicit conversion of a primitive value to an object What is un-boxing then? Un-boxing is the process of converting the object back to its primitive value .. .Practical OCA Java SE Programmer I: Certification Guide Table of Contents Chapter Declare and initialize variables (including casting of primitive data types) Primitive variables char data. .. quotations in a book review Working with Java Data Types Objectives Declare and initialize variables (including casting of primitive data types) Differentiate between object reference variables... wrapper classes such as Boolean, Double, and Integer Declare and initialize variables (including casting of primitive data types) Exam Objective Primitive variables In Java, we have simple data types

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

TỪ KHÓA LIÊN QUAN