JAVA notes Prepared by Farag Zakaria Safy Saad Master Student @ Cairo University Faculty of Computers & Information ITI-JAVA Intake 30 [email protected]This is my own study notes; please keep free to send me any errors exist or any other top you need to add. 1. Key word & reserved word key word is a word whose meaning is defined by the programming language as int,… Reserved word they have no meaning by programming language as goto,const You cannot use any key word or reserved word in defining variables 2. Allowed access modifiers for the public class are public , final , abstract , strictfp only 3. Defining memory heap size when running java applications -Xms32m defines minimum heap space as 32 mega -Xmx32m defines maximum heap space as 32 mega. Ex. java -Xms32m –Xmx512m Test // run Test class with minimum heap size 32mega and maximum heap size 512 mega bytes 4. Garbage collection JVM parameters -XX:+UseSerialGC run serial garbage collection. -XX:+UseParallelGC runs parallel garbage collection. -XX:+UseParallelOldGC runs parallel compact collector -XX:ParallelCMSThreads=n runs concurrent Mark and Sweep collector with n threads. -XX:+UseConcMarkSweepGC runs Concurrent Mark and Sweep collector. 5. strictfp Marking aclass as strictfp means that any method code in the class will conform to the IEEE 754 standard rules for floating point s 6. All wrapper classes have no default constructor Wrapper classes constructors are WrapperType(Type) , Wrapper(String). see next example. 7. Byte wrapper class constructors are Byte(byte), Byte(String) ex. Byte b = new Byte(); // compilation error undefined constructor Byte() Byte b = new Byte(3); // compilation error Byte b = new Byte((byte)3); // true Byte b = 21; // true
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
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. Exception’s 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
{
public void printABC() // it must throws MyException or any child of it or throws
// None or any runtime exception
}
43. Volatile
A field may be declared volatile, in which case the Java memory model ensures
that all threads see a consistent value for the variable.
When any thread accesses volatile fields it performs automatic synchronization
(automatic locking).
A compile-time error occurs if a final variable is also declared volatile.
Ex.
class ABC
{
final volatile int x = 10; // compilation error
}
44. Static
If the keyword this or the keyword super occurs in an initialization expression for
a class variable, then a compile-time error occurs.
Ex.
class ABC
{
int x = 10;
}
class XYZ extends ABC
{
int a = 10;
static int z = super.x; // compilation error (super and this can't be used in static context)
static int y = this.a; // compilation error
}
45. Initializers for Instance Variables (related to classes)
Initialization expressions for instance variables may use the simple name of any
static variable declared in or inherited by the class, even one whose declaration
occurs textually later.
Ex.1
class Test
{
float f = j; // no compilation error
static int j = 10;
}
Ex.2
class Test
{
int i = j; // compilation error -- incorrect forward reference
int j = 10;
}
46. Abstract Methods
1. It is a compile-time error for a private method to be declared abstract.
2. It is a compile-time error for a static method to be declared abstract.
3. It is a compile-time error for a final method to be declared abstract.
4. An abstract class can override an abstract method by providing another
abstract method declaration.
47. Native Methods
- A method that is native is implemented in platform-dependent code(in another
programming language).
- A compile-time error occurs if a native method is declared abstract. Ex.
class Test
{
abstract native void print(); // compile 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)
{
Test t2 = new Test();
if ( t1 instanceof Test)
{
System.out.println(" t1 instanceof Test = true");
}
else
{
System.out.println(" t1 instanceof Test = false"); // will be printed
// because t1 is a reference (doesn't refer to any object)
}
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
}
52. Auto boxing
Boxing is the automatic assignment of a primitive value to a compatible wrapper
type.
Ex. Integer x = 1;
Unboxing is the automatic extraction of a wrapped value.
Integer z = 1;
int y = z;
Boxing pool
If the value that is being boxed is true, false, a byte, a char in the range
\u0000 to \u007f, or an int or short number between -128 and 127 then the
object is pooled.
Ex.
Integer i1 = 2;
Integer i2 = 2;
Integer i3 = 200;
Integer i4 = 200;
System.out.println( i1 == i2 ); // will print true because objects are not pooled
System.out.println( i3 == i4 ); // will print false because objects are not pooled so
references are not equal.
53. Mutable & Immutable
Mutable once the object is created you can edit it.
Immutable once the object is created you can't edit or modify it.
Ex. String contains immutable string
StringBuffer contains mutable strings and is thread safe (all of its methods
are synchronized).
StringBuffer sb = "abc"; // compilation error cannot convert from String to StringBuffer
StringBuilder contains mutable strings but is not thread safe.
(faster than StringBuffer)
StringBuilder sb = "ab" ; // compilation error cannot convert from String to StringBuilder
To apply Immutable concept to your own defined objects.
Ex. if you have class Person with first name and last name and you need to make
sure that all objects of this class are immutable see the following class code
class Person
{
String firstName;
String lastName;
public Person(String firstName, String lastName)
{
this.firstName = firstName;
this.lastName = lastName;
}
String getFirstName()
{
return firstName;
}
String getLastName()
{
return lastName;
}
}
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
55. The class must be abstract if
1. The class has one or more abstract methods.
2. The class inherits abstract methods and doesn't provide an implement to any of
them.
3. Class implements an interface and don't implement every method.
56. Static features (static variables, static methods)
Static features belong to the class not to its instances so it exists before any object
(instance) of the class is created.
Static Methods
1. May access only the static data of its class, it may not access non-static data.
2. May call only the static methods of its class, it may not call non-static methods.
3. Static methods has no this pointer (reference).
4. Static methods may not be overridden by non-static methods
57. Serialization is the process of storing the state of a java object by converting it to
byte stream.
Rules of serialization
1. Static fields are not serialized because they are not belonging to any object.
2. Transient fields are not serialized.
3. Fields from the base class are handled only if those are serializable.
What is preserved when an object is serialized?
1. Only the object's data are preserved.
2. Methods and constructors are not part of the serialized stream.
3. Class information is included.
What is the difference between serializable and externalizable
Serializable -- provides the default serialization mechanism of the compiler(JVM).
Externalizable -- provides customized serialization mechanism which allows you to
implement your own protocols through the methods
writeExternal (…) and readExternal (…)
Version Control
All serialized objects are automatically assigned a unique identifier.
If the identifier of the class doesn't equal the identifier of the serialized object a
java.io.InvalidClassException is thrown.
Ex. class ABC implements Serializable
{
int x = 20;
}
then you create an object ABC myObject = new ABC() ;
and wrote it to a file the compiler assigns default value for hidden variable
serialVersionUID .
And after that another variable is added to the class.
class ABC implements Serializable
{
int x = 20;
int y = 300;
}
-- at this point the compiler assigns another value to serialVersionUID
if you tried to read myObject now java.io.InvalidClassException will be thrown
To prevent this exception you should add serialVersionUID to ABC class
Ex.
class ABC implements Serializable
{
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 object’s lock
4. By invoking an object’s 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 thread’s run() method?
After a thread is started, via its start() method of the Thread class, the JVM invokes
the thread’s 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.
Sub-typing is not allowed in generics
Ex. ArrayList<Object> myList = new ArrayList<String>(); // compile error
// cannot covert from ArrayList<String> to ArrayList<Object>
Inheritance relationship is maintained between collection elements.
Ex.
class A
{}
class B extends A
{}
class C extends B
{}
ArrayList<A> myList = new ArrayList<A>();
ArrayList<A> myList = new ArrayList<B>(); // compilation errors
myList.add(new A()); // ok no errors
myList.add(new B()); // ok no errors
myList.add(new C()); // ok no errors
Wildcards ? means collection of unknown type
Ex.
public void printCollection(ArrayList<Object> list)
{}
ArrayList<Object> list1 = new ArrayList<Object>();
ArrayList<String> list2 = new ArrayList<String>();
when calling printCollection function
printCollection(list1); // ok no errors
printCollection(list2); // compilation error
to prevent the last error see the following code
public void printCollection(ArrayList<?> list) // ? maps to any type
{
// the only allowed here is to read elements of list as Objects
// add elements to list is not allowed(list.add(new Object()) gives compilation errors)
}
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
Bounded wildcards <? extends ...>
bounds unknown type to be subtype of another type
Ex.
public void printCollection(ArrayList<? extends Object> list) // maps to any subtype of Object
{
// the only allowed here is to read elements of list as Objects
// add elements to list is not allowed(list.add(new Object()) gives compilation errors)
}
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 doesn’t. 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"; // shadows the name variable of class A
String getName() // really this is the same as overriding but for variables
and declarations
{
return name;
}
}
A a = new B();
System.out.println(a.getName()); // will print B due to shadowing
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(); // due to shadowing this is the Inner class inside this
method
in.print(); //// will print Local Inner class
}
}
78. Double indirection
in most JVMs, the reference value is actually the address of and address. The second
address refers to the real data.
79. Code exercises
difference between null and "" in string
String s = null;
s+= "abc";
System.out.println(s); /// will print nullabc;
String s = "";
s+= "abc";
System.out.println(s); /// will print abc;
Division by zero
Dividing integer by zero
int i=12;
System.out.println( i/0 ); // will give ArithmaticException division by zero
// with integers
Dividing floats and doubles by zero
double d = 12;
System.out.println( d/0 ); // gives Infinity with floating and double variables
Division remainder with floats and doubles
int i=12;
System.out.println( i%0 ); // will give ArithmaticException division by zero
// with integers
Division remainder with floats and doubles
double d = 12;
System.out.println( d%0 ); // gives NaN with floating and double variables
Casting Object to interface
Ex.1
interface MyInterface
{
}
class MyObject
{
}
in main()
MyObject o = new MyObject();
MyInterface myInterface = (MyInterface)o; // no compilation errors but it will throw
// ClassCastException at runtime
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
you will get a ClassCastException error at runtime.
--- create or replace procedure abc(custId in number, custName out nvarchar2(100))
86. DataSource
DataSource DriverManager 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)
Managed by the application code
An application does not need to hardcode driver information
Driver information are hardcoded in application code
Connection pooling and distributed No connection pooling
transactions No distributed transactions
87.
88. What is the difference between DOM and SAX parsers
DOM SAX
Object based Event Based
Creates tree of xml in memory Don't so it is faster
Read/write 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 }
}
93. final volatile int x; // compile time error
// The field x can be either final or volatile, not both
94. public class Doubler {
static int two() { return two(1); } private static int two(int i) { return 2*i; } }
class Test extends Doubler {
public static long two(long j) {return j+j; } public static void main(String[] args) { System.out.println(two(3)); System.out.println(Doubler.two(3)); // compile-time error // The method two(int) from the type Doubler is not visible }
}
95. class ColoredPoint { int x, y; byte color; void setColor(byte color) { this.color = color; }
} class Test {
public static void main(String[] args) {
ColoredPoint cp = new ColoredPoint(); byte color = 37; cp.setColor(color); cp.setColor(37); // compile-time error
} }
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 {
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)"); }