SCJA



Sun Education and 310-019 and SCJA and Article

Article: Java-Data types, Variables, and Arrays

uCertify has sent us this article which is useful for the SCJA certification exam. The article helps you to understand the Java types, variables and arrays, a topic for CX310-019 exam.

Java-Data types, Variables, and Arrays
Java is a robust language. One of the factors, which makes Java robust is the fact that it is a strongly typed language, i.e., every variable has a type, every expression has a type, and every type is defined.Java defines eight primitive data types. These are as follows:
  1. int
  2. byte
  3. long
  4. short
  5. float
  6. char
  7. boolean
  8. double

These can be grouped into four main categories as listed below:

  • Integers: This includes int, long, short , and byte.
  • Floating-point numbers: This includes float and double. These represent numbers with fractional precision.
  • Characters: The char type is included in this category.
  • Boolean: The boolean is a special type to represent true/false values.

The width and range of each type is given below:

Type Width Range
byte 8-bit -128 to 127
short 16-bit -32,768 to 32,767
int 32-bit -2,147,483,648 to -2,147,483,647
long 64-bit -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
float 32-bit 1.4e-045 to 3.4e+038
double 64-bit 4.9e-324 to 1.8e+308
char 16-bit ‘\u0000′ to ‘\uffff ‘


Type Conversion and Type Casting

Java provides two kinds of data type conversions automatic and explicit. Automatic conversion takes place when the following two conditions are fulfilled:

  • The two types are compatible.
  • The destination type is larger than the source type.

When these two conditions are met, widening conversion takes place, i.e., a narrow data type is promoted to a wider one. For example, value of byte type will be promoted to int, as int is wider than byte in width.

In many cases automatic type conversions are helpful, but they fail to fulfill all the requirements. For example, an automatic conversion cannot be performed to convert int to byte, as int is wider than byte. The general form to perform such type of narrowing conversion is as follows:

(target-type) value

The example below describes an explicit conversion:

class Rat {
public static void main(String args[]){
int a=10,b=20;
byte c;
c= (byte)(a+b);
System.out.print(c);
}

}

here, the value obtained after adding variables a and b of int type is stored in c, which is of byte type. Therefore, before storing the value casting is done:

c= (byte)(a+b);

Variable

A variable is said to be a storage unit in Java. A variable is defined as the combination of an identifier, a type, and an optional initializer. Every variable has a scope, which defines its visibility, and a lifetime.

Variable Declaration:

The general form for declaring a variable in Java, is as follows:

type identifier[=value];

In the line mentioned above, type defines the data type of a variable. It can be int, short, char, etc. The identifier refers to the name of the variable, and the value is any constant assigned to a variable. The variable declaration must end with a semicolon “;”. Java keywords such as final, try, etc. are not allowed as variable names. Some examples given below describe variable declaration in detail:

int a, b, c; // declaration of three variables a, b, and c of int type.

int a=3, b; // declaration of two variables a and b and initialization of a.

char x=’x'; // declares char type variable and assigns value. The char type value must be within single quotes.

Dynamic Initialization of Variables :

The example given below describes the dynamic initialization:

class Dynamic {
public static void main(String args[]) {
int a=10, b=30;
double c=a+b; //dynamic initialization of variable c
System.out.print(c);
}
}

In the example given above, the variable c is dynamically assigned the value obtained after the addition of values stored in variables ‘a’ and ‘b’.

The Scope and Lifetime of a Variable

In the example mentioned above, all the variables are declared within the main method. However, Java allows a variable declaration within any block. An opening and closing brace defines a block. This is a block:

{

//block

}

A block defines a scope. A scope determines the visibility and lifetime of an object, which is defined inside it.

The other programming languages such as C defines two categories of scopes: global and local. These two traditional categories do not gel well with Java’s strict object-oriented model. In Java, the two main scopes are those that are defined by a class and a method.

The scope defined by a method begins with an opening brace and finishes with a closing brace. The parameters of a method are also within that scope.

As a rule, the variables declared inside a scope are only visible to the code within that scope. These variables are not visible to the code outside the scope. Therefore, declaring a variable inside a scope localizes it and prevents it from unauthorized access or modification.

Nested scopes are allowed, i.e., a scope within a scope. For example, each time a programmer creates a block of code, he creates a new, nested scope. When this happens, the outer scope encloses the inner scope. This means that objects declared in the outer scope will be visible to the code within the inner scope but not vice-versa. Objects declared inside the inner scope will not be visible to the outer scope.

The example below describes the nested scope:

class Nested {
public static void main(String args[]) {
int x; //visible to all code within main()
x=100;
if (x==100) { //start of new scope
int y=20; // known only within this block
//x and y both known here
System.out.println(+x + ” ” +y);
}

y=200; // error, as y is not known here
System.out.print(x) // x is known here
}
}

here, the variable x is declared at the start of the main() method’s scope and is accessible to all the subsequent code within the main method. The variable y is declared within the if block and is accessible within this block. That is why a compile-time error will be generated if y is initialized to 200.

