Index |
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:
| ||
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("------------"); } }
| ||
5) jshell |
With jshell, we can execute Java code in a shell.
| ||
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("------------"); } }
| ||
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("------------"); } }
| ||
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("------------"); } }
| ||
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("------------"); } }
| ||
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("------------"); } }
| ||
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() + "."); } }
| ||
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() + "."); } }
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)); }
| ||
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("------------"); } }
| ||
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("------------"); } }
| ||
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("------------"); } }
| ||
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("------------"); } }
| ||
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("------------"); } }
| ||
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; } }
| ||
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("------------"); } }
| ||
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()); } }
| ||
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("------------"); } }
| ||
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 } }
| ||
24) Glossary |
|
© Copyright Samir Amberkar 2023-24