Core Java Interview Questions | Eklavya Online

Core Java Interview Questions

To date, the Java platform has attracted more than 6.5 million software developers. It’s used in every major industry segment and has a presence in a wide range of devices, computers, and networks. Java technology’s versatility, efficiency, platform portability, and security make it the ideal technology for network computing. From laptops to datacenters, game consoles to scientific supercomputers, cell phones to the Internet, Java is everywhere!

Java powers more than 4.5 billion devices including:

  • 800+ million PCs
  • 2.1 billion mobile phones and other handheld devices (source: Ovum)
  • 3.5 billion smart cards
  • Set-top boxes, printers, Web cams, games, car navigation systems, lottery
    terminals, medical devices, parking payment stations, and more.

Tiers are the physical units of separation or deployment, while layers are the logical units of separation.

Imagine that you’re designing an e-commerce website. A 3 tier architecture would consist of web pages, a web server and a database, with the corresponding 3 layers being the “Presentation”, “Business Logic” and “Database” layers.
If you take the database tier and layer out then your have a 2 tier architecture.

A Web server exclusively handles HTTP requests, whereas an application server serves business logic to application programs through any number of protocols.

Initiate, pull, branch, merge, commit, push.

(Init) Make your own repository. (Pull) Download an existing repository from a url. (Branch / Merge )Make revisions. Commit then push your modifications.

Java Development Kit (JDK) is the most widely used Java Software Development Kit. Java Runtime Environment (JRE) is an implementation of the Java Virtual Machine which executes Java programs.

JAR files (Java ARchive) allows aggregating many files into one, it is usually used to hold Java classes in a library.

WAR files (Web Application aRchive) stores XML, java classes, and JavaServer pages for Web Application purposes.

Equals is intended to check logical equality and == checks if both references point to same object. (Thanks Sandeep)

a == b;// Compares references, not values.

a.equals(b);// Compares values for equality.

Unicode requires 16 bits

ASCII require 7 bits. but it is usually represented as 8 bits.

UTF-8 represents characters using 8, 16, and 18 bit patterns.

UTF-16 uses 16-bit and larger bit patterns.

Define reflection

Reflection allows program related access to information about the fields, methods and constructors of loaded classes

It use reflected fields, methods, and constructors

It helps to operate on their underlying counterparts on objects

It operates within security restrictions.

Difference between script and program:

1. A program has well defined structure, which must be followed even execute a single file. A script is a set of instructions (may be a single statement), which are complete in it-self. And execute independently as rest of the instructions.

2. Script is loose-type. It means variable’s data-type is not must. In scripting language, variables can be used without declaring them. And its type is defined when values are assigned to them. That is loose-type. Program is strong-type. It means variable’s data-type must be declared. In programming language,
variables cannot be used without declaring them. When data-type of variable is declared, then it accepts only that type of value.

3. Programs are generally compiled, so we need compiler. And scripts are generally interpreted, so we need interpreter. Interpreter is by default available in web-browsers.

The enableEvents() method is used to enable an event for a particular object. Normally, an event is enabled when a listener is added to an object for a particular event.

The enableEvents() method is used by objects that handle events by overriding their event-dispatch methods.

A private variable may only be accessed within the class in which it is declared.

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

Box.Filler, Button, Canvas, Checkbox, Choice, Container, Label, List, Scrollbar, or TextComponent.

this is used to refer to the current object instance.

super is used to refer to the variables and methods of the superclass of the current object instance.

Private method can be overridden by private, friendly, protected or public

methods. Friendly method can be overridden by friendly, protected or public methods.

Protected method can be overridden by protected or public methods. Public method

can be overridden by public method

The Frame class extends Window to define a main application window that can have a menu bar

A layout manager is an object that is used to organize components in a container.

This operator gives the value which is related to the remainder of a divisione.g

x=7%4 gives remainder 3 as an answer

A field variable is a variable that is declared as a member of a class.

A local variable is a variable that is declared local to a method.

The setLayout() method is used to specify a container’s layout.

