Tuesday, March 31, 2009

Variable Declaration -Part2

Variable Declaration

Declaring a variable with the final keyword makes it impossible to reinitialize that
variable once it has been initialized with an explicit value (notice we said explicit
rather than default). For primitives, this means that once the variable is assigned a
value, the value can't be changed. For example, if you assign 10 to the int variable
x, then x is going to stay 10, forever. So that's straightforward for primitives, but
what does it mean to have a final object reference variable? A reference variable
marked final can't ever be reassigned to refer to a different object. The data within
the object can be modified, but the reference variable cannot be changed. In other
words, a final reference still allows you to modify the state of the object it refers
to, but you can't modify the reference variable to make it refer to a different object.
Burn this in: there are no final objects, only final references.
We've now covered how the final modifier can be applied to classes, methods,
and variables.

Transient Variables
If you mark an instance variable as transient, you're telling the JVM to skip
(ignore) this variable when you attempt to serialize the object containing it.
Serialization is one of the coolest features of Java; it lets you save (sometimes called
"flatten") an object by writing its state (in other words, the value of its instance
variables) to a special type of I/O stream. With serialization you can save an object
to a file, or even ship it over a wire for reinflating (deserializing) at the other end, in
another JVM.

Volatile Variables
The volatile modifier tells the JVM that a thread accessing the variable must
always reconcile its own private copy of the variable with the master copy in
memory. Say what? Don't worry about it. For the exam, all you need to know about
volatile is that, as with transient, it can be applied only to instance variables.
Make no mistake, the idea of multiple threads accessing an instance variable is scary
stuff, and very important for any Java programmer to understand.


Static Variables and Methods
The static modifier is used to create variables and methods that will exist
independently of any instances created for the class. In other words, static
members exist before you ever make a new instance of a class, and there will be
only one copy of the static member regardless of the number of instances of that
class. In other words, all instances of a given class share the same value for any given
static variable. We'll cover static members in great detail in the next chapter.
Things you can mark as static:
1 Methods
2 Variables
3 A class nested within another class, but not within a method
4 Initialization blocks

