Java - Fundamentals

java

How can we change the temporary directory that Java use?

Try using the -Djava.io.tmpdir= option to select an alternate temp location.

How can we define a skeleton program?

class HelloWorld {
    public static void main(String [] args) {
        System.out.println("...");
    }
}

How can we define a class?

class ClassName {
}

How can we define a class that inherits from another class?

public class DerivedClassName extends BaseClassName {
}

How can we create an instance of a class?

ClassName c = new ClassName();

How can we invoke the constructor of a super class?

Inside our constructor, if we need to invoke the constructor of the super class, we can:

super(parameters)

super() must be the first statement executed inside a sub-class constructor.

How can we write, compile, and run a Java-based program?

We can use a text editor to create a .java file, or use an Integrated Development Environment such as Eclipse. Skeleton for Java program:

class ClassName {
    public static void main(String[] args) {
        System.out.println("Hello World!");
    }
}
"C:\Program Files\Java\jdk1.7.0_04\bin\javac"  SVNTool.java 
    -cp ".;C:\parsers\commons-lang-2.4.jar;C:\parsers\svnkit-1.7.4-v1\lib\svnkit-cli-1.7.4-v1.jar;C:\parsers\svnkit-1.7.4-v1\lib\svnkit-1.7.4-v1.jar"
javac SVNTool.java -classpath ".;C:\parsers\commons\commons-lang-2.4.jar"
java -cp ".;c:\parsers\log4j\log4j-1.2.14.jar" ExperimentLog4J

How can we run a Java program?

java -cp target/MavenTestApp-1.0-SNAPSHOT.jar org.koushik.javabrains.App

How can we create an instance of a class given the name of the class as a string?

Class c = null;
c = Class.forName(strServName);
ServletInterface pdhObj = (ServletInterface) c.newInstance();
pdhObj.processData(req, res, servctxt);

In the above code, we create an instance of the class and then invoke the processData method from that instance.

How can we determine if you have 64-bit Java or 32-bit Java?

java -version

Look closely at the output of the above command. It should indicate whether you have 32-bit Java or 64-bit Java. Another way:

java -d32

If the above command give you an error, then you have 64-bit Java.

What is an interface?

In its most common form, an interface is a group of related methods with empty bodies.

interface Bicycle {
    //  wheel revolutions per minute
    void changeCadence(int newValue);
}

Note that in the above code, we do not provide the concrete implementation for each method.

How can we implement the interface for an object?

To implement this interface, we use the 'implements' keyword in the class definition:

class ACMEBicycle implements Bicycle {
   // The compiler will now require that methods
   // changeCadence, changeGear, speedUp, and applyBrakes
   // all be implemented. Compilation will fail if those
   // methods are missing from this class.

    void changeCadence(int newValue) {
        ...
    }
}

Why should we use interface?

Implementing an interface allows a class to become more formal about the behavior it promises to provide. Interfaces form a contract between the class and the outside world, and this contract is enforced at build time by the compiler. If your class claims to implement an interface, all methods defined by that interface must appear in its source code before the class will successfully compile.

What is the definition of Instance Variables (Non-Static Fields)?

Technically speaking, objects store their individual states in "non-static fields", that is, fields declared without the static keyword. Non-static fields are also known as instance variables because their values are unique to each instance of a class (to each object, in other words); the currentSpeed of one bicycle is independent from the currentSpeed of another.

What is the definition of Class Variables (Static Fields)?

A class variable is any field declared with the static modifier; this tells the compiler that there is exactly one copy of this variable in existence, regardless of how many times the class has been instantiated. A field defining the number of gears for a particular kind of bicycle could be marked as static since conceptually the same number of gears will apply to all instances. The code static int numGears = 6; would create such a static field. Additionally, the keyword final could be added to indicate that the number of gears will never change.

What is the definition of Local Variables?

Similar to how an object stores its state in fields, a method will often store its temporary state in local variables. The syntax for declaring a local variable is similar to declaring a field (for example, int count = 0;). There is no special keyword designating a variable as local; that determination comes entirely from the location in which the variable is declared — which is between the opening and closing braces of a method. As such, local variables are only visible to the methods in which they are declared; they are not accessible from the rest of the class.

What is the definition of Parameters?

You've already seen examples of parameters, both in the Bicycle class and in the main method of the "Hello World!" application. Recall that the signature for the main method is public static void main(String[] args). Here, the args variable is the parameter to this method. The important thing to remember is that parameters are always classified as "variables" not "fields". This applies to other parameter-accepting constructs as well (such as constructors and exception handlers) that you'll learn about later in the tutorial.

