Você está na página 1de 21

Key Shortcut for Eclipse Imports:

Ctrl

Shift

Java. Lang package is automatically imported in Java. It contains Object, Class,


Exception, Error, String, StringBuilder, StringBuffer.

How can I get the user input in Java?


One of the simplest ways is to use a Scanner object as follows:

Scanner reader = new Scanner(System.in); // Reading from System.in


System.out.println("Enter a number: ");
int n = reader.nextInt(); // Scans the next token of the input as an int.

In brief, == tests if references are equal and equals() tests if values are equal.
Unless you want to check if two strings are the same object, you should always
use equals().

How to convert string to int?


int n = Integer.parseInt("10");

Can we use string for switch statement?


Yes to version 7. From JDK 7, we can use string as switch condition.
Before version 6, we can not use string as switch condition.
// java 7 only!
switch (str.toLowerCase()) {
case "a":
value = 1;
break;
case "b":
value = 2;
break;
}

What will happen if you put return statement or System.exit () on


try or catch block? Will finally block execute?
This is a very popular tricky Java question and it's tricky because many programmers
think that no matter what, but the finally block will always execute. This question
challenge that concept by putting a return statement in the try or catch block or
calling System.exit from try or catch block. Answer of this tricky question in Java

is that finally block will execute even if you put areturn statement in the try
block or catch block but finally block won't run if you callSystem.exit form try or
catch.
Anagram : a word, phrase, or name formed by rearranging the letters of another,
such as spar, formed from rasp.
String vs StringBuilder: StringBuilder is mutable, which means you can modify it
after its creation.
StringBuilder vs StringBuffer: StringBuffer is synchronized, which means it is
thread-safe but slower than StringBuilder.

Palindrome: if the input is "radar", the output should be true, if input

How to split a string with white space


characters?
String[] strArray = aString.split("\\s+");

8. How to repeat a string?


String str = "abcd";
String repeated = StringUtils.repeat(str,3);
//abcdabcdabcd

In JDK 6, the substring() method gives a window to an array of chars


which represents the existing String, but do not create a new one. To
create a new array to back string, you can do add an empty string like
the following:
str.substring(m, n) + ""

This will create a new char array that represents the new string. The
above approach sometimes can make your code faster, because
Garbage Collector can collect the unused large string and keep only
the sub string.

9. How to convert string to date?


String str = "Sep 17, 2013";
Date date = new SimpleDateFormat("MMMM d, yy", Locale.ENGLISH).parse(str);
System.out.println(date);
//Tue Sep 17 00:00:00 EDT 2013

10. How to count # of occurrences of a


character in a string?
Use StringUtils from apache commons lang.
int n = StringUtils.countMatches("11112222", "1");
System.out.println(n);

you can not override a private or static method in Java, if you create a similar method with
same return type and same method arguments in child class then it will hide the super class
method, this is known as method hiding. Similarly, you cannot override a private method in
sub class because it's not accessible there, what you do is create another private method
with the same name in the child class.

Nested classes are divided into two categories: static and non-static. Nested
classes that are declared static are called static nested classes. Non-static
nested classes are called inner classes.

A binary search tree (BST) is a node based binary tree data structure which has
the following properties.

The left subtree of a node contains only nodes with keys less than the nodes
key.
The right subtree of a node contains only nodes with keys greater than the
nodes key.
Both the left and right subtrees must also be binary search trees.

From the above properties it naturally follows that:


Each node (item in the tree) has a distinct key.

Let T be a rooted tree. The lowest common ancestor between two nodes n1 and n2 is defined as the
lowest node in T that has both n1 and n2 as descendants (where we allow a node to be a descendant
of itself).

Definition - What does Superkey mean?


A superkey is a combination of columns that uniquely identifies any row within a relational
database management system (RDBMS) table. A candidate key is a closely related concept
where the superkey is reduced to the minimum number of columns required to uniquely identify
each row.

Techopedia explains Superkey


For example, imagine a table used to store customer master details that contains columns such
as:

Customer name

Customer ID

Social security number (SSN)

Address

Date of birth

A certain set of columns may be extracted and guaranteed unique to each customer. Examples
of superkeys are as follows:

Name+SSN+Birthdate

ID+Name+SSN

However, this process may be further reduced. It can be assumed that each customer ID is
unique to each customer. So, the superkey may be reduced to just one field, customer ID, which
is the candidate key. However, to ensure absolute uniqueness, a composite candidate key may
be formed by combining customer ID with SSN.
A primary key is a special term for candidate keys designated as unique identifiers for all table
rows. Until this point, only columns have been considered for suitability and are thus termed
candidate keys. Once a candidate key is decided, it may be defined as the primary key at the
point of table creation.

C dynamic memory allocation : namely malloc, realloc, calloc and free


Function

Description

malloc

allocates the specified number of bytes

realloc

increases or decreases the size of the specified block of memory. Reallocates it if


needed

calloc

allocates the specified number of bytes and initializes them to zero

free

releases the specified block of memory back to the system

Differences between

malloc()

malloc()

and

calloc()

takes a single argument (the amount of memory to allocate in bytes), while

calloc()

needs two

arguments (the number of variables to allocate in memory, and the size in bytes of a single variable).

malloc()

does not initialize the memory allocated, while

memory block have been initialized to 0

calloc()

guarantees that all bytes of the allocated

int * array = malloc(10 * sizeof(int));

Polymorphism is the ability of an object to take on many forms. The most


common use of polymorphism in OOP occurs when a parent class reference is
used to refer to a child class object.

in Object oriented programming Abstraction is a process of hiding the


implementation details from the user, only the functionality will be provided
to the user. In other words user will have the information on what the object
does instead of how it does it.

Abstract Class
A class which contains the abstract keyword in its declaration is known
as abstract class.

Abstract classes may or may not contain abstract methods ie., methods with
out body ( public void get(); )

But, if a class have at least one abstract method, then the class must be
declared abstract.

If a class is declared abstract it cannot be instantiated.

To use an abstract class you have to inherit it from another class, provide
implementations to the abstract methods in it.

If you inherit an abstract class you have to provide implementations to all the
abstract methods in it.

Since method invocation is determined by the JVM not compiler, it is known as


runtime polymorphism.

The Singleton's purpose is to control object creation, limiting the


number of objects to one only.

For example, if you have a license for only one connection for your
database or your JDBC driver has trouble with multithreading, the
Singleton makes sure that only one connection is made or that only
one thread can access the connection at a time.
Constructors are called recursively up the class hierarchy. Every constructor must call its
super-class constructor as the first thing. (The call can be omitted if it is to the no-arg
constructor, in which case the compiler will automatically insert it.)
As an aside, Java doesn't have virtual methods

By default you can put any Object into a Queue, but from Java 5, Java
Generics makes it possible to limit the types of object you can insert into
a Queue. Here is an example:
Queue<MyObject> queue = new LinkedList<MyObject>();

If I don't 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.

this keyword can be used inside the constructor to call another overloaded
constructor in the same Class. This is called the Explicit Constructor
Invocation

this keyword can only be the first statement in Constructor.

A constructor can have either this or super keyword but not


both.

Can we override the overloaded method?


Yes.

Can we override static method?


No, you can't override the static method because they are the part of class not object.

Yes, You can have many main() methods in a class by overloading the main method.

Which class is the superclass for every class.


Object class.

What if the static modifier is removed from the signature of


the main method?
Program compiles. But at runtime throws an error "NoSuchMethodError".

If I don't 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.
Object based programming languages follow all the features of OOPs except Inheritance.
Examples of object based programming languages are JavaScript, VBScript etc.

14) What will be the initial value of an object reference


which is defined as an instance variable?
The object references are all initialized to null in Java.

Final methods can't be overriden.


Final class can't be inherited.
A final variable, not initalized at the time of declaration, is known as blank final variable.

What is the difference between static binding and dynamic


binding?
In case of static binding type of object is determined at compile time whereas in dynamic
binding type of object is determined at runtime.

A virtual function is a member function that you expect to be redefined in derived


classes.

The FileNoFoundException is inherited from the IOException. Exception's


subclasses have to be caught first.
The Vector class provides the capability to implement a growable array of
objects. Vector proves to be very useful if you don't know the size of the
array in advance, or you just need one that can change sizes over the
lifetime of a program.

What are Wrapper classes?


These are classes that allow primitive types to be accessed as objects. Example:
Integer, Character, Double, Boolean etc.

Can you use abstract and final both with a method?


No, because abstract method needs to be overridden whereas you can't override final
method.

An interface is a contract. It says "My class implements all of these methods".


Declare the class as abstract and you won't need to implement all the methods.
However, please note that abstract classes cannot be instantiated.
The Reader/Writer class hierarchy is character-oriented, and the
InputStream/OutputStream class hierarchy is byte-oriented.

Serialization is the process of writing the state of an object to a byte stream.


Deserialization is the process of restoring these objects.
Interface is a blueprint of a class that have static constants and abstract methods.It can
be used to achieve fully abstraction and multiple inheritance.
An interface that have no data member and method is known as a marker interface.For
example Serializable, Cloneable etc.

Can an Interface be final?


No, because its implementation is provided by another class.

Can we define private and protected modifiers for variables


in interfaces?
No, they are implicitly public.
By static import, we can access the static members of a class directly, there is no to
qualify it with the class name.

Based on 2014 revenue, the NoSQL market leaders are MarkLogic, MongoDB, and
Datastax.[19] Based on 2015 popularity rankings, the most popular NoSQL
databases are MongoDB, Apache Cassandra, and Redis

The Vector class provides the capability to implement a growable array of


objects. Vector proves to be very useful if you don't know the size of the
array in advance, or you just need one that can change sizes over the
lifetime of a program.
You can use memory related methods from java.lang.Runtime class to get the free
memory, total memory and maximum heap memory in Java. By using these methods, you
can find out how many percents of the heap is used and how much heap space is
remaining.Runtime.freeMemory() return amount of free memory in
bytes, Runtime.totalMemory() returns total memory in bytes
and Runtime.maxMemory() returns maximum memory in bytes.

The statement String str = new String("test"); creates a string object which gets stored
on the heap like any other object. The string literal "test" that is passed as an argument
is stored in the string constant pool.

1)Checked Exception
The classes that extend Throwable class except RuntimeException and Error are known
as checked exceptions e.g.IOException,SQLException etc. Checked exceptions are
checked at compile-time.

2)Unchecked Exception
The classes that extend RuntimeException are known as unchecked exceptions e.g.
ArithmeticException,NullPointerException etc. Unchecked exceptions are not checked at
compile-time.

What is the base class for Error and Exception?


Throwable.

Both poll() and remove() take out the object from the Queue but if poll() fails then it
returns null but if remove fails it throws Exception.
Hashtable doesn't allow null keys but HashMap allows one null key.
As of Java 7 now, default size of ArrayList is 10 and default capacity of HashMap is 16, it
must be power of 2. Here is code snippet from ArrayList and HashMap class :
Is it possible for two unequal objects to have the same hashcode?
Yes, two unequal objects can have same hashcode that's why collision happen in a
hashmap.
the equal hashcode contract only says that two equal objects must have the same
hashcode it doesn't say anything about the unequal object.
Shortcut for Hierarchy : ctrl + T
You can use PowerMock library to test static methods in Java.

The eight primitive types are byte, char, short, int, long, float, double, and
boolean.

1)Checked Exception
The classes that extend Throwable class except RuntimeException and Error are known
as checked exceptions e.g.IOException,SQLException etc. Checked exceptions are
checked at compile-time.

2)Unchecked Exception
The classes that extend RuntimeException are known as unchecked exceptions e.g.
ArithmeticException, NullPointerException etc. Unchecked exceptions are not checked at
compile-time.

What is the base class for Error and Exception?


Throwable.

Is there any case when finally will not be executed?


finally block will not be executed if program exits(either by calling System.exit() or by
causing a fatal error that causes the process to abort).

The garbage collector invokes an object's finalize() method when it detects


that the object has become unreachable.
A dead thread cannot be restarted.

A class loader is an object that is responsible for loading classes. The class
ClassLoader is an abstract class.

What is exception propagation ?


Forwarding the exception object to the invoking method is known as exception
propagation.

A transient variable is a variable that may not be serialized during


Serialization and which is initialized by its default value during deserialization,
The ArithmeticException is thrown when integer is divided by zero or taking
the remainder of a number by zero. It is never thrown in floating-point
operations.
The code sleep(2000); puts thread aside for exactly two seconds. The code
wait(2000), causes a wait of up to two second. A thread could stop waiting
earlier if it receives the notify() or notifyAll() call. The method wait() is
defined in the class Object and the method sleep() is defined in the class
Thread.

How many objects will be created in the following code?


1.
2.
3.

String s1="Welcome";
String s2="Welcome";
String s3="Welcome";
Only one object.

Why java uses the concept of string literal?


To make Java more memory efficient (because no new objects are created if it exists
already in string constant pool).

1.

String s = new String("Welcome");


Two objects, one in string constant pool and other in non-pool(heap).

What is nested class?


A class which is declared inside another class is known as nested class. There are 4 types
of nested class member inner class, local inner class, anonymous inner class and static
nested class.

Can a class have an interface?


Yes, it is known as nested interface.

Can an Interface have a class?


Yes, they are static implicitely.

How will you invoke any external process in Java?


By Runtime.getRuntime().exec(?) method.

What kind of thread is the Garbage collector thread?


Daemon thread.

Can an unrefrenced objects be refrenced again?


Yes.

What is Garbage Collection?


Garbage collection is a process of reclaiming the runtime unused objects. It is performed
for memory management.

What is gc()?
gc() is a daemon thread.gc() method is defined in System class that is used to send
request to JVM to perform garbage collection.

What is the purpose of finalize() method?


finalize() method is invoked just before the object is garbage collected.It is used to
perform cleanup processing.

What is the difference between the Reader/Writer class


hierarchy and the InputStream/OutputStream class
hierarchy?
The

Reader/Writer

class

hierarchy

is

character-oriented,

and

the

InputStream/OutputStream class hierarchy is byte-oriented.

126)What an I/O filter?


An I/O filter is an object that reads from one stream and writes to another, usually
altering the data in some way as it is passed from one stream to another.

How do I convert a numeric IP address like 192.18.97.39


into a hostname like java.sun.com?
By InetAddress.getByName("192.18.97.39").getHostName() where 192.18.97.39 is the
IP address.

What is reflection?
Reflection is the process of examining or modifying the runtime behaviour of a class at
runtime.

Can you access the private method from outside the


class?
Yes, by changing the runtime behaviour of a class if the class is not secured.

What is a native method?


A native method is a method that is implemented in a language other than Java.

What comes to mind when someone mentions a shallow


copy in Java?
Object cloning.

We can pass them around as method parameters where a method expects an


object. It also provides utility methods.
An error is an irrecoverable condition occurring at runtime. Such as
OutOfMemory error. Exceptions are conditions that occur because of bad
input etc. e.g. FileNotFoundException will be thrown if the specified file does
not exist.

New objects are simply allocated at the end of the used heap.

HashMap has no or relatively less number of collision or binary tree is balanced. If that's
not the case then their performance degrades as a number of records grows.
What is heap and stack in a process?
They are two separate areas of memory in the same process. Talking about Java, the stack
is used to store primitive values and reference type to object but actual object is always
created in heap. One critical difference between heap and stack is that heap memory is
shared by all threads but each thread has their own stack.

