Thursday, December 3, 2009

Saturday, November 21, 2009

Friday, August 14, 2009

String Builder Class

The thread safe StringBuffer class has a replacement in the form of StringBuilder .It doesnot have synchronized methods so it works much faster .So if you are performing a number of string operations in a single thread you will gain a tremendous performance while using this class .The string builder class consist of mutable sequence of charecters
.It provides an API ,which is compatible with StringBuffer,but there is no guarntee of its sychronization.This class is designed in such a way that it can be used as a drop in replacement
for StringBuffer in places

Thursday, August 13, 2009

Process Builder

An operating system process is created by using this class.A collection of process attributes is managed by ProcessBuilder instance.By using those attributes,the start() method creates a new process instance.To create a new subprocess with identical/related attributes the start method can be invoked from the same instance.
These process attributes are managed by each process builder in the following way:
Command: Command consist of a list of strings which makes the external program file to be invoked and its argument,if any significant.The String list representing a valid operating system is System dependent.

Environment:
A mapping which is System dependant varying from variables to values.The copy of the enviornment of the current process is the initial value.

Working Directory:
The current working directory of the current process is the default valueusually the system property,user.dir,imparts the name of the directory

RedirectErrorStream property:

At initial stage the standard output and error output of a subprocess are sent to two separate streams,meaning that this property is false.The false property can be accessed using two of the methods

--Process.getInputStream()

--Process.getErrorStream()

Friday, July 17, 2009

inheritence Demoonstration

package EmployeeandDate;
public class Date
{
int day,month,year;
public Date(int d,int m,int y)
{ day=d;
month=m;
year=y;
}
public String GetDate()
{
return day+"-"+month+"-"+year;
}
}

:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

package EmployeeandDate;
public class Employee
{ public String Name;
public int ID_No;
public String CompanyName;
Date d;
public Employee()
{}
public Employee(String n,int id,String c_name, Date dob)
{
Name=n; ID_No=id; CompanyName=c_name; d=dob;
}
public String GetDetails()
{ return "Name: "+Name+"\n"+"ID: "+ID_No+"\n"+"company Name: "+CompanyName+"\n"+d.GetDate(); }
}
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

package EmployeeandDate;
public class Master extends Employee
{ public int dept_id;
public Master(String n,int id,String c_name, Date dob,int e)
{
Name=n;
ID_No=id;
CompanyName=c_name;
d=dob;
dept_id=e;
}
public String GetDetails()
{ return "Name: "+Name+"\n"+"ID: "+ID_No+"\n"+"company Name: "+CompanyName+"\n"+d.GetDate()+"\n"+dept_id; }
}
::::::::::::::::::::::::
import EmployeeandDate.Master;
import EmployeeandDate.Date;
class Test
{
public static void main(String args[])
{ Master m=new Master("Vishal Hegde",007,"Johnson Private Limited",new Date(1,1,1989),123);
System.out.println(m.GetDetails()); }
}::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

Saturday, July 11, 2009

Creating Arrays

You can create arrays ,like all objects,using the new keyword.For example to create an array of a primitive type.

s=new char[26];
The first line creates an array of 26 char values.After the creation the values are initialized to the default value(''\u0000' for charecters).

Tuesday, July 7, 2009

Variables and Scope

Variables are of 2 types:
  • primitive type
  • reference type
Variables defined within a method are local variables,but are sometimes refered as automatic,temporary or stack variables.You must initialise local variable explicitly before the first use.

Method parameters and constructor parameters are also local variables but they are initialised by the calling method.

Variables defined outside the method are created when the object is created with new xxx() call.There are 2 possible types of this variables.
  • The first kind is declared using the static keyword.
Variables labeled static are created when the class is loaded and continues to exists as long as the class is loaded.

  • The second variable is instance variable that is declared without the static keyword.
Instance variable continues to exists as long as object exists.Instance variable are sometimes referred to as the member variables,because they are the member of the object created from the class

Method parameter variables define argument passed in a method call.

Local VARIABLES are created when execution enters the method and are destroyed when the method is exited.That is why variables are sometimes referred as temporary or automatic.

Basic fundamentals of Java

1. Source file's elements (in order)

  • Package declaration
  • Import statement
  • Class definitions
2. Importing packages doesn't recursively import sub-packages.

3. Sub-packages are really different packages, happen to live within an enclosing package. Classes in sub-packages cannot access classes in enclosing package with default access.

4. Comments can appear anywhere. Can't be nested. No matter what type of comments.

5. At most one public class definition per file. This class name should match the file name. If there are more than one public class definitions, compiler will accept the class with the file's name and give an error at the line where the other class is defined.

6. It's not required having a public class definition in a file. Strange, but true. J In this case, the file's name should be different from the names of classes and interfaces (not public obviously).

7. Even an empty file is a valid source file.

8. An identifier must begin with a letter, dollar sign ($) or underscore (_). Subsequent characters may be letters, $, _ or digits.

9. An identifier cannot have a name of a Java keyword. Embedded keywords are OK. true, false and null are literals (not keywords), but they can't be used as identifiers as well.

10. const and goto are reserved words, but not used.

11. Unicode characters can appear anywhere in the source code. The following code is valid.

ch\u0061r a = 'a';

char \u0062 = 'b';

char c = '\u0063';

12. Java has 8 primitive data types.

13. All numeric data types are signed. char is the only unsigned integral type.

14. Object reference variables are initialized to null.

15. Octal literals begin with zero. Hex literals begin with 0X or 0x.

16. Char literals are single quoted characters or unicode values (begin with \u).

17. A number is by default an int literal, a decimal number is by default a double literal.

18. 1E-5d is a valid double literal, E2d is not (since it starts with a letter, compiler thinks that it's an identifier)

19. Two types of variables.

a. Member variables

  • Accessible anywhere in the class.
  • Automatically initialized before invoking any constructor.
  • Static variables are initialized at class load time.
  • Can have the same name as the class.
b. Automatic variables method local
Must be initialized explicitly. (Or, compiler will catch it.) Object references can be initialized to null to make the compiler happy. The following code won't compile. Specify else part or initialize the local variable explicitly.

public String testMethod ( int a) {

String tmp;

if ( a > 0 ) tmp = "Positive";

return tmp;

}

· Can have the same name as a member variable, resolution is based on scope.

20. Arrays are Java objects. If you create an array of 5 Strings, there will be 6 objects created.

21. Arrays should be
  • Declared. (int[] a; String b[]; Object []c; Size should not be specified now)
  • Allocated (constructed). ( a = new int[10]; c = new String[arraysize] )
  • Initialized. for (int i = 0; i <>

22. The above three can be done in one step.

int a[] = { 1, 2, 3 }; (or )

int a[] = new int[] { 1, 2, 3 }; But never specify the size with the new statement.

23. Java arrays are static arrays. Size has to be specified at compile time. Array.length returns array's size. (Use Vectors for dynamic purposes).

24. Array size is never specified with the reference variable, it is always maintained with the array object. It is maintained in array.length, which is a final instance variable.

25. Anonymous arrays can be created and used like this: new int[] {1,2,3} or new int[10]

26. Arrays with zero elements can be created. args array to the main method will be a zero element array if no command parameters are specified. In this case args.length is 0.

27. Comma after the last initializer in array declaration is ignored.

int[] i = new int[2] { 5, 10}; // Wrong

int i[5] = { 1, 2, 3, 4, 5}; // Wrong

int[] i[] = {{}, new int[] {} }; // Correct

int i[][] = { {1,2}, new int[2] }; // Correct

int i[] = { 1, 2, 3, 4, } ; // Correct

28. Array indexes start with 0. Index is an int data type.

29. Square brackets can come after datatype or before/after variable name. White spaces are fine. Compiler just ignores them.

30. Arrays declared even as member variables also need to be allocated memory explicitly.

static int a[];

static int b[] = {1,2,3};

public static void main(String s[]) {

System.out.println(a[0]); // Throws a null pointer exception

System.out.println(b[0]); // This code runs fine

System.out.println(a); // Prints 'null'

System.out.println(b); // Prints a string which is returned by toString

}

31. Once declared and allocated (even for local arrays inside methods), array elements are automatically initialized to the default values.

32. If only declared (not constructed), member array variables default to null, but local array variables will not default to null.

33. Java doesn't support multidimensional arrays formally, but it supports arrays of arrays. From the specification - "The number of bracket pairs indicates the depth of array nesting." So this can perform as a multidimensional array. (no limit to levels of array nesting)

34. In order to be run by JVM, a class should have a main method with the following signature.

public static void main(String args[])

static public void main(String[] s)

35. args array's name is not important. args[0] is the first argument. args.length gives no. of arguments.

36. main method can be overloaded.

37. main method can be final.

38. A class with a different main signature or w/o main method will compile. But throws a runtime error.

39. A class without a main method can be run by JVM, if its ancestor class has a main method. (main is just a method and is inherited)

40. Primitives are passed by value.

41. Objects (references) are passed by reference. The object reference itself is passed by value. So, it can't be changed. But, the object can be changed via the reference.

42. Garbage collection is a mechanism for reclaiming memory from objects that are no longer in use, and making the memory available for new objects.

43. An object being no longer in use means that it can't be referenced by any 'active' part of the program.

44. Garbage collection runs in a low priority thread. It may kick in when memory is too low. No guarantee.

45. It's not possible to force garbage collection. Invoking System.gc may start garbage collection process.

46. The automatic garbage collection scheme guarantees that a reference to an object is always valid while the object is in use, i.e. the object will not be deleted leaving the reference "dangling".

47. There are no guarantees that the objects no longer in use will be garbage collected and their finalizers executed at all. gc might not even be run if the program execution does not warrant it. Thus any memory allocated during program execution might remain allocated after program termination, unless reclaimed by the OS or by other means.

48. There are also no guarantees on the order in which the objects will be garbage collected or on the order in which the finalizers are called. Therefore, the program should not make any decisions based on these assumptions.

49. An object is only eligible for garbage collection, if the only references to the object are from other objects that are also eligible for garbage collection. That is, an object can become eligible for garbage collection even if there are references pointing to the object, as long as the objects with the references are also eligible for garbage collection.

50. Circular references do not prevent objects from being garbage collected.

51. We can set the reference variables to null, hinting the gc to garbage collect the objects referred by the variables. Even if we do that, the object may not be gc-ed if it's attached to a listener. (Typical in case of AWT components) Remember to remove the listener first.

52. All objects have a finalize method. It is inherited from the Object class.

53. finalize method is used to release system resources other than memory. (such as file handles and network connections) The order in which finalize methods are called may not reflect the order in which objects are created. Don't rely on it. This is the signature of the finalize method.

protected void finalize() throws Throwable { }

In the descendents this method can be protected or public. Descendents can restrict the exception list that can be thrown by this method.

54. finalize is called only once for an object. If any exception is thrown in finalize, the object is still eligible for garbage collection (at the discretion of gc)

55. gc keeps track of unreachable objects and garbage-collects them, but an unreachable object can become reachable again by letting know other objects of its existence from its finalize method (when called by gc). This 'resurrection' can be done only once, since finalize is called only one for an object.

56. finalize can be called explicitly, but it does not garbage collect the object.

57. finalize can be overloaded, but only the method with original finalize signature will be called by gc.

58. finalize is not implicitly chained. A finalize method in sub-class should call finalize in super class explicitly as its last action for proper functioning. But compiler doesn't enforce this check.

59. System.runFinalization can be used to run the finalizers (which have not been executed before) for the objects eligible for garbage collection.



Monday, July 6, 2009

Encapsulation and Data Hiding

class student
{
int RollNo;
String name;
private int age;

public void setAge(int a)
{
if(a>=10&& a<=20)
age=a;
else
age=12;
}

public int GetAge()
{
return age;
}
}

class TestStudent
{
public static void main(String args[])
{
student s1=new student();
s1.setAge(200);
System.out.println("Age of the student"+s1.GetAge());
}
}

Thursday, July 2, 2009

Compiling using the -d Option

Normally tha java compiler places the class files in the same directory as the source files.You can reroute the clas files to another using the -d option of the javac command.The simplest way to compile files within the package is to be working in the directory one level abobe the beginning of the package.

To compile all the files within the shipping.domain package use:
javac -d ../classes shipping/domain/*.java

The import statement

The import statement taks the following form:

import [..;

or

import[.].*;
When you want to use packages ,use the import statement to tell the compiler when to find classes

eg: import java.util.*; // thats a predefined packages being imported

eg: import shipping.domain.*; // thats a user-defined package

Remember that the import statement is used to make classes in other packages accessible to the current class.

If you want to only access the Writer class from the java.io package then you would use:

import java.io.Writer;

if you want to access the whole class from java.io package then you would use:

import java.io.*;

The Package Statement

The java technology programming language provides the package statement as a way to group related classes.The package statement takes the following form:
package[.]*;
You can indicate that classes in a source file belong to a particular package using the package statement.
For example:
1 package shipping.domain;
2
3 //class vehicle of the 'domain' sub-package within the 'shipping' application package.
4 public class Vehicle {
5 .....
6 }
The package declaration if any must be at the begining of he source code .You can precede it white space and comments,but nothing else.
Only one package declaration is permitted and it governs the entire source file .If a Java technology source file does not contain a package declaration then the classes declared in that file belongs to the unnamed (default) package.
pAckage names are hierarchical and are seperated by dots.It is usual for the elements of the packagename to be entirely lower case.

Executing simple application in a console window


The simple source code i wrote was stored in D:\ drive of the java directory but when you open a console window its default path is set to c:\Documents and Settings\Administrator>
in order to set it to D:\java ,you must first type d:\ and press [enter] as ilustrated in the diagram.After then type cd cd refers to "change directory". after doing that if you simply write javac app.java it will not compile it will produce error because you have not set the path of directory to the compiler of java so error willl be produced as javac is not recognised......
so you need to set the path as illustrated in the diagram
After setting the path compilation of .java file is necessary so that it can be converted into .class file so that machine can interpret it..
syntax:
Javac app.java
for execution
Syntax
java app

Simple Java Console Application

here we are creating a simple class reffered as app ...

public static void main(String args[]) is a must for every programming language because this is the entry point for execution to take place. Without this statement the program wil be compiled but not executed.
public here is an access specifier which shows that any outside program can access the main method ..
static here refers that the copy of variable/method cannot be manipulated

void here refers that there is no return type
main is a keyword to specify the opening gate for execution
String args[] are used to store command line arguments.

if you are unable to see the code just double click the image

Inventor of Java

James Gosling

James Gosling, the inventor of the Java programming language and one of the most influential figures in the history of programming languages ...

Installing Java virtual machine



Before you can run any java programs it is necessary that you download java software

development kit(SDK).You can find it in http://java.sun.com/j2se/1.5.0/

Java runtime Enviornment


Java source files are compiled in the sense that they are coverted into a set of bytecodes from thetext format you write them.The byte codes are stored in .class file.At the runtime the bytecodes that make up a java program are loaded ,checked and run in an interpreter.In case of appplets you can download the bytecodess and then they are interpreted by Jvm in the browser.
Interpreter has 2 functions
-->Executes the bytecode
-->Makes appropriate calls to the underlying hardwarer


Wednesday, July 1, 2009

Garbage collection

if you are little bit familiar with java you must be aware that memory is allocated whenever an instance of object is created or whn variable is declared.But when there's no need for that particular variable or an object it is reffered to as a garbage and deallocated from the memory.Here memory will be refernced by heaps and stack.Most programming language permit the memory to be allocated dynamically at the runtime.The process of allocating memory

Tuesday, June 30, 2009

Java technology architecture


The java technology architecture uses the following feautres:


  • The JVM

  • Garbage collection

  • The JRE

  • JVM tool interface



  • The JVM



(abbreviation for Java virtual machine).The java virtual machine specifications define JVM as


An imaginary machine that is implemented by emulating it in a softwareon a real machine.Code for the JVM is stored in .class file,which contains code for atmost one public class.


The java virtual machine specification provides the hardware platform specifications to which you compile all java technology code.This specification enables the java software to be platform independant because the compilation is done for the generic machine,known as JVM.You can emulate the generic machine in software to run on various existing Systems or implement it in the hardware.


The compliler tajes the java application source code and generates bytecodes.Bytecodes are machine code instructions from the JVM. Every java technology interpreter ,regardless of whether it is a Java technology development tool or a web browser that can run applets, has an implementation of JVM.

Primary goals of Java Tecnology

--> Eliminates many pitfalls of other languages,such as pointersarithematic and memory management that affect the robustness of the code
--> Is object oriented to help you visualize the program in real-life terms

-->Enables you to streamline the code

-->An interpreted enviornment resulting in the following benefits:
--Speed of development:Reduces the compile -link-load test cycle
--Code portability:Enables you to write code that can run on multiple operating systems on any certified JVM
-->A way for programs to run more than one thread of activity
-->A means to change programs dynamically during their runtime life by enabling them to download to code modules
--> A means of ensuring security by checking the loaded code modules


What is Java Technology

The java Technology is :

--> A programming language

The sytax of java programming language is similar to C++ syntax.You can use java programming language to create all kinds of applications whether it be related to a microwave, your ipod or your cell phones


--> A development enviornment
As an development enviornment ,java technology provides you with a large suit of tools, compiler, an interpreter,a documentation generator,a class file packaging tool and so on.
Java programming language is mentioned in the context of the World Wide Web(www) and browsers that are that are capable of running programs called applets.

Applets-- They are the programs written in the java programing language that reside on web servers and downloaded by a browser to a client system and are run by that browser .Applets are usually small in size to minimize download time and inovked by HTML web page

--> An application enviornment
Java technology applications are standalone programs that do not require a web browser to execute.Typically they are general purpose programs to run on any machines where the Java Runtime enviornment (JRE) is installed
--> A deployment enviornment
There are two main deployment enviornment.
1--> JRE
This is supplied by java 2 software development kit(Java 2 SDK) which contains the complete set of class files for all the java technology packages ,which include basic language classes,GUI component clases and so on.

2-->Other Main is in your web browser
most commercial browsers supply a Java technology interpreter and runtime enviornment

Unable to understand Java .Learn it the easy way

Hey people if you are reading this then i feel that either you guys are unable to Understand java or want to learn something more about it.Whether it be an ametuar or professional everybody's welcomed here and share their thoughts.Probably i have created this blog because i have some knowledge about it and want to share it with you guys..also i want to learn things that i dont know.