They can be applied to variables, methods and even a block of code, static

methods and variables are not associated with any instance of class

Java uses layout managers to lay out components in a consistent manner across all windowing platforms. Since Java’s layout managers aren’t tied to absolute sizing and positioning, they are able to accomodate platform-specific differences among windowing systems.

Numeric promotion is the conversion of a smaller numeric type to a larger numeric type, so that integer and floating-point operations may take place. In numerical promotion, byte, char, and short values are converted to int values. The int values are also converted to long values, if necessary. The long and float values are converted to double values, as required.

It uses those low order bytes of the result that can fit into the size of the type allowed by the operation.

A Canvas object provides access to a Graphics object via its paint() method

A class does not inherit constructors from any of its superclasses.

When a task invokes its yield() method, it returns to the ready state. When a task invokes its sleep()method, it returns to the waiting state.

No, shift operators can be applied only to integer or long types

A statement block is used to organize a sequence of statements as a single statement group.

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

Window, Frame and Dialog classes use a BorderLayout as their layout.

instanceof” keyword is used to check what is the type of object. F

The Reader/Writer class is character-oriented and the InputStream/OutputStream class is byte-oriented.

The CheckboxMenuItem class extends the MenuItem class to support a menu item that may be checked or unchecked

TCP/IP is a two-way communication between the client and the server and it is a reliable and there is a confirmation regarding reaching the message to the destination. It is like a phone call. UDP is a one-way communication only between the client and the server and it is not a reliable and there is no confirmation regarding reaching the message to the destination. It is like a postal mail.

The GregorianCalendar class provides support for traditional Western calendars

The Class class is used to obtain information about an object’s design

A program’s main() method has a void return type.

No the reference cannot be change, but the data in that object can be changed

A program’s main() method takes an argument of the String[] type.

A compilation unit is a Java source code file.

Without layout managers, Java programmers are faced with determining how their GUI will be displayed across multiple windowing systems and finding a common sizing and positioning that will work within the constraints imposed by each windowing system.

The Object class is extended by all other classes.

A class is a subclass of itself.

A Scrollbar is a Component, but not a Container. A ScrollPane is a Container.

A ScrollPane handles its own events and performs its own scrolling.

The Reader/Writer class hierarchy is character-oriented, and the InputStream/OutputStream class hierarchy is byte-oriented.

This operator gives the value which is related to the remainder of a divisione.g

x=7%4 gives remainder 3 as an answer

The only statements for which it makes sense to use a label are those statements that can enclose a break orcontinue statement.

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

The File class encapsulates the files and directories of the local file system.

The RandomAccessFile class provides the methods needed to directly access data contained in any part of a file

The abs() method is used to calculate absolute values.

?– Yes, we can have an inner class inside a method and final variables can be accessed.

By associating Checkbox objects with a CheckboxGroup.

Methods are functions that operate on instances of classes in which they are defined. Objects can communicate with each other using methods and can call methods in other classes. Method definition has four parts. They are name of the method, type of object or primitive type the method returns, a list of parameters and the body of the method. A method’s signature is a combination of the first three parts mentioned above.

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 reenters the pool of ready tasks.

The scheduler then determines which task should execute next, based on priority and other factors.

Unicode is used for internal representation of characters and strings and it uses 16 bits to represent each other.

JVM stands for Java Virtual Machine. It’s an abstract computer or virtual computer which runs the compiled java programs. Actually JVM is a software implementation which stands on the top of the real hardware platform and operating system. It provides abstraction between the compiled java program and the hardware and operating system. So the compiled program does not have to worry about what hardware and operating system he has to run in, it’s all handled by the JVM and thus attaining portability. All Java programs are compiled in to bytecodes. JVM can only understand and execute Java bytecodes. we can visualize Java bytecodes as machine language for JVM. Java compiler takes the .java files and compiles it to a “bytecode” file with .class file extension. Compiler generates one class file for one source file.

There may be times when we want to call subroutines which are written in some other language other than Java like C++, VB6 etc.

Yes, a for statement can loop indefinitely. For example, consider the following:

for(;;) ;

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.

System.arraycopy(myOldArray, 0, myNewArray, 0, length);+

java. lang. reflect package has the ability to analyze itself in runtime.

A task’s priority is an integer value that identifies the relative order in which it should be executed with respect to other tasks. The scheduler attempts to schedule higher priority tasks before lower priority tasks.

A top-level class may be public, abstract, or final.

In case of signed left shift >> the new bits are set to zero. But in case of signed

right shift it takes the value of most significant bit before the shift, that is if the most

significant bit before shift is 0 it will introduce 0, else if it is 1, it will introduce 1

The result is a String object.

No, it is not the main method in which you define variables. Global variables is not possible because concept of encapsulation is eliminated here.

The Dictionary class provides the capability to store key-value pairs.

validate() method is used to cause a container to be laid out and redisplayed

Ans: So that it can be invoked without creating an instance of that class

No it is applied only to class and methods

The = operator is right associative.

Yes, a lock can be acquired on a class. This lock is acquired on the class’s Class object

The java.util.EventObject class is the highest-level class in the event-delegation class hierarchy.

Commas are used to separate multiple statements within the initialization and iteration parts of a forstatement.

They are loaded just before the constructor is called

A local inner class may be final or abstract.

A public class may be accessed outside of its package.

A non-public class may not be accessed outside of its package.

The read() method returns -1 when it has reached the end of a file.

The purpose of the System class is to provide access to system resources.

?– Every computer connected to a network has an IP address. An IP address is a number that uniquely identifies each computer on the Net. An IP address is a 32-bit number.

A (non-local) inner class may be declared as public, protected, private, static, final, or abstract.

Wrapped classes are classes that allow primitive types to be accessed as objects.

The non-Unicode letter characters $ and _ may appear as the first character of an identifier

?– A Choice is displayed in a compact form that requires you to pull it down to see the list of available choices and only one item may be selected from a choice. A List may be displayed in such a way that several list items are visible and it supports the selection of one or more list items.

?– Wrapper classes are classes that allow primitive types to be accessed as objects.

When JVM compiles the class file he does not compile the full class file in one shot. Compilation is done on function basis or file basis. Advantage gained from this is that heavy parsing of original source code is avoided. Depending on need basis the compilation is done. This typ of compilation is termed as JIT or Just-in- Time compilation.

this() can be used to invoke a constructor of the same class whereas super() can be used to invoke a super class constructor.

Order of precedence determines the order in which operators are evaluated in expressions.

Associatity determines whether an expression is evaluated left-to-right or right-to-left.

To create a object immutable You need to make the class final and all its member final so that once objects gets crated no one can modify its state. You can achieve same functionality by making member as non final but private and not modifying them except in constructor. Also its NOT necessary to have all the properties final since you can achieve same functionality by making member as non final but private and not modifying them except in constructor.

?– a) String objects are constants and immutable whereas StringBuffer objects are not. b) String class supports constant strings whereas StringBuffer class supports growable and modifiable strings.

It is very difficult to remember a set of numbers(IP address) to connect to the Internet. The Domain Naming Service(DNS) is used to overcome this problem. It maps one particular IP address to a string of characters. For example, www. mascom. com implies com is the domain name reserved for US commercial sites, moscom is the name of the company and www is the name of the specific computer, which is mascom’s server.

These public, protected and private, these can be applied to class, variables,

constructors and methods. But if you don�t specify an access modifier then it is

considered as Friendly

If you are running Java on English Windows platforms, it is probably Cp1252. If you are running Java on English Solaris platforms, it is most likely 8859_1

The elements of a BorderLayout are organized at the borders (North, South, East, and West) and the center of a container.

A Java Bean is a software component that has been designed to be reusable in a variety of different environments

The String literal “abc” is not a primitive value. It is a String object.

A Choice is displayed in a compact form that requires you to pull it down to see the list of available choices. Only one item may be selected from a Choice.

A List may be displayed in such a way that several List items are visible. A List supports the selection of one or more List items.

The stop(), suspend() and resume() methods have been deprecated in JDK 1.2.

The ActionEvent event is generated as the result of the clicking of a button.

No abstract class cannot be instantiated i.e you cannot create a new object of this

class

 

Yes, a double value can be cast to a byte.

An abstract class may not be declared as final.

class variable is a static variable and does not belong to instance of class but

rather shared across all the instances

– member variable belongs to a particular instance of class and can be called from any

method of the class

– automatic or local variable is created on entry to a method and has only method

scope

Via reference to any instance of the class

Code:

Computer comp = new Computer ();

comp.harddisk where hardisk is a static variable

comp.compute() where compute is a method

A static variable is associated with the class as a whole rather than with specific instances of a class.

Non-static variables take on unique values with each object instance

E is the base of the natural logarithm and PI is mathematical value pi.

The default value of the boolean type is false.

No. An object cannot be cast to a primitive value

The compiler supplies a default constructor for a class if no other constructors are provided

Public – main method is called by JVM to run the method which is outside the scope of project therefore the access specifier has to be public to permit call from anywhere outside the application static – When the JVM makes are call to the main method there is not object existing for the class being called therefore it has to have static method to allow invocation from class. void – Java is platform independent language therefore if it will return some value then the value may mean different to different platforms so unlike C it can not assume a behavior of returning value to the operating system. If main method is declared as private then – Program will compile properly but at run-time it will give “Main method not public.” error.

Array is a set of related data type and static whereas vector is a growable array of objects and dynamic.

A Scrollbar is a Component, but not a Container whereas Scrollpane is a Conatiner and handles its own events and perform its own scrolling.

Two methods may not have the same name and argument list but different return types.

An argument can be passed in two ways. They are passing by value and passing by reference. Passing by value: This method copies the value of an argument into the formal parameter of the subroutine. Passing by reference: In this method, a reference to an argument (not the value of the argument) is passed to the parameter.

The readLine() method returns null when it has reached the end of a file.

?– A super class is a class that is inherited whereas sub class is a class that does the inheriting.

An abstract class is a class designed with implementation gaps for subclasses to fill in and is deliberately incomplete

The >> operator carries the sign bit when shifting right. The >>> zero-fills bits that have been shifted out.

?– URL stands for Uniform Resource Locator and it points to resource files on the Internet. URL has four components: http://www. address. com:80/index.html, where http – protocol name, address – IP address or host name, 80 – port number and index.html – file path.

The purpose of the Runtime class is to provide access to the Java runtime system

The java.lang package is always imported by default.

Jar file allows to efficiently deploying a set of classes and their associated resources. The elements in a jar file are compressed, which makes downloading a Jar file much faster than separately downloading several uncompressed files. The package java. util. zip contains classes that read and write jar files

It is referred to as the modulo or remainder operator. It returns the remainder of dividing the first operand by the second operand.

The FontMetrics class is used to define implementation-specific properties, such as ascent and descent, of aFont object

The == operator compares two objects to determine if they are the same object in memory. It is possible for two String objects to have the same value, but located indifferent areas of memory

The ResourceBundle class is used to store locale-specific resources that can be loaded by a program to tailor the program’s appearance to the particular locale in which it is being run.

The static variables are initialized when the class is loaded Non static variables

are initialized just before the constructor is called

The null is not a keyword.

The digits 0 through 9 may not be used as the first character of an identifier but they may be used after the first character of an identifier

An abstract method is a method whose implementation is deferred to a subclass.

The SimpleTimeZone class provides support for a Gregorian calendar.

Try statements may be tested.

– Uniary ++, –, +, -, |, ~, ()

– Arithmetic *, /, %,+, –

-Shift <<, >>, >>>

– Comparison =, instanceof, = =,!=Bitwise &, ^, |Short Circuit &&, ||

Ternary ?:Assignment =

Code:

Computer.harddisk

Computer.compute()

The values true and false are not keywords.

A non-static inner class may have object instances that are associated with instances of the class’s outer class.

A static inner class does not have any object instances.

The elements of a CardLayout are stacked, one on top of the other, like a deck of cards.

No when features are friendly or protected they can be accessed from all the

classes in that package but not from classes in another package

A package statement must appear as the first line in a source code file (excluding blank lines and comments).

Set stores elements in an unordered way but does not contain duplicate elements, whereas list stores elements in an ordered way but may contain duplicate elements.

javap disassembles compiled Java files and spits out representation of the Java program. This is a useful option when the original source code is not available.

public, abstract and final can be used for top-level class.

The default value of an String type is null.

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.

StringBuffer is a peer class of String that provides almost all functionality of strings. String represents fixed-length, immutable character sequences. Comparatively StringBuffer represents mutable, growable and writeable character sequences. But StringBuffer does not create new instances as string so it’s more efficient when it comes to intensive concatenation operation.

  1. a) Integer is a class defined in the java. lang package, whereas int is a primitive data type defined in the Java language itself. Java does not automatically convert from one to the other. b) Integer can be used as an argument for a method that requires an object, whereas int can be used for calculations.

?– a) doGet() method is used to get information, while doPost() method is used for posting information. b) doGet() requests can’t send large amount of information and is limited to 240-255 characters. However, doPost()requests passes all of its data, of unlimited length. c) A doGet() request is appended to the request URL in a query string and this allows the exchange is visible to the client, whereas a doPost() request passes directly over the socket connection as part of its HTTP request body and the exchange are invisible to the client.

While defining method, variables passed in the method are called parameters. While using those methods, values passed to those variables are called arguments.

If an expression involving the Boolean & operator is evaluated, both operands are evaluated. Then the &operator is applied to the operand. When an expression involving the && operator is evaluated, the first operand is evaluated.

If the first operand returns a value of true then the second operand is evaluated. The && operator is then applied to the first and second operands. If the first operand evaluates to false, the evaluation of the second operand is skipped.

String objects are constants. StringBuffer objects are not constants.

setBounds() method is used to set the position and size of a component

No. It is not a valid java operator.

You can access protected features from other classes by subclassing the that

class in another package, but this cannot be done for friendly features

?– BDK, Bean Development Kit is a tool that enables to create, configure and connect a set of set of Beans and it can be used to test Beans without writing a code.

During compilation, the values of each case of a switch statement must evaluate to a value that can be promoted to an int value.

The ObjectInputStream class supports the reading of objects from input streams.

Abstract class must be subclassed and final class cannot be subclassed

The fractional part of the result is truncated. This is known as rounding toward zero.

So they can be invoked as if they are a mathematical code library.

Automatic variable have to be initialized explicitly

The preferred size of a component is the minimum component size that will allow the component to display normally.

The elements of a GridBagLayout are organized according to a grid. However, the elements are of different sizes and may occupy more than one row or column of the grid. In addition, the rows and columns may have different sizes

The elements of a GridBagLayout are of equal size and are laid out using the squares of a grid.

Ans: It converts all the 1 bits in a binary value to 0s and all the 0 bits to 1s, e.g

11110000 coverts to 00001111

The File class is used to create objects that provide access to the files and directories of a local file system

No they are not allowed to use non static features of the class, they can only call

static methods and can use static data

A void return type indicates that a method does not return a value.

The prefix form performs the increment operation and returns the value of the increment operation.

The postfix form returns the current value all of the expression and then performs the increment operation on that value.

The Java Spec says that everything in Java is pass-by-value. There is no such thing as “pass-by-reference” in Java. The difficult thing can be to understand that Java passes “objects as references” passed by value.

An unreachable object may become reachable again. This can happen when the object’s finalize() method is invoked and the object performs an operation which causes it to become accessible to reachable objects.

In procedural program, programming logic follows certain procedures and the instructions are executed one after another. In OOP program, unit of program is object, which is nothing but combination of data and code. b) In procedural program, data is exposed to the whole program whereas in OOPs program, it is accessible with in the object and which in turn assures the security of the code.

source : A source is an object that generates an event. This occurs when the internal state of that object changes in some way. listener : A listener is an object that is notified when an event occurs. It has two major requirements. First, it must have been registered with one or more sources to receive notifications about specific types of events. Second, it must implement methods to receive and process these notifications.

public: Any thing declared as public can be accessed from anywhere. private: Any thing declared as private can’t be seen outside of its class. protected: Any thing declared as protected can be accessed by classes in the same package and subclasses in the other packages. default modifier : Can be accessed only to classes in the same package.

Method overloading: When a method in a class having the same method name with different arguments is said to be method overloading. Method overriding : When a method in a class having the same method name with same arguments is said to be method overriding.

FlowLayout: The elements of a FlowLayout are organized in a top to bottom, left to right fashion. BorderLayout: The elements of a BorderLayout are organized at the borders (North, South, East and West) and the center of a container. CardLayout: The elements of a CardLayout are stacked, on top of the other, like a deck of cards. GridLayout: The elements of a GridLayout are of equal size and are laid out using the square of a grid. GridBagLayout: The elements of a GridBagLayout are organized according to a grid. However, the elements are of different size and may occupy more than one row or column of the grid. In addition, the rows and columns may have different sizes.

Clipping is the process of confining paint operations to a limited area or shape.

Inner class : classes defined in other classes, including those defined in methods are called inner classes. An inner class can have any accessibility including private. Anonymous class : Anonymous class is a class defined inside a method without a name and is instantiated and declared in the same place and cannot have explicit constructors.

A Stream is an abstraction that either produces or consumes information. There are two types of Streams and they are: Byte Streams: Provide a convenient means for handling input and output of bytes. Character Streams: Provide a convenient means for handling input & output of characters. Byte Streams classes: Are defined by using two abstract classes, namely InputStream and OutputStream. Character Streams classes: Are defined by using two abstract classes, namely Reader and Writer.

?– Stored procedure is a group of SQL statements that forms a logical unit and performs a particular task. Stored Procedures are used to encapsulate a set of operations or queries to execute on database. Stored procedures can be compiled and executed with different parameters and results and may have any combination of input/output parameters.

The methods to override are equals() and hashCode().

Java uses the CLASSPATH environment variable to read the classes and libraries from file system. This variable is used by all JDK Tools and Extension including Java Compiler (javac) and JRE(java) use this variable to locate the dependent user classes and jar files to perform specific tasks.

Java Compiler uses it to locate the dependent user classes and jar files to compile Java source files.

Java Run-time Environment (JRE) uses the classpath variable to identify the location of files to be loaded for the run-time dependencies (e.g. classes and jar files) of java program.

: A class can have a block of initializer code that is simply surrounded by curly

braces and labeled as static e.g.

Code:

public class Demo{

static int =10;

static{

System.out.println(�Hello world�);

}

}

And this code is executed exactly once at the time of class load

On Windows

You need use below windows program Process Explorer that lets you see which files are open for a particular process or program

 

On Unix, Linux or Mac

It can be done using lsof command. lsof is one of my favorite and useful java debugging commands on Unix. Below is the syntax for using this command:

view plainprint?

lsof -p [pid]

Connection Pooling is a technique used for sharing the server resources among requested clients. It was pioneered by database vendors to allow multiple clients to share a cached set of connection objects that provides access to a database.
Getting connection and disconnecting are costly operation, which affects the application performance, so we should avoid creating multiple connection during multiple database interactions. A pool contains set of Database connections which are already connected, and any client who wants to use it can take it from pool and when done with using it can be returned back to the pool.

Apart from performance this also saves you resources as there may be limited database connections available for your application.

new ArrayList(Arrays.asList(myArray))

Setting CLASSPATH on Windows XP

  • Right-click My Computer, and then click Properties.
  • Click the Advanced tab.
  • Click Environment variables.
  • Click one the following options, for either a user or a system variable
  • Click New to add a new variable name and value.
  • Enter Variable name as CLASSPATH
  • enter all directories and jar files separated by semicolon. (e.g. c:\dir1;c:\dir2;c:\dir3\abc.jar)

Setting CLASSPATH on Windows 7

  • Click Start
  • Then right-click on Computer,
  • select Properties
  • click Select Advanced System Settings tab.
  • click the Environment Variables button.

Setting CLASSPATH on Unix, Linux and Mac

  • Use export command to set the CLASSPATH environment variable in your system.
  • ExportCLASSPATH=/path/to/dir1:/path/to/dir2:path/to/abc.jar

It can refer only to methods and it indicates that the body of the method is to be

found else where and it is usually written in non java language

When continue statement is applied it prematurely completes the iteration of a

loop. When break statement is applied it causes the entire loop to be abandoned.

A transient variable is not stored as part of objects persistent state and they

cannot be final or static

: For Unary operators

If operant is byte, short or a char it is converted to an int. If it is any other type it is not

converted

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.

Checking CLASSPATH on Windows

To check CLASSPATH variable is set on Microsoft Windows, run following command on command prompt

C:> echo %CLASSPATH%

If CLASSPATH variable is not set you will see %CLASSPATH% on windows system.

Checking CLASSPATH on Unix, Linux or Mac

To check CLASSPATH variable is set on Unix/Linux/Mac run following command on shell
$ echo $CLASSPATH

If CLASSPATH variable is not set you will see CLASSPATH: Undefined variable error on Unix/Linux/Mac systems.

How to set Multiple Jar Files in Java Classpath

Java versions Older then Java 6 does not support wildcard characters. Setting Multiple jars using wildcard in Java classpath are allowed in Java 6 and later versions.

For example, to specify all jar files in a directory “lib” the classpath entry should look like this lib/*

The wildcard entry (*) in classpath value will match only jar files NOT class files. To match both class files and JAR files in a same directory lib, you need to specify both values as shown below

Setting Multiple Jars in Classpath on Windows

Windows environment variable values are separated by semicolon, therefore you classpath entry would look like thislib/*;lib

Setting Multiple Jars in Classpath on Unix, Linux or Mac

Unix environment variable values are separated by colon, therefore you classpath entry would look like thislib/*:lib

Older version of Java

In older version of Java(older than Java 6), each jar file needs to be specified in the classpath. It can be a tedious and erroneous task if you are using many third party libraries.

You can easily set any system properties in java using System.setPropoerty method, However it may not have any effect in case of CLASSPATH property. This is mainly because the Java system class loader is initialized very early in the JVM startup sequence. The class loader copies the classpath into its own data structures, and the classpath property is not read again. Therefore changing it after its already copied does not affect anything. There are mainly two reasons for this – First most important reason is security. You do not want a malicious code change the classpath at runtime and load some unwanted classes. Second reason is performance, since reading the classpath every-time its needed may not be efficient.

By providing proper implentation for the key class as shown below with the equals() and hashCode() methods.

 

…..

static class Key {

private String key;

 

public Key(String key) {

this.key = key;

}

 

 

@Override

public boolean equals(Object obj) {

 

if (obj instanceof Key)

return key.equals(((Key) obj).key);

else

return false;

 

}

 

@Override

public int hashCode() {

return key.hashCode();

}

}

…..

If you rerun it after making the fix shown above to the MemoryLeak class, you will get an output as shown below. The program runs endlessly, and creates only one object in the HashMap.

 

map size: 1

Free memory after count 1000 is 4MB

map size: 1

Free memory after count 2000 is 4MB

map size: 1

Free memory after count 3000 is 4MB

map size: 1

Free memory after count 4000 is 4MB

Free memory after count 73000 is 4MB

map size: 1

Free memory after count 74000 is 4MB

map size: 1

Free memory after count 75000 is 4MB

Final can be applied to classes, methods and variables and the features cannot be

changed. Final class cannot be subclassed, methods cannot be overridden.

You can use Reflections library for doing this. Reflections is a open source Java library. It scans Java classpath and indexes it with metadata. This library allows you to query the classpath at runtime and can be very handy for many run-time reflection code needs.

HashSet : HashSet does not allow duplicate values. It provides add method rather put method. You also use its contain method to check whether the object is already available in HashSet. HashSet can be used where you want to maintain a unique list.

HashMap : It allows null for both key and value. It is unsynchronized. So come up with better performance.

You can use Reflections library for doing this. Reflections is a open source Java library. It scans Java classpath and indexes it with metadata. This library allows you to query the classpath at runtime and can be very handy for many run-time reflection code needs.

If one of the operands is double, the other operand is converted to double

Else If one of the operands is float, the other operand is converted to float

Else If one of the operands is long, the other operand is converted to long

Else both the operands are converted to int

If you profile your application, you can notice a graph like a saw tooth. Here is how you can determine this with the help of jconsole for the above bad key class example. All you have to do is while your MemoryLeak is running, get the Java process id by typing.

C:\>jps

5808 Jps

4568 MemoryLeak

3860 Main

 

Now, open up the jconsole as shown below on a command line

 

C:\>jconsole 4568

By Java API definitions: Statement is a object used for executing a static SQL statement and returning the results it produces. PreparedStatement is a SQL statement which is precompiled and stored in a PreparedStatement object. This object can then be used to efficiently execute this statement multiple times. There are few advantages of using PreparedStatements over Statements

  • Since its pre-compiled, Executing the same query multiple times in loop, binding different parameter values each time is faster. (What does pre-compiled statement means? The prepared statement(pre-compiled) concept is not specific to Java, it is a database concept. Statement precompiling means: when you execute a SQL query, database server will prepare a execution plan before executing the actual query, this execution plan will be cached at database server for further execution.)
  • In PreparedStatement the setDate()/setString() methods can be used to escape dates and strings properly, in a database-independent way.
  • SQL injection attacks on a system are virtually impossible when using PreparedStatements.

There is no easy way to do this in current java versions.

There are 2 alternatives to deal with this problem using third party libraries.

Use Jar class loader library

The “http://www.jdotsoft.com/JarClassLoader.php”JarClassLoader library provides you the feature of loading resources from a top JAR and from JARs inside the top JAR.

 

Explode and combine into one jar

Instead of trying to bundle jar file inside jar you can explode all required jars and re-bundle them as one jar using following two libraries

  • The first is “http://one-jar.sourceforge.net/”One-Jar, which uses a special classloader to allow the nesting of jars.
  • The second is “http://classworlds.codehaus.org/uberjar.html”UberJar, (or “http://maven.apache.org/plugins/maven-shade-plugin/”Maven Shade Plugin), which explodes the included libraries and puts all the classes in the top-level jar.

It indicates that these variables can be modified asynchronously

In a Java class import statements are used to access other classes. You also do a wild card import like org.fromdev.* on your java file.
In such cases, It will become very impractical/slow for the Java Virtual Machine to search for classes in every file/folder on a machine, therefore you can provide the Java Virtual Machine with a list of places to look. This is done by putting folder and jar files on your classpath.

Environment variables in general are a set of dynamic name value pair that can be used by processes to decide the behavior based on a system. These are supported by all modern operating systems.

The CLASSPATH variable is a Java way to tell the possible locations of user classes or jar files for a Java application. Since each user/computer may choose to have classes in different location its best to have custom locations configured in Classpath variable.

In case you have not set the classpath environment variable, the default value is used as the “.” (current directory). That means, the current directory is searched.

There are three major relationship models:-

  • One-to-one
  • One-to-many
  • Many-to-many

This can be done in two simple ways

 

Using ClassLoader.getResourceAsStream

This method can be used to load any file from CLASSPATH
InputStream in =this.getClass().getClassLoader().getResourceAsStream(“MyFile.txt”);

 

Using Class.getResourceAsStream

This method can be used to load files using relative path to the package of the class
InputStream in =this.getClass().getResourceAsStream(“SomeTextFile.txt”);

 

This method can also be used to load any files from CLASSPATH by prefixing a “/”