Things you can't mark as static:
1 Constructors (makes no sense; a constructor is used only to create instances)
2 Classes (unless they are nested)
3 Interfaces
4 Method local inner classes (we'll explore this in Chapter 8)
5 Inner class methods and instance variables
6 Local variables

Declaring Enums
As of 5.0, Java lets you restrict a variable to having one of only a few pre-defined
values—in other words, one value from an enumerated list. (The items in the
enumerated list are called, surprisingly, enums.)
Using enums can help reduce the bugs in your code. For instance, in your coffee
shop application you might want to restrict your size selections to BIG, HUGE,
and OVERWHELMING. If you let an order for a LARGE or a GRANDE slip in, it
might cause an error. Enums to the rescue. With the following simple declaration,
you can guarantee that the compiler will stop you from assigning anything to a
CoffeeSize except BIG, HUGE, or OVERWHELMING:
enum CoffeeSize { BIG, HUGE, OVERWHELMING };
From then on, the only way to get a CoffeeSize will be with a statement something
like this:
CoffeeSize cs = CoffeeSize.BIG;
It's not required that enum constants be in all caps, but borrowing from the Sun
code convention that constants are named in caps, it's a good idea.
The basic components of an enum are its constants (i.e., BIG, HUGE, and
OVERWHELMING), although in a minute you'll see that there can be a lot more
to an enum. Enums can be declared as their own separate class, or as a class member,
however they must not be declared within a method!
Declaring an enum outside a class:
enum CoffeeSize { BIG, HUGE, OVERWHELMING } // this cannot be
// private or protected
class Coffee {
CoffeeSize size;
}
public class CoffeeTest1 {
public static void main(String[] args) {
Coffee drink = new Coffee();
drink.size = CoffeeSize.BIG; // enum outside class
}
}
The preceding code can be part of a single file. (Remember, the file must be named
CoffeeTest1.java because that's the name of the public class in the file.) The
key point to remember is that the enum can be declared with only the public or
default modifier, just like a non-inner class. Here's an example of declaring an enum
inside a class:
class Coffee2 {
enum CoffeeSize {BIG, HUGE, OVERWHELMING }
CoffeeSize size;
}
public class CoffeeTest2 {
public static void main(String[] args) {
Coffee2 drink = new Coffee2();
drink.size = Coffee2.CoffeeSize.BIG; // enclosing class
// name required
}
}
The key points to take away from these examples are that enums can be declared
as their own class, or enclosed in another class, and that the syntax for accessing
an enum's members depends on where the enum was declared.
The following is NOT legal:
public class CoffeeTest1 {
public static void main(String[] args) {
enum CoffeeSize { BIG, HUGE, OVERWHELMING } // WRONG! Cannot
// declare enums
// in methods
Coffee drink = new Coffee();
drink.size = CoffeeSize.BIG;
}
}
To make it more confusing for you, the Java language designers made it optional to
put a semicolon at the end of the enum declaration:
public class CoffeeTest1 {
enum CoffeeSize { BIG, HUGE, OVERWHELMING }; // <--semicolon
// is optional here
public static void main(String[] args) {
Coffee drink = new Coffee();
drink.size = CoffeeSize.BIG;
}
}

So what gets created when you make an enum? The most important thing to
remember is that enums are not Strings or ints! Each of the enumerated CoffeeSize
types are actually instances of CoffeeSize. In other words, BIG is of type CoffeeSize.
Think of an enum as a kind of class, that looks something (but not exactly) like this:
// conceptual example of how you can think
// about enums
class CoffeeSize {
public static final CoffeeSize BIG =
new CoffeeSize("BIG", 0);
public static final CoffeeSize HUGE =
new CoffeeSize("HUGE", 1);
public static final CoffeeSize OVERWHELMING =
new CoffeeSize("OVERWHELMING", 2);

public CoffeeSize(String enumName, int index) {
// stuff here
}
public static void main(String[] args) {
System.out.println(CoffeeSize.BIG);
}
}
Notice how each of the enumerated values, BIG, HUGE, and OVERWHELMING,
are instances of type CoffeeSize. They're represented as static and final, which in
the Java world, is thought of as a constant. Also notice that each enum value knows
its index or position…in other words, the order in which enum values are declared
matters. You can think of the CoffeeSize enums as existing in an array of type
CoffeeSize, and as you'll see in a later chapter, you can iterate through the values of
an enum by invoking the values() method on any enum type. (Don't worry about
that in this chapter.)

Declaring Constructors, Methods, and Variables in an enum

Because an enum really is a special kind of class, you can do more than just list the
enumerated constant values. You can add constructors, instance variables, methods,
and something really strange known as a constant specific class body. To understand
why you might need more in your enum, think about this scenario: imagine you
want to know the actual size, in ounces, that map to each of the three CoffeeSize
constants. For example, you want to know that BIG is 8 ounces, HUGE is 10
ounces, and OVERWHELMING is a whopping 16 ounces.
You could make some kind of a lookup table, using some other data structure,
but that would be a poor design and hard to maintain. The simplest way is to treat
your enum values (BIG, HUGE, and OVERWHELMING), as objects that can each
have their own instance variables. Then you can assign those values at the time the
enums are initialized, by passing a value to the enum constructor. This takes a little
explaining, but first look at the following code:

enum CoffeeSize {
BIG(8), HUGE(10), OVERWHELMING(16);
// the arguments after the enum value are "passed"
// as values to the constructor
CoffeeSize(int ounces) {
this.ounces = ounces; // assign the value to
// an instance variable
}
private int ounces; // an instance variable each enum
// value has
public int getOunces() {
return ounces;
}
}
class Coffee {
CoffeeSize size; // each instance of Coffee has-a
// CoffeeSize enum
public static void main(String[] args) {
Coffee drink1 = new Coffee();
drink1.size = CoffeeSize.BIG;
Coffee drink2 = new Coffee();
drink2.size = CoffeeSize.OVERWHELMING;
System.out.println(drink1.size.getOunces()); // prints 8
System.out.println(drink2.size.getOunces()); // prints 16
}
}
The key points to remember about enum constructors are
1 You can NEVER invoke an enum constructor directly. The enum constructor
is invoked automatically, with the arguments you define after the constant
value. For example, BIG(8) invokes the CoffeeSize constructor that takes
an int, passing the int literal 8 to the constructor.
2 You can define more than one argument to the constructor, and you can
overload the enum constructors, just as you can overload a normal class
constructor.
To initialize a CoffeeType with both the number of ounces and, say, a lid type,
you'd pass two arguments to the constructor as BIG(8, "A"), which means
you have a constructor in CoffeeSize that takes both an int and a String.

And finally, you can define something really strange in an enum that looks like an
anonymous inner class. It's known as a constant
specific class body, and you use it when you need a particular constant to override a
method defined in the enum.
Imagine this scenario: you want enums to have two methods—one for ounces
and one for lid code (a String). Now imagine that most coffee sizes use the same
lid code, "B", but the OVERWHELMING size uses type "A". You can define a
getLidCode() method in the CoffeeSize enum that returns "B", but then you need
a way to override it for OVERWHELMING. You don't want to do some hard-tomaintain
if/then code in the getLidCode() method, so the best approach might
be to somehow have the OVERWHELMING constant override the getLidCode()
method.
This looks strange, but you need to understand the basic declaration rules:
enum CoffeeSize {
BIG(8),
HUGE(10),
OVERWHELMING(16) { // start a code block that defines
// the "body" for this constant
public String getLidCode() { // override the method
// defined in CoffeeSize
return "A";
}
}; // <-- the semicolon is REQUIRED when you have a body
CoffeeSize(int ounces) {
this.ounces = ounces;
}
private int ounces;
public int getOunces() {
return ounces;
}
public String getLidCode() { // this method is overridden
// by the OVERWHELMING constant
return "B"; // the default value we want to return for
// CoffeeSize constants
}
}

Read more...

Variable Declaration -Part1

Variable Declaration
There are two types of variables in Java:

1. Primitives: A primitive can be one of eight types: char, boolean, byte,
short, int, long, double, or float. Once a primitive has been declared, its
primitive type can never change, although in most cases its value can change.

2.Refence variables: A reference variable is used to refer to (or access) an
object. A reference variable is declared to be of a specific type and that type
can never be changed. A reference variable can be used to refer to any object
of the declared type, or of a subtype of the declared type (a compatible type).

Declaring Primitives and Primitive Ranges

Primitive variables can be declared as class variables (statics), instance variables,
method parameters, or local variables. You can declare one or more primitives, of the
same primitive type, in a single line. Few examples of
primitive variable declarations:

byte b;
boolean myPrimitive;
int x, y, z; // declare three int primitives

All six number types in Java are made up of a certain number of 8-bit bytes, and
are signed, meaning they can be negative or positive. The leftmost bit (the most
significant digit) is used to represent the sign, where a 1 means negative and 0 means
positive.

Declaring Reference Variables
Reference variables can be declared as static variables, instance variables, method
parameters, or local variables. You can declare one or more reference variables,
of the same type, in a single line. Few examples of
reference variable declarations:

Object o;
Dog myReferenceVariable;
String s1, s2, s3; // declare three String vars.

Instance Variables
Instance variables are defined inside the class, but outside of any method, and
are only initialized when the class is instantiated. Instance variables are the fields
that belong to each unique object. For example, the following code defines fields
(instance variables) for the name, title, and manager for employee objects:

class Employee {
// define fields (instance variables) for employee instances
private String name;
private String title,
private String manager;
// other code goes here including access methods for private
// fields
}

The preceding Employee class says that each employee instance will know its
own name, title, and manager. In other words, each instance can have its own
unique values for those three fields. If you see the term "field," "instance variable,"
"property," or "attribute," they mean virtually the same thing.

1. Can use any of the four access levels (which means they can be marked with
any of the three access modifiers)
2. Can be marked final
3. Can be marked transient
4. Cannot be marked abstract
5. Cannot be marked synchronized


Cannot be marked strictfp
1. Cannot be marked native
2. Cannot be marked static, because then they'd become class variables.

We've already covered the effects of applying access control to instance variables
(it works the same way as it does for member methods). A little later in this chapter
we'll look at what it means to apply the final or transient modifier to an
instance variable. First, though, we'll take a quick look at the difference between
instance and local variables.

Local (Method) Variables
Local variables are variables declared within a method. That means the variable is
not just initialized within the method, but also declared within the method. Just
as the local variable starts its life inside the method, it's also destroyed when the
method has completed. Local variables are always on the stack, not the heap.
Just don't forget that while the local variable is on the stack, if the variable is an
object reference, the object itself will still be created on the heap. There is no such
thing as a stack object, only a stack variable. You'll often hear programmers use
the phrase, "local object," but what they really mean is, "locally declared reference
variable." .
Local variable declarations can't use most of the modifiers that can be applied
to instance variables, such as public (or the other access modifiers), transient,
volatile, abstract, or static, but as we saw earlier, local variables can be
marked final.

class Test {
public void logIn() {
int count = 10;
}
}

Typically, you'll initialize a local variable in the same line in which you declare
it, although you might still need to reinitialize it later in the method. The key is
to remember that a local variable must be initialized before you try to use it. The
compiler will reject any code that tries to use a local variable that hasn't been
assigned a value, because—unlike instance variables—local variables don't get
default values.

A local variable can't be referenced in any code outside the method in which
it's declared. In the preceding code example, it would be impossible to refer to the
variable count anywhere else in the class except within the scope of the method
logIn(). Again, that's not to say that the value of count can't be passed out of the
method to take on a new life. But the variable holding that value, count, can't be
accessed once the method is complete, as the following illegal code demonstrates:
class Test {
public void logIn() {
int count = 10;
}
public void doSomething(int i) {
count = i; // Won't compile! Can't access count outside
// method login()
}
}
It is possible to declare a local variable with the same name as an instance
variable. It's known as shadowing, as the following code illustrates:
class Test {
int count = 9; // Declare an instance variable named count
public void logIn() {
int count = 10; // Declare a local variable named count
System.out.println("local variable count is " + count);
}
public void count() {
System.out.println("instance variable count is " + count);
}
public static void main(String[] args) {

new Test().logIn();
new Test().count();
}
}

The preceding code produces the following output:
local variable count is 10
instance variable count is 9

The following code is trying to set an instance variable's value using a
parameter:

class Boo {
int size = 20;
public void setSize(int size) {
size = size; //which size equals which size???
}
}

So you've decided that—for overall readability—you want to give the parameter
the same name as the instance variable its value is destined for, but how do you
resolve the naming collision? Use the keyword this. The keyword this always,
always, always refers to the object currently running. The following code shows this
in action:

class Boo {
int size = 20;
public void setSize(int size) {
this.size = size; // this.size means the current object's
// instance variable, size. The size
// on the right is the parameter
}
}

Read more...

Readers Appreciation Programme

Readers Appreciation Programme Update

I always appreciated the reading.It is a very nice habit you always keep on reading in your spare time to learn something extra something good.To appreciate readers I have extensively worked on this and came out with some Sound links which gives so much to offer.These Links can be seen in Hot Offers Section.You can get Books,electronic gadgets at very cheap prices.Just follow these links and you will see a good range of books and corresponding offers.Through these links You will get millions of Good as well as very old collection of books.So go Just check out these links or Visit my Store.Be Updated as more to come in later days.
To visit My Store Click below:-

Visit My Store

Read more...

Monday, March 30, 2009

Bitwise Operator :Introduction

Java defines several types of Bitwise operators which are applicable to integer type,long,int ,short,byte,char values.These operators act on each and every bit of their operands.

Bitwise Operators are listed as following :-




Bitwise operators manipulate the bits within an integer value,so it is important to know what effects the changes will bring on integer value.It is also useful to know how Java stores integer values and the way negative integer values are represented.

All integer values in Java are represented by binary numbers of varying lengths.For example a byte value for 22 in binary is 00010101.The formula used to convert binary to integer would be as example tells:-in above case the binary to integer conversion takes place as

16+4+1=21

the theory is get all bits whose value is 1, count its position from right and say it "n" and compute "pow(2,n-1)" thus here first 1 comes at 1st position thus giving value pow(2,1-1)=pow(2,0)=1
Similarly for second you get as poe(2,2)=4 as it appears on 3rd position.

All integer types are signed integers due to which they can either represent a negative integer or positive value.Java use two's complement method for representing negative numbers.Lets see how 2's Complement works.Take binary string for a negative number assume -21 be the number.
First invert all bit values ,that is change 0 to 1 and vice-versa.Then add 1 to its rightmost bit.

21 is represented as 00010101 in binary string.

ENCODING FOR 2'S COMPLEMENT
Step 1: Invert all individual bits we get 11101010
Step 2: Add 1 to Rightmost bit that is

11101010

+1
---------------------
11101011 it is binary value for -21
---------------------
DECODING 2'S COMPLEMENT

of -21 (11101011)
Step 1: Invert all individual bits here we get 00010100 which is equal to 20.
Step 2: Add 1 to rightmost bit

00010100
+1
-------------------
00010101 and it is equal to 21
--------------------

IMPORTANT:-Java uses 2's complement to store negative numbers and because all integers are signed values in Java thus applying them may produce unexpected outcomes.Consider for example ,turning on higher order bits will cause resulting values to be interpreted as negative .To avoid such situations always keep in mind that higher order bits determines the sign of an integer value no matter what how that bit is set.

Useful Links :-

Assignment Operators
Arithmetic Operators
Logical operators
Relational Operators
Conditional Operators
Bitwise Logical operator
Bitwise Left shift Operator
Bitwise Right shift Operator

Sponsored Links :-

Get Your SCJP preparation Kit free!!!!!!!
Get Your SCWCD preparation Kit free!!!
Are you Intelligent check here

Read more...

Saturday, March 28, 2009

Java World Readers Appriciation Programme

Java World Readers Appreciation Programme

Reading is a very nice hobby ,it not only help you engage in your spare time but lets you learn some useful thought or get some handy  knowledge.Knowledge is never ever been wasteful it is always useful in one or the other part.For example:- if you are not a perfectionist in Cooking although you are quite intrested in it ,then you may look forward to some recipie book by any shef so that you can also cook a great meal,and as said in my country"The way of heart is through one's Stomach" you can win hearts of many and get appraisal, thats how wonders are done by reading.

So to increase the Habit of reading among everyone whether one loves books or not The JAVA WORLD is soon going to launch "The Readers Appreciation Programme".In which you will get loads of benefits of reading books.It is expected to be launched some day in April or May as I am currently working on it to give maximum benefit to readers.

This site is all about Java but I will appreciate readers from all spheres to just come and reap the fruits of the habit they had developed.
Looking Forward to launch the programme.
Keep in touch and don't forget to sign up for my daily Java Tutorials.

>>Any queries never hesitate to ask as "one question can change your life" so always be prepared to ask(but never mindless questions).
With Best wishes
 
Va
javatute@gmail.com

Read more...

Using Prepared Statement

Using Prepared Statement Object

There are several situations where you want to query database according to some condition.For Example if you want to list all employees having salary greater than 10,000,then you will provide condition which states salary must be greater than 10,000.

The query would be :-

"select * from emp where salary>10000 "

The above query will list all employees having salary more than 10,000.
For providing any condition you must provide some condition using Comparison Operators.
To make it possible ,you will have to prepare a query statement ,that receives an appropriate value in the where clause,at run time.

The PreparedStatement object allows you to execute parametrized queries.The PreparedStetement Object is created using the preparedStatement() method of the Connection Class.Like following:

stat=conn.preparedStatement("select * from emp where salary=?");

The preparedStatement() method of the Connection object takes SQL statements a parameter .The SQL Statement can contain placeholders that can be replaced by INPUT parameters at runtime.

Note:-The "?" symbol is a placeholder that can be replaced by the INPUT parameters at runtime.

For replacing a placeholder use following:

stat.setInt(1,10000);
result=stat.executeQuery();
result.next();

Here we are setting value of salary in the query through "setInt()" method.
This value is set to "?" and query is passed further to execute.

GoTo:-
Home
JDBC Architecture
Configuring ODBC Sources
Connecting to database
Querying Database
Using ResultSet Object
Deatailed JDBC Example-Statement Object

Read more...

JDBC Example-Statement Object

Detailed JDBC Example-Statement Object:-

The simple quries that include retrieving data from database comes under statement object.As told in previous tutorials statement object is used for very basic database function that is getting data from database.

Following example include Simple functions which will be explained further lets take a look at example:-

import java.sql.*;

public class jdbcexample
{
static Connection conn;
static Statement stat;
static ResultSet result;
public static void main(String a[])
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
conn=DriverManager.getConnection("jdbc:odbc:Mydata");
stat=conn.createStatement();
result=stat.executeQuery("select * from emp");
while(result.next())
{
System.out.println(result.getString(1));
System.out.println(result.getString(2));
System.out.println(result.getString(3));
}
}catch(Exception e){}
}
}

This is very basic exapmle here all variable before main method are declared static because all these variables are used in main method which is static and you cannot use any non static variable in static methods .So you have to declare them static.
Coming to point as you know statement object is used to get value from database only not making any structural changes.For making structural changes you have to use preparedStatement object.In statement object first you have to create the statement using create Statement object of Connection class after that result is obtained in ResultSet object by using method executeQuery(String s) method of Statement object.After that continue to fetch data .

Go to :-
Home
JDBC Architecture
Configuring ODBC Sources
Connecting to database
Querying Database
Using ResultSet Object

Read more...

Wednesday, March 25, 2009

Sun Certified Java Programmer Ebook-Khalid e Mughal Download

A Programmer's Guide to Java SCJP Certification: A Comprehensive Primer (3rd Edition)

provides detailed coverage of all exam topics and objectives, readily runnable code examples, programming exercises, extensive review questions, and a new mock exam. In addition, as a comprehensive primer to the Java programming language, this book is an invaluable reference tool.

This new edition has been thoroughly updated to focus on the latest version of the exam (CX-310-065). In particular, it contains in-depth explanations of the language features. Their usage is illustrated by way of code scenarios, as required by the exam. The companion Web site (www.ii.uib.no/~khalid/pgjc3e/) contains a version of the SCJP 1.6 Exam Simulator developed by the authors. The site also contains the complete source code for all the book’s examples, as well as solutions to the programming exercises.


What you will find in this book:

* Extensive coverage of all the objectives defined for the Sun Certified Programmer for the Java Platform, Standard Edition 6 (CX-310-065) Exam
* An easy-to-follow structure with chapters organized according to the exam objectives, as laid out by Sun Microsystems
* Summaries that clearly state and differentiate the exam objectives and the supplementary objectives to be covered in each chapter
* A list of Sun’s objectives for the SCJP 1.6 Exam and a guide to taking the exam
* A complete mock exam with new questions (not repeats of review questions)
* Numerous exam-relevant review questions to test your understanding of each major topic, with annotated answers
* Programming exercises and solutions at the end of each chapter
* Copious code examples illustrating concepts, where the code has been compiled and thoroughly tested on multiple platforms
* Program output demonstrating expected results from running the examples
* Extensive use of UML (Unified Modeling Language) for illustration purposes
* An introduction to basic terminology and concepts in object-oriented programming
* Advice on how to avoid common pitfalls in mastering the language and taking the exam
* Platform- and tool-independent coverage
* Information about the SCJP 1.6 Upgrade (CX-310-066) Exam

From the Back Cover
"We have written A Programmer’s Guide to Java Certification to allow the reader to master the Java programming language. Mastering the language should naturally culminate in the practical goal of passing the Sun Certified Programmer for Java‘ 2 Platform exam. In addition to preparing the reader thoroughly for the exam, this book also provides comprehensive coverage of all the essential Java features and core APIs that every proficient Java programmer should master."
- The authors

What you will find in this book:
• In-depth coverage of all the important topics, in particular, extensive coverage of ALL the objectives defined for the Sun Certified Programmer for Java TM 2 Platform exam (equivalent to Level 1 in the new Certification Initiative for Enterprise Development). • Easy to follow structure with chapters organized according to the exam objectives as laid out by Sun • Summaries which clearly state and differentiate the exam objectives and the supplementary objectives to be covered in each chapter • A list of Sun’s objectives for the Programmer exam, and a guide to taking the exam • Numerous exam-relevant review questions to test understanding of each major topic, with annotated answers • A complete mock exam with NEW questions (not repeats of review questions) • Programming exercises at the end of each chapter, with solutions • Ample code examples to illustrate concepts, which have been compiled and thoroughly tested on multiple platforms • Screen shots which illustrate how the examples would look when run • Numerous illustrations which use the standard diagramatic notation, UML • An introduction to basic terminology and concepts in object-oriented programming • Advice on how to avoid common pitfalls in mastering the language • Platform independent coverage - platform specific details are provided where relevant

Additional but relevant topics are also covered, such as using threads, building GUI with AWT and Swing components, rendering graphics, implementing applets, handling I/O streams, generating documentation using Javadoc and much more.

The accompanying web site includes a mock exam engine; complete source code for all the examples and solutions for the programming exercises; links to important resources (web browsers, Sun’s JDK, and integrated development environments for Java); updates; and more....

Written for anyone with previous programming experience (although not necessarily in Java), this book’s comprehensive coverage of the basic and the advanced features of the language make it as useful for experienced Java programmers aiming at certification, as for programmers learning Java for the first time.

Download Here
A Programmer's Guide to Java SCJP Certification: A Comprehensive Primer (3rd Edition)

Read more...

Tuesday, March 24, 2009

The switch Construct

The switch Construct

Another decision construct available in Java is switch construct.switch construct is used when there are multiple values of same varible are to be tested.The switch statement successively test the value of an expression or a variable against a list of inetger or character constants.Whenever a match is found the statement associated with that case constant are executed.Lets look at Syntax:-

switch(variable_name)
{
case expression1: statements;

case expression2: statements;

.
.
.
case expressionn: statements;
default: statements;
}

switch is a keyword which is followed by parentheses

switch(1)

the case keyword is followed by a constant like

case 1: x=y+z;

Note:There should be no difference in data types of case constants and switch variable.

Break statement:-

The break statements cause the program flow to exit from the current body of construct.Contol now passes to the very next statement followed by the end of switch construct.If break is not used then program flow would be linear and all case statements will execute despite any value or constants.

Consider following example:-

switch(n)
{
case 1: System.out.println("1");
case 2: System.out.println("2");
case 3: System.out.println("3");
case 4: System.out.println("4");
default: System.out.println("5");
}

In this case the output would be
1
2
3
4
5

Now consider the example:-

int n=1;
switch(n)
{
case 1: System.out.println("1");
break;
case 2: System.out.println("2");
break;
case 3: System.out.println("3");
break;
case 4: System.out.println("4");
break;
default: System.out.println("5");
}

In this case the output would be 1,because control jumps after case statement of value 1 executes thus not executing any other statements.

SCJP QUOTE:-Check for various tricky variations on switch construct.

The default keyword:-The statements associated with the default keyword are executed if the value of the switch variable does not match any of the case statements.
For Example:-

int n=4;
switch(n)
{
case 1: System.out.println("1");
break;
case 2: System.out.println("2");
break;
default:System.out.println("no match");
}

The output would be no match

IMPORTANT:-
1.The default label ,if used must be the last option in the switch construct.
2.It is not necessary to use default construct.
3.The case expression can be of either numeric or character data type.

Read more...

The if..else Decision Construct

The if..else Construct

It is a decision construct
The if decision construct is followed by a logical expression in which data is compared and a decision is made based on result of comparison.That is take it in a lighter way suppose you are going to watch a movie and in case you found house full board hanging out then you must have a choice that is if there is a houseful the i am gonna watch blah blah movie.

Follow like this :-

if( ! houseful ){
watch movie a
}
else {
watch movie b
}

Similarly the Syntax is :-

If(boolean_expr)
{
statements;
}
else
{
statements;
}

Example:-

To find equality of two numbers

if(num1!=num2)
{
System.out.println(num1+"not equal to"+num1);
}
else
{
System.out.println(num1+"is equal to"+num2);
}

This example finds equality of two numbers.If the value of first number is not equal to that of second then if block executes and prints message when if block completes execution
the control never goes to else block and resumes simple program flow.Same is the case is with else block it will be executed when the boolean expression in if is false and after completion program continues its normal flow.Always if comes before else keep in mind.

Read more...

Sun Certified Java Programmer Ebook -Katherine Sierra and Bert Bates

With hundreds of practice questions and hands-on exercises, SCJP Sun Certified Programmer for Java 6 Study Guide covers what you need to know--and shows you how to prepare--for this challenging exam.

100% complete coverage of all official objectives for exam 310-065
Exam Objective Highlights in every chapter point out certification objectives to ensure you're focused on passing the exam
Exam Watch sections in every chapter highlight key exam topics covered
Simulated exam questions match the format, tone, topics, and difficulty of the real exam
Covers all SCJP exam topics, including:

Declarations and Access Control � Object Orientation � Assignments � Operators � Flow Control, Exceptions, and Assertions � Strings, I/O, Formatting, and Parsing � Generics and Collections � Inner Classes � Threads � Development

CD-ROM includes:

Complete MasterExam practice testing engine, featuring: Two full practice exams; Detailed answers with explanations; Score Report performance assessment tool
Electronic book for studying on the go
Bonus coverage of the SCJD exam included!
Bonus downloadable MasterExam practice test with free online registration.
To Download Click Below

SCJP Sun Certified Programmer for Java 6 Exam 310-065


About the Author
Kathy Sierra is a co-developer of the SCJP exam and SunAnd#39;s practice exam. She is also a Sun Certified Java Instructor and the founder of the worldAnd#39;s largest Java certification website, Javaranch.com.

Bert Bates is a Sun Certified Programmer for Java and has participated in the development of the SCJP exam and SunAnd#39;s practice exam. He is the coauthor, with Kathy Sierra, of the previous editions of this book.

Read more...

Sunday, March 22, 2009

Data Type Conversion(Casting)

Type Conversion(Type Casting)

Every variable is explicitly defined of some type.Before used in any experssion..Consider following experssions:

int x=2;
double y;
float f=2.3f;
y=x+f;

As told in assignment operators that expressions to the right of '=' is evaluated first and assignd to the left variable.The experssion on the right has two variable of different data types(numeric) int and float.The int value is automatically promoted to the higher data type float because float has higher range than int.When experssion is evaluated the resulting value is of type float.This value is to be assigned to variable y,which is of type double whose range is even larger than float thus result is double.In case if the type of variable y is int the the snippet on compilation result in an error.


NOTE:- Java automatically promotes values to higher data types,to prevent loss of information.

If you attempt following

int x=2.65/2;

after evaluation of expression on right the resulting value is of type float and when assignment occur it will result in compile error stated as:
"Incompatible types for declaration,Explicit cast needed to convert double to int."


This is because the data can be lost when it is converted from higher data types to lower data type.The compiler requires that you typecast the assignment.To accomplish this type previous declaration as:

int x=(int)2.65/2;

This is known as explicit typecasting.Explicit typecasting has to be done where there is chance of losing th precision of data.
lets take a look at other example:

short a=1,b=2,c;
c=a+b;

This code seems fine at first as all variables are of same data type.Howere ,the compiler returnes an error.Following explains why

When you use '+' operator ,data resulting from experssion using '+' is assumed to be atleast int by java comiler.Thus you will have to either declare z as int or explicitly cast z as short as
z=(short)(a+b);

NOTE:-
When you typecast to lower data type,you may always lose some data.Always check the result of such a typecast.

Rules for typecasting:-

1.Aboolean value cannot be typecat.
2.There is implicit conversion for non-boolean data if the conversion increases the range of data that can be stored.
3.If the range is narrowed,an implicit typecast is required.
4.The implicit casting order is
byte -->short -->int -->long -->float -->double
char -->int -->float -->double.
5.Any other conversion needs to be typecast as it narrows the range of values that can be stored.

Read more...

Friday, March 20, 2009

JDBC-ResultSet Object

The ResultSet Object

The ResultSet Object provides you with method to access data from the table .Executing a statement usually generates a ResultSet object.It maintains a pionter which points to the current row of data.Initially ResultSet is pointed towards the value '-1' that is before first value
and ResultSet.next() takes it to first row.The next() method takes it to next row of data.
You can retrieve data from ResultSet rows by calling the getXXX() methods.Where XXX is
the data type.of parameter.

Syntax:-
// ResultSet result=[Statement object].executeQuery("select * from emp");

Simple JDBC Example:-
// simplejdbc.java
public class simplejdbc{
public static void main(String args[]){
ResultSet result;
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection ("jdbc:odbc:MyDataSource","sa","");
Statement stat=con.createStatement();
result=stat.executeQuery("select * from emp");
while (result.next())
{
System.out.println(result.getString(1));
}
}catch(Exception e)
{
}
}
}

Explanation:-
Firstly load the driver through Class.forName() method.Then create connection providing connection string.After that create a statement object through which queries will be executed.
Now results of queries are fetched into ResultSet obect and getString(index of column or name of column) which further may be used for computations.

Read more...

Thursday, March 19, 2009

Setting Mnemonics and Shortcut Keys

Setting a Shrotcut Key(Mnemonic)

A shortcut key is an underlined character you may in labels,buttons,menus etc.These are called as mnemonics.You can select a control by pressing the combination of Alt key and the character.For example if underlined character is 's' then in order to activate control press Alt+s.You can set mnemonic by using setMnemonic(Char ch)

Syntax:-

component.setMnemonic(Char ch);

Exapmle:-
In the Screen shot the mnemonic is set as 'M'.
So this button can be activated by pressing Alt+M.
// memonic.java

import java.awt.*;
import javax.swing.*;
public class mnemonic
{
public static void main(String a[])
{
JFrame frm=new JFrame("Mnemonic Demo");
JPanel panel=new JPanel();
JButton Button=new JButton("Setting Mnemonic");
Button.setMnemonic('M');
panel.add(Button);
frm.getContentPane().add(panel);
frm.setVisible(true);
frm.pack();
}
}

Read more...

Setting ToolTip and Icon

Adding Icons and ToolTips

Tooltips are shot information messages which are displayed when your mouse pointer rests at some components.That is if suppose your mose pointer is at a button whose tooltiop is set as "click here" the if your pointer comes over button the a small message will appear saying "click here".

For setting ToolTip we can use setToolTipText() method of JComponent class.

ToolTip Example:-

// tooltip.java

import javax.swing.*;
public class tooltip
{
public static void main(String a[])
{
JFrame frm=new JFrame("ToolTip Demo");
JPanel panel=new JPanel();
JLabel labeltool=new JLabel("ToolTio DemoPlace mouse over it");
labeltool.setToolTipText("This is ToolTip");
panel.add(labeltool);
frm.getContentPane().add(panel);
frm.setVisible(true);
frm.pack();
}
}

SettingIcon Example:-

// settingicon.java

import java.awt.*;
import javax.swing.*;
public class settingicon
{
public static void main(String a[])
{
JFrame frm=new JFrame("Setting Icon Demo");
JPanel panel=new JPanel();
JLabel label=new JLabel(new ImageIcon("BAK.png"));
panel.add(label);
frm.getContentPane().add(panel);
frm.setVisible(true);
frm.pack();
}
}

Read more...

Tuesday, March 17, 2009

DataBase Querying

Querying a DataBase

Once a connection with the database is established we can proceed with the data retrieval,insertion and other database functions.In JDBC we can query the database and process the results contained in resultset.
JDBC does not enforce any restriction on the type of SQL statements that can be sent,but as a programmer,you must ensure that database must be able to process the statements.

JDBC provides three classes for sending SQL statements to a database.These are:-

1.The Statement object:-You can create the statement object by calling the createStatement() method from the Connection object.
The statement object is mostly used to fetch the records from database.

Syntax:-
// Statement stat=conn.createStatement();

2.The PreparedStatement object:-You can create the PreparedStement object by calling the PreparedStatement() method from the Connection object.The PreparedStatement object contains set of methods that you can use for sending queries with INPUT parameters.For example inserting values in database it is done through PreparedStatements.

Syntax:-
// PreparedStatement pstat=conn.prepareStatement("select * from emp where empid=?");
// pstat.setString(1,empid);
// pstat.executeQuery();

3.The CallabeStatement object:- You can create the CallabeStatement object by calling the preapareCall() method from the Conncetion object.This object contains full fuctionality for calling a stored procedure.You can handle both input as well as output parameters using CallableStatement object.

Read more...

Monday, March 16, 2009

Connecting to Database

Connecting to a database

Java Contains java.sql package which contains classes that help in connecting to a database.You may have several connection objects in an application that connects to one or more databases.
Steps for connecting databse:-There are steps to follow in order to connect to a database

Step1:- Load the JDBC Specific driver

To establish a connection with a database ,you need to load specific type driver.e.g. if you are using JDBC-ODBC Bridge as connection load its drivre and if you are using JDBC type 4 driver then load that driver.
For loading the driver following syntax is used:-

for JDBC-ODBC
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
for JDBC Type 4 driver
Class.forName("net.sourceforge.jtds.jdbc.Driver");

That is the abstract is you have to specify the path where the driver is located in your classpath.

Step2:- Establish the connetcion

In order to establish a connection you have to call the getConnection() method of Driver Manager class The getConnection() method of DriverManager class attempts to locate the driver that can connect to the database represented by the JDBC URL passed to the getConnection() method.

for exmaple:-
for JDBC-ODBC Bridge
Connection conn=DriverManager.getConnection("jdbc:odbc:Mydatasource"," "," ");
for JDBC Type 4 Driver
Connection conn=DriverManager.getConnection(""jdbc:jtds:sqlserver://localhost:1433/master","sa",""");

The JDBC URL
The JDBC URL is a string that provides a way of identifying a database .A JDBC URL is divided into following parts.

protocol:subprotocol:datasource

Protocol:-This identifies main protocol that is jdbc.
subprotocol:-It is the name of the database connectivity mechanism.If the mechanism of retrieving the data is JDBC-ODBC the subprotocol will be odbc.
datasource:-It identifies the datasource on a system.It can be remote also but you have to provide the full network address of datasource.

Example:-

//connect.java
Connection conn;
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
conn=DriverManager.getConnection("jdbc:odbc:Mydatasource","sa"," ");
System.out.println("Connected to Mydatasource........");
}catch(Exception e){
System.out.println("Error in connnection........");
}

Read more...

Saturday, March 7, 2009

Configuring ODBC Data Sources

Configuring ODBC Data Source for JDBC Connection


Following are the steps to follow to create a data source for JDBC-ODBC  Connection.

Step1 :-Open Control panel>Click on Administrative tools




Step 2:-
Now click on Data Souces(ODBC) to create the database
Step 3:-Proceed to add a new User DSN click add..

Step 4:- In create a new Data source wizard add the databse which you are using then click finish.

Step 5:-Specify the name of your DataSource in specific field and specify the server too.

Step 6:-In this step anthenticate yourself either with windows authentication or DBMS specific authentication by entering the usrename and password.

Step 7:-If you want to change default database and if you want to attach a database file change the settings according to you or left it as it is.

Step 8:-If you want to change log addresses and to change SQL Server message language change in this window.


Step 9:-Now Test your Data Source by clicking Test Data Source..

Step 10:-If Test completed successfully then following window will appear otherwise go back and some settings as per error.




Read more...

JDBC:Introduction

DataBase Management
A database is a collection of related information and DBMS is a software that provides you with a mechanism to store,retrive and modify data in databse.
There are many DBMS/RDBMS products available such as MS-SQL Server,IBM DB2,MS-Access etc.Each DBMS/RDBMS stores data in its own format.
It is an easy task to handle databse through front end as end user does not know the complex functionality of DBMS product.To made it easy just design a front end and do all databse handling through event handling.


Database Connectivity:-


For your application to interact with the database,it needs to have the following information:
1.The DBMS/RDBMS product using which the database is created.
2.The location of database.
3.The name of database.

ODBC(Open Database Connectivity) API
ODBC API is a set of libraray routines that enable your programs to access a variety of databses.All you need to do is install DBMS specific ODBC driver and write your programs to interact with specific Odbc driver.
Later,if the database is upgraded to a newer version of DBMS/RDBMS product ,you will need to change only the ODBC driver and not the program.

JDBC(Java Database Connectivity) API

JDBC probides a database programming API.Since ODBC API is written in C language and makes use of Clanguage constructs that Java does not support,a Java program cannot directly communicate with an ODBC driver.
There are 4 types of JDBC drivers are available :
1.JDBC-ODBC bridge drivers
2.Native API partly Java driver
3.JDBC net pure Java driver.
4.Native protocol pure Java driver

Here we will discuss JDBC-ODBC bridge driver which is the basic of all 4 and not very complex.

JDBC driver manager
The JDBC driver manager is very important in JDBC architecture.The function of JDBC driver manager is to connect a Java application to the appropriate driver specified in your application.



JDBC-ODBC bridge
The Sun microsystems provides a driver to access ODBC data sources from JDBC.This driver is called JDBC-ODBC BRIDGE.The JDBC-ODBC bridge is implemented as the JdbcOdbc.class and a native library is used to access the ODBC driver.In the windows platform,the native library is JDBCODBC.dll

CONFIGURE ODBC DATA SOURCE  >>>

Home

Read more...

Friday, March 6, 2009

JTextField


JTextField

A text field is a basic text control that enables the user to type a small amount of text.
The text field is editable. It is handy in cases 
where a single line of input is required or a little information is neede.
It is mostly used in forms and does most work on Event handling.There are certain methods which copies the contents of TextField whenever an action is fired.


Constructors:-

JTextField has four types of constructors which are as follows

1.JTextField()

2.JTextField(String)  //Creates a TextField with initial text as String

3.JTextField(String,int)  //creates a TextField with length of cloumn being chars and default text is as String

4.JTextField(int)   //creates s TextField with length  of column being chars.

Note: Always try to specify the number of columns for each text field. If you do not specify the number of columns or a preferred size, then the field's preferred size changes whenever the text changes, which can result in unwanted layout changes.

Example:-Creating a form with JTextField

//textfield.java
import javax.swing.*;
class textfield extends JFrame{
public static void main(String a[]){
  JFrame frame=new JFrame("JTextFieldDemo");
  JPanel panel=new JPanel();
  JTextField txt=new JTextField(10);
  JTextField txtf=new JTextField("Default",20);   //with default text written and size of 20 
  panel.add(txt);
  panel.add(txtf);
  frame.getContentPane().add(panel);
  frame.setVisible(true);
  frame.pack();
}
}

We have several methods for getting and setting values from and to JTextField

1.String getText()

2.void setText(String)

Edit methods of JTextField component

1.void setEditable(boolean)  //set whether the text in the JTextField is editable or not

2. boolean isEditable()   //returns whether the tetfield is editable or not

For setting and getting the width of JTextField use

void setColumns(int)  //specifies the width of textfield

int getColumns()  //obtains number of columns of the TextField

For selecting whole field at once use following

void selectAll() 
For adding ActionListeners use following

void addActionListener(ActionListener)  //adds action listener

void removeActionListener(ActionListener)  //removes ActionListener

Related links:-

Read more...

Exception Matching

Exception Matching

When an exception is thrown, Java will try to find a catch clause for the exception type. If it doesn't
find one, it will search for a handler for a supertype of the exception. If it does not
find a catch clause that matches a supertype for the exception, then the exception
is propagated down the call stack. This process is called exception matching. Let's
look at an example:

//except.java

import java.io.*;

public class except {
public static void main(String a[]){
try{
RandomAccessFile raf=new RandomAccessFile("myfile.java","r");
byte[] b=new byte[1000];
raf.readFully(b,0,1000);
}catch(FileNotFoundException e){
System.out.println("File not found");
System.out.println(e.getMessage());
e.printStackTrace();
}catch(IOException e){
System.out.println("IO Exception");
System.out.println(e.getMessage());
}
}
}

Explanation:-
This program attempts to open a file and to read some data from it.Opening
and reading files can generate many exceptions, most of which are some type of
IOException.FileNotFoundException is a subclass of IOException. Therefore, we
could handle it in the catch clause that catches all subtypes of IOException,
but then we would have to test the exception to determine whether it was a
FileNotFoundException.Instead, we coded a special exception handler for
the FileNotFoundException and a separate exception handler for all other
IOException subtypes.If this code generates a FileNotFoundException, it will be handled by the first catch clause. If it generates another IOException—perhaps
EOFException, which is a subclass of IOException—it will be handled by the
second catch clause.
If some other exception is generated, such as
a runtime exception of some type, neither catch clause will be executed and the
exception will be propagated down the call stack.
Notice that the catch clause for the FileNotFoundException was placed above
the handler for the IOException. This is really important! If we do it the opposite
way, the program will not compile. The handlers for the most specific exceptions
must always be placed above those for more general exceptions.

Read more...

Wednesday, March 4, 2009

User Defined Exceptions

User Defined Exceptions

You can also create your own exceptions by extending Exception class.
The extended class contains constructors,data members,and methods like any other class.
The throw and throws keywords are used while implementing user defined exceptions.

Example:-

class IllegalException extends Exception{
}

class trial{
int num1,num2;
public trial{
val1=a;
val2=b;
}
void show()throws IllegalException{
if((num1<0)(num2>0)) throw new IllegalException();
System.out.println("value 1=:"+num1);
System.out.println("value 2=:"+num2);
}
}

class Exceptionexample{
public static void main(String a[]){
trial value=new trial(-1,1);
try{
value.show();
}catch(IllegalException e){
System.out.println("Illegal values caught");
}
}
}

Illustration:-
1.Class IllegalException is extended from Exception class.
2.trial class has a method that throws a user defined exception called IllegalException.
3.The main() method in Exceptionexample class creates an object of class trial and
passes errorneous values to the constructor.
4.show method() throws an exception ,which is caught by the exception handlerin the main() method.
5.The message present in the catch block,"Illegal values caught",is displayed on the screen.

Read more...

Exception Hierarchy



All exception classes are subtypes of class Exception. This class derives from the
class Throwable (which derives from the class Object).Above Figure shows the
hierarchy for the exception classes.
As you can see, there are two subclasses that are derived from Throwable: Exception
and Error. Classes that derive from Error represent unusual situations that are
not caused by program errors, and indicate things that would not normally happen
during program execution, such as the JVM running out of memory.

Generally, application won't be able to recover from an Error,
so you're not required to handle them.
If your code does not handle them (and it usually won't), it will still compile with no trouble. Although often thought of as exceptional conditions, Errors are
technically not exceptions because they do not derive from class Exception.

In general, an exception represents something that happens not as a result of
a programming error, but rather because some resource is not available or some
other condition required for correct execution is not present
For example, if your
application is supposed to communicate with another application or computer that
is not answering, this is an exception that is not caused by a bug.Above Figure also
shows a subtype of Exception called RuntimeException. These exceptions are
a special case because they sometimes do indicate program errors. They can also
represent rare, difficult-to-handle exceptional conditions. Runtime exceptions are
discussed in greater detail later in this chapter.

Java provides many exception classes, most of which have quite descriptive
names. There are two ways to get information about an exception. The first is
from the type of the exception itself. The next is from information that you can
get from the exception object. Class Throwable (at the top of the inheritance
tree for exceptions) provides its descendants with some methods that are useful in
exception handlers. One of these is printStackTrace(). As expected, if you call
an exception object's printStackTrace() method.
We discussed that a call stack builds upward with the most recently called method
at the top. You will notice that the printStackTrace() method prints the most
recently entered method first and continues down, printing the name of each
method as it works its way down the call stack (this is called unwinding the stack)
from the top.

Read more...

Use of finally

Use of finally

Sometimes when an exception is raised ,the rest of statements in try block are ignored.Sometimes it is necessry to process certain statements,no matter whether an exception is raised or not.
A finally block encloses code that is always executed at some point after the
try block, whether an exception was thrown or not. Even if there is a return
statement in the try block, the finally block executes right after the return
statement is encountered, and before the return executes.
This is the right place to close your files, release your network sockets, and
perform any other work your code requires. If the try block executes with
no exception, the finally block is executed just after the try block
completes. If there was an exception occured, the finally block executes
immediately after the proper catch block completes.

Remember:-
1.Finally blocks are not mandatory in exception handling.
2.There can be only One finally block for a try.
3.finally can follow try that is finally can exist without catch as follows
try{
//do something
}
finally{
//Handle here
}
4.No code can be placed in between try catch.
5.No code can be placed between try finally.
6.If finally is to be placed in after try containing catche(s) then finally must follow last catch statemet.


Example:-

try{
opensomeFile();
writeanyFile(); //may result in exception
}
catch(Exception.....){
process the exception
}
finally{
closeFile();
}

In the above example we have to close the file irrespective of whether the exception is occured or not.You can place the code in both ty and catch blocks.But assume a situation where
exception is thrown before closing that file and we have no catch for exception raised.
our file will remain open.Thus in finally block we put the code which will be executed all the times regardless of whetehr an exception is raised or not.

Read more...

About This Blog

This Blog is all about Java and programming.This blog is written by Vaibhav Pandey .He is a Computer Science Graduate .You can contact the author at javatute@gmail.com for any suggestion or Query.You can also contact the author for advertising on this blog.All the material presented here is the property of author and its reproduction in any form is strictly prohibited.

Disclaimer:-Download links provided here are not of author in any means.These are found over the Internet.
Page copy protected against web site content infringement by Copyscape

  © Blogger templates The Professional Template by Ourblogtemplates.com 2008

Back to TOP