0% found this document useful (0 votes)
5 views

Part 1 - Java programming Basics

The document provides a comprehensive overview of Java programming, covering its definition, history, and key features such as platform independence and object-oriented principles. It details fundamental concepts including classes, objects, variables, methods, and control-flow statements, along with coding conventions and the Java API. Additionally, it explains the compilation process, variable types, and the significance of Java's syntax and memory management.

Uploaded by

montadhr.social
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Part 1 - Java programming Basics

The document provides a comprehensive overview of Java programming, covering its definition, history, and key features such as platform independence and object-oriented principles. It details fundamental concepts including classes, objects, variables, methods, and control-flow statements, along with coding conventions and the Java API. Additionally, it explains the compilation process, variable types, and the significance of Java's syntax and memory management.

Uploaded by

montadhr.social
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 97

Java Programming

1. OVERVIEW ............................................................................................................................................... 4
1.1. WHAT IS JAVA? .................................................................................................................................... 4
1.2. JAVA HISTORIE ..................................................................................................................................... 4
1.3. PLATFORM INDEPENDANCE...................................................................................................................... 4
1.3.1. Compilation ............................................................................................................................. 4
1.3.2. Platform dependency ............................................................................................................... 6
1.3.3. Interpreters.............................................................................................................................. 6
1.3.4. How Java is platform independence and use compiler .............................................................. 9
1.4. JAVA SE ........................................................................................................................................... 10

2. CLASSES OBJECTS AND THEIR MEMBERS................................................................................................ 11


2.1. OBJECTS ........................................................................................................................................... 11
2.2. BASICS ............................................................................................................................................. 12
2.2.1. Comments ............................................................................................................................. 12
2.2.2. Case sensitivity ...................................................................................................................... 13
2.2.3. Naming rules ......................................................................................................................... 13
2.2.4. Print to console ...................................................................................................................... 13
2.3. VARIABLES ........................................................................................................................................ 13
2.3.1. Variable declaration............................................................................................................... 14
2.3.2. Assignment statement ........................................................................................................... 14
2.3.3. Kinds of variables ................................................................................................................... 14
2.3.4. Primitive type......................................................................................................................... 15
2.3.4.1. Variables Integers............................................................................................................................. 15
2.3.4.2. Variables Floating-point Numbers ..................................................................................................... 17
2.3.4.3. Variables Character Boolean ............................................................................................................. 17
2.3.5. Variables casting.................................................................................................................... 19
2.3.5.1. Implicit casting ................................................................................................................................. 19
2.3.5.2. Explicit casting.................................................................................................................................. 20
2.3.6. Objects references ................................................................................................................. 21
2.3.7. Statements ............................................................................................................................ 21
2.3.8. Arrays .................................................................................................................................... 22
2.3.8.1. 1D Arrays ......................................................................................................................................... 23
2.3.8.2. 2D Arrays ......................................................................................................................................... 25
2.3.8.3. 3D Arrays ......................................................................................................................................... 28
2.4. METHODS ......................................................................................................................................... 29
2.4.1. Method types......................................................................................................................... 30
2.4.2. How Data is passed to Methods ............................................................................................. 31
2.4.3. Method Overloading .............................................................................................................. 33
2.4.4. Methods varargs.................................................................................................................... 34
2.5. CONSTRUCTORS.................................................................................................................................. 35
2.6. THIS REFERENCE ................................................................................................................................. 39
3. METHOD BUILDING BLOCKS: OPERATORS AND CONTROL-FLOW STATEMENTS ..................................... 40
3.1. OPERATORS ....................................................................................................................................... 40
3.1.1. Arithmetic Operators ............................................................................................................. 40
3.1.2. Comparison Operators ........................................................................................................... 42
3.1.3. Logical Operators................................................................................................................... 44
3.1.4. Bitwise Operators .................................................................................................................. 45
3.1.5. Bit Shift Operators ................................................................................................................. 47
3.2. CONTROL-FLOW STATEMENTS ................................................................................................................ 49
3.2.1. If-statement........................................................................................................................... 49
3.2.2. Switch.................................................................................................................................... 50
3.2.3. Ternary .................................................................................................................................. 52
3.2.4. For Statement ........................................................................................................................ 53
3.2.5. For-each statement................................................................................................................ 55
3.2.6. While Statement .................................................................................................................... 56
3.2.7. Break Statement .................................................................................................................... 57
3.2.8. Continue statement ............................................................................................................... 58
3.3. VARIABLE SCOPE ................................................................................................................................. 60

4. PACKAGES STRINGS AND INFORMATION HIDING .................................................................................. 62


4.1. JAVA API .......................................................................................................................................... 62
4.2. PACKAGES ......................................................................................................................................... 63
4.2.1. Access class in packages......................................................................................................... 64
4.2.2. Creating Packages ................................................................................................................. 66
4.2.3. Naming package (conventions) .............................................................................................. 68
4.3. STRINGS ........................................................................................................................................... 68
4.3.1. String manipulations .............................................................................................................. 69
4.3.2. String Pool Interning .............................................................................................................. 72
4.3.3. String Immutability ................................................................................................................ 74
4.3.4. String concatenation .............................................................................................................. 75
4.3.5. Escape sequences .................................................................................................................. 77
4.4. ACCESS LEVELS ................................................................................................................................... 77
4.4.1. Information Hiding................................................................................................................. 78
5. STATIC FINAL AND CODING CONVENTIONS............................................................................................ 80
5.1. MATH CLASS ...................................................................................................................................... 80
5.2. STATIC ............................................................................................................................................. 81
5.2.1. Static methods ....................................................................................................................... 81
5.2.2. Static Variables ...................................................................................................................... 82
5.3. INITIALIZERS: STATIC AND INSTANCE VARIABLES .......................................................................................... 83
5.4. FINAL VARIABLE ................................................................................................................................. 85
5.4.1. Constant variables ................................................................................................................. 86
5.5. BOXED PRIMITIVES .............................................................................................................................. 87
5.5.1. Auto boxing ........................................................................................................................... 88
5.5.2. Prefer Primitives to Boxed Primitives ...................................................................................... 90
5.6. CODING CONVENTIONS ........................................................................................................................ 91
5.6.1. Naming.................................................................................................................................. 91
5.6.2. Structuring Programs ............................................................................................................. 93
5.6.3. Stylistic .................................................................................................................................. 94
5.6.4. Comments ............................................................................................................................. 95
1. Overview

1.1. What is Java?


 We can define java as a :
 General purpose: it’s not constrained to one particular domain and can be used
to a wide variety of applications
 Object oriented:
 Platform independent: Write once runs anywhere. You can run java programs
on any platform regardless of the operating system and architecture
 Concurrent: Support concurrent programming and multithreading. This enable
programs activities at the same time
 Very fast: it is indistinguishable (‫ ) ال يمكن تميزه‬from C and C++

 There make java really solid and very reliable and a complete programming language

 Java build on few additional principles:


 Familiar syntax:
 Simple and safe:
 C and C++: programmers manipulate memory to free up space (if it’s not
properly, it can the programs crash)
 Java: Automatic memory management (using Garbage collection: study
in JVM part)
 Secure:
 It has rich library which include predefine functionality (Java API)
 It ‘s free open source
 It has very large usage in internet and browsers using applets

1.2. Java Historie

1.3. Platform indépendance


 Platform independence is one of the key benefits of java.
 To need what platform dependency is, we need to understand what is compilation

1.3.1. Compilation
A. Machine Language
 Every computer has a fixed set of instructions
 A computer program is made up off (compose par) some of these instructions. That is the
instructions help a computer program will form something meaningful.
 Each instruction is basically a sequence of zero and ones (0, 1). It has binary format
 That instruction is called machine language, machine code or native code.
