CoursJemaiSCJP Full2022
CoursJemaiSCJP Full2022
Abderrazak JEMAI
Abderrazak.Jemai@insat.rnu.tn
AU : 2021-2022
1
Sommaire
I. Declarations and Access Control ................................................................................... 4
I.1. Identifiers and JavaBeans ....................................................................................... 4
I.2. Declare Classes ...................................................................................................... 4
I.3. Declare Interfaces .................................................................................................. 5
I.4. Declare Class Members .......................................................................................... 5
II. Object Orientation......................................................................................................... 5
II.1. Inheritance, Is-A, Has-A .......................................................................................... 5
II.2. Polymorphism........................................................................................................ 6
II.3. Overriding/overloading .......................................................................................... 6
II.4. Implementing an interface ..................................................................................... 6
II.5. Coupling and cohesion ........................................................................................... 6
III. Assignements ............................................................................................................ 6
III.1. Passing Variables into Methods.............................................................................. 6
III.2. Array Declaration, Construction, and Initialization ................................................. 7
III.3. Initialization Blocks ................................................................................................ 7
III.4. Using Wrapper Classes and Boxing ......................................................................... 8
III.5. Autoboxing ............................................................................................................ 9
III.6. Overloading ......................................................................................................... 10
III.7. Garbage Collection............................................................................................... 10
IV. Operators ................................................................................................................ 10
IV.1. Arithmetic and relational Operators..................................................................... 10
IV.2. Logical Operators ................................................................................................. 10
V. Flow Control, Exceptions, and Assertions..................................................................... 11
1. If and switch Statements ......................................................................................... 11
2. Loops and Iterators .................................................................................................. 11
3. Handling Exceptions ................................................................................................ 12
4. Assertions................................................................................................................ 13
VI. Strings, I/O, Formatting, and Parsing........................................................................ 14
VI-1. String, StringBuilder, and StringBuffer .................................................................. 14
VI-2. File Navigation and I/O......................................................................................... 15
VI-3. Serialization ......................................................................................................... 16
VI-4. Parsing,Tokenizing ............................................................................................... 16
VII. Generics and Collections.......................................................................................... 17
2
VII-1. Overriding hashCode() and equals() ................................................................. 17
VII-2. Collections ....................................................................................................... 18
3
I. Declarations and Access Control
Methods
The first letter should be lowercase, and then normal camelCase rules should be
used. For example: doCalculation(), setValue()
Variables
Like methods, the camelCase format should be used, starting with a lowercase
letter. Some examples: buttonWidth, myString
Constants
Java constants are created by marking variables static and final. They should be
named using uppercase letters with underscore characters as separators:
MIN__VALUE
If the property is not a boolean, the getter method's prefix must be get.
There can be only one public class per source code file. If there is a public class in a file,
the name of the file must match the name of the public class.
Access control in Java is a little tricky because there are four access controls (levels of
access) but only three access modifiers (private, protected, public). The fourth access
4
control level (called default or package access) is what you get when you don't use any of
the three access modifiers.
• Class Access
Default Access: A class declaration with default access has no modifier. A class with
default access can be seen only by classes within the same package.
Public Access: A class declaration with the public keyword gives all classes from all
packages access to the public class.
You can modify a class declaration using the keyword final, abstract, or strictfp. Marking
a class as strictfp means that any method code in the class will conform to the IEEE 754
standard rules for floating points.
Final Classes: When used in a class declaration, the final keyword means the class can't be
subclassed. In other words, no other class can ever extend (inherit from) a final class, and
any attempts to do so will give you a compiler error.
Interface Constants: Interface constants are always considered public static final
whenever you have explicitly mention it or no.
Protected and Default Members: The protected and default access control levels are
almost identical, but with one critical difference. A default member may be accessed only
if the class accessing the member belongs to the same package, whereas a protected
member can be accessed (through inheritance) by a subclass even if the subclass is in a
different package.
HAS-A relationships are based on usage, rather than inheritance. In other words,
class A HAS-A B if code in class A has a reference to an instance of class B.
5
II.2. Polymorphism
Remember, any Java object that can pass more than one IS-A test can be considered
polymorphic.
II.3. Overriding/overloading
Any time you have a class that inherits a method from a superclass, you have the
opportunity to override the method (unless, as you learned earlier, the method is marked
final).
Coupling is the degree to which one class knows about another class.
The term cohesion is used to indicate the degree to which a class has a single, well-
focused purpose.
In general, good OO design calls for loose coupling and good OO design calls for high
cohesion
III. Assignements
III.1. Passing Variables into Methods
When you pass an object variable into a method, you must keep in mind that you're
passing the object reference. A reference variable holds bits that represent a way to reach
the specific object.
class ReferenceTest {
public static void main (String [] args) {
int a = 1;
ReferenceTest rt = new ReferenceTest();
6
System.out.println("Before modify() a = " + a);
rt.modify(a);
System.out.println("After modify() a = " + a) ;
}
void modify(int number) {
number = number + 1;
System.out.println("number = " + number);
}
}
int key []; // brackets after name (legal but less readable)
Constructing an Array
7
class SmallInit {
static int x;
int y;
}
Table 2: Initialization blocks
Static init blocks run once, when the class is first loaded.
class Init {
Init(int x) { System.out.println("1-arg const"); }
Init() { System.out.println("no-arg const"); }
static { System.out.println("1st static init"); }
{ System.out.println("1st instance init"); }
{ System.out.println("2nd instance init"); }
static { System.out.println("2nd static init"); }
public static void main(String [] args) {
new Init();
new Init(7);
}
}
8
Table 4: Wrapper Classes and Their Constructor Arguments
III.5. Autoboxing
Boxing is the mechanism of creating an object (wrapper) for a primitive in order to mach an
argument. For example, the int value 12 is boxed as an Integer(“12”) object.
two instances of the following wrapper objects will always be = = when their
primitive values are the same:
Boolean
Byte
9
Character from \u0000 to \u007f (7f is 127 in decimal)
Short and Integer from -128 to 127
III.6. Overloading
We discuss in this section, the case where no method matches exactly the arguments list
of caller one. When an exact match isn't found, the JVM uses the method with the smallest
argument that is wider than the parameter. Otherwise, JVM tries in order: Widening then
boxing and at last time var-args.
IV. Operators
10
| | short-circuit OR
Not Short-Circuit Logical Operators
& non-short-circuit AND
| non-short-circuit OR
Logical Operators ^ and !
^ exclusive-OR (XOR)
! Boolean invert
Any variables used in the expression of a while loop must be declared before the
expression is evaluated.
11
The enhanced for loop is a specialized for loop that simplifies looping through an array
or a collection.
int [] a = {1,2,3,4};
System.out.print(a[x]);
System.out.print(n);
int x;
long x2;
Long [] La = {4L, 5L, 6L};
long [] la = {7L, 8L, 9L};
int [][] twoDee = {{1,2,3}, {4,5,6}, {7,8,9}};
String [] sNums = {"one", "two", "three"};
Animal [] animals = {new Dog(), new Cat()};
3. Handling Exceptions
try {
// First line
12
//
}
catch(MyFirstException) {
// Handles this exception.
// This is the next line of the exception handler.
//
}
catch(MySecondException) {
// Put code here that handles this exception
}
A finally block encloses code that is always executed. Whether an exception was thrown
or not.
try {
} finally {
4. Assertions
Assertions are used at development time. They let you test your assumptions before
deployment. The assertion code evaporates when the program is deployed.
13
You can disable assertions at runtime with: java -da com.insat.TestClass
As we can notice, the concat method attached to the x object of String class doesn’t operate
on “Java” string itself. But a new element (string) is produced “Java Rules”. A searching
process on the dictionary is done. If there is no entry in the dictionary matching “Java Rule”,
this new string is added to the dictionary. In the two cases, an entry index is returned (for
example “102”) which serves as “a reference” used within the new object (String type)
corresponding to the concat return value. The reference to this new object is assigned to “x”
in example 1 (and abandoned in the two cases of example 2, so no change is done on s1 and
s2).
Several methods are available and can be used in String class. The most common are:
The following methods are some of the more commonly used methods in the
String class.
charAt() Returns the character located at the specified index
concat() Appends one String to the end of another ( "+" also works)
equalsIgnoreCase() Determines the equality of two Strings, ignoring case
length() Returns the number of characters in a String
replace() Replaces occurrences of a character with a new character
substring() Returns a part of a String
toLowerCase() Returns a String with uppercase characters converted
toString() Returns the value of a String
14
toUpperCase() Returns a String with lowercase characters converted
trim() Removes whitespace from the ends of a String
As we can see, each modification on a String object, a new String object is often created.
This mechanism is very expensive in term of memory allocation and related time processing.
The java.lang.StringBuffer and java.lang.StringBuilder classes should be used when you have
to make a lot of modifications to strings of characters.
The StringBuilder class was added in Java 5. It has exactly the same API as
the StringBuffer class, except StringBuilder is not thread safe.
In other words, its methods are not synchronized. It will run faster
File : creates a java object (File MetaData-descriptor serving as a java driver which
negotiates with the corresponding filesystem (AIX/jfs, Solaris/ufs, Windows/NTFS,
etc. ).
FileReader This class is used to inform the filesystem that read operations would be
requested. A no permission exception could be returned. Otherwise, the filesystem
and JVM will prepare the suitable mechanism to serve future read access methods.
15
BufferedReader This class is used to make FileReader more simple and efficient to
use. Designer will find in BufferedReader better methods in term of flexibility and
performance.
FileWriter This class is used to inform the filesystem that write operations would be
requested. It is used to write to character files. Its write() methods allow you to write
character(s) or Strings to the target file.
BufferedWriter This class is similar to FileWriters and used to make some kind of
write operations more efficient and easier to use.
PrintWriter This class has been created to enhance mechanism and related methods
of writing to a file. New methods like format(), printf(), and append() make
PrintWriters very flexible and powerful.
VI-3. Serialization
Serialization mechanism is used to save some objects and all of their instance variables
in order to reuse them later without redoing all the done process. A snapshot of the
selected objects (chosen to be persistent) is done. These object should be marked
Serializable (implements Serializable Interface) to inform the JVM to do what should be
done to facilitate the save/restore process of the selected object.
Example :
class Employee implements Serializable {}
public class SaveEmployees{
public static void main(String[] args) {
Employee e = new Employee();
try{ File f = new File(“employees.ser”);
FileOutputStream of = new FileOutputStream(f);
ObjectOutputStream objf = new ObjectOutputStream(of);
objf.writeObject(e);
objf.close();
} catch (Exception e) {}
}
}
VI-4. Parsing,Tokenizing
Regular expressions package (called regex) provides a lot of classes and related methods
to manage and search sub-expression in a wider one. It can be seen as a kind of
language within a language.
16
Example :
import java.util.regex.*;
class RegexSmall {
public static void main(String[] args) {
Pattern p = Pattern.compile("ab"); // the expression
Matcher m = p.matcher("abaaaba"); // the source
boolean b = false;
while(b = m.find()) {
System.out.print(m.start() + " ");
}
}
}
This produces : 0 4
Tokenizing is the process of taking big pieces of source data, breaking them into little
pieces, and storing the little pieces in variables.
When comparing two objects, the equals() method in class Object uses only the
== operator for comparisons, so unless you override equals(), two objects are
considered equal only if the two references refer to the same object.
Overriding hashCode()
17
A subset of objects may be stored in the same entry if their hashcodes are identical.
VII-2. Collections
As a general definition of collections, they can be categorized into four main types:
Sets are used when you don't want any duplicates in your
collection.
a b c d e b Processing
- Sorted, Unsorted,
- Ordered or Unordered.
Some basic operations you should remember and use within collections:
18
and another “fifth” category providing a “set” of utilities that could be
widely used for collection elements :
o Utilities : Collections, Arrays
19
Classes implementing Collection Interface :
Applications to Collections:
• ArrayList
ArrayList is a kind of vector that could contain elements. These elements should be Objects
and not primitives.
import java.util.*;
class Ex2ArrayList
{
public static void main(String [] args)
{
System.out.println("ArrayList methods are not synchronized");
System.out.println(" whereas Vector methods are synchronized for thread
safety");
ArrayList<Integer> a = new ArrayList<Integer>();
a.add(2);
a.add(4);
a.add(6);
a.add(8);
System.out.println("a has " + a.size() + " elements");
System.out.println("a=" + a);
20
System.out.println("Deleeting element Integer 6...");
a.remove(new Integer(6));
System.out.println("a has now " + a.size() + " elements");
System.out.println("a=" + a);
}
}
• Using the Collections Framework
import java.util.*;
class Ex3ArrayListCollectionsFramework
{
public static void main(String [] args)
{
System.out.println("Collections methods applied to ArrayList elements");
ArrayList<Integer> a = new ArrayList<Integer>();
a.add(2); a.add(6); a.add(4); a.add(8);
System.out.println("a=" + a);
System.out.println("Sorting a elements...");
Collections.sort(a);
System.out.println("a=" + a);
}
import java.util.*;
}
}
21
import java.util.*;
class Ex4_compareTo
{
public static void main(String [] args)
{
System.out.println("Using compareTo implementation to compare employee
criteria\n");
ArrayList<EmployeeComparedByAge > a = new ArrayList<EmployeeComparedByAge >();
EmployeeComparedByAge e1= new EmployeeComparedByAge();
e1.name="Sami"; e1.salary=2000; e1.age=30;
for (EmployeeComparedByAge x : a)
{
System.out.println(x.name + " has " + x.salary + " salary and " + x.age +
" years olds");
}
System.out.println("\n\nSorting a elements...");
Collections.sort(a);
for (EmployeeComparedByAge x : a)
{
System.out.println(x.name + " has " + x.salary + " salary and " + x.age +
" years olds");
}
}
22
23