Get started !
online LTE test
online C test

Updated or New
GPRS RAN refresh notes New
GSM RAN refresh notes New



About
Sparkle At Learning
Feedback
Information Theory
Modulation
Multiple Access
DSP (wip)
OSI Model
Data Link layer
SS7
Word about ATM
GSM
GPRS
UMTS
WiMAX
LTE
CV2X
5G
Standard Reference
Reference books
Resources on Web
Miscellaneous
Mind Map
Magic MSC tool
Bar graph tool
Algorithms
C programming
C++ programming
Java programming
Perl resources
Python programming
Javascript/HTML
MATLAB
GIT
ASCII table
Project Management

another knowledge site

3GPP Modem
Simulator


Sparkle At Office comic strip

Java Programming

Index
1)Books on OOP and Java
2)Java releases
3)Object Oriented Programming keywords/concepts
4)"Hello World" program
5)jshell
6)Bullet points
7)class
8)Objects are References
9)Inheritance
10)Object, Overriding a method
11)abstract class
12)Polymorphism
13)Polymophic function with List, <? extends>
14)instanceof
15)Abstract interface, implements
16)static
17)final
18)Autoboxing
19)Sorting
20)Equality
21)TreeSet
22)HashMap
23)Streams API
24)Glossary

Programs compiled with OpenJDK 17.0.15 on Ubuntu.

1) Books on OOP and Java For introduction to Object Oriented Programming, you may refer

    Intro to OOP by Timothy Budd

Best book to start on Java would be,

     Head First Java by Kathy Sierra, Bert Bates, and Trisha Gee

2) Java releases Java is backward compatible, so old code should run on latest JVMs.

Java 9 is actually Java 1.9 (consider "Java SE" as "Java").

Refer All JDK release notes at oracle.com for official annoucements about feature additions/removal for each release.

If you need quick un-official overview, you may check this Page by Marco Behler.

Link API documentation for Release 17 is here.

Class Hierarchy can be found here.

