Labels

Showing posts with label JAVA. Show all posts
Showing posts with label JAVA. Show all posts

20 Jun 2012

JDBC Introduction


The JDBC API is a Java API that can access any kind of tabular data, especially data stored in a Relational Database.
JDBC helps you to write Java applications that manage these three programming activities:
  1. Connect to a data source, like a database
  2. Send queries and update statements to the database
  3. Retrieve and process the results received from the database in answer to your query

15 Jun 2012

The Greatest Question\Riddle of Them All?

As our Java project progressed, we began to add new members to our development team.
This meant many resumes to review and many interviews to conduct.
It was to become quite a time consuming chore for the interviewers.
During a portion of the interview, a series of technical questions about Java are asked.
The goal behind these questions is to allow the interviewee to talk to us about Java.
Some of the Java questions are general. Some of the Java questions are more specific.
The general questions will sometimes yield some very creative answers from the interviewee.
One of our questions is fairly specific.
The question is : "How can you send data from a Servlet to a JSP and back?"
A very simple question. A very simple answer is all that is expected.
The answer we expect needed to include mention of
the "getAttribute" method, the "setAttribute" method, and the "HttpServletRequest" object.
We believed that all of the Java interviewees would answer this question easily.
We were wrong!
Over 90% of the interviewees could not give a satisfactory answer to this question.
Some of the answers, we got, were long-winded statements about frameworks, tag libraries, database access, etc.
Some of the interviewees would simply say, "I don't know".
When the answer is revealed, the interviewee would usually say, "oh yeah, that's right".
This greatly surprised us. Why was this happening?
We concluded that this question can be correctly answered by the Java developer who
has actually written this kind of code.
To someone who has never written this kind of code, the answer is not evident.
Nevertheless, we have been able to find plenty of Java developers for our team.
The turnover rate of developers on our team is very low.
We have been very happy with the quality of work produced by the Java developers on our team.
We still ask this question during our interviews.
The fact that this question is giving most of our interviewees so much trouble,
causes us to wonder if we are asking the interviewees to solve the greatest riddle of all time!

14 Jun 2012

Interview Questions on Java

Java Interview Questions site attempts to discuss core java IT technical interview questions in detail. These are some of the java job interview questions that were asked in various java interviews. Questions from different people and communities are consolidated in place for your convenience. These questions are organized according to various java topics. This is to help you prepare well for java related technical interviews. I wish you good luck and hope you find a great job.

Interview Questions on Java

What if the main method is declared as private?
The program compiles properly but at runtime it will give “Main method not public.” message.
What is meant by pass by reference and pass by value in Java?
Pass by reference means, passing the address itself rather than passing the value. Pass by value means passing a copy of the value.
If you’re overriding the method equals() of an object, which other method you might also consider?
hashCode()
What is Byte Code?
Or
What gives java it’s “write once and run anywhere” nature?
All Java programs are compiled into class files that contain bytecodes. These byte codes can be run in any platform and hence java is said to be platform independent.
Expain the reason for each keyword of public static void main(String args[])?
public- main(..) is the first method called by java environment when a program is executed so it has to accessible from java environment. Hence the access specifier has to be public.
static: Java environment should be able to call this method without creating an instance of the class , so this method must be declared as static.
void: main does not return anything so the return type must be void
The argument String indicates the argument type which is given at the command line and arg is an array for string given during command line.
What are the differences between == and .equals() ?
Or
what is difference between == and equals
Or
Difference between == and equals method
Or
What would you use to compare two String variables – the operator == or the method equals()?
Or
How is it possible for two String objects with identical values not to be equal under the == operator?
The == operator compares two objects to determine if they are the same object in memory i.e. present in the same memory location. It is possible for two String objects to have the same value, but located in different areas of memory.
== compares references while .equals compares contents. The method public boolean equals(Object obj) is provided by the Object class and can be overridden. The default implementation returns true only if the object is compared with itself, which is equivalent to the equality operator == being used to compare aliases to the object. String, BitSet, Date, and File override the equals() method. For two String objects, value equality means that they contain the same character sequence. For the Wrapper classes, value equality means that the primitive values are equal.
 public class EqualsTest {

 public static void main(String[] args) {

  String s1 = "abc";
  String s2 = s1;
  String s5 = "abc";
  String s3 = new String("abc");
  String s4 = new String("abc");
  System.out.println("== comparison : " + (s1 == s5));
  System.out.println("== comparison : " + (s1 == s2));
  System.out.println("Using equals method : " + s1.equals(s2));
  System.out.println("== comparison : " + s3 == s4);
  System.out.println("Using equals method : " + s3.equals(s4));
 }
}
Output
== comparison : true
== comparison : true
Using equals method : true
false
Using equals method : true
What if the static modifier is removed from the signature of the main method?
Or
What if I do not provide the String array as the argument to the method?
Program compiles. But at runtime throws an error “NoSuchMethodError”.
Why oracle Type 4 driver is named as oracle thin driver?
Oracle provides a Type 4 JDBC driver, referred to as the Oracle “thin” driver. This driver includes its own implementation of a TCP/IP version of Oracle’s Net8 written entirely in Java, so it is platform independent, can be downloaded to a browser at runtime, and does not require any Oracle software on the client side. This driver requires a TCP/IP listener on the server side, and the client connection string uses the TCP/IP port address, not the TNSNAMES entry for the database name.
What is the difference between final, finally and finalize? What do you understand by the java final keyword?
Or
What is final, finalize() and finally?
Or
What is finalize() method?
Or
What is the difference between final, finally and finalize?
Or
What does it mean that a class or member is final?
o final – declare constant
o finally – handles exception
o finalize – helps in garbage collection
Variables defined in an interface are implicitly final. A final class can’t be extended i.e., final class may not be subclassed. This is done for security reasons with basic classes like String and Integer. It also allows the compiler to make some optimizations, and makes thread safety a little easier to achieve. A final method can’t be overridden when its class is inherited. You can’t change value of a final variable (is a constant). finalize() method is used just before an object is destroyed and garbage collected. finally, a key word used in exception handling and will be executed whether or not an exception is thrown. For example, closing of open connections is done in the finally method.
What is the Java API?
The Java API is a large collection of ready-made software components that provide many useful capabilities, such as graphical user interface (GUI) widgets.
What is the GregorianCalendar class?
The GregorianCalendar provides support for traditional Western calendars.
What is the ResourceBundle class?
The ResourceBundle class is used to store locale-specific resources that can be loaded by a program to tailor the program’s appearance to the particular locale in which it is being run.
Why there are no global variables in Java?
Global variables are globally accessible. Java does not support globally accessible variables due to following reasons:
  • The global variables breaks the referential transparency
  • Global variables creates collisions in namespace.
How to convert String to Number in java program?
The valueOf() function of Integer class is is used to convert string to Number. Here is the code example:
String numString = “1000″;
int id=Integer.valueOf(numString).intValue();
What is the SimpleTimeZone class?
The SimpleTimeZone class provides support for a Gregorian calendar.
What is the difference between a while statement and a do statement?
A while statement (pre test) checks at the beginning of a loop to see whether the next loop iteration should occur. A do while statement (post test) checks at the end of a loop to see whether the next iteration of a loop should occur. The do statement will always execute the loop body at least once.
What is the Locale class?
The Locale class is used to tailor a program output to the conventions of a particular geographic, political, or cultural region.
Describe the principles of OOPS.
There are three main principals of oops which are called Polymorphism, Inheritance and Encapsulation.
Explain the Inheritance principle.
Inheritance is the process by which one object acquires the properties of another object. Inheritance allows well-tested procedures to be reused and enables changes to make once and have effect in all relevant places
What is implicit casting?
Implicit casting is the process of simply assigning one entity to another without any transformation guidance to the compiler. This type of casting is not permitted in all kinds of transformations and may not work for all scenarios.
Example
int i = 1000;
long j = i; //Implicit casting
Is sizeof a keyword in java?
The sizeof operator is not a keyword.
What is a native method?
A native method is a method that is implemented in a language other than Java.
In System.out.println(), what is System, out and println?
System is a predefined final class, out is a PrintStream object and println is a built-in overloaded method in the out object.
What are Encapsulation, Inheritance and Polymorphism
Or
Explain the Polymorphism principle. Explain the different forms of Polymorphism.
Polymorphism in simple terms means one name many forms. Polymorphism enables one entity to be used as a general category for different types of actions. The specific action is determined by the exact nature of the situation.
Polymorphism exists in three distinct forms in Java:
• Method overloading
• Method overriding through inheritance
• Method overriding through the Java interface
What is explicit casting?
Explicit casting in the process in which the complier are specifically informed to about transforming the object.
Example
long i = 700.20;
int j = (int) i; //Explicit casting
What is the Java Virtual Machine (JVM)?
The Java Virtual Machine is software that can be ported onto various hardware-based platforms
What do you understand by downcasting?
The process of Downcasting refers to the casting from a general to a more specific type, i.e. casting down the hierarchy
What are Java Access Specifiers?
Or
What is the difference between public, private, protected and default Access Specifiers?
Or
What are different types of access modifiers?
Access specifiers are keywords that determine the type of access to the member of a class. These keywords are for allowing
privileges to parts of a program such as functions and variables. These are:
Public : accessible to all classes
Protected : accessible to the classes within the same package and any subclasses.
Private : accessible only to the class to which they belong
Default : accessible to the class to which they belong and to subclasses within the same package
Which class is the superclass of every class?
Object.
Name primitive Java types.
The 8 primitive types are byte, char, short, int, long, float, double, and boolean.
What is the difference between static and non-static variables?
Or
What are class variables?
Or
What is static in java?
Or
What is a static method?
A static variable is associated with the class as a whole rather than with specific instances of a class. Each object will share a common copy of the static variables i.e. there is only one copy per class, no matter how many objects are created from it. Class variables or static variables are declared with the static keyword in a class. These are declared outside a class and stored in static memory. Class variables are mostly used for constants. Static variables are always called by the class name. This variable is created when the program starts and gets destroyed when the programs stops. The scope of the class variable is same an instance variable. Its initial value is same as instance variable and gets a default value when its not initialized corresponding to the data type. Similarly, a static method is a method that belongs to the class rather than any object of the class and doesn’t apply to an object or even require that any objects of the class have been instantiated.
Static methods are implicitly final, because overriding is done based on the type of the object, and static methods are attached to a class, not an object. A static method in a superclass can be shadowed by another static method in a subclass, as long as the original method was not declared final. However, you can’t override a static method with a non-static method. In other words, you can’t change a static method into an instance method in a subclass.
Non-static variables take on unique values with each object instance.
What is the difference between the boolean & operator and the && operator?
If an expression involving the boolean & operator is evaluated, both operands are evaluated, whereas the && operator is a short cut operator. When an expression involving the && operator is evaluated, the first operand is evaluated. If the first operand returns a value of true then the second operand is evaluated. If the first operand evaluates to false, the evaluation of the second operand is skipped.
How does Java handle integer overflows and underflows?
It uses those low order bytes of the result that can fit into the size of the type allowed by the operation.
What if I write static public void instead of public static void?
Program compiles and runs properly.
What is the difference between declaring a variable and defining a variable?
In declaration we only mention the type of the variable and its name without initializing it. Defining means declaration + initialization. E.g. String s; is just a declaration while String s = new String (“bob”); Or String s = “bob”; are both definitions.
What type of parameter passing does Java support?
In Java the arguments (primitives and objects) are always passed by value. With objects, the object reference itself is passed by value and so both the original reference and parameter copy both refer to the same object.
Explain the Encapsulation principle.
Encapsulation is a process of binding or wrapping the data and the codes that operates on the data into a single entity. This keeps the data safe from outside interface and misuse. Objects allow procedures to be encapsulated with their data to reduce potential interference. One way to think about encapsulation is as a protective wrapper that prevents code and data from being arbitrarily accessed by other code defined outside the wrapper.
What do you understand by a variable?
Variable is a named memory location that can be easily referred in the program. The variable is used to hold the data and it can be changed during the course of the execution of the program.
What do you understand by numeric promotion?
The Numeric promotion is the conversion of a smaller numeric type to a larger numeric type, so that integral and floating-point operations may take place. In the numerical promotion process the byte, char, and short values are converted to int values. The int values are also converted to long values, if necessary. The long and float values are converted to double values, as required.
What do you understand by casting in java language? What are the types of casting?
The process of converting one data type to another is called Casting. There are two types of casting in Java; these are implicit casting and explicit casting.
What is the first argument of the String array in main method?
The String array is empty. It does not have any element. This is unlike C/C++ where the first element by default is the program name. If we do not provide any arguments on the command line, then the String array of main method will be empty but not null.
How can one prove that the array is not null but empty?
Print array.length. It will print 0. That means it is empty. But if it would have been null then it would have thrown a NullPointerException on attempting to print array.length.
Can an application have multiple classes having main method?
Yes. While starting the application we mention the class name to be run. The JVM will look for the main method only in the class whose name you have mentioned. Hence there is not conflict amongst the multiple classes having main method.
When is static variable loaded? Is it at compile time or runtime? When exactly a static block is loaded in Java?
Static variable are loaded when classloader brings the class to the JVM. It is not necessary that an object has to be created. Static variables will be allocated memory space when they have been loaded. The code in a static block is loaded/executed only once i.e. when the class is first initialized. A class can have any number of static blocks. Static block is not member of a class, they do not have a return statement and they cannot be called directly. Cannot contain this or super. They are primarily used to initialize static fields.
Can I have multiple main methods in the same class?
We can have multiple overloaded main methods but there can be only one main method with the following signature :
public static void main(String[] args) {}
No the program fails to compile. The compiler says that the main method is already defined in the class.
Explain working of Java Virtual Machine (JVM)?
JVM is an abstract computing machine like any other real computing machine which first converts .java file into .class file by using Compiler (.class is nothing but byte code file.) and Interpreter reads byte codes.
How can I swap two variables without using a third variable?
Add two variables and assign the value into First variable. Subtract the Second value with the result Value. and assign to Second variable. Subtract the Result of First Variable With Result of Second Variable and Assign to First Variable. Example:
int a=5,b=10;a=a+b; b=a-b; a=a-b;
An other approach to the same question
You use an XOR swap.
for example:

int a = 5; int b = 10;
a = a ^ b;
b = a ^ b;
a = a ^ b;
What is data encapsulation?
Encapsulation may be used by creating ‘get’ and ‘set’ methods in a class (JAVABEAN) which are used to access the fields of the object. Typically the fields are made private while the get and set methods are public. Encapsulation can be used to validate the data that is to be stored, to do calculations on data that is stored in a field or fields, or for use in introspection (often the case when using javabeans in Struts, for instance). Wrapping of data and function into a single unit is called as data encapsulation. Encapsulation is nothing but wrapping up the data and associated methods into a single unit in such a way that data can be accessed with the help of associated methods. Encapsulation provides data security. It is nothing but data hiding.
What is reflection API? How are they implemented?
Reflection is the process of introspecting the features and state of a class at runtime and dynamically manipulate at run time. This is supported using Reflection API with built-in classes like Class, Method, Fields, Constructors etc. Example: Using Java Reflection API we can get the class name, by using the getName method.
Does JVM maintain a cache by itself? Does the JVM allocate objects in heap? Is this the OS heap or the heap maintained by the JVM? Why
Yes, the JVM maintains a cache by itself. It creates the Objects on the HEAP, but references to those objects are on the STACK.
What is phantom memory?
Phantom memory is false memory. Memory that does not exist in reality.
Can a method be static and synchronized?
A static method can be synchronized. If you do so, the JVM will obtain a lock on the java.lang.
Class instance associated with the object. It is similar to saying:
synchronized(XYZ.class) {
}
What is difference between String and StringTokenizer?
A StringTokenizer is utility class used to break up string.
Example:
StringTokenizer st = new StringTokenizer(“Hello World”);
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
Output:
Hello
World

24 May 2012

Core Java Syllabus

 

 Introduction of Java


  • What is Java?
  • How to Get Java
  • A First Java Program
  • Compiling and Interpreting Applications
  • The JDK Directory Structure

Data types and Variables


  • Primitive Datatypes ,Declarations
  • Variable Names
  • Numeric Literals,Character Literals
  • String,String Literals
  • Arrays,Non-Primitive Datatypes,The Dot Operator


Operators and Expressions


  • Expressions
  • Assignment Operator
  • Arithmetic Operators
  • Relational Operators
  • Logical Operators
  • Increment and Decrement Operators
  • Operate-Assign Operators (+=, etc.)
  • The Conditional Operator
  • Operator Precedence
  • Implicit Type Conversions
  • The Cast Operator

23 May 2012

Advanced Java Syllabus

            Advanced Java Programming(Download as pdf)

                                

                                           

Java Database Connectivity

 

o JDBC Product
o Types of Drivers
o Two-Tier Client/Server Model
o Three-Tier Client/Sever Model
o Basic Steps of JDBC
o Creating and Executing SQL Statement
o The Result Set Object
o Working with Database MetaData
o Interface

 

Servlets

 

o Servlet Interaction & Advanced Servlets
o Life cycle of Servlet
o Java Servlet Development Kit
o Javax.servlet package
o Reading Servlet Parameters
o Reading Initialization Parameters
o The javax.servlet.http Package
o Handling HTTP

 

JavaServer Pages

 

o JSP Technologies
o Understanding the Client-Server Model
o Understanding Web server software
o Configuring the JSP Server
o Handling JSP Errors
o JSP Translation Time Errors
o JSP Request Time Errors
o Creating a JSP Error Page

 

RMI

 

o RMI Architecture
o Designing RMI application
o Executing RMI application

 

EJB

 

o Types of EnterpriseJava beans
o Session Bean & Entity Bean
o Features of Session Bean
o Life-cycle of Stateful Seession Bean
o Features of Entity Bean
o Life-cycle of Entity Bean
o Container-managed Transactions &
o Bean-managed Transactions
o Implementing a container-manged Entity Bean

 

XML

 

o What is XML?
o XML Syntax Rules

 

Struts

 

o Introduction to the Apache Struts
o MVC Architecture
o Struts Architecture
o How Struts Works?
o Introduction to the Struts Controller
o Introduction to the Struts Action Class
o Using Struts ActionFrom Class
o Using Struts HTML Tags
o Introduction to Struts Validator Framework
o Client Side Address Validation in Struts
o Custom Validators Example
o Developing Application with Struts Tiles

 

Hibernate

 

o Introduction to Hibernate 3.0
o Hibernate Architecture
o First Hibernate Application

21 May 2012

TUTORIAL 6 - Collections

Collections


Collections
A Collection allows a group of objects to be treated as a single unit. Collections define a set of core interfaces. These are -
  • Collection
  • Set
  • List
  • SortedSet
  • Map
  • SortedMap
Collections also provide implementation for these interfaces.
Core Interfaces
The Object hierarchy of Core Interfaces defined in Collections is given below.
Figure: Core Interfaces of Collections
Collection Interface
The Collection interface is the root of Collection hierarchy, and is used for common functionality across all collections. There is no direct implementation of Collection interface.
Set Interface
The Set interface is used to represent a group of unique elements. It extends the Collection interface. The class HashSet implements the Set interface.
SortedSet Interface
The SortedSet interface extends the Set interface. It provides extra functionality of keeping the elements sorted. So SortedSet interface is used to represent collections consisting of unique, sorted elements. The class TreeSet is an implementation of interface SortedSet.
List Interface
The list interface extends the Collection interface to represent sequence of numbers in a fixed order. Classes ArrayList, Vector and LinkedList are implementation of List interface.
Map Interface
The Map Interface is a basic interface that is used to represent mapping of keys to values. Classes HashMap and Hashtable are implementations of Map interface.
SortedMap Interface
The SortedMap Interface extends Map interface and maintains their mappings in key order. The class TreeMap implements SortedMap interface.
The table below gives the list of Collection interfaces and the classes that implement them.
Interface Class Implementation
Set HashSet
SortedSet TreeSet
List ArrayList, Vector, LinkedList
Map HashMap, Hashtable
SortedMap TreeMap

TUTORIAL 5 - Threads

Threads


Threads
A thread is in process in execution within a program. Within a program each thread defines a separate path of execution.
Creation of a thread
A thread can be created in two ways a) By implementing the Runnable interface. The Runnable interface consists of only one method - the run method. The run method has a prototype of public void run(); b) By extending the class Thread.
Execution of a thread
To execute a thread, the thread is first created and then the start() method is invoked on the thread. Eventually the thread would execute and the run method would be invoked. The example below illustrates the two methods of thread creation. You should note that the run method should not be invoked directly.

public class ThreadExample extends Thread {
   public void run() {
      System.out.println("Thread started");
   }
   public static void main(String args[]) {
      ThreadExample t = new ThreadExample();
      t.start();
   }
}
Example - Creation of Thread by extending the 
Thread class.


When the run method ends, the thread is supposed to "die". The next example shows the creation of thread by implementing the Runnable interface.

public class ThreadExample2 implements Runnable {
   public void run() {
   .../* Code which gets executed when 
         thread gets executed. */
   }
   public static void main(String args[]) {
      ThreadExample2 Tt = new ThreadExample2();
      Thread t = new Thread(Tt);
      t.start();
   }
}

Example - Creating thread by implementing Runnable

States of thread
A thread can be in one of the following states - ready, waiting for some action, running, and dead. These states are explained below. Running State A thread is said to be in running state when it is being executed. This thread has access to CPU. Ready State A thread in this state is ready for execution, but is not being currently executed. Once a thread in the ready state gets access to the CPU, it gets converted to running state. Dead State A thread reaches "dead" state when the run method has finished execution. This thread cannot be executed now. Waiting State In this state the thread is waiting for some action to happen. Once that action happens, the thread gets into the ready state. A waiting thread can be in one of the following states - sleeping, suspended, blocked, waiting for monitor. These are explained below.
Yielding to other processes
A CPU intensive operation being executed may not allow other threads to be executed for a "large" period of time. To prevent this it can allow other threads to execute by invoking the yield() method. The thread on which yield() is invoked would move from running state to ready state.
Sleep state of a thread
A thread being executed can invoke the sleep() method to cease executing, and free up the CPU. This thread would go to the "sleep" state for the specified amount of time, after which it would move to the "ready" state. The sleep method has the following prototypes.

public static void sleep (long millisec) 
            throws InterruptedException;
public static void sleep (long millisec, int nanosec) 
            throws InterruptedException;

Synchronized state
A code within the synchronized block is "atomic". This means only one thread can execute that block of code for a given object at a time. If a thread has started executing this block of code for an object, no other thread can execute this block of the code (or any other block of synchronized code) for the same object.

public synchronized void synchExample() {
   /* A set of synchronized statements. Assume 
      here that x is a data member of this class. */
   if(x == 0)
      x = 1;
}


TUTORIAL 4 - File Handling

File Handling

File Handling and Input/Output

java.io package
Classes related to input and output are present in the JavaTM language package java.io . Java technology uses "streams" as a general mechanism of handling data. Input streams act as a source of data. Output streams act as a destination of data.

File class
The file class is used to store the path and name of a directory or file. The file object can be used to create, rename, or delete the file or directory it represents. The File class has the following constructors -
File(String pathname); // pathname could be file or a directory name
File(String dirPathname, String filename);
File(File directory, String filename);
<!--more-->
The File class provides the getName() method which returns the name of the file excluding the directory name.
String getName();

Byte Streams
The package java.io provides two set of class hierarchies - one for handling reading and writing of bytes, and another for handling reading and writing of characters. The abstract classes InputStream and OutputStream are the root of inheritance hierarchies handling reading and writing of bytes respectively.



read and write methods
InputStream class defines the following methods for reading bytes -
int read() throws IOException
int read(byte b[]) throws IOException
int read(byte b[], int offset, int length) throws IOException
Subclasses of InputStream implement the above mentioned methods.




OutputStream class defines the following methods for writing bytes -
void write(int b) throws IOException
void write(byte b[]) throws IOException
void write(byte b[], int offset, int length) throws IOException
Subclasses of OutputStream implement the above mentioned methods.




The example below illustrates code to read a character.
//First create an object of type FileInputStream type using the name of the file.
FileInputStream inp = new FileInputStream("filename.ext");
//Create an object of type DataInputStream using inp.
DataInputStream dataInp = new DataInputStream(inp);
int i = dataInp.readInt();

Reader and Writer classes
Similar to the InputStream and OutputStream class hierarchies for reading and writing bytes, Java technology provides class hierarchies rooted at Reader and Writer classes for reading and writing characters.

A character encoding is a scheme for internal representation of characters. Java programs use 16 bit Unicode character encoding to represent characters internally. Other platforms may use a different character set (for example ASCII) to represent characters. The reader classes support conversions of Unicode characters to internal character shortage. Every platform has a default character encoding. Besides using default encoding, Reader and Writer classes can also specify which encoding scheme to use.
The Reader class hierarchy is illustrated below.
The Writer class hierarchy is illustrated below.

The table below gives a brief overview of key Reader classes.
CharArrayReader The class supports reading of characters from a character array.
InputStreamReader The class supports reading of characters from a byte input stream. A character encoding may also be specified.
FileReader The class supports reading of characters from a file using default character encoding.

The table below gives a brief overview of key Writer classes.
CharArrayWriter The class supports writing of characters from a character array.
OutputStreamReader The class supports writing of characters from a byte output stream. A character encoding may also be specified.
FileWriter The class supports writing of characters from a file using default character encoding.

The example below illustrates reading of characters using the FileReader class.
//Create a FileReader class from the file name.
FileReader fr = new FileReader("filename.txt");
int i = fr.read(); //Read a character

TUTORIAL 3 - Declaration and Access Control

Declaration and Access Control

Array Fundamentals
Arrays are used to represent fixed number of elements of the same type. The following are legal syntax for declaring one-dimensional arrays.

int anArray[];
int[] anArray;
int []anArray;

It is important to note that the size of the array is not included in the declaration. Memory is allocated for an array using the new operator as shown below.
anArray = new int[10];
The declaration and memory allocation may be combined together as shown below.
int anArray[] = new int[10];
The elements of the array are implicitly initialized to default values based on array types (0 for integral types, null for objects etc.). This is true for both local arrays as well as arrays which are data members. In this respect arrays are different from normal variables. Variable defined inside a method are not implicitly initialized, where as array elements are implicitly initialized.

Array Initializations
Arrays are initialized using the syntax below
int intArray[] = {1,2,3,4};
The length operator can be used to access the number of elements in an array (for example - intArray.length).

Multidimensional Arrays
The following are legal examples of declaration of a two dimensional array.
int[] arr[];
int[][] arr;
int arr[][];
int []arr[];

When creating multi-dimensional arrays the initial index must be created before a later index. The following examples are legal.

int arr[][] = new int[5][5];
int arr[][] = new int[5][];

The following example will not compile;
int arr[][] = new int[][5];

Class Fundamentals
A class defines a new type and contains methods and variables. The example below illustrates a simple class.


class City {
String name; // member variable
String getName() // member method
{
return name;
}
public static void main(String arg[]) {
}
}

Method overloading
JavaTM technology allows two methods to have the same name as long as they have different signatures. The signature of a method consists of name of the method, and count and type of arguments of the method. Thus as long as the argument types of two methods are different, they may be over-loaded (have the same name).

Class constructors
Constructors are member methods that have same name as the class name. The constructor is invoked using the new operator when a class is created. If a class does not have any constructors then Java language compiler provides an implicit default constructor. The implicit default constructor does not have any arguments and is of the type -
class_name() { }

If a class defines one or more constructors, an implicit constructor is not provided. The example below gives a compilation error.


class Test {
int temp;
Test(int x) {
temp = x;
}
public static void main() {
Test t = new Test(); /* This would generate a
compilation error, as there is no constructor
without any arguments. */
}
}

TUTORIAL 2 - Operators and Assignments

 

 

Operators and Assignments

Operators and Assignments

Commonly used operators
Following are some of the commonly used JavaTM technology operators - Multiplication (*), Addition (+), Subtraction (-), logical and (&&) Conditional Operator ?:, Assignment (=), left shift (<<), right shift (>> and >>>), Equality comparison (==), Non-equality comparison (!=).

Conversion rules in Assignments
In the description below, I am giving basic conversion rules for assignment when source and destination are of different types.

If source and destination are of the same type, assignment happens without any issues.
If source is of smaller size than destination but source and destination are of compatible types, then no casting is required. Implicit widening takes place in this case. An example is assigning an int to a long.
If source and destination are of compatible types, but source is of larger size than destination, explicit casting is required. In this case, if no casting is provided then the program does not compile.

Floating point numbers
Decimal numbers (for example 1.3) are of type double by default. To make them of type float they must be followed by F (say, 1.3F).

The equality operator
The equality operator (==) when applied to objects return true if two objects have same reference value, false otherwise. The example below illustrates this --


String str1 = "first string";
String str2 = new String("first string");
String str3 = "first string";
boolean test1 = (str1 == str2);
boolean test2 = (str1 == str3);

In the example above, test1 is set to false because str1 and str2 point to different references. As str1 and str3 point to the same reference, test2 gets set to true. When a string is initialized without using the new operator, and with an existing string, then the new string also points to the first string's location. So in the example above, str1 and str3 point to the same pool of memory and hence test2 gets set to true. The string str2 on the other hand is created using the new operator and hence points to a different block of memory. Hence test1 gets set to false.

The conditional operators && and ||
Operator && returns true if both operands are true, false otherwise. Operator || returns false if both operands are false, true otherwise. The important thing to note about these operators is that they are short-circuited. This means that the left operand is evaluated before the right operator. If the result of the operation can be evaluated after computing the left operand, then the right side is not computed. In this respect these operators are different from their bit-wise counterparts - bit-wise and (&), and bit-wise or (|). The bit-wise operators are not short-circuited. This means both the operands of bit-wise operator are always evaluated independent of result of evaluations.

Storing integral types
All the integer types in Java technology are internally stored in two's complement. In two's complement, positive numbers have their corresponding binary representation. Two's complement representation of negative numbers is generated using the following three step process -

First get the binary representation of the number.
Then interchange zeros and ones in the binary representation.
Finally add one to the result. So for example two's complement of -18 would be (assuming one byte representation) -
Converting 18 to binary -- 0001 0010
Interchanging 0s and 1s -- 1110 1101
Adding 1 -- 1110 1110

So 1110 1110 would be binary representation of -18 using two bytes and using two's complement representation.

The shift operators
The shift left operator in Java technology is "<<". There are two operators for doing the right shift - signed right shift (>>) and zero fill right shift (>>>).

The left shift operator fills the right bits by zero. The effect of each left shift is multiplying the number by two. The example below illustrates this -

int i = 13; // i is 00000000 00000000 00000000 0000 1101
i = i << 2; // i is 00000000 00000000 00000000 0011 0100 After this left shift, i becomes 52 which is same as multiplying i by 4 Zero fill shift right is represented by the symbol >>>. This operator fills the leftmost bits by zeros. So the result of applying the operator >>> is always positive. (In two's complement representation the leftmost bit is the sign bit. If sign bit is zero, the number is positive, negative otherwise.) The example below illustrates applying the operator >>> on a number.

int b = 13; // 00000000 00000000 00000000 0000 1101
b = b >>> 2; // b is now 00000000 00000000 00000000 0000 0011

So the result of doing a zero fill right shift by 2 on 13 is 3. The next example explains the effect of applying the operator >>> on a negative number.

int b = -11; //11111111 11111111 11111111 1111 0101
b = b >>> 2; // b now becomes 00111111 11111111 11111111 1111 1101

So the result of applying zero fill right shift operator with operand two on -11 is 1073741821.

Signed right shift operator (>>) fills the left most bit by the sign bit. The result of applying the signed shift bit has the same sign as the left operand. For positive numbers the signed right shift operator and the zero fill right shift operator both give the same results. For negative numbers, their results are different. The example below illustrates the signed right shift.

int b = -11; // 11111111 11111111 11111111 1111 0101
b = b >> 2; // 11111111 11111111 11111111 1111 1101 (2's complement of -3)
// Here the sign bit 1 gets filled in the two most significant bits.

The new value of b becomes -3.

TUTORIAL 1 - LANGUAGE FUNDAMENTALS

Language Fundamentals


  1. Identifiers are names of variables, functions, classes etc. The name used as an identifier must follow the following rules in JavaTM technology.
    • Each character is either a digit, letter, underscore(_) or currency symbol ($,¢, £ or ¥)
    • First character cannot be a digit.
    • The identifier name must not be a reserved word.
  2. A keyword or reserved word in Java technology has special meaning and cannot be used as a user defined identifier. The list of keywords in Java technology is given below. It is important to completely remember this list as you can expect a question in Java Certification exam related to this.
    abstractbooleanbreakbytecasecatch
    charclassconstcontinuedefaultdo
    doubleelseextendsfinalfinallyfloat
    forgotoifimplementsimportinstanceof
    intinterfacelongnativenewnull
    packageprivateprotectedpublicreturnshort
    staticstrictfpsuperswitchsynchronizedthis
    throwthrowstransienttryvoidvolatile
    whileassertenum



    It is important to note the following
    1. const and goto are not currently in use.
    2. null, true, and false are reserved literals but can be considered as reserved words for the purpose of exam.
    3. It is important to understand that Java language is case-sensitive. So even though super is a keyword, Super is not.
    4. All the Java technology keywords are in lower case.
    5. strictfp is a new keyword added in Java 1.2. assert is added in Java 1.4 and enum in Java 5.0
    6. The list of keywords as defined by Sun is present here.
  3. A literal in Java technology denotes a constant value. So for example 0 is an integer literal, and 'c' is a character literal. The reserved literals true and false are used to represent boolean literals. "This is a string" is a string literal.
  4. Integer literals can also be specified as octal (base 8), or hexadecimal (base 16). Octal and hexadecimal have 0 and 0x prefix respectively. So 03 and 0x3 are representation of integer three in octal and hexa-decimal respectively.
  5. Java technology supports three type of comments
    1. A single line comment starting with //
    2. A multi-line comment enclosed between /* and */
    3. A documentation or javadoc comment is enclosed between /** and */. These comments can be used to generate HTML documents using the javadoc utility, which is part of Java language.
  6. Java technology supports the following primitive types - boolean (for representing true or false), a character type called char, four integer types (byte, short, int and long) and two floating point types (float and double). The details of these types are given below -
    Data types Width (in bytes) Minimum value Maximum Value
    byte 1 -27 27 - 1
    short 2 -215 215-1
    int 4 -231 231 - 1
    long 8 -263 263 - 1
    char 2 0x0 0xffff
    float 4 1.401298e-45 3.402823e+38
    double 8 4.940656e-324 1.797693e+308

  7. Corresponding to all the primitive type there is a wrapper class defined. These classes provide useful methods for manipulating primitive data values and objects.
    Data types Wrapper class
    int Integer
    short Short
    long Long
    byte Byte
    char Character
    float Float
    double Double

  8. Instance variables (data members of a class) and static variables are initialized to default values. Local variables (i.e. variables defined in blocks or inside member functions) are not initialized to default values. Local variables must be explicitly initialized before they are used. If local variables are used before initialization, compilation error gets generated. The defaults for static and instance variables are given in the table below.
    Data types Default Values
    boolean false
    char '\u0000'
    Integer types (byte, short, int, long) 0
    Floating types (float, double) 0.0F or 0.0 D
    Object References null


    
        public static void main(String args[]) {
            int i;
            System.out.println(i);   
        }
    
    
    In this example printing of i generates a compilation error because local variable i is used before being initialized. The initialization of instance and static variables is an important concept both for understanding of Java language, and for Java Certification exam.
  9. A Java source file has the following elements in this specific order.
    • An optional package statement. All classes and interfaces defined in the file belong to this package. If the package statement is not specified, the classes defined in the file belong to a default package. An example of a package statement is -
      package testpackage;
    • Zero or more import statements. The import statement makes any classes defined in the specified package directly available. For example if a Java source file has a statement importing the class "java.class.Button", then a class in the file may use Button class directly without providing the names of the package which defines the Button class. Some examples of import statement are -
      import java.awt.*; // All classes in the awt package are imported.
      import java.applet.Applet;
    • Any number of class and interface definitions may follow the optional package and import statements.
    If a file has all three of the above constructs, they must come in the specific order of package statement, one or more import statements, followed by any number of class or interface definitions. Also all the above three constructs are optional. So an empty file is a legal Java file.
  10. The Java interpreter executes a method called main, defined in the class specified in command line arguments. The main method is the entry point for execution of a class. In Java technology the main method must have the following signature -
    public static void main(String args[])
    The java interpreter is invoked with the name of the class as an argument. The class name is followed by possible set of arguments for the main function of the class. When a Java program is invoked then the Java interpreter name "java" and the class name are not passed to the main() method of the class. The rest of the command line arguments are passed as an array of String. For example invoking java Sky blue gray
    would invoke main method of Sky class with an array of two elements - blue and gray.

13 May 2012

JAVA




A high-level programming language developed by Sun Microsystems. Java was originally called OAK, and was designed for handheld devices and set-top boxes. Oak was unsuccessful so in 1995 Sun changed the name to Java and modified the language to take advantage of the burgeoning World Wide Web. Java is an object-oriented language similar to C++, but simplified to eliminate language features that cause common programming errors. Java source code files (files with a .java extension) are compiled into a format called bytecode (files with a .class extension), which can then be executed by a Java interpreter. Compiled Java code can run on most computers because Java interpreters and runtime environments, known as Java Virtual Machines (VMs), exist for most operating systems, including UNIX, the Macintosh OS, and Windows. Bytecode can also be converted directly into machine language instructions by a just-in-time compiler (JIT). Java is a general purpose programming language with a number of features that make the language well suited for use on the World Wide Web. Small Java applications are called Java applets and can be downloaded from a Web server and run on your computer by a Java-compatible Web browser, such as Netscape Navigator or Microsoft Internet Explorer.