Java

Basics of Java Programming Language. Links: method overloading, java interview questions

86 flashcards · Programming Languages · by lakesare

  1. public class Dog extends Animal How can we create a new Dog now?

    Dog x = new Dog(); or Animal x = new Dog(); This will fail though: Dog x = new Animal(); Because not all animals are dogs: incompatible types: Animal cannot be converted to Dog

  2. public class Dog extends Animal What will happen if we: Animal animal = new Dog(); Dog dog = animal;

    Runtime error, because compiler doesn't know if this particular animal is a dog. We need to explicitly typecast animal to promise compiler that animal will be a dog: Dog dog = (Dog)animal

  3. Result of System.out.println(3/2)? How to make it output 1.5?

    => 1. Because: 3 and 2 are both ints largest integer which is less than or equal to 3/2 is one Make at least one of the numbers double, e.g. 3/2.0.

  4. Write down syntax of a for loop.

    Just like in Javascript: for ( int i = 0; i < 10; i = i + 1 ) System.out.println("*");

  5. How many times will rrrr be printed out? for (int i = 0; i != 2; i++) { System.out.println("Hello rrrrrrrld"); }

    2. While i != 2 is true.

  6. How many times each loop * will be printed out in each loop? for(int i = 0; i < 3000; i = i + 2) System.out.println("*"); for(int i = 0; i >= 0; i = i + 1) System.out.println("*"); for(int i = m; i >= n; i = i + 1) System.out.println("*"); (You can assume that n > m)

    for(int i = 0; i < 3000; i = i + 2) - 1500. Last i is 2998, but we count first 0, so it's 1500. for(int i = 0; i >= 0; i = i + 1) - forever for(int i = m; i >= n; i = i + 1) - 0

  7. What are the semantics of a for loop? for(initialization; condition; increment)

    1. Execute the initialisation expression. 2. Evaluate the condition. If false then leave the loop. If true go to 3. 3. Execute the body. 4. Execute the increment. 5. Go to 2.

  8. How would you declare an instance method?

    Just don't include a static keyword.

  9. What is method overloading?

    When class has more than one method having the same name if their argument list is different. class Rrr{ int hi(int a){ return 4; } double hi(String a){ return 3.0; } } (And they even can me returning different datatypes)

  10. How would you call static method from static method?

    Just p(). class Test{ static void p(String string){ System.out.println(string); } public static void main(){ p("Hello!"); } } Static variables can be accessed just as staticVariable too.

  11. How to compile and run a java program, e.g.: file my_file.java: class MyClass { public static void main(String[] args) { System.out.println("Hello World"); } }

    You want to do: javac my_file.java and then java MyClass # The name of the class, not file Links: SO answer, javac docs, java docs

  12. What are the semantics of a for( ; ; ) statement?

    Empty condition will evaluate to true. This loop will run forever.

  13. Name 2 ways of generating random numbers in Java.

    double Math.random() => [0, 1) Uses Random.nextDouble() internally. import java.util.Random; Random random = new Random(); int Random#nextInt(maxInt); => [0, maxInt) Links: docs for java.util.Random

  14. How to give arguments to main? Test.java class Test{ public static void main(String[] args){ for (int i = 0; i != args.length; i++) { System.out.println(args[i]); } } }

    javac Test.java java Test wow hi rrr

  15. What's a CLASSPATH?

    Env variable telling java where to search for packages. Default CLASSPATH is . (current directory).

  16. What's java package?

    A package is a namespace that organizes a set of related classes and interfaces. The package name corresponds to a directory structure on disk where the classes are stored.

  17. import java.util.Scanner Explain what's what here.

    → java is a top level package → util is a sub package → and Scanner is a class which is present in the sub package util.

  18. package letmecalculate; public class Calculator { public int add(int a, int b){ return a+b; } public static void main(String args[]){ Calculator obj = new Calculator(); System.out.println(obj.add(10, 20)); } } How to use this class in another program?

    import letmecalculate.Calculator; public class Demo{ public static void main(String args[]){ Calculator obj = new Calculator(); System.out.println(obj.add(100, 200)); } }

  19. What if java file has no package declaration?

    Then it's automatically included in the 'default package'.

  20. What's an alternative to import hi.Calculator;?

    *: import hi.*; new Calculator(); Fully qualified name: new hi.Calculator();

  21. Name 3 ways to access a class from another package.

    import package.*; - all the classes and interfaces of this package will be accessible but not subpackages. import package.classname; - only declared class of this package will be accessible fully qualified name.

  22. 1. What will running: > javac -d . Test.java result in? 2. How to call main now? Test.java package hello; class PlusCalculator{ } class Test{ public static void main(String[] args){ for (int i = 0; i != args.length; i++) { System.out.println(args[i]); } } }

    1. Running javac will result in a folder hello with: PlusCalculator.class Test.class 2. > java hello.Test

  23. Name 2 ways to specify a classpath.

    1. environment variable > export CLASSPATH=.:/lib Use colon : as the path separator on Linux, and ; in Windows. 2. -cp argument > java -cp .:/lib Use -cp on Linux, and -classpath in Windows.

  24. Imagine following directory structure. Org is a package, mypackage is a subpackage. /home/user/myprogram/ | ---> org/ | ---> mypackage/ | ---> HelloWorld.class ---> SupportClass.class ---> UtilClass.class How to run HelloWorld class?

    java -cp /home/user/myprogram org.mypackage.HelloWorld

  25. How to make java hi.hello run everywhere?

    We should put a directory containing hi package into our CLASSPATH, e.g.: export CLASSPATH=$CLASSPATH:dir-containing-hi-package

  26. How would you go about printing all Unicode characters Java can hold in a char?

    char takes up 2 bytes, therefore there are 216 characters it can hold (Unicode is bigger) to print a unicode character we can just typecase its number (char)15

  27. How should checked VS unchecked exceptions be handled?

    Checked exceptions must be either: try-catched, or declared in the method in which it is thrown. Unchecked exception CAN be try-catched and declared, but not necessarily.

  28. public void hi() { throw new IOException(); } This code won't compile: error: unreported exception IOException; must be caught or declared to be thrown Resolve it.

    This code won't compile, because we are not handling a checked exception. try-catch it: public void hi() { try { throw new IOException(); } catch(IOException e) { //handle caught exception. } } 2. declare throws in method public void hi() throws IOException { throw new IOException(); }

  29. What checked VS unchecked exceptions are subclasses of?

    checked exceptions: Exception unchecked exceptions: Error, RuntimeException (Both java.lang.Error and java.lang.Exception classes are sub classes of java.lang.Throwable class)

  30. When should you use checked VS unchecked exceptions?

    checked exceptions: represent invalid conditions in areas outside the immediate control of the program (invalid user input, database problems, network outages, absent files) unchecked exceptions: represent defects in the program, bugs (arithmetic overflow, divide by zero) Unchecked runtime exceptions represent conditions that, generally speaking, reflect errors in your program's logic and cannot be reasonably recovered from at run time. So it doesn't make sense to include them in your method's…

  31. How can we rewrite it to avoid using aa variable? int[] aa = { 1, 3, 0 }; int[] hi = sortArray(aa);

    int[] hi = sortArray(new int[] { 1, 3, 0 });

  32. Java overriding VS overloading?

    overriding: when extended class overrides one of the methods from its superclass overloading: when class has more than one method having the same name and their argument list is different.

  33. What's binding in Java?

    Association of method call to the method body is known as binding. For every method call there should be proper method definition. This is a rule in java. If compiler does not see the proper method definition for every method call, it throws error.

  34. Name 2 types of binding in Java.

    static binding - happens during compilation dynamic binding - happens during runtime

  35. this VS super: explain what's going on here. class SuperClass{ public SuperClass(int i){ System.out.println("Super Class Constructor"); } } class SubClass extends SuperClass{ public SubClass(){ this(10); } public SubClass(int i){ super(i); } }

    this(10) calls overloaded constructor in the same class super(i) calls constructor in a superclass.

  36. Why can't this/super be used in static methods?

    this: there is no this to refer to in static method super: static methods can't be overridden, so super has no overridden method to refer to

  37. Binding of what methods happens at the compile time (when we're overriding a method)?

    Static binding happens for these and only these methods: static private final

  38. Explain output. class Human{ public static void walk(){ System.out.println("Human walks"); } } class Boy extends Human{ public static void walk(){ System.out.println("Boy walks"); } public static void main(String args[]) { Human obj = new Boy(); Human obj2 = new Human(); obj.walk(); //=> Human walks obj2.walk(); //=> Human walks } }

    In both cases we're calling is a static method walk(). And if method is static (or private, or final), - static binding is used, which looks a types rather than objects. Since types of obj1 and obj2 is Human - Human.walk() is called. Links: example and explanation

  39. Explain output. class Human{ public void walk(){ System.out.println("Human walks"); } } class Boy extends Human{ public void walk(){ System.out.println("Boy walks"); } public static void main(String args[]) { Human obj = new Boy(); Human obj2 = new Human(); obj.walk(); //=> Boy walks obj2.walk(); //=> Human walks } }

    In both cases we're calling is an instance method walk(). And if method is not static, or private, or final, - dynamic binding is used, which looks at objects rather than types. Method overriding happens. Links: example and explanation

  40. Will mymethod get overloaded? int mymethod(int a, int b) float mymethod(int var1, int var2)

    No, argument lists are exactly the same. Compile error will happen.

  41. Name 4 access modifiers in Java.

    Use the most restrictive access level that makes sense for a particular member. Use private unless you have a good reason not to.Avoid public fields except for constants. (Many of the examples in the tutorial use public fields. This may help to illustrate some points concisely, but is not recommended for production code.) Public fields tend to link you to a particular implementation and limit your flexibility in changing your code.

  42. Name 3 ways to use keyword final.

    final keyword is used in several different contexts to define an entity that can only be assigned once. 1. A final class cannot be subclassed: public final class MyFinalClass {...} public class ThisIsWrong extends MyFinalClass {...} // forbidden 2. A final method cannot be overridden or hidden by subclasses. public class Base{ public void m1() {...} public final void m2() {...} public static void m3() {...} public static final void m4() {...} } public class Derived extends Base{ public void m1(…

  43. Explain output. class Human{ Human(){ p("Human constructor called"); } } class Student extends Human{ Student(){ p("Student constructor called"); } } new Student(); // Human constructor called // Student constructor called

    super() is implicitly included in each constructor which does not include either: this() function, or explicit super() call as its first statement. Every constructor calls up the chain till class at the top is reached. Links: java constructors article

  44. When do overloading and overriding happen - at runtime or compile time?

    overloading: compile time, static binding overriding: runtime, dynamic binding Notice that although static methods are inherited (from parent) they are not overridden (by child). This could be a surprise if you expected otherwise.

  45. Method hiding VS overriding?

    Method hiding: subclass defined a static method with the same signature as a static method in the superclass. Method overriding: subclass defined an instance method with the same signature as the instance method in superclass. Hiding signifies that: The version of a method that is executed is NOT determined by the object that is used to invoke it. In fact it will be determined by the type of reference variable used to invoke the method. Overriding signifies that: The version of method that is e…

  46. Why can't static methods be overridden?

    Because, static methods are resolved statically (i.e. at compile time) based on the class they are called on and not dynamically as in the case with instance methods which are resolved polymorphically based on the runtime type of the object. You also can't call super() from static methods.

  47. Where can super() VS super.hi() be used?

    super(): can only be used in constructor, and only as a first statement in a constructor. super.hi(): can only be used from instance methods and a constructor (hi can be both a static and an instance method). Links: book

  48. What is thread interference?

    When two operations, running in different threads, but acting on the same data, interleave. Two operations consist of multiple steps, and the sequences of steps overlap. Links: oracle tutorial example

  49. Give an example of thread interference being a trouble.

    class Counter { private int c = 0; public void increment() { c++; } public void decrement() { c--; } } It might not seem possible for operations on instances of Counter to interleave, since both operations on c are single, simple statements. However, even simple statements can translate to multiple steps by the virtual machine. Suppose Thread A invokes increment at about the same time Thread B invokes decrement. If the initial value of c is 0, their interleaved actions might follow this sequenc…

  50. What are synchronized methods?

    Make thread interference impossible, - when one thread is executing a synchronized method for an object, all other threads that invoke synchronized methods for the same object suspend execution until the first thread is done with the object. class Counter { private int c = 0; public synchronized void increment() { c++; } public synchronized void decrement() { c--; } } Links: oracle tutorial

  51. Name 3 classes for resizable arrays in Java.

    Vector - synchronized ArrayList - implemented like Vector, but not synchronized LinkedList - implemented differently, and has Queue methods Vector is almost identical to ArrayList, and the difference is that Vector is synchronized. Because of this, it has a bigger overhead than ArrayList. LinkedList is faster in add/remove, but slower in get.

  52. What's an interface?

    Class with empty methods that your class can 'implement', which would force it to have all those methods defined. 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.

  53. Explain this image:

    interface Collection{} interface Set extends Collection{} interface List extends Collection{} interface Queue extends Collection{} class ArrayList implements List{} class LinkedList implements List, Queue{}

  54. Why do people usually use ArrayList instead of Vector?

    Every Vector's method is synchronized, so: in single thread code - ArrayList is faster, in multithread code - you get better control over locking Links: stackoverflow answer

  55. Give syntax for interfaces.

    Interface: public interface Drivable{ void setWheels(int n); } Class that implements interface: public class Vehicle implements Drivable, SomeOtherInterface{ // must be at least as visible void setWheels(int n){ this.numOfWheels = n; } }

  56. Explain syntax. List<String> list = new ArrayList<>();

    <String> - generic that tells java what will be stored in this ArrayList <> - we don't need to specify <String> once again, since java will automatically infer it

  57. Turn Box into a generic class: public class Box { private Object object; public void set(Object object) { this.object = object; } public Object get() { return object; } }

    // <T> is the type of the value being boxed public class Box<T> { private T t; public void set(T t) { this.t = t; } public T get() { return t; } } A type variable can be any non-primitive type you specify: any class type, any interface type, any array type, or even another type variable.

  58. What are the conventions for type parameters naming?

    By convention, type parameter names are single, uppercase letters. Without this convention, it would be difficult to tell the difference between a type variable and an ordinary class or interface name. The most commonly used type parameter names are: E - Element (used extensively by the Java Collections Framework) K - Key N - Number T - Type V - Value

  59. What's the difference between Javadoc and Java annotations?

    Java annotations are not stripped during the compile time, and can be discovered via reflection.

  60. Name 3 built-in Java annotations.

    @Override - compile error if method is not found in one of the parent classes or implemented interfaces. @Deprecated - compile error if method is used. @FunctionalInterface - compile error if interface has more than one method. Links: functional interface, all java annotations

  61. What's a functional interface?

    An interface with exactly one abstract method. Can be annotated with @FunctionalInterface if we want to catch errors at compile time: Invalid '@FunctionalInterface' annotation; Hi is not a functional interface

  62. What's an abstract class?

    A class that is declared abstract - it may or may not include abstract methods. public abstract class Animal{ public void sleep(int hours){ doSleep() } public abstract void makeNoise(); } Abstract classes can't be instantiated, and require subclasses to provide implementation of their abstract methods. Links: article

  63. Why are interface's methods not declared as abstract, despite them being practically abstract? public interface Hi{ public void doSomething(); public void doSomethingElse(); }

    They can be declared abstract! But all of the methods in an interface are already implicitly abstract, so the abstract modifier is not usually used. Links: stack overflow answer

  64. Create a valid functional interface.

    @FunctionalInterface public interface Rrr{ public void doSomething(); } Annotation is not necessary, but will catch errors at compile time: stackoverflow.

  65. Why use System.lineSeparator() instead of classic "\n"?

    System.lineSeparator() => system-dependent line separator string. On UNIX systems, it returns "\n"; on Microsoft Windows systems it returns "\r\n". Links: oracle docs

  66. What is the difference between errors and exceptions in Java?

    Error: serious problem that we should not try to catch (If you get an OutOfMemoryError, you have no guarantee that you will be able to do next line reliably) Exception: conditions that a reasonable application might want to catch. When an Error happens, you can never be sure that the application is able to execute the next line of code. If you get an OutOfMemoryError, you have no guarantee that you will be able to do anything reliably.

  67. What is JVM?

    java className Program that compiles: bytecode (.class files resulting from running javac) => machine code. Whenever, a program is written in JAVA, the javac compiles it. The result of the JAVA compiler is the .class file or the bytecode and not the machine native code (unlike C compiler). The bytecode generated is a non-executable code and needs an interpreter to execute on a machine. This interpreter is the JVM and thus the Bytecode is executed by the JVM. And finally program runs to give the…

  68. What's meant by saying that Java is platform independent?

    Bytecode is the same for all OSes, BUT JVMs (interpreting .class files [or bytecode]) are OS-dependent! An important point to be noted is that while JAVA is platform-independent language, the JVM is platform-dependent. Different JVM is designed for different OS and byte code is able to run on different OS.

  69. How to create Java bytecode?

    Write hi.java, run javac, and it will result in a Hi.class file which consists of bytecode.

  70. Where does System class come from? System.out.println("Hello!");

    java.lang.System It doesn't need to be imported, because compiler automatically imports it for you. System.out is a variable of java.lang.System (this class does not need to be imported; java.lang package is so fundamental that the compiler always imports this for you).

  71. What does rectangle_1.equals(rectangle_2) return by default?

    Same as rectangle_1 == rectangle_2, that is only returns true if it's actually the very same object. The equals method for class Object implements the most discriminating possible equivalence relation on objects; that is, for any non-null reference values x and y, this method returns true if and only if x and y refer to the same object (x == y has the value true).

  72. class Rectangle { int a, b; public Rectangle(int a, int b){ this.a = a; this.b = b; } // public boolean equals(Rectangle rectangle) { // return true; // } } If .equals is not defined: rectangle_1 == rectangle_2; //=> ? rectangle_1.equals(rectangle_2); //=> ? If .equals is defined: rectangle_1 == rectangle_2; //=> ? rectangle_1.equals(rectangle_2); //=> ?

    If .equals is not defined: rectangle_1 == rectangle_2; //=> false rectangle_1.equals(rectangle_2); //=> false (both just check if it's literally the reference to the same object) If .equals is defined: rectangle_1 == rectangle_2; //=> false rectangle_1.equals(rectangle_2); //=> true The equals method for class Object implements the most discriminating possible equivalence relation on objects; that is, for any non-null reference values x and y, this method returns true if and only if x and y ref…

  73. this() VS super()? Where and how are they used?

    this(10) calls overloaded constructor in the same class super(i) calls constructor in a superclass. class SuperClass{ public SuperClass(int i){ System.out.println("Super Class Constructor"); } } class SubClass extends SuperClass{ public SubClass(){ this(10); } public SubClass(int i){ super(i); } }

  74. Why is this List subscribers = new ArrayList(); preferred to this ArrayList subscribers = new ArrayList(); ?

    List is an interface, ArrayList is a class. You should use interfaces rather than classes as parameter types. More generally, you should favour the use of interfaces rather than classes to refer to objects. If appropriate interface types exist, then parameters, return values, variables, and fields should all be declared using interface types.

  75. What is the command for jvm?

    java className ../essential files❯ ls Hangman.java WordGamesArcade.java../essential files❯ javac WordGamesArcade.java ../essential files❯ ls Hangman.java WordGamesArcade.javaHangman.class WordGamesArcade.class../essential files❯ java WordGamesArcade WORD GAMES ARCADE

  76. What access level modifier is used if you don't mention any modifier at all? String getRandomWord() { int r = random.nextInt(words.size()); return words.get(r); }

    package-private

  77. What is the difference between protected and private access modifiers?

    protected - Only this class and any subclasses may access the method/property. private - Only this class may access the method/property. It won't even be inherited.

  78. When class has mostly static methods, it frequently doesn't make sense to instantiate it. How do you prevent class instantiation?

    By marking constructor as private.

  79. Why ArrayList<int> won't compile?

    Because the rule for generic types is you can only specify class or interface types, not primitives!

  80. byte hi = 5;. But what are their corresponding autoboxing classes? (What to put into ArrayList<_____>) byte short int long float double boolean char

    byte => Byte short => Short int => Integer long => Long float => Float double => Double boolean => Boolean char => Character

  81. We can stuff both new Integer(3) object and 3 primitive into the argument here. How?

    Thanks to autoboxing! Since Java 5, Java will automatically convert your value to either object or a primitive, depending on what argument is expected.

  82. What's that and why is it used? class MyClass { static Map<Double, String> labels; static { labels = new HashMap<Double, String>(); labels.put(5.5, "five and a half"); labels.put(7.1, "seven point 1"); } //... }

    This is a static block. It's used to initialize complex static variables. 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.

  83. Why were the enhanced for loops introduced in Java? for (int myValue : myArray) { System.out.println(myValue); }

    The enhanced for loop was introduced in Java 5 as a simpler way to iterate through all the elements of a Collection. It can also be used for arrays, as in the above example, but this is not the original purpose.

  84. Name 2 differences between: Array, and Student[] arr = new Student[7]; ArrayList ArrayList arr = new ArrayList(); arr.add(23);

    1. ArrayList is resizable: We can't change the length after creating the Array object. 2. ArrayList can never store primitives: ArrayList can not contains primitive data types, it can only contains Object while Array can contain both primitive data types as well as objects. We can pretend ArrayList contains primitives, but this is achieved via autoboxing internally.

  85. What is the parent class of Exception and Error classes?

    Throwable

  86. HashSet VS HashMap?

    HashSet - is a set, e.g. { 1, 2, 3, 4, 5 } HashMap - is a key -> value (key to value) map, e.g. {a -> 1, b -> 2, c -> 2, d -> 1} HashSet import java.util.HashSet; class HashSetDemo{ public static void main(String[] args) { // Create a HashSet HashSet<String> hset = new HashSet<String>(); // Add elements to HashSet hset.add("AA"); hset.add("BB"); hset.add("CC"); hset.add("DD"); // Displaying HashSet elements System.out.println("HashSet contains: "); for(String temp : hset){ System.out.println(te…