TutorialsPoint.com Java Interview Questions Flashcards

1
Q

Five features of Java?

A
  1. Object Oriented
  2. Platform independent
  3. Robust
  4. Interpreted
  5. Multi-threaded
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Why architectural neutral?

A

Compiler generates byte code which then can be interpreted by Java runtime

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What do you know about Java?

A
  1. High level programming language originally developed by Sun Microsystems.
  2. Runs on many platforms such as Windows, Mac OS, Unix various OS
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Supported platforms?

A
  1. Windows
  2. Mac OS
  3. Unix/Linux various versions
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

How Java enabled high performance?

A

Uses just-in-time compiler which is a program that turns Java byte code which is interpreted into instructions that can be sent directly to the processor.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Why Java is considered dynamic?

A

Designed to adapt to an evolving environment

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What is Java Virtual Machine (JVM)?

A
  1. Java is compiled into platform independent byte code.
  2. The byte code is distributed over the web and interpreted by the Java Virtual Machine on the platform it is being run.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

List two or three Java IDEs?

A
  1. Eclipse
  2. Netbeans
  3. IntelliJ
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

List some Java keywords unlike C, C++?

A
  1. Import
  2. Super
  3. Finally
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Describe Object?

A
  1. A runtime entity in which it’s state is stored in fields and behavior is shown via methods.
  2. Methods operate on object’s internal state and serve as the primary mechanism for object-to-object communication.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Define class?

A
  1. A blue print from which individual objects are created.
  2. Contains fields and methods to describe the behavior of an object.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What kind of variables a class can consist of?

A
  1. Local variable
  2. Instance variables
  3. Class variables
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What is a local variable?

A
  1. Variables defined inside methods, constructors, or blocks.
  2. Declared and initialized within method and destroyed when method completes.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What is an instance variable?

A
  1. Variable within a class but outside any method.
  2. Instantiated when class is loaded.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What is a class variable?

A

Declared within a class, outside any method, with the static keyword.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What is Singleton class?

A

Ensures that only one instance of a class is created.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

Define Constructor?

A
  1. A special method which is invoked when a new object is created.
  2. Every class has a constructor.
  3. Java compiler builds default constructor when none explicitly found.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

List three steps for creating an Object for a class?

A
  1. Declared
  2. Instantiated
  3. Initialized
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

Default value of byte data type?

A

0

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

Default value of float and double data type?

A
  1. 0.0f
  2. 0.0d
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

When byte data type is used?

A

Save space in large arrays, in place of integers, since 4 times smaller than int.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

What is a static variable?

A

Class variable which is declared with static keyword in class, but outside a method, constructor, or block

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

Define Access Modifier?

A

Used to set access levels for classes, variables, methods, and constructors. Defaults to package access level.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

What is protected access modifier?

A

Variables, methods, and constructors declared protected in a superclass can be accessed only by:

  1. subclasses in other package
  2. any class within the package of the protected members’ class.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
What is synchronized Non Access Modifier?
Used to indicate that method can be accessed by only one thread at a time.
26
Variables used in switch statement can be used with which datatypes?
1. byte 2. short 3. int 4. char
27
When **parseInt()** method can be used?
1. Used to get primitive data type of a certain String. 2. For translating base 2, 8, 10, and 16 numbers stored as strings into integers.
28
Why is **String** class considered immutable?
Once created a String object **cannot be changed**. This enables safe sharing between many threads which is essential for multithreaded programming.
29
Which operators have highest precedence?
1. () 2. []
30
Why is **StringBuffer** mutable?
When necessary to make changes, StringBuffer to be used instead of String.
31
What is difference between String, StringBuffer, and StringBuilder classes?
1. **String** cannot be updated and thus to concat strings requires create of new String object. It is thread safe. 2. **StringBuilder** is faster, but not thread safe. Recommended for single thread programs. 3. **StringBuffer** is thread safe
32
Which package is used for pattern matching with regular expressions?
java.util.regex
33
java.util.regex consists of which classes?
1. Pattern 2. Matcher 3. PatternSyntaxException
34
What is **finalize()** method?
1. Method which is called just before object's final destruction by the garbage collector. 2. Can be used to ensure object terminates cleanly.
35
What is an **Exception**?
1. A problem that arises during the execution of a program. 2. Exceptions are caught by handlers positioned along the thread's method invocation stack.
36
Explain **Checked Exceptions**?
1. Exceptions that are checked at compile time to ensure code handles them properly. * If code within a method throws a checked exception, then the method must either handle the exception or specify the exception using throws keyword. 2. Examples: 1. FileNotFoundException 2. IOException
37
Explain **Runtime Exception**?
Exceptions that aren't checked at compile time and which should be preventable by proper coding. Examples: 1. ArrayIndexOutOfBoundsException 2. ClassCastException
38
What are the two subclasses under **Exception** class?
1. **IOException** *(checked exception)* 2. **RuntimeException** *(runtime exception)*
39
When **throws** keyword is used?
If method does not handle a checked exception, the method must declare it using the throws keyword.
40
When **throw** keyword is used?
An exception can be thrown, either newly instantiated one or an exception that was just caught, by using throw keyword.
41
How is **finally** used under Exception Handling?
Used to create a block of code that follows a **try** block. It executes whether or not an exception has occurred.
42
What things to be kept in mind while creating own exceptions?
1. All exceptions must be child of throwable 2. Depending on exception type: 1. Must **extend Exception** class to write **checked exception** that is to be enforced by the Handle or Declare Rule 2. Must **extend RuntimeException** when writing **runtime exception**
43
Define **inheritance**?
Process where one class is built upon another class **inheriting (re-using) methods** and **adding of other methods**.
44
When **super** keyword used?
1. If method overrides its super class's method, overridden method can be invoked using super keyword. *Applies to constructors too.* 2. Also used to refer to hidden field *(when super class and sub-class have same field name which is a bad practice)*.
45
What is **Polymorphism**?
Ability of an object to take on many forms. Common uses: 1. When parent class reference is used to refer to child class object. * Deer d = new Deer(); * Animal a = d; * Vegetarian v = d; * Object o = d; 2. When class has multiple inheritance. * public class Deer extends Animal implements Vegetarian{}
46
What is abstraction?
1. Ability to make a class abstract in OOP. 2. Abstract classes usually have one or more abstract methods in which method is declared but not implemented.
47
What is **Abstract class**?
1. Class cannot be Instantiated and is either partially or not at all implemented. 2. The class contains one or more abstract methods which are simply method declarations without body.
48
When **Abstract methods** are used?
When wanting a class to contain a particular method but you want actual implementation to be determined by child classes, you declare parent class as abstract.
49
What is **Encapsulation**?
Technique of making fields private and providing access to the fields via public methods. *AKA data hiding.*
50
What are primary benefits of **Encapsulation**?
1. Ability to modify implemented code without breaking code of others using our code. 2. Gives maintainability, flexibility, and extensibility to our code.
51
What is an **interface**?
1. Collection of abstract methods. 2. A class implements an interface, thereby inheriting the abstract methods of the interface.
52
Give some features of **Interface**?
1. Cannot be Instantiated 2. Does not contain any constructors 3. All methods are abstract *(not implemented)* 4. All fields automatically constants *(public static final)* 5. Class can implement multiple interfaces
53
Define **Packages** in Java?
A group of related types (*classes, interfaces, enumerations, and annotations*) providing **access protection** and **name space management**.
54
Why packages are used?
1. Prevent naming conflicts 2. To control access 3. Make searching/locating and usage of classes, interfaces, enumerations, and annotations, etc. easier.
55
Define **Multithreaded program**?
1. Contains two or more parts that can run concurrently. 2. Each part is called a thread and each thread defines a separate path of execution.
56
Explain two ways in which a **Thread** can be created?
1. Implementing Runnable interface 2. Extending Thread class
57
What is an **applet**?
1. Java program that runs in a Web browser. 2. An applet can be fully functional because it has entire Java API at its disposal.
58
An **applet** extends which class?
java.applet.Applet
59
Explain **garbage collection** in Java?
Used to **free the memory** by **cleaning objects no longer referenced**.
60
Define **immutable object**?
Can't be changed once created. Example: String
61
Explain the usage of **this()** with constructors?
Used with variables or methods and used to call constructor of same class.
62
Explain **Set Interface**?
1. Collection of elements which cannot contain duplicate elements. 2. Contains only methods inherited from Collection and adds restriction that duplicate elements are prohibited.
63
Explain **TreeSet**?
It is **Set** implemented when we want elements in **sorted order**.
64
What is **Comparable Interface**?
1. Used to sort collections and arrays of objects using collections.sort() and Java.utils. 2. Objects of the class implementing the Comparable interface can be ordered.
65
Difference between **throw** and **throws**?
1. **Throw** is used to **trigger an exception**. 2. **Throws** is used in **declaration of exception**.
66
Explain the following: ## Footnote **public static void main (String args[])**
1. **public**: is the access specifier 2. **static**: allows main() to be called without instantiating a particular instance of a class 3. **void**: affirms the compiler that no value is returned 4. **main()**: method is called at the beginning of Java program 5. **String args[]**: args parameter is an instance array of class String
67
Define JRE (Java Runtime Environment)?
Implementation of the Java Virtual Machine which invokes Java programs.
68
What is a **JAR** file?
1. Java Archive file which aggregates many files into one. 2. Holds Java classes in a library. 3. Built in ZIP file format and has .jar file extension.
69
What is **WAR** file?
1. Web Archive file used to store XML, Java classes, and JavaServer pages. 2. Used to distribute a collection of JavaServer Pages, Java Servlets, Java classes, XML files, static Web pages, etc.
70
Define **JIT compiler**?
1. **Just-in-time compiler** that improves runtime performance of computer programs based on bytecode. 2. It compiles the bytecode into platform specific executable code that is immediately executed.
71
Difference between **object oriented** programming language and **object based** programming language?
**Object based** follows all features of OOP except inheritance. Example: JavaScript is object based.
72
What is purpose of **default constructor**?
Java compiler creates **default constructor** only if there is no constructor in the class.
73
Can a constructor be made final?
No You use the final keyword in a method declaration to indicate that the method cannot be overridden
74
What is **static block**?
Used to initialize the static data member. It is used before main method at time of classloading. 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 }
75
Define **composition**?
Holding the reference of another class within some class. Example: class Fruit { ... } class Apple { private Fruit fruit = new Fruit(); //... }
76
What is function/method **overloading**?
When a class has multiple methods by same name but **different parameters**.
77
What is function/method **overriding**?
When a subclass provides a specific implementation of a method that is already provided by its parent class.
78
What is **final class** and **final method**?
1. **Class declared as final** cannot have subclasses. 2. **Methods declared as final** cannot be overridden.
79
What is **NullPointerException**?
NullPointerException is thrown **when calling the instance method of a null object**, accessing or modifying the field of a null object. **To prevent:** public void doSomething(Integer num) { if (num != null) { // do something to num } }
80
What are ways in which a **thread** can enter the **waiting state**?
1. By invoking its sleep() or wait() method 2. By blocking on IO 3. By unsuccessfully attempting to acquire an object's lock 4. Invoking deprecated suspend() method.
81
How does multi-threading take place on a computer with a single CPU?
The operating system's task scheduler allocates execution time to multiple tasks. By quickly switching between executing tasks, it creates the impression that tasks execute sequentially.
82
What invokes a thread's run() method?
After a thread is started, via start() method of the Thread class, the JVM invokes the thread's run() method when thread is initially executed.
83
Does it matter in which order catch statements for FileNotFoundException and IOException are written?
Yes. FileNotFoundException is inherited from IOException. **Exception's subclasses have to be caught first.**
84
What is difference between yielding and sleeping?
1. When task invokes **yield()** method, it returns to **ready state**. 2. When task invokes **sleep()** method, it returns to **waiting state**.
85
Why **Vector class** is used?
Ability to implement a **growable array** of objects.
86
How many bits are used to represent ASCII, UTF-16, and UTF8 chars?
1. **ASCII**: 8 2. **UTF-8**: one to four 8-bit units 3. **UTF-16**: one or two 16-bit units **UTF**: Unicode Transformation Format
87
What are **wrapper classes**?
Classes that allow primitive types to be accessed as objects. Example: Integer, Character, Double, Boolean, etc.
88
What is difference between a **Window** and a **Frame**?
**Frame class extends Window** to define a window with a title and a border.
89
Which package has light weight components?
**java.Swing** package. All components in Swing except JApplet, JDialog, JFrame, and JWindow are lightweight components.
90
What is difference between **paint()** and **repaint()** methods?
1. The **paint()** method supports painting via Graphics object. 2. The **repaint()** method is used to cause paint() to be invoked by the AWT painting thread.
91
What is the purpose of the **File class**?
Used to create objects that provide access to files and directories of local file system.
92
What is difference between the **Reader/Writer class** hierarchy and the **InputStream/OutputStream class** hierarchy?
1. **Reader/Writer** is character-oriented. 2. **InputStream/OutputStream** is byte-oriented.
93
Which class is used for obtaining design information about an object?
The **Class class**. The **java.lang.Class** class instance represents classes and interfaces in a running Java application. Example: Class cls = Class.forName("ClassDemo"); ClassLoader cLoader = cls.getClassLoader();
94
What is the difference between **static** and **non-static** variables?
1. A **static** variable is associated with the class as a whole rather than specific instances of a class. 2. **Non-static** variables take on their own values with each object instance.
95
What is **Serialization** and **deserialization**?
1. **Serialization** is process of writing the state of object to a byte stream. 2. **Deserialization** is process of restoring these objects.
96
What are **use cases**?
Describes a situation that a program might encounter and what behavior the program should exhibit in that circumstance.
97
Explain the use of **subclass** in a Java program?
Subclass inherits all the public and protected methods and the implementation. It also inherits all the default modifier methods and their implementation.
98
How to add a menu shortcut to menu item?
1. If there is a button instance called b1, you add short cut by calling b1.setMnemonic('F') so user can use Alt+F to click the button. 2. Using setShortcut(MenuShortcut s) method in MenuItem class.
99
Can you write a Java class that could be used both as an applet as well as an application?
Yes, just add a main() method to the applet.
100
What is the difference between **Swing** and **AWT** components?
1. AWT components are heavyweight, whereas Swing components are lightweight. 2. Heavyweight components depend on the local windowing toolkit. For example when java.awt.Button is running on the Java platform for Unix platform, it maps to a real Motif button.
101
What is the difference between constructors and other methods?
1. Constructors must have same name as the class and cannot return a value. 2. Constructors are only called once while other methods could be called many times.
102
Is there any limitation of using inheritance?
Yes, since inheritance inherits everything from the superclass and interface, it may make the subclass error-prone in some situations when dynamic overriding or dynamic overloading.
103
When is **ArrayStoreException** thrown?
When copying elements between arrays, if the source or destination arguments are not arrays or their types are not compatible.
104
Can you call one constructor from another constructor?
Yes, use **this()** syntax.
105
What is difference between methods sleep() and wait()?
1. The code sleep(2000) puts thread aside for exactly 2 seconds whereas wait(2000) causes a wait of up to 2 seconds. 2. A thread could stop waiting earlier if it receives the notify() or notifyAll() call. 3. wait() is defined in the class Object. sleep() is defined in the class Thread.
106
When **ArithmeticException** is thrown?
1. When integer is divided by zero. 2. Non-terminating decimal numbers using BigDecimal. For example 1/3 = 0.3333...
107
What is a **transient variable**?
A variable that may not be serialized during Serialization and which is initialized by its default value during de-serialization. Useful for minimizing network traffic. Example: private Image image; private **transient** Image thumbnailImage;
108
What is **synchronization**?
1. The capability to **control the access of multiple threads to shared resources**. 2. The synchronized keyword in Java provides locking which ensures mutual exclusive access of shared resource and prevents data race.
109
What is the **Collections API** or **Collections Framework**?
The Collections API or Framework is a set of **interfaces** (ex: see diagram below), **implementations** (ex: HashSet, TreeSet), **aggregate operations** (ex: forEach), and **algorithms** (ex: Collections.sort) that support operations on collections of objects.
110
Does **garbage collection** guarantee that a program will not run out of memory?
No, program can use up memory resources faster than they are garbage collected. It is possible for programs to create objects that are not subject to garbage collection.
111
What class is the immediate superclass of the **Applet class**?
Panel. A panel provides space in which an application can attach any other component, including other panels.
112
Which Java operator is right associative?
The **=** operator.
113
What is the difference between a **break** statement and a **continue** statement?
1. A **break** terminates the statement for which it applies (switch, for, do, or while). 2. A **continue** statement is used to end the current loop iteration and return control to the loop statement.
114
If a variable is declared **private**, where may the variable be accessed?
Only may be accessed within the class in which it is declared.
115
What is the purpose of the **System** class?
Provides access to system resources.
116
List primitive Java types?
1. Integer types: 1. **byte** *(8 bit signed)* 2. **short** *(16 bit signed)* 3. **int** *(32 bit signed)* 4. **long** *(64 bit signed or unsigned)* 2. Floating types: 1. **float** *(32 bit)* 2. **double** (64 bit) 3. **char** *(single 16-bit Unicode character)* 4. **boolean**
117
What is the relationship between **clipping** and **repainting** under AWT?
When a window is repainted by the AWT painting thread, it sets the clipping regions to the area of the window that requires repainting.
118
Which class is the immediate superclass of the **Container class**?
Component
119
What class of exceptions are generated by the Java run-time system?
1. RuntimeException 2. Error
120
Under what conditions is an object's **finalize()** method invoked by the garbage collector?
When the object has become unreachable
121
How can a dead thread be restarted?
It can't
122
Which arithmetic operations can result in the throwing of an **ArithmeticException**?
Division by zero
123
Variable of **boolean** type is automatically initialized as?
false
124
Can **try** statements be nested?
Yes
125
What are ClassLoaders?
Java **ClassLoader** loads a java class file into java virtual machine.
126
What is the difference between an **Interface** and an **Abstract class**?
1. An **abstract class** can have instance methods that implement default behavior. 2. An **interface** can only declare constants and instance methods, but cannot implement default behavior and all methods are implicitly abstract. An interface has all public members and no implementation.
127
What will happen if you remove **static** modifier from the signature of the main method?
Program throws **NoSuchMethodError** error at runtime.
128
What is the default value of an object reference declared as an instance variable?
Null, unless defined explicitly.
129
Can a top level class be private or protected?
No. Must use public or no access modifier.
130
Why do we need **wrapper classes**?
We can pass them around as method parameters where a **method expects an object**. It also provides utility methods.
131
What is the difference between **error** and an **exception**?
1. An **error** is an unrecoverable condition occurring at runtime such as OutOfMemory error. 2. **Exceptions** can be caught and dealt with by the program.
132
Is it necessary that each **try** block must be followed by a **catch** block?
No. It should be followed by either a **catch** block or a **finally** block.
133
When a thread is created and started, what is its initial state?
ready
134
What is the **Locale** class?
It is used to **tailor program output** to the conventions of a particular geographic, political, or cultural region.
135
What are **synchronized methods** and **synchronized statements**?
1. **Synchronized methods** are methods that are used to control access to an object. 2. A **synchronized statement** can only be executed after a thread has acquired the lock for the object or class referenced in the synchronized statement.
136
What is **runtime polymorphism** or **dynamic method dispatch**?
A process in which a call to an overridden method is resolved at runtime rather than at compile time. In this process an overridden method is called through the reference variable of a superclass.
137
What is **Dynamic Binding** (late binding)?
Refers to the linking of a procedure call to the code to be executed in response to the call. Occurs when the code associated with a given procedure call is not known until the time of the call at run-time.
138
Can a constructor be inherited?
No
139
What are the advantages of **ArrayList** over arrays?
1. Can grow dynamically 2. Provides more powerful insertion and search mechanisms than arrays.
140
Why deletion in **LinkedList** is faster than **ArrayList**?
It only involves updating the next pointer in the before the deleted node and the previous pointer in the node after the deleted node.
141
How to decide when to use **ArrayList** or **LinkedList**?
1. **LinkedList** when frequently adding and removing from middle of the list and only access list elements sequentially. 2. **ArrayList** when you need to support random access, without inserting or removing other than from the end.
142
What is a Values Collection View?
A collection returned by the **values()** method of the **Map Interface**. It contains all the objects present as values in the map.
143
What is **dot operator**?
1. The dot operator (.) is used to access the instance variables and methods of class objects. 2. Also used to access classes and sub-packages from a package.
144
Where and how can you use a **private constructor**?
When you don't want other classes to Instantiate the object and to prevent subclassing.
145
What is **type casting**?
It the treating of a variable of one type as though it is another type. Example of casting to int using (int): double x = 9.997; int nx = **(int)** x;; int rnx = **(int)** Math.round(x);
146
Describe life cycle of thread?
1. Newborn state 2. Runnable state 3. Running state 4. Blocked state 5. Dead state
147
What is the difference between the \>\> and \>\>\> operators?
1. \>\> operator carries the sign bit when shifting right. 2. \>\>\> operator zero-fills bits when shifting right.
148
Which method of the Component class is used to set the position and size of a component?
setBounds()
149
What is the range of the short type?
-(2^15) to 2^15 - 1
150
What is the immediate superclass of Menu?
MenuItem
151
Does Java allow Default Arguments?
No
152
Which Numbers is denoted by leading zero in Java?
Octal. For example 06
153
Which Number is denoted by leading 0x or 0X?
Hexadecimal. Example oxF
154
Break statement can use labels?
Yes. Example: **first:** for( int i = 0; i \< 10; i++) { **second:** for(int j = 0; j \< 5; j ++ ) { **break first;** } }
155
Where import statement is used in Java program?
It is allowed at the beginning of the program after package statement.
156
Explain suspend() method under Thread class?
Used to pause or temporarily stop execution of the thread.
157
Explain isAlive() method under Thread class?
It used to determine whether a thread is still running or not.
158
What is currentThread()?
A public static method used to obtain a reference to the current thread.
159
Explain main thread under Thread class execution?
The main thread is created automatically and begins to execute immediately when a program starts. It is a thread from which all child threads originate.
160
Life cycle of an applet includes which steps?
1. Initialization 2. Starting 3. Stopping 4. Destroying 5. Painting
161
Why is the role of init() method under applets?
It initialized the applet and is the first method to be called.
162
Which method is called by Applet class to load an image?
getImage(URL object,file name) Example: import java.applet.Applet; import java.awt.Graphics; import java.awt.Image; public class ImageApplet extends Applet { Image im; public void init() { im = getImage(getDocumentBase(), "image.jpg"); } public void paint(Graphics g) { g.drawImage(im, 0, 0, this); } }
163
Define **CODE** as an attribute of Applet?
It is used to specify the name of the applet class. Example: CODE="Main.class" WIDTH="800" HEIGHT="500">
164
Define **canvas**?
It is a simple drawing surface which is used for painting images or to perform other graphical operations. Canvas control represents a rectangular area where application can draw something or can receive inputs created by user.
165
Define **Networking Programming**?
It refers to writing programs that execute across multiple devices, in which the devices are all connected to each other using a network.
166
What is a **Socket**?
Sockets **provide the communication mechanism between two computers using TCP**. A client program creates a socket on its end of the communication and attempts to connect that socket to a server.
167
Advantages of Java Sockets?
1. Sockets are flexible and sufficient. 2. Efficient socket based programming can be easily implemented for general communications.
168
What are the disadvantages of Sockets?
1. Socket based communications allows only to send packets of raw data between applications. 2. Both the client-side and server-side have to provide mechanisms to make data useful in any way.
169
Which class is used by server applications to obtain a port and listen for client requests?
Java.net.ServerSocket
170
Which class represents the socket that both the client and server use to communicate with each other?
Java.net.Socket
171
Why **Generics** are used in Java?
* Stronger type checks at compile time. * Elimination of casts. * Can implement generic algorithms that work on collections of different types **Preferred: Using generics:** List list = new ArrayList(); list.add("hello"); String s = list.get(0); // no cast **Using cast:** List list = new ArrayList(); list.add("hello"); String s = (String) list.get(0); // cast
172
What **environment variables** do I need to set my machine in order to be able to run Java programs?
**CLASSPATH** - tells applications, including the JDK tools, where to look for user classes **PATH** - conveniently run the executables (javac.exe, java.exe, javadoc.exe, and so on) from any directory
173
Is there any need to import Java.lang package?
No, JVM loads by default.
174
What is **Nested top-level class**?
If a class is declared within a class and specify the static modifier, the compiler treats the class like any other top-level class. Nested top-level class is an inner class.
175
What is **Externalizable interface**?
An interface in which **contains two methods readExternal and writeExternal**. These methods give you control over the serialization mechanism.
176
If **System.exit(0);** is written at the end of the try block, will the **finally** block still execute?
No because control immediately goes out of the program.
177
What is **daemon thread**?
**Low priority thread** which runs intermittently in the background doing **garbage collection operation** for the Java runtime system.
178
Which method is used to create the **daemon thread**?
setDaemon
179
Which method must be implemented by all threads?
run()
180
What is the **GregorianCalendar** class?
Provides support for **traditional Western calendars**.
181
What is the **SimpleTimeZone** class?
It is a concrete subclass of TimeZone that represents time zone for use with a Gregorian calendar. * Holds an offset from GMT, called raw offset. * Also holds start and end rules for a daylight saving time schedule.
182
What is the difference between the **size** and **capacity** of a **Vector**?
**Size** is actual number of elements stored. **Capacity** is the maximum number of elements that can be stored at a given instance of time.
183
Can a **vector** contain heterogeneous objects?
Yes because it stores everything in terms of Object.
184
What is an **enumeration**?
Enumeration is a special data type that enables a variable to be a set of predefined constants **Example of declaration:** public enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY } **Example of iteration:** for (Planet p : Planet.values()) { System.out.printf("Your weight on %s is %f%n", p, p.surfaceWeight(mass)); }
185
What is the difference between **Path** and **ClassPath**?
They are both operating system level environment variables. **Path** defines where system can find the executables (.exe) files. **ClassPath** is used to specify location of .class files.
186
Can a class declared as private be accessed outside its package?
No; private is the most restrictive access modifier
187
What are the restrictions imposed on a static method or a static block of code? Aka class method
Class (static) methods: 1. Cannot access instance variables or instance methods directly 2. Must use an object reference 3. Cannot use the "this" keyword as there is no instance for "this" to refer to.
188
Can an interface extend another interface?
Yes and it can extend multiple interfaces.
189
Which object oriented Concept is achieved by using **overloading** and **overriding**?
Polymorphism
190
What is an object's lock and which objects have locks?
It is a mechanism that is used by **multiple threads** to obtain **synchronized access to the object**. A thread may execute a synchronized method of an object only after it has acquired the object's lock.
191
What is **Downcasting**?
It is **casting from a general to a more specific type**. i.e. casting down the hierarchy. **Example:** class Parent{ /\* ... \*/} class ChildClass extends Parent { /\* ... \*/ } public class Tester { public static void main (String args[]) { Parent p = new Parent ( ); ChildClass c = **(ChildClass)** p; } }
192
What are **order of precedence** and **associativity** and how are the used?
**Order of precedence** determines order in which operators are evaluated in expressions. **Associativity** determines whether expression is evaluated left-to-right or right-to-left. **Examples of right-to-left Associativity:** Unary: ++, - -, !, ~ Conditional: ?: Assignment: =, +=, -=, \*=, /=, %=, \>\>=, \<\<=, &=, ^=, |=
193
If a method is declared as **protected**, where may method be accessed?
May only be accessed **by classes or interfaces of the same package** or by **subclasses of the class** in which it is declared.
194
What is the difference between **inner class** and **nested class**?
1. When a class is defined within a scope of another class, then it becomes inner class. 2. If the access modifier of the inner class is static, then it becomes nested class.
195
What restrictions are placed on method **overriding**?
1. Must have **same** name, argument list, and return type. 2. Cannot limit the access of the method it overrides.
196
What is **constructor chaining** and how is it achieved?
A child object constructor always first needs to construct its parent. It is done via an implicit call to the no-args constructor as the first statement.
197
Can a double value be cast to a byte?
Yes ``` double d1 = 10.5; // 8 bytes // byte b1 = d1; // error as 8 bytes to 1 byte ``` byte b1 = **(byte)** d1; // 8 bytes cast to 1 byte System.out.println(b1); // prints 10
198
How does a **try** statement determine which **catch** clause should be used to handle an exception?
The catch clauses are **examined in order they appear**. The first one capable of handling the exception is executed. The remaining are ignored.
199
What will be the default values of all the elements of an array defined as an instance variable?
If the array is an array of primitive types, then all the elements will be initialized to the default value corresponding to that primitive type.