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

Thursday, May 12, 2011

Constructor Chaining

We know that constructors are invoked at runtime when you say new on some class type as follows:
Sparrow sparrow = new Sparrow();

Now we will see what really happens when we say new Sparrow()?
(Assume Sparrow extends Bird and Bird extends Object.)
  1. Sparrow constructor is invoked. Every constructor invokes the constructor of its superclass with an (implicit) call to super(), unless the constructor invokes an overloaded constructor of the same class (more on that in a minute). 
  2. Bird constructor is invoked (Bird is the superclass of Sparrow).
  3. Object constructor is invoked (Object is the ultimate superclass of all classes, so class Bird extends Object even though you don't actually type "extends Object" into the Bird class declaration. It's implicit.) At this point we're on the top of the stack.
  4. Object instance variables are given their explicit values. By explicit values,we mean values that are assigned at the time the variables are declared,like "int x = 27", where "27" is the explicit value (as opposed to the default value) of the instance variable.
  5. Object constructor completes.
  6. Bird instance variables are given their explicit values (if any).
  7. Bird constructor completes
  8. Sparrow instance variables are given their explicit values (if any). 
  9. Sparrow constructor completes.
You can find below,  how constructors are working in call stack

  1. Object()
  2.  Bird() calls super()
  3.  Sparrow() calls super()
  4. main() calls  new Sparrow()


Monday, April 18, 2011

Nested Classes

A class defined within another class is called a nested class. Like other members of a class, a nested class can be declared static or not. A nonstatic nested class is called an inner class. An instance of an inner class can exist only within an instance of its enclosing class and has access to its enclosing class's members even if they are declared private.
The following table shows the types of nested classes: 

Types of Nested Classes
Type Scope Inner
static nested class member no
inner [non-static] class member yes
local class local yes
anonymous class only the point where it is defined yes

Wednesday, April 6, 2011

Java Display Image Gray

JButton  photoBtn = new JButton();
File file = new File("C:/photos/myImage.jpg");
BufferedImage myImage = ImageIO.read(file);
BufferedImage imageGray = new BufferedImage(myImage.getWidth(), myImage.getHeight(), BufferedImage.TYPE_BYTE_GRAY);
Graphics g = imageGray.getGraphics();
g.drawImage(myImage, 0, 0, 200, 200, null);
g.dispose();
photoBtn.setIcon(new ImageIcon(imageGray));
photoBtn.revalidate();

The above code display colored image as gray in button as icon.

Tuesday, April 5, 2011

Java 5 Feature : Formatted Output: printf

Takes a variable number of arguments
– System.out.printf("Formatting String", arg1, arg2, …);
• Advantages
– Lets you insert values into output without much clumsier String concatenation.
– Lets you control the width of results so things line up
– Lets you control the number of digits after the decimal point in numbers, for consistent-looking output
• Very similar to C/C++ printf function
– If you know printf in C/C++, you can probably use Java's printf immediately without reading any documentation
        • Although some additions in time formatting and locales
– Use String.format to get the equivalent of C's sprintf

Monday, April 4, 2011

Java reserved words for literal values


false
A boolean literal value.
null
A reference literal value.
true
A boolean literal value.

Saturday, April 2, 2011

Java Basics


A Java program is mostly a collection of objects talking to other objects by invoking each other's methods. Every object is of a certain type, and that type is defined by a class or an interface. Most Java programs use a collection of objects of many different types.


  • Class A template that describes the kinds of state and behavior that objects of its type support. 

  • Object At runtime, when the Java Virtual Machine (JVM) encounters the new keyword, it will use the appropriate class to make an object which is an instance of that class. That object will have its own state, and access to all of the behaviors defined by its class.

  • State (instance variables) Each object (instance of a class) will have its own unique set of instance variables as defined in the class. Collectively, the values assigned to an object's instance variables make up the object's state.



  • Behavior (methods) When a programmer creates a class, she creates methods for that class. Methods are where the class' logic is stored. Methods are where the real work gets done. They are where algorithms get executed, and data gets manipulated.

Sunday, March 13, 2011

JAVA 7 Features


Virtul Machine

JSR 292: Support for dynamically-typed languages (InvokeDynamic)

VM and language extensions to support the implementation of dynamically-typed languages at performance levels near to that of the Java language itself

Strict class-file checking [NEW]
Per the Java SE 6 specification, class files of version 51 (SE 7) or later must be verified with the typechecking verifier introduced by JSR 202 in Java SE 6; the VM must not fail over to the old inferencing verifier

Language

JSR 334: Small language enhancements (Project Coin)

A set of small language changes intended to simplify common, day-to-day programming tasks:

1.      Strings in switch statements
2.      Automatic resource management
3.      Improved type inference for generic instance creation ("diamond")
4.      Simplified varargs method invocation,
5.      Better integral literals,
6.       Improved exception handling (multi-catch)

Core

Upgrade class-loader architecture

Modifications to the ClassLoader API and implementation to avoid deadlocks in non-hierarchical class-loader topologies

Method to close a URLClassLoader

A method that frees the underlying resources, such as open files, held by a URLClassLoader

Concurrency and collections updates (jsr166y)

A lightweight fork/join framework, flexible and reusable synchronization barriers, transfer queues, a concurrent-reference HashMap, and thread-local pseudo-random number generators

Internationalization

Unicode 6.0

Upgrade the supported version of Unicode to 6.0

Locale enhancement

Upgrade the java.util.Locale class to support IETF BCP 47 and UTR 35 (CLDR/LDML)

Separate user locale and user-interface locale

Upgrade the handling of locales to separate formatting locales from user-interface language locales, as is done on Vista and later versions of Windows

I/O and Networking

JSR 203: More new I/O APIs for the Java platform (NIO.2)

New APIs for filesystem access, scalable asynchronous I/O operations, socket-channel binding and configuration, and multicast datagrams

NIO.2 filesystem provider for zip/jar archives

A fully-functional and supported NIO.2 filesystem provider for zip and jar files

SCTP (Stream Control Transmission Protocol)

An implementation-specific API for the Stream Control Transmission Protocol on Solaris

SDP (Sockets Direct Protocol)

Implementation-specific support for reliable, high-performance network streams over Infiniband connections on Solaris and Linux

Use the Windows Vista IPv6 stack

Upgrade the networking code to use the Windows Vista IPv6 stack, when available, in preference to the legacy Windows stack

TLS 1.2

Add support for TLS 1.2, which was standardized in 2008 as RFC 5246

Security & Cryptography

Elliptic-curve cryptography (ECC)

A portable implementation of the standard Elliptic Curve Cryptographic (ECC) algorithms, so that all Java applications can use ECC out-of-the-box

JDBC

JDBC 4.1

Upgrade to JDBC 4.1 and Rowset 1.1

Client

XRender pipeline for Java 2D

A new Java2D graphics pipeline based upon the X11 XRender extension, which provides access to much of the functionality of modern GPUs

Create new platform APIs for 6u10 graphics features

Create new platform APIs for features originally implemented in the 6u10 release: Translucent and shaped windows, heavyweight/lightweight mixing, and the improved AWT security warning

Nimbus look-and-feel for Swing

A next-generation cross-platform look-and-feel for Swing

Swing JLayer component

Add the SwingLabs JXLayer component decorator to the platform

Web

Update the XML stack

Upgrade the JAXP, JAXB, and JAX-WS APIs to the most recent stable versions

Management

Enhanced JMX Agent and MBeans [NEW]

An implementation-specific enhanced JMX management agent, ported from JRockit, which makes it easier to connect to the platform MBean server through firewalls, together with a richer set of MBeans which expose additional information about the internal operation of the VM

Deferred to JDK 8 or later

JSR 294: Language and VM support for modular programming

Enhancements to the Java language and virtual-machine specifications to support modular programming, at both compile time and run time

JSR 308: Annotations on Java types

An extension to the Java annotation syntax to permit annotations on any occurrence of a type

JSR TBD: Language support for collections

Literal expressions for immutable lists, sets, and maps, and indexing-access syntax for lists and maps

JSR TBD: Project Lambda

Lambda expressions (informally, "closures") and defender methods for the Java programming language

Modularization (Project Jigsaw)

A simple, low-level module system focused upon the goal of modularizing the JDK, and the application of that system to the JDK itself

JSR 296: Swing application framework

An API to define the basic structure of a typical Swing application, thereby eliminating lots of boilerplate code and providing a much-improved initial developer experience

Swing JDatePicker component

Add the SwingLabs JXDatePicker component to the platform



Thursday, June 3, 2010

Singleton - Multiple Users [Thread Safe]

Following is the way by which we can use Singleton Design pattern for multiple users.

public class Singleton {
         private volatile static Singleton singleton; //volatile is needed so that multiple thread can reconcile the instance
         private Singleton(){
         }

         public static Singleton getSingleton(){ //synchronized keyword has been removed from here
         if(singleton = = null)
         {          //needed because once there is singleton available no need to aquire monitor again & again as it is costly
                synchronized(Singleton.class)
                {
                        //this is needed if two threads are waiting at the monitor at the time when singleton was getting instantiated
                      if(singleton==null)
                      {      
                              singleton= new Singleton();
                       }
                  }
          }
          return singleton;
    }
}

Wednesday, May 5, 2010

Read value from Java properties

Here, you will find the source code to read value of the key from properties file. java.util.Properties class extends Hashtable. Properties class creates the properties file which stores key - value pair using Hashtable. To retrieve value from properties file we have to follow following steps.
  1. Create an object of Properties class.
  2. Load properties file using FileInputStream into properties object.
  3. Get value from properties object using getProperty() method passing key as an input.
The below code will help to understand more...

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;

public class PropertiesReadTest {

    public static void main(String[] args) {
        Properties properties = new Properties();
        try {
            properties.load(new FileInputStream("C:\\temp\\test.properties"));
            String value = properties.getProperty("key");
            System.out.println("Value = " + value);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Output is shown here in following image





Tuesday, May 4, 2010

Source code to read content of File

Here you will find the source code to read the content of file.

Steps
  1. Create the FileReader object using file name as an input to FileReader constructor.
  2. Pass that FileReader object to BufferedReader.
  3. Read the line from BufferedReader object till readline gets null.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class FileReadTest {

    public static void main(String[] args) {
         try {
            BufferedReader br = new BufferedReader(new FileReader("C:\\temp\\test.txt"));
            String line = "";
            while((line = br.readLine()) != null)
            {
                System.out.println(line);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}


Friday, April 30, 2010

Java pass by value or pass by reference

  • Java manipulates objects by reference, and all object variables are references. However, Java doesn't pass method arguments by reference; it passes them by value.
  • Java is strictly pass-by-value, exactly as in C.
  • Java has pointers and is strictly pass-by-value.


Thursday, April 29, 2010

Encapsulation in JAVA

Encapsulation in java means declare instance variables of class as private and access that instance variables using public methods.
Following is the example which shows that Person class having name and age are private instance variables and those are accessed by public getter and setter methods.

public class Person {
    private String name;
    private int age;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
}



OOPs concepts in JAVA

  • Abstraction: Hides certain details and only show the essential features of the object.
  • Encapsulation: The internal representation of an object is generally hidden from view outside of the object's definition.
  • Inheritance: Defines relationships among classes in an object-oriented language.  
  • Polymorphism: Define more than one method with the same name.


    finally block not executed

    Finally block is always executed except some of the following cases.
    • If the JVM exits while the try or catch code is being executed, then the finally block may not execute. 
              e.g. System.exit(0);
    • If the thread executing the try or catch code is interrupted or killed, the finally block may not execute even though the application as a whole continues. 
             e.g. Thread.interrupted();


    Wednesday, April 14, 2010

    Retrieve key from HashMap using value

    Below is the code to retrieve the key from HashMap using value
    import java.util.HashMap;
    import java.util.Map;
    import java.util.Set;
    import java.util.Map.Entry;

    public class TestClass {

        public static void main(String[] args) {
            Map<Integer, Person> people = new HashMap<Integer, Person>();
            Person person1 = new Person();
            person1.setName("Mack");
            person1.setPost("Dev");
           
            Person person2 = new Person();
            person2.setName("John");
            person2.setPost("Dev");
           
            people.put(1, person1);
            people.put(2, person2);

            Set<Entry<Integer, Person>> peopleSet = people.entrySet();
            for (Entry<Integer, Person> entry : peopleSet) {
                Integer key = entry.getKey();
                Person value = entry.getValue();
                if (value.equals(person2)) {
                    System.out.println("Key = " + key);
                }
            }
        }
    }


    Monday, April 12, 2010

    Serialization and Deserialization

    1. Serialization is the process of transforming an in-memory object to a byte stream
    2. An object is serialized by writing it to an ObjectOutputStream. 
    3. Serialization Code 
               FileOutputStream out = new FileOutputStream("test.txt" );
               ObjectOutputStream oos = new ObjectOutputStream( out );
               oos.writeObject(new String ());
               oos.close ();
    1. Deserialization is the inverse process of reconstructing an object from a byte stream to the same state in which the object was previously serialized. 
    2. An object is deserialized by reading it from an ObjectInputStream.
    3. Deserialization Code
    FileInputStream in = new FileInputStream( "test.txt" );
    ObjectInputStream ois = new ObjectInputStream( in );
    String s = (String) ois.readObject();
    ois.close();



    Thursday, April 8, 2010

    Difference between abstract class and interface

    What is an Abstract Class?

    1. An abstract class is a special kind of class that cannot be instantiated.So the question is why we need a class that cannot be instantiated? An abstract class is only to be sub-classed (inherited from). In other words, it only allows other classes to inherit from it but cannot be instantiated. The advantage is that it enforces certain hierarchies for all the subclasses. In simple words, it is a kind of contract that forces all the subclasses to carry on the same hierarchies or standards.
    2.  A class may inherit only one abstract class.
    3. An abstract class can contain access modifiers for the subs, functions, properties
    4. Fast
    5. An abstract class can have fields and constants defined

    What is an Interface?

    1. An interface is not a class. It is an entity that is defined by the word Interface. An interface has no implementation; it only has the signature or in other words, just the definition of the methods without the body. As one of the similarities to Abstract class, it is a contract that is used to define hierarchies for all subclasses or it defines specific set of methods and their arguments. The main difference between them is that a class can implement more than one interface but can only inherit from one abstract class.
    2. A class may inherit several interfaces.
    3. An interface cannot have access modifiers for the subs, functions, properties etc everything is assumed as public
    4. Requires more time to find the actual method in the corresponding classes.
    5. No fields can be defined in interfaces

    Friday, March 26, 2010

    What is difference between HashMap and HashTable and HashSet and TreeSet?

    Hashtable
    Hashtable is basically a data structure to retain values of key-value pair
    •  It didn’t allow null for both key and value. You will get NullPointerException if you add null value.
    • It is synchronized. So it comes with its cost. Only one thread can access in one time. So It is slow.
    HashMap
    Like Hashtable it also accepts key value pair.
    • It allows null for both key and value. 
    • It is unsynchronized. So come up with better performance(fast)

    HashSet
    It is from Set family.
    • HashSet does not allow duplicate values. 
    • It provides add method rather put method. 
    • You also use its contains method to check whether the object is already available in HashSet. 
    • HashSet can be used where you want to maintain a unique set but not the order. 


    TreeSet
     It is also from Set family.
    • Likely HashSet, TreeSet does not allow duplicate values.
    • It provides add method rather put method. 
    • You also use its contains method to check whether the object is already available in TreeSet. 
    • TreeSet can be used where you want to maintain a unique set as well as the order. 



    Friday, February 12, 2010

    What is difference between Unchecked and Checked Exceptions?

    Unchecked exceptions :
    • represent defects in the program (bugs) - often invalid arguments passed to a non-private method. To quote from The Java Programming Language, by Gosling, Arnold, and Holmes : "Unchecked runtime exceptions represent conditions that, generally speaking, reflect errors in your program's logic and cannot be reasonably recovered from at run time."
    • are subclasses of RuntimeException, and are usually implemented using IllegalArgumentException, NullPointerException, or IllegalStateException
    • a method is not obliged to establish a policy for the unchecked exceptions thrown by its implementation (and they almost always do not do so)
    Checked exceptions :
    • represent invalid conditions in areas outside the immediate control of the program (invalid user input, database problems, network outages, absent files)
    • are subclasses of Exception
    • a method is obliged to establish a policy for all checked exceptions thrown by its implementation (either pass the checked exception further up the stack, or handle it somehow)

    Thursday, February 11, 2010

    What is difference between Synchronized method and Synchronized block?

    What is difference between Synchronized method and Synchronized block?


    The key difference is this: if you declare a method to be synchronized, then the entire body of the method becomes synchronized; if you use the synchronized block, however, then you can surround just the "critical section" of the method in the synchronized block, while leaving the rest of the method out of the block.
    If the entire method is part of the critical section, then there effectively is no difference. If that is not the case, then you should use a synchronized block around just the critical section. The more statements you have in a synchronized block, the less overall parallelism you get, so you want to keep those to the minimum.

    What is difference between ArrayList and Vector ?

    1. The Vector class is synchronized, the ArrayList is not.
    2. ArrayList is fast than the Vector.