Example: 000001011110000101110000101110111111010111010111000010111001

 Machine language is very difficult to write code with it because it composes by binary
code. It will be very simply.

 Computers understand only machine language


B. Assembly language
 Example for assembly language :

 Because computers understand machine language only, they not understand assembly
language. There is program called assembler which translate assembly language to
machine language.

 Machine language and assembly language called low level language because they use low
level details of computer for example memory location.
 because low level language are very difficult to write code with they, new high level
language are create to facility programming.
C. High level language
 For example C,C++,Java, python …
 They use English like words, mathematic notations and punctuations to write programs
and hide low level details of computers.
 To can computers understand high level language, we are create new program called
compiler which translate high level language to machine language which is executable
program is then executed by CPU in a separate step
 Target language has many formats like machine language, byte code...

D. Core compilation operations:


 Verify syntax and semantics for source code.
 Code optimizations
 Generate machine code

1.3.2. Platform dependency

1.3.3. Interpreters
 It is just a platform dependency issue
 In an interpreted language, we have an interpreter which is a program that directly
executes the source code. The CPU execute interpreter and the interpreter execute
internally the source code.
 It is a virtual machine that is similar to CPU. Like CPU, the interpreters execute the
instruction using fetch and execute cycle.

 Like a CPU, interpreter use fetch and execute cycle like this:
 Fetch next program statement from memory
 Understand what necessary to carry out that statement
 Execute precompiled machine code in its library
 Interpreters has many benefits like:
 Platform independence
 No compilation step
 Easier to update
 Limitation of interpreters is Slow because many reasons like:
 Costly memory access
 Source code is reinterpreted every time
 Interpreters is loaded into memory
 Many language use interpreters like :
 Ruby
 Python
 PHP
1.3.4. How Java is platform independence and use compiler

 JVM is an interpreter program. It is interpreting java byte code. So we can thing of java
as interpreted language.

 Java byte code interpretation is much faster because it is compact compiled and
optimized.

 Byte code is designed to work in network environment


1.4. Java SE
 Java software family:

 Java SE:

 Java versions:
2. Classes Objects and their Members

2.1. Objects
 Objects are created from classes.
 Classes and object are most fundamental aspect in object oriented language (OOP).
 OOP is created in 1960s
 It mainly helped model in a real word scenarios in a more natural way

 Example:
 Each class can have:
 Variables: state, characters can defined
 Methods: behavior, actions can do
 Member classes: referred to as master classes. Members of master class
 Members interface: members of master interface
 This is an example of defining class and creating objects with Java :

2.2. Basics
2.2.1. Comments
 Double slash //: it ignores rest of line.
 Single line comments or disable single line of code
 Block quotes /* */: ignore everything between /* and */.
 Detailed code description or disable large areas of code

2.2.2. Case sensitivity


 Everything is case-sensitive: variable name “test” is different from “Test”.

2.2.3. Naming rules


 Naming rules for classes, methods or variables has some laws to uses:
 Must start with letter, underscore(Tiret bas ‘_’) or $
 Others characters can be letters, underscore, $ or numbers
 It cannot be reserved keywords

2.2.4. Print to console


 We can print to console using:
 System.out.println(string): print and place cursor at beginning of next line
 System.out.print (string): print and place cursor after the printed string

2.3. Variables
 Object states are represented by variable which store state information stored like student
ID name or genre. It’s container that hold some data and pick.
 Variables can stored many types of data like:
 Numeric like 100 (int)
 String like “john” (String)
 Object like student (Student: class)
 Variables has 2 types:
 Primitive
 Objects references (not primitive)

 Variable types determine which type of data it can store and their operations.

 It’s statically typed language: if variable of one type is assigned a value which is of some other
type then we get a compilation error  static type checking
2.3.1. Variable declaration

 Example(literal -> row data): int count = 25; Boolean flag = true;
 Example (expression -> evaluate): int count = x; int count = getCount();

2.3.2. Assignment statement


 Variable is something whose value can be changed.

2.3.3. Kinds of variables


 Instance variable (fields or attribute) declared on class level and not method
level. It represented object state. Its specific to each object of class
o Cannot be reinitialized directly within class ( reinitialize only in methods
or in other place)
o Get default value: take default value of their type.
 Static variable (fields or attribute) it’s start with static keyword its class variable.
It’s unique for all objects of class. Only copy per class
o Cannot be reinitialized directly within class ( reinitialize only in methods
or in other place)
o Get default value: take default value of their type.
 Local variable: declared in methods. It include method parameters and it’s not
accessible outside the method
o Don’t get default value: you should initialized when declared before used
2.3.4. Primitive type

 Java is OOP language. For performance reasons, java define 8 primitives types

 Java define many types for the some general type like Integer (byte, short, int, long)
because for reasons of size because each primitive type has their size in memory. To
optimize usage of language. So to represent small number, you cannot use for example
long to optimize memory

2.3.4.1. Variables Integers


 Integers are whole, fix point numbers
 In java, we can represent integers by 4 primitive’s types: byte, short, int, long.
 Java use Signed two’s component to represent integers
There is an example for using these types:

 Number representation Formats: There are many formats for represents integers in
Java :

 Underscore for readability: in java you can separate numbers when you assign number
to variable with underscore like example later to facility readability for this large number
to improve readability: ( it can be used between number in all numbers formats ,
cannot used underscore in beginning or the end)

 Initialization in single ligne: in java you can initialize 2 variables in single statement
like this:
2.3.4.2. Variables Floating-point Numbers
 Float numbers are real numbers like 3.1
 They can represented by 32-bit float or 64-bit double (double is more precise)
 Java use 32/64 bit IEEE 754 floating point

There is an example for using these types:

 Rules for using float or double:


 Item 48: Avoid(éviter) float or double, if exact answers are
required: are ill-suited ‫ ال يناسب‬for monetary calculations (like e-commerce
applications)
 Use BigDecimal. (when use calculations, big decimal is proffered for its
precision)
 Int or long keep track of decimal point yourself

 Floating point is not as fast as integer arithmetic.

So you need to use floating point variable only if number contains a fractional part.

 Stick int and double: double’s preciseness useful in neural networks


 Use byte, short, float only if memory saving is important

2.3.4.3. Variables Character Boolean


 Character would consist of single letter characters like ‘a’, ‘A’.
 In java Char represented by 16 bit. It use 16-bit unsigned integer to represent characters

 Default value is a null in decimal value ‘\u0000’.

 Java use 16-bit Unicode (UTF-16) scheme to represent characters


 Unicode represent all characters in all languages
 UTF-16 is one implementation of Unicode to represent all characters in all
languages.(use hexadecimal format)

 Example of declaration of characters:

 Boolean is binary data type which can true/false

 Example of declaration of Boolean


2.3.5. Variables casting
 Sometimes we may have to assign the variable with value of some other data type. So this
type will convert to the other type. This is typecasting
 Typecasting is assign variable or literal of one type to variable of another type
 Int <- long
 Int <- byte

 Typecasting is possible only between numeric data types (any primitive type except
Boolean) so cannot cast to Boolean or vice versa

 Typecasting can be implicit or explicit

2.3.5.1. Implicit casting


 We use implicit casting when we have to casting variable of smaller type to variable of
large type (widening conversion).
 Implicit casting done by the compiler automatically

 This example of implicit casting:

 In implicit casting, we have some information to loss for example between int to float
numbers we lost some of least significant bits of value that is being assigned
2.3.5.2. Explicit casting
 We use explicit casting when we have to casting variable of larger type to variable of
smaller type (narrowing conversion)
 Explicit casting done by developer. To use Explicit casting we need to use (type) like this
example:

 Without the explicit casting, we have compiler error


 In explicit casting, there are some information lost you order for assignment. For
