Powered By Blogger

Sunday, 11 November 2012

Program In JAVA in convention


Q. Why Java?
A. The programs that we are writing are very similar to their counterparts in several
other languages, so our choice of language is not crucial. We use Java because
it is widely available, embraces a full set of modern abstractions, and has a variety
of automatic checks for mistakes in programs, so it is suitable for learning to program.
There is no perfect language, and you certainly will be programming in other
languages in the future.
Q. Do I really have to type in the programs in the book to try them out? I believe
that you ran them and that they produce the indicated output.
A. Everyone should type in and run HelloWorld. Your understanding will be
greatly magnified if you also run UseArgument, try it on various inputs, and modify
it to test different ideas of your own. To save some typing, you can find all of the
code in this book (and much more) on the booksite. This site also has information
about installing and running Java on your computer, answers to selected exercises,
web links, and other extra information that you may find useful or interesting.
Q. What is the meaning of the words public, static and void?
A. These keywords specify certain properties of main() that you will learn about
later in the book. For the moment, we just include these keywords in the code (because
they are required) but do not refer to them in the text.
Q. What is the meaning of the //, /*, and */ character sequences in the code?
A. They denote comments, which are ignored by the compiler. A comment is either
text in between /* and */ or at the end of a line after //. As with most online code,
the code on the booksite is liberally annotated with comments that explain what it
does; we use fewer comments in code in this book because the accompanying text
and figures provide the explanation.
Q. What are Java’s rules regarding tabs, spaces, and newline characters?
A. Such characters are known as whitespace characters. Java compilers consider
all whitespace in program text to be equivalent. For example, we could write Hel-

1  Your First Program 11
Hello World as follows:
public class Hello World { public static void main ( String []
args) { System.out.print("Hello, World") ; System.out.
println() ;} }
But we do normally adhere to spacing and indenting conventions when we write
Java programs, just as we always indent paragraphs and lines consistently when we
write prose or poetry.
Q. What are the rules regarding quotation marks?
A. Material inside quotation marks is an exception to the rule defined in the previous
question: things within quotes are taken literally so that you can precisely
specify what gets printed. If you put any number of successive spaces within the
quotes, you get that number of spaces in the output. If you accidentally omit a
quotation mark, the compiler may get very confused, because it needs that mark to
distinguish between characters in the string and other parts of the program.
Q. What happens when you omit a brace or misspell one of the words, like public
or static or void or main?
A. It depends upon precisely what you do. Such errors are called syntax errors and
are usually caught by the compiler. For example, if you make a program Bad that is
exactly the same as HelloWorld except that you omit the line containing the first
left brace (and change the program name from HelloWorld to Bad), you get the
following helpful message:
% javac Bad.java
Bad.java:2: '{' expected
public static void main(String[] args)
^
1 error
From this message, you might correctly surmise that you need to insert a left brace.
But the compiler may not be able to tell you exactly what mistake you made, so the
error message may be hard to understand. For example, if you omit the second left
brace instead of the first one, you get the following messages:

 2 Elements of Programming
% javac Bad.java
Bad.java:4: ';' expected
System.out.print("Hello, World");
^
Bad.java:7: 'class' or 'interface' expected
}
^
Bad.java:8: 'class' or 'interface' expected
^
3 errors
One way to get used to such messages is to intentionally introduce mistakes into a
simple program and then see what happens. Whatever the error message says, you
should treat the compiler as a friend, for it is just trying to tell you that something
is wrong with your program.
Q. Can a program use more than one command-line argument?
A. Yes, you can use many arguments, though we normally use just a few. Note that
the count starts at 0, so you refer to the first argument as args[0], the second one
as args[1], the third one as args[2], and so forth.
Q. What Java methods are available for me to use?
A. There are literally thousands of them. We introduce them to you in a deliberate
fashion (starting in the next section) to avoid overwhelming you with choices.
Q. When I ran UseArgument, I got a strange error message. What’s the problem?
A. Most likely, you forgot to include a command-line argument:
% java UseArgument
Hi, Exception in thread “main”
java.lang.ArrayIndexOutOfBoundsException: 0
at UseArgument.main(UseArgument.java:6)
The JVM is complaining that you ran the program but did not type an argument as
promised. You will learn more details about array indices in SECTION 1.4. Remember
this error message: you are likely to see it again. Even experienced programmers
forget to type arguments on occasion.
!

Your First Program In JAVA


   Your First Program
IN THIS SECTION, OUR PLAN IS to lead you into the world of Java programming by taking
you through the basic steps required to get a simple program running. The Java
system is a collection of applications, not unlike many of the other applications
that you are accustomed to using (such
as your word processor, email program,
and internet browser). As with any application,
you need to be sure that Java
is properly installed on your computer



Programming in Java To introduce you to developing Java programs, we
break the process down into three steps. To program in Java, you need to:
1.Create a program by typing it into a file named, say, MyCode.java.
 2.Compile it by typing javac MyCode.java in a terminal window.
 3.Run (or execute) it by typing java MyCode in the terminal window.
In the first step, you start with a blank screen and end with a sequence of typed
characters on the screen, just as when you write an email message or a paper. Programmers
use the term code to refer to program text and the term coding to refer
to the act of creating and editing the code. In the second step, you use a system application
that compiles your program (translates it into a form more suitable for the
computer) and puts the result in a file named MyCode.class. In the third step, you
transfer control of the computer from the system to your program (which returns
control back to the system when finished). Many systems have several different
ways to create, compile, and execute programs. We choose the sequence described
here because it is the simplest to describe and use for simple programs.

Creating a program. A Java program is nothing more than a sequence of characters,
like a paragraph or a poem, stored in a file with a .java extension. To create
one, therefore, you need only define that sequence of characters, in the same way
as you do for email or any other computer application


 .
Compiling a program. At first, it might seem that Java is designed to be best understood
by the computer. To the contrary, the language is designed to be best understood
by the programmer (that’s you). The computer’s language is far more
primitive than Java. A compiler is an application that translates a program from the
Java language to a language more suitable for executing on the computer. The compiler
takes a file with a .java extension as input (your program) and produces a
file with the same name but with a .class extension (the computer-language version).
To use your Java compiler, type in a terminal window the javac command
followed by the file name of the program you want to compile.
Executing a program. Once you compile the program, you can run it. This is the
exciting part, where your program takes control of your computer (within the constraints
of what the Java system allows). It is perhaps more accurate to say that your
computer follows your instructions. It is even more accurate to say that a part of
the Java system known as the Java Virtual Machine (the JVM, for short) directs your
computer to follow your instructions. To use the JVM to execute your program,
type the java command followed by the program name in a terminal window.
your program
(a text file)
computer-language
version of your program
type javac HelloWorld.java
to compile your program
use any text editor to
create your program
type java HelloWorld
to execute your program
output
Developing a Java program
editor HelloWorld.java compiler HelloWorld.class JVM "Hello, World"

6 Elements of Programming
% javac HelloWorld.java
% java HelloWorld
Hello, World
  IS AN EXAMPLE OF a complete Java program. Its name is HelloWorld,
which means that its code resides in a file named HelloWorld.java (by convention
in Java). The program’s sole action is to print a message back to the terminal window.
For continuity, we will use some standard Java terms to describe the program,
but we will not define them until later in the book: PROGRAM 1.1.1 consists of a single
class named HelloWorld that has a single method named main(). This method uses
two other methods named System.out.print() and System.out.println() to
do the job. (When referring to a method in the text, we use () after the name to
distinguish it from other kinds of names.) Until SECTION 2.1, where we learn about
classes that define multiple methods, all of our classes will have this same structure.
For the time being, you can think of “class” as meaning “program.”
The first line of a method specifies its name and other information; the rest is
a sequence of statements enclosed in braces and each followed by a semicolon. For
the time being, you can think of “programming” as meaning “specifying a class
  Hello, World
public class HelloWorld
{
public static void main(String[] args)
{
System.out.print("Hello, World");
System.out.println();
}
}
This code is a Java program that accomplishes a simple task. It is traditionally a beginner’s first
program. The box below shows what happens when you compile and execute the program. The
terminal application gives a command prompt (% in this book) and executes the commands
that you type (javac and then java in the example below). The result in this case is that the
program prints a message in the terminal window (the third line).
!
name and a sequence of statements for its main() method.” In the next two sections,
you will learn many different kinds of statements that you can use to make
programs. For the moment, we will just use statements for printing to the terminal
like the ones in HelloWorld.
When you type java followed by a
class name in your terminal application, the
system calls the main() method that you
defined in that class, and executes its statements
in order, one by one. Thus, typing
java HelloWorld causes the system to call
on the main() method in PROGRAM 1.1.1 and
execute its two statements. The first statement
calls on System.out.print() to print
in the terminal window the message between
the quotation marks, and the second
statement calls on System.out.println()
to terminate the line.
Since the 1970s, it has been a tradition that a beginning programmer’s first
program should print "Hello, World". So, you should type the code in PROGRAM
  into a file, compile it, and execute it. By doing so, you will be following in the
footsteps of countless others who have learned how to program. Also, you will be
checking that you have a usable editor and terminal application. At first, accomplishing
the task of printing something out in a terminal window might not seem
very interesting; upon reflection, however, you will see that one of the most basic
functions that we need from a program is its ability to tell us what it is doing.
For the time being, all our program code will be just like PROGRAM 1.1.1, except
with a different sequence of statements in main(). Thus, you do not need to
start with a blank page to write a program. Instead, you can
􀁳􀀀Copy HelloWorld.java into a new file having a new program name of
your choice, followed by .java.
􀁳􀀀Replace HelloWorld on the first line with the new program name.
􀁳􀀀Replace the System.out.print() and System.out.println() statements
with a different sequence of statements (each ending with a semicolon).
Your program is characterized by its sequence of statements and its name. Each
Java program must reside in a file whose name matches the one after the word
class on the first line, and it also must have a .java extension.
main() method
body
name
statements
Anatomy of a program
text file named HelloWorld.java
public class HelloWorld
{
public static void main(String[] args)
{
System.out.print("Hello, World");
System.out.println();
}
}
!

Thursday, 1 November 2012

Why do you overload Constructor in Java ?

When we talk about Constructor overloading, first question comes in mind is why do some one overloadConstructors in Java or why do we have overloaded constructor ? If you have been using framework or API like JDK or Spring you must have seen lot of method overloading and constructor overloading. Constructor overloading make sense if you canConstruct object via different way. One of Classical example of Constructor overloading is ArrayList in Java. ArrayList has three constructors one is empty, other takes a collection object and one take initial Capacity. these overloaded constructor allows flexibility while create arraylist object. It may be possible that you don't know size of arraylist during creation than you can simply use default no argument constructor but if you know size then its best to use overloaded Constructor which takes capacity. Since ArrayList can also be created from another Collection, may be from another List than having another overloaded constructor makes lot of sense. By using overloaded constructor you can converty yourArrayList into Set or any other collection.

Important points related to Constructor overloading:

1. Constructor overloading is similar to method overloading in Java.

2. You can call overloaded constructor by using this() keyword in Java.

3. overloaded constructor must be called from another constructor only.

4. make sure you add no argument default constructor because once compiler will not add if you have added any constructor in Java.

5. if an overloaded constructor called , it must be first statement of constructor in java.

6. Its best practice to have one primary constructor and let overloaded constructor calls that. this way
your initialization code will be centralized and easier to test and maintain.


That’s all on Constructor overloading in java. Biggest advantage of Constructor overloading is flexibility which allows you to create object in different way and classic examples are various Collection classes. Though you should remember that once you add a constructor, compiler will not add default no argument constructor.

Tuesday, 23 October 2012

Automatic memory management in Java


Automatic memory management

Java uses an automatic garbage collector to manage memory in the object lifecycle. The programmer determines when objects are created, and the Java runtime is responsible for recovering the memory once objects are no longer in use. Once no references to an object remain, the unreachable memory becomes eligible to be freed automatically by the garbage collector. Something similar to amemory leak may still occur if a programmer's code holds a reference to an object that is no longer needed, typically when objects that are no longer needed are stored in containers that are still in use. If methods for a nonexistent object are called, a "null pointer exception" is thrown.
One of the ideas behind Java's automatic memory management model is that programmers can be spared the burden of having to perform manual memory management. In some languages, memory for the creation of objects is implicitly allocated on the stack, or explicitly allocated and deallocated from the heap. In the latter case the responsibility of managing memory resides with the programmer. If the program does not deallocate an object, a memory leak occurs. If the program attempts to access or deallocate memory that has already been deallocated, the result is undefined and difficult to predict, and the program is likely to become unstable and/or crash. This can be partially remedied by the use of smart pointers, but these add overhead and complexity. Note that garbage collection does not prevent "logical" memory leaks, i.e. those where the memory is still referenced but never used.
Garbage collection may happen at any time. Ideally, it will occur when a program is idle. It is guaranteed to be triggered if there is insufficient free memory on the heap to allocate a new object; this can cause a program to stall momentarily. Explicit memory management is not possible in Java.
Java does not support C/C++ style pointer arithmetic, where object addresses and unsigned integers (usually long integers) can be used interchangeably. This allows the garbage collector to relocate referenced objects and ensures type safety and security.
As in C++ and some other object-oriented languages, variables of Java's primitive data types are not objects. Values of primitive types are either stored directly in fields (for objects) or on the stack (for methods) rather than on the heap, as commonly true for objects (but see Escape analysis). This was a conscious decision by Java's designers for performance reasons.  
Java contains multiple types of garbage collectors. By default, HotSpot uses the Concurrent Mark Sweep collector, also known as the CMS Garbage Collector. However, there are also several other garbage collectors that can be used to manage the Heap. For 90% of applications in Java, the CMS Garbage Collector is good enough .

Saturday, 13 October 2012

JAVA STRUCTURES






                                                                     Anand Raj
                                                                     anandraj217@gmil.com
                                                                        8298649924

Saturday, 6 October 2012

FEATURES OF JAVA


FEATURES OF JAVA
SIMPLE:-there are various features that Makes the java as a simple language. Programs are easy to write and debug because java does not use the pointers explicitly. it is much   harder to write the java program that can crash the system but cannot say about the other programming languages. Java provides the bug free system due to strong memory management .it also has the automatic memory Allocation and deallocation system.
OBJECT ORIENTED:- to be object oriented language, any language must follow at least the four characteristic.
·         Inheritance: it is process of creating the new classes and using the behavior of the existing classes by extending them just to reuse the existing code and adding features as needed.
·         Encapsulation: it is the mechanism of combing the information and providing the abstraction
·         Polymorphism: As the name suggest one name multiple form, Polymorphism is way of providing the different functionality by the
·         Function having the same name based on the signatures of the methods
·         Dynamic binding: Sometimes we don’t have the knowledge of object about their specific types while writing our code, it is the way of providing the maximum functionality to a program about the specific type at runtime.
As the language like objective C,C++ fulfils the above four characteristics yet they are structured as well as object oriented languages .but in case of java ,it is a fully object oriented language because object is at the outer most level of data structure in java.
·         DISTRIBUTED: Distributed computing involves several computers working together on a Network.java is designed to make distributed computing easy. Since networking capability is inherently integrated into java, writing network programs is like sending and Receiving data to and from a file.
·         ROBUST: Java has the strong memory allocation and automatic garbage collection mechanism. it providing the powerful exception handling and type checking mechanism as compare to other programming language. Compiler checks the program whether there any error and interpreter checks any run time error and makes the system secure from crash .all of the above features make the java language robust.java has eliminated creating types of error programming constructs found in other languages. it not support pointers, for example, thereby eliminating the possibility of overwriting memory and corrupting data.java has a runtime exception handling feature to providing programming support for robustness.java forces the programmer to write the code to deal with exception ,java can catch and respond to an exceptional situation so that the providing can continue its normal execution and terminate.
·         SECURE: java does not use memory pointers explicitly .all the programs in java are run are under an area known as the sand box .security manager determines the accessibility options of a class like reading and writing a file a file to the local disk. Java uses the public key encryption system to allow the java application to transmit over the internet in the secure encrypted from .the byte code verifier checks the classes after loading.
·         ARCHITECTURE NEUTRAL: The term architectural neutral seems to be weird, but yes java is an ARCHITECTURE NEUTRAL language as well. The growing popularity of networks makes developers think distributed. In the world of network it is essential that the application must be able to migrate easily to different computer system .not only to computer system but a wide variety of hardware architecture and operating system   as well. The java compiler does this by generating byte code Instructions to be easily interpreted on any machine and to be easily translated into native machine code on the fly. The compiler generates an architecture nature object file format to enable a java application to execute anywhere on the network and then compiled code is executed on many Processor. Given the presence of the java Runtime system. Hence java was designed to support application on network. This feature of java has Thrived the programming language.
·         PORTABLE: the feature Write-once-run-anywhere makes the java language portable provided that the System must have interpreter for the JVM. java also has the standard data size irrespective of operating system or the processor.ie there are no platform-specific features in the java language. In some languages, such as ada, the largest integer varies on different platforms. But in java, the range of the integer is the same on every platform, asis the Behaviour of arithmetic. The fixed range of the number makes the program portable.
·         Interpreted: we all know that java is an interpreted language as well. With an interpreted language such as java, programs run directly from the code.
The interpreted language depends on an interpreted language depends on an interpreted program.
                  The versatility of being platform independent makes java to outshine from other language.
The source code to be written and distributed is platform independent.
Another advantage of java as interpreted language is its error debugging quality. Due to this any error occurring in the program gets traced. This is how it is different to work with java.
·         HIGH PERFORMANCE: java uses native code usage, and lightweight process called threads. In the beginning interpretation of byte code resulted the performance slow but the advance version of JVM uses the adaptive and just in time compilation technique that improves the performance.
·         MULTTHREDED: As we all know several features of java like Secure, Robust, Portable, Dynamic etc; you  will be more delighted to know another feature of java which is Multithreaded.
Java is also a Multithreaded programming language. Multithreaded means a single program having different threads executing independently at the same time. Multiple threads execute instruction according to the program code in a process or program. Multithreading works the similar way as multiple processes run on one computer.
Multithreading programming is a very interesting concept in java. In java multithreading programs not even a single thread disturbs the execution of other thread . Threads are obtained from the pool of available ready to run threads and they run on the system CPUs. This is how multithreading works in java which you will soon come to know in details in NEXT BLOGS.
·         DYNAMIC: While executing the java program the user can the required files dynamically from a local drive or from a computer thousands of miles away from the user just by connecting with the internet. New class can be loaded on the fly without recompilation .there is no need for developers to create and for users to install, major new software version. New features can be incorporated transparently as needed.
·         PLATFORM INDEPENDENT: The concept of write once run anywhere (Known as the platform independent) is one of the important key feature of java language that makes java as most powerful language .Not even a single language is idle to this feature but java is closer to this feature .the program written on platform can run any platform provided the platform must have the J.V.M.



·          




Tuesday, 2 October 2012

Declaring Classes


Declaring Classes:-
You  seen classes defined in the following way:
class MyClass {
    // field, constructor, and
    // method declarations
}
This is a class declaration. The class body (the area between the braces) contains all the code that provides for the life cycle of the objects created from the class: constructors for initializing new objects, declarations for the fields that provide the state of the class and its objects, and methods to implement the behavior of the class and its objects.
The preceding class declaration is a minimal one. It contains only those components of a class declaration that are required. You can provide more information about the class, such as the name of its superclass, whether it implements any interfaces, and so on, at the start of the class declaration. For example,
class MyClass extends MySuperClass implements YourInterface {
    // field, constructor, and
    // method declarations
}
means that MyClass is a subclass of MySuperClass and that it implements the YourInterface interface.
You can also add modifiers like public or private at the very beginning—so you can see that the opening line of a class declaration can become quite complicated. The modifiers public and private, which determine what other classes can access MyClass, are discussed later in this lesson. The lesson on interfaces and inheritance will explain how and why you would use the extends and implements keywords in a class declaration. For the moment you do not need to worry about these extra complications.
In general, class declarations can include these components, in order:-
1.     Modifiers such as public, private, and a number of others that you will encounter later.
2.     The class name, with the initial letter capitalized by convention.
3.     The name of the class's parent (superclass), if any, preceded by the keyword extends. A class can only extend (subclass) one parent.
4.     A comma-separated list of interfaces implemented by the class, if any, preceded by the keyword implements. A class can implement more than one interface.
5.     The class body, surrounded by braces, {}.
                                                                                                                                       By:-Anand Raj
                                                                                                                                         Katihar(Bihar)
                                                                                                                            anandraj217@gmail.com
                                                                                                                            anandrajktr@yahoo.com
                                                                                                                            Mob No:-8298649924