What are the rules for naming?

  1. Variable names are case-sensitive. A variable's name can be any legal identifier — an unlimited-length sequence of Unicode letters and digits, beginning with a letter, the dollar sign "$", or the underscore character "_". The convention, however, is to always begin your variable names with a letter, not "$" or "_". Additionally, the dollar sign character, by convention, is never used at all. You may find some situations where auto-generated names will contain the dollar sign, but your variable names should always avoid using it. A similar convention exists for the underscore character; while it's technically legal to begin your variable's name with "_", this practice is discouraged. White space is not permitted.
  2. Subsequent characters may be letters, digits, dollar signs, or underscore characters. Conventions (and common sense) apply to this rule as well. When choosing a name for your variables, use full words instead of cryptic abbreviations. Doing so will make your code easier to read and understand. In many cases it will also make your code self-documenting; fields named cadence, speed, and gear, for example, are much more intuitive than abbreviated versions, such as s, c, and g. Also keep in mind that the name you choose must not be a keyword or reserved word.
  3. If the name you choose consists of only one word, spell that word in all lowercase letters. If it consists of more than one word, capitalize the first letter of each subsequent word. The names gearRatio and currentGear are prime examples of this convention. If your variable stores a constant value, such as static final int NUM_GEARS = 6, the convention changes slightly, capitalizing every letter and separating subsequent words with the underscore character. By convention, the underscore character is never used elsewhere.

What is the definition of immutable?

It means that it cannot be changed once created. String objects are immutable, which means that once created, their values cannot be changed.

What is the definition of 'class literal'?

There's also a special kind of literal called a class literal, formed by taking a type name and appending ".class"; for example, String.class. This refers to the object (of type Class) that represents the type itself.

What is the purpose of the instanceof operator?

The instanceof operator compares an object to a specified type. You can use it to test if an object is an instance of a class, an instance of a subclass, or an instance of a class that implements a particular interface.

class Parent {}
class Child extends Parent implements MyInterface {}
interface MyInterface {};

Parent obj1 = new Parent();
Parent obj2 = new Child();

System.out.println("obj1 instanceof Parent: " + (obj1 instanceof Parent));
System.out.println("obj1 instanceof Child: " + (obj1 instanceof Child));
System.out.println("obj1 instanceof MyInterface: " + (obj1 instanceof MyInterface));
System.out.println("obj2 instanceof Parent: " + (obj2 instanceof Parent));
System.out.println("obj2 instanceof Child: " + (obj2 instanceof Child));
System.out.println("obj2 instanceof MyInterface: " + (obj2 instanceof MyInterface));

When using the instanceof operator, keep in mind that null is not an instance of anything.

What are the characteristics of a constructor method?

  1. Constructor declarations look like method declarations—except that they use the name of the class and have no return type.
  2. You don't have to provide any constructors for your class, but you must be careful when doing this. The compiler automatically provides a no-argument, default constructor for any class without constructors. This default constructor will call the no-argument constructor of the superclass. In this situation, the compiler will complain if the superclass doesn't have a no-argument constructor so you must verify that it does. If your class has no explicit superclass, then it has an implicit superclass of Object, which does have a no-argument constructor.
  3. Constructors must have the same name as the class, and have no return type, not even void.

How can we create a method that takes a variable number of arguments?

You can use a construct called varargs to pass an arbitrary number of values to a method. You use varargs when you don't know how many of a particular type of argument will be passed to the method. It's a shortcut to creating an array manually (the previous method could have used varargs rather than an array).

To use varargs, you follow the type of the last parameter by an ellipsis (three dots, …), then a space, and the parameter name. The method can then be called with any number of that parameter, including none.

public Polygon polygonFrom(Point... corners) {
    int numberOfSides = corners.length;
    double squareOfSide1, lengthOfSide1;
    squareOfSide1 = (corners[1].x - corners[0].x)
                     * (corners[1].x - corners[0].x) 
                     + (corners[1].y - corners[0].y)
                     * (corners[1].y - corners[0].y);
    lengthOfSide1 = Math.sqrt(squareOfSide1);

    // more method body code follows that creates and returns a 
    // polygon connecting the Points
}

You can see that, inside the method, corners is treated like an array. The method can be called either with an array or with a sequence of arguments. The code in the method body will treat the parameter as an array in either case. You will most commonly see varargs with the printing methods; for example, this printf method:

public PrintStream printf(String format, Object... args)

What happens if we do not define our own constructor method?

All classes have at least one constructor. If a class does not explicitly declare any, the Java compiler automatically provides a no-argument constructor, called the default constructor. This default constructor calls the class parent's no-argument constructor, or the Object constructor if the class has no other parent. If the parent has no constructor (Object does have one), the compiler will reject the program.

What is explicit constructor invocation?

From within a constructor, you can also use the this keyword to call another constructor in the same class. Doing so is called an explicit constructor invocation. Here's another Rectangle class, with a different implementation:

public class Rectangle {
    private int x, y;
    private int width, height;

    public Rectangle() {
        this(0, 0, 1, 1);
    }
    public Rectangle(int width, int height) {
        this(0, 0, width, height);
    }
    public Rectangle(int x, int y, int width, int height) {
        this.x = x;
        this.y = y;
        this.width = width;
        this.height = height;
    }
    ...
}

If present, the invocation of another constructor must be the first line in the constructor.

What is the difference between a public class and a package-private class?

A class may be declared with the modifier public, in which case that class is visible to all classes everywhere. If a class has no modifier (the default, also known as package-private), it is visible only within its own package.

What is the meaning of package-private at member level?

At the member level, you can also use the public modifier or no modifier (package-private) just as with top-level classes, and with the same meaning. For members, there are two additional access modifiers: private and protected. The private modifier specifies that the member can only be accessed in its own class. The protected modifier specifies that the member can only be accessed within its own package (as with package-private) and, in addition, by a subclass of its class in another package.

If we do not specify an access modifier for a member variable, that member variable is package-private, which means that it is visible to other classes within the same package, but it is not visible to classes that are located in other packages. The protected modifier specifies that the member can only be accessed within its own package (as with package-private) and, in addition, by a subclass of its class in another package.

How can we declare and initialize multiple variables of the same type on the same line?

type identifier [=value][,identifier[=value]...];
int d=3, e, f=5;

What is the purpose of the finalize() method?

It is called before an object is destroyed. If we need to run some code when an object is destroyed, then we can implement / override this finalize method, but keep in mind that this finalize method is not invoked until our object is destroyed or garbage-collected. If our object never go out of scope, it is never garbage collected, and therefore this finalize method is never invoked.

What is the default access specifier for a member of a class?

When no access specifier is used, then by default, the member of a class is public within its own package, but cannot be accessed outside of its package.

What is the purpose of the final keyword?

Variables can be declared as final. Doing so prevent its content from being modified. This means we must initialize the variable when we declare it:

final int x = 1;

What is polymorphism?

Super class reference variable can refer to a sub-class object. When an overridden method is called through a super-class reference, Java determine which version of that method to execute based on the type of the object being referred to at the time the call occur.

Flow control:

if (...) {
} else if (...) {
} else {
}
while (...) {
}
do {} while (condition);
for (init; condition; increment) { }
break: equivalent of last
continue: equivalent of next
switch(age) {
  case 1:
    ...
    break;
  case 2:
    ...
    break;
  default:
    ...
    break
}
for (int counter = 1; counter < 10; counter++) {
}
do {
} while (...);

Operators:

addition: +
subtraction: -
multiplication: *
division: /
modulus: %
assignment: =
increment: ++
decrement: --
comparison: ==
negation: !
less than: <
greater than: >
logical and:  &&
logical or: ||
tuna += 5;  // is equivalent to tuna = tuna + 5;

What are the shift operators?

  1. «
  2. »
  3. »>

The signed left shift operator "«" shifts a bit pattern to the left, and the signed right shift operator "»" shifts a bit pattern to the right. The bit pattern is given by the left-hand operand, and the number of positions to shift by the right-hand operand. The unsigned right shift operator "»>" shifts a zero into the leftmost position, while the leftmost position after "»" depends on sign extension.

NEED TO FIND CONCRETE EXAMPLES.

What are the bitwise operators?

  1. bitwise AND: &
  2. bitwise exclusive OR: ^
  3. bitwise inclusive OR: |
  4. bitwise complement: ~

The unary bitwise complement operator "~" inverts a bit pattern; it can be applied to any of the integral types, making every "0" a "1" and every "1" a "0". For example, a byte contains 8 bits; applying this operator to a value whose bit pattern is "00000000" would change its pattern to "11111111".

The bitwise & operator performs a bitwise AND operation. The bitwise ^ operator performs a bitwise exclusive OR operation. The bitwise | operator performs a bitwise inclusive OR operation.

int bitmask = 0x000F;
int val = 0x2222;
// prints "2"
System.out.println(val & bitmask);

