ClassInstance (member) Variable ConstructorGetter/SetterMethodObject Instantiation (creation of objects)Use the ObjectArrays & CollectionsPolymorphism - extend, overrideCallbackObverver Design PatternInner Class - Nested ClassMemory LeaksenumUtilitiesfor loopfor each loop & var argswhile & iteratorsStringBuilderCompare StringCharAtequals() and hashCode()Try Catch, Finally, ThrowsThreadIntroductionAdvanced Concepts Reference - As neededAnnotationsRegular ExpressionsCompile & RunJava HomeCompileRunCreate a jar fileOtherfind command - extremely handy and usefulVisual VM
All Java classes have the following structure. They are organized as below for better readability.
x1// Instance Variables23// Constructors45// Getters & Setters 67// Methods89// Inner ClassesAccess modifiers in Java - see and memorize this table
Instance variables are typically private, hence use getters and setters which are public.
Instances are created using new className(), which invokes its constructor Understand the use of super in constructors.
Methods have the following signature. Param is a placeholder, it is bound to the variable that is passed during method invokation, i.e., when the method is invoked. While invoking methods, types must match!.
xxxxxxxxxx11public int methodName (Type1 param1, Type2 param2, Type3 param3, ...)Methods can be called only through the reference to the instance of the object.
xxxxxxxxxx81A a = new A();2a.method(argument);34B b - new B(a);5C c = b.method2();67c.method3(somevariable);8...xxxxxxxxxx21Bike bike; // type variable2int x; // type variablexxxxxxxxxx11Bike (int hp, String color); // type variablethis is used for chaining, super is used for super's constructor**
xxxxxxxxxx11Bike getBike(); Accesspermission returntype name(type parameter);
xxxxxxxxxx61boolean enjoy(int hp) {2 if (hp > 100)3 return true;4 else5 return false;6}xxxxxxxxxx21Bike bike = new Bike(100, "red"); // matching constructor2Bike bike = new Bike(100, "red", 100000); xxxxxxxxxx31String color = bike.getColor();2float cost = bike.getCost();3boolean result = bike.enjoy();
xxxxxxxxxx121Bike[] bike;2ArrayList<Bike> alBike;34Bike[] bike = new Bike[5];5ArrayList<Bike> alBike = new ArrayList();67Iterator<Bike> iterator = alBike.iterator();8while(iterator.hasNext()) {9 Bike bike = iterator.next();10 System.out.println(bike.hp);11}12
The entire philosophy of Object Oriented Programming is creating different "behaviors" of methods by "overriding" them. Overriding is achieved by extend a class and/or implements interfaces.
Interfaces are public. Interfaces can contain instance variables but they are final. Interfaces contain only method signatures. There are no actual implementations. However, if a method is static, it can be implemented in the interface. For example
xxxxxxxxxx101interface Itest {2 int z = 10;3 4 int sum(int x, int y);5 6 static int sub(int x, int y) {7 int c = x - y;8 return c;9 }10}invoke as follows:
xxxxxxxxxx11int result = Itest.sub(10,3);
xxxxxxxxxx61package tmp;23public interface ITest {4 String name = "Josh";5 String getName();6}xxxxxxxxxx51package tmp;23public interface ITest2 {4 int getAge();5}xxxxxxxxxx171package tmp; 23public abstract class AbstractTest implements ITest {45 public String name;6 public int age;78 public AbstractTest(String name, int age) {9 this.name = name;10 this.age = age;11 }1213 14 public String getName() {15 return this.name;16 }17}xxxxxxxxxx181package tmp;23public class ConcreteTest extends AbstractTest implements ITest2 {45 public ConcreteTest(String name, int age) {6 super(name, age);7 }89 10 public String getName() {11 return "CC: " + this.name;12 }1314 15 public int getAge() {16 return this.age;17 }18}xxxxxxxxxx391package tmp;23public class Main {45 public static <Itest2> void main(String[] args) {67 // **anonymous** class implementing interface - callback8 ITest iTest = new ITest() {9 10 public String getName() {11 System.out.println(name);12 return null;13 }14 };15 iTest.getName();1617 ConcreteTest concreteTest = new ConcreteTest("Josh",25);18 System.out.println(concreteTest.name);19 System.out.println(concreteTest.age);2021 ConcreteTest test = new ConcreteTest("JoshG",20) {22 23 public String getName() {24 this.name = "Josh Ganguly";25 System.out.println(this.name);26 return "My name is " + name;27 }2829 30 public int getAge() {31 this.age += 1;32 return this.age;33 }34 };3536 System.out.println(test.getName());37 System.out.println(test.getAge());38 }39}xxxxxxxxxx131public void experiment(TimeTraveler timeTraveler) {2 /* invoke the time-machine and print how much time has passed using a callback and 3 * adjust the time traveler's ability to travel */4 TimeTravelCallback timeTravelCallback = new TimeTravelCallback() {5 6 public void leaped(Time unit, int amount, boolean ahead) {7 timeTraveler.adjust(unit,amount,ahead);8 if (timeTraveler.getRemainingYearsOfTravel() > 0) {9 timeMachine.travel(timeTraveler,this);10 }11 }12 };13}Notice the new of an interface. This syntax means an anonymous class is created of type TimeTravelCallback.
This anonymous class is override the interface TimeTravelCallback and that means all of the methods of that interfsce has to be defined within the body of the anonymous class.
The above block of code, creates the anonumous class, loads its method but none of the methods are invoked yet. To invoke, one has to execute the following code.
xxxxxxxxxx11timeTravelCallback.leaped(DAYS,100,true);The reference to the interface is called a callback. TimeTravelCallback is an interface and timeTravelCallback is a callback.
Just as an instance of a class is a reference to the instance variables/getter & setter/methods of a class, in the case of a callback, the callback is a reference to the methods of the interface.
xxxxxxxxxx81/** Obverver Design Pattern */23package callback;45/** STEP-I1 */6interface IEvent {7 void onSomeEvent();8}xxxxxxxxxx151package callback;23/** STEP-S1 - Subject to implement the interface */4class Subject implements IEvent {56 public Subject() {7 System.out.println("Subject Created");8 }910 /** STEP-S2 */11 12 public void onSomeEvent() {13 System.out.println("Subject performing callback after synchronous Task");14 }15}xxxxxxxxxx251package callback;23public class Main {45 // Driver Function6 public static void main(String[] args) {7 /** STEP-D1 - Create subject, 8 NOTE: Instance type is set to Interface as Subject implements interface */9 IEvent callback = new Subject();1011 /** STEP-D2 - Create observer */12 Observer observer = new Observer();1314 /** STEP-D3 - using the observer's register method, 15 set the listener (subject) field */16 observer.registerEventListener(callback);1718 /** STEP-D4 - Using the listener (subject) reference, 19 invoke the method in the subject instance */20 observer.doWorkSync();21 observer.doWorkAsync();2223 System.out.println("Completed");24 }25}xxxxxxxxxx551package callback;23/** STEP-Obs-1 - Create Observer */4class Observer {5 /** STEP-Obs-1 */6 private IEvent callback;78 // Constructor9 public Observer() {10 System.out.println("Observer Created");11 }1213 /** STEP-Obs-1b */14 public void registerEventListener(IEvent iEvent) {15 this.callback = iEvent;16 }1718 /** Step-2-Obs-sync19 * Do the work SYNCHRONOUSLY once the event happens */20 public void doWorkSync() {21 System.out.println("Performing callback before synchronous Task");2223 if (this.callback != null) {24 /** invoke the callback method of Subject */25 callback.onSomeEvent();26 }27 }2829 /** Step-2-Async30 * Do the work ASYNCHRONOUSLY once the event happens */31 public void doWorkAsync() {32 // An Async task always executes in new thread33 new Thread(new Runnable() {34 public void run() {35 System.out.println("Performing operation in Asynchronous Task");3637 try {38 Thread.sleep(2000);39 } catch (InterruptedException e) {40 e.printStackTrace();41 }4243 // check if listener is registered.44 if (callback != null) {45 /** Invoke the callback method of Subject */46 callback.onSomeEvent();47 }48 }49 }).start();50 }5152 public void invoke(IEvent listener) {53 listener.onSomeEvent();54 }55}
xxxxxxxxxx391// https://www.geeksforgeeks.org/nested-classes-java/2// https://www.geeksforgeeks.org/anonymous-inner-class-java/34package classnested;56class OuterClass {7 static int outer_x = 10; // static8 private static int outer_private = 30; // private & static910 int outer_y = 20; // non-static1112 static class StaticNestedClass { // static nested class, note the "static"13 void display() {14 // can access static member of outer class15 System.out.println("outer_x = " + outer_x);1617 // can access display private static member of outer class18 System.out.println("outer_private = " + outer_private);1920 // Compilation error, static nested class cannot 21 // directly access non-static membera22 // System.out.println("outer_y = " + outer_y);23 }24 }2526 class InnerClass {27 void display() {28 // can access static member of outer class29 System.out.println("outer_x = " + outer_x);3031 // can also access non-static member of outer class32 System.out.println("outer_y = " + outer_y);3334 // can also access private member of outer class35 System.out.println("outer_private = " + outer_private);36 }37 }38 39}If you need to access the instance variables of the outer class from the inner class, access them with instance.variable. This will ensure that if the instance is not available, the GC will clear out the reference to the variable. See faucet.java
xxxxxxxxxx161public enum OlympicMedal {23 GOLD(1),4 SILVER(2),5 BRONZE(3);67 private int medal;89 OlympicMedal(int medal) {10 this.medal = medal;11 }1213 public int getMedal() {14 return medal;15 }16}xxxxxxxxxx81public class Main {23 public static void main(String[] args) {4 System.out.println(OlympicMedal.GOLD);5 System.out.printf("%d %s\n",OlympicMedal.GOLD.getMedal());6 }7}8xxxxxxxxxx11OlympicMedal{medal=1, country='India'}x
1package com.olympic.iceskater;23public class SpeedSkater extends IceSkater {45 private enum OlympicGame {6 USA("USA","Lake Placid"), // singleton instance7 France("France","Chamonix");89 public String hostCountry;10 public String city;1112 OlympicGame(String hostCountry, String city) {13 this.hostCountry = hostCountry;14 this.city = city;15 }1617 public String getHostCountry() {18 return hostCountry;19 }2021 public String getCity() {22 return city;23 }2425 26 public String toString() {27 return "OlympicGame{" +28 "hostCountry='" + hostCountry + '\'' +29 ", city='" + city + '\'' +30 '}';31 }3233 public static void printHostCountry(OlympicGame ... olympicGames) {34 for (OlympicGame arg : olympicGames) {35 System.out.printf("%s, %s\n",arg.hostCountry, arg.city);36 }37 }38 }3940 public SpeedSkater(String name, int age) {41 super(name, age);42 }4344 public static void main(String[] args) {45 SpeedSkater speedSkater = new SpeedSkater("Josh",25);46 OlympicGame.printHostCountry(OlympicGame.USA, OlympicGame.France);4748 }49}
xxxxxxxxxx61int a[] = new int[];2int b[] = new int[]{5,6,7,8}; 3 4for (int i=0; i<3; i = i+2) { //Step 1: Establish relationship b/w a & b5 a[i] = b[i+2]; //Step 2: Ensure space for a is available & b exists6} //Step 3: Check boundary conditionsxxxxxxxxxx51public void printHostCountry(OlympicGame ... olympicGames) {2 for (OlympicGame game : olympicGames) {3 System.out.println(game.hostCountry);4 }5}xxxxxxxxxx61ArrayList<Type> myType = new ArrayList<Type>(Type);2Iterator<Type> iter = myType.iterator();3while (iter.hasNext()) {4 Test myType = iter.next();5 System.out.println();6}xxxxxxxxxx61StringBuilder sb = new StringBuilder();2sb.append("Hello ");3sb.append("how ");4sb.append("are ");5sb.append("you ");6System.out.printf("%s\n",sb.toString());xxxxxxxxxx41StringBuilder sb1 = new StringBuilder("Josh");2StringBuilder sb2 = new StringBuilder("Josh2");3int value = sb1.toString().compareTo(sb2.toString());4System.out.println(value);xxxxxxxxxx11System.out.printf("%c",sb1.charAt(3));xxxxxxxxxx541package tmp;23import java.util.Objects;45public class Rect {6 double a;7 double b;8 String name;910 public Rect(String name, double a, double b) {11 this.a = a;12 this.b = b;13 this.name = name;14 }1516 public double area() {17 return a*b;18 }1920 21 public boolean equals(Object o) {22 if (this == o) return true;23 24 if (o == null || getClass() != o.getClass()) {25 return false;26 }27 28 Rect rect = (Rect) o;29 return Double.compare(rect.a, a) == 0 &&30 Double.compare(rect.b, b) == 0 &&31 Objects.equals(name, rect.name);32 33 Rect that = (Rect) o;34 return ((a == that.a) &&35 (b == that.b) &&36 (name))3738 (getName().compareTo(that.getName())==0) &&39// (getName() == that.getName()) &&40 (getAge() == that.getAge()));41 }4243 44 public int hashCode() {45 46 Double dbA = new Double(this.a);47 Double dbB = new Double(this.b);48 49 int hash = Integer.valueOf(this.name) + 31*dbA.hashCode() + 31*dbB.hashCode();50 return hash;51// return Objects.hash(a, b, name);52 }53}54try block will execute a sensitive code which can throw exceptionscatch block will be used whenever an exception (of the type caught) is thrown in the try blockfinally block is called in every case after the try/catch blocks. Even if the exception isn't caught or if your previous blocks break the execution flow.throw keyword will allow you to throw an exception (which will break the execution flow and can be caught in a catch block).throws keyword in the method prototype is used to specify that your method might throw exceptions of the specified type. It's useful when you have checked exception (exception that you have to handle) that you don't want to catch in your current method.xxxxxxxxxx171public class ExcepTest {23 public static void main(String args[]) {4 int a[] = new int[2];5 try {6 System.out.println("Access element three :" + a[3]);7 } 8 catch (ArrayIndexOutOfBoundsException e) {9 System.out.println("Exception thrown :" + e);10 }11 finally {12 a[0] = 6;13 System.out.println("First element value: " + a[0]);14 System.out.println("The finally statement is executed");15 }16 }17}Java Exceptions - Geek for Geeks Java Exceptions - Stack Java Exceptions - Edureka Java Exceptions - Tutorial Point Code Java Exceptions - Jenkov
I have some examples in my javafun repo on threads, callback, future, etc.
Jenkov Tutorial See files 1 to 6 first
Review my example code
[Search Youtube "java thread Defog Tech"
Advanced Concepts](https://howtodoinjava.com/java/multi-threading/concurrency-vs-parallelism/) Use this as a rererence
Jenkov Tutorial See files 8 to rest more as a reference
xxxxxxxxxx161(RetentionPolicy.RUNTIME) // Duration2(ElementType.METHOD) // Target, implicitly understood3public @interface Safe { // Definition4 static final long INVALID = 0L;56 /**7 * @return the deposit-safe's password8 */9 long password() default INVALID;10}1112// Usage13(password=2997257199L)14private boolean getTools() {15 return safetyDepositBox.canGetTools(this);16}Regular Expressions - javatpoint
xxxxxxxxxx81# run the following from command line to find the location of $JAVA_HOME2/usr/libexec/java_home 34export JAVA_HOME=jdk-install-dir5export PATH=$JAVA_HOME/bin:$PATH67# set it in ~/.bash_profile8PATH="/Library/Java/JavaVirtualMachines/adoptopenjdk-12.jdk/Contents/Home:${PATH}"xxxxxxxxxx11123# TODO - ensure `target/classes` exists (creating it if it doesn't)4# TODO - compile all the Java files within the project and output them into `target/classes`56rm -rf target/classes7mkdir -p target/classes8find . -name "*.java" > sources.txt9javac @sources.txt -d target/classes1011# rm sources.txtWe could also do:
x
1# In IntelliJ IDE the source code is in "java" folder 2# If the project is java_tmp then the source code is at java_tmp/src/main/java3# You need to be inside java folder in the terminal as the packages start from here45# You don't need to worry about sourcepath. 6# javac the main class with fully qualified path name as per the package,7# javac will automatically compile the dependendent files8# classpath as per package destination folder for classes9javac -cp classes buildandrun/Main.java -d classes 1011# add libraries : separated12javac -d classes -cp classes:lib/some.jar path/file.java \13path/file1.java \14path/file2.java \15path/file3.java \16path/file4.java1718javac -d classes -cp classes:lib/some.jar path/file.java1920# Add -sourcepath and -cp21javac -sourcepath . -cp testClasses path/file.java -d testClassesx
12# You need to be inside java folder in the terminal as the packages start from here34# classpath package.classname arguments(if any)5java -cp classes buildandrun.Main6# add libraries : separated package.classname7java -cp classes:lib/some.jar fully.qualified.path.Classnamex
1# c for create, f for telling that output needs to go to file2jar cf jar-file input-class-file(s)34# Example - 5jar cf test.jar *.class
xxxxxxxxxx21# ./ means current directory and sub-directories below2find ./ -name "*filename*"xxxxxxxxxx71cd /Applications/VisualVM.app 2find . -name "*conf*"3cd ./Contents/Resources/visualvm/etc/4vc visualvm.conf56# In the above file7visualvm_jdkhome="/Library/Java/JavaVirtualMachines/adoptopenjdk-12.jdk/Contents/Home"