Java_com211_printout
Java_com211_printout
released in 1995. Java runs on a variety of platforms, such as Windows, Mac OS, and the various
versions of UNIX. This tutorial gives a complete understanding of Java. Java is guaranteed to be
Write Once, Run Anywhere.
Java is:
Case Sensitive
Class Names must be in Upper Case.
Method Names must start with a Lower Case letter except Constructors.
Program File Name - Name of the program file should exactly match the class name.
public static void main(Stringargs[]) - java program processing starts from the main
method which is a mandatory part of every java program…
Java Identifiers:
All Java components require names. Names used for classes, variables and methods are called
identifiers. In Java, there are several points to remember about identifiers. They are as follows:
All identifiers should begin with a letter (A to Z or a to z), currency character ($) or an
underscore (_).
After the first character identifiers can have any combination of characters.
A key word cannot be used as an identifier.
Most importantly identifiers are case sensitive.
Examples of legal identifiers: age, $salary, _value, __1_value
Examples of illegal identifiers: 123abc, -salary
Java Modifiers:
Like other languages, it is possible to modify classes, methods, etc., by using modifiers. There are
two categories of modifiers:
Access Modifiers: default, private, public, protected:
Java provides a number of access modifiers to set access levels for classes, variables,
methodsand constructors. The four access levels are:
o Visible to the package –the default. No modifiers are needed.
o Visible to the class only – private.
o Visible to the world – public.
o Visible to the package and all subclasses – protected.
1
Misc or Miscellaneous Operators: Conditional Operator ( ? : )
The operator is written as: variable x =(expression)?value_if_true: value_if_false
Errors in Programming
Errors (bugs) are bound to occur and removed (debugged) in our programs. The following common
errors exist in programming:
Syntax error: When a Programmer violates the grammatical rules of the programming
language he/she is using. E.g.: misspell a keyword, absence of semi-colon, etc.
Semantic error: This error occurs if the compiler cannot attach meaning to a program
statement. E.g.: assigning a char value to an integer location, etc.
Compile-time error: This occurs at compilation stage of the program development. They are
actually syntax and semantic errors.
Logic error: This is usually made by programmers. The program will compile and run
perfectly but the output will be erroneous. E.g.: using <= in place of >=, etc.
Run-time error: The error is encountered at execution stage of the program development.
E.g.: divide by zero, memory overflows, etc.
JAVA ARRAYS
An array is a group of variables, all of the same data type that is referred to by a single name. The
values in the group occupy contiguous locations in the computer memory, i.e. the data are stored one
next to each other in the computer memory. Each element in the array is identified by the array name
and a subscript pointing to the particular location within the array.
2
Score
20 40 10 50 30
Types of Array:
(i) One (Single) dimensional array: with a single row or column.
(ii) Two-dimensional array: with more the one row and column.
As with single objects, both the declaration and allocation can be combined in a single declaration
with initialization as shown below:
element-type[] arrayName = new element-type[n];
Note: element-type could be any of the primitive data type such as int, float, double, char, etc.
Examples:
float[] x; //declares x to be a reference to an array of floats…
x = new float[8]; //allocates an array of 8 floats, referenced by x.
boolean[] flags = new boolean[5];
double[] myList = new double[10];
Note that we can initialize an array explicitly with an initialization list, like this:
int[] c = {44, 88, 55, 33}; c[0] = 44;
This means: c[1] = 88;
int[] c; c[2] = 55;
c = new int[4]; c[3] = 33;
Two-dimensional Array:
A two-dimensional array looks like a matrix as shown below:
34 05 -5
-10 -2 24
15 13 -7
3
class Main { Example: Compute Sum and Average of Array
public static void main(String[] args) Elements
{ class Main {
public static void main(String[] args) {
// create an array int[] numbers = {2, -9, 0, 5, 12, -25, 22, 9, 8, 12};
int[] age = {12, 4, 5}; int sum = 0;
Double average;
// loop through the array
// using for loop // access all elements using for each loop
System.out.println("Using for-each // add each element in sum
Loop:"); for (int number: numbers) {
for(int a : age) { sum += number;
System.out.println(a); }
} // get the total number of elements
}} int arrayLength = numbers.length;
Output
Using for-each Loop: // calculate the average
12 // convert the average from int to double
4 average = ((double)sum / (double)arrayLength);
5
System.out.println("Sum = " + sum);
System.out.println("Average = " + average); }}
Example: To print all elements of 2d Output:
ragged array Using Loop: Sum = 36
Average = 3.6
for (int i = 0; i < a.length; ++i) {
for(int j = 0; j < a[i].length; ++j) { Note:
System.out.println(a[i][j]); average = ((double)sum / (double)arrayLength);//
} As you can see, we are converting the int value into
} double. This is called type casting in Java.
Java Class
A class is a blueprint for the object. Before we create an object, we first need to define the class.
We can think of the class as a sketch (prototype) of a house. It contains all the details about the
floors, doors, windows, etc. Based on these descriptions we build the house. House is the object.
Since many houses can be made from the same description, we can create many objects from a class.
Create a class in Java class Bicycle {
We can create a class in Java using the class // state or field
keyword. For example, private int gear = 5;
// behavior or method
class ClassName { public void braking() {
// fields System.out.println("Working of Braking");
// methods }
} }
The above class named Bicycle contains a field
named gear and a method named braking().
4
Java Objects
An object is called an instance of a class. For example, suppose Bicycle is a class then
MountainBicycle, SportsBicycle, TouringBicycle, etc can be considered as objects of the class.
Creating an Object in Java We have used the new keyword along with the
Here is how we can create an object of a class. constructor of the class to create an object.
className object = new className(); Constructors are similar to methods and have the
same name as the class.
// for Bicycle class
Bicycle sportsBicycle = new Bicycle(); For example, Bicycle() is the constructor of the
Bicycle touringBicycle = new Bicycle(); Bicycle class.
JAVA METHODS
A method is a block of code that performs a specific task. Suppose you need to create a program to
create a circle and color it. You can create two methods to solve this problem: (i) a method to draw
the circle (ii) a method to color the circle.
Dividing a complex problem into smaller chunks makes your program easy to understand and
reusable.
Here,
modifier - It defines access types whether the method is public, private, and so on. To learn more,
visit Java Access Specifier.
static - If we use the static keyword, it can be accessed without creating objects.
For example, the sqrt() method of standard Math class is static. Hence, we can directly call
Math.sqrt() without creating an instance of Math class.
parameter1/parameter2 - These are values passed to a method. We can pass any number of
arguments to a method.
Calling a Method in Java
In the above example, we have declared a method named addNumbers(). Now, to use the method, we
need to call it.
Here's is how we can call the addNumbers() method.
// calls the method
addNumbers();
public static void main(String[] args) { public static void main(String[] args) {
int num1 = 25,num2 = 15; int result;
private String formatNumber(String value) { When you run the program, the output will be:
return String.format("%.2f", 500
Double.parseDouble(value)); 89.993
} 550.00
Note: In Java, you can also overload constructors in a similar way like methods.
7
JAVA CONSTRUCTORS
Constructor Called:
The name is Engr MOWEMI
In the above example, we have created a constructor named Main(). Inside the constructor, we are
initializing the value of the name variable.
Hence, the program prints the value of the name variables as Engr MOWEMI.
JAVA RECURSION
JAVA INHERITANCE
Inheritance is one of the key features of OOP that Example 1: Java Inheritance
allows us to create a new class from an existing class Animal {
class.
String name;
The new class that is created is known as
subclass (child or derived class) and the existing public void eat() {
class from where the child class is derived is System.out.println("I can eat");
known as superclass (parent or base class). }
10
IS-A RELATIONSHIP
In Java, inheritance is an is-a relationship. That Output:
is, we use inheritance only if there exists an is-a My name is Rohu
relationship between two classes. For example, I can eat
Car is a Vehicle
Orange is a Fruit In the above example, we have derived a
Surgeon is a Doctor subclass Dog from superclass Animal.
Dog is an Animal
Here, Car can inherit from Vehicle, Orange can
inherit from Fruit, and so on.
JAVA EXCEPTIONS
12
Java Exception Handling
Exceptions abnormally terminate the execution of a program. This is why it is important to handle
exceptions. Here's a list of different approaches to handle exceptions in Java.
(i) try...catch block (ii) finally block (iii) throw and throws keyword
1. Java try...catch block Example: Exception handling using try...catch
The try-catch block is used to handle exceptions class Main {
in Java. Here's the syntax of try...catch block: public static void main(String[] args) {
try { try {
// code int x = 5 / 0;
} catch(Exception e) { System.out.println("Rest of code in try
// code block"); }
}
Here, we have placed the code that might catch (ArithmeticException e) {
generate an exception inside the try block. Every System.out.println("ArithmeticException => "
try block is followed by a catch block. + e.getMessage());
} }
When an exception occurs, it is caught by the }
catch block. The catch block cannot be used Output
without the try block. ArithmeticException => / by zero
Note: To handle the exception, we have put the Note: If none of the statements in the try block
code, 5 / 0 inside the try block. Now when an generates an exception, the catch block is
exception occurs, the rest of the code inside the skipped.
try block is skipped.
2. Java finally block Example: Using finally block
In Java, the finally block is always executed no class Main {
matter whether there is an exception or not. The public static void main(String[] args) {
finally block is optional. And, for each try block, try { int x = 5 / 0; }
there can be only one finally block. catch (ArithmeticException e) {
The basic syntax of finally block is: System.out.println("ArithmeticException => "
try { //code } + e.getMessage()); }
catch (ExceptionType1 e1) {// catch block } finally { System.out.println("This is the finally
finally { // finally block always executes } block"); } }
If an exception occurs, the finally block is }
executed after the try...catch block. Otherwise, it Output
is executed after the try block. For each try ArithmeticException => / by zero
block, there can be only one finally block. This is the finally block
Multiple Catch blocks catch (IndexOutOfBoundsException e2) {
For each try block, there can be zero or more System.out.println("IndexOutOfBoundsException
catch blocks. Multiple catch blocks allow us to => " + e2.getMessage());
handle each exception differently. }
The argument type of each catch block indicates } }
the type of exception that can be handled by it. class Main {
For example: public static void main(String[] args) {
class ListOfNumbers { ListOfNumbers list = new ListOfNumbers();
public int[] arr = new int[10]; list.writeList(); } }
public void writeList() { Output
try { IndexOutOfBoundsException => Index 10 out of
arr[10] = 11; bounds for length 10
}
catch (NumberFormatException e1) { Multiple catch blocks works like if…else if
System.out.println("NumberFormatException statement. If an exception occurs, only one catch
=> " + e1.getMessage()); } statement is executed.
13
Catching Multiple Exceptions Example 2: Multi-catch block
This reduces code duplication and increases code class Main {
simplicity and efficiency. There is no code public static void main(String[] args) {
redundancy. try {
Each exception type that can be handled by the int array[] = new int[10];
catch block is separated using a vertical bar( | ). array[10] = 30 / 0;
Its syntax is: } catch (ArithmeticException |
try { ArrayIndexOutOfBoundsException e) {
// code System.out.println(e.getMessage());
} catch (ExceptionType1 | Exceptiontype2 ex) { } }
// catch block }
} Output
/ by zero
No matter where the data is coming from or going to and no matter what its type, the algorithms for
sequentially reading and writing data are basically the same:
Reading Writing
The java.io package contains a collection of stream classes that support these algorithms for reading
and writing. To use these classes, a program needs to import the java.io package. The stream classes
are divided into two class hierarchies, based on the data type (either characters or bytes) on which
they operate.
14
Character Streams
Reader and Writer are the abstract superclasses for character streams in java.io. Reader provides the
API and partial implementation for readers--streams that read 16-bit characters--and Writer provides
the API and partial implementation for writers--streams that write 16-bit characters. Subclasses of
Reader and Writer implement specialized streams and are divided into two categories: those that read
from or write to data sinks (shown in gray in the following figures) and those that perform some sort
of processing (shown in white). The figure shows the class hierarchies for the Reader and Writer
classes.
Most programs should use readers and writers to read and write textual information. The reason is
that they can handle any character in the Unicode character set, whereas the byte streams are limited
to ISO-Latin-1 8-bit bytes.
Byte Streams
To read and write 8-bit bytes, programs should use the byte streams, descendants of InputStream and
OutputStream. InputStream and OutputStream provide the API and partial implementation for input
streams (streams that read 8-bit bytes) and output streams (streams that write 8-bit bytes). These
streams are typically used to read and write binary data such as images and sounds. Two of the byte
stream classes, ObjectInputStream and ObjectOutputStream, are used for object serialization.
As with Reader and Writer, subclasses of InputStream and OutputStream provide specialized I/O that
falls into two categories, as shown in the following class hierarchy figure: data sink streams (shaded)
and processing streams (unshaded).
The File class from the java.io package, allows us to work with files.
To use the File class, create an object of the class, and specify the filename or directory name:
Example:
import java.io.File; // Import the File class
File myObj = new File("filename.txt"); // Specify the filename
15
The File class has many useful methods for creating and getting information about files.
For example:
Method Type Description
canRead() Boolean Tests whether the file is readable or not
canWrite() Boolean Tests whether the file is writable or not
createNewFile() Boolean Creates an empty file
delete() Boolean Deletes a file
exists() Boolean Tests whether the file exists
getName() String Returns the name of the file
getAbsolutePath() String Returns the absolute pathname of the file
length() Long Returns the size of the file in bytes
list() String[] Returns an array of the files in the directory
mkdir() Boolean Creates a directory
Create a File
To create a file in Java, you can use the createNewFile() method. This method returns a boolean
value: true if the file was successfully created, and false if the file already exists. Note that the
method is enclosed in a try...catch block. This is necessary because it throws an IOException if an
error occurs (if the file cannot be created for some reason):
Example:
import java.io.File; // Import the File class
import java.io.IOException; // Import the IOException class to handle errors
To create a file in a specific directory (requires permission), specify the path of the file and use
double backslashes to escape the "\" character (for Windows). On Mac and Linux you can just write
the path, like: /Users/name/filename.txt
Example:
File myObj = new File("C:\\Users\\MyName\\filename.txt");
Write To a File
In the following example, we use the FileWriter class together with its write() method to write some
text to the file we created in the example above. Note that when you are done writing to the file, you
should close it with the close() method:
16
Example:
import java.io.FileWriter; // Import the FileWriter class
import java.io.IOException; // Import the IOException class to handle errors
Read a File
In the previous chapter, you learned how to create and write to a file.
In the following example, we use the Scanner class to read the contents of the text file we created in
the previous chapter:
Example:
import java.io.File; // Import the File class
import java.io.FileNotFoundException; // Import this class to handle errors
import java.util.Scanner; // Import the Scanner class to read text files
17
public class GetFileInfo {
public static void main(String[] args) {
File myObj = new File("filename.txt");
if (myObj.exists()) {
System.out.println("File name: " + myObj.getName());
System.out.println("Absolute path: " + myObj.getAbsolutePath());
System.out.println("Writeable: " + myObj.canWrite());
System.out.println("Readable " + myObj.canRead());
System.out.println("File size in bytes " + myObj.length());
} else {
System.out.println("The file does not exist.");
}
}
}
The output will be:
File name: filename.txt
Absolute path: C:\Users\MyName\filename.txt
Writeable: true
Readable: true
File size in bytes: 0
Delete a File
To delete a file in Java, use the delete() method:
Example
import java.io.File; // Import the File class
public class DeleteFile {
public static void main(String[] args) {
File myObj = new File("filename.txt");
if (myObj.delete()) {
System.out.println("Deleted the file: " + myObj.getName());
} else {
System.out.println("Failed to delete the file.");
}
}}
The output will be:
Deleted the file: filename.txt
Delete a Folder
You can also delete a folder. However, it must be empty:
Example:
import java.io.File;
18
JFRAME
The IDE’s GUI Builder makes it possible to build professional-looking GUIs without an intimate
understanding of layout managers. You can lay out your forms by simply placing components where
you want them.
The IDE creates the JFsample folder on your system in the designated location. This folder
contains all of the project’s associated files, including its Ant script, folders for storing
sources and tests, and a folder for project-specific metadata.
2. In the Projects window, right-click the Yele node and choose New > JFrame Form.
Alternatively, you can find a JFrame form by choosing New > Other > Swing GUI Forms >
JFrame Form.
19
ii) Navigator: Provides a representation of all the components, both visual and non-visual, in
your application as a tree hierarchy. The Navigator also provides visual feedback about what
component in the tree is currently being edited in the GUI Builder as well as allows you to
organize components in the available panels.
iii) Palette: A customizable list of available components containing tabs for JFC/Swing, AWT,
and JavaBeans components, as well as layout managers. In addition, you can create, remove,
and rearrange the categories displayed in the Palette using the customizer.
iv) Properties Window: Displays the properties of the component currently selected in the GUI
Builder, Navigator window, Projects window, or Files window.
JAVA SERVLET
Servlet: This is a server component which responsible to create a dynamic content. Servlet is
basically a java file which can take a request from the client on the internet, process the
request and provide the response.
Java Servlets: are the java programs class that run on the JAVA to enable web server or
application server. They are used to handle the request obtained from the webserver, process
the request, produce the response, and then send a response back to the webserver.
20
Java Servlet has the technology to design and deploy dynamic web pages using the Java
Programming Language. It implements a typical servlet in the client-server architecture, and
the Servlet lives on the server-side.
22