example,
 When casting 123456 to byte, it’s outside of range of byte and we have explicit
casting. So variable gets assignment which 64 because JVM discards all but the
lower 8 bits of the binary equivalent of the number 123456. Because the variable
is small container than integer.

 Second scenario is when you cast float point number to integer. In this case we
have always truncate the number
2.3.6. Objects references

 Objects stored in memory: There is special memory assigned to JVM. JVM gets chunk
(‫ )قطعة‬of memory from the underlying operating system in order to run this programs.
One of these memories is referred to heap and all objects are stored on the heap.

 Bit depth: is JVM specific (It’s for all variables primitives no for objects references) that
bit depth of one JVM is smaller or larger than that of an object reference on another.
 Default bit depth is null (reference object is not pointing to anything)

 If you used operation in null reference, you have exception NullPointerException

2.3.7. Statements
 In java statements are constitute programs. Its command to be executed
 Every statements ends with semicolon
 Statements change program state
 There are many format for statements:
 Declare variable
 Change variable value
 Invoke method
 Invoke one or more expressions (evaluated to single value. This evaluate happens
at runtime)

 There are many types of statement


 Declaration statements: int count = 25;
 Expressions statement (not at class level)

 Control flow statement (not at class level)

2.3.8. Arrays
 Array is very basic data structure in java. Data structure is an organized collection of
related data
 Array is a container objects that holds a fixed number of values of single type
 Objects: array in java is basically an object. And it stored on the heap like any
other object
 Fixed: number of items they can store is decide at the array creation time itself
and cannot be changed after
 Single type: items in array should be in a single data type(primitive or objects)
2.3.8.1. 1D Arrays

 Creating an array: there are 3 ways to creating an array in java


 1st way: using new keyword like this

 If you declare array without initialize number of case and without initialization, the
object reference take null value

 2nd way: initialize array values in declaration between 2 braces and empty number
of items like this
 Array size in automatically gets from number of items between braces. When you
specify array size, will get compile time error

 3rd way: this is a simple syntax without new keyword. With only items between
braces like this:

 In java you can have this syntax with square brackets after references like this(this
way not entirely to you it’s not good to use this)

 You can use length to know size of an array of number of items in this array. It’s
numbers of elements or array contents like this:

 Accessing an element outside of boundary will result an error runtime

 Array of objects references: when you using array of objects, you can initialize like
this

 Random access:
 Most JVM implementations use linear layout to represent arrays so array elements
are represented contiguously (next to each others in memory) so they have fast
random access (in constant time)
2.3.8.2. 2D Arrays
 Many dimensions arrays are like matrix

 Creating an array: there are 3 ways to creating an array in java


 1st way:
 Internal the JVM, it will be basically create a one dimensional array with four
elements corresponds to the four rows and there 4 elements cannot contains data
but each elements is actually an object reference referent to another array for 2
elements and there are referenced in arrays represent actual rows and they contain
the actual data

 2nd way:

 3rd way:
 Arrays with irregular rows: in java it’s possible to have array with many numbers of
elements in different rows for example you have one row have 4 elements and other row have
6 elements. You can use this feature like this.

 Length: you can use length with 2D arrays like this:


2.3.8.3. 3D Arrays

 Creating an array: there are 3 ways to creating an 3D arrays in java like 2D arrays and
arrays
 1st way:

 In memory, 3D arrays are represented like 2D but second level is ordonner like this
example:
2.4. Methods
 Methods are defining behavior of classes. It represent self-contained logic that can be
used any number of times. All algorithms are coded into methods.
 Methods receive data at input and with some processing and finally generate some output

 The syntax for a method in java is like:

 To call this method you code like this:

All arguments should have some type of arguments defined in definition.


 void : You can use void keyword when your method are nothing to return

 The return type must be primitive, object reference or void


 Primitive, object reference: must return value. If not, they get compiler error
 Void: nothing to return
 Benefits of methods:
 Avoid duplicate code
 Divide and conquer (software reuse, clear and readable code)

2.4.1. Method types


 There are 2 types of methods:
 Instance methods: Objects level methods. It used usually to affect object state. It
directly manipulate instance variables or others instance methods

 Static methods: it begins with static keyword in the method declaration.


 Absence of static keyword, so it is instance method

o Static method is class level methods that are unlike instance methods. It
cannot access to instance variable/methods
o It can access unique static variables or methods

o To access instance methods from static methods, you should create


instance of this class to can access to this method.
2.4.2. How Data is passed to Methods
 To very understand this part you should know how variables are represented in memory:
 Primitive variable: the variable in memory contain logical name(name in
program), memory address, value. In real time, we have memory address in the
real data so no variable name at runtime

 Object reference:
 In programming language there are 2 types of data passing:
 Pass by value: you pass the value of the method argument to the method
parameter. There is copy of the argument values made and is assigned to the
method parameter.
o Primitive argument: value is passed

o Object reference argument: value of memory address. Memory address of


the actual object

 When we reassignment object parameter in the method so new object will create in
memory and their address will assigned to parameter, so the argument will not change,
because it contain address of first object like this example
When we pass data to method in java, in the background, we have identical to variable
assignment like this

 Pass by reference

2.4.3. Method Overloading


 Sometimes, it makes sense to maintain multiple versions of the same method in the same
class. By multiple versions, we mean that the method would have the same name but
would take different input. this feature is method overloading.
 Methods overloading have:
o Same name
o Different parameter lists

 So you must change parameter list (parameter, of parameter type, or parameters numbers)

 Change only the return type doesn’t matter


 Valid example:

 When you pass for example number to overload(23), the compiler will choose the more
specific method (for example when we pass byte and we have short and int, it will choose the
method with short parameter). It finds one with the next larger type.

 Invalid examples:

2.4.4. Methods varargs


 There are new feature that was introduced in java 5 call varargs. Before, in java method
can be invoked with fixed number of parameters.
 With varargs, methods can have a special type of parameter call varargs which is
shorthand for variable length arguments. This parameter can take variable number of
arguments
 It should be a last parameter of the method

 It can be the only parameter of the method


 Method can have only one varagrs parameter
 Can’t pass null or empty array

 Syntax and invocation:

 The method in java is infinitely overloaded


 Varargs provides simpler and flexible invocation
 Example:

 Varargs and overloading methods:


 Invalid overload example

 Varargs method will be matched last: when we have 2 methods overloading one
of them with varargs, compiler will execute method without varargs.

2.5. Constructors
 It is related to constructing objects and initialize their states
 Constructor is runs on object creation. It is mostly used to initialize object state. It
initializes the instance variables of the object.
 Syntax:

o Constructors can have varargs parameters


 Example for using constructors
 Default constructor: when class have not constructor, compiler inserts one constructor
with no parameter (named no-args constructor). If class include constructor then compiler
will not insert any constructor

 Constructors and overloading:


 constructor have same overloading rules as methods
 You can create object using any of the constructors

 This: this is followed by any arguments needed by the overloading constructor. So you
do not use a constructor name itself to invoke the overloading constructor it’s got be the
special this invocate statement
 this statement have numbers of restricts:
o Must be first statement in the constructor. Otherwise we have compiler error
o Only one per constructor
o Cannot use instance variables as arguments
o No recursive invocation. If exist we have infinity loop
2.6. This reference
 To access variables or methods for class, we use it’s object reference followed by dot
operator after variable or method name

 But to can an object access its own members, it can use this reference.

 Its reference to the current object


 Members can also access directly without any this reference
 Why we use this reference and we can access members directly: the real use of this
reference when we want to access instance variables that are hidden by local variable
which define in method or constructor

 You use this reference when your variables or methods are hidden by local variables
or methods

 This reference cannot be used in static methods( in static methods you cannot access to
instance variables or methods in same class )
3. Method building blocks: operators and control-flow statements

