Friday, 25 April 2014

nested classes in java

Defination
class declared inside a class is known as nested class.

Syntax

Class Outer_Class_Name{
...
...
   Class Inner_Class_Name{
   ...
   ...
   }
}

Types of nested classes
There are two types of nested classes non-static inner classes and static nested classes.
  1. non-static nested class(inner class)
    • a)Member inner class
    • b)Annomynous inner class
    • c)Local inner class
  2. static nested class


Difference between non-static inner classes and static nested classes in Java?

Non-static inner classes  have access to other members of the enclosing class, even if they are declared private. 
Static nested classes do not have access to other members of the enclosing class.

Difference between narmal classes and  nested classes in Java?

A nested class is a member of its enclosing class.
As a member of the OuterClass, a nested class can be declared privatepublicprotected, or package private
(Recall that outer classes can only be declared public or package private.)

Advantage of nested classes?

Why Use Nested Classes?

Compelling reasons for using nested classes include the following:
  • It is a way of logically grouping classes that are only used in one place: If a class is useful to only one other class, then it is logical to embed it in that class and keep the two together. Nesting such "helper classes" makes their package more streamlined.
  • It increases encapsulation: Consider two top-level classes, A and B, where B needs access to members of A that would otherwise be declaredprivate. By hiding class B within class A, A's members can be declared private and B can access them. In addition, B itself can be hidden from the outside world.
  • It can lead to more readable and maintainable code: Nesting small classes within top-level classes places the code closer to where it is used.


static nested class

A static class that is created inside a class is known as static nested class.
  • It can access static data members of outer class including private.
  • It cannot refer directly to instance variables or methods defined in its enclosing class: it can use them only through an object reference.
  • static nested class cannot access non-static (instance) data members directly.



Wednesday, 19 February 2014

how to get current system operating system name in java

use below c0de in your java class
String osName = System.getProperty("os.name");
System.out.println("Os: " + osName);


Friday, 1 November 2013

java.io package

This lesson covers the Java platform classes used for basic I/O. It first focuses on I/O Streams, a powerful concept that greatly simplifies I/O operations. The lesson also looks at serialization, which lets a program write whole objects out to streams and read them back again. Then the lesson looks at file I/O and file system operations, including random access files.
Most of the classes covered in the I/O Streams section are in the java.io package.
Most of the classes covered in the File I/O section are in the java.nio.file package.

I/O Streams

I/O Streams

An I/O Stream represents an input source or an output destination.
A stream can represent many different kinds of sources and destinations, including disk files, devices, other programs, and memory arrays.
Streams support many different kinds of data, including simple bytes, primitive data types, localized characters, and objects.
Some streams simply pass on data; others manipulate and transform the data in useful ways.
No matter how they work internally, all streams present the same simple model to programs that use them:
A stream is a sequence of data.
A program uses an input stream to read data from a source, one item at a time:
Reading information into a program.
Reading information into a program.
A program uses an output stream to write data to a destination, one item at time:
Writing information from a program.
Writing information from a program.
In this lesson, we'll see streams that can handle all kinds of data, from primitive values to advanced objects.
The data source and data destination pictured above can be anything that holds, generates, or consumes data.
Obviously this includes disk files, but a source or destination can also be another program, a peripheral device, a network socket, or an array.
In the next section, we'll use the most basic kind of streams, byte streams, to demonstrate the common operations of Stream I/O. For sample input, we'll use the example file in.txt, which contains the following





Byte Streams

Programs use byte streams to perform input and output of 8-bit bytes. All byte stream classes are descended from InputStream and OutputStream.
There are many byte stream classes. To demonstrate how byte streams work, we'll focus on the file I/O byte streams, FileInputStream and FileOutputStream. Other kinds of byte streams are used in much the same way; they differ mainly in the way they are constructed.

Using Byte Streams

We'll explore FileInputStream and FileOutputStream by examining an example program named CopyBytes, which uses byte streams to copy xanadu.txt, one byte at a time.
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class CopyBytes {
    public static void main(String[] args) throws IOException {

        FileInputStream in = null;
        FileOutputStream out = null;

        try {
            in = new FileInputStream("xanadu.txt");
            out = new FileOutputStream("outagain.txt");
            int c;

            while ((c = in.read()) != -1) {
                out.write(c);
            }
        } finally {
            if (in != null) {
                in.close();
            }
            if (out != null) {
                out.close();
            }
        }
    }
}
CopyBytes spends most of its time in a simple loop that reads the input stream and writes the output stream, one byte at a time, as shown in the following figure.
Simple byte stream input and output.
Simple byte stream input and output.
Notice that read() returns an int value. If the input is a stream of bytes, why doesn't read() return a byte value? Using a int as a return type allows read() to use -1 to indicate that it has reached the end of the stream.

Always Close Streams

Closing a stream when it's no longer needed is very important — so important that CopyBytes uses a finally block to guarantee that both streams will be closed even if an error occurs. This practice helps avoid serious resource leaks.
One possible error is that CopyBytes was unable to open one or both files. When that happens, the stream variable corresponding to the file never changes from its initial null value. That's why CopyBytes makes sure that each stream variable contains an object reference before invoking close.

When Not to Use Byte Streams

CopyBytes seems like a normal program, but it actually represents a kind of low-level I/O that you should avoid. Since xanadu.txt contains character data, the best approach is to usecharacter streams, as discussed in the next section. There are also streams for more complicated data types. Byte streams should only be used for the most primitive I/O.
So why talk about byte streams? Because all other stream types are built on byte streams.

hi

Friday, 16 August 2013

Differences between Object and Instance

Differences between Object and Instance

There is a lot of discussions on this topic over the internet. Some of the people says both are same and some of other says both are different. Here I am planning to share my overall view on this topic. As per my knowledge both are looks same but different. Here are the some useful points:
  • Instance is Logical but object is Physical means occupies some memory.
  • We can create an instance for abstract class as well as for interface, but we cannot create an object for those.
  • Object is instance of class and instance means representative of class i.e object.
  • Instance refers to Reference of an object.
  • Object is actually pointing to memory address of that instance.
  • You can’t pass instance over the layers but you can pass the object over the layers
  • You can’t store an instance but you can store an object
  • A single object can have more than one instance.
  • Instance will have the both class definition and the object definition where as in object it will have only the object definition.
Syntax of Object:
classname var = new classname();
Syntax of Instance:
classname varname; 
But for instance creation it returns only a pointer refering to an object, syntax is : 

Tuesday, 5 April 2011

what is interface

interface

Definition:

Interface is a pure abstract class that contains

public static final variables,

public Abstract methods

It provides only forcibility (specification) to subclass.

Need of interface:

Interface is invented in java for below two reasons

1) For releasing specification

2) For implementing multiple inheritance

Syntax:

[public/] interface

{

public static final data-type variable-name=variable value;

---------- -----------------------------------------------------------------;

----------------------------------------------------------------------------;

public abstract return-type method-name(arguments list…);

---------- -----------------------------------------------------------------;

----------------------------------------------------------------------------;

}

Creating interface

Using keyword “interface” programmers can develop a class of type interface.

We can create public and default interface, but we can’t create private and protected interfaces

The default access specifier of interface is

Before interface-name we can place “abstract” keyword in our .java file but in compilation phase compiler removes abstract keyword and generates .class file

Variables in interfaces

In interface by default all variables are public static final variables.

Public – because it as to access from ay where.

Static – because we can’t instance interface.

Final – because it is common value for all subclases

Since interface variables are static final, it must be initialized else it leads to

CE symbol “=” expected

Methods in interfaces

In interface by default all methods are public and abstract methods

since methods has to access from anywhere outside the class.

By default interface members access specifier is public

/*this is our written code means InterfaceDemo1.java file*/

interface InterfaceDemo1

{

public static final String shape = "Quadrilateral";

int sides = 4;

public abstract double areaOfQuadrilateral();

double perimeterOfQuadrilateral();

}

/*this is the compiler changed code means InterfaceDemo1.class file*/

interface InterfaceDemo1

{

public abstract double areaOfQuadrilateral();

public abstract double perimeterOfQuadrilateral();

public static final String shape = "Quadrilateral";

public static final int sides = 4;

}

/*

here we can see in variable declaration missing keywords are automatically

placed by compiler.

and interface access specifier "public" keyword not placed,

interface default access specifier is

*/

/*

We can compile interface but we can’t execute

because it doesn’t contain main method.

*/

Rules on interface

Do

Don’t

For interface either directly or indirectly can't be instantiated (creating objects). because it doesn't have a constructor. Violation leads to CompiletimeError CE:InterfaceDemo1 is abstract can't be instantiated.

But we can create reference variables of interface to store either null or its subclass object reference

In interface we can’t write concrete methods, including constructors and static and non static blocks. Violation leads to CE: interface method can’t have a body.

Inheritance with interface

We must use “implement” keyword to establish inheritance relation between class and interface

Rule on interface subclass

Subclass must implement all abstract methods of interface, else subclass should be declare as abstract otherwise it leads to CompiletimeError

These implementing methods access specifier in subclass should also be public, because interface methods are public methods.

Developing inheritance with two interface

we should use “extends” keyword to establish inheritance relation between two interfaces

Multiple inheritance using interfaces

Extending super class and implements interfaces

Extending interfaces

Difference between Interface and Abstract class

what is abstraction

Abstraction

Defination:

The process of providing necessary information (method proto-type ) by removing / hiding unnecessary information (method body) is called Abstraction.

Hiding implementation

Removing implementation

In first case (hiding implementation) abstraction provides reusability to the subclass developer.

As a superclass developer we define a method with logic and inform to user (subclass developer) only prototype, for using this method implementation is unnecessary for subclass developer.

EX

System.out.println();

Here we don’t bother about println() method implementation

All classes by default contain concrete methods hence they are implementing abstraction at first level.

in second case (removing implementation) abstraction provides forcibility to the subclass developer.

we should explicitly implement abstraction at second level

it means in super class we define a method without body, the method should be overridden and implemented in subclass based on subclass business requirement.

below steps shows us, implementing abstraction at second level for sub classes to implement sum logic.

1. Create abstract class by using abstract keyword.

Syntax

abstract class

Ex

public abstract MyAbstract{

2. Declare abstract method in that class , remove body of the method({}) And declare it as abstract method, by using abstract keyword(modifier)

Syntax

abstract(parameterlist);

EX

abstract void m1();

3. Define subclass from this abstract class and override abstract method in the subclass with that class business requirement

Rules in creating abstract class

1 it should contain abstract modifier in its prototype and should not have body else it leads to compile time error.

2 if a class contain abstract method it should be declared as abstract else it leads to compile time error.

Rules in implementing abstraction

Rule 1

abstract method must contain abstract keyword else it leads to compile time error missing method body or declare abstract.

Ex

void add();// CE

Abstract void add();

Rule 2

if a class contain abstract method it should be declared as abstract class using abstract keyword else it leads to compile time error.

Ex

Class Example{

Abstract void add ();//CE

}

Abstract class Example {

Abstraction void m1();

}

Rule 3

If a class is declared as abstract it can’t be instantiated directly means object can’t be create by using its constructor violation leads to CE

Ex

abstract class Example {

abstraction void m1();

p s v m (String[] args){

Example e= new Example();//CE: Example is abstract can’t be instantiated

}

Rule 4

Sub class must override all abstract methods of its super calss else it should be declared as abstract violation leads to compile time error

EX

class Sample extends Example{}//CE sample is not a abstract and doesnot override abstract method m1 in Example.

To solve the above CE we can give below 2 solutions

1) Declare sample class as abstract

2) Declare body for m1() in sample which is abstract method in Example

Wednesday, 23 March 2011

java Data Types

Data Types

THE Java programming language is a strongly typed (not keyboard typing it’s a Data Types)) language, which means that every variable and every expression has a type (data type) that is known at compile time.

Types limit the values that a variable can hold or that an expression can produce, limit the operations supported on those values, and determine the meaning of the operations. Strong typing helps detect errors at compile time.

The types of the Java programming language are divided into two categories:

The primitive types are

the boolean type and

the numeric types.

The numeric types are

the integral type’s

byte, short, int, long, and char, and

the floating-point types

`float and double.

There is also a special null type

4.1 The Kinds of Types and Values

There are two kinds of data types in the Java programming language:

primitive types and

reference types . correspondingly,

There are, two kinds of data values that can be stored in variables, passed as arguments,returned by methods, and operated on:

primitive values and

Reference values

There is also a special null type

the type of the expression null, which has no name. Because the null type has no name, it is impossible to declare a variable of the null type or to cast to the null type. The null reference is the only possible value of an expression of null type. The null reference can always be cast to any reference type.

In practice, the programmer can ignore the null type and just pretend that null is merely a special literal that can be of any reference type

4.2 Primitive Types and Values

A primitive type is predefined by the Java programming language and named by its reserved keyword

Primitive Type:

1) Numeric Type

2) boolean type

The boolean type has exactly two values: true and false

Numeric Type:

1) Integral Type

2) Floating Point Type

Integral Type: one of byte ,short, int ,long ,char

Floating Point Type: one of float ,double

The numeric types are the

integral types and the

floating-point types.

The integral types are byte, short, int, and long, whose values are 8-bit,

16-bit, 32-bit and 64-bit signed two’s-complement integers, respectively, and

char, whose values are 16-bit unsigned integers representing UTF-16 code units

The floating-point types are float, whose values include the 32-bit IEEE 754

floating-point numbers, and double, whose values include the 64-bit IEEE 754

floating-point numbers.

The boolean type has exactly two values: true and false

4.2.1)Integral Types and Values

The values of the integral types are integers in the following ranges:

• For byte, from –128 to 127, inclusive

• For short, from –32768 to 32767, inclusive

• For int, from –2147483648 to 2147483647, inclusive

• For long, from –9223372036854775808 to 9223372036854775807

• For char, from '\u0000' to '\uffff' inclusive, that is, from 0 to 65535

4.2.2 Integer Operations

4.2.3 Floating-Point Types, Formats, and Values

The floating-point types are

float, whose values include the 32-bit IEEE 754 floating-point numbers, and

double, whose values include the 64-bit IEEE 754 floating-point numbers.

4.2.4 Floating-Point Operations

4.2.5 The boolean Type and boolean Values

The boolean type represents a logical quantity with two possible values, indicated by the literals true and false (§3.10.3).

4.3 Reference Types and Values

There are three kinds of reference types:

class types (§8),

interface types (§9), and

array types (§10).

Reference types may be parameterized (§4.5) with type arguments (§4.4).

The reference types are

class types,

interface types, and

array types. There is also a special

null type.