Note : A variable is created when its scope is entered, and gets destroyed when its scope ends. This means that a variable will not hold its value once it has gone out of scope.

Array

An array is a group of variables of the same data type referred to by a common name. Arrays of any data type can be created and may have one or more dimensions. A particular element in an array is accessed by its index.

One Dimensional Array

A one-dimensional array is a list of variables of the same data type. The general form for creating a one-dimensional array is:

type var-name[]; or type[] var-name;

here, type refers to the data type of an array, and var-name refers to the name of the array.

For example,

int arr[];

This declares an empty array named arr of int type. In Java, the size of an array is set when it is explicitly created using the new operator.

int arr[]= new int [5];

It will create an array named arr of size 5. It will store 5 elements, from 0 to 4. The starting index of an array is 0.

The diagram below depicts a conceptual view of the array declared above:

here, each box will contain one element.

The first element of the array is positioned at the 0th location, therefore, to get the value of the first element, the following code is used:

System.out.print(arr[0]);

Note: In Java, the elements of an array are always set to default values after their creation. An int type array is set to 0 and a boolean type array contains false by default if no value is stored in an array.

Multidimensional Arrays

In Java, a multidimensional array is known as an array of arrays. The general form for declaring a multidimensional array:

type var-name[][]; or type[][] var-name;

like a one dimensional array, the size of a two dimensional array is also explicitly created using the new operator. The example below describes this:

int a[][]=new a[3][2];

This will create an array, which contains 3 rows and 2 columns. It will contain 3*2, i.e., 6 elements. The first index is [0][0] and the last index is [2][1]

Array size

In Java, the length field specifies the size of an array.

The example below describes its use.