3.1. Operators
 Operator is a symbol which performs operation on its operands and produces a result

 Java support many types of operators :


 Assignment: it’s assign value of right hand side of operator to variable on the left
Example: int a = 100;
 Arithmetic
 Comparison
 Logical
 Bitwise
 Bit shift
 Instanceof
 Note that operator can operate on either one, two or three operations

3.1.1. Arithmetic Operators


 It’s the most basics topic like addition and subtraction
 In java there are many arithmetic operators like:
 Addition (+) : int i = 5 + 2; (i == 7)
 There are other uses for addition operator. It is unary plus or string
concatenations
 Subtraction (-): int k = 5-2; (k == 3)
 There are other uses for subtraction like unary minus(indicate the
number is negative) like this example

 Multiplication (*)
 Division (/)
 Modulus (%) : indicate the rest of division like int I = 5%2 (I = 1)
 Pre and post increment (++): it increment the variable by 1 unity
 Pre increment (++x): increment the variable before any other operation in
the line

 Post increment (x++): increment the variable after any other operation in
the line

 Pre and post decrement (--): like pre and post increment

 Arithmetic Operators apply to only primitive numeric types (all primitive except
Boolean)

 Compound Arithmetic assignment operators:

 =+ will be treated as only assignment operation (Unary plus operator; indicates


positive value) and is not affecting the sign of variable two
 Arithmetic operations rules:
 Rule 1:Multiplicative operators (*,/,%) have higher precedence over additive
operations (+,-)
 Rule 2: Operators in same group are evaluated left to right

 Use parenthesis to change evaluation order


 Operand Promotion:
 Operands smaller than int are promoted to int (byte, short, char)

 Same type operation: If both operands are int, long, float or double then
operations are carried in that type and evaluated to a value of that type

 Mixed type operation: If operands belong to different types, then smaller type is
promoted to larger type

 The type of final result will be of largest data type

3.1.2. Comparison Operators


 It means compare one operand to another ex: x > y
 Basically, we use comparison operators when
 condition is bean testing
 Generate Boolean value: output of comparison operation will be Boolean value.
Generally used in control flow statement
 Also called relational operators
 Object reference comparison: Equal to and not equal to are used also to compare object
reference like this example

 Typically, these operators(==, !=) are used with object reference when we should
know the object is null or not like this example:
3.1.3. Logical Operators
 We can use logical operators when we should use multiple conditions. Test if many
conditions are valid or not like (x >7) and (x < 2)

 Logical operators are used to test one or more conditions:


 If((x < 7) && (y <3) && (z > 5)){}
 Generate Boolean value
 Used in control-flow statements
 Also called conditional operators

 Short cut operators (&& , ||):


 &&: if left operand is false then return true
 ||: if left operand is true, then return true
 These operators can improve performance by potentially reducing number of
tests
 There operators prevents NullPointerException: like this example

 Operators’ precedence: the logical operators precedence is like this (! > && > ||)
 Use parenthesis to change evaluation order. Uses parenthesis is a good idea to
disable any confusion

3.1.4. Bitwise Operators


 Its operate on individual bits of operands
 Operands can exist in bitwise operators is:
 Integers primitives: (can applicant operand promotion rules are applies in
arithmetic operators)
 Boolean (rare used)
 It mostly used in :
 embedded systems applications,
 hash tables or hash Map’s hash function
 Compression and encryption
 There are many bitwise operators
 & -> Bitwise AND: it return 1 if both input bits are 1
 | -> Bitwise OR: it return 1 if either of input bits is 1

 ^ -> Bitwise XOR (Exclusive OR): it return 1 ONLY if one of the input bits is 1
(but not both)

 ~ -> Bitwise NOT: it inverts bits

 & and | are not short cut operators


 Compound bitwise assignment:
3.1.5. Bit Shift Operators
 It’s also operate on individual bits of operands
 It’s called also shifts bits
 The operands of bit shifts operators is integers primitives
 If you consider that binary representation, then the big shift operators can shift the bits
in either left or right direction
 There are many types of bit shift operators:
 << left shift: left shift left operand by the number of bits specified on right

 Insert zero at lower order bits

 It’s same as multiplication by powers of 2

 >>> Unsigned right shift: right shift left operand by numbers of bits specified on
right. It’s exact opposite of left shift operator

 Insert zeroes at higher order bits


 It’s same as division by powers of 2

 >> signed right shift: Same ass >>> but padded with MSD. But the higher order
bits (big significant bit instead of zeroes) are not bothered with it

 The operator ‘>>’ uses the sign bit (left most bit) to fill the trailing positions after shift. If
the number is negative, then 1 is used as filler and if the number is positive, then 0 is used as
filler. For example, if binary representation of number is 10….100, then right shifting it
by 2 using >> will make it 11…….1.

 Compound big shift operators:

 The most applications of bit shift operators are


 Compiler optimizations (multiplication and division). JVM is replace these
operations with appropriate big shift operations which are much more fast
 Hash tables egg: Java Hash Map’s hash function
 Embedded programming
 Games programming
 Systems with no floating point support
3.2. Control-flow statements
3.2.1. If-statement
 It is control the order which statements are executed.
 In order to do that, they make use of Boolean conditions
 It Execute block of code if some test is passes

 Use else block if test fails

 Use else if blocks for long conditional tests

 If statement can be nested: we can have many if statements in each other’s like this
3.2.2. Switch
 It can be an alternative to if statement. But not all feature of switch statements cannot
presented with if statement

 Break statement indicate the finish of switch statement, without break statement,
all subsequences blocks are executed in sequence
 Break statement should be last statement in the block. Any statements after break
are unreachable
 Default block has keyword default followed by colon. It replace else keyword in
if statement
 Default block can be last block and cannot be last block and have break statement
 There are many types of switch expressions:
 Integer (int): final value of expression should be integer like 7, x, x + y
 Byte (byte)
 Short (short)
 Character ( char )
 String (since java 7)
 Enum

 if we used switch expression with other then types, we have compiler error

 Case label restrictions:


 Must be within range of data type of switch expression

 Constant expression: Integer, string literal or constant variable (text between


double cotes (value known at compile time)
 Value must be unique
 Cannot be null
 When it is infeasible (not used) to use switch (if statement is preferred):
 More than one condition to test
 Tests other than equality x >= 3 (se switch if we have equality test)
 Switch expression is not integer, String or enum
 A case label restriction does not apply
 When if statement is preferred:
 Readability is improves: the code is more readable the switch statement than with
if statement
 Intent: switch deliberately states that only one variable is involved

 Speed: Faster due to single condition and constant case labels (show how time is
gain when you have more than 100 conditions)

3.2.3. Ternary
 It is other alternative to if else statement. But it can called also operators
 It only used like an alternative of is else statement in one scenario:
 Shorthand for if-else with single statements
 Syntax of ternary:

 Example:
 When is ternary is preferred
 Improves readability

 Ternary is not in all types like an expression statement for example when you code that
you have compiler error

3.2.4. For Statement


 It is used to iterate or loop over elements of an array or similar data structure and do
something with each element.
 It is an iteration statement
 It’s iterate or execute element block of code for some number of things
 Syntax:
 Initialization: can be variable declarations or list of common sparated expression
statement
o Initialization is optional
o Can have one initialization statement in initialization part:

o Expression statement: Can have list of comma-separated expression


statements

 Condition expression: some kind of Boolean expression. Must evaluate to


Boolean
o It is optional: if omitted, a true is assumed (infinite loop) then you can use
break statement like switch

 Expression list: part of increment or sometimes even decrement operation


o Can have list of comma-separated expression statements like in a case of
initialization
 Example:

3.2.5. For-each statement


 It’s introduced in java 5
 It’s make easier iterate arrays or other data structures

 Prefer for-each:
 Item 46: prefer for-each loop to traditional for loops. Because:
o Cleaner syntax. egg: index variable, condition, and expression list are
hidden
o Eliminates opportunities for error
o Preferred for nested iterations
 When is traditional for preferable
 You need to access to array index: for example replace elements
 Multiple arrays in parallel
 Use for loop (traditional or for-each) when you known how many times to loop

3.2.6. While Statement


 Its iteration statement
 Use while loop when you have only condition expression
 There are 2 types of while loop:
 Normal while:

 Do-while: run at least once

 Infinite loop
3.2.7. Break Statement
 It used to exits immediately enclosing switch or loop (for/while).
 When we use break statement with if() , is invalid example

 Labeled break statement: we use labeled break statement when we need to exits one of
outer switch or loop instead of the immediately and closing one. For this we can use:
 Label break: it is block of statement from it’s we want to exit the break. It’s any
value java identifier and need to followed by :

 Syntax:
 Example:

 The label use in the block statement should be the label for block in which the
break statement appears (include)

3.2.8. Continue statement


 It’s similar to break statement.
 It’s used with only loops
 It continues with next iteration if innermost loop and any statement immediately followed
it are not executed
 Continue statement in for loop:

 Labeled continue statement: it’s like labeled break statement


 Syntax:

 Labeled break vs. labeled continue:


3.3. Variable scope
 Every variable has a scope which is basically the part of the program where the variable
can be used and you get compiler error if you try to used outside of it scope
 There are many types of variable so there are many types of variables scope:
 Scope of class level variable:
o Are considered global and their accessibility in anywhere in the class
o Cannot assigned to variable declared before it

 Scope of local variable:


o Declared in methods or constructors or in block statement
o It is accessible from the declaration point to end of block(method,
constructors or control flow statement)
 Shadowing class level variables:
 Local variable cannot be shadowed or hidden
 Local variable can hide class variables

 Any methods invoked (or called) from current block will have new scope
4. Packages Strings and Information Hiding

4.1. Java API


 It’s library of hundred well-tested classes
 Java 8 have 4240 classes in Java API
 There classes are developed by experts and it’s used by millions of programmers
 The important packages of Java API are:
 Java.lang: the package contains classes that are fundamental to Java like String
class
 Java.util: data structures
 Java.io: reading from file and writing a file
 Java.net: include classes to handle networking like downloading
 Java.sql: used for retrieving and storing data in databases

 You can visit oracle site to show others packages

 There are 3rd parties of API that are open source. You can freely used them and customize
them as you need

 Spring: Popular framework for developing Web applications


 Apache Commons & Google Guava: Both of them include libraries for
performing common programming tasks like string manipulation or using
different data structures or using Math functions.
 JDOM: To parse XML documents
 Jackson or Google’s gson: To parse JSON text. JSON is like XML but is more
compact and in recent years, it is very commonly used to exchange data, e.g.,
Web services.
 Hibernate: Object-relational mapping (ORM) framework for interacting with
databases
 Apache Solr: For fast text search. Most major companies typically use Solr for
providing search functionality, e.g., ebay & linkedin
 Weka or Apache Mahout: For data mining tasks, e.g., providing product
recommendations like the way Amazon does with their “People who bought this
also bought … “feature.
 Apache Hadoop: Used for working with tera & peta bytes of data

 Item 47: Know and use the libraries: some benefits of this best practice:
 Focus on writing new logic without having to retrieve the wheel
 APIs improve performance over time. There is performance of existing
functionality would be improved in newer version of the API
 Gain new functionality too.

4.2. Packages
 Java classes are grouped in something called packages
 It’s basically directories in the file system
 To use particular class, you need to load a package that contains the class

 Why we need packages?


 Provide meaningful organization

 Help in name scope


 Security: for example you may want to restricts parts of your class to be
inaccessible outside of this package

4.2.1. Access class in packages


 Same package: direct access. Classes can directly reference those other classes by just
using their class names
 Different package: there are 2 ways to do
 import statement:

o Import single class:


 Explicit import (single type import). That we are importing a single type.
And this type can be class or interface.

o Import multiple classes:


 separate explicit import

 * import (or import on demand) : import all classes in a package


 Explicit import or * import?

 * import can break your code in future

 Better clarity with explicit import: when we look at imports statements, we know how
classes are used in this class
 Explicit import seems to be preferred
 Fully qualified class name (rare!): package name followed by a dot which is then
followed by class name (java.util.HashMap)

o Its required if you used 2 class with same name but in 2 different packages
like Date

There are 2 solutions for this problem:

 Solution1: See only one explicit import

 When you use simple name of class, it’s referred to class from the explicit import

 Solution 2: Only use fully qualified name


 This import is invalid import. It will give compiler error

 You can have as many import statements as you want and you may never even use those
classes and will not have any effects.
 Does not make your class bigger: it’s not going to import byte code of code
 Does not affect runtime performance
 Saves from typing fully-qualified name – compiler does this: when you compiler
your code, your compiler replaces the simple class names with the corresponding
fully qualified name

Java.lang is imported by default


4.2.2. Creating Packages
 Packages are directories on the file system
 1st step: I want all my packages names to start with the text “com.semanticsquare”. So
we need to create directories corresponding to package name
 Single name ‘basics’: So packages is a single directory and the directory name
would be the package name itself

 Multiple components ‘com.semanticsquare.basics’: package would correspond to a


nested directory structure like there. Each component in package name correspond
to a directory in the nested directory structure
 So your classes or packages, you need to add to this package, would be in this
structure of directories.

 2nd step package statement: to have a package statement in the class and the package
statement is this:

 It must be the first statement above any imports. If not, you have compiler error

 Effect of creating package: when you compile class and this class is in on package, you
need to add package name to the class name (fully qualified name) in the command like
this:

 Sub packages: like java.util and java.util.concurent


4.2.3. Naming package (conventions)

 1st : Use organization’s reverse internet domain name

 Components naming conventions:


 Lowercase alphabets (rarely digits)
 Should be short, generally (less than 8 characters)
 Meaning abbreviations like util for utilities
 Acronyms are fine like awt for Abstract Window Toolkit
 Generally single word
 Never start with java or javax (used with standard java API)

4.3. Strings
 String manipulations is one of the most activities in programming that’s because string
represent text
 Strings are objects of class java.lang.String
 We can simply instantiate the String class to create string objects
 Empty string:

 Not empty string: using one of constructors. There are 3 methods to create string
instantiate not empty:
o 1st method: using default constructors with passing string literal to
constructor
o 2nd method: using one of constructors of string class with passing
array of characters like this

We can also instantiate string using char like this:

o 3rd method (recommended way to create strings): using string


literal

 String literal between double quotes (“) is a string object

 String class uses characters array to store text.


 We know that in java characters are internally represented UTF-16 and schema which is
implementation of Unicode, so String in java is a sequence of Unicode characters.
 String is immutable: String object is value cannot be changed

 Specials features of string:


 String literal: string can be directly created from string literal
 + operator: String concatenation
 String pool (saves memory): all strings objects created are stored in special area
memory called string pool
o Advantage of string pool:
 if 2 strings are created using the same string return than they
would be represented by the same string object in the string
pool
 But, if you create 2 string with new keyword, then they
represented by different string object

4.3.1. String manipulations


 Length: return length of string (number of characters in string)

 Is empty method: return Boolean. True if string object is empty (length is zero) or false
if not
 Comparing: compare 2 strings. There are 3 methods used when compare 2 strings
 String.equals(): return Boolean, true if 2 strings are true. False if not (respect
lower case and upper case “a”.equals(“A”) == false)

 String. equalsIgnoreCase(): same that equals but it not respect lower case and
upper case “a”.equals(“A”) == true

 String. compareTo(): compare the Unicode value of characters of 2 strings and


return number. Compares two strings lexicographically. The comparison is based
on the Unicode value of each character in the strings. The character sequence
represented by this String object is compared lexicographically to the character
sequence represented by the argument string. The result is a negative integer if
this String object lexicographically precedes the argument string. The result is a
positive integer if this String object lexicographically follows the argument string.
The result is zero if the strings are equal; compareTo returns 0 exactly when the
equals(Object) method would return true.

 If two strings are different, then either they have different characters at some index that is
a valid index for both strings, or their lengths are different, or both. If they have different
characters at one or more index positions, let k be the smallest such index; then the string
whose character at position k has the smaller value, as determined by using the < operator,
lexicographically precedes the other string. In this case, compareTo returns the difference of
the two character values at position k in the two strings.

 Searching: search one string in another. There are many methods for searching string in
another string:
 String. contains(): check if string contain the argument or not (return Boolean )

 String. startsWith(): Tests if this string starts with the specified prefix (argument
of method)

 String. endsWith():Tests if this string ends with the specified suffix (the
argument of the method)

 String. indexOf():Returns the index within this string of the first occurrence of
the specified substring or the specified character
 String. lastIndexOf():Returns the index within this string of the last occurrence
of the specified character

 Examining individual characters to return individual character from string, you can use
String.charAt ().it Returns the char value at the specified index. An index ranges from 0
to length () - 1. The first char value of the sequence is at index 0, the next at index 1, and
so on, as for array indexing

 Extracting substrings: to extract substring from your string you should used
String.substring(). There are overloading for this method:
 One arguments (number): Returns a string that is a substring of this string. The
substring begins with the character at the specified index and extends to the end of
this string

 2 arguments (2 numbers): Returns a string that is a substring of this string. The


substring begins at the specified beginIndex and extends to the character at index
endIndex - 1. Thus the length of the substring is endIndex-beginIndex

 Case translation: There are many methods used to case translation:


 String. toLowerCase(): Converts all of the characters in this String to lower case
using the rules of the default locale. This is equivalent to calling
toLowerCase(Locale.getDefault()).

 String. toUpperCase(): Converts all of the characters in this String to upper case
using the rules of the default locale. This method is equivalent to
toUpperCase(Locale.getDefault()).

 String. trim():Returns a string whose value is this string, with any leading (start
with) and trailing (end with) whitespace removed. If this String object represents
an empty character sequence, or the first and last characters of character sequence
represented (the space character), then will removed

 String is immutable, so only copy is returned

 Replace: When you need to replace something you need to use


 String.replace(“”,””): Replaces each substring of this string that matches the
literal target sequence with the specified literal replacement sequence. The
replacement proceeds from the beginning of the string to the end, for example,
replacing "aa" with "b" in the string "aaa" will result in "ba" rather than "ab".
 String.replaceAll (“”,””): Replaces each substring of this string that matches the
given regular expression with the given replacement. An invocation of this
method of the form str.replaceAll(regex, repl) yields exactly the same result as the
expression java.util.regex.Pattern.compile(regex).matcher(str).replaceAll(repl)
 Split: split a string based on same characters. So you need to use String.split(“”)

 There is static method from Class String to convert from primitive type to string: we used
method called String.valueOf ()

 3rd party String utilities: these are other classes offered by others communities which
offered some additional features that are usually not available in standard string class that
comes with java library
 StringUtils: developed by Apache commons Lang
 String utilities class: developed by guava’s

4.3.2. String Pool Interning


 String literal vs. using new:
 String literal:
o Are stored in special area of memory called string pool (it’s part of
heap)
o Literals have same content then they share same storage in string pool
(until these 2 string literals are in different packages or different
classes)
 String via new keyword:
o Are no different from regular java object. Storage in the heap
o If we create string object with new keyword as first time (no object is
created with same string literal), there are 2 copies of string object are
created in memory like this

o If string objects have same content then they no shared same storage
 String pool:
 Store single copy of each string literal as string object
 There are one copy of string pool in the heap
 Also called string table
 String interning: is a process of building string pool
 Intern: s string pool element
 Is supported by python, ruby, C#, JavaScript
 String interning by JVM:

 Examples:
o String s = “hel” + “lo”; the 2 literal are created in string pool at compiler
time. And the result of concatenation is a string which is created at
runtime
o String s1 = “lo”; String s2 = “hel” + s1; s1 is created at runtime in string
pool by s2 is not created at string pool but simple object will be created
with new keyword.

 To add string which is not in string pool to string pool, you need to execute one method
like this:

 Is explicit interning useful? It must likely not mostly for JVM. It seem better off
or be used only by the JVM like:

4.3.3. String Immutability


 When string are created, it’s value can never be changed. When we change value of
string, then new object are created and assigned to variable and the old value of string
will be abandoned and removed by garbage collection (discussed in JVM part)

 Why immutability?
 String interning: if string is mutable, then sharing is not possible. When 2 String
objects are referred to same string literal and we would change the value of one
variable. Then the other variable will changed then the problem
 Concurrency: basically allow multiple threads to perform some actions at the
same time. The problem is similar to interning

 Security: if string are mutable, then hacker can change a file name in propriety
when use is authenticated when used FileInputStream method

4.3.4. String concatenation


 String concatenation means concatenate strings together. Join strings together
 + Operator: give precedence to string operation and so any non string will be
automatically converted to string.

 + operator will concatenate objects from left to right (strings in left will concatenate
first(like “hello” and “ world!”) after that the string result will concatenate with other
objects (“hello world!” with 125 and integer will automatically converted to string)
 String concatenation will also perform using StringBuilder and StringBuffer from
package java.lang.
 There are many differences between String class and StringBuilder and StringBuffer like:
 String class is immutable but StringBuilder and StringBuffer are mutable (allow
their content to be changed
 StringBuilder:
 It was introduced in java 5
 Example of its usage:
 When we append content using string builder then reference to new object will be
returned
 toString method will return string object which initialized using content in string
builder
 have many other methods like:
o length,
o delete: delete character between 2 indices
o insert: inserting content in specify index
o reverse: reverse string
o replace: replace certain substring with the specified string
o It’s not synchronized: it’s concurrency concept. If same string builder
object is shared across 2 threads then one thread can modify content
 StringBuffer:
 Added to java before string builder and it work just like string builder (like string
class but can modified
 It’s slow then string builder
 It’s synchronized (this synchronization slows the program) so it’s using by one
thread and will not shared between 2 thread (allow one thread to modify their
content)
 API compatible with string builder
 Item 51: Beware the performance of string concatenation (Attention aux
performances de la concatenation de chaînes).
 + operator concatenate more than new string unless performance is irrelevant
 With each concatenation using + operator these steps are executed:
o Step1: contents of both strings are first copied
o Step2: new string builder object is created and appended with both strings
o Step3: return string via toString()

 It’s quite expensive to use + operator so time consuming is O (N*N) in each


concatenation.
 Item 51 recommends to use string builder as it has linear complexity because one
object of string builder are created outside of for loop

 Use string builder if performance is important and use + operator only to combine
new strings.

4.3.5. Escape sequences


 It’s character preceded by \
 It help to use special characters in string and characters literals
 There are 8 escape sequences then java supports:
 \” : double quote (not required in char literal)
 \’ : single quote (not required in string literal)
 \n : new line
 \t : tab
 \\ : backslash
 \r : carriage return
 \b : backspace

4.4. Access levels


 It provides restrictions on accessing classes and their members
 Accessibility of classes/interfaces:
 Inside package: you can use any modifier (without any keyword) to need the
class accessible inside the package and all classes outside package cannot use it.
 Inside and outside package: use ‘public’ to can any class use this class and it
instantiate inside package and outside package.

 Accessibility for class members (variables / methods / constructors):


 Inside class: to be accessible only inside the class in which it is define use
keyword ‘private’
 Inside package: to be access only inside package and outside package, you do
not use any access modifier. We refers to this with package-private
 Inside package and any subclass: to be accessible to all classes in the same
package and to all subclasses and these subclasses may be outside the package,
you would use access modifier called ‘protected’.
 Inside and outside package: to be accessible by any class inside or outside
package (in any place), you would to use the access modifier ‘public’.
 Private access modifier: when you use private access modifier with variable, then this
variable will visible only within this class
 When use access modifier with local variables (in method) will you give
compiler error
 Using private modifier so this member is private to the class and not private to the
object

4.4.1. Information Hiding


 It’s important design principle that helps in building well design software
 Encapsulation: is a language facility that allows bundling of data and methods that
operate on data. Its data + methods. So in java it will be traduced by class like this
 Encapsulation alone does not lead to good design. Because many reasons:
 Tight coupling: variables are all declared as public so it’s access from any place

 So we need to follow additional design principle to make that happen

 Tight coupling disadvantage:


 We cannot enforce invariant (or range) that is we cannot define fixed value range
of values for the variable. For example we cannot restrict gender field to only
these 3 values (male, female, transgender) because client can directly access to the
field and changed
 Can’t change internal data representation without effecting client code (for
example change gender from string to integer)
 So the solution is information hiding presented by these items:
 Item 14: in public classes, use accessory methods, not public fields
o 1st step: change variable (fields) from public to private
o 2nd step: introduce 2 methods (getter and setter)
 one public setter method: to initialize field(mutating state)
 one public getter method: return the value of the field

 Item 13: minimize the accessibility of classes and members.


o Design minimal public API of your class: you show all the class
members and see which of them will really be needed by the client code
and just make them public
o Make all other members private
o Make member default, only if really needed in other class of same
package
o Accessibility for class/interface:
 If possible, let it be default
 If only one class uses it, make it private nested (inner class with
access private)
 using information hiding, we are loosely coupled system which have many advantages:
 we can develop, use, test, and optimize in isolation
 they can be utilized in multiple projects
 decrease in building large systems
5. Static final and Coding Conventions

5.1. Math class


 It’s from package java.lang.Math
 There are many methods common used from Math class
 Math.random():
o Return random number between 0.0 and 1.0 (1.0 is exclusive and method
will never return number of 1.0)
o Value return is double value

 Example for using random method from Math class to generate number between 0
and 5

 Math.abs():
o Return absolute of parameter number like this
o Return value always positive

 Math.round():
o It round the input argument to the nearest long or int. it depend on the data
type of the argument
o If argument is double value so it will nearest to the long value
o If argument is float so it will nearest to the int value

 Math.ceil():
o It return the small double that is greater than or equal to the argument and
should be equal to the integer
 Math.floor()
o Opposite of ceil
o Return the largest double that is less than not equal to the argument and it
should be equal to integer

 Math.min()/max()
 Math.sqrt()
o Positive square root of a double
o NaN if argument is NaN or –ve
o NaN -> Not-a-Number (undefined) like 0.0/0.0

5.2. Static
5.2.1. Static methods
 There are 2 types of methods:
 Instance methods: methods invoke bill with states that is instance variables
 Static methods: utility methods that do not depend on state. Example: min
methods from class java.lang.Math
 Static methods have the keyword static in the method declaration (absence of static
keyword so it’s instance method

 Example: main method


 Static methods are class level methods:
 No access to instance variables and instance methods
 Can access to static variables (class level variables)
 Static variables in class are shared all objects in class
 Can access static methods
 It save heap space if you don’t have to create an object

 Invocation: className.methodName() like Math.min()

 Not recommended to invoke static method using reference variable and if you do
compiler will implicitly resolve back to class name next

 Item 4: Enforce noninstantiability with a private constructor


 If all methods in your class are static then you can make the class non insatiable by
marking their constructor as private
 If you make constructor private, then no other code can create an object of your class
and also save same heap space

5.2.2. Static Variables


 It also declared with keyword static

 It is independent of any instance of the class


 It declared directly within class: that is a class level
 Like instance variables, they will initialized with default value if they are not explicitly
initialized
 Accessibility: ClassName.variable if they are declared with public class modifier
 Code inside the class can access directly
 It also referred with class variables
 One copy per class
 That copy is shared across all objects for the class

 With instance variables, each object has one copy for variable

 Accessibility within the class:


 Accessible from static methods define in the class
 Accessible from instance methods and constructors because it shared from all
objects for class
 Resume for accessibility for static variables/methods in class:

5.3. Initializers: Static and Instance variables


 Java provide a facility called Initializer block which can be useful for initializing static
and instance variables in certain situations
 There are separate initializer block for instance or static variables
 Static initializer: Useful to
 Initialize static fields that cannot be initialized in a single line(initialization need
multiple lines)
o Populating a data structure
o Initialization with error handling

 You can also use this method to initialize data when you have error handling:

 You can have any numbers of static initializers and they will be executed in the
order in which they appear in the code source
 Cannot reference to instance members like instance variables/methods in static
initializers
 Instance initializers:
 Initialize instance variables
 Syntax:

 You can have any numbers of static initializers and they will be executed in the order
in which they appear in the code source
 Can reference to static variables
 Constructors initialize state. Why instance initializer?
 Share code between multiple constructors

 Initializer copied into beginning of every constructor


5.4. Final Variable
 Final keyword is simply implies that something cannot be changed
 For variable value should be final that is it shouldn’t change once initialized then it will
be marked with keyword final

 Final basically implies constant. If it’s used with


 Primitive variable: value cannot be changed
 Reference variable: reference is constant (not object content). Reference always
reference to object it was initialized with.

 Cannot reassigned another object but however content of object can be changed

 Final variables don’t get default value


 Used with local, instance or static variables
 final instance variables:
 constant for life of the object
 must be initialize in (otherwise it get compiler error):
o declaration it self
o constructor (it called black final)
o instance initializer (it called black final)
 final local variables:
 constant for life of the block

 final static variables:


 Constant irrespective for all instances

 Must be initialized in (otherwise it get compiler error):


o Declaration
o Static initializer
 Naming convention:
o All CAPS (all characters with majuscule) with underscore separating
words
5.4.1. Constant variables
 In java variables are evaluated at runtime and not at compile time
 Constant variables are kind of final variables whose values are known at compile time
that we don’t have to wait at runtime to know their value

 It’s referred to as compile time constants

 The benefit of knowing value at compile time is that the compiler can take that value and
replace every instance of the variable with the actual value itself and stored in .class file

 So in this example the JVM doesn’t have to look into the math class to make this
assignment.

So the compiler is able to perform such an optimization

 Constant variable are final variables but for a final variable to be qualified as a constant
variable so there are few restrictions. To declare constant variable you need to be
 Declared with a modifier final
 Primitive or string
 Initialized in declaration statement
 Initialized with compile time constant expression ( this expression have constant
value at compile time)
 Valid example:
 Invalid example:

 compile-time constant expression:

5.5. Boxed Primitives


 In java we have 8 primitive types on each of them has an associated class called boxed
primitives:
 int: Integer
 long: Long
 byte: Byte
 short: Short
 float: Float
 double: Double
 boolean: Boolean
 char: Character

 These classes are part of java.lang package

 Uses of box primitives:


 Converting strings to primitives

 Provide several useful public static fields


o For example all numeric primitives have max and min value
o To know max or min value of numeric primitive, you can access to
MAX_VALUE, MIN_VALUE
 Utility methods
o Character: isLetter, isDigit, isLetterOrDigit, isLowerCase, isUpperCase,
isWhitespace
o Integer.toBinaryString(int)
o Double.isNaN(double)
 Populating data structures like ArrayList and HashMap
o Can’t add primitives directly to such data structures

 Used in Generics when defining something called parameterized types like


ArrayList<Integer>
 Common methods:
 Unwrap (boxed to primitive)

 Parsing strings

 To string

 Wrap

5.5.1. Auto boxing


 It’s introduced in Java 5
 It’s automatically boxes a primitive
 Prior to java 5, we want to manually create a box primitive by invoking either its
constructor or the value of methods. But in java 5 a feature called auto boxing was
introduced and it’s feature of compiler
 Auto boxing suggests a compiler can automatically box a primitive. That is if needed a
compiler can automatically convert a primitive into the box box primitive
 We can directly assign a primitive to a box primitive

 After compilation, the compiler will replace automatically the primitive value to initialize
box primitive like this:

 Auto unboxing

 In compilation, the compiler will replace boxed by int Value method like this

 Methods invoking:

 No auto boxing for arrays


5.5.2. Prefer Primitives to Boxed Primitives
 Item 49: Prefer primitive types to boxed primitives. For many
raisons like:
 Time and space efficiency: they are faster and also simpler. If box primitive are
used carelessly and if auto boxing is involved then we may face serious
performance issues. For example in this example we are calculate the sum of all
positive integer value

 This program is very slow because usage of long wrapper class instead of primitive long
and that sea while using long wrapper class would cause the slowness. Here plus operator has
two operands a primitive long and the box primitive

 Boxed primitives are classes:


 Primitive have only values
 Boxed primitives have identities too: each box primitive instance is a separate
object which has memory address and that memory address is the identities.

 So two box primitives can have same value but different identities

 == and !=: When you compare box primitive with operations == or !=, the JVM
do identities comparison. Same value but not equals
 <, <=, >, >=: when use these operators with box primitives, auto unboxing will
performed but it’s not recommendation to use arithmetic operators with box
primitive (item 49)
 Mixed type computations: the box primitive will initialize with null by default.
So when you doesn’t initialize box primitive and do arithmetic operators with
primitive type, so the box primitive will unboxing and generate
NullPointerException like this example.
5.6. Coding Conventions
5.6.1. Naming
 Item 56 Use generally accepted naming conventions.
 This item talk about two aspects of naming conventions
 Typographical naming: appearance(‫ )مظهر خارجي‬for example what case to use
like upper or lower case
 Grammatical naming: part of speech like usage of verbs nouns and adjectives
 Typographical:
 Packages:
o Lowercase alphabetic characters, rarely digits
o Generally short ( < 8 chars) and single word
o Meaningful abbreviations, e.g., util for utilities
o Acronyms are fine, e.g., awt for Abstract Window Toolkit
o Never start with java or javax
o Use organization’s (reverse internet domain name)
 Classes:
o Capitalize first letter of each word for example BufferedWriter
 Methods and variables:
o Use camel case that it is same as classes but the first letter is not
capitalized
o For static final variables: All CAPS with underscore separating words
 Abbreviations:
o Class methods and fields:
 Avoid abbreviations except commonly used like min/max
 Acronyms are fine like HttpUrl
o Local variables:
 Abbreviations and acronyms are fine
 Meaningful individual characters are fine
 Grammatical:
 Classes:
o Singular noun or noun phrase
 User (instead of Users), BufferWriter
o Keep class name simple and descriptive
 Methods:
o Can named based on what they are do or what they return
o Performing action:
 Verb or verb phrase and verbs indicate their action like append or
calculateDistance
 Use descriptive names for methods
 Don’t hesitate to use longer names
o Return boolean value:
 Start with is followed by noun or noun phrase or adjective

 Sometimes has is used like hasLicense


o Return a non boolean attribute of object:
 Noun or noun phrases( attribute name as the method name) like
gender or hashCode
 getAttribute if there is setter like getGender
o Special methods:
 Methods that convert type of an object: toType like toString,
toArray
 Static factory methods (responsibility of create object): valueOf
methods when discuses box primitives, of, getInstance,
newInstance, getType, newType
 Fields:
o Boolean fields:
 Usually adjective are used (some programmers use a prefix is but
not recommended) for example active instead of isActive
o Non boolean fields:
 Use noun or noun phrases
o Data structures:
 Use plural nouns for reference to array itself
 Use singular nouns for each elements
o Name objects of same class
 Use purpose
5.6.2. Structuring Programs
 Class organization: the order in which we need to place our class members:
1. Variables: static followed by instance variables
2. Static stuffs:
a) Static Initializers
b) Static nested classes
c) Static methods
3. Instance stuffs
a) Instance Initializers
b) Constructors
c) Instance nested classes
d) Instance methods
 Class size:
 The single responsibility principle: is a computer programming principle that
states that every module, class, or function[1] should have responsibility over a single part
of the functionality provided by the software, and that responsibility should be entirely
encapsulated by the class
o Helps create better abstractions (loosely coupled classes
o Helps in having fewer lines of codes
 Less than 2000 lines (if your class more than 2000 lines, then you should thing to
class responsibility)
 Methods:
 Small and focused
o Should do only one thing
 Refactor long method in many smalls methods
o Software reuse
o Clean and readable code

 Group methods with similar functionality


 Local variables:
 Item 45: minimize the scope of local variables
o Declare where first used

o Prefer for to while loops (because for loop minimize the scope of index)

5.6.3. Stylistic
 It’s just about placement of process we’re already doing
 Braces:
 Beginning brace: end of line
 Ending brace: start of the statement
 Indentation: Indent blocks by 4 spaces (or 1 tab)

 Wrapping lines:
 Line length is 80 characters but ins some expressions it possible
 If in one line there are long expression:
o Break (go to next line) after comma like in methods calls and
declarations
o Break (go to next line) before operator like in if blocks and arithmetic
ops
 When you break or go to the next line you should use 8 spaces rules (or 2 tabs)

5.6.4. Comments
 Comments are used in describing what this class does, or what a method does or in some
cases describing what some blocks of code within a method
 Sometimes that may be some non obvious design decisions that may go into to writing
some code and it will be useful to comment those design decisions in the code itself that
it’s useful for anybody viewing the code
 If you’re frequently writing comments than it could reflect poorly on the quality of code
 Most of time using good descriptive method and variable names would serve as
documentation by itself. That is for the most part we don’t have to write any comments at
all
 The self-descriptive without any comments would be very clean and beautiful
 There are 2 types of comments:
 Implementation comments: comments about implementation details
o // or /* … */
o Code documentation
o Disable code
 Documentation comment: are commentes for génération API documentation
(javadoc)
o /** … */
o Write comments for public API (implementation free)
o Code contain javadoc comments then java tools can extract to HTML files
and places in bin folder for JDK
 Implementation comments:
 Used inside methods or with private fields because it signify implementation
details
 There are types of implementations comments:
o Block comments:
 Describe a block of code
 1 or more line in /* … */
 Preceded by blank line
 Don’t use //
o Single line comments
 Short comments
 Preceded by blank line
 // or /* */

o Trailing comments
 Very short comments
 Appear on same line as code
 // or /* */
 Documentation comments:
 Used with methods, classes and constructors
 Javadoc comments or rarely block comments
o Usually javadoc comment: generally they should provide an overview and
shouldn’t talk about implementation details
o Block comments: when you would add implementation details, then you
can add them in separately block comments
 Use always documentation comments for describe classes, methods or
constructors (recommendation)
 Generally they should provide an overview and shouldn’t talk about
implementation details.
 If you would add implementation details then you can add them in separately
block comments
 Class documentation

 Methods documentation

 Generate javaDoc HTML

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy