ilovepdf_merged
ilovepdf_merged
History
Java language, originally called the ‘Oak’, was developed by James Gosling
at Sun Microsystems, which is now a subsidiary of Oracle Corporation, and
released in 1995 as a core component of Sun Microsystems' Java platform.
It has derived much of its syntax from C and C++ but has a simpler object
model and fewer low-level facilities.
Features of Java:
1. Simple, Object-oriented, and Familiar
Java can be programmed without extensive programmer
training while being attuned to current software practices.
The needs of distributed, client-server based systems coincide
with the encapsulated, message-passing paradigms of object-
based software.
It looks like C++ as far as possible results in it being a familiar
language, while removing the unnecessary complexities of C++.
2. Robust and Secure
It provides extensive compile-time checking, followed by a
second level of run-time checking
Java technology is designed to operate in distributed
environments, which means that security is of paramount
importance
3. Architecture Neutral and Portable
Java technology is designed to support applications that will be
deployed into heterogeneous network environments.
To accommodate the diversity of operating environments, the
Java compiler product generates bytecode – an architecture
neutral intermediate format designed to transport code
efficiently to multiple hardware and software platforms. The
interpreted nature of Java technology solves both the binary
distribution problem and the version problem; the same Java
programming bytecodes will run on any platform.
4. High Perforrnance
The automatic garbage collector runs as a low priority
background thread, ensuring a high probability that memory is
available when required, leading to better performance.
5. Interpreted, Threaded, and Dynamic
The Java interpreter can execute the bytecodes directly on any
machine to which the interpreter and run-time system have
been ported.
Java technology’s multi-threading capability provides the
means to build applications with many concurrent threads of
activity. Multi-threading thus results in a high degree of
interactivity with end users.
While Java compiler is strict in its compile-time static checking,
the language and run-time system are dynamic in their linking
stages.
Java Editions:
J2SE: Java 2 Standard Edition
J2EE: Java 2 Enterprise Edition
J2ME: Java 2 Micro Edition
The Java source code (.java file) is normally compiled to produce the
bytecode file (.class file) which is normally interpreted by the Java virtual
machine (JVM).
NetBeans Features
• Environment: easily configured user interface and a modular architecture
extensible with additional plugins.
• Project System: support for multiple source roots, easy management of
libraries, easily ported to other environments, all based on Apache Ant.
• Web Development: Web Application project type, Supports the J2EE 1.3
and 1.4 standards with web application build support based on Apache Ant.
• Enterprise Java Beans (EJB) Development: easy to create and deploy and
import java beans.
• Web Services Development: wizards for creating web services and web
services clients, providing the basic (java/wsdl) code needed, and easy to
use testing tools of existing web services.
• Java 2 Platform, Micro Edition (J2ME) MIDP development: visual design
editor with end-to-end support for enterprise applications.
• Code Editor: Syntax highlighting for Java, XML, HTML, CSS, JSP and IDL, full
support of new JDK 1.5 features, live parsing/error marking, popup javadoc,
code completion, and fast class importing.
• Refactoring: renaming, changing and moving of various objects, field
encapsulation and usage finding.
• Award Winning Debugger: Language independent debugger core, variable
modification and watches, various breakpoints and “Fix and Continue”
mechanism.
• GUI Builder: fully WYSIWYG designer with "Test Form" feature, extensible
Component Palette pre-installed Swing and AWT components, showing a
components tree and properties, automatic code generation and full
JavaBeans support.
• Version control Support: supports command lined vcs, supplying merging
and diff tools and containing a built- in CVS client.
• XML: XML, DTD and CSS Text Editor and XML Productivity Tools Wizards to
help user generate codes.
NetBeans Extras
• NetBeans Profiler: provides information about the runtime behavior of
applications. Allows developers to monitor the thread state, CPU
performance, and memory usage of their applications. makes it easy to
track down performance problems and memory leaks.
• NetBeans Platform: provides the services common to almost all large
desktop applications such as: window, menu, settings management and
storage, file access and more.
• NetBeans Mobility Pack: used to write, test, and debug applications for the
Java Micro Edition platform (J2ME) technology-enabled mobile devices. It
integrates support for the Mobile Information Device Profile (MIDP) 2.0,
the Connected, Limited Device Configuration (CLDC) 1.1.
• The mobility pack allows for the unique “On-Phone” debugging mode.
NetBeans Matisse
• The Goal: to take the best features from OSX and VS designers and allow
the same possibilities for Java Programmers.
• In order to reach that goal there was a need to develop a new layout
manager to support all the needed functionalities.
• Matisse provides a simple and intuitive layout of GUIs without having to
understand the complexities of Swing layout managers.
• As you drag and drop components into a form, the IDE automatically
suggests alignment, spacing, and resizing constraints.
• By simply right clicking a UI Object you can add an event handler with a
method waiting to be implemented without knowing too much about the
surrounding of this object. (watch example clip in the site)
Installation
• Installing JDK: in order to install NetBeans you need to first install JDK. You
can easily find an installation in Sun’s web site.
• NetBeans installation: you can find the installations kits for all the versions
in the NetBeans home page.
• Installation steps: you can watch a movie describing the installation step by
step in the.
Starting Up A Project
• When creating a new project, NetBeans already includes all the needed
packages for compiling and testing. It also outlines the sources by the right
logical directories and creates the files that are mandatory. For instance, if
you create a new java application you must implement a main class and so
it’s automatically created.
Testing
• JUnit Tests: you simply choose the class you want to test and in the tools
menu choose “create JUnit Test”. After filling the arguments NetBeans
automatically creates a test class inheriting from TestCase with the default
methods to implement and puts everything under the Test package.
Debugging
• NetBeans has two modes, run mode and debug mode.
• The debug mode is very easy to use.
• You can use the local variables window and watch window to follow the
progress of the program.
VARIABLES
Variable Declaration
Syntax: <datatype> <varName>; [= value;]
Example: String name;
int age;
double price = 55.66;
Assigning a value
Syntax: <varName> = value;
Example: name = “Maria Blanco”;
age = 22;
price = 200.50;
WRAPPER CLASSES
Java Wrapper Classes are used in converting one data type (such as a String) into another data
type (such as int or double). It is also used in wrapping a primitive value into an object.
Wrapper Class Primitive Type
Integer int
Float float
Double double
Long long
Byte byte
Short short
Character char
Boolean boolean
System.out.println(); or
System.out.print(); or
System.out.printf();
System is a class
out is a public static field: it accepts output data.
class AssignmentOperator {
public static void main(String[] args) {
System.out.println("Java programming is interesting.");
}
}
Output:
Java programming is interesting.
Operators
JAVA OPERATORS
1. Unary Arithmetic Operators
2. Binary Arithmetic Operators
3. Bitwise Operators
4. Shift Operators
5. Relational and Logical Operators
6. Cast Operator
7. Assignment Operator
8. Ternary Operator
++ Increment
-- Decrement
Increment and decrement operators have two formats: postfix and prefix.
Arithmetic Operators
There are some general guidelines to consider when creating arithmetic expressions:
Use parentheses to alter precedence.
Consider the size of resulting values and possible loss of precision.
Apply arithmetic operators’ precedence level.
Arithmetic Operators
When using negative numbers with modulus calculation, drop the negative signs
from either operand and calculate the result. The sign of the left operand is the
sign of the result.
The (+) operator can be used to add numbers and String objects.
Dividing integer by zero results in the throwing of ArithmeticException
Bitwise Operators
works on integer values, by manipulating its bit-pattern equivalent.
Operator Use Operation
Shift Operators
performs bit manipulation on data by shifting the bits of its first operand right or
left. This table summarizes the shift operators available in the Java
programming language.
>> op1 >> op2 shift bits of op1 right by distance op2
<< op1 << op2 shift bits of op1 left by distance op2
>>> op1 >>> op2 shift bits of op1 right by distance op2 (unsigned)
Relational Operators
compares two values and determines the
relationship between them.
Relational Operators
compares two values and determines the
relationship between them.
Logical Operators
often used with relational operators to construct more complex decision-making
expressions.
Operator Use Operation
Cast Operators
used in converting (casting) one type into another type or an object into
another object.
Syntax:
(Cast type) Value;
Example:
double dbl = 55.66;
int number = (int)dbl;
Assignment Operators
Used to assign values to a variable
Shorthand operator if combined with other operators
Example:
int a=10;
a+=10; // a = a+ 10
a-=10; // a = a- 10
a*=10; // a = a* 10
a/=10; // a = a/ 10
Ternary Operator
an operator that deals with three operands.
Syntax:
variable = condition ? value : value;
Example:
int x = 20, y = 30;
int biggerNumber = 0;
biggerNumber = x>y ? x : y;
// What do u think will be the value of the biggerNumber??
Module 4 Study Guide
Control Structures
if, else statement
switch, case statement
while loop
do, while loop
for loop
The if statement enables your program to selectively execute other statements, based on some
criteria.
The else statement performs a different set of statements if the expression is false.
Syntax:
if(condition/boolean expression) {
//codes to execute if the condition is true
}
else {
//codes to execute if the condition is false
}
The switch statement is used to conditionally perform statements based on an integer
expression.
Syntax:
switch(varName)
{
case const1: codes here; break;
case const2: codes here; break;
default: codes here; break;
}
The break statement causes the program flow to exit from the body of the switch construct.
Each case label takes only a single argument, but when execution jumps to one of these labels,
it continues downward until it reaches a break statement.
The while loop executes a given statement or block of statements repeatedly as long as the
value of the expression is true.
Syntax:
while(condition/expression) {
//codes to execute if condition is true
}
The do-while loop facilitates evaluation of condition or expression at the end of the loop to
ensure that the statements are executed at least once .
Syntax:
do{
//codes to execute if condition is true
} while(condition/expression);
The for loop executes a given statement or a block of statements for a definite number of
times.
Syntax:
for (initialization; condition; altering list) {
//codes to execute if condition is true
}
The foreach loop is for traversing items in a collection. foreach is usually used in place of a
standard for statement. It usually maintain no explicit counter: they essentially say "do this to
everything in this set", rather than "do this x times".
Syntax:
for(initialization : [collection/array]) {
//codes to execute if condition is true
}
Arrays
First index
0 1 2 3 4 5 6 7 8 9
Array length is 10
Element at index 8
Array Declaration
Syntax:
type arrayName[ ] = new type[length];
Example:
String names[ ] = new String[5];
int [ ]grades = new int[15];
double[ ] grades;
grades = new double[2];
Array Initialization
Syntax:
type arrayName[ ] = {value,value,…};
Example:
String names[ ] ={“maria”,”blanco”,”forever”};
It describes the task to be performed on objects. These objects that have to be created
and stored in the computer memory, contain data and instructions to perform tasks specific to
that object.
Procedural vs. OOP
The focus of procedural programming is to break down a programming task into a
collection of variables, data structures, and subroutines
Whereas in object-oriented programming, it is to break down a programming task into
objects that expose behavior (methods) and data (members or attributes) using
interfaces.
The most important distinction is that while procedural programming uses procedures
to operate on data structures, object-oriented programming bundles the two
together, so an "object", which is an instance of a class, operates on its "own" data
structure.
Object-Oriented Programming
It uses a collection of objects interacting with each other.
One of the principal advantages of using OOP technique is that it enables programmers to
create modules that need not be changed when a new type of object is added.
Benefits of OOP:
Reduced software complexities and realistic modelling through the use of various
techniques:
Abstraction – the process of picking out the common features of objects and
procedures. This process focuses on the essential characteristics of an object.
Reduced software complexities and realistic modelling through the use of various
techniques:
Encapsulation – the process of hiding the implementation details of an object.
Software reusability by implementing inheritance. Programs are built that can be used
by several other applications.
superclass (base class) – the parent class from which properties are inherited by
another class
subclass (derived class) – a new class with properties taken from a parent class
abstract class – a well-encapsulated conceptual class. The objects of this class do not
exist in real world
Class Diagram
A class diagram is used to describe the attributes and behaviours of objects in the
system.
Class Name
2. Class Variables (static fields) –variables stored in the class and are available to all
objects of a class or objects of other classes if access is permitted, usually referred to as the
static members of the class.
3. Local Variables (method variables or local data) – data used in a method. This data is
temporary and does not exist once the method has completed execution.
Module 6 Study Guide
The meaning of Encapsulation, is to make sure that "sensitive" data is hidden from
users. To achieve this, you must:
• declare class variables/attributes as private (only accessible within the same class)
• provide public setter and getter methods to access and update the value of
a private variable
Get and Set
Private variables can only be accessed within the same class (an outside class has no
access to it)
However, it is possible to access them if we provide public getter (accessor)
and setter (mutator) methods.
The get method returns the variable value, and the set method sets the value.
The get method returns the value of the variable name.
The set method takes a parameter (newName) and assigns it to the name variable.
The this keyword is used to refer to the current object.
However, as the name variable is declared as private, we cannot access it from outside this
class.
Why Encapsulation?
Better control of class attributes and methods
Class variables can be made read-only (if you omit the set method), or write-only (if you
omit the get method)
Flexible: the programmer can change one part of the code without affecting other parts
Increased security of data
Inheritance
The technique of deriving new class definitions from an existing class definition.
The following are the benefits of using class inheritance in OOP:
Re-use of predefined and well-tested classes
Standardization of behaviors across a group of classes
Ability to use members of a family of classes interchangeably in methods
Take Note:
Java does not support multiple inheritance, however, Java provides same effects and
benefits of multiple inheritance through the use of interface.
2. Method Overriding
Providing a different implementation of a method in a subclass of the class that originally
defined a method.
Overloading Overriding
Overloaded functions supplement each other. Overriding function replaces the function it
overrides.
Overloaded functions can exist, in any number, Each function in a base class can be overridden
in the same class. at most once in any one derived class.
Overloaded functions must have different Overriding functions must have argument lists
argument lists. of identical type and order.
The return type of an overloaded function may The return type of an overriding method must
be chosen freely. be identical to the function it overrides.
This ability of our reference to change behavior according to what object it is holding is called
polymorphism. Polymorphism allows multiple objects of different subclasses to be treated as
objects of a single superclass, while automatically selecting the proper methods to apply to a
particular object based on the subclass it belongs to.
Abstraction
The Abstract Class and Interface:
Abstract Class – contains one or more abstract methods and, therefore, can never be
instantiated. It is defined so that other classes can extend them and make them
concrete by implementing the abstract methods.
Take Note:
All abstract classes are public by default and cannot be instantiated. Constructors and
public methods cannot be declared as abstract.
An abstract class is a class that cannot be instantiated. It often appears at the top of an object-
oriented programming class hierarchy, defining the broad types of actions possible with objects
of all subclasses of the class.
Those methods in the abstract classes that do not have implementation are called
abstract methods.
Coding Guidelines:
Use abstract classes to define broad types of behaviors at the top of an object-oriented
programming class hierarchy, and use its subclasses to provide implementation details of the
abstract class.
Interfaces
An interface is a special kind of block containing method signatures (and possibly constants)
only. Interfaces define the signatures of a set of methods without the body.
Interfaces define a standard and public way of specifying the behavior of classes. They allow
classes, regardless of their location in the class hierarchy, to implement common behaviors.
Note that interfaces exhibit polymorphism as well, since program may call an interface method
and the proper version of that method will be executed depending on the type of object passed
to the interface method call.
Interface – an abstract class that represents a collection of method definitions and constant
values. It can later be implemented by classes that define the interface using the implements
keyword.
Why do we use Interfaces?
We need to use interfaces if we want unrelated classes to implement similar methods.
Thru interfaces, we can actually capture similarities among unrelated classes without artificially
forcing a class relationship.
Another reason for using an object's programming interface is to reveal an object‘s
programming interface without revealing its class.
As we can see later on the section Interface vs. Classes, we can actually use an interface as data
type.
Finally, we need to use interfaces to model multiple inheritance which allows a class to have
more than one superclass.
Multiple inheritance is not present in Java, but present in other object-oriented languages like
C++.
Another common characteristic is that both interface and class can define methods.
However, an interface does not have an implementation code while the class have one.
When your class tries to implement an interface, always make sure that you implement all the
methods of that interface, or else, you would encounter this error,
Coding Guidelines:
Use interfaces to create the same standard method definitions in may different classes.
Once a set of standard method definition is created, you can write a single method to
manipulate all of the classes that implement the interface.
As we have seen in the previous section, a class can implement an interface as long as it
provides the implementation code for all the methods defined in the interface.
Another thing to note about the relationship of interfaces to classes is that, a class can only
EXTEND ONE super class, but it can IMPLEMENT MANY interfaces.
EXCEPTION
Exception denotes an abnormal event that occurs during the execution of the program
and disrupts its normal flow.
CONCEPTS OF EXCEPTION
1. When an error occurs within a method, the method creates an object called exception
object and hands it off to the runtime system.
2. Exception object contains information about the error, including its type and the state of
the program when the error occurred.
3. Creating an exception object and handing it to the runtime system is called throwing an
exception.
4. After a method throws an exception, the runtime system attempts to find a list of
methods, called the call stack to handle it.
5. The runtime system searches the call stack for a method that contains a block of code
that can handle the exception called exception handler.
6. When an appropriate handler is found, the runtime system passes the exception to the
handler. An exception handler is considered appropriate if the type of the exception
object thrown matches the type that can be handled by the handler.
7. The exception handler chosen is said to catch the exception. If the runtime system
exhaustively searches all the methods on the call stack without finding an appropriate
exception handler, as shown in the next figure, the runtime system (and, consequently,
the program) terminates.
Exception-Handling Keywords
try
catch
throw
throws
finally
Exception-Handling Techniques
try{
//codes that may throw exception
}
catch(ExceptionType e1){
//codes that handle exception e1
}
catch(ExceptionType e2){
//codes that handle exception e2
}
finally{
/*codes to execute whether or not errors are
encountered*/
}
Exceptions thrown during execution of the try block can be caught and handled in a
catch block.
The code in the finally block is always executed.
The following are the key aspects about the syntax of the try-catch-finally construct:
• The block notation is mandatory.
• For each try block, there can be one or more catch blocks, but only one finally block.
• The catch blocks and finally blocks must always appear in conjunction with the try
block, and in the correct order.
• A try block must be followed by at least one catch block OR one finally block, or both.
• Each catch block defines an exception handle. The header of the catch block takes
exactly one argument, which is the exception its block is willing to handle. The
exception must be of the Throwable class or one of its subclasses.
where:
ExceptionList – list of exception types separated by comma
ThrowableInstance – an instance (object) of an exception
Assertions
An assertion is a statement in Java that enables you to test your assumptions about
your program.
Each assertion contains a boolean expression that you believe will be true when the
assertion executes.
By verifying that the boolean expression is indeed true, the assertion confirms your
assumptions about the behavior of your program, increasing your confidence that the
program is free of errors.
Types of Assertion:
Pre-condition – an assertion which invokes when a method is invoked.
Post-condition – an assertion which invokes after a method finishes.
The assertion statement has two forms:
The first is:
assert Expression1;
where: Expression1 = boolean expression.
When the system runs the assertion,
it evaluates Expression1 and if it is false throws an AssertionError with no details.
Collections
The Collection in Java is a framework that provides an architecture to store and
manipulate the group of objects.
Java Collections can achieve all the operations that you perform on a data such as
searching, sorting, insertion, manipulation, and deletion.
Java Collection means a single unit of objects. Java Collection framework provides
many interfaces (Set, List, Queue, Deque) and classes (ArrayList, Vector, LinkedList,
PriorityQueue, HashSet, LinkedHashSet, TreeSet).
Collection
What is Collection in Java
A Collection represents a single unit of objects, i.e., a group.
What is a framework in Java
It provides readymade architecture.
It represents a set of classes and interfaces.
It is optional.
What is Collection framework
The Collection framework represents a unified architecture for storing and
manipulating a group of objects. It has:
Interfaces and its implementations, i.e., classes
Algorithm
Hierarchy of Collection Framework
The java.util package contains all the classes and interfaces for the Collection
framework.
Iterable Interface
The Iterable interface is the root interface for all the collection classes. The Collection
interface extends the Iterable interface and therefore all the subclasses of Collection
interface also implement the Iterable interface.
It contains only one abstract method. i.e.,
Collection Interface
The Collection interface is the interface which is implemented by all the classes in the
collection framework. It declares the methods that every collection will have. In other
words, we can say that the Collection interface builds the foundation on which the
collection framework depends.
Some of the methods of Collection interface are Boolean add ( Object obj), Boolean
addAll ( Collection c), void clear(), etc. which are implemented by all the subclasses of
Collection interface.
List Interface
List interface is the child interface of Collection interface. It inhibits a list type data
structure in which we can store the ordered collection of objects. It can have duplicate
values.
List interface is implemented by the classes ArrayList, LinkedList, Vector, and Stack.
To instantiate the List interface, we must use :
There are various methods in List interface that can be used to insert, delete, and
access the elements from the list.
ArrayList
The ArrayList class implements the List interface. It uses a dynamic array to store the
duplicate element of different data types. The ArrayList class maintains the insertion
order and is non-synchronized. The elements stored in the ArrayList class can be
randomly accessed.
LinkedList
LinkedList implements the Collection interface. It uses a doubly linked list internally to
store the elements. It can store the duplicate elements. It maintains the insertion
order and is not synchronized. In LinkedList, the manipulation is fast because no
shifting is required.
Vector
Vector uses a dynamic array to store the data elements. It is similar to ArrayList.
However, It is synchronized and contains many methods that are not the part of
Collection framework.
Stack
The stack is the subclass of Vector. It implements the last-in-first-out data structure,
i.e., Stack. The stack contains all of the methods of Vector class and also provides its
methods like boolean push(), boolean peek(), boolean push(object o), which defines
its properties.
Queue Interface
PriorityQueue
The PriorityQueue class implements the Queue interface. It holds the elements or
objects which are to be processed by their priorities. PriorityQueue doesn't allow null
values to be stored in the queue.
Deque Interface
Deque interface extends the Queue interface. In Deque, we can remove and add the
elements from both the side. Deque stands for a double-ended queue which enables
us to perform the operations at both the ends.
Deque can be instantiated as:
ArrayDeque
ArrayDeque class implements the Deque interface. It facilitates us to use the Deque.
Unlike queue, we can add or delete the elements from both the ends.
ArrayDeque is faster than ArrayList and Stack and has no capacity restrictions.
Set Interface
Set Interface in Java is present in java.util package. It extends the Collection interface.
It represents the unordered set of elements which doesn't allow us to store the
duplicate items. We can store at most one null value in Set. Set is implemented by
HashSet, LinkedHashSet, and TreeSet.
Hashset
HashSet class implements Set Interface. It represents the collection that uses a hash
table for storage. Hashing is used to store the elements in the HashSet. It contains
unique items.
Linked Hashset
LinkedHashSet class represents the LinkedList implementation of Set Interface. It
extends the HashSet class and implements Set interface. Like HashSet, It also contains
unique elements. It maintains the insertion order and permits null elements.
SortedSet Interface
SortedSet is the alternate of Set interface that provides a total ordering on its
elements. The elements of the SortedSet are arranged in the increasing (ascending)
order. The SortedSet provides the additional methods that inhibit the natural ordering
of the elements.
The SortedSet can be instantiated as:
TreeSet
Java TreeSet class implements the Set interface that uses a tree for storage. Like
HashSet, TreeSet also contains unique elements. However, the access and retrieval
time of TreeSet is quite fast. The elements in TreeSet stored in ascending order.
Module 10 Study Guide
InputStream and OutputStream
Java I/O (Input and Output) is used to process the input and produce the output.
Java uses the concept of a stream to make I/O operation fast. The java.io package
contains all the classes required for input and output operations.
We can perform file handling in Java by Java I/O API.
A stream is a sequence of data. In Java, a stream is composed of bytes. It's called a
stream because it is like a stream of water that continues to flow.
In Java, 3 streams are created for us automatically. All these streams are attached with
the console.
1) System.out: standard output stream
2) System.in: standard input stream
3) System.err: standard error stream
OutputStream
Java application uses an output stream to write data to a destination; it may be a
file, an array, peripheral device or socket.
InputStream
Java application uses an input stream to read data from a source; it may be a file,
an array, peripheral device or socket.
OutputStream Class
Java OutputStream class is an abstract class. It is the superclass of all classes
representing an output stream of bytes. An output stream accepts output bytes
and sends them to some sink.
Java FileInputStream class obtains input bytes from a file. It is used for reading byte-
oriented data (streams of raw bytes) such as image data, audio, video etc. You can also
read character-stream data. But, for reading streams of characters, it is recommended
to use FileReader class.
FileInputStream class declaration for Java.io.FileInputStream class:
Java FileReader class is used to read data from the file. It returns data in byte format
like FileInputStream class.
It is character-oriented class which is used for file handling in java.
Java.io.FileReader