Part 1 - Java programming Basics
Part 1 - Java programming Basics
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
There make java really solid and very reliable and a complete programming language
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.
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...
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.
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.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();
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
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
So you need to use floating point variable only if number contains a fractional part.
Typecasting is possible only between numeric data types (any primitive type except
Boolean) so cannot cast to Boolean or vice versa
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:
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)
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)
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
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:
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
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.
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
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
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
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
So you must change parameter list (parameter, of parameter type, or parameters numbers)
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:
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:
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.
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
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)
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
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)
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
^ -> Bitwise XOR (Exclusive OR): it return 1 ONLY if one of the input bits is 1
(but not both)
>>> Unsigned right shift: right shift left operand by numbers of bits specified on
right. It’s exact opposite of left shift operator
>> 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.
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
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
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
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.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
Any methods invoked (or called) from current block will have new scope
4. Packages Strings and Information Hiding
There are 3rd parties of API that are open source. You can freely used them and customize
them as you need
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
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
When you use simple name of class, it’s referred to class from the explicit import
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
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:
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
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
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
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
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
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:
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
+ 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()
Use string builder if performance is important and use + operator only to combine
new strings.
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
Not recommended to invoke static method using reference variable and if you do
compiler will implicitly resolve back to class name next
With instance variables, each object has one copy for variable
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
Cannot reassigned another object but however content of object can be changed
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.
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:
Parsing strings
To string
Wrap
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:
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
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
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