Fundamental Object-Oriented Concepts
In Java, a narrowing conversion is also known as an explicit type conversion or casting.
A byte can represent values between -128 to 127.
An array, in Java, is an ordered collection of primitives, object references, or other arrays. All the elements of an array must be of the same type, except in case of polymorphism.
Array elements are initialized to default values, wherever they are created.
The increment operator can be used in either of the two forms given below:
- Prefix form: In the prefix form, it appears before the operand. For example, ++a;
- Postfix form: In the postfix form, it appears after the operand. For example, a ++;
Numeric promotions are used to convert the operands in a numeric expression to a common type before an operation is performed between the operands.
In Java, there are two kinds of numeric promotions as follows:
- Unary numeric promotion
- Binary numeric promotion
Pass SCJA Certification Java 1.2 in a first attempt:
When the destination data type is narrower than the source data type, an explicit type conversion is required.
An enumeration is a feature added to J2SE 5. It is very similar to a class, except that it cannot be instantiated. It is declared using the keyword enum. An enumeration can have constructors, methods, and instance variables in the same way as a class. Identifiers of an enum are referred to as enum constants.
An enum constructor can never be invoked directly. They are always called automatically on initialization. An enum can be declared inside, as well as outside a class.
The ordinal() method is defined in the java.lang package. It is a method of the Enum class. This method is used to get the index of enum constants. It is a final method.
The compareTo() method cannot compare two different types of enum variables. It can compare variables of the same enum type.
A variable declared as an enum constant is final.
Inheritance defines an is-a relationship between a superclass and its subclasses.
A Java class can compile successfully even without the main() method. However, it requires the main() method for its execution.
A class can implement more than one interface and each interface must be separated by a comma.
An abstract class consists of one or more abstract methods that are declared but left unimplemented. It is the responsibility of subclasses that extend an abstract class to implement the unimplemented part of the abstract class.
A constructor is used to create an object that is an instance of a class. It has the same name as the class in which it resides. A constructor for a class is declared in the same way as a method is declared, but it is declared without a return type. A constructor can be marked with one of the following keywords: public, private, or protected.
In Java, final is a keyword. It has the following impact on variables, methods, and classes:
- If a variable declaration is preceded by the final keyword, its value cannot be changed in the program.
- If in a method declaration, the method name is preceded by the final keyword, that method cannot be overridden.
- If in a class declaration, the class name is preceded by the final keyword, that class cannot be inherited.
Variables that have only one copy per class are known as static variables. They are not attached to a particular instance of a class but rather belong to a class as a whole.
Method overriding occurs only when two method names and the parameters passed to them are the same.
An abstract method is a method that is not defined in the class in which it is declared. Instead, the method definition is deferred to one or more subclasses. An abstract method only has a semicolon after the method name and parenthetical argument list.
The final and abstract class modifiers are not used in combination.
A method declared within an interface is declared as public. It cannot be declared with any other access specifier such as private, or protected.
All variables in an interface are static and final.
Multiplicity refers to cardinality in UML diagrams. It represents the number of objects in one class related to the number of objects in another class.
Generalization defines a is-a-kind of relationship in which one class shares its structure and/or behavior with one or more other classes. The concept of generalization in UML is similar to inheritance in Java.
Association navigation represents the direction in which a relationship can be traversed. It can be either unidirectional, i.e., in one direction, or bi-directional, i.e., in both directions.
The setter method of a Javabean must be declared public, with a void return type and an argument that represents the property type. The getter method of a JavaBean must be declared public. It takes no arguments, and should have a return type that matches the argument type of the setter method for that property.
The naming convention for setter methods is that they should be prefixed with set and the name of the variable. The name of the variable should begin with an upper case. The naming convention for getter methods is similar to that of setter. It should begin with get and the name of the variable. The name of the variable should begin with an upper case.
A class variable or class method declared as private, can only be accessed by other members of its class.
When an overloaded method is invoked, Java uses the type and/or number of arguments to determine, which version of the overloaded method will be called.
When an overloaded method is invoked, java examines the number or type of parameters passed to the method and matches it with actual arguments to decide which method is to be called.
In Java, runtime polymorphism or dynamic method dispatch is a process in which a call to an overridden method is resolved at runtime rather than at compile-time. In this process, an overridden method is called through the reference variable of a superclass.
UML Representation of Object-Oriented Concepts
By using the inheritance, a generic class can be created that can then be inherited by other more specific classes. In Java terminology, a class that is inherited is called a superclass, and the class that inherits another class is called a subclass. A subclass inherits all the instance variables (attributes) and methods (operations) defined in the superclass.
In UML, the public access specifier is represented by , private by -, and
protected by #.
A unidirectional association implies that the object of the class from which the arrow generates can invoke its methods in the class towards which the arrow points.
Aggregation represents a stronger relation between two entities than does an association.
Composition represents a whole-part relationship like aggregation. It implies that the parts cannot exist without whole.
Composition is similar to aggregation, but represents a stronger relationship than aggregation.
Java Implementation of Object-Oriented Concepts
Numeric values having no decimal parts are called integer literals. These values can be expressed in decimal, octal, and hexadecimal forms. By default, integer literals are in decimal form.
A semicolon in the enum declaration is optional and may be put at the end of enum declaration.
An identifier must begin with a letter, a dollar sign ($), or an underscore (_). Subsequent characters may be letters, dollar signs, digits, or underscore. Identifiers are case sensitive.
Decimal form contains a sequence of decimal digits (0 to 9), the octal form contains a sequence of octal digits (0 to 7) prefixed by 0 (zero).
In Java, an object is created using the new operator. This object creation is a two-step process as follows:
- First of all, a variable of the class is declared. This variable simply refers to an object.
- In the next step, the actual physical copy of the object is created and assigned to that variable.
An enumerated type cannot be declared local to a method.
Class variables and instance variables are initialized with a null value, whereas variables declared inside code blocks are not automatically initialized.
The keywords native and synchronized cannot be used as class modifiers.
An abstract class cannot be final.
An inner class is defined within the scope of an outer class. An inner class can directly access the members of an outer class but the members of the inner class are known only within the scope of the inner class and may not be used by the outer class.
A constructor cannot have a return type, not even void.
Private members of a class cannot be accessed from outside of the class in which it is declared private, otherwise a compile-time error will occur.
Whenever a subclass and its superclass have identical method names and parameters, the subclass version of the method is called, and the superclass version remains hidden. To call the superclass version of the method, the super keyword with a dot operator is placed before the method name.
A compile-time error will be generated if one tries to inherit a class declared as final.
An abstract class can be extended but it cannot be instantiated, i.e., an object of that class cannot be created.
A class containing one or more abstract methods must be declared as abstract. However, a class can also be declared as abstract even if it has no abstract methods. An abstract class may also have non-abstract methods.
A variable or method declared in an interface cannot be private.
A subclass reference variable can be assigned to a superclass reference variable. However, vice-versa is not true.
An interface reference variable has knowledge of the methods declared within its interface declaration.
A static variable or method, when accessed outside its class, can be used independently of any object. Either of these can be accessed with its classname and dot operator.
Every method in an interface is abstract, whether explicitly declared as such or not.
The return type and the parameter type of the method declared in an interface must respectively match the return type and the parameter type in the implementing class. Otherwise, it will not compile.
A method cannot be declared more restrictive than it is in its superclass.
An interface cannot be instantiated. However, a reference variable of an interface can be created. An interface reference variable can only refer to the object of the class that implements that interface.
In Java, trying to access elements outside the boundary of an array will cause a runtime error.
The compiler checks the number or type of parameter to determine the method that is to be invoked in case of method overloading.
Pass SCJA Certification Java 1.2 in a first attempt:
Algorithm Design and Implementation
An assignment statement is an expression statement. The statement ends with a semicolon.
for(initialization; condition; iteration)
{
//body of the loop
}
All the three components, i.e., initialization, condition, and iteration are optional.
A class member declared as static can be accessed before any object of its class is created.
A static class variable, whose value is not explicitly initialized, is always implicitly initialized to a default value.
Variables declared within blocks (i.e., inside braces) are known as local variables. They are so called because they are not available for use outside the block where they are declared.
A local variable of any data type is not implicitly initialized. If an attempt is made to access an uninitialized local variable, the code will generate a compile-time error.
There is no access specifier required for local variables, as their scope is limited to the method in which they are declared. They are unknown in other parts of the code.
Runtime system creates a separate copy of each instance variable defined by the class. Therefore, each instance of a class has its own copy of all instance variables defined by the class.
The following lists of variables is in ascending order of scope (least to the highest) in a Java application: block, local, instance, and static
A local variable is declared without any access specifier, i.e., default. Declaring it as public, private, or protected will result in compile-time error. A local variable can be declared as final.
The do-while control statement is executed at least once, as the while conditional expression is at the bottom. In each iteration, the do-while loop first executes the body of the do loop and then checks the while condition. If the condition is true, the loop repeats, else, it terminates.
The for loop executes in the following three steps: When the loop first starts, the initialization expression is executed and then the control is transferred to step 2.The condition is evaluated. If the condition evaluates to true, the body of the loop executes and the program control is transferred to step 3. If the condition evaluates to false, the loop terminates. The iteration expression executes and then the control is transferred to step 2.
The break statement is used inside the switch statement to terminate a statement sequence. When a break statement is encountered, the execution branches to the first line of code that follows the entire switch statement block.
The following points must be noted about the if statement: The argument to the if statement must be a Boolean expression. If the argument evaluates to true, the statements in the if-block are executed.
If the argument evaluates to false, the statements in the else-block are executed. If the number of statements after the if clause is more than one, it is necessary to put them inside the curly braces. However, in case of a single statement, the curly braces are optional.
Each case value must be a unique literal value. Variables are not allowed as case values.
All arrays in Java have a public final field known as length. This field is used to find the number of elements that the array holds.
The if-else statement is a conditional statement. It is used to execute a statement or group of statements based on some condition. The general format of the statement is given below:
if(boolean_expression)
{statements;}
else
{statements;}
In call-by-reference method call, a reference to an argument (not the value of the argument) is passed to the parameter.
In the call by value process, when a method call is executed, the actual value of an argument is passed to the formal parameter of the method. The method receives a copy of the value, and modifies it in accordance with the operation performed within the body of the method, without affecting the original value of the parameter passed.
When an object reference value is passed to a formal parameter, the changes made to the object via the formal parameter is reflected back in the calling method when the call returns.
If in a class declaration, the class name is preceded by the final keyword, then that class cannot be inherited.
The replace() method of the StringBuffer class replaces one set of characters with another set inside a StringBuffer object.
The XOR operator manipulates bits in such a way that if one of the corresponding bits in two input operands is 1, the result is 1. Otherwise, the result is 0.
Boolean logical operators operate on Boolean operands. They combine two boolean values and return a Boolean value as a result.
The == operator is generally used to check the equality of primitive type values. It evaluates to true if the two values are the same. Otherwise, it evaluates to false. The == comparison operator may also be used to determine whether two object references refer to the same object. It evaluates to true if the two reference variables refer to the same object. Otherwise, it evaluates to false.
An arithmetic assignment operator combines two separate operations, namely calculation and assignment. For example, x=x +a; can be rewritten as x+ =a;
The not equal to operator is a Boolean logical operator. It is denoted by the != symbol. It compares two expressions and returns true if the expression on the left hand side is not equal to the expression on the right hand side, otherwise it returns false.
The modulo operator (%) is used to get the remainder after the division has been completed. It can be used with integers and floating-point numbers.
The operator concatenates two strings, producing a new String object as the result.
The charAt() method of the String class is used to extract a single character from a given string.
In Java, the StringBuffer class is similar to the String class. It provides the following three constructors:
- StringBuffer()
- StringBuffer(int size)
- StringBuffer(String str)
The indexOf() method of the String class is used to search the first occurrence of a character or a substring from a given string.
The setLength() method of the StringBuffer class sets the length of the buffer within the StringBuffer object.
The startsWith() method of the String class checks whether a given string starts with a specified string or not. It returns boolean true if the string matches, otherwise returns false.
The substring method extracts a substring from a given string. It has the following two forms as follows:
- substring(int startIndex)
- substring(int startIndex, int endIndex)
LinkedList is a class that extends the AbstractSequentialList class and implements the List and Queue interfaces. LinkedList is a generic class.
Java Development Fundamentals
A package is a group of classes and interfaces. It is used to manage a large group of related classes and interfaces. Potential naming conflicts are avoided by using a package, i.e., same identifier names can be used in different classes of the same package. A package can be nested within other packages.
The public access specifier allows a class to be extended by all the subclasses in the same package as well as in other packages.
A method declared as default cannot be accessed through a non-subclass in a different package. The method must be declared as public to be called from a non-subclass outside the package.
Default visibility allows a variable to be accessed by all the sub classes in the same package but it cannot be accessed by subclasses in other packages.
It sets the directory in which class files should be stored. The java compiler, javac, by default stores the .class files in the same directory as the .java files. However, if the -d option is set, the specified directory is treated as the root of the class hierarchy and .class files are placed in this directory or in the appropriate subdirectory below it.
The java.awt package contains classes to implement user interfaces and for painting graphics and images in applications.
The setBackground() method is defined by the Component class. It is used to set the background of an applet’s window to a specified color.
The java.lang.ref subpackage was added in the java.lang package since Java internal version 1.2. It contains reference-object classes, which provide flexible control over the garbage collection process. The java.lang.reflect subpackage contains classes, which provides reflective information about the fields, constructors, methods, and modifiers of a class.
The Java compiler implicitly calls the java.lang package. There is no need to explicitly import this package in a Java program.
Java Platforms and Integration Technologies
RMI is a distributed environment technology. It provides object-to-object communication between different Java Virtual Machines (JVMs).
The RMI architecture specifies three layers, namely the stub and skeleton layer, the remote reference layer, and the transport layer.
The remote reference layer interprets and manages references made by clients to remote service objects.
JDBC stands for Java Database Connectivity. It is used to connect a database to a Java application.
A connection is closed automatically when it is garbage collected. It is recommended that programmers explicitly close the connection to conserve resources.
The Connection interface in JDBC provides methods to handle transaction processing, to create objects for executing SQL statements, and to create objects for executing stored procedures. Apart from these, it also provides some basic error handling methods.
The executeQuery() method of the PreparedStatement interface, under JDBC, is used to execute SQL statements and stored procedures that return a result set.
COMMIT is a transaction control command that informs a database to clear a transaction log and save the changes permanently in the database since the last ROLLBACK or COMMIT.
A user must load a driver that enables the JDBC classes to communicate with a data source. The standard method to load a driver is as follows: Class.forName(DriverClassName)
The java.sql package provides API (Application Programming Interface) for accessing and processing data stored in a data source using Java.
In the two-tier model, a Java application interacts directly with the data source. In this model, a JDBC driver is required, which can communicate with the particular data source being accessed.
A batch update is a process of combining multiple UPDATE, DELETE, or INSERT statements into a single batch and having the whole batch sent to the database and processed in one round.
The DriverManager, which is the management layer of JDBC, works between a user and a database driver. It keeps track of all the drivers that are available and handles establishing a connection between a database and the appropriate driver.
JMS, which stands for Java Message Service also referred to as Messaging Oriented Middleware (MOM), defines standards for reliable enterprise messaging.
JMS clients are Java applications that make use of JMS, and the JMS provider is the name given to the messaging system that handles the sending and receiving of messages. There are two messaging models of JMS as follows:
- Publish-and-subscribe
- Point-to-point
The JMS client that sends a message is known as a producer, and the JMS client that receives the message is known as a consumer.
Client Technologies
JavaScript can be used to create image rollovers and validating forms. It can also be used to open a new browser window.
JNDI stands for Java Naming and Directory Interface. It is an API that allows Java programs to interact with any naming and directory service that implements JNDI.
The two major disadvantages of JavaScript are:
- It lacks support for graphical user interface, i.e., it cannot be used to draw images and other graphical components.
- It is less secure. It runs on the user’s Web browser. The HTML source code of a Web page can be viewed in a Web browser.
J2ME is aimed at developing applications that can run on consumer devices such as cellular phones, PDAs, etc. It has two elements, namely configurations and profiles.
The AMS (Application Management Software) available on the mobile device is responsible for the download, installation, and management of the life cycle of a MIDlet. It checks the MIDlet suite for authenticity before installing it.
A MIDlet suite contains one or more MIDlets. It should have at least one class that extends the MIDlet class and implements all the life cycle methods of the MIDlet class, such as startApp(), pauseApp(), etc.
An applet cannot start other programs on the client.
An applet cannot access the java.home and user.home system properties.
Applets lack caching capability. This causes an applet to be downloaded each time when a user visits a site.
Swing is a set of classes in Java that provides a richer user-interface than AWT. It provides components that are more flexible and user-interactive than AWT components. It contains some additional components, which are not available in AWT such as tabbed panes, scroll panes, etc.
Server Technologies
Servlets are Web-based components that run in a Web container. They provide a platform-independent method for building Web-based applications.
JTA (Java Transaction API) is a set of APIs (Application Program Interface) that supports transactions. JTA API is used by applications to start, abort, and commit transactions.
The information provided by a deployment descriptor is declarative and therefore it can be modified without changing the source code of a bean.
All JSP pages are compiled into servlet code. This is done in two phases. In the first phase, JSP text is translated into Java code and in the second phase, Java code is compiled into a servlet.
A JavaBean is implemented in the presentation layer, whereas an EJB is implemented in the business tier.
The jspInit() method of the javax.servlet.jsp.JspPage interface is invoked by the container only once when a JSP page is initialized. It can be overridden by a page author to initialize resources such as database and network connections, and to allow a JSP page to read persistent configuration data.
An Enterprise JavaBeans(EJB) container is an environment for EJB components to run.
A stateful session bean can be accessed from multiple clients either directly or through some adapter, in contrast to other approaches such as URL rewriting, HttpSession attributes, which are limited to HTTP clients.
A session bean is a type of EJB (Enterprise JavaBean) that encapsulates the logic of a business process and business rules. There are two types of session beans, as classified on the basis of state mode, namely stateless session bean and stateful session bean.
An entity bean represents an entity such as an employer, student, etc. An entity bean is grammatically a noun. An instance of an entity bean holds a record in memory about a corresponding entity from a table in a database.
A stateful session bean is well suited for implementing a business task dedicated to a single client that maintains a conversational state between the bean and the client.
A Web container manages the execution of JSP pages and servlet Web components. Web components respond to HTTP requests. J2EE Web components are either JSP pages or servlets. Web components and their container run on the J2EE server.
The servlet API of the J2EE platform is part of the Web-tier. It runs on the J2EE server.
Client technology can be classified as an application client and a Web client. An application client is an application written in Java, which can directly communicate with a software component in the EJB tier or with a component in a Web tier through HTTP.
Pass SCJA Certification Java 1.2 in a first attempt: