[go: up one dir, main page]

0% found this document useful (0 votes)
3 views23 pages

CoursJemaiSCJP Full2022

The document provides a comprehensive overview of the Java programming language, covering key topics such as declarations, object orientation, assignments, operators, flow control, exceptions, and collections. It outlines naming conventions, access control, inheritance, polymorphism, and the use of interfaces, as well as practical examples of method overloading, garbage collection, and control structures. This serves as a foundational guide for understanding Java programming principles and practices.
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)
3 views23 pages

CoursJemaiSCJP Full2022

The document provides a comprehensive overview of the Java programming language, covering key topics such as declarations, object orientation, assignments, operators, flow control, exceptions, and collections. It outlines naming conventions, access control, inheritance, polymorphism, and the use of interfaces, as well as practical examples of method overloading, garbage collection, and control structures. This serves as a foundational guide for understanding Java programming principles and practices.
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/ 23

JAVA Language

Abderrazak JEMAI

Institut National des Sciences Appliquées et de Technologie

Département Génie Informatique et Mathématiques

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

I.1. Identifiers and JavaBeans


In Java, identifiers must start with a letter, a currency character ($), or a connecting
character such as the underscore ( _ ). Java keywords can’t be used as identifiers.

Classes and interface:


The first letter of a class or an interface should be capitalized

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

JavaBeans Naming Standards


JavaBeans are Java classes that have properties. Think of properties as private instance
variables. The methods that change a property's value are called setter methods, and the
methods that retrieve a property's value are called getter methods.

JavaBean Property Naming Rules

If the property is not a boolean, the getter method's prefix must be get.

 If the property is a boolean, the getter method's prefix is either get or


is. For example, getValue() or isFull() are both valid JavaBeans names
for a boolean property.

The setter method's prefix must be set.

I.2. Declare Classes


• Source File Declaration Rules

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.

• Class Declarations and Modifiers

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.

• Nonaccess Class Modifiers (strictfp, final and abstract)

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.

Abstract Classes: An abstract class can never be instantiated. It should be extended


(subclassed).

I.3. Declare Interfaces


An interface can be seen as a 100-percent abstract class.

Interface Constants: Interface constants are always considered public static final
whenever you have explicitly mention it or no.

I.4. Declare Class Members


Members can use all four: public, protected, default, private.

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.

II. Object Orientation

II.1. Inheritance, Is-A, Has-A


In OO, the concept of IS-A is based on class inheritance or interface implementation. IS-A
is a way of saying, "this thing is a type of that thing."

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).

You cannot override a method marked final.

You cannot override a method marked static.

Overloaded methods ("Le surcharge" en français). The rules are simple:

• Overloaded methods MUST change the argument list.


• Overloaded methods CAN change the return type.
• Overloaded methods CAN change the access modifier.
• Overloaded methods CAN declare new or broader checked exceptions.

II.4. Implementing an interface


When you implement an interface, you're agreeing to adhere to the contract defined in the
interface. A class can implement more than one interface.

II.5. Coupling and cohesion


Coupling and cohesion, have to do with the quality of an OO design.

 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.

When a primitive variable is passed to a method, it is passed by value.

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);
}
}

 The resulting output looks like this:


Before modify() a = 1
number = 2
After modify() a = 1

Table 1: Passing a primitive variable to a method

III.2. Array Declaration, Construction, and Initialization


Declaring an Array

Declaring an array of primitives:

int[] key; // brackets before name (recommended)

int key []; // brackets after name (legal but less readable)

Declaring an array of object references:

Thread[] threads; // Recommended

Thread threads[]; // Legal but less readable

Constructing an Array

int [] testScores; // Declares the array of ints

testScores = new int[4]; // constructs an array and assigns it testScores variable

III.3. Initialization Blocks


Initialization blocks run when the class is first loaded (a static initialization block) or when
an instance is created (in the case of an instance initialization block). Let's look at an
example:

7
class SmallInit {

static int x;

int y;

static { x = 7 ; } // static init block

{ y = 8; } // instance init block

}
Table 2: Initialization blocks

 Static init blocks run once, when the class is first loaded.

 Instance init blocks run every time a class instance is created.

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);
}
}

 The following output should make sense:


1st static init
2nd static init
1st instance init
2nd instance init
no-arg const
1st instance init
2nd instance init
1-arg const
Table 3: Initialization blocks (Example)