NEED TO FIND CONCRETE EXAMPLES.

What are the logical / conditional operators?

  1. &&: conditional AND
  2. ||: conditional OR
if ((value1 == 1) && (value2 == 2)) { ... }
if ((value1 == 1) || (value2 == 1)) { ... }

How can we use the ternary operator?

Another conditional operator is ?:, which can be thought of as shorthand for an if-then-else statement. This operator is also known as the ternary operator because it uses three operands. In the following example, this operator should be read as: "If someCondition is true, assign the value of value1 to result. Otherwise, assign the value of value2 to result."

int value1 = 1;
int value2 = 2;
int result;
boolean someCondition = true;
result = someCondition ? value1 : value2;

System.out.println(result);

Can we use the == operator to compare content?

No. The == operator compares objects, not content, therefore we can not use it to compare strings. In order for two objects to be equal, they must be the same (reside at the same address)

What is the purpose of the public access modifier?

public: When an instance variable is declared 'public', any code can access and modify this instance variable. When a method is declared 'public', any code can invoke this method.

What is the purpose of the private access modifier?

private: When an instance variable is declared 'private', only methods that are members of this class can access and modify the value of this instance variable. When a method is declared 'private', only other methods that are member of the same class can invoke this method. 'private' method can not be inherited.

What is the purpose of the protected access modifier?

protected: When an instance variable is declared 'protected', only methods that are members of this class or members of derived-class can access and modify the value of this instance variable. When a method is declared 'protected', only other methods that are members of the same class or members of derived-class can invoke this method.

What is a constructor?

A constructor is a method that has the same name as the class, and is used to initialize instance variables. There can be multiple constructors (each with the same name as the class, but takes a different argument list)

What is polymorphism?

An object of the super class can be assigned to a variable of the sub class.

public static void main(String[] args) {
  tuna bucky = new tuna();
  food bucky = new tuna();
  food bucky[] = new food[2];
  bucky[0] = new potpie();
  bucky[1] = new tuna();
  for (int x = 0; x < 2; x++) {
    bucky[x].eat();
  }
}

You can assign different objects to variables as long as the reference variable is of the super-class type. The super class can hold reference to the sub-class (objects of the sub-class can be assigned to variables that has type being the super-class).

What is a polymorphic array?

If we have an array of type super-class, that array can store reference to instances of sub-class.

What is a polymorphic argument?

Any method that can accept an argument of type super-class, can also accept sub-class. Anytime you can pass in an object of the super class, you can also pass in the object of the sub-class (If the function was defined with the super-class as an argument, you can pass that function an object of the derived-class, and when a method of that instance is invoked by the function, the method of the derived class is invoked.)

What is overriding vs overloading?

Overriding: When a sub-class define a method with the same name and signature as a method in the parent class. When we override a method, the new method must have the same signature, return type, and scope.

Overloading: When a class has multiple methods with the same name, but different signature.

What is an abstract class? What is an abstract method?

An abstract class is a class that is declared with the keyword 'abstract'. We cannot create an instance of this class, but we can use it for inheritance and polymorphism.

An abstract method is a method that must be overridden. To declare a method as abstract (notice that we do not define the body for the method):

public abstract void eat();

If a class contains an abstract method, the class must be declared abstract as well.

How can we make all instances of a class share the same variable?

Declare the instance variable with the keyword 'static'

How can we invoke a method without having to create an instance of that class?

Declare that method with the keyword 'static'. To invoke a static method, use the class name.

What does it means to declare a variable with the keyword final?

You can not modify it after we assign / initialize it.

How can we implement a function that takes an arbitrary number of arguments?

public static int average( int ... numbers) {
  int total = 0;
  for (int x: numbers) {
    total += x;
  }
  return total / numbers.length;
}

Can we use the same name for an instance variable and a parameter variable?

Yes, we can. Use the this keyword to prevent ambiguity.

How can we generate a random GUID?

Not answered yet. If you are using an older JDK that is not easy to generate a GUID, you can see if your database provides you with a function for generating a GUID.

How can we make random number:

import java.util.Random;
Random dice = new Random();
int number = dice.nextInt(6); // generate a random number between 0 and 5
int number = 1 + dice.nextInt(6); // generate a random number between 1 and 6

How can we determine the JDK version that was used to compile a class file?

javap -verbose MyClass
javap -verbose MyClass | find "version" (Windows)
javap -verbose MyClass | grep version (Linux)

See also:

How can we access environment variable?

String username = System.getenv("USERNAME")

How can we use appropriate line terminator?

String lineSeparator = System.getProperty("line.separator");

