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 Variables
2
3// Constructors
4
5// Getters & Setters
6
7// Methods
8
9// Inner Classes
Access 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!.
xxxxxxxxxx
11public int methodName (Type1 param1, Type2 param2, Type3 param3, ...)
Methods can be called only through the reference to the instance of the object.
xxxxxxxxxx
81A a = new A();
2a.method(argument);
3
4B b - new B(a);
5C c = b.method2();
6
7c.method3(somevariable);
8...
xxxxxxxxxx
21Bike bike; // type variable
2int x; // type variable
xxxxxxxxxx
11Bike (int hp, String color); // type variable
this
is used for chaining, super
is used for super's constructor**
xxxxxxxxxx
11Bike getBike();
Accesspermission returntype name(type parameter);
xxxxxxxxxx
61boolean enjoy(int hp) {
2 if (hp > 100)
3 return true;
4 else
5 return false;
6}
xxxxxxxxxx
21Bike bike = new Bike(100, "red"); // matching constructor
2Bike bike = new Bike(100, "red", 100000);
xxxxxxxxxx
31String color = bike.getColor();
2float cost = bike.getCost();
3boolean result = bike.enjoy();
xxxxxxxxxx
121Bike[] bike;
2ArrayList<Bike> alBike;
3
4Bike[] bike = new Bike[5];
5ArrayList<Bike> alBike = new ArrayList();
6
7Iterator<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
xxxxxxxxxx
101interface 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:
xxxxxxxxxx
11int result = Itest.sub(10,3);
xxxxxxxxxx
61package tmp;
2
3public interface ITest {
4 String name = "Josh";
5 String getName();
6}
xxxxxxxxxx
51package tmp;
2
3public interface ITest2 {
4 int getAge();
5}
xxxxxxxxxx
171package tmp;
2
3public abstract class AbstractTest implements ITest {
4
5 public String name;
6 public int age;
7
8 public AbstractTest(String name, int age) {
9 this.name = name;
10 this.age = age;
11 }
12
13
14 public String getName() {
15 return this.name;
16 }
17}
xxxxxxxxxx
181package tmp;
2
3public class ConcreteTest extends AbstractTest implements ITest2 {
4
5 public ConcreteTest(String name, int age) {
6 super(name, age);
7 }
8
9
10 public String getName() {
11 return "CC: " + this.name;
12 }
13
14
15 public int getAge() {
16 return this.age;
17 }
18}
xxxxxxxxxx
391package tmp;
2
3public class Main {
4
5 public static <Itest2> void main(String[] args) {
6
7 // **anonymous** class implementing interface - callback
8 ITest iTest = new ITest() {
9
10 public String getName() {
11 System.out.println(name);
12 return null;
13 }
14 };
15 iTest.getName();
16
17 ConcreteTest concreteTest = new ConcreteTest("Josh",25);
18 System.out.println(concreteTest.name);
19 System.out.println(concreteTest.age);
20
21 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 }
28
29
30 public int getAge() {
31 this.age += 1;
32 return this.age;
33 }
34 };
35
36 System.out.println(test.getName());
37 System.out.println(test.getAge());
38 }
39}
xxxxxxxxxx
131public 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.
xxxxxxxxxx
11timeTravelCallback.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.
xxxxxxxxxx
81/** Obverver Design Pattern */
2
3package callback;
4
5/** STEP-I1 */
6interface IEvent {
7 void onSomeEvent();
8}
xxxxxxxxxx
151package callback;
2
3/** STEP-S1 - Subject to implement the interface */
4class Subject implements IEvent {
5
6 public Subject() {
7 System.out.println("Subject Created");
8 }
9
10 /** STEP-S2 */
11
12 public void onSomeEvent() {
13 System.out.println("Subject performing callback after synchronous Task");
14 }
15}
xxxxxxxxxx
251package callback;
2
3public class Main {
4
5 // Driver Function
6 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();
10
11 /** STEP-D2 - Create observer */
12 Observer observer = new Observer();
13
14 /** STEP-D3 - using the observer's register method,
15 set the listener (subject) field */
16 observer.registerEventListener(callback);
17
18 /** STEP-D4 - Using the listener (subject) reference,
19 invoke the method in the subject instance */
20 observer.doWorkSync();
21 observer.doWorkAsync();
22
23 System.out.println("Completed");
24 }
25}
xxxxxxxxxx
551package callback;
2
3/** STEP-Obs-1 - Create Observer */
4class Observer {
5 /** STEP-Obs-1 */
6 private IEvent callback;
7
8 // Constructor
9 public Observer() {
10 System.out.println("Observer Created");
11 }
12
13 /** STEP-Obs-1b */
14 public void registerEventListener(IEvent iEvent) {
15 this.callback = iEvent;
16 }
17
18 /** Step-2-Obs-sync
19 * Do the work SYNCHRONOUSLY once the event happens */
20 public void doWorkSync() {
21 System.out.println("Performing callback before synchronous Task");
22
23 if (this.callback != null) {
24 /** invoke the callback method of Subject */
25 callback.onSomeEvent();
26 }
27 }
28
29 /** Step-2-Async
30 * Do the work ASYNCHRONOUSLY once the event happens */
31 public void doWorkAsync() {
32 // An Async task always executes in new thread
33 new Thread(new Runnable() {
34 public void run() {
35 System.out.println("Performing operation in Asynchronous Task");
36
37 try {
38 Thread.sleep(2000);
39 } catch (InterruptedException e) {
40 e.printStackTrace();
41 }
42
43 // check if listener is registered.
44 if (callback != null) {
45 /** Invoke the callback method of Subject */
46 callback.onSomeEvent();
47 }
48 }
49 }).start();
50 }
51
52 public void invoke(IEvent listener) {
53 listener.onSomeEvent();
54 }
55}
xxxxxxxxxx
391// https://www.geeksforgeeks.org/nested-classes-java/
2// https://www.geeksforgeeks.org/anonymous-inner-class-java/
3
4package classnested;
5
6class OuterClass {
7 static int outer_x = 10; // static
8 private static int outer_private = 30; // private & static
9
10 int outer_y = 20; // non-static
11
12 static class StaticNestedClass { // static nested class, note the "static"
13 void display() {
14 // can access static member of outer class
15 System.out.println("outer_x = " + outer_x);
16
17 // can access display private static member of outer class
18 System.out.println("outer_private = " + outer_private);
19
20 // Compilation error, static nested class cannot
21 // directly access non-static membera
22 // System.out.println("outer_y = " + outer_y);
23 }
24 }
25
26 class InnerClass {
27 void display() {
28 // can access static member of outer class
29 System.out.println("outer_x = " + outer_x);
30
31 // can also access non-static member of outer class
32 System.out.println("outer_y = " + outer_y);
33
34 // can also access private member of outer class
35 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
xxxxxxxxxx
161public enum OlympicMedal {
2
3 GOLD(1),
4 SILVER(2),
5 BRONZE(3);
6
7 private int medal;
8
9 OlympicMedal(int medal) {
10 this.medal = medal;
11 }
12
13 public int getMedal() {
14 return medal;
15 }
16}
xxxxxxxxxx
81public class Main {
2
3 public static void main(String[] args) {
4 System.out.println(OlympicMedal.GOLD);
5 System.out.printf("%d %s\n",OlympicMedal.GOLD.getMedal());
6 }
7}
8
xxxxxxxxxx
11OlympicMedal{medal=1, country='India'}
x
1package com.olympic.iceskater;
2
3public class SpeedSkater extends IceSkater {
4
5 private enum OlympicGame {
6 USA("USA","Lake Placid"), // singleton instance
7 France("France","Chamonix");
8
9 public String hostCountry;
10 public String city;
11
12 OlympicGame(String hostCountry, String city) {
13 this.hostCountry = hostCountry;
14 this.city = city;
15 }
16
17 public String getHostCountry() {
18 return hostCountry;
19 }
20
21 public String getCity() {
22 return city;
23 }
24
25
26 public String toString() {
27 return "OlympicGame{" +
28 "hostCountry='" + hostCountry + '\'' +
29 ", city='" + city + '\'' +
30 '}';
31 }
32
33 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 }
39
40 public SpeedSkater(String name, int age) {
41 super(name, age);
42 }
43
44 public static void main(String[] args) {
45 SpeedSkater speedSkater = new SpeedSkater("Josh",25);
46 OlympicGame.printHostCountry(OlympicGame.USA, OlympicGame.France);
47
48 }
49}
xxxxxxxxxx
61int 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 & b
5 a[i] = b[i+2]; //Step 2: Ensure space for a is available & b exists
6} //Step 3: Check boundary conditions
xxxxxxxxxx
51public void printHostCountry(OlympicGame ... olympicGames) {
2 for (OlympicGame game : olympicGames) {
3 System.out.println(game.hostCountry);
4 }
5}
xxxxxxxxxx
61ArrayList<Type> myType = new ArrayList<Type>(Type);
2Iterator<Type> iter = myType.iterator();
3while (iter.hasNext()) {
4 Test myType = iter.next();
5 System.out.println();
6}
xxxxxxxxxx
61StringBuilder sb = new StringBuilder();
2sb.append("Hello ");
3sb.append("how ");
4sb.append("are ");
5sb.append("you ");
6System.out.printf("%s\n",sb.toString());
xxxxxxxxxx
41StringBuilder sb1 = new StringBuilder("Josh");
2StringBuilder sb2 = new StringBuilder("Josh2");
3int value = sb1.toString().compareTo(sb2.toString());
4System.out.println(value);
xxxxxxxxxx
11System.out.printf("%c",sb1.charAt(3));
xxxxxxxxxx
541package tmp;
2
3import java.util.Objects;
4
5public class Rect {
6 double a;
7 double b;
8 String name;
9
10 public Rect(String name, double a, double b) {
11 this.a = a;
12 this.b = b;
13 this.name = name;
14 }
15
16 public double area() {
17 return a*b;
18 }
19
20
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))
37
38 (getName().compareTo(that.getName())==0) &&
39// (getName() == that.getName()) &&
40 (getAge() == that.getAge()));
41 }
42
43
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}
54
try
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.xxxxxxxxxx
171public class ExcepTest {
2
3 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
xxxxxxxxxx
161RetentionPolicy.RUNTIME) // Duration (
2ElementType.METHOD) // Target, implicitly understood (
3public @interface Safe { // Definition
4 static final long INVALID = 0L;
5
6 /**
7 * @return the deposit-safe's password
8 */
9 long password() default INVALID;
10}
11
12// Usage
13password=2997257199L) (
14private boolean getTools() {
15 return safetyDepositBox.canGetTools(this);
16}
Regular Expressions - javatpoint
xxxxxxxxxx
81# run the following from command line to find the location of $JAVA_HOME
2/usr/libexec/java_home
3
4export JAVA_HOME=jdk-install-dir
5export PATH=$JAVA_HOME/bin:$PATH
6
7# set it in ~/.bash_profile
8PATH="/Library/Java/JavaVirtualMachines/adoptopenjdk-12.jdk/Contents/Home:${PATH}"
xxxxxxxxxx
111
2
3# 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`
5
6rm -rf target/classes
7mkdir -p target/classes
8find . -name "*.java" > sources.txt
9javac @sources.txt -d target/classes
10
11# rm sources.txt
We 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/java
3# You need to be inside java folder in the terminal as the packages start from here
4
5# 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 files
8# classpath as per package destination folder for classes
9javac -cp classes buildandrun/Main.java -d classes
10
11# add libraries : separated
12javac -d classes -cp classes:lib/some.jar path/file.java \
13path/file1.java \
14path/file2.java \
15path/file3.java \
16path/file4.java
17
18javac -d classes -cp classes:lib/some.jar path/file.java
19
20# Add -sourcepath and -cp
21javac -sourcepath . -cp testClasses path/file.java -d testClasses
x
1
2# You need to be inside java folder in the terminal as the packages start from here
3
4# classpath package.classname arguments(if any)
5java -cp classes buildandrun.Main
6# add libraries : separated package.classname
7java -cp classes:lib/some.jar fully.qualified.path.Classname
x
1# c for create, f for telling that output needs to go to file
2jar cf jar-file input-class-file(s)
3
4# Example -
5jar cf test.jar *.class
xxxxxxxxxx
21# ./ means current directory and sub-directories below
2find ./ -name "*filename*"
xxxxxxxxxx
71cd /Applications/VisualVM.app
2find . -name "*conf*"
3cd ./Contents/Resources/visualvm/etc/
4vc visualvm.conf
5
6# In the above file
7visualvm_jdkhome="/Library/Java/JavaVirtualMachines/adoptopenjdk-12.jdk/Contents/Home"