Subscribe to Java/SCJP        RSS Feed
-----

SCJP Notes - Part 2

Icon Leave Comment
1) Hashtable and Hashmap are different in the sense that Hashmap is unsynchronized and permits nulls as keys as well as values.
a. In case the iteration performance is important, keep the capacity/size small because the time for iteration is proportional to capacity + size. However get() and put() have constant time performance.
b. The load factor and initial capacity effect the performance of hashmap. When the number of entries in the hashmap exceed the product of load factor and current capacity, the hashmap is rehashed so as to have twice the number of buckets. A value of 0.75 is for load factor is good tradeoff between time and space cost.
c. The expected number of entries should be taken into account when setting the initial capacity, so as to minimize the number of rehash operations. If the initial capacity is greater than the number of entries divided by the load factor, no rehash will ever occur.
d. The parameterized constructors allow for setting the initial capacity and/or load factor.
e. The hashmap is unsynchronized for structural changes. Collections.synchronizedMap should be used for synchronized access.
f. The iterator returned by hashmap is fail-fast which means that if the map is modified by any means other than the iterator’s modification methods, the iterator throws ConcurrentModificationException. However, the fail fast behaviour is not guaranteed.
g. The put() method returns null if there is no mapping for the key or null was stored as the value for that key otherwise it returns the previous value of the key. Similar is the case with get(). The containsKey() method may be used to distinguish between the cases when there is no key with specified name and when null is stored as value for the key.
h. The implementation class which wants to leave out some operation, simply throws UnsupportedOperationException in that method.

2) switch expects an argument of type int. But due to auto casting short, byte, char also work.

3) strictfp used in front of method or class indicates that floating-point numbers will follow FP-strict rules in all expressions.

4) Even the order of arguments matters when overriding a method. (Not overriden if order changed)

5) Object reference and local variables are stored on stack.

6) IS a relationship is inheritance and HAS a relationship is composition (One class has an object of other as its member)

7) The interfaces without a method are:
a. Serializable
b. Cloneable
c. Remote

8) getClass(), notify(), notifyAll() and wait() are declared as final in the object class.

9) Implement only the abstract methods of abstract class. If an abstract method is present, the class itself must be abstract

10) boolean and char as return types can’t be typecast to any other form.

11) Declared type Legal return types
byte byte
short byte,short
int byte,short,int
long byte,short,int,long
float byte,short,int,long,float
double byte,short,int,long,float,double

Notice that a 32 bit float can be returned as 64 bit long. This is because the float numbers can be represented exponentially.

12) String return type declaration means that no other object than String can be returned because String is a final class and hence no class can subclass it.

13) a. byte[][] d = {{1}}; //valid
b. byte[1][1] d = ({1}.{1}}; //invalid
c. byte[1][1] d = {1}; //invalid
d. byte[1][1] d = new byte[][]; //invalid
e. byte[2][] d = new byte[][]; //invalid
f. conclusion: the size of array can’t be specified when declaring the array.
g. byte[][] d = new byte[1][] ; declares multidimensional array. Compiler expects each element of d to be of type byte[]. A value of primitive type can be accessed by using the notation d[1][1]
h. int[][] multidim = new int[5][4]; //valid
int[][] multidim = new int[5][4][]; //valid
int[][] multidim = new int[5][][4]; //invalid

14) A method returning an array can be declared as
String getNames()[] {} //valid
String[] getNames() {} //valid
Strinf getNames[]() {} //invalid

15) The array object’s size can be any expression but the value of the expression should be known at runtime.

16) Literal is a type of value and the behavior of the value is determined by the type of literal.

17)The non-primitives which can be used as literals are String and array

18)Signed literals are stored in 2’s complement form

19)A value will be evaluated as non-integer if either it has decimal point or the letter e or E (denoting the exponent)

20)All java keywords are always in lower case

21)Some hard to remember keywords are const, goto, strictfp and volatile

22)Identifiers can start with a-z,A-Z,_,$

23)_ and $ are the only non-unicode characters that can start an identifier.

24)Identifiers can have _,$,letters and digits in it.

25)The keywords in java are:
1. public 2. protected 3. private 4. final 5.abstract 6. static 7. transient 8.volatile 9. synchronized 10. native 11. switch 12. case 13. break 14. continue 15 for 16 while 17 do 18 if 19 else 20 try 21 catch 22 throw 23 throws 24 finally 25 extends 26 implements 27 interface 28 class 29 void 30 int 31 short 32 byte 33 long 34 float 35 double 36 instanceof 37 strictfp
38. this 39 super 40 import 41 package 42 return 43 new 44 true 45 false 46 null 47 const 48 goto 49 assert 50 default 51 boolean 52 const
There are a total of 52 reserved words and keywords. Of these const, goto and three literals (true, false and null) are not keywords.The keywords const and goto are reserved even though they are not in use. The keywords true, false and null are boolean literals. assert is a keywords as per java 1.4
Technically speaking, reserved words are identifiers that can be used only as
keyword.

26)instanceof operator’s result is tried to be computed at compile time only because hierarchy is known to the compiler. The purpose of this operator is to determine whether an object belongs to a given class (or any of the superclass).

27)It is legal to compare a character primitive with any number

28)Shift operators can take place on all integers, regardless of the base they are displayed in (octal, decimal or hexadecimal).

29)The sign bit is copied to the right and is kept same when using the >> operator but not when using the >>> operator.

30)&, |, ^ and ~ are bitwise operators

31)The || and && operators work with boolean operands

32)The | and & operators work only with integer and boolean values

33)When an explicit cast is performed on a floating point number, it causes to lose all the digits after the decimal.

34)java starts counting up from -128 when we go over 127 for a byte.

35)compile time error comes when assigning superclass object to subclass reference. Runtime error comes after explicit casting when the reference and object are incompatible.

36)The == operator tests whether the object referenced by reference variable is same. The default behavior of equals() is also same as = = operator.

37)
String java = “Java”;
	  String va = “va”;
	  Sysout(java == “java”); 
			Sysout(other.java == java);
		  Sysout(java ==  (“Ja” + “va”);
		  Sysout(java ==  (“Ja” + va);
Class Other {static String java = “Java”;}


37)The getConnection() method in DriverManager class is synchronized

38)Type 1 are JDBC-ODBC drivers
Type 2 are native API driver
Type 3 driver JDBC calls are first translated to DBMS independent net protocol and then translated to DBMS specific protocol.
Type 4 drivers are pure java classes that directly interact with the DBMS are quite fast.

39)The DataSource interface was introduced in JAVA 2.0 to support connection pooling and distributed transactions.

40)The JDBC url has three parts: jdbc:<subprotocol>:<subname>

41)The statement object can be used to pass SQL commands to the database.

42)The prepared statement can be passed parameters and hence can be used with different values and is usually faster due to precompilation.

43)The callable statement can be used to invoke stored procedures

44)The different versions of execute statement are:
a. executeUpdate(String sql) Statements which return a count
b. executeQuery(String sql) Statements which return single resultset
c. execute(String sql) Statements which return multiple result sets

45)While using the statement object, the query is passed when it has to be executed. But for prepared statement the query is passed when creating the statement object from the connection object which helps in pre-compilation.

46)Callable statement extends prepared statement

47)Callable statement can also take output parameters too. But that parameter must be registered using registerOutParameter() method before calling the execute method. E.g callstmt.registerOutParameter(3, java.sql.Types.VARCHAR); if the third parameter is supposed to be the OUT parameter.

48)The commit occurs when the statement completes or the next execute occurs, whichever comes first. In the case of statements returning a ResultSet, the statement completes when the last row of the ResultSet has been retrieved or the ResultSet has been closed. In advanced cases, a single statement may return multiple results as well as output parameter values. Here, the commit occurs when all results and output parameter -values have been retrieved.

49)
Using a PreparedStatement
package java_databases.ch04;
import java.sql.*;
public class PreparedStmt{
public static void main(String args[]){
int qty;
float cost;
String name;
String desc;
String query = ("SELECT * FROM Stock WHERE Item_Number = ?";
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con =
DriverManager.getConnection ("jdbc:odbc:Inventory");
PreparedStatement pstmt = con.prepareStatement(query);
pstmt.setInt(1, 2);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
name = rs.getString("Name");
desc = rs.getString("Description");
qty = rs.getInt("Qty");
cost = rs.getFloat("Cost");
System.out.println(name+", "+desc+"\t: "+qty+"\[email protected] $"+cost);
}
}
catch(ClassNotFoundException e){
e.printStackTrace();
}
catch(SQLException e){
e.printStackTrace();
}
}
}


50)You can explicitly convert an input parameter to a particular JDBC type by using the method setObject. This method can take a third argument, which specifies the target JDBC type. The driver converts the Java Object to the specified JDBC type before sending it to the database. If no JDBC type is given, the driver will simply map the Java Object to its default JDBC type.

51)The setNull method allows you to send a NULL value to the database as an IN
parameter. You can also send a NULL to the database by passing a Java null value to a setXXX method.

52) Auto Boxing and Auto Unboxing
g(int i) and g(Integer i) are different as while overriding autoboxing is ignored.
g(Integer i), g(Number i) and g(Object i) are all overridden methods as Integer is a type of Number and Number is a type of Object

53)LifeCycle of Servlet
a) The init() method is called once for each servlet and is a good place for global initializations.
b The service() method is called for each incoming request for the servlet and is good place for local initializations.
c) The doGet and doPost methods are called depending upon the type of request.
d) When the container is going to shut down. The destroy method is called which can be used to clean any initializations and freeing up resources.
e) Keep the shared data minimum and synchronize the block using any shared data. Don’t use the SingleThreadModel interface.
f) Why must the init() method call super.init(config)? The reason is that a servlet is passed its ServletConfig instance in its init() method, but not in any other method. This could cause a problem for a servlet that needs to access its config object outside of init(). Calling super.init(config) solves this problem by invoking the init() method of GenericServlet, which saves a reference to the config object for future use
g) The purpose of init() method can be solved by a constructor but java 1.1 didn’t allow constructors for dynamically loaded java classes. Moreover javax.servlet.Servlet interface can’t have a constructor.

0 Comments On This Entry

 

January 2022

S M T W T F S
      1
2345678
9101112131415
161718192021 22
23242526272829
3031     

Recent Entries

Recent Comments

Search My Blog

15 user(s) viewing

15 Guests
0 member(s)
0 anonymous member(s)