In a strongly typed language compiler ensure type correctness, for example, you can not
store the number in String or vice-versa. Java is a strongly typed language, that's why you
have different data types e.g. int, float, String, char, boolean etc. You can only
store compatible values in respective types. On the other hand, weakly typed language
don't enforce type checking at compile time and they tree values based upon context.
Python and Perl are two popular example of weakly typed programming language, where
you can store a numeric string in number type.
A well-formed XML is the one which has root element and all tags are closed properly,
attributes are defined properly, their value is also quoted properly. On another hand, a
valid XML is the one which can be validated against an XSD file or schema. So it's possible
for an XML to be well-formed but not valid because they contain tags which may not be
allowed by their schema.
DOM parser is an in-memory parser so it loads whole XML file in memory and create a DOM
tree to parse. SAX parser is an event based parser, so it parses XML document based on the
event received e.g. opening tag, closing tag, the start of attribute or end of the attribute.
Because of their working methodology, DOM parser is not suitable for large XML file as they
will take a lot of space in memory and your process may run out of memory, SAX is the one
which should be used to parse large files. For small files, DOM is usually much faster than
SAX.
An immutable object is very useful for concurrent programming because they can be
shared between multiple threads without worrying about synchronization. In fact, the
whole model of functional programming is built on top of Immutable objects.
In Java, you can avoid SQL injection by using Prepared statement.
In short result of LEFT outer join is INNER JOIN + unmatched rows from LEFT table
and RIGHT OUTER join is INNER JOIN + unmatched rows from the right-hand side table.
A class is a blueprint on which objects are created. A class has code and behavior but an
object has both the state and behavior. You cannot create an object without creating a
class to represent its structure. The class is also used to map an object in memory, in
Java, JVM does that for you.
Association means two objects are related to each other but can exist without each other,
Composition is a form of association where one object is composed of multiple objects,
but they only exists together e.g. human body is the composition of organs, individual
organs cannot live they only useful in the body. Aggregation is a collection of object e.g.
city is an aggregation of citizens.
One drawback of recursion is depth since recursion stores intermediate result in the stack
you can only go up to a certain depth, after that your program will die
with StackOverFlowError, this is why iteration is preferred over recursion in
production code.
One difference between & and && is that bitwise operator (&) can be applied to both
integer and boolean but logical operator (&&) can only be applied to boolean variables.

SOLID (single responsibility, open-closed, Liskov substitution, interface


segregation and dependency inversion)
a programmer will create a system that is easy to maintain and extend over
time

Initial
S

SRP

OCP

LSP

ISP

DIP

In order to implement interface in Java, until your class is abstract, you need to provide
implementation of all methods, which is very painful.

A stateless system is a system which doesn't maintain any internal state. Such system will
produce the same output for same input at any point of time. It's always easier to code
and optimize a stateless system, so you should always strive for one if possible.
In correlated sub-query, inner query depends upon the outer query and executes for each
row in the outer query. While non-correlated subquery doesn't depend upon the outer
query and can be executed independently. Due to this reason former is slow and later is
fast. BTW, correlated subquery has some nice application, one of them is finding Nth
highest salary in Employee table, as seen on previous SQL question as well.

ps -ef | grep "myJavaApp"

Main difference is that Iterator was introduced in place of Enumeration. It also allows you to
remove elements from collection while traversing which was not possible with Enumeration. The
methods of Iterator e.g. hasNext() and next() are also more concise then corresponding
methods in Enumeration e.g. hasMoreElements(). You should always use Iterator in your
Java code as Enumeration may get deprecated and removed in future Java release
This question is tricky because unlike the Integer, where MIN_VALUE is negative, both
the MAX_VALUE and MIN_VALUE of the Double class are positive numbers.

1.0 / 0.0 = Double.Infinity


List is an ordered collection, List's contract maintains insertion order or
element. Set is an unordered collection, you get no guarantee on which order
element will be stored.

Java is always pass-by-value.

A STABLE sort preserves relative order of records with equal keys

Client Server Model:


Email
Network Printing
World Wide Web
The sharing of resources of a server constitutes a service.

This process of serializing an object is also called marshalling an object. The


opposite operation, extracting a data structure from a series of bytes, is
deserialization (which is also called unmarshalling).
Uses:
A method of transferring data through the wires (messaging).
A method of storing data (in databases, on hard disk drives).
A method of remote procedure calls, e.g., as in SOAP.
A method for distributing objects, especially in component-based software
engineering such as COM, CORBA, etc.
A method for detecting changes in time-varying data.
The language also allows the developer to override the serialization process
more thoroughly by implementing another interface, the Externalizable interface,
which includes two special methods that are used to save and restore the
object's state.

C and C++
C and C++ do not provide direct support for serialization.
Java
Java provides automatic serialization which requires that the object be marked by
implementing the java.io.Serializable interface. Implementing the interface
marks the class as "okay to serialize", and Java then handles serialization
internally. There are no serialization methods defined on the Serializable
interface, but a serializable class can optionally define methods with certain
special names and signatures that if defined, will be called as part of the
serialization/deserialization process. The language also allows the developer to
override the serialization process more thoroughly by implementing another
interface, the Externalizable interface, which includes two special methods that
are used to save and restore the object's state.
There are three primary reasons why objects are not serializable by default and
must implement the Serializable interface to access Java's serialization
mechanism.
1. Not all objects capture useful semantics in a serialized state. For
example, a Thread object is tied to the state of the current JVM.
There is no context in which a deserialized Thread object would
maintain useful semantics.
2. The serialized state of an object forms part of its classes'
compatibility contract. Maintaining compatibility between versions
of serializable classes requires additional effort and consideration.
Therefore, making a class serializable needs to be a deliberate
design decision and not a default condition.
3. Serialization allows access to non-transient private members of a
class that are not otherwise accessible. Classes containing sensitive
information (for example, a password) should not be serializable nor
externalizable.
The standard encoding method uses a simple translation of
the fields into a byte stream. Primitives as well as non-transient,
non-static referenced objects are encoded into the stream. Each
object that is referenced by the serialized object and not marked as
transient must also be serialized; and if any object in the complete
graph of non-transient object references is not serializable, then
serialization will fail. The developer can influence this behaviour by
marking objects as transient, or by redefining the serialization for
an object so that some portion of the reference graph is truncated
and not serialized.
It is possible to serialize Java objects through JDBC and store them
into a database. While Swing components do implement the
Serializable interface, they are not portable between different
versions of the Java Virtual Machine. As such, a Swing component,

or any component which inherits it, may be serialized to an array of


bytes, but it is not guaranteed that this storage will be readable on
another machine.

The marker interface pattern is a design pattern in computer science, used with
languages that provide run-time type information about objects. It provides a
means to associate metadata with a class where the language does not have
explicit support for such metadata.

Serialization is simply turning an existing object into a byte array. This byte array
represents the class of the object, the version of the object, and the internal state of the
object. This byte array can then be used between JVM's running the same code to
transmit/read the object.

Serialization is simply turning an existing object into a byte array. This byte array
represents the class of the object, the version of the object, and the internal state of the
object. This byte array can then be used between JVM's running the same code to
transmit/read the object.
Why would we want to do this?
There are several reasons:

Communication: If you have two machines that are running the same code, and
they need to communicate, an easy way is for one machine to build an object with
information that it would like to transmit, and then serialize that object to the other
machine. It's not the best method for communication, but it gets the job done.

Persistence: If you want to store the state of a particular operation in a database,


it can be easily serialized to a byte array, and stored in the database for later
retrieval.

Deep Copy: If you need an exact replica of an Object, and don't want to go to the
trouble of writing your own specialized clone() class, simply serializing the object to
a byte array, and then de-serializing it to another object achieves this goal.

Caching: Really just an application of the above, but sometimes an object takes
10 minutes to build, but would only take 10 seconds to de-serialize. So, rather than
hold onto the giant object in memory, just cache it out to a file via serialization, and
read it in later when it's needed.

Cross JVM Synchronization: Serialization works across different JVMs that may
be running on different architectures.

Typical web artifacts in a Java environment are


1. HTML pages,
2. XML files,
3. webservices,
4. servlets and
5. JSPs.
Web services:
Web service interface: function or methods or parameters
Encapsulation
No security risks because we are trying using same part 80 by using HTTP.
Software as a service since use it from across internet rather than installing software or servers.

Table 1: Creating and Working with Objects


Object

HTML Tag

JavaScript

Web
page

<BODY> . . . </BODY>

document

Image

<IMG NAME="myImage">

document.myImage

HTML
form

<FORM name="myForm"> . . .
</FORM>

document.myForm

Button

<INPUT TYPE="button"
NAME="myButton">

document.myForm.myButton

Queue is interface, Stack is class.


Print Queue using iterator.
For Queue, use LinkedList as class.

Você também pode gostar