III.4. Using Wrapper Classes and Boxing

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.

 Boxing, ==, and Equals()

Integer i1 = 1000;Integer i2 = 1000;


if(il != i2) System.out.println("different objects");
if(i1.equals(i2)) System.out.println("meaningfully
equal");
Produces the output:
different objects
meaningfully equal
Integer i3 = 10;Integer i4 = 10;
if(i3 == i4) System.out.println("same object");
if(i3.equals(i4)) System.out.println("meaningfully
equal");

This example produces the output:


same object
meaningfully equal

 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.

III.7. Garbage Collection


An object becomes eligible for garbage collection when no more reference variable
references to it. Before the object is deleted by the garbage collector, Java provides you a
mechanism to execute some code. This code is located in a method named finalize() that
all classes inherit from class Object.

IV. Operators

IV.1. Arithmetic and relational Operators


Arithmetic and relational operators are similar to those of C Language.

 Compound Assignment Operators


y = y - 6;
x = x + 2 * 5;
Now, with compound operators:
y -= 6;
x += 2 * 5; (Not x =(x+2)*5)
 Relational Operators
> greater than
>= greater than or equal to
< less than
<= less than or equal to}

Table 6: Java arithmetic and relational Operators

IV.2. Logical Operators

 Logical Operators(&, |, ^, !, &&, and | )


Bitwise Operators (Not on the Exam!)
Short-Circuit Logical Operators
&& short-circuit AND

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

Table 7: Java Logical Operators

V. Flow Control, Exceptions, and Assertions


1. If and switch Statements
 The basic format of an if statement is as follows:
if (booleanExpression) {
System.out.println("booleanExpression yields true");
}

 The following code demonstrates a legal if-else statement:


if (x > 5) {
System.out.println("x is greater than 5");
} else {
System.out.println("x is not greater than 5");
}

 The general form of the switch statement is:


switch (expression) {
case constant1: code for case 1
case constant2: code block for case 2
default: code block for default
}
Table 8: switch statement

2. Loops and Iterators


 A while statement looks like this:
while (expression) {
// do stuff
}

Any variables used in the expression of a while loop must be declared before the
expression is evaluated.

 The following shows a do loop in action:


do {
System.out.println("Inside loop");
} while(false);
Table 9: while statement

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};

for(int x = 0; x < a.length; x++) // basic for loop

System.out.print(a[x]);

for(int n : a) // enhanced for loop

System.out.print(n);

Table 10: enhanced for loop statement

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()};

// legal 'for' declarations


for(long y : la ) ; // loop thru an array of longs
for(long lp : La); // autoboxing the Long objects
into longs
for(int[] n : twoDee); // loop thru the array of arrays
for(int n2 : twoDee[2]); // loop thru the 3rd sub-array
for(String s : sNums); // loop thru the array of Strings
for(Object o : sNums); // set an Object ref to each
String
for(Animal a : animals); // set an Animal ref

// ILLEGAL 'for' declarations


for(x2 : la); // x2 is already declared
for(int x2 : twoDee); // can't stuff an array into an
int
for(int x3 : la); // can't stuff a long into an int
for(Dog d : animals); // you might get a Cat!
Table 11: Examples of enhanced for loop statement

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.

The following legal code demonstrates a try, catch, and finally:

try {

// calling methods having exceptions in their declarations

} catch (AnException ex) {

// Exception handling code

} finally {

// a code to be always executed

// for example, closing database or a network connection

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.

 Running with Assertions

You can enable assertions at runtime with: java -ea com.insat.TestClass

13
You can disable assertions at runtime with: java -da com.insat.TestClass

 By default, assertions are disabled.

VI. Strings, I/O, Formatting, and Parsing


VI-1. String, StringBuilder, and StringBuffer
Objects belonging to String class are store in a specific place (dictionary) and their value can
never change (they are immutable). For example:

 Example 1 : Let's Lake this example a little further:


String x = "Java";
x = x.concat(" Rules!");
System.out.println("x = " + x); // the output is: Java Rules!
x.toLowerCase(); // no assignment, create a new, abandoned String
System.out.println("x = " + x); // no assignment, the output is still: x = Java Rules!
x = x.toLowerCase(); // create a new String, assigned to x
System.out.println("x = " + x); // the assignment causes the output: x = java rules!
 Example 2 : Let's Lake this example a little further:
String s1 = "spring ";
String s2 = s1 + "summer ";
s1.concat("fall ") ;
s2.concat(s1);
s1 += "winter ";
System.out.println(s1 + " " + s2);
The result of this code fragment is "spring winter spring summer".

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.

 StringBuffer vs. StringBuilder

 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

 So apart from synchronization, anything we say about StringBuilder's


methods holds true for StringBuffer's methods, and vice versa.

 Example using StringBuilder and StringBuffer


StringBuffer sb = new StringBuffer("abc");
sb.append("def");
System.out.println("sb = " + sb); // output is "sb =
abcdef"
 Because operations are done on the object itself, the method calls can be chained
to each other :
StringBuilder sb = new StringBuilder("abc");
sb.append("def").reverse().insert(3, "---");
System.out.println( sb ); // output is "fed ---
cba"

VI-2. File Navigation and I/O


A summary of the I/O main classes is as follows:

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. ).

Several methods can be invoked like :


delete()
renameTo()
exists()

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.

ObjectOutputStream and ObjectIntputStream class could be used to save and restore


serializable marked objects.

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.

 Tokenizing with String.split()


import java.util.*;
class SplitTest {
public static void main(String[] args) {
String[] tokens = args[0] .split(args[1] ) ;
System.out.println("count " + tokens.length);
for(String s : tokens)
System.out.println(">" + s + "<");
}
}
% java SplitTest "ab5 ccc 45 @" "\d"
Produces :count 4, >ab< > ccc < >< > @<

VII. Generics and Collections


VII-1. Overriding hashCode() and equals()
Overriding equals()

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()

Hashcode mechanism is used to increase performance in case of large collections of


data. Collections such as HashMap and HashSet use the hashcode value of an object to
determine how the object should be stored and retrieved in/from the collection.

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:

 Lists Lists of things (classes that implement List) : [a, b, a, a, c,d,e,d]

 Sets Unique things (classes that implement Set). [a, b, c, d, e]

Sets are used when you don't want any duplicates in your
collection.

 Maps Things with a unique ID (classes that implement Map) : Record


of elements (example : Database Table)

 Queues Things arranged by the order in which they are to be


processed :

a b c d e b Processing

Elements within these four categories could be

- Sorted, Unsorted,
- Ordered or Unordered.

Some basic operations you should remember and use within collections:

− Add objects to the collection.


− Remove objects from the collection.
− Find out if an object within a collection.
− Retrieve an object from a collection.
− Iterate through the collection in order to manipulate and process each
element one after another.

Collections are of two kinds:

- Interfaces : Collection, Set, SortedSet, List, Map, SortedMap, Queue


- Classes : subdivided into 4 main categories :
o Maps : HashMap, HashTable, TreeMap, LinkedHashMap
o Sets : HashSet, LinkedHashSet, TreeSet
o Lists : ArrayList, Vector, LinkedList
o Queues : PriorityQueue

18
and another “fifth” category providing a “set” of utilities that could be
widely used for collection elements :
o Utilities : Collections, Arrays

• Comparing Collection Interfaces and Classes

Collections are of two kinds:

- Interfaces : Collection, Set, SortedSet, List, Map, SortedMap, Queue


- Classes : subdivided into 4 main categories :
o Maps : HashMap, Hashtable, TreeMap, LinkedHashMap
o Sets : HashSet, LinkedHashSet, TreeSet
o Lists : ArrayList, Vector, LinkedList
 Vector is basically the same as an ArrayList, but Vector
methods are synchronized for thread safety.

o Queues : PriorityQueue

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);

System.out.println("Deleeting element at order 1...");


a.remove(1);
System.out.println("a has now " + 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

We can found many useful methods in Collections class : sort()

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);
}

Implementing compareTo method()

import java.util.*;

public class EmployeeComparedByAge implements Comparable<EmployeeComparedByAge>


{
String name;
int age;
int Salary;
public int compareTo(EmployeeComparedByAge e) {
return Integer.compare(age, e.age);

}
}

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;

EmployeeComparedByAge e2= new EmployeeComparedByAge();


e2.name="Mohamed"; e2.salary=800; e2.age=32;

EmployeeComparedByAge e3= new EmployeeComparedByAge();


e3.name="Youssef"; e3.salary=1400; e3.age=20;

a.add(e1); a.add(e2); a.add(e3);

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

You might also like