Do we have to pre-declare variable before it is used?

No. We do not have to pre-declare a variable before it is used. A variable can be declare on the same line when it is used:

String temp = keyboard.nextLine();

How can we make an executable JAR file?

See the ant page.

How can we work with properties files?

Properties properties = new Properties();
properties.load(new FileInputStream(new File(fileName)));
String server = properties.getProperty("PROPERTY_NAME");

Can we put constants inside an interface?

Yes. However we do not have to use 'public static final'

Can we define concrete implementation for a method inside an interface?

No. An interface can not contain a concrete implementation of a method. It can only contain the signature of the methods:

interface SampleInterface {
  int SAMPLE_CONSTANT = 5;
  public void methodName();
  public void methodName();
}

What are the differences between an abstract class and an interface?

Abstract classes are actually classes. A class can implement an interface. However, a class cannot implement an abstract class using the implements keyword. A class can inherit from an abstract class and provide concrete definition for abstract methods.

  1. Abstract class can contain instance and static variable.
  2. Abstract class can contain 0 or more abstract methods.
  3. Abstract method does not have a body
public abstract class AbstractClassExample {
  public int x;
  private int y;
  static int z;
  abstract void methodName1(String a);
  abstract in methodName2(String b, String c);
}

For interfaces, all variables are by default 'public static final'.

We can implement multiple interfaces, but we can only extend one abstract class.

Can we create an instance of an abstract class?

No.

How can we override a method?

The method in the sub-class must have the same name and parameter list as the method defined in the parent class.

What is the purpose of the final keyword?

The final keyword when applied to a method means that a subclass cannot override that method. When the final keyword is applied to a class, it means that we cannot extend that class. When applied to a data member, it means that we cannot change the value of that member after it is initialized.

How can we access the static variable?

We can use ClassName.variableName or instance.variableName

Is there such a thing as a private class?

Mostly no. We cannot declare a top-level class with the private access modifier. However, the access modifier private can be applied to inner class.

What is the purpose of static initialization blocks?

Static initialization blocks are used to initialize static variables when it involve some logic.

How many static initialization blocks can we have in each class?

There is no limit.

What is the execution order for static initialization blocks?

Static initialization blocks are executed in the order that they are defined in the class.

What does the compiler do with the regular initialization blocks?

The compiler copies these regular initialization blocks into the body of each constructor.

How can we define a constant?

The static modifier, in combination with the final modifier, is also used to define constants. The final modifier indicates that the value of this field cannot change. For example, the following variable declaration defines a constant named PI, whose value is an approximation of pi (the ratio of the circumference of a circle to its diameter):

static final double PI = 3.141592653589793;

Constants defined in this way cannot be reassigned, and it is a compile-time error if your program tries to do so.

What is the rule for naming constants?

By convention, the names of constant values are spelled in uppercase letters. If the name is composed of more than one word, the words are separated by an underscore (_).

What is compile-time constant?

If a primitive type or a string is defined as a constant and the value is known at compile time, the compiler replaces the constant name everywhere in the code with its value. This is called a compile-time constant. If the value of the constant in the outside world changes (for example, if it is legislated that pi actually should be 3.975), you will need to recompile any classes that use this constant to get the current value.

What does the compiler do when it see a compile-time constant?

If a primitive type or a string is defined as a constant and the value is known at compile time, the compiler replaces the constant name everywhere in the code with its value. This is called a compile-time constant. If the value of the constant in the outside world changes (for example, if it is legislated that pi actually should be 3.975), you will need to recompile any classes that use this constant to get the current value.

What is the purpose of the static initialization block?

A static initialization block is a normal block of code enclosed in braces, { }, and preceded by the static keyword. Here is an example:

static {
    // whatever code is needed for initialization goes here
}

A class can have any number of static initialization blocks, and they can appear anywhere in the class body. The runtime system guarantees that static initialization blocks are called in the order that they appear in the source code.

What is the advantage of using static method instead of static initialization block?

There is an alternative to static blocks — you can write a private static method:

class Whatever {
    public static varType myVar = initializeClassVariable();

    private static varType initializeClassVariable() {

        // initialization code goes here
    }
}

The advantage of private static methods is that they can be reused later if you need to reinitialize the class variable.

What is the difference between a static initialization block and a regular initialization block?

Initializer blocks for instance variables look just like static initializer blocks, but without the static keyword:

{
    // whatever code is needed for initialization goes here
}

What does the Java compiler do with the regular initialization block?