class Rat {
public static void main(String args[]) {
int a[]=new int[4];
System.out.print(a.length);

here, the output will be 4.

What is an ArrayIndexOutOfBoundsException?

In Java, a run-time error ArrayIndexOutOfBoundsException is encountered when a program attempts to extract a value from an array outside its boundary. For example,

  1. class Rat {
  2. public static void main(String args[]) {
  3. int a[]=new int[4];
  4. System.out.print(a[5]);

The above-mentioned code will generate an exception at runtime, as the code at line number 3 declares and creates an array of size 4. It will have index starting from 0 to 3 , but the code at line number 4 attempts to extract the value from the 5th location.

Visit uCertify Web site to read more free articles for other Java certification exams.

Oct 31 2007 04:27 am | No Comments »


Sun Education and 310-019 and SCJA and Article

JDBC: Free Article for SCJA Exam from uCertify

This free article for SCJA certification exam is provided by uCertify that will help you to prepare and excel in exam CX310-019. This exam measures your in-depth knowledge and skills in designing application using Java technology.

JDBC

The introduction of the Java language is required before introducing the concept of JDBC. Java is an object-oriented programming language. It incorporates all the objected-oriented concepts such as polymorphism, abstraction, encapsulation, etc. Java is a platform independent language because it can run on different operating systems. Java syntactically resembles C and C++, but it is simpler than the two, as it does not contain pointers and multiple inheritance. Both pointers and multiple inheritance seem complex to the application developer. Java has some drawbacks too. It does not provide much facility for developing GUI (graphical user interface) applications. The earlier version of Java did not contain any support for database access. This was the major drawback of this language, as in today’s world, keeping and managing databases is quite important. To remove this drawback, Sun Microsystems has introduced a new interface known as Java Database Connectivity (JDBC). JDBC provides database connectivity to Java applications.

JDBC Interface

JDBC stands for Java Database Connectivity. It provides database access to Java applications. The JDBC API interfaces are used to connect to the database and execute all types of SQL statements. The JDBC API interfaces can execute normal SQL statements, dynamic SQL statements, and stored procedures that take both IN and OUT parameters. The section below provides a description of various JDBC API interfaces.

Callable Statement Interface: This interface provides methods for executing stored procedures that return OUT parameter values. The CallableStatement object inherits the PreparedStatement object, adds various methods for registering parameters to be OUT parameters, and provides methods to get the parameters passed back from the stored procedure.

Connection Interface: This provides database connection to Java applications. It can be used to create various Statement objects for executing SQL statements and stored procedures. It also provides the facility to set the transaction properties for the connection.

Database MetaData: This interface provides various methods for obtaining the information about the database. It provides listing of tables for a specific database, primary keys, columns, and other information related to specific tables.

Driver Interface: This is a database specific Driver object, which the JDBC vendor provides. It contains information about connecting Java applications to the database. It also provides information about the database, such as version of the database, etc.

Prepared Statement Interface: This interface supports the execution of dynamic SQL statements and stored procedures. It allows setting various parameters in dynamic statements with specified data values.

Note: Dynamic statements are those statements whose values are not known at the time of creation.

Result Set Interface: This object is used to get information from a SQL SELECT statement. The SQL SELECT statement returns the cursor, which is used by the Result Set interface to search the results returned by the SELECT statement. It provides a set of methods for extracting information from different columns contained in the cursor.

Result Set Metadata: This interface provides information about a returned result set. It is created from a ResultSet object and provides information specific to that object. It provides the information about the number of columns in the result set such as names, and types of the column.

Statement Interface: This is created from the Connection object. It is used to execute standard SQL statements and stored procedures. It provides two main methods, executeQuery() and executeUpdate(). These methods support execution of SQL queries and SQL updates. The executeQuery() method returns a ResultSet object. JDBC API Objects Java provides various objects that can be used in Java applications. These objects provide Java with some of the database specific data types available in most databases.

The table below describes various JDBC API objects:

Object Detail
Date It provides an object that can accept database date values.
Driver Manager It provides another way to make a connection to the database.
Driver Property Info It is used to manage Driver objects.
Time It provides an object that can accept database time values.
Timestamp It is used to get the values from the database that are of timestamp data type.
Types It provides a list of predefined integer values that identify the various data types that can be used in JDBC.

 

JDBC Exceptions

Whenever an error occurs in Java, an exception is thrown. The JDBC API introduces three new exceptions. These exceptions are discussed as follows:

DataTruncation Exception: This exception is thrown when JDBC unintentionally truncates a data value. The exception provides methods to get information about the data value that was truncated and the truncation error as well.

SQLException Exception: This is thrown by almost all the methods in the JDBC API. It provides methods for getting information about the error and the present state of the SQL transaction.

SQLWarning Exception: This exception is generated when the database issues a warning. The warnings are silently sent to the object whose method caused it to be reported.

JDBC Vs CGI

Before the introduction of JDBC, the Java applications used to call and access CGI (Common Gateway Interface) programs through streams in Java. The CGI scripts in Java call a separate program that provides database access and returns results. The CGI approach is slow and allows bugs to get into the applications. In addition to this, one must know both the technologies - Java and CGI - to make applications, whereas to access the database through JDBC, one must be a master in Java only.

Another strong reason to use JDBC is that it provides faster access than the CGI approach. In CGI approach, another program is called that accesses the database, processes the data, and returns the result back to the calling program in a stream. This requires multiple levels of processing that increase wait time and also allow more bugs to creep into the applications. The figure below demonstrates the way CGI accesses the database. When a CGI script is called, a new script is executed through a Web server, whereas execution of a JDBC statement against the database requires only some sort of server that passes the SQL commands through to the database. This increases the speed of execution of SQL statements. The CGI script first connects to the database and processes the results, whereas the JDBC allows the connection of the database to Java applications so that it can perform all the processing.

The figure below demonstrates how a JDBC statement is executed:

Please visit http://www.ucertify.com to read more free articles for SCJA and other Java Certification such as SCWCD, SCMAD, etc.

Sep 27 2007 05:52 am | No Comments »


Sun Education and SCJA

Free 310-035 SCJP Mock Exam from Jchq.net

Try this mock test containing 60 questions for SCJP Exam 310-035 from Jchq.net Website. The questions in this mock test cover all the objectives of the actual exam. The mock test is based on the latest format for the SCJP exam and you will get instructions with each question about how many answer options you should select.
You have an option to view the correct answer option for each question along with the reference to which objective it belongs. Check out this free mock test for SCJP Exam at Jchq.net website.

Sep 11 2007 01:34 pm | No Comments »


Sun Education and 310-019 and SCJA and Sample Questions

Free Sample Questions for SCJA Exam CX-310-019

Ejavaguru.com is providing 10 free sample questions for Sun Certified Associate for the Java Platform (SCJA) Exam CX-310-019. The SCJA exam validates your skills in using different Java platforms J2SE, J2ME and J2EE. It also measures your knowledge in understanding the fundamentals of Object Oriented Concept and java programming skills.

The exam CX-310-091 helps you to achieve other advanced certifications such as SCJP, SCJD, SCWCD and SCBCD. The sample questions available at the website provide answers explanation after each question.

Click on CX-310-019 Exam link to view the sample questions.

Sep 11 2007 01:04 pm | No Comments »


Quiz and Sun Education and 310-019 and SCJA

Free 310-019 SCJA Practice Questions from Javabeat.net

The SCJA (Sun Certified Associate for the Java Platform, Standard Edition) exam 310-019 is an entry-level test that evaluates your knowledge in developing application and software projects using Java programming language and technologies. The exam 310-019 also validates your basic understanding of Object Oriented Concept.

Are you looking for practice questions for SCJA exam? Try these free practice questions offered by Javabeat.net. The test is divided into eight parts, each containing 5 questions. These questions cover all objectives of the actual exam such as UML Representation of Object-Oriented Concepts, Java Implementation of Object-Oriented Concepts, Algorithm Design and Implementation, Java Development Fundamentals etc.

The practice questions are available on the SCJA page at the Website . The correct answer is also provided for each question. Prepare for your SCJA exam 310-019 with these practice questions.

Sep 03 2007 09:44 am | No Comments »

Next Page »