Showing posts with label Core Java. Show all posts
Showing posts with label Core Java. Show all posts

Monday, March 12, 2012

Java Synchronization

Synchronization in Java:

Java Synchronization is a process of controlling the access of shared resources by the multiple threads in such a manner where only one thread can access one resource at a time. In non synchronized multithreaded application, it is possible for one thread to modify a shared object, while another thread is in the process of using or updating the object's value.

Synchronization prevents such type of data corruption. Synchronization is best use with the Multi-Threading in Java. Synchronization can be done at two levels:
  • Synchronizing a function
  • Synchronizing a block of code
Please find the sample code below

Synchronizing a function
: 
public synchronized void  Display() 
{
   // related code
}
Synchronizing a block of code inside a function:
 public myFunction ()
{
  synchronized (this)
   {
  // Synchronized code
   }
}

Read more...

Friday, January 20, 2012

Java Stack and Heap Memory

Java Stack and Heap Memory: 

Each time an object is created in Java it goes into the area of memory known as heap. The primitive variables like int and double are allocated in the stack, if they are local method variables and in the heap if they are member variables (i.e. fields of a class). In Java methods local variables are pushed into stack when a method is invoked and stack pointer is decremented when a method call is completed. In a multi-threaded application each thread will have its own stack but will share the same heap. This is why care should be taken in your code to avoid any concurrent access issues in the heap space. The stack is threadsafe (each thread will have its own stack) but the heap is not threadsafe unless guarded with synchronization through your code. 

A method in stack is re-entrant allowing multiple concurrent invocations that do not interfere with each other. A function is recursive if it calls itself. Given enough stack space, recursive method calls are perfectly valid in Java though it is tough to debug. Recursive functions are useful in removing iterations from many sorts of algorithms. All recursive functions are re-entrant but not all re-entrant functions are recursive. Idempotent methods are methods, which are written in such a way that repeated calls to the same method with the same arguments yield same results. For example clustered EJBs, which are written with idempotent methods, can automatically recover from a server failure as long as it can reach another server.

Read more...

Sunday, January 1, 2012

Java Mail API

Java Mail API is used to send and receive emails between applications. To send and receive the emails  SMPT, POP and IMAP protocols are used. The message sending and receiving is done by creating a framework using set of abstract classes in the API. This framework allows the application to create customized cross-platform mail application by having basic knowledge of e-mail. There are methods and classes that are used to access mail folders, message downloading and sending messages along with attachments feature.

Java Mail API is used to create personal mail filter, simple mailing lists and personal mail applications. Java mail also includes the capabilities to add the emailing process to an enterprise application or even to create a full-fledged e-mail client. Many companies in the industry have written new e-mail clients using Java Mail.
  • JavaMail is a set of abstract classes that create a framework for sending, receiving and handling e-mail. 
  • The package that Sun provides contains implementations of IMAP and SMTP, which allow sending and receiving mail. 
  • The framework eases the creation of cross-platform mail application without an in-depth knowledge of e-mail.
  • There are methods and classes that allow access to mail folders, download messages, send messages with attachments and filter mail.

Read more...

Tuesday, September 13, 2011

Difference between JRE/JVM/JDK

JDK is the Java Development Kit i.e. JDK is bundle of software that you can use to develop Java based software. JRE is the Java Runtime Environment i.e. JRE is an implementation of the Java Virtual Machine which actually executes Java programs. Typically, each JDK contains one (or more) JRE’s along with the various development tools like the Java source compilers, bundling and deployment tools, debuggers,development libraries, etc.

Read more...

Thursday, February 4, 2010

STRING OBJECTS in JAVA

The Java String class (java.lang.String) is a class of object that represents a character array of arbitrary length. While this external class can be used to handle string objects, Java integrates internal, built-in strings into the language.

An important attribute of the String class is that once a string object is constructed, its value cannot change (note that it is the value of an object that cannot change, not that of a string variable, which is just a reference to a string object). All String data members are private, and no string method modifies the string’s value.


CONVERTING OBJECTS TO STRINGS


The String + operator accepts a non-string operand, provided the other operand is a string. The action of the + operator on non-string operands is to convert the non-string to a string, then to do the concatenation. Operands of native types are converted to string by formatting their values. Operands of class types are converted to a string by the method toString()

that is defined for all classes. Any object or value can be converted to a string by explicitly using one of the static valueOf() methods defined in class String:

String str = String.valueOf (obj);
If the argument to valueOf() is of class type, then valueOf() calls that object’s toString() method. Any class can define its own toString() method, or just rely on the default. The output produced by toString() is suitable for debugging and diagnostics. It is not meant to be an elaborate text representation of the object, nor is it meant to be parsed. These conversion rules also apply to the right-hand side of the String += operator.

CONVERTING STRINGS TO NUMBERS


Methods from the various wrapper classes, such as Integer and Double, can be used to convert numerical strings to numbers. This is often necessary for command line arguments where the parameter list is available to the
main () method as a string array. The wrapper classes contain static methods ( such as parseInt() ) which convert a string to its own internal data type.

These can be used with class names rather than creating a separate object. Be aware that these particular conversion methods throw a NumberFormatException and must be used in the context of a try and catch block combination.

Read more...

Wednesday, November 4, 2009

Java Program to list the Contents of a Zip File

Java Sample program to list the contents of a zip file

In this program we need to get the entries of the zip file, since each file in a zip file is represented by an entry. In this program assume that the filename of the zip file is 'Test.zip'. By calling the entries method of the ZipFile object we get an Enumeration back that can be used to loop through the entries of the file. We have to cast each element in the Enumeration to a ZipEntry.


import java.util.zip.ZipFile;
import java.util.zip.ZipEntry;
import java.io.IOException;
import java.util.Enumeration;

public class ListZipFiles
{
public void doListFiles()
{
try
{
ZipFile zipFile = new ZipFile("Test.zip");
Enumeration zipEntries = zipFile.entries();

while (zipEntries.hasMoreElements())
{
//Process the name, here we just print it out
System.out.println(((ZipEntry)zipEntries.nextElement()).getName());
}
}
catch (IOException ex) {
ex.printStackTrace();
}
}
// Command line arguments
public static void main(String[] args) {

new Main().doListFiles();
}
}

Read more...

Sunday, June 21, 2009

Java Garbage Collection

Garbage Collection in Java

Java has built-in facility to re-claim unwanted memory, this is known as garbage collection. Garbage collector plays its role if there is any memory defficiency. Usually an object no longer referenced, for example when you assign with null, it could be ready for garbage collection. In java all objects are created in heap memory, whereas primitive type and object reference are placed in stack memory. Object class has defined finalize() method that is called by the garbage collector on an object when garbage collection determines that there are no more references to the object.


The purpose of Java Garbage Collection is to identify and discard objects that are no longer needed by a program so that their resources can be reclaimed and reused. A Java object is subject to garbage collection when it becomes unreachable to the program in which it is used. Garbage collection is also called automatic memory management as JVM automatically removes the unused variables/objects (value is null) from the memory.


Every class inherits finalize() method from java.lang.Object, the finalize() method is called by garbage collector when it determines no more references to the object exists. In Java, it is good idea to explicitly assign null into a variable when no more in use. In Java on calling System.gc() and Runtime.gc(), JVM tries to recycle the unused objects, but there is no guarantee when all the objects will garbage collected. Java Garbage collection is an automatic process and can't be forced.

Java Garbage Collection program

class GC
{

public static void main(String args[]){
MyObj obj = new MyObj();
obj=null;
System.gc();
}
}

class MyObj
{

public MyOb(){
System.out.println("Object created");
}

protected void finalize()
{

System.out.println("Garbage collector in action");
}
}
Garbage collection will start immediately upon request of System.gc(). Garbage collection does not guarantee that a program will not run out of memory. It is possible for programs to use up memory resources faster than they are garbage collected. It is also possible for programs to create objects that are not subject to garbage collection.

Read more...

Friday, May 8, 2009

Java Static Modifier

Static Modifier in Java:

In java we can have a Static Block, Static Variable, Static Method. Static modifier specifies that a variable or method is the same for all objects of a particular class. Some times we need a common variable or method for all objects of a part icular class. Typically, new variables are allocated for each instance of a class.

Variable declared as being static is only allocated once, regardless of how many objects are instantiated and all instantiated objects share the same instance of the static variable.
Similarly, a static method is one whose implementation is exactly the same for all objects of a part icular class. Static methods have access only to static variables.

Example of a static member variable and a static method:

static int refCount;
static int getRefCount() {
return refCount;
}
A beneficial side effect of static members is that they can be accessed without having to create an instance of a class. Static method or a variable is not attached to a particular object, but rather to the class as a whole. They are allocated when the class is loaded.

A static initializer block resembles a method with no name, no arguments, and no return type. It doesn't need a name, because there is no need to refer to it from outside the class definition. The code in a static initializer block is executed by the virtual machine when the class is loaded.

Example of a Static Block
static{
date1 = new Date();
for(int count = 0; count <>
var = var+1;
}
Static blocks are blocks defined within the body of a class using the static keyword but which are not inside any other blocks.

Read more...

Thursday, May 7, 2009

Java Access Modifiers

Access Modifiers in Java

Access to variables and methods in Java classes is accomplished through access modifiers. Access modifiers define varying levels of access between class members and the outside world (other objects). Access modifiers are declared immediately before the type of a member variable or the return type of a method.

There are four access modifiers in java :

  • default
  • public
  • protected
  • private
Access modifiers affect the visibility not only of class members, but also of classes themselves.

Default Access Modifier

The default access modifier specifies that only classes in the same package can have access to a class's variables and methods. Class members with default access have a visibility limited to other classes within the same package. There is no actual keyword for declaring the default access modifier, it is applied by default in the absence of an access modifier.

Code for default access variable and member:
long length;
void getLength() {
return length;
}
Notice that neither the member variable nor the method supplies an access modifier, so each
takes on the default access modifier implicitly.

public Access Modifier

The public access modifier specifies that class variables and methods are accessible to anyone, both inside and outside the class. This means that public class members have global
visibility and can be accessed by any other object.

Sample Code for public member variables:
public int count;
public boolean valid;
protected Access Modifier

The protected access modifier specifies that class members are accessible only to methods in that class and subclasses of that class. This means that protected class members have visibility limited to subclasses.

Sample code for protected variable and a protected method :
protected char Name;
protected char getName() {
return Name;
}
The private Access Modifier

The private access modifier is the most restrictive; it specifies that class members are accessible only by the class in which they are defined. This means that no other class has access to private class members, even subclasses.

Code example for private member variables:
private String firstName;
private double Value;
Access to classes, constructors, methods and fields are regulated using access modifiers. Access modifiers in Java determine the visibility and the scope of the Java elements.

Read more...
Blog Widget by LinkWithin

JS-Kit Comments

  © Blogger template Newspaper III by Ourblogtemplates.com 2008

Back to TOP