Chapter 2 Java Building Blocks Flashcards
Creating Objects
How to create object?
- Calling Constructor
- Some classes provide built-in methods that allow you to create new instances without using a constructor or the new keyword. (Integer using the valueOf() method.)
Park p = new Park();
What is constructor?
A constructor in Java is a special method that is used to initialize objects.
The constructor is called when an object of a class is created.
It can be used to set initial values for object attributes.
Two key points to note about the constructor
2 key points to identify a constructor.
- Constructor name matches class name
- No return type
public class Chick { public Chick() { System.out.println("in constructor"); } }
Default Constructor
For most classes, you don’t have to code a constructor—the compiler will supply a “do nothing” default constructor for you.
The purpose of a constructor
is to initialize fields
READING AND WRITING MEMBER FIELDS
public class Swan { int numberEggs; // instance variable public static void main(String[] args) { Swan mother = new Swan(); mother.numberEggs = 1; // set variable System.out.println(mother.numberEggs); // read variable }
read values of already initialized fields on a line initializing a new field
1: public class Name { 2: String first = "Theodore"; 3: String last = "Moose"; 4: String full = first + last; 5: }
EXECUTING INSTANCE INITIALIZER BLOCKS
Code Block
The code between the braces is called a code block.(sometimes called “inside the braces” {})
Instance Initializer
Code blocks appear outside a method.
Line 5 is an instance initializer
1: public class Bird { 2: public static void main(String[] args) { 3: { System.out.println("Feathers"); } 4: } 5: { System.out.println("Snowy"); } //instance initializer 6: }
FOLLOWING ORDER OF INITIALIZATION
Order of Initialization
- Fields and instance initializer blocks are run in the order in which they appear in the file.
- The constructor runs after all fields and instance initializer blocks have run.
What is the output?
1: public class Chick { 2: private String name = "Fluffy"; 3: { System.out.println("setting field"); } 4: public Chick() { 5: name = "Tiny"; 6: System.out.println("setting constructor"); 7: } 8: public static void main(String[] args) { 9: Chick chick = new Chick(); 10: System.out.println(chick.name); } }
Ans : setting field setting constructor Tiny
1: public class Chick { 2: private String name = "Fluffy"; //2 3: { System.out.println("setting field"); }//3 4: public Chick() { 5: name = "Tiny";//4 6: System.out.println("setting constructor");//5 7: } 8: public static void main(String[] args) { 9: Chick chick = new Chick(); //1 10: System.out.println(chick.name); } }//6
Can you refer to a variable before it has been defined?
Ans : No.
Order matters for the fields and blocks of code. You can’t refer to a variable before it has been defined
Example :
{ System.out.println(name); } // DOES NOT COMPILE private String name = "Fluffy";
What do you think this code prints out?
public class Egg { public Egg() { number = 5; } public static void main(String[] args) { Egg egg = new Egg(); System.out.println(egg.number); } private int number = 3; { number = 4; }
Ans: 5
public class Egg { public Egg() { number = 5; //4 } public static void main(String[] args) { Egg egg = new Egg(); //1 System.out.println(egg.number); } private int number = 3; //2 { number = 4; } //3 }
Data types
- Primitive types
- Reference types
What is primitive types?
- Java has eight (8) built-in data types, referred to as the Java primitive types.
- A primitive is not an object in Java nor does it represent an object.
- A primitive is just a single value in memory, such as a number or character.
Balanced parentheses problem
You cannot use a closed brace “}” if there’s no corresponding open brace “{” that it matches written earlier in the code.
In programming, this is referred to as the balanced parentheses problem, and it often comes up in job interview questions.
Java primitive types
- boolean (true or false), defalult false
- byte (8-bit integral value), defalult 0 (-128 to 127)
- short (16-bit integral value), defalult 0 (-32,768 to 32,767)
- int (32-bit integral value), defalult 0 (-2,147,483,648 to 2,147,483,647)
- long (64-bit integral value), defalult 0L (-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807)
- float (32-bit floating-point value), defalult 0.0f
- double (64-bit floating-point value), defalult 0.0d
- char(16-bit Unicode value), default ‘\u0000’ (or 0)
IS STRING A PRIMITIVE?
Ans : No.
What is String default value?
String or any object default value is null.
Java primitive type key points:
- The float and double types are used for floating-point (decimal) values.
- A float requires the letter f following the number so Java knows it is a float.
- The byte, short, int, and long types are used for numbers without decimal points. In mathematics, these are all referred to as integral values, but in Java, int and Integer refer to specific types.
- Each numeric type uses twice as many bits as the smaller similar type. For example, short uses twice as many bits as byte does.
- All of the numeric types are signed in Java. This means that they reserve one of their bits to cover a negative range. For example, byte ranges from -128 to 127. You might be surprised that the range is not -128 to 128. Don’t forget, 0 needs to be accounted for too in the range.
SIGNED AND UNSIGNED: SHORT AND CHAR
short and char are closely related, as both are stored as integral types with the same 16-bit length.
short is signed
char is unsigned
Unsigned means range is strictly positive including 0.
Therefore, char can hold a higher positive numeric value than short, but cannot hold any negative numbers.
Valid short and char declaration
short bird = 'd'; char mammal = (short)83; System.out.println(bird); // Prints 100 System.out.println(mammal); // Prints S
Invalid short and char declaration
short reptile = 65535; // DOES NOT COMPILE out of range char fish = (short)-1; // DOES NOT COMPILE out of range
FLOATING-POINT NUMBERS AND SCIENTIFIC NOTATION
This means the numbers are stored as two numbers, a and b, of the form a x 10b.
This notation allows much larger values to be stored, at the cost of accuracy.
No in exam
Declare and initialize long
Add the uppercase L.
L is more readable then lowercase l (look like 1)
long max = 3123456789L; // now Java knows it is a long
Literals and the Underscore Character
In Java SE 7 and later, any number of underscore characters (_)can appear anywhere between digits in a numerical literal. This feature enables you, for example. to separate groups of digits in numeric literals, which can improve the readability of your code.
underscores in numbers to make them easier to read
You can add underscores anywhere except at the beginning of a literal, the end of a literal, right before a decimal point, or right after a decimal point.
int million2 = 1_000_000; double notAtStart = _1000.00; // DOES NOT COMPILE double notAtEnd = 1000.00_; // DOES NOT COMPILE double notByDecimal = 1000_.00; // DOES NOT COMPILE double annoyingButLegal = 1_00_0.0_0; // Ugly, but compiles double reallyUgly = 1\_\_\_\_\_\_\_\_\_\_2; // Also compiles
Writing Literals
Numeric primitives.
When a number is present in the code, it is called a literal.
By default, Java assumes you are defining an int value with a numeric literal.
long max = 3123456789; // DOES NOT COMPILE long max = 3123456789L; // now Java knows it is a long
please use the uppercase L. The lowercase l looks like the number 1.
Java allows you to specify digits in several other formats:
- base 10 since there are 10 numbers. It is also known as the decimal number system.
- Octal (digits 0–7), which uses the number 0 as a prefix—for example, 017
- Hexadecimal (digits 0–9 and letters A–F/a–f), which uses 0x or 0X as a prefix—for example, 0xFF, 0xff, 0XFf. Hexadecimal is case insensitive so all of these examples mean the same value.
- Binary (digits 0–1), which uses the number 0 followed by b or B as a prefix—for example, 0b10, 0B10
Reference type
A reference type refers to an object (an instance of a class).
Primitive vs Reference type
Unlike primitive types that hold their values in the memory where the variable is allocated,
references do not hold the value of the object they refer to. Instead, a reference “points” to an object by storing the memory address where the object is located, a concept referred to as a pointer.
some examples that declare and initialize reference types.
java.util.Date today; String greeting; today = new java.util.Date(); greeting = new String("How are you?");
DISTINGUISHING BETWEEN PRIMITIVES AND REFERENCE TYPES
- First, reference types can be assigned null, which means they do not currently refer to an object. Primitive types will give you a compiler error if you attempt to assign them null.
int value = null; // DOES NOT COMPILE String s = null;
- reference types can be used to call methods, assuming the reference is not null. Primitives do not have methods declared on them
4: String reference = "hello"; 5: int len = reference.length(); 6: int bad = len.length(); // DOES NOT COMPILE
- primitive types have lowercase type names. All classes that come with Java begin with uppercase.
Declaring Variables
A variable is a name for a piece of memory that stores data.
When you declare a variable, you need to state the variable type along with giving it a name.
String zooName; int numberAnimals;
Initializing variable
After declared a variable, we can give it a value.
This is called initializing a variable.
To initialize a variable, you just type the variable name followed by an equal sign
zooName = "The Best Zoo"; numberAnimals = 100;
declarations and initializations
String zooName = "The Best Zoo"; int numberAnimals = 100;
Identifier
An identifier is the name of a variable, method, class, interface, or package.
There are only four rules to remember for legal identifiers:
- Identifiers must begin with a letter, a $ symbol, or a _ symbol.
- Identifiers can include numbers but not start with them.
- Since Java 9, a single underscore _ is not allowed as an identifier.
- You cannot use the same name as a Java reserved word.A reserved word is special word that Java has held aside so that you are not allowed to use it. Remember that Java is case sensitive, so you can use versions of the keywords that only differ in case. Please don’t, though.
Reserved words
abstract, assert,
boolean, break, byte
case, catch, char, class, const, continue
default, do, double
else, enum, extends
false**, final, finally, float, for
goto
if, implements, import, instanceof, int, interface
long
native, new, null**
package, private, protected, public
return
short, static, strictfp, super, switch, synchronized
this, throw, throws, transient, true**, try
void, volatile
while
_ (underscore)
* The reserved words const and goto aren’t actually used in Java. They are reserved so that people coming from other programming languages don’t use them by accident—and in theory, in case Java wants to use them one day.
** true/false/null are not actually reserved words, but literal values. Since they cannot be used as identifier names, we include them in this table.
legal identifier example
long okidentifier; float $OK2Identifier; boolean _alsoOK1d3ntifi3r; char \_\_SStillOkbutKnotsonice$;
illegal identifier example
int 3DPointClass; // identifiers cannot begin with a number byte hollywood@vine; // @ is not a letter, digit, $ or _ String *$coffee; // * is not a letter, digit, $ or _ double public; // public is a reserved word short _; // a single underscore is not allowed
Most Java developers follow these conventions for identifier names:
- Method and variable names are written in camelCase with the first letter being lowercase.
- Class and interface names are written in camelCase with the first letter being uppercase. Also, don’t start any class name with $, as the compiler uses this symbol for some files.
Also, know that valid letters in Java are not just characters in the English alphabet.
Java supports the Unicode character set, so there are thousands of characters that can start a legal Java identifier.
Style: snake_case
Constant indentifier style
ex: THIS_IS_A_CONSTANT
Style: camelCase
Constant indentifier style
THIS_IS_A_CONSTANT