Saturday, 30 April 2016
Some Questions
You might be asked the following questions.
(1) what is Abstract syntax tree?
(2) Which Linux command being used to show the remaining disk space?
(3) What is cache validation?
(4) What applying singleton pattern?
(5)what is Recursion
(6) Why using hash-map searching is faster?
(7) What is big(O) notation?
(8) Recursion
(9) what mean the keyword "strictfp" in java?
Friday, 1 April 2016
OCAJP Test Notes
Reference variable is used to store a reference, which points to an instance.
Primitive type: byte(8), char(16), short(16bit), int(32), long(64), and floating float(32), double(64), etc
Java use four type integers byte, short, int, and long; and two type of floating-point numbers: float(single precision) and double(double precision). Normally you should use the double type, because it is more accurate than the float type.
suffix: float(F) double(D); and long(L)
octal(0) and hex(0xFFFF) literals:
Type casting is required when assigning a value to a variable of a smaller type range, for instance,
double d = 4.5;
int i = (int i)d
Primitive Wrapper Classes
Each primitive has its reference type, i.e. a wrapper class extended from Number.
Integer a = 1;
Float b = 1.0f;
Can you compare them in a conditional statement?
No. for they have different class type.
Can you use method compareTo() to compare each other?
No. for in the compareTo() method requires the same type of object.
The same principle as applying if(a==b){}; resulting a compilation error, "incompatible types."
However, for the primitive types
int a = 1;
float b = 1.0f;
You may use conditional statement to compare different data types .
Java narrowing primitive convention: applied on the char, byte and short, required to be cast in method invocation.
What happens with the following code?
Short s = new Short(9);
You get a compiling error here. "no suitable constructor", because 9 is considered as a int type.
So, casting
Short s = new Short((short)9);
reference(class): String, Enum, and arrays
In java chained declaring is not allowed. int a = b = c=100 causes a compiling error, for the variable b and c is considered not declared yet. How about this? int a, b, c=100;
Identifier Naming
starting "_" or "$" or any letter; it cannot start with a digit. it cannot be a reserved word; an identifier can be of any length.
$$ is a valid identifier.
int $$ = 0;
if ... else
Switch
Note: switch cannot work with long, float and double. Ensure that expression in any switch statement is not null to prevent a NullPointerException from being thrown.
do{...}while(Boolean condition)
break without label: quit from entire loop block.
break with label: break from the labeled statement block, which contains a loop or loops.
verb(lower case) + (adj. / noun)
Object does have such a constructor, so if Object is the only super-class, there is no problem.Please note: ref. to super class constructor, super() must be put in the first line of the sub-class constructor.
List list = new ArrayList();
VM create an instance ArrayList in the heap memory and gives back the reference value in the list variable;
When the instance has no need any more, then we may set list = null, and inform the GC to recycle this part of resource.
Using "import static package" can even over-skip the class qualifications.
A static block will be first invoked as the class is loaded by JVM, no matter where it has been put in the class. so no matter what, it will be implemented before the constructor. it could has several static block, and they will be implemented automatically according to their occurrence sequence.
Interface
Interface is an protocol defined how a group of classes communicate with external ones. interface could be modified as public or no modifier; as having no modifier it is considered as an interface used only in the current package.
Interface variables and methods, may omit modifier; by default they will be understood as public abstracted methods and "public static final " respectively.
When an interface need adding new abstract methods; it is best to extend from it, thus it won't break existing code. so an interface could extends from many other interfaces. please, an interface cannot implement other interfaces; it doesn't make any sense, for interface cannot instantiate those inherited abstract methods.public interface myinterface{ double PI = 3.14; void setRidus(double r); double getRidus(); }
Sub-classes can inherit fields and methods from the interface, abstract class or normal class.
The instance method could be overridden in sub-class and class fields and method could be hidden in the subclass due to shadowing.
Overriding distinguished by 1) the inheritance, and then must be instance methods. 2) then the same signature and argument(type, sequence and number) 3) return type must be same for the primitive; for the reference type it must be the sub-types. 4) access-modifier must be the same as the super-class.
Method cannot be overridden:
Final method in the super-class cannot be overridden, just like final class cannot be extended.
Static method cannot be overridden, but could be hidden in the sub-class.
Please note: hidden fields/static methods are rarely used.
Virtual Method Invocation:
This principle is only relevant to the overridden instance methods. For hidden class methods, they can be directly referred by real class name; however, for overridden methods are referred is determined by the actual class used to instantiate the reference variable. Meaning that, variable type could be declared as a super-class, but in the run-time it could be instantiated as any sub-class object. So invoking overridden instance methods, requires to watch out the object class type.
JVM calls the appropriate method for the object that is referred to in each variable. It does not call the method that is defined by the variable's type. This behavior is referred to as virtual method invocation and demonstrates an aspect of the important polymorphism features in the Java language.
Super keyword:
For overridden instance methods, the overridden super-class instance methods can be accessed by the super keyword.
Note: In a subclass, you can overload the methods inherited from the super-class. Such overloaded methods neither hide nor override the super-class methods—they are new methods, unique to the subclass.
Why static method cannot be overridden?
Static methods cannot be overridden because method overriding only occurs in the context of dynamic (i.e. run-time) lookup of methods. Static methods (by their name) are looked up statically (i.e. at compile-time).
String class.- protected Object clone() throws CloneNotSupportedExceptionCreates and returns a copy of this object. object must implements clonable interface.
- public boolean equals(Object obj)Indicates whether some other object is "equal to" this one. You have to note this equals only use "==", so it may not fit what your need, so you may override it.
- protected void finalize() throws ThrowableCalled by the garbage collector on an object when garbagecollection determines that there are no more references to the object.
- public final Class getClass()Returns the runtime class of an object.
- public int hashCode()Returns a hash code value for the object.
- public String toString()Returns a string representation of the object.
The hashCode() Method
hashCode() is the object's hash code, which is the object's memory address in hexadecimal. By definition, if two objects are equal, their hash code must also be equal. If you override the equals() method, you change the way two objects are equated and Object's implementation of hashCode() is no longer valid. Therefore, if you override the equals() method, you must also override the hashCode() method as well.abstract.static and final, and they can contain implemented methods.Checked exception means you need to check it.
Unchecked exception means you don't need to check it.
All java exceptions and errors are Throwables.
Checked exception is extended from "Run-time-Exception"
Unchecked exception is extended from "Exception"
If checked exception is not caught, then you need to 'throws' it.
When an error occurs within a method, the method creates an object and hands it off to the runtime system. The object, called an exception object, contains information about the error, including its type and the state of the program when the error occurred. Creating an exception object and handing it to the run-time system is called throwing an exception.
Java generics is introduced from Java 5. The basic purpose behind using generics is to enable you to mark your intent of using a class, method, or interface with a particular data type. Generics add compile-time safety to collections. By this way, a type inconsistency may be found in a early time, rather than in the run time. Generics can be applied on a class, an interface, a method, and even a constructor. They are called generic classes, generic methods, or generic constructors.
For a generic class, formal generic types should be declared after class name;
For a generic method, formal generic type should be declared after access modifier before the return type. This is important, otherwise compiler may don't know what's return type.
for class generics : type parameter inferred from the type argument.
for method generics: type parameter inferred from the real data type.
The type variable can be presented by a wildcard(?); it means it could be any types. Wildcard can be extended from a upper bound type(extends) or a super type of a lower bound type(super).
Queue: ArrayDeque
Linked: keep insertion order, not sorted
Hash: keep no insertion order, not sorted
Tree: keep no insertion order, sorted.
Set: unique, element must be comparable.
Map: keep key value pairs.
Can you put more than one class in one java file?
Yes. the only limitation is you only can have one public class. the rest must be default access.
Super-class has explicitly declare a constructor with arguments, then JVM will automatically provide no non-argument for it. So you need to watch out here, as define a non-argument in the sub-class extended from it. It will cause a compiling error, for the super-class has no a non-argument constructor defined yet.
Is able to declare public static void main(String args[]) in other access modifier?
no, you must declare main class as public. you cannot use protected, default modifier, and private.
final public static void main(String args[])
final means here for the static method cannot be shadowed.
final means for the instance method, it means the method cannot be overridden.
java constant declaring: must be final static int xxx = yyy; the constant must be initialized as declaring, otherwise it will give a compiling error. so what is a constant is? it should be a value that commonly shared by the instances, and it cannot shadowed.
All java arrays are objects, int[] array={1,2,3}; array instanceof Object = true.
If you have a Object object = null; what happens as System.out.println(obejct)?
It will print out 'null'; It won't cause null pointer exception, for there is no operations on the null.
What happens when you print out b.i?
class A{
private int i = 10;
public void f(){}
public void g(){}
}
class B extends A{
public int i = 20;
public void g(){}
}
public class C{
A a = new A();//1
A b = new B();//2
}
No you cannot. for b has been declared as Type A, for the A the i is a private field, not accessible.
static method cannot access instance fields, but only static fields.
instance method can access class field and instance field both.
Keyword final
It can be used to modify class, variable, and method. I think it try to define something it is final; not allowed to be changed.
a final class cannot be extended; a final variable cannot be hidden(??? i didn't see this.), anyway it will be constant; it cannot be assigned a new value; a final field must be initiated as declaring it; a final method cannot be overridden.
final modifier cannot be applied on the constructor, for constructor cannot be inherited.
char, byte, short int are int type, but you need to watch out type narrowing, meaning that when assigning a int number to byte, char, short; requiring casting.
Keywork transient
transient keyword, telling JVM the modified variable is not serialize-able/persisted.
Sunday, 13 March 2016
Interface vs abstract class
Interface is a communication protocol defines how a class of instances interacts with the external world, i.e. other instances. So interface method is about abstract instance methods.
Abstract class is a place to put common attributes and methods of a class in one place. It could be class or instance members.
Interface and abstract class are abstract, so they won't have any implementation. One class can implement several interfaces, depending on how many deceives or channels via which it interacts with the external objects. Abstract class could have implemented method and fields. They are common members of the class or its instances.
Interface can only define constants, and fields defined in the interface are implicitly considered as 'public static final'. Interface abstracted methods can only be defines as public, for they are used as communication to the external.
Abstract class as explained before, as explained it is a common place to put all the common features in one place; so you may define member access, as public, protected, default, and even private.
We can define constant and abstracted method in the interface; in the java 8, we may declare static method also in the interface.
What is Servlet
Servlet sounds like "let/making server do something". Actually, it bind the java class and HTTP request together. Meaning that, it is a common interface and handler, which is able to handle remote request and dispatching to the underlying java class handler, and generate response to the remote caller.
Servlet life cycle, init(), service(), and destroy(). they are implemented by the container.
init() the input parameters extracted from httprequest; service() is the functional handler; when the requested task has been done, then container will call destroy() to terminate servlet.
Wednesday, 16 June 2010
About Java Run Out Perm. Space
What is the memory leak? The dynamically allocated memory has become unreachable.
1) C/C++ is prone to cause memory leak, because it has no auto garbage collection mechanism.
2) JAVA: unbounded memory use, but
There are two types of Memory in JVM: Heap and Permanent.
What Heap for? dynamatically generating instances.
What Permanent for? store the templates, i.e. Classes, but not dynamically used.
So run out the memory of this part, mostly because it has been used out of boundary of the space, at least I think so. So increasing permananent memory from the default of 64mb to 150 mb.
Add java option: -XX:MaxPermSize=150m
Stack memory:
In addition: java vm also manage a stack for the handling local var. and function calls; each thread has its own stack, seen as a private memory. If there is no memory left for storing local var., then java will throw a stack overflow error.
Heap memory:
Java VM maintain a memory space for a common usage for all threads, where all objects are created there. no matter where these class having been instantiated. When heap runs out, then java throws java.lang.OutOfMemoryError.
So there are 3 different kind of memory usage in java. heap perm. and stack.
Monday, 21 September 2009
HttpURLConnection: java.net.ConnectException: Connection timed out
CodeGuru Forums > Java Programming > Java Programming > HttpURLConnection: java.net.ConnectException: Connection timed out:
Click to See Complete Forum and Search --> : HttpURLConnection: java.net.ConnectException: Connection timed out:
vadirajak1
January 11th, 2005, 03:44 AM
Hi,
I am trying to read from a URL and display the contents in an Applet. I am using URL,HttpURLConnection classes. I am consistently getting Connection time out Exception. I am unable to connect. Could any one help me out with this. I have tried some TimeOut handler classes available on the net but still I am getting the same Exception. Please provide your comments if you have come across similar problems before.
Here is the code Iam using
url = new URL((URL)null, str, new HttpTimeoutHandler(15000)); // timeout value in milliseconds
HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
httpConnection.connect();
nputStream is = httpConnection.getInputStream();
Thanks & Regards,
Vadi
cma
January 11th, 2005, 07:57 AM
Can you connect to the server directly, say, using your browser?
cjard
January 11th, 2005, 08:53 AM
connection timeouts occur when:
the IP address for the requested server is successfully found
connection establishment packets are dispatched to the IP address
the destination address deliberately ignores or does not receive them
similar to connection timeout is Connection Refused, but in this case the destination system is actually sending packets back saying "go away, there is no service running on the port you are trying to connect to"
your packets are just being lost.. either the system or some intermediate system is firewalled. follow CMA's advice.. if you cant connect using telnet, a browser or some other app, its a network problem, not a java one
vadirajak1
January 12th, 2005, 01:11 AM
I am able to connect to the url through browser and able to see the data that is there. But when trying to connect through the code, I am getting the connection time out exception. So this must not be a Network/Firewall related issue. Also, the same code is working fine when we tried testing it from the US, but it is giving the timeout Exception when tried from India. Is this a simple time out issue? If so, even some of the time out handlers available on the net are not solving the issue? Can anyone suggest a way out please.
Thanks & Regards,
Vadi
cjard
January 12th, 2005, 07:52 AM
check your browser proxy settings
try using telnet to connect to the same server that youre using in code and the browser:
telnet www.google.com 80
codeguru.com
Copyright 2009 WebMediaBrands Inc., All Rights Reserved.
Friday, 4 September 2009
Java Memory Insufficent
The JVM heap space is where all Java objects are stored, as well as memory used by the garbage collector. Sun recommends increasing this value for server applications,
Large server applications often experience two problems with these
defaults. One is slow startup, because the initial heap is small and
must be resized over many major collections. A more pressing problem
is that the default maximum heap size is unreasonably small for most
server applications.
If an application gobbles up memory until it throws an OutOfMemory exception, or seems to be spending an excessive amount of time doing garbage collection, a heap dump can help track down the source of the problem.
Three type of Insufficent Memory:
1. Heap memory error: when an application creates a new object but the heap does not have sufficient space and cannot be expanded further, and OutOfMemoryError will be thrown with the following error message:
java.lang.OutofMemoryError: Java heap space
2. Non-heap memory error: The permanent generation is a non-heap memory area in the HotSpot VM implementation that stores per-class structure as well as interned strings. When the permanent generation is full, the application will fail to load a class or to allocate an interned string, and an OutOfMemoryError will be thrown with the following error message:
java.lang.OutOfMemoryError: PermGen space
3. Native memory error: The Java Native Interface(JNI) code or the native library of an applicaiton and the JVM implementation allocate memory from the native heap. An OutOfMemoryError will be thrown when an allocation in the native heap fails. For instance, the following error message indicates insufficient swap space, which could be caused by a configuration issue in the operating system or by another process in the system that is consuming much of memory.
java.lang.OutOfMemoryError: request <size> bytes for <reason>. Out of swap space?
Reasons for Insufficent Memory
Momory Leaks: An applicatoin keeps a reference to an object that it no longer needs. Garbage collector cannot free this part of memory.
Finalizers: excessive use of finalizers.
DeadLocks:
Looping Threads:
High Lock Contention:
How to remotely monitoring JVM
1) Opening a monitoring port on the remote Tomcat server, we added following java VM options at the startup script,
Export JAVA_OPTS="$JAVA_OPTS -Dcom.sun.management.jmxremote.port=19993 -Dcom.sun.management.jmxremote.authenticate=
false -Dcom.sun.management.jmxremote.ssl=false"
This requires firewall opening between the local pc and server on port specified 19993.
2) There are two good tools for monitoring JVM, i.e. JConsole and VirtualVM. run these two appliation and login the remote server and the specified port, then you may monitor the VM state.
JConsole is shipped with JDK after version 5. You may easily find it from JAVA_HOME/bin/jconsole.exe
VisualVM is a third party software, which can be download from its official home.
How to Reset Heap Memory Size
Sometime the insuficent memory is just caused by the insufficent heap memory, so it need to reset the memory size.The Java Virtual Machine takes two command line arguments which set the initial and maximum heap sizes:
-Xms and -Xmx. For example if you want to give your Java program needs a 128Mb initial and 256Mb maximum heap size you could launch it as follows:
JAVA_OPTS="-server -Xms128M -Xmx256M"
Set HeapDumpOnOutOfMemoryError Option
set JAVA_OPTS=%JAVA_OPTS% -server -Xms512m -Xmx800m -XX:PermSize=64M -XX:MaxPermSize=128m -Djava.awt.headless=true -XX:+HeapDumpOnOutOfMemoryError -XX:+HeapDumpOnCtrlBreak
A heap dump file will be generated in /bin folder, when out of memory happens.
The -XX:+HeapDumpOnOutOfMemoryError command-line option was introduced in Java SE release
5.0 update 7. This option tells the HotSpot VM to generate a heap dump when the first thread throws a
java.lang.OutOfMemoryError because the Java heap or the permanent generation is full. There is
no overhead in running with this option, and so it can be useful for production systems where
OutOfMemoryError takes a long time to surface.
The heap dump is in HPROF binary format, and so it can be anaylzed by any tool that can import this
format, for example the Heap Analysis Tool (HAT).
By default the heap dump is created in a file called java_pid<pid>.hprof in the working directory
of the VM, where <pid> is the process ID. You can specify an alternative file name or directory with
the -XX:HeapDumpPath= option. For example, -XX:HeapDumpPath=/disk2/dumps will cause the
heap dump to be generated in the /disk2/dumps directory.
How to monitor JVM
I sent several banches of data to the debitorregisterweb, and it seems that there are some heap memory that cannot be released afterwards, the used the heap space increased step by step, where is the gc operation,
How to fix memory leak
http://java.dzone.com/news/how-fix-memory-leaks-java
How profile Java application in VirtualVM
Can Jackson Deserialize Java Time ZonedDateTime
Yes, but must include JSR310. Thus ZonedDateTime can be deserialized directly from JSON response to POJO field. <dependency> <g...
-
The strictfp keyword is used to force the precision of floating point calculations (float or double) in Java conform to IEEE’s 754 standard...
-
In construction. Spring test annotations: @SpringBooTest @DataJpaTest @TestPropertySource @ActiveProfiles @Sql @SpringBootTest It is used f...
-
Testing Controllers @Runwith(SrpingRunner.class) Unit test @Runwith(SrpingRunner.class) @WebMvcTest(SpecificController.class) Integration te...