Escolar Documentos
Profissional Documentos
Cultura Documentos
Prepared by
Farag Zakaria Safy Saad
Master Student @ Cairo University
Faculty of Computers & Information
ITI-JAVA Intake 30
farag_cs2005@yahoo.com
This is my own study notes; please keep free to send me any errors exist or any other top
you need to add.
// true
Ex. double pi = PI
12. Variable types
1. Member variable these are the non static variables of the class when an object
is constructed(belongs to specific object).
The Compiler initialize them to their default values.
2. Automatic variables(local variables) are the variables of a method when it
executed.
Must be explicity initialized before being used.
3. Class variables (static variables) exists even if the class is not instanciated
(no object created from this class).
Compiler initialize them to their default values;
class ABC
{
int x; // member variable
int z; // class variable
initialized with 0;
initialized with 0;
b. import statements
c. class, interface , enum definitions
You compile with the file name but run with the class name
for example if you have file Good.java which contains
class ABC
{
public static void main(String args[])
{}
}
compilation command is ====== javac Good.java to run === java ABC
14. Evaluation order
Ex.
int[] a = {4,4};
int b = 1;
a[b] = b = 0; // evaluation from left to right requires that a[b] evaluated first then b
so a[1] = b; and b = 0; then a[1]=0
15. Difference between & and &&
in & both left operand and right operands are evaluated
in && the right operand is not evaluated if the left operand is false because the
whole operation is false
boolean a = true;
boolean b = false;
if ( b && (a = false) )
{
System.out.println("test");
}
System.out.println("a = " + a + " , b = " + b); // prints a = true , b = false
boolean a = true;
boolean b = false;
if ( b & (a = false) )
{
System.out.println("test");
}
System.out.println("a = " + a + " , b = " + b); // prints a = false , b = false
{
System.out.println("String is empty");
}
}
when called with test(null) the first operand is evaluated to ture and the second
operand will be evaluated so it will through NullPointerException
//
public static void test(String s)
{
if ( str == null // str.length() == 0)
{
System.out.println("String is empty");
}
}
when called with test(null) the first operand is evaluated to true and prints String is
empty
17. switch(x)
Ex.2
class ABC
{
byte method_1()
{
final int m = 127;
return m;
}
}
Ex.3
class ABC
{
byte method_1()
{
final int m = 128;
return m;
}
}
Ex.4
class ABC
{
byte method_1()
{
int m = 126;
return m;
}
}
24. Enumeration
is a set of constants(special kind of class)
syntax
enum WeekDays
{
Saturday,Sunday,Monday,Tuesday,Wednesday,Thursday,Friday
};
// ; is optional
enum properties
1. Cannot be defined in a method
Ex.
public void print()
{
enum A{} // compilation error enum A cannot be local
}
2. Enum cannot extends anther because multiple inheritance is not allowed in JAVA
Ex.
enum Day{}
enum Week extends Day{} // compilation error
Defining constructors
enum WeekDays
{
Saturday(1),Sunday(2),Monday(3),Tuesday(4),Wednesday(5),Thursday(6),Friday(7);
// ; is mandatory
int order;
WeekDays(int order)
{
this.order = order;
}
public int getOrder()
{
return order;
}
};
// ; is optional
Enum types must not be declared abstract; doing so will result in a compile-time
error.
Ex.
abstract enum Dog{D1,D2};
// Compile Error
// Illegal modifier for the member enum Dog; only public, protected, private & static are
// permitted
}
Ex. 2
enum Dog
{
D1, D2;
// compilation error D1,D2 must implement abstract method print()
abstract void print();
}
The correct code of the previous
enum Dog
{
D1
{
void print(){}
}
,
D2
{
void print(){}
};
abstract void print();
}
class ABC
{
protected void method() throws FileNotFoundException
{}
}
class ABChild extends ABC
{
void method() throws NotSerializableException // two errors here
{
// 1. You cannot reduce method scope (method must be protected or public)
}
}
//////////////
interface X
{
void print();
}
class YZ implements X
{
protected void print()
// compilation error you cannot reduce method visibility
{
// because default access modifier for interface methods is public
}
}
-------------A compile-time error occurs if a static method hides an instance method(nonstatic methods)
BUT for variables it is permissible for a static variable to hide an instance variable
Ex.
class A
{
int x = 90;
void print(){}
}
class B extends A
{
static int x = 90; // ok no errors
static void print(){} // compile time error
// This static method cannot hide the instance method from A
// This method can hide print() method in class A if it is static.
26. Constructors
-- cannot be static
-- cannot be final
only allowed access modifiers for constructors are public, protected, private,
default
Default constructors created if there is no any constructor in the class with the same
access modifier of the class otherwise it is not created.
Ex.
class ABC
{
public ABC(int x) // because existence of this constructor default const. doesn't
{}
created
}
if you tried ABC a = new ABC(); in main it will give compilation error because
ABC() is undefined.
this() used to call another constructor in the same class and must appear
in
when creating an object from a class the compiler creates the super and member
classes first then creates the current object
27. Accessing protected member of super class from subclass via super class reference.
A method in subclass has access to the protected instance members/methods of its
superclass, but only if it accesses them via a subclass object
Ex.
package points;
public class Point {
protected int x, y;
}
package threePoint;
import points.Point;
public class Point3d extends Point {
protected int z;
public void delta(Point p) {
p.x += this.x;
// compile-time error: cannot access p.x
p.y += this.y;
// compile-time error: cannot access p.y
// x,y can be accessed but using reference from subclass Point3d because it is
// outside its package
}
public void delta3d(Point3d q) {
q.x += this.x;
q.y += this.y;
q.z += this.z;
}
}
28. Objects and classes
Data Hiding defining the scope visibility of variables to public, protected, private
Encapsulation aggregation of data and behavior.
(data hiding) + How to access these data(setters, getters, .).
Inner classes
is a class inside class or method.
- when you create an object from inner class you must have an object from the
outer class.
- It is a compile-time error if a static class contains a usage of a non-static
member of an enclosing class.
- Member interfaces are always implicitly static. It is permitted but not required
for the declaration of a member interface to explicitly list the static modifier
class Outer
{
class Inner
{
void print()
{System.out.println("Inner");}
}
}
// to create object from Inner inside main
Outer out = new Outer();
Inner inner = out.new Inner(); // or Inner in = new Outer().new Inner();
class Inner // allowed to access members of Outer class and final variables
{
//inside the method print and final variables of its parameters
}
// only a , z, xn variables are visible to Inner class
}
}
inner classes cannot have static declarations unless they are compile-time constant
fields
Ex.
class Outer
{
class Inner
{
static final int x = 3; // OK no compilation errors
static int x;
// compilation error inner classes can't have static declarations
static void getX() // compilation error
{
return x;
}
}
static class NestedButNotInner
{
static int z=3; // OK no errors, not an inner class
}
interface NeverInner{} // interfaces are never inner because they are static by
// default
}
- Nested classes that are not inner classes may declare static members freely, in
accordance with the usual rules of the Java programming language
- Member interfaces are always implicitly static so they are never considered to be
inner classes.
Annonymous classes can be declared to extends another class or to implement a
single interface BUT not both.
Annonymous classes cannot have constructors because the name of the constructor
is the same as the name of the class and they didn't have names.
Nesting Classes
A compile-time error occurs if a class has the same simple name as any of its
enclosing classes or interfaces
Ex.
class Test
{
class Test{} ///
}
compilation error The nested type Test cannot hide an enclosing type
Ex.2
class Test
{
static final int x;
public Test()
{
x = 3; // compile time error final field x cannot be assigned
}
static
{
x = 10; // x must be assigned value in the static initializer or compile time error occur
}
}
31. Interface
is a collection of constants and abstract methods.
interface MyInterface
{
// final , static , public only allowed for variables
// variables must have initial value
public static final int x = 0; // public static final is default for variables
// public abstract are default for methods //
}
interface ABC
{
int a;
//// compilation error a must be initialized because its default is
//
public static final
}
Static by default so that they cannot be defined in Inner classes or inside methods
Ex.
class Outer
{
class Inner
{
interface X // Compilation error
{}
}
}
protected and private declarations are not allowed in interfaces, only allowed public
and abstract
interface X
{
protected void print(); // Compilation error protected and private is not allowed.
}
32. Static class loading vs dynamic class loading
Static class loading done using new operator
Ex. Car c = new Car(); // throws NoClassDefFoundException if Car cannot be found
Dynamic class loading done using reflection Class.forName(String classname)
// throws ClassNotFoundException
Interface
All methods are abstract
Variables are final static by default
Cannot implements another interface
Can extends another interface(one
or more)
May have no methods
May have no methods (Marker
interface)
May have a constructor
Cannot have constructors
Static by default so that cannot
defined inside Inner classes because
static is not allowed in Inner classes.
36. Abstract classes and interfaces are away to defer implementation to sub classes
They CANNOT be final because their methods should be overridden by children
classes.
37. operator for method parameters only
used to pass variable length of arguments to method
void print(int x) // you can call it with print(1), print(1,2),print(1,2,.)
// or print(new int[]{1,2,3,4});
// void print(int x) gives compilation error since is not defined
/////////////
void print(int x){}
void print(int x){}
// No errors
void print(int[] x){}
// compilation error (duplicate method) the same as print(intx)
38. Checked Exceptions
are exceptions that doesn't descend from RuntimeException which must be handled
by try and catch or throws-declaration.
39. Runtime Exceptions(Unchecked Exceptions).
avoidable exceptions that are your own fault.(they should never happen)
Ex. RuntimeException, ArrayIndexOutOfBoundsException,..
Class Error and its subclasses also are unchecked.
40. Finally block in exceptions
finally{} block executed in all circumstances.
what prevents finally block from completion
a. death of the current thread.
b. Execution of System.exit().
b. Turning off the computer.
41. Exceptions subclasses have to be caught first before the General Exception
Ex.
FileNoFoundException is inherited from the IOException
try
{
} catch (IOException exp) // compilation error
{
}
catch(FileNoFoundException exp) // Need to be catched
// first before IOException
// Unreachable catch block for FileNotFoundException.
It is already handled by the catch block for IOException
{
}
42. If there is an overriding method in the sub class and this method throws an
exception in the super class then it must throw the same exception which it throws
in the super class or throw an exception which is a sub class of the exception which
it throws in the super class.
Ex.
class ABC
{
public void printABC() throws MyException
{}
}
class XYZ extends ABC
{
// no compilation error
48. Run method of threads doesn't throws any checked exceptions but it may throw any
runtime exception
class ABC implements Runnable
{
public void run() throws Exception // compilation error
}
class ABC implements Runnable
{
public void run() throws RuntimeException // NO ERRORS
public void run() throws ArrayIndexOutOfBoundsException // NO ERRORS
}
49. Assertion
provide a convenient mechanism for verifying that a class's method are called
correctly and used commonly to check
1. Preconditions
2. Post conditions
3. Class invariants (a constraint on a class's state that must be met before and after
execution of any non-private method of a class).
ex. assert Exp1;
assert Exp1:Exp2;
// Exp1 must be boolean type
// Exp2 may have any type;
50. Parameters passing in java
In java parameters passing is by value BUT if you pass a reference the jvm makes
a copy of the reference (You can use it inside function but you cannot assign it
another object).
class Value
{
public int i = 15;
}
public class Test
{
public static void main(String[] args)
{
Test t = new Test();
t.first();
}
public void first()
{
int i = 5;
Value v = new Value();
v.i = 25;
second(v,i);
System.out.println(v.i); // prints 20 the last value assigned to v.i in
//
second() function
}
public void second(Value v, int i)
{
i = 0;
v.i = 20;
Value val = new Value();
v = val;
// ok no compilation error but visible inside function only
System.out.println(v.i); // prints 15 because v assigned to a new object
}
}
51. instanceof used to test type of objects not references
public class Test
{
static Test t1;
public static void main(String[] args)
{
if ( t2 instanceof Test)
{
System.out.println("t2 instanceof Test = true"); // will be printed because t2
// holds an object
}
}
}
// Example 2
class Cup
{
}
class PassionCup
{}
in main
Cup c = new PassionCup();
PassionCup pc = new PassionCup();
if ( c instance of PassionCup )
{
System.out.println("c instanceof PassionCup is true"); // will be printed because instanceof
// test objects not references
}
if ( pc instanceof Cup )
{
System.out.println("pc instanceof Cup is true"); // will be printed because of
// PassionCup extends Cup
}
Ex.
Integer
Integer
Integer
Integer
i1 = 2;
i2 = 2;
i3 = 200;
i4 = 200;
because there is no setters in this class, once an object is created you cannot modify
it
54. Final classes cannot be extended and final methods cannot be overridden
{
private static final long serialVersionUID = 1;
int x = 20;
}
if you create and object ABC myObject = new ABC(); and wrote it to a file.
and you add another data to ABC class
class ABC implements Serializable
{
private static final long serialVersionUID = 1;
int x = 20;
int y = 300;
}
Now if you need to read the stored old object from file the compiler checks
if serialVersionUID of the stored object is equal to serialVersionUID of the new class
the compiler reads the old object and initialize the new features to their default
vales (y will be initialized to 0 NOT 300 )
58. Objects of some system-level classes are not serializable
59. Threads
- Single threaded java program has one entry point (main function) and one exit
point.
- Multi-threaded java program has one entry point (main function) and multiple end
points.
60. A thread can enter the waiting state by the following ways:
1. Invoking its sleep() method,
2. By blocking on I/O
3. By unsuccessfully attempting to acquire an objects lock
4. By invoking an objects wait() method.
5. It can also enter the waiting state by invoking its (deprecated) suspend() method.
61. What is the difference between preemptive scheduling and time slicing?
Under preemptive scheduling, the highest priority task executes until it enters the
waiting or dead states or a higher priority task comes into existence. Under time
slicing, a task executes for a predefined slice of time and then re-enters the pool of
ready tasks. The scheduler then determines which task should execute next, based
on priority and other factors.
62. What invokes a threads run() method?
After a thread is started, via its start() method of the Thread class, the JVM invokes
the threads run() method when the thread is initially executed.
63. What is daemon thread and which method is used to create the daemon thread?
Daemon threads are threads with low priority and runs in the back ground doing the
garbage collection operation for the java runtime system. The setDaemon() method
is used to create a daemon thread. These threads run without the intervention of
the user. To determine if a thread is a daemon thread, use the accessor method
isDaemon()
When a standalone application is run then as long as any user threads are active the
JVM cannot terminate, otherwise the JVM terminates along with any daemon
threads which might be active. Thus a daemon thread is at the mercy of the runtime
system. Daemon threads exist only to serve user threads.
64. How would you implement a thread pool?
public class ThreadPool implements ThreadPoolInt
This class is an generic implementation of a thread pool, which takes the following
input
a) Size of the pool to be constructed
b) Name of the class which implements Runnable and constructs a thread pool with
active threads that are waiting for activation. Once the threads have finished
processing they come back and wait once again in the pool.
This thread pool engine can be locked i.e. if some internal operation is performed on
the pool then it is preferable that the thread engine be locked. Locking ensures that
no new threads are issued by the engine. However, the currently executing threads
are allowed to continue till they come back to the passivePool.
65. Is there a separate stack for each thread in Java?
Yes. Every thread maintains its own separate stack, called Runtime Stack but they
share the same memory. Elements of the stack are the method invocations,
called activation records or stack frame. The activation record contains pertinent
information about a method like local variables.
66.
67. How you can run Garbage collection?
I can run GC through calling System.gc() or Runtime.getRuntime().gc();
but this didn't guarantee that GC will run it only put its thread in ready state.
GC informs the object when it is about destroying it by calling its finalize() method
68. Reflection
Reflection is commonly used by programs which require the ability to examine or
modify the runtime behavior of applications running in the Java virtual machine.
see Class,Method, Constructor,Member to know the attributes ,methods and
constructors of an object in runtime
69. Collections
Set - didn't contain duplicates and may contain at most one null value.
- A Set stores elements in an unordered way and does not contain duplicate elements.
Map is set of objects that map key with value, cannot contain duplicate keys
List - set of elements that maintain its insertion order.
- stores elements in an ordered way but may contain duplicate elements.
70. Generics
An enhancement to the type system that supports operations on objects of various
types while providing compile-time type safety.
It adds compile-time type safety to the Collections Framework and eliminates the
drudgery of casting.
Ex.
ArrayList<String> myList = new ArrayList<String>();
the previous generics restrict the type of objects in this ArrayList to String at compile time
and prevent casting Objects to String.
}
ArrayList<Object> list1 = new ArrayList<Object>();
ArrayList<String> list2 = new ArrayList<String>();
when calling printCollection function
printCollection(list1); // ok no errors
printCollection(list2); // ok no errors
71. Iterator : Enables you to cycle through a collection in the forward direction only, for
obtaining or removing elements
ListIterator : It extends Iterator, allow bidirectional traversal of list and the
modification of elements.
72. Properties class
The properties class is a subclass of Hashtable that can be read from or written to a
stream. It also provides the capability to specify a set of default values to be used.
73. Enumeration: It is series of elements. It can be use to enumerate through the
elements of a vector, keys or values of a hashtable. You cannot remove elements
from Enumeration.
74. What method should the key class of Hashmap override?
The methods to override are equals() and hashCode().
75. What is the difference between Enumeration and Iterator?
The functionality of Enumeration interface is duplicated by the Iterator interface.
Iterator has a remove() method while Enumeration doesnt. Enumeration acts as
Read-only interface, because it has the methods only to traverse and fetch the
objects, where as using Iterator we can manipulate the objects also like adding and
removing the objects.
So Enumeration is used whenever we want to make Collection objects as Read-only.
76.
77. Shadowing(Hiding)
A variable is shadowed if there is another variable with the same name that is closer
in scope. In other words, referring to the variable by name will use the one closest in
scope , the one in the outer scope is shadowed.
Ex.1
class A
{
String name="A";
String getName()
{
return name;
}
}
class B extends A
{
String name="B";
String getName()
{
return name;
}
}
A a = new B();
System.out.println(a.getName());
Ex.2
class Outer
{
class Inner
{
void print()
{ System.out.println("Inner class"); }
}
void printMessage()
{
class Inner
{
void print()
{ System.out.println("Local Inner class"); }
}
Inner in = new Inner();
The idea is that even if the class does not implement the interface, but one of its
subclass might. If the actually object class does not implement the interface then
The compiler knows at compile time exactly what interfaces are implemented by the
final class. If the compiler can determine at compile time that the final class can
never be instanceof the interface, that's a compile time error.
Static with null references
Ex.
public class Test
{
static String name="Farag";
static Test getName()
{
System.out.println("Getting Name");
return null;
}
public static void main(String[] args)
{
System.out.println(getName().name); // it will executes without NullPointerException
}
}
when getName() returns null reference and calling static variable name using this
reference the compiler recognizes that static variable name is not associated with an
object so it will execute it without throwing NullPointerException
casting array of primitives to array of objects.
Ex.
Object c = new long[4];
// OK
Object[] c1 = new Long[4]; // OK
Object[] c = new long[4]; // compilation error cannot convert from long[] to Object[]
ArrayList
Not synchronized
Implement the List interface.
implemented using dynamically resizable
arrays
providing fast random access and fast
traversal
data is retrieved using the get() method
has no default size
HashMap
Store null values
Ex. hm.put("f",null); compiles and runs OK
without exceptions
Not synchronized
allows null values as key and value
does not guarantee that the order of the
map will remain constant over time.
enumerator for the Hashtable isnt fail- Iterator in the HashMap is fail-safe
safe
can be synchronized by
Map m =
Collections.synchronizeMap(hashMap);
83. Fail-safe is relevant from the context of iterators. If an iterator has been created on
a collection object and some other thread tries to modify the collection object
structurally, a concurrent modification exception will be thrown. It is possible for
other threads though to invoke set method since it doesnt modify the collection
structurally. However, if prior to calling set, the collection has been modified
structurally, IllegalArgumentException will be thrown.
84. String pooling & computation
if you create String as String s="my string"; the JVM checks the string literal pool first. If the
string already exists in the pool, a reference to the pooled instance returned. If the string
does not exist in the pool, a new String object instantiates, then it is placed in the pool.
Concatenation of constant Strings computed in compile time.
Concatenating string expressions is computed at runtime.
Ex.
String hello = "Hello";
String lo = "lo";
System.out.println( hello == ( "Hel" + "lo") ); // prints true (pool computed at compile time)
86. DataSource
DataSource
a DataSource object has properties that
identify and describe the data source it
represents
Work with JNDI and managed separately
from application (Ex. by Application Server)
An application does not need to hardcode
driver information
Connection pooling and distributed
DriverManager
transactions
No distributed transactions
87.
88. What is the difference between DOM and SAX parsers
DOM
Object based
Creates tree of xml in memory
Read/write
SAX
Event Based
Don't so it is faster
Read only
89. Weak reference is one that does not prevent the referenced object from being
garbage collected.
You might use them to manage a HashMap to look up a cache of objects.
90. public class Test
{
public void print(String match)
{
System.out.println("--== String ==--");
}
public void print(StringBuffer match)
{
System.out.println("--== String Buffer ==--");
}
public static void main(String[] args)
{
Test t = new Test();
t. print (null); // Compilation error The method match(String) is ambiguous
}
}
91. public class Test
{
public void print(Object match)
{
System.out.println("--== Object ==--");
}
public void print(String match)
{
System.out.println("--== String ==--");
}
public static void main(String[] args)
{
Test t = new Test();
t. print (null); // will print --== String ==-}
}
92. A hidden class (static) method can be invoked by using a reference whose type
is the class that actually contains the declaration of the method. In this respect,
hiding of static methods is different from overriding of instance methods.
The example:
class Super {
static String greeting() {
return "Goodnight";
}
String name() {
return "Farag";
}
}
class Sub extends Super {
static String greeting() {
return "Hello";
}
String name() {
return "Ali";
}
}
public class Test {
public static void main(String[] args) {
Super s = new Sub();
// Super has the declaration of static method
System.out.println(s.greeting() + ", " + s.name());
// prints Goodnight, Ali
}
}
Here, a compile-time error occurs for the second invocation of setColor, because
no applicable method can be found at compile time. The type of the literal 37 is
int, and int cannot be converted to byte by method invocation conversion.
96. Overloading Ambiguity
class Point
{
int x, y;
}
class ColoredPoint extends Point
{
int color;
}
class Test
{
static void test(ColoredPoint p, Point q)
{
System.out.println("(ColoredPoint, Point)");
}
static void test(Point p, ColoredPoint q) {
System.out.println("(Point, ColoredPoint)");
}
public static void main(String[] args) {
ColoredPoint cp = new ColoredPoint();
test(cp, cp); // compile-time error
}
}
This example produces an error at compile time. The problem is that there are two
declarations of test that are applicable and accessible, and neither is more specific
than the other. Therefore, the method invocation is ambiguous.
Solutions is to add third method
static void test(ColoredPoint p, ColoredPoint q)
{
System.out.println("(ColoredPoint, ColoredPoint)");
}
===================================================================
General Questions(allapplabs)
100.
If I do not provide any arguments on the command line, then the String array
of Main method will be empty or null?
It is empty. But not null.
Ex.
class Test
{
public static void main(String[] args)
{
System.out.println(args.length); // if you run with java Test
// it will print 0
}
}
101.
Can I import same package/class twice? Will the JVM load the package twice
at runtime?
One can import the same package or same class multiple times. Neither compiler nor
JVM complains abt it. And the JVM will internally load the class only once no matter
how many times you import the same class.
102.
Does importing a package imports the subpackages as well? e.g. Does
importing com.MyTest.* also import com.MyTest.UnitTests.*?
No you will have to import the subpackages explicitly. Importing com.MyTest.* will
import classes in the package MyTest only. It will not import any class in any of it's
subpackage.
103.
Can main method be declared final?
Yes, the main method can be declared final, in addition to being public static.
104.
105.
S
106.
S
107.
S
108.
A
109.
110.
111.
To be seen later
Thread.setDefaultUncaughtExceptionHandler(new
Thread.UncaughtExceptionHandler()
References
1. The Java Language Specification, Third Edition
http://java.sun.com/docs/books/jls/
2. http://www.allapplabs.com/
3. Java community process
http://jcp.org/en/jsr/platform?listBy=2&listByType=platform
4. JAVA Docs
5. http://www.interview-questions-java.com/
6. http://java.boot.by/scjp-tiger/index.html
7. Certification books and sites
8.