3) Object Oriented Programming keywords/concepts Few basic concepts:

  • Classes and objects
  • Inheritance (hierarchy)
  • Polymorphism (overloading/overriding)
  • Abstraction (template)

  • 4) "Hello World" program In Java, all goes in a class.
    Code goes in file with extension .java.
    Compiler, javac, gives us .class file.
    Java Virtual Machine (JVM), triggered by java, runs the program.

    Below is proverbial "Hello World" program.

    import java.lang.System; // Not needed explicitly import java.lang.String; // Not needed explicitly public class Hello_World { public static void main(String[] args) { System.out.println("Hello World!"); System.out.println("------------"); } }

    ~/Java$ javac Hello_World.java ~/Java$ java Hello_World Hello World! ------------ ~/Java$

    5) jshell With jshell, we can execute Java code in a shell.

    ~/Java$ jshell Aug 09, 2025 1:44:06 PM java.util.prefs.FileSystemPreferences$1 run INFO: Created user preferences directory. | Welcome to JShell -- Version 17.0.15 | For an introduction type: /help intro jshell> System.out.println("Hello jshell !"); Hello jshell ! jshell> jshell> /exit | Goodbye

    6) Bullet points Java is strongly typed langauge, so it is particular about the type of data held by the variable and the type for which the variable is declared for.

    boolean and numbers are not compatible, so conditional expression must result into a boolean. Casting to boolean is also not allowed.

    Though no recommended, we can use public static to create global variables.

    All (class) files can be zipped in Java ARchive (.jar) file. manifest file specifies class with main method.

    Object is basically "a reference". So, when object is passed as a parameter in a function call, the function will be working with the original object. String is an object, but being immutable, above does not apply to it. Pass String to function and original String is not affected.

    7) class Sample program to illustrate class.

    //Either type full name for using existing packages or import it //Captilised word indicate Class import java.util.ArrayList; import java.util.Random; class Person { private String personName = "Doe"; public Person() // Constructor { // I am there, just in case } public Person(String firstName) // Constructor { personName = firstName; } public void Person() // Same name as Constructor, but *not* a Constructor // allowed, but not recommended { // just fooling around } public String getName() { return personName; // String is not mutable (immutable), so returning it is ok. } // I do not need Destructor like C++. -Java } public class Lucky_Draw { private static ArrayList<String> contestantNames = null; // Paramterised type, "<type>", introduced in Java 5 public static void addContestant(String contestantName) { if(contestantNames != null) contestantNames.add(contestantName); }; public static String drawTheWinner() { Random randomNumberEngine = new Random(); if( (contestantNames == null) || (contestantNames.isEmpty()) ) return null; int drawNumber = randomNumberEngine.nextInt(contestantNames.size()); return contestantNames.get(drawNumber); } public static void main(String[] args) { contestantNames = new ArrayList<String>(); Person Arnold = new Person("Arnold"); Person Tom = new Person("Tom"); Person Denzel = new Person("Denzel"); Person Audrey = new Person("Audrey"); Person Marilyn = new Person("Marilyn"); Person Sandra = new Person("Sandra"); Person Unknown = new Person(); addContestant(Arnold.getName()); addContestant(Tom.getName()); addContestant(Denzel.getName()); addContestant(Audrey.getName()); addContestant(Marilyn.getName()); addContestant(Sandra.getName()); addContestant(Unknown.getName()); String winnerName = null; winnerName = drawTheWinner(); System.out.println("Contestants are:"); for(String contestantName:contestantNames) // Enhanced "for" loop, introduced in Java 5 { System.out.println(contestantName); } System.out.println("(long pause)"); System.out.print(".... and the winner is .... number "); System.out.print(contestantNames.indexOf(winnerName) + 1); System.out.println(" .... " + winnerName + " !"); System.out.println("------------"); } }

    Contestants are: Arnold Tom Denzel Audrey Marilyn Sandra Doe (long pause) .... and the winner is .... number 7 .... Doe ! ------------

    8) Objects are References Objects are references, so declaring a variable of a class creates a reference; object needs to be created (or class needs to be instantiated) with new !

    class IAmAClass { private int intFromIAmAClass; // instance variable, so it will have "0" value. public IAmAClass() { System.out.println("Object of IAmAClass: \"I am born !\""); } public int getIntFromIAmAClass() { return intFromIAmAClass; } } public class Objects_are_References { // memory is allocated for integer variable // being class variable, it goes in Heap memory. public static int intVariable; // memory is allocated for object reference (and not for object), object is yet come into existence ! // being class variable, it goes in Heap memory. public static IAmAClass iAmAnObjectReference; public static void main(String[] args) { // static primitive integer type, so it will have "0" value. System.out.println("intVariable = " + intVariable); // static reference variable, so it will have "null" value. System.out.println("iAmAnObjectReference = " + iAmAnObjectReference); int localVariable; // local variable, so it will have junk value; compiler will complain ! // System.out.println("localVariable = " + localVariable); localVariable = 0xdecaf; System.out.println("I like my coffee " + String.format("%x", localVariable) + "."); iAmAnObjectReference = new IAmAClass(); // Object is created now. // being local variable, it goes in Stack memory. System.out.println("iAmAnObjectReference = " + iAmAnObjectReference); System.out.println("iAmAnObjectReference.getIntFromIAmAClass() returned " + iAmAnObjectReference.getIntFromIAmAClass()); iAmAnObjectReference = null; // Object (created above and was referenced by iAmAnObjectReference) is now eligible for "garbage collection". System.out.println("------------"); } }

    intVariable = 0 iAmAnObjectReference = null I like my coffee decaf. Object of IAmAClass: "I am born !" iAmAnObjectReference = IAmAClass@70dea4e iAmAnObjectReference.getIntFromIAmAClass() returned 0 ------------

    9) Inheritance Below is a simple illustration of "Inheritance".

    class EmployeePersonalInfo { String employeeName; // no access specifier, so it is public } class Employee { private EmployeePersonalInfo employeeRecord = null; // No one (not even Subclass) can access employeeName. protected String designationTitle = null; // Subclass can access it (even those outside package) public Employee() { employeeRecord = new EmployeePersonalInfo(); employeeRecord.employeeName = "Doe"; designationTitle = "Employee"; } public Employee(String joinerName) { this(); // call another constructor; in this case Employee() will be called. employeeRecord.employeeName = joinerName; } public String getEmployeeName() { return employeeRecord.employeeName; } public String getDesignation() { return designationTitle; } } class Developer extends Employee { private String programmingLanguage; public Developer() { // default constructor of superclass will be called implicitly. programmingLanguage = ""; designationTitle = "Developer"; } public Developer(String joinerName, String joinerProgrammingLanguage) { super(joinerName); // call appropriate constructor of superclass otherwise // default constructor of superclass will be called. programmingLanguage = joinerProgrammingLanguage; designationTitle = "Developer"; } public String getProgrammingLanguage() { return programmingLanguage; } } class Tester extends Employee { public Tester() { // default constructor of superclass will be called implicitly. designationTitle = "Tester"; } public Tester(String joinerName) { super(joinerName); designationTitle = "Tester"; } } public class Inheritance_Example { public static void main(String[] args) { Developer John = new Developer("John", "C"); System.out.println("New " + John.getDesignation() + ", " + John.getEmployeeName() + " (knows " + John.getProgrammingLanguage() + " language)"); Tester Smith = new Tester("Smith"); System.out.println("New " + Smith.getDesignation() + ", " + Smith.getEmployeeName()); System.out.println("------------"); } }

    New Developer, John (knows C language) New Tester, Smith ------------

    10) Object, Overriding a method Object is superclass of all classes. Its methods can even be overridden.

    class Child extends Object { public String toString() // Overriding a method of Superclass of all classes "Object" { return "I am just a child !"; } } class AnotherChild { public String toString() // Overriding a method of Superclass of all classes "Object" { return "I am also just a child !"; } } public class Child_of_Object { public static void main(String[] args) { Child justAChild = new Child(); System.out.println(justAChild); AnotherChild anotherChild = new AnotherChild(); System.out.println(anotherChild); System.out.println("------------"); } }

    I am just a child ! I am also just a child ! ------------

    11) abstract class Abstract class forces subclasses to implement its abstract methods.

    abstract class Human { public abstract void whoAreYou(); } class Woman extends Human { public void whoAreYou() { System.out.println("I am a woman"); } } class Man extends Human { public void whoAreYou() { System.out.println("I am a man"); } } public class Abstract_Example { public static void main(String[] args) { Man Adam = new Man(); Woman Eve = new Woman(); Adam.whoAreYou(); Eve.whoAreYou(); System.out.println("------------"); } }

    I am a man I am a woman ------------

    12) Polymorphism Below example illustrates Polymorphism in Java.

    import java.util.ArrayList; class Employee { private String employeeName = null; protected String designationTitle = null; public Employee(String joinerName) { employeeName = joinerName; } public String getEmployeeName() { return employeeName; } public String getDesignation() { return designationTitle; } } class Developer extends Employee { // Overriding also known as "Inclusion Polymorphism" public Developer(String joinerName) { super(joinerName); designationTitle = "Developer"; } // Overloading also known as "Ad hoc Polymorphism" public Developer(String joinerName, String joinerProgrammingLanguage) { this(joinerName); designationTitle += " in " + joinerProgrammingLanguage; } } class Tester extends Employee { public Tester(String joinerName) { super(joinerName); designationTitle = "Tester"; } } public class Polymorphism_Example { public static void main(String[] args) { Developer John = new Developer("John"); Tester Smith = new Tester("Smith"); // Declared as Employee and holding Developer, "Assignment Polymorphism" Employee Lucy = new Developer("Lucy", "Java"); // Parametrised type is also Polymorphism ArrayList<Employee> listOfAllEmployees = new ArrayList<Employee>(); listOfAllEmployees.add(John); listOfAllEmployees.add(Smith); listOfAllEmployees.add(Lucy); for(Employee eachEmployee : listOfAllEmployees) printEmployee(eachEmployee); System.out.println("------------"); } // Works with "Employee" and its subclasses, "Pure Polymorphism" public static void printEmployee(Employee employeeToPrint) { System.out.println(employeeToPrint.getEmployeeName() + " is " + employeeToPrint.getDesignation() + "."); } }

    John is Developer. Smith is Tester. Lucy is Developer in Java. ------------

    13) Polymophic function with List, <? extends> What happens when we pass List of subclass to a function which takes List of superclass ?
    Compiler will complain with "error: incompatible types".
    The solution is to change the function to accept the subclasses.

    import java.util.List; import java.util.ArrayList; class Person { private String personName; public Person(String givenName) { personName = givenName; } public String toString() { return personName; } } class CommonPerson extends Person { public CommonPerson(String givenName) { super(givenName); } } class VIPPerson extends Person { public VIPPerson(String givenName) { super(givenName); } } public class Polymorphic_Function_with_List_Example { public static void main(String[] args) { CommonPerson commonMan = new CommonPerson("Common Man"); CommonPerson commonWoman = new CommonPerson("Common Woman"); VIPPerson richMan = new VIPPerson("Rich Man"); VIPPerson richWoman = new VIPPerson("Rich Woman"); List<CommonPerson> commonPeople = new ArrayList<>(); commonPeople.add(commonMan); commonPeople.add(commonWoman); List<VIPPerson> richPeople = new ArrayList<>(); richPeople.add(richMan); richPeople.add(richWoman); System.out.println("Temple VIP queue ... "); templeVIPQueue(richPeople); System.out.println(""); System.out.println("Temple Common queue ... "); templeCommonQueue(commonPeople); System.out.println(""); System.out.println("Voting queue ... "); votingQueue(richPeople); votingQueue(commonPeople); List<Person> allPeople = new ArrayList<>(); allPeople.add(commonMan); allPeople.add(commonWoman); allPeople.add(richMan); allPeople.add(richWoman); System.out.println(""); countPopulation(allPeople); System.out.println("------------"); } public static void templeVIPQueue(List<VIPPerson> listVIPs) { listVIPs.forEach(eachVIP -> System.out.println(eachVIP)); } public static void templeCommonQueue(List<CommonPerson> listCommonPeople) { listCommonPeople.forEach(eachCommonPerson -> System.out.println(eachCommonPerson)); } public static void votingQueue(List<Person> allPeople) { allPeople.forEach(eachPerson -> System.out.println(eachPerson)); } public static void countPopulation(List<Person> allPeople) { System.out.println("Total population is " + allPeople.size() + "."); } }

    Polymorphic_Function_with_List_Example.java:63: error: incompatible types: List<VIPPerson> cannot be converted to List<Person> votingQueue(richPeople); ^ Polymorphic_Function_with_List_Example.java:64: error: incompatible types: List<CommonPerson> cannot be converted to List<Person> votingQueue(commonPeople); ^ Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output 2 errors

    However, if we change it as below, it will work.
    Though keyword extends is used, it will also work for subclasses which implements.

    public static void votingQueue(List<? extends Person> allPeople) { allPeople.forEach(eachPerson -> System.out.println(eachPerson)); }


    Below one will work too.

    public static <T extends Person> void votingQueue(List<T> allPeople) { allPeople.forEach(eachPerson -> System.out.println(eachPerson)); }

    Temple VIP queue ... Rich Man Rich Woman Temple Common queue ... Common Man Common Woman Voting queue ... Rich Man Rich Woman Common Man Common Woman Total population is 4. ------------

    14) instanceof Be careful when applying Polymorphism; instanceof helps in figuring out real object type.

    import java.util.ArrayList; class Person { protected String personName = "Doe"; public Person(String firstName) { personName = firstName; } public String toString() { return personName; } public boolean AreYouKiller() { return true; } } class Guest extends Person { public Guest(String firstName) { super(firstName); } public boolean AreYouKiller() { return false; } } class Killer extends Person { public Killer(String firstName) { super(firstName); } public boolean AreYouKiller() { return false; } } public class Murder_Mystry_Dinner { private static ArrayList<Person> guestList = null; public static void main(String[] args) { guestList = new ArrayList<Person>(); Person Arnold = new Guest("Arnold"); Person Tom = new Guest("Tom"); Person Denzel = new Guest("Denzel"); Person Audrey = new Guest("Audrey"); Person Marilyn = new Guest("Marilyn"); Person Sandra = new Guest("Sandra"); Person Doe = new Killer("Doe"); guestList.add(Arnold); guestList.add(Tom); guestList.add(Denzel); guestList.add(Audrey); guestList.add(Marilyn); guestList.add(Sandra); guestList.add(Doe); System.out.println("Let us find killer .... "); for(Person guestPerson:guestList) { if(true == guestPerson.AreYouKiller()) System.out.println(guestPerson + " is a killer."); else System.out.println(guestPerson + " is not a killer."); } System.out.println("...."); System.out.println("Better call Sherlock Holmes .... "); for(Person guestPerson:guestList) { if(guestPerson instanceof Killer) System.out.println("Sherlock: \"" + guestPerson + " is a killer ... catch him !\""); } System.out.println("------------"); } }

    Let us find killer .... Arnold is not a killer. Tom is not a killer. Denzel is not a killer. Audrey is not a killer. Marilyn is not a killer. Sandra is not a killer. Doe is not a killer. .... Better call Sherlock Holmes .... Sherlock: "Doe is a killer ... catch him !" ------------

    15) Abstract interface, implements There is not multiple inheritance in Java, however similar result can be achieved via interface.

    import java.util.ArrayList; class Employee { private String employeeName = null; protected String designationTitle = null; public Employee(String joinerName) { employeeName = joinerName; } public String getEmployeeName() { return employeeName; } public String getDesignation() { return designationTitle; } } // Interface for Consultants interface ConsultantEmployee { public abstract boolean isConsultant(); } // Developer can be a Consultant class Developer extends Employee implements ConsultantEmployee { private boolean aConsultant; public Developer(String joinerName, boolean isConsultant) { super(joinerName); designationTitle = "Developer"; aConsultant = isConsultant; } public boolean isConsultant() { return aConsultant; } } // Tester can be a Consultant class Tester extends Employee implements ConsultantEmployee { private boolean aConsultant; public Tester(String joinerName, boolean isConsultant) { super(joinerName); designationTitle = "Tester"; aConsultant = isConsultant; } public boolean isConsultant() { return aConsultant; } } // Manager can *not* be a Consultant class Manager extends Employee { public Manager(String joinerName) { super(joinerName); designationTitle = "Manager"; } } public class Interface_Example { public static void main(String[] args) { ArrayList<Employee> listOfAllEmployees = new ArrayList<Employee>(); Developer John = new Developer("John", false); listOfAllEmployees.add(John); Tester Smith = new Tester("Smith", false); listOfAllEmployees.add(Smith); Manager Lucy = new Manager("Lucy"); listOfAllEmployees.add(Lucy); Tester Emily = new Tester("Emily", true); listOfAllEmployees.add(Emily); for(Employee eachEmployee : listOfAllEmployees) { System.out.println("New " + eachEmployee.getDesignation() + ", " + eachEmployee.getEmployeeName()); boolean aConsultant = false; if(eachEmployee instanceof Developer) aConsultant = ((Developer)eachEmployee).isConsultant(); // Need to cast before calling the interface method else if(eachEmployee instanceof Tester) aConsultant = ((Tester)eachEmployee).isConsultant(); if(aConsultant) System.out.println("(" + eachEmployee.getEmployeeName() + " is a consultant)"); } System.out.println("------------"); } }

    New Developer, John New Tester, Smith New Manager, Lucy New Tester, Emily (Emily is a consultant) ------------

    16) static Below program illustrates various aspects of keyword, static.

    // instead of "System.out.println" use "out.println", NOT recommended import static java.lang.System.out; class Person { private static int populationNumber; public Person() { ++populationNumber; } public static int populationIs() { return populationNumber; } static // will be calling during loading of the class { System.out.println("Class Person is being loaded."); System.out.println("Initial population is " + populationNumber + "."); } } public class Static_Example { public static void main(String[] args) { System.out.println("main() starts."); Person Person1 = new Person(); Person Person2 = new Person(); Person Person3 = new Person(); Person Person4 = new Person(); System.out.println("Latest population is " + Person.populationIs() + "."); System.out.println("------------"); } }

    main() starts. Class Person is being loaded. Initial population is 0. Latest population is 4. ------------

    17) final final indeed means final !

    import java.util.Date; class Birth { private Date dateOfBirth; final private int lifeSpanInYears = 120; // variable cannot be changed. final public void setDateOfBirth(Date inputDate) // method cannot be overridden. { dateOfBirth = inputDate; } } final class Death { void mourn() // automatically final { } } class Rebirth extends Death { void bornAgain() { } } public class Final_Example { public static void main(String[] args) { System.out.println("------------"); } }

    Final_Example.java:21: error: cannot inherit from final Death class Rebirth extends Death ^ 1 error

    18) Autoboxing Java provides wrapper calls for all primitive types, for example Integer for int, as illustrated below.

    Automatic wrapping/unwrapping is known as Autoboxing.

    Wrapper classes for various primitive types are:

    Boolean
    Byte
    Double
    Float
    Integer
    Long
    Short


    import java.util.ArrayList; public class Autoboxing_Example { public static void main(String[] args) { // ArrayList<int> listOfInts = new ArrayList<int>(); // No, above is not possible, let us wrapper class Integer. // It works just like original int. ArrayList<Integer> listOfIntegers = new ArrayList<Integer>(); Integer randomNumber = 786; listOfIntegers.add(randomNumber); int devilsNumber = 666; listOfIntegers.add(devilsNumber); int int333 = 333; randomNumber = devilsNumber; // Integer = int, assignment works both ways randomNumber += int333; // += works with Integer. devilsNumber = randomNumber; // int = Integer listOfIntegers.add(devilsNumber); devilsNumber = randomNumber.intValue() - int333; // we can extract value as well, though we may not need it listOfIntegers.add(devilsNumber); for(Integer eachNumber : listOfIntegers) System.out.println(eachNumber); String strRandomNumber = Integer.toString(randomNumber); // Integer to String System.out.println("strRandomNumber = " + strRandomNumber); devilsNumber = Integer.parseInt("666"); // String to Integer System.out.println("devilsNumber = " + devilsNumber); System.out.println("------------"); } }

    786 666 999 666 ------------

    19) Sorting Three options to sort:
    Option 1: By implementing Comparable interface
    Option 2: By implementing Comparator
    Option 3: By using lambda in place of Comparator

    Options are illustrated below.

    import java.util.ArrayList; import java.util.List; import java.util.Collections; import java.lang.Comparable; import java.util.Comparator; class Person implements Comparable<Person> { private String personFirstName = "John"; private String personLastName = "Doe"; private int millionWorth = 0; public Person(String firstName, String lastName, int weathInMillions) { personFirstName = firstName; personLastName = lastName; millionWorth = weathInMillions; } public String toString() { return personFirstName + " " + personLastName + ", wealth of " + millionWorth + " millions USD"; } public String getFirstName() { return personFirstName; } public String getLastName() { return personLastName; } public int getMillionWorth() { return millionWorth; } public int compareTo(Person compareWithPerson) { // 1) Compare first name int compareResult = personFirstName.compareTo(compareWithPerson.getFirstName()); if(0 != compareResult) return compareResult; // 2) Compare last name compareResult = personLastName.compareTo(compareWithPerson.getLastName()); if(0 != compareResult) return compareResult; // 3) Compare wealth if(millionWorth > compareWithPerson.getMillionWorth()) return -1; if(millionWorth < compareWithPerson.getMillionWorth()) return 1; return 0; } } public class List_Example { public static void main(String[] args) { List<Person> hollywoodStars = new ArrayList<>(); Person Arnold = new Person("Arnold", "Schwarzenegger", 1200); Person Tom = new Person("Tom", "Cruise", 600); Person Denzel = new Person("Denzel", "Washington", 300); Person JenniferA = new Person("Jennifer", "Aniston", 320); Person Reese = new Person("Reese", "Witherspoon", 400); Person Jessica = new Person("Jessica", "Biel", 250); Person JenniferL = new Person("Jennifer", "Lopez", 400); hollywoodStars.add(Arnold); hollywoodStars.add(Tom); hollywoodStars.add(Denzel); hollywoodStars.add(JenniferA); hollywoodStars.add(Reese); hollywoodStars.add(Jessica); hollywoodStars.add(JenniferL); // Option 1: By implementing Comparable interface System.out.println(""); System.out.println("Default ..."); Collections.sort(hollywoodStars); hollywoodStars.forEach(eachStar -> System.out.println(eachStar)); // lambda for forEach // Option 2: By implementing Comparator System.out.println(""); System.out.println("Namewise ..."); NameComparator starNameCompare = new NameComparator(); hollywoodStars.sort(starNameCompare); hollywoodStars.forEach(eachStar -> System.out.println(eachStar)); System.out.println(""); System.out.println("Wealthwise ..."); NumberComparator starWeathCompare = new NumberComparator(); hollywoodStars.sort(starWeathCompare); for(Person eachStar : hollywoodStars) { System.out.print("With the wealth of " + eachStar.getMillionWorth() + " millions USD, it is "); System.out.println(eachStar.getFirstName() + " " + eachStar.getLastName()); } // Option 3: By using lambda in place of Comparator System.out.println(""); hollywoodStars.sort((firstPerson, secondPerson) -> firstPerson.getFirstName().compareTo(secondPerson.getFirstName())); hollywoodStars.forEach(eachStar -> System.out.println(eachStar)); System.out.println("------------"); } } class NameComparator implements Comparator<Person> { public int compare(Person firstPerson, Person secondPerson) { int compareResult = firstPerson.getFirstName().compareTo(secondPerson.getFirstName()); if(0 != compareResult) return compareResult; return firstPerson.getLastName().compareTo(secondPerson.getLastName()); } } class NumberComparator implements Comparator<Person> { public int compare(Person firstPerson, Person secondPerson) { if(firstPerson.getMillionWorth() > secondPerson.getMillionWorth()) return -1; if(firstPerson.getMillionWorth() < secondPerson.getMillionWorth()) return 1; return 0; } }

    Default ... Arnold Schwarzenegger, wealth of 1200 millions USD Denzel Washington, wealth of 300 millions USD Jennifer Aniston, wealth of 320 millions USD Jennifer Lopez, wealth of 400 millions USD Jessica Biel, wealth of 250 millions USD Reese Witherspoon, wealth of 400 millions USD Tom Cruise, wealth of 600 millions USD Namewise ... Arnold Schwarzenegger, wealth of 1200 millions USD Denzel Washington, wealth of 300 millions USD Jennifer Aniston, wealth of 320 millions USD Jennifer Lopez, wealth of 400 millions USD Jessica Biel, wealth of 250 millions USD Reese Witherspoon, wealth of 400 millions USD Tom Cruise, wealth of 600 millions USD Wealthwise ... With the wealth of 1200 millions USD, it is Arnold Schwarzenegger With the wealth of 600 millions USD, it is Tom Cruise With the wealth of 400 millions USD, it is Jennifer Lopez With the wealth of 400 millions USD, it is Reese Witherspoon With the wealth of 320 millions USD, it is Jennifer Aniston With the wealth of 300 millions USD, it is Denzel Washington With the wealth of 250 millions USD, it is Jessica Biel Arnold Schwarzenegger, wealth of 1200 millions USD Denzel Washington, wealth of 300 millions USD Jennifer Lopez, wealth of 400 millions USD Jennifer Aniston, wealth of 320 millions USD Jessica Biel, wealth of 250 millions USD Reese Witherspoon, wealth of 400 millions USD Tom Cruise, wealth of 600 millions USD ------------

    20) Equality == operator cannot be overridden in Java, but, equals method can be.

    class IAmSoUnique { private String myUniqueness; public IAmSoUnique(String uniqueQuality) { myUniqueness = uniqueQuality; } public String getMyUniqueness() { return myUniqueness; } public boolean equals(Object anotherIAmSoUnique) // yes, it takes Object as input. { return myUniqueness.equals(((IAmSoUnique)anotherIAmSoUnique).getMyUniqueness()); } // if equals is overridden, hashCode must also be overridden to respect the rule of equality in Java. public int hashCode() { return myUniqueness.hashCode(); } } public class Equality_Example { public static void main(String[] args) { IAmSoUnique godOfFire = new IAmSoUnique("Fire"); IAmSoUnique fireMan = new IAmSoUnique("Fire"); if(godOfFire == fireMan) System.out.println("godOfFire and fireMan are same."); else System.out.println("godOfFire and fireMan are *not* same."); if(fireMan.equals(godOfFire)) System.out.println("godOfFire and fireMan are equal."); else System.out.println("godOfFire and fireMan are *not* equal."); System.out.println("hashCode of godOfFire is " + String.format("0x%x", godOfFire.hashCode()) + "."); System.out.println("hashCode of fireMan is " + String.format("0x%x", fireMan.hashCode()) + "."); System.out.println("------------"); } }

    godOfFire and fireMan are *not* same. godOfFire and fireMan are equal. hashCode of godOfFire is 0x216a56. hashCode of fireMan is 0x216a56. ------------

    21) TreeSet TreeSet is Balanced Sorted (ascending order) Binary tree with no duplicates.

    import java.util.Set; import java.util.TreeSet; import java.util.Comparator; class Person { private String personFirstName = "John"; private String personLastName = "Doe"; public Person(String firstName, String lastName) { personFirstName = firstName; personLastName = lastName; } public String toString() { return personFirstName + " " + personLastName; } public String getFirstName() { return personFirstName; } public String getLastName() { return personLastName; } } public class TreeSet_Example { public static void main(String[] args) { Person Arnold = new Person("Arnold", "Schwarzenegger"); Person Tom = new Person("Tom", "Cruise"); Person Denzel = new Person("Denzel", "Washington"); Person JenniferA = new Person("Jennifer", "Aniston"); Person Reese = new Person("Reese", "Witherspoon"); Person Jessica = new Person("Jessica", "Biel"); Person JenniferL = new Person("Jennifer", "Lopez"); NameComparator nameCompare = new NameComparator(); Set<Person> personTree = new TreeSet<>(nameCompare); personTree.add(Arnold); personTree.add(Tom); personTree.add(Denzel); personTree.add(JenniferA); personTree.add(Reese); personTree.add(Jessica); personTree.add(JenniferL); personTree.add(Tom); // this is duplicate, TreeSet will *not* take it. personTree.forEach(eachPerson -> System.out.println(eachPerson)); System.out.println("------------"); } } class NameComparator implements Comparator<Person> { public int compare(Person firstPerson, Person secondPerson) { int compareResult = firstPerson.getFirstName().compareTo(secondPerson.getFirstName()); if(0 != compareResult) return compareResult; return firstPerson.getLastName().compareTo(secondPerson.getLastName()); } }

    Arnold Schwarzenegger Denzel Washington Jennifer Aniston Jennifer Lopez Jessica Biel Reese Witherspoon Tom Cruise ------------

    22) HashMap Key and values could be Objects in Java hash tables. Note that Key class must override equals and hashCode so that two matching key objects will lead to correct Value object.

    import java.util.Map; import java.util.HashMap; import java.util.Collections; // Key will be Language class Language { private String nameOfTheLanguage; public Language(String whichLanguage) { nameOfTheLanguage = whichLanguage; } public String toString() { return nameOfTheLanguage; } public boolean equals(Object anotherLanguage) { return toString().equals(((Language)anotherLanguage).toString()); } public int hashCode() { return toString().hashCode(); } } // Value will be Paradigm class Paradigm { private String nameOfTheParadigm; public Paradigm(String whichParadigm) { nameOfTheParadigm = whichParadigm; } public String toString() { return nameOfTheParadigm; } } public class HashMap_Example { public static void main(String[] args) { Paradigm paradigmProcedural = new Paradigm("Procedural"); Paradigm paradigmOOP = new Paradigm("Object oriented"); Language languageC = new Language("C"); Language languageCPP = new Language("C++"); Language languageJava = new Language("Java"); Map<Language, Paradigm> mappingLanguageToParadigm = new HashMap<>(); mappingLanguageToParadigm.put(languageC, paradigmProcedural); mappingLanguageToParadigm.put(languageCPP, paradigmOOP); mappingLanguageToParadigm.put(languageJava, paradigmOOP); for(Language eachLanguage : mappingLanguageToParadigm.keySet()) System.out.println("Programming paradigm for " + eachLanguage + " is " + mappingLanguageToParadigm.get(eachLanguage) + "."); Language duplicateLanguageJava = new Language("Java"); System.out.println("Value(" + duplicateLanguageJava + ") = " + mappingLanguageToParadigm.get(duplicateLanguageJava)); for(Paradigm eachParadigm : mappingLanguageToParadigm.values()) System.out.println(eachParadigm); // update value for key mappingLanguageToParadigm.put(languageCPP, paradigmProcedural); for(Paradigm eachParadigm : mappingLanguageToParadigm.values()) System.out.println(eachParadigm); System.out.println("------------"); } }

    Programming paradigm for Java is Object oriented. Programming paradigm for C++ is Object oriented. Programming paradigm for C is Procedural. Value(Java) = Object oriented Object oriented Object oriented Procedural Object oriented Procedural Procedural ------------

    23) Streams API Streams API allows processing of Collection of objects in chained manner.

    import java.util.List; import java.util.stream.Collectors; public class Streams_API_Example { public static void main(String[] args) { List<Integer> justFewNumbers = List.of(78,55,2,87,13,54,76,55,89,11,44,16,37,45,67,29,33,88); // find prime numbers in first 15 numbers from the list and print them in ascending order. List<Integer> primeNumbers = justFewNumbers.stream() .limit(15) .filter(aNumber -> checkPrime(aNumber)) // lambda for filter .sorted() .collect(Collectors.toList()); primeNumbers.forEach(primeNumber -> System.out.println(primeNumber)); System.out.println("------------"); } public static boolean checkPrime(Integer aNumber) { return java.math.BigInteger.valueOf(aNumber).isProbablePrime(10); // Certainty=10 } }

    2 11 13 37 67 89 ------------

    24) Glossary
    Ad hoc Polymorphism - 12
    ArrayList - 7
    Assignment Polymorphism - 12
    BigInteger - 23
    Collections - 19
    Collectors - 23
    Comparable - 19
    Comparator - 19
    Constructor - 7
    Destructor - 7
    HashMap - 22
    Heap memory - 8
    Inclusion Polymorphism - 12
    Integer - 18
    List - 19
    List.of - 23
    Map - 22
    Object - 10
    Overloading - 12
    Overriding - 12
    Parametrised type - 12
    Pure Polymorphism - 12
    Random - 7
    Set - 21
    Stack memory - 8
    String - 7
    TreeSet - 21
    cast - 15
    collect - 23
    compareTo - 19
    equals - 20
    extends - 9
    filter - 23
    final - 17
    forEach - 19
    garbage collection - 8
    immutable - 7
    implements - 15
    indexOf - 7
    instanceof - 14
    int - 18
    intValue - 18
    interface - 15
    isEmpty - 7
    isProbablePrime - 23
    keySet - 22
    lambda - 19, 23
    limit - 23
    main - 4
    mutable - 7
    new - 8
    parseInt - 18
    println - 4
    private - 9
    protected - 9
    public - 9
    sort - 19
    sorted - 23
    static - 16
    stream - 23
    super - 9
    this - 9
    toList - 23
    toString - 10, 18
    values - 22



    © Copyright Samir Amberkar 2023-24