1. Variables hold the state of the program and methods operate on that state.
  2. Program entry point
    • You can use any valid variable name format in the main method. for example String[] args, String args[], String… args
    • public final static void main(final String[] args) {},
    • Both the final keywords are optional and even if you don’t write them it is still a valid entry point.
  3. Launching single-file source code program
    • Useful for testing for small programs
    • This option is when your program is just one file
    • So standard way is
      javac Zoo.java
      java Zoo
    • Easy one line way is
      java Zoo.java one two,
    • where one two are command line arguments
  4. Imports
    • java.util.Random
      Random r = new Random()
      r.nextInt(10) // gives a random number between 0 to 9
    • So AtomicInteger is in the package java.util.concurrent.atomic
      import java.util.; this will not import AtomicInteger
    • import java.util.concurrent.; this will not import AtomicInteger
      import java.util.concurrent.atomic.; this will import AtomicInteger import java.util.concurrent.atomic.AtomicInteger; this will import AtomicInteger
    • java.lang package is special and automatically imported, you don’t have to explicitly import it. For example System.out.println works without import java.lang.System;
    • Invalid Imports
    • import java.nio.*.* only one wild card at the end is allowed
    • import java.nio.files.Path.*; you cannot import method from class
    • if the classes are in the same package, then they don’t need import of each other at all
    • Importing by class name takes precedence over wildcards,
      import a.MainClass
      import b.*
    • This is fine even if MainClass is defined in both packages. MainClass in package “a” will be used and no compiler error is present.
  5. javac command
    • javac packagea/ClassA.java packageb/ClassB.java
    • javac packagea/.java packageb/.java
    • java packageb.ClassB
    • By default, the javac command places the compiled classes in the same directory as the source code. It also provides an option to place the class files into a different directory. The -d option specifies this target directory. Java options are case sensitive. This means you cannot pass -D instead of -d.
    • javac -d classes packagea/ClassA.java packageb/ClassB.java The package structure is preserved under the requested target directory.
    • javac also needs to know the location of the classes that are needed to compile
    • javac -cp
      javac -classpath
      javac –class-path
      java -cp “C:\temp\directoryWithJars\*” myPackage.MyClass.
    • you can use a wildcard (*) to match all the JARs in a directory. This command will add to the classpath all the JARs that are in directoryWithJars. It won’t include any JARs in the classpath that are in a subdirectory of directoryWithJars.
  6. java command
    • To run the program, you specify the classpath so Java knows where to find the classes
    • java -cp classes packageb.ClassB
    • java -classpath classes packageb.ClassB
    • java –class-path classes packageb.ClassB
    • If you have the wrong number of dashes, the program will not run.
    • For windows –> java -cp “.;C:\temp\someOtherLocation;c:\temp\myJar.jar” myPackage.MyClass (saying look for classes needed to run in current directory or in jar.
    • For mac –> java -cp “.:/tmp/someOtherLocation:/tmp/myJar.jar” myPackage.MyClass(saying look for classes needed to run in current directory or in jar.
    • The period (.) indicates that you want to include the current directory in the classpath. The rest of the command says to look for loose class files (or packages) in someOtherLocation and within myJar.jar. Windows uses semicolons (;) to separate parts of the classpath; other operating systems use colons (:).
  7. jar command
    • jar -cvf test.jar . (. current directory containing files to be used to create the JAR)
    • jar –create –verbose –file test.jar . (. current directory containing files to be used to create the JAR)
    • jar -cvf test.jar -C dir . (using -C you can specify directory containing files to be used to create the JAR)
    • there is no long form for -C
  8. Looks weird but is fine. Compiles and runs
    1: public class Name {
    2: String first = "test1";
    3: String last = "test2";
    4: String full = first + last;
    5: }
  9. Order of the initialization
    • Fields and instance initializer blocks are run in the order in which they appear in the file. The constructor runs after all fields and instance initializer blocks have run
    • { System.out.println(name); } // DOES NOT COMPILE
      private String name = "test";
  10. A float requires the letter f or F following the number so Java knows it is a float. Without an f or F, Java interprets a decimal value as a double.
    • This does not compile, float y = 2.1; Java interprets 2.1 as a double and says can’t fit in float. You have to explicitly say that 2.1f or 2.1F
  11. A long requires the letter l or L following the number so Java knows it is a long. Without an l or L, Java interprets a number without a decimal point as an int in most scenarios.
    • By default, Java assumes you are defining an int value with a numeric literal
    • long max = 3123456799; // DOES NOT COMPILE, Java interprets the literal as an int and notices that the value is larger than int allows.
    • long max = (long)3123456799; // DOES NOT COMPILE, because the value is first interpreted as an int by the compiler and is out of range
    • long max = 3123456789L; // Now Java knows it is a long
  12. Octal (digits 0–7), which uses the number 0 as a prefix—for example, 017.
  13. Hexadecimal (digits 0–9 and letters A–F/a–f), which uses 0x or 0X as a prefix—for example, 0xFF, 0xff, 0XFf. Hexadecimal is case insensitive, so all of these examples mean the same value.
  14. Binary (digits 0–1), which uses the number 0 followed by b or B as a prefix—for example, 0b10, 0B10.
  15. You can add underscores anywhere except at the beginning of a literal, the end of a literal, right before a decimal point, or right after a decimal point. You can even place multiple underscore characters next to each other.
    • double notAtStart = _1000.00; // DOES NOT COMPILE
    • double notAtEnd = 1000.00_ // DOES NOT COMPILE
    • double beforeDecimal= 1000_.00; // DOES NOT COMPILE
    • double afterDecimal= 1000._00; // DOES NOT COMPILE
    • double annoyingButLegal = 1_00_0.0_0; // Ugly, but compiles
    • double reallyUgly = 1__________2; // Also compiles
  16. Wrappers
    • All are valid
      int primitive = Integer.parseInt("123");
      Integer wrapper = Integer.valueOf("123");
      Integer wrapper = Integer.valueOf(123);
    • All of the numeric wrapper classes extend the Number class, which means they all come with some useful helper methods: byteValue(), shortValue(), intValue(), longValue(), floatValue(), and doubleValue(). The Boolean and Character wrapper classes include booleanValue() and charValue(), respectively.
    • Double apple = Double.valueOf("200.99");
      System.out.println(apple.byteValue()); // -56
      System.out.println(apple.intValue()); // 200
      System.out.println(apple.doubleValue()); // 200.99
  17. Text Blocks (also known as multi line strings)
    • Essential whitespace is part of your String and is important to you.
    • Incidental whitespace just happens to be there to make the code easier to read. You can reformat your code and change the amount of incidental whitespace without any impact on your String value.
    • Imagine a vertical line drawn on the leftmost non-whitespace character in your text block. Everything to the left of it is incidental whitespace, and everything to the right is essential whitespace
      14: String pyramid = """
      15: *
      16: * *
      17: * * *
      18: """;
    • There are 4 lines printed in above example, as the closing “”” is on the next line. if we wanted only 3 lines “”” should be on the line 17. The closing “”” on line 18 are the leftmost characters, so the line is drawn at the leftmost position. Line 15 has two essential whitespace characters to begin the line, and line 16 has one. There are no incidental whitespaces in above example.
    • String block = “””doe”””; // DOES NOT COMPILE
    • Text blocks require a line break after the opening “””
  18. Variable names
    • You cannot create a variable named 3dMap or this
    • Identifiers must begin with a letter, a currency symbol, or a _ symbol. Currency symbols include dollar ($), yuan (¥), euro (€), and so on.
    • Identifiers can include numbers but not start with them.
    • A single underscore _ is not allowed as an identifier.
    • You cannot use the same name as a Java reserved word. A reserved word is a special word that Java has held aside so that you are not allowed to use it.
    • Remember that Java is case sensitive, so you can use versions of the keywords that only differ in case.
    • There are other names that you can’t use. For example, true, false, and null are literal values, so they can’t be variable names
    • var is not a reserved word, so can be used as identifier
      This code compiles and is valid
      package var;
    • public class Var {
    • public void var() {
    • var var = “var”;
    • }
    • public void Var() {
    • Var var = new Var();
    • }
    • }
  19. int i1, i2, i3 = 0; // only i3 is initialized to 0. i1 and i2 are not initialized, if you try to use them later in code you will get compile error saying not initialized.
  20. int num, String value; // DOES NOT COMPILE
  21. double d1, double d2; // DOES NOT COMPILE
  22. int a, var b = 3; // DOES NOT COMPILE
  23. var n = null; // DOES NOT COMPILE
  24. double d1; double d2; // COMPILE
  25. Be on the lookout for var used with constructors, method parameters, or instance variables, that is not allowed. Remember that var is only used for local variable type inference!
  26. you can request JVM for garbage collection using System.gc(), but it is not guaranted that JVM will consider your request.
  27. Usually, you check if the object is left dangling in the heap memory without any reference to it and then you termed it as eligible for GC, which is correct.
  28. This one is interesting. An object can still have a reference pointed to it, but still can be eligible for GC. Because that reference itself is not accessible anymore. An object is eligible for garbage collection once no references to it are accessible in the program. Check this example

2: public class Bear {
3: private Bear pandaBear;
4: private void roar(Bear b) {
5: System.out.println("Roar!");
6: pandaBear = b;
7: }
8: public static void main(String[] args) {
9: Bear brownBear = new Bear();
10: Bear polarBear = new Bear();
11: brownBear.roar(polarBear);
12: polarBear = null;
13: brownBear = null;
14: System.gc(); } }

18.
–> The reference is a variable that has a name and can be used to access the contents of an object.
–> A reference can be assigned to another reference, passed to a method, or returned from a method.
–> All references are the same size, no matter what their type is.
–> An object sits on the heap and does not have a name.
–> Therefore, you have no way to access an object except through a reference.
–> Objects come in all different shapes and sizes and consume varying amounts of memory.
–> An object cannot be assigned to another object, and an object cannot be passed to a method or returned from a method. It is the object that gets garbage collected, not its reference.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.