The Java compiler copies initializer blocks into every constructor. Therefore, this approach can be used to share a block of code between multiple constructors.

How can we prevent a sub-class from overriding a method?

Declare the method with the final keyword. A final method cannot be overridden in a subclass.

Can we use a final method to initialize data members?

Absolutely. Here is an example of using a final method for initializing an instance variable:

class Whatever {
    private varType myVar = initializeInstanceVariable();

    protected final varType initializeInstanceVariable() {

        // initialization code goes here
    }
}

This is especially useful if subclasses might want to reuse the initialization method.

How can we use the 'assert' statement in Java?

assert (boolean expression to test);
assert toString(ACE) == "Ace";

If the boolean expression is false, you will get an error message. If you use the assert statement, you must run your program with the ea flag:

java -ea YourProgram

What is "package private"?

There are two levels of access control:

  1. At the class level—public, or package-private (no explicit modifier).
  2. At the member level—public, private, protected, or package-private (no explicit modifier).

So, package-private is when we do not explicitly specify an access modifier such as public, private, or protected. A class may be declared with the modifier public, in which case that class is visible to all classes everywhere. If a class has no modifier (the default, also known as package-private), it is visible only within its own package (packages are named groups of related classes).

At the member level, you can also use the public modifier or no modifier (package-private) just as with top-level classes, and with the same meaning. For members, there are two additional access modifiers: private and protected. The private modifier specifies that the member can only be accessed in its own class. The protected modifier specifies that the member can only be accessed within its own package (as with package-private) and, in addition, by a subclass of its class in another package. The following table shows the access to members permitted by each modifier.

Why should we avoid using the public access modifier except for constant?

It is for better data hiding, so that we can avoid accidental changes. Public fields tend to link you to a particular implementation and limit your flexibility in changing your code. Constants, on the other hand, are constants. We should not be changing them ever, so it is ok for them to be public, and beside, other code cannot change them anyway, so there is no risk involve. For constants, having direct public access make it easier to use it rather than having to implement a method to retrieve the constant.

Can we use an interface name as a return type?

Yes. You also can use interface names as return types. In this case, the object returned must implement the specified interface.

Can we use the this keyword with a constructor?

From within a constructor, you can also use the this keyword to call another constructor in the same class. Doing so is called an explicit constructor invocation.

public class Rectangle {
    private int x, y;
    private int width, height;

    public Rectangle() {
        this(0, 0, 1, 1);
    }
    public Rectangle(int width, int height) {
        this(0, 0, width, height);
    }
    public Rectangle(int x, int y, int width, int height) {
        this.x = x;
        this.y = y;
        this.width = width;
        this.height = height;
    }
    ...
}

In the above code, one constructor invokes another constructor, but instead of using the name of the class, we use the this keyword.

What is the rule that we must observe when invoking a constructor from inside another constructor?

If present, the invocation of another constructor must be the first line in the constructor.

What is covariant return type?

This is related to polymorphism. Assume that we have a class named Number, and another class ImaginaryNumber is a sub-class of Number. If we have a function that is declared to return an instance of the Number class. This function can also return an instance of the ImaginaryNumber. The same is not true the other way around. A function that was declared to return an instance of ImaginaryNumber, cannot return an instance of Number.

Covariant return type is allowed to vary in the same direction as the subclass.

Can we use the name of an interface as the return type of a method?

Yes. You can use interface names as return types. In this case, the object returned must implement the specified interface.

What happens when we declare a primitive variable and what happens when we declare an object variable?

When we declare a primitive variable such as:

int x

the compiler reserve memory for it. However when we declare an object variable such as:

Point p;

there is no object being created, and as such, the compiler does not consume any memory.

When do we need to implement the toString method?

The toString() method is used whenever we want to print the object, or concatenate the objects.

What is Java SE, What is Java EE, What is Java ME, What is Java FX?

Java SE abbreviate for Java Standard Edition. Java SE is the core Java programming platform. It contains the minimal set of the libraries and APIs that any Java programmer should learn. Java SE is for developing desktop applications and it is the foundation for developing in Java language. It consists of development tools, deployment technologies, and other class libraries and toolkits used in Java applications.

Java EE abbreviate for Java Enterprise Edition. The Java platform (Enterprise Edition) differs from the Java Standard Edition Platform (Java SE) in that it adds libraries which provide functionality to deploy fault-tolerant, distributed, multi-tier Java software, based largely on modular components running on an application server. In other words, if your application demands a very large scale, distributed system, then you should consider using Java EE. Built on top of Java SE, it provides libraries for database access (JDBC, JPA), remote method invocation (RMI), messaging (JMS), web services, XML processing, and defines standard APIs for Enterprise JavaBeans, servlets, portlets, Java Server Pages, etc…

Java ME abbreviate for Micro Edition. This is the platform for developing applications for mobile devices and embedded systems such as set-top boxes. Java ME provides a subset of the functionality of Java SE, but also introduces libraries specific to mobile devices. Because Java ME is based on an earlier version of Java SE, some of the new language features introduced in Java 1.5 (e.g. generics) are not available.

JavaFX is a platform for creating rich internet applications using a lightweight user-interface API. It is a recent addition to the family of Java platforms.

How are reference data types passed into a method?

Reference data type parameters, such as objects, are also passed into methods by value. This means that when the method returns, the passed-in reference still references the same object as before. However, the values of the object's fields can be changed in the method, if they have the proper access level.

Consider a method in an arbitrary class that moves Circle objects:

public void moveCircle(Circle circle, int deltaX, int deltaY) {
    // code to move origin of circle to x+deltaX, y+deltaY
    circle.setX(circle.getX() + deltaX);
    circle.setY(circle.getY() + deltaY);

    // code to assign a new reference to circle
    circle = new Circle(0, 0);
}

Let the method be invoked with these arguments:

moveCircle(myCircle, 23, 56)

Inside the method, circle initially refers to myCircle. The method changes the x and y coordinates of the object that circle references (i.e., myCircle) by 23 and 56, respectively. These changes will persist when the method returns. Then circle is assigned a reference to a new Circle object with x = y = 0. This reassignment has no permanence, however, because the reference was passed in by value and cannot change. Within the method, the object pointed to by circle has changed, but, when the method returns, myCircle still references the same Circle object as before the method was called. https://docs.oracle.com/javase/tutorial/java/javaOO/arguments.html

How can we pass a method into a method?

If you want to pass a method into a method, then use a lambda expression or a method reference.

How can we write a method that accept arbitrary number of arguments?

You can use a construct called varargs to pass an arbitrary number of values to a method. You use varargs when you don't know how many of a particular type of argument will be passed to the method. It's a shortcut to creating an array manually. To use varargs, you follow the type of the last parameter by an ellipsis (three dots, …), then a space, and the parameter name. The method can then be called with any number of that parameter, including none.

public Polygon polygonFrom(Point... corners) {
    int numberOfSides = corners.length;
    double squareOfSide1, lengthOfSide1;
    squareOfSide1 = (corners[1].x - corners[0].x)
                     * (corners[1].x - corners[0].x) 
                     + (corners[1].y - corners[0].y)
                     * (corners[1].y - corners[0].y);
    lengthOfSide1 = Math.sqrt(squareOfSide1);

    // more method body code follows that creates and returns a 
    // polygon connecting the Points
}

You can see that, inside the method, corners is treated like an array. The method can be called either with an array or with a sequence of arguments. The code in the method body will treat the parameter as an array in either case. You will most commonly see varargs with the printing methods; for example, this printf method:

public PrintStream printf(String format, Object... args)

If we need to have a method that can accept an arbitrary number of arguments, we can define it:

public void methodName(Object... args)

The … is just a shortcut to indicate an array.

Can a class inherit from multiple different classes?

No.

Can a class implements multiple interfaces?

Yes.

class MyClass extends MySuperClass implements InterfaceA, InterfaceB, InterfaceC {
}

What are the 3 components of a field declaration?

Field declarations are composed of three components, in order:

  1. Zero or more modifiers, such as public or private.
  2. The field's type (int, double, float, boolean, String, etc)
  3. The field's name.

What are the conventions for naming variables, classes, and methods?

  1. The name of a class should start with a capital letter.
  2. The name of a variable should start with a lowercase letter.
  3. The name of a method should start with a verb, and should start with a lowercase letter. In multi-word names, the first letter of each of the second and following words should be capitalized.

Can we have methods with the same name?

Yes, but the complete method signature should be different. However, you cannot declare more than one method with the same name and the same number and type of arguments, because the compiler cannot tell them apart. The compiler does not consider return type when differentiating methods, so you cannot declare two methods with the same signature even if they have a different return type.

Overloaded methods should be used with careful consideration, as they can make code much less readable.

What are the rules for defining constructors?

Constructor declarations look like method declarations—except that they use the name of the class and have no return type. For example, Bicycle has one constructor:

public Bicycle(int startCadence, int startSpeed, int startGear) {
   ...
}

To create a new Bicycle object called myBike, a constructor is called by the new operator:

Bicycle myBike = new Bicycle(30, 0, 8);

What is special about the "no argument" constructor?

Although Bicycle only has one constructor, it could have others, including a no-argument constructor:

public Bicycle() {
    gear = 1;
    cadence = 10;
    speed = 0;
}

We can invoke the "no argument" constructor:

Bicycle yourBike = new Bicycle();

You don't have to provide any constructors for your class, but you must be careful when doing this. The compiler automatically provides a no-argument, default constructor for any class without constructors. This default constructor will call the no-argument constructor of the superclass. In this situation, the compiler will complain if the superclass doesn't have a no-argument constructor so you must verify that it does. If your class has no explicit superclass, then it has an implicit superclass of Object, which does have a no-argument constructor.

Can we use access modifier to control access to constructors?

Yes. You can use access modifiers in a constructor's declaration to control which other classes can call the constructor.

Why do some people say that Java is not a pure object oriented language?

People say that Java is not a pure object oriented language because Java has primitives such as int that are not objects.

Why is Java popular?

  1. Java is platform-independent. After you compile Java, you can take the compiled file and deploy it anywhere without having to recompile from source. With C or C++, we have to recompile from source.
  2. Java is object-oriented. C++ is object-oriented too.
  3. Java manage memory better than C++ through a process called Garbage Collection
  4. C++ has pointers. Java has no concept called pointers.
  5. C++ support multiple inheritance. Java does not support multiple inheritance.
  6. Java does not allow structural programming, and C++ does.

What are the 3 different kind of class loader?

  1. System class loader: load all classes in the CLASSPATH
  2. Extension class loader: load all classes from the extension directories (jre, ext, lib, etc)
  3. Bootstrap class loader: load all the Java core files

Java starts with the Bootstrap class loader -> Extension class loader -> System class loader.

Why does Java prefer immutable classes?

A number of classes in Java are immutable, such as String. Wrapper classes are also immutable. The value of a String object once created cannot be modified. Any modification on a String object creates a new String object. This provides a guarantee that the object is not changed. However, the variable is not tightly bound to that object. We can still assign the variable to another object, or cause the variable to point to a different object. Nonetheless, immutable classes guarantee that the object itself is not changed.

String str3 = “value1”;
str3.concat(“value2”)
System.out.println(str3); // output “value1”

Note that the value of str3 is not modified in the above example. The result should be assigned to a new variable, or the same variable can be reused.

What does JSR abbreviate for?

Java Specification Request.

What is the purpose of JAX-RS?

JAX-RS is the standard for building RESTful web services.

What does JMS abbreviate for?

Java Message Service

What does EJB abbreviate for?

Enterprise JavaBeans. Earlier version of EJB was hard to develop, and hard to do unit testing. That was one of the reason why people shifted toward Spring.

What is the Model 1 architecture and what is the Model 2 architecture?

In the beginning (Model 1 architecture), there was JSP pages, but there were no servlets. When Java introduce the Model 2 architecture, servlet was introduced, and JSP pages were implemented as servlets. In the Model 1 architecture, JSP was responsible for everything. It was responsible for getting the data from the database, and rendering it.

What is the purpose of the Class.forName method?

This is to load a particular class, or to create an instance of a class where the name of the class is not known at compile time but is known at runtime.

Class.forName(“org.hsqldb.jdbcDriver”);

How should we implement the toString method?

class Animal {
  String name;
  String type;
  public Animal(String name, String type) {
    this.name = name;
    this.type = type;
  }
  public String toString() {
    return “Animal [name=“ + name + “, type=“ + type + “]”;
  }
}

public class ToStringExample {
  public static void main(String[] args) {
    Animal animal = new Animal(“Tommy”, “Dog”);
    System.out.println(animal);
  }
}

The above code would output:

Animal [name=Tommy, type=Dog]

It seems to be a good convention to always include the name of the class in the result of the toString method.

What is the error message that Java compiler display if it cannot resolve a class?

Cannot resolve … to a type.

What kind of data type do we get when we divide 2 integers?

We get an int, unless we do a cast. In other words, we may lose precision if we are not careful.

What does IoC abbreviate for?

Inversion of Control

How is Ioc related to dependency injection?

IoC is just another name for dependency injection.

What is the purpose of the transient keyword?

The transient keyword in Java is used to indicate that a field should not be serialized. For example, if the value of a field can be derived from other fields, it should not be serialized (to conserve disk space). At the time of deserialization, the readObject method is called to perform any operations necessary to restore the state of the object back to the state at which the serialization occurred.

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License