Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
29 views

Java_com211_printout

Java coding format

Uploaded by

tyegold56
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views

Java_com211_printout

Java coding format

Uploaded by

tyegold56
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

JAVA is a high-level programming language originally developed by Sun Microsystems and

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 Object Oriented, Platform independent, Simple, Secure, Architectural-neutral, Portable,


Robust, Multithreaded, Interpreted, High Performance, Distributed and Dynamic.

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.

 Non-access Modifiers: static, final, abstract, strictfp


Java provides a number of non-access modifiers to achieve many other functionality.
o The static modifier for creating class methods and variables
o The final modifier for finalizing the implementations of classes, methods, and
variables.
o The abstract modifier for creating abstract classes and methods.
o The synchronized and volatile modifiers, which are used for threads.

Data Types in Java:


There are two data types available in Java:
 Primitive Data Types: byte, short, int, long, float, double, boolean, char and String
 Reference/Object Data Types: Reference variables are created using defined constructors of
the classes. They are used to access objects. These variables are declared to be of a specific
type that cannot be changed. Example: Animal animal = new Animal("giraffe")

1
Misc or Miscellaneous Operators: Conditional Operator ( ? : )
The operator is written as: variable x =(expression)?value_if_true: value_if_false

public class Test { System.out.println( "Value of b is : " + b );


public static void main(String args[]){ }
int a=10, b; }
b = (a == 1) ? 20: 30; This would produce the following result −
System.out.println( "Value of b is : " + b ); Value of b is : 30
b = (a == 10) ? 20: 30; Value of b is : 20

Enhanced for loop (for-each loop) in Java:


As of java 5 the enhanced for loop was introduced. This is mainly used for Arrays.
Syntax:
The syntax of enhanced for loop is: public class TestArray {
public static void main(String[] args) {
for(declaration : expression) double[] myList = {1.9, 2.9, 3.4, 3.5};
{ // Print all the array elements
//Statements; for (double element: myList) {
} System.out.println(element);
}
}}
The break Keyword:
The break keyword is used to stop the entire loop. The break keyword must be used inside any loop
or a switch statement. The break keyword will stop the execution of the innermost loop and start
executing the next line of code after the block. [Syntax: break;]

The continue Keyword:


The continue keyword can be used in any of the loop control structures. It causes the loop to
immediately jump to the next iteration of the loop. In a for loop, the continue keyword causes flow of
control to immediately jump to the update statement. In a while loop or do/while loop, flow of
control immediately jumps to the Boolean expression. [Syntax: continue;]

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

Score[0] Score[1] … Score[4]

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.

Creating one-dimensional array:


The general syntax for creating an array is:
element-type[] arrayName; // declares the array.
arrayName = new element-type[n]; //allocates storage for n elements.

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

The following are therefore the features of a two-dimensional array:


 It uses two subscripts i.e. [row][column].
 It has grid of rows and columns, with the 1st subscript locating the row and the 2nd subscript
locating the column.
 Java sees a two-dimensional array as a big array containing small arrays. Each row forms an
array of the whole array.
Examples:
Int[][] x = new int[3][5]; //declares a two-dimensional array x of 3 rows & 5 columns.
a[0][2] = 50; // assigns 50 to the element in row 0 column 2 (1st row 3rd column).
int[][] a = {{1, 2, 3}, {4, 5, 6, 9}, {7}, }; //2d ragged array with 3,4,1 columns respectively.

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 AND OBJECTS


Java is an object-oriented programming language. The core concept of the object-oriented approach
is to break complex problems into smaller objects.
An object is any entity that has a state and behavior. For example, a bicycle is an object. It has
(i) States: idle, first gear, etc (ii) Behaviors: braking, accelerating, etc.

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.

Access Members of a Class


We can use the name of objects along with the dot(.) operator to access members of a class. For
example:
class Bicycle { // create object
// field of class Bicycle sportsBicycle = new Bicycle();
int gear = 5;
// access field and method
// method of class sportsBicycle.gear;
void braking() { sportsBicycle.braking();
...
}
}
In the above example, we have created a class named Bicycle. It includes a field named gear and a
method named braking(). Notice the statement,
Bicycle sportsBicycle = new Bicycle();
Here, we have created an object of Bicycle named sportsBicycle. We then use the object to access
the field and method of the class:
sportsBicycle.gear – This line access the field gear
sportsBicycle.braking() – This line access the method braking()
We have mentioned the word method quite a few times. You will learn about Java methods in detail
in the next paragraph.

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.

In Java, there are two types of methods:


i) User-defined Methods: We can create our own method based on our requirements.
ii) Standard Library Methods: These are built-in methods in Java that are available to use. (We
have discussed this)

Declaring a Java Method


The syntax to declare a method is: i) returnType - It specifies what type of value a method
returns. For example if a method has an int return type then
returnType methodName() { it returns an integer value. If the method does not return a
// method body value, its returntype is void. In the example, returnType is
} int. We use return keyword to give out result from method.
5
ii) methodName - It is an identifier that is used to refer to the
For example, particular method in a program. In the example,
int addNumbers() { methodName is addNumbers().
// code iii) method body - It includes the programming statements that
} are used to perform some tasks. The method body is
enclosed inside the curly braces { }. In the example,
method body is code.

The complete syntax of declaring a method is


modifier static returnType nameOfMethod (parameter1, parameter2, ...) {
// method body
}

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();

class Main { class Main {


// create a method // create a method
public int addNumbers(int a, int b) {
int sum = a + b; public static int square(int num) {
// return value // return statement
return sum; return num * num;
} }

public static void main(String[] args) { public static void main(String[] args) {
int num1 = 25,num2 = 15; int result;

// create an object of Main // call the method


Main obj = new Main(); // store returned value to result
// calling method result = square(10);
int result = obj.addNumbers(num1, num2);
System.out.println("Sum is: " + result); System.out.println("Squared value of 10 is: " +
} result);
} }
}
Output Output:
Sum is: 40 Squared value of 10 is: 100
6
Method Parameters in Java
A method parameter is a value accepted by the method. As mentioned earlier, a method can also
have any number of parameters. If we pass any other data type instead of the declared type for the
parameter, the compiler will throw an error. It is because Java is a strongly typed language.
For example, Example 3: Method Parameters
class Main {
// method with two parameters // method with no parameter
int addNumbers(int a, int b) { public void display1() {
// code System.out.println("Method without parameter");
} }
// method with no parameter // method with single parameter
int addNumbers(){ public void display2(int a) {
// code System.out.println("Method with a single
} parameter: " + a); }
If a method is created with parameters, we public static void main(String[] args) {
need to pass the corresponding values while Main obj = new Main(); // create object Main
calling the method. For example, obj.display1(); // calling method with no parameter
// calling the method with two parameters obj.display2(24); // call method with single parameter
addNumbers(25, 15); }}
Output
// calling the method with no parameters Method without parameter
addNumbers(); Method with a single parameter: 24

JAVA METHOD OVERLOADING


In Java, two or more methods may have For example:
the same name if they differ in
parameters (different number of void func() { ... }
parameters, different types of parameters, void func(int a) { ... }
or both). float func(double a) { ... }
float func(int a, float b) { ... }
These methods are called overloaded
methods and this feature is called method Here, the func() method is overloaded. These methods
overloading. have the same name but accept different arguments.

Let’s look at a real-world example:


class HelperService { public static void main(String[] args) {
HelperService hs = new HelperService();
private String formatNumber(int value) { System.out.println(hs.formatNumber(500));
return String.format("%d", value);
} System.out.println(hs.formatNumber(89.9934));

private String formatNumber(double value) { System.out.println(hs.formatNumber("550"));


return String.format("%.3f", value); }
} }

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

What is a Constructor? Example 1: Java Constructor


A constructor in Java is similar to a method class Main {
that is invoked when an object of the class is private String name;
created.
// constructor
Unlike Java methods, a constructor has the Main() {
same name as that of the class and does not System.out.println("Constructor Called:");
have any return type. For example, name = "Engr MOWEMI";
}
class Test {
Test() { public static void main(String[] args) {
// constructor body // constructor is invoked while
} // creating an object of the Main class
} Main obj = new Main();
Here, Test() is a constructor. It has the same System.out.println("The name is " + obj.name);
name as that of the class and doesn't have a }
return type. }
Output:

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.

Notice the statement of creating an object of the Main class.


Main obj = new Main();
Here, when the object is created, the Main() constructor is called. And, the value of the name
variable is initialized.

Hence, the program prints the value of the name variables as Engr MOWEMI.

Types of Constructor 2. Java Parameterized Constructor


In Java, constructors can be divided into 3 types: A Java constructor can also accept one or more
i) No-Arg Constructor parameters. Such constructors are known as
ii) Parameterized Constructor parameterized constructors (constructor with
iii) Default Constructor parameters).

1. Java No-Arg Constructors Example 3: Parameterized constructor


Similar to methods, a Java constructor may or class Main {
may not have any parameters (arguments).
String languages;
If a constructor does not accept any parameters,
it is known as a no-argument constructor. For // constructor accepting single value
example, Main(String lang) {
private Constructor() { languages = lang;
// body of the constructor System.out.println(languages + "
} Programming Language");
}
Example 2: Java private no-arg constructor
class Main { public static void main(String[] args) {
8
int i; // call constructor by passing a single value
Main obj1 = new Main("Java");
// constructor with no parameter Main obj2 = new Main("Python");
private Main() { Main obj3 = new Main("C");
i = 5; }
System.out.println("Constructor is called"); }
}
public static void main(String[] args) { Output:
// calling constructor without any parameter
Main obj = new Main(); Java Programming Language
System.out.println("Value of i: " + obj.i); Python Programming Language
} C Programming Language
}
Output:
Constructor is called
Value of i: 5

3. Java Default Constructor Output:


If we do not create any constructor, the Java
compiler automatically create a no-arg a = 0
constructor during the execution of the program. b = false
This constructor is called default constructor.
Here, we haven't created any constructors.
Example 4: Default Constructor Hence, the Java compiler automatically creates
class Main { the default constructor.

int a; The default constructor initializes any


boolean b; uninitialized instance variables with default
values.
public static void main(String[] args) {
Advantages and Disadvantages of Recursion
// A default constructor is called When a recursive call is made, new storage
Main obj = new Main(); locations for variables are allocated on the stack.
As, each recursive call returns, the old variables
System.out.println("Default Value:"); and parameters are removed from the stack.
System.out.println("a = " + obj.a); Hence, recursion generally uses more memory
System.out.println("b = " + obj.b); and is generally slow. On the other hand, a
} recursive solution is much simpler and takes less
} time to write, debug and maintain.

JAVA RECURSION

In Java, a method that calls itself How Recursion works?


is known as a recursive method.
And, this process is known as
recursion.
A physical world example would
be to place two parallel mirrors
facing each other. Any object in
between them would be reflected
recursively.
9
Ex.: Factorial of a Number Using Recursion In the above example, we have a method named
class Factorial { factorial(). The factorial() is called from the
static int factorial( int n ) { main() method. with the number variable passed
if (n != 0) // termination condition as an argument.
return n * factorial(n-1); // recursive call
else Here, notice the statement,
return 1; return n * factorial(n-1);
} The factorial() method is calling itself. Initially,
the value of n is 4 inside factorial(). During the
public static void main(String[] args) { next recursive call, 3 is passed to the factorial()
int number = 4, result; method. This process continues until n is equal to
result = factorial(number); 0.
System.out.println(number + " factorial = "
+ result); } } When n is equal to 0, the if statement returns
false hence 1 is returned. Finally, the
Output: accumulated result is passed to the main()
4 factorial = 24 method.

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). }

The extends keyword is used to perform }


inheritance in Java. For example,
class Dog extends Animal {
class Animal {
// methods and fields public void display() {
} System.out.println("My name is " + name);
}
// use of extends keyword to perform inheritance }
class Dog extends Animal { class Main {
public static void main(String[] args) {
// methods and fields of Animal Dog labrador = new Dog();
// methods and fields of Dog
} // access field of superclass
labrador.name = "Rohu";
In the above example, the Dog class is created by labrador.display();
inheriting the methods and fields from the
Animal class. // call method of superclass
// using object of subclass
Here, Dog is the subclass and Animal is the labrador.eat();
superclass. }
}

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 METHOD OVERRIDING

Java Overriding Rules Method Overriding in Java Inheritance


 Both the superclass and the subclass must If the same method is present in both the
have the same method name, the same superclass and subclass, what will happen?
return type and the same parameter list.
 We cannot override the method declared In this case, the method in the subclass overrides
as final and static. the method in the superclass.
 We should always override abstract
methods of the superclass. A method that
doesn't have its body (or block code { })
is known as an abstract method. E.g:
abstract void display();

Example on Inheritance super Keyword in Java Inheritance


class Animal { The super keyword is used to call the method of
// method in the superclass the parent class from the method of the child
public void eat() { class.
System.out.println("I can eat");
} Example 3: super Keyword in Inheritance
} class Animal {
// method in the superclass
class Dog extends Animal { public void eat() {
// overriding the eat() method System.out.println("I can eat"); }}
@Override
public void eat() { class Dog extends Animal {
System.out.println("I eat dog food"); // overriding the eat() method
}} @Override
public void eat() {
class Main { // call method of superclass
public static void main(String[] args) { super.eat();
// create an object of the subclass System.out.println("I eat dog food"); }}
Dog labrador = new Dog();
class Main {
// call the eat() method public static void main(String[] args) {
labrador.eat(); // create an object of the subclass
}} Dog labrador = new Dog();
// call the eat() method Output
Output labrador.eat();
I can eat
I eat dog food }}
I eat dog food 11
Why use inheritance?
1. The most important use of inheritance in Java is code reusability. The code that is present in
the parent class can be directly used by the child class.
2. Method overriding is also known as runtime polymorphism. Hence, we can achieve
Polymorphism in Java with the help of inheritance.
Types of inheritance
There are five types of inheritance.
1. Single Inheritance: In single inheritance, a single subclass extends from a single superclass.
2. Multilevel Inheritance: In multilevel inheritance, a subclass extends from a superclass and then the
same subclass acts as a superclass for another class.
3. Hierarchical Inheritance: In hierarchical inheritance, multiple subclasses extend from a single
superclass.
4. Multiple Inheritance: In multiple inheritance, a single subclass extends from multiple superclasses.
5. Hybrid Inheritance: Hybrid inheritance is a combination of two or more types of inheritance.

JAVA EXCEPTIONS

An exception is an unexpected event that occurs Java Exception hierarchy


during program execution. It affects the flow of Here is a simplified diagram of the exception
the program instructions which can cause the hierarchy in Java.
program to terminate abnormally. An exception
can occur for many reasons.
Some of them are: (1) Invalid user input (2)
Device failure (3) Loss of network connection
(4) Physical limitations (out of disk memory) (5)
Code errors (6) Opening an unavailable file.
Errors Exceptions
Errors represent irrecoverable conditions such as Exceptions can be caught and handled by the
Java virtual machine (JVM) running out of program. When an exception occurs within a
memory, memory leaks, stack overflow errors, method, it creates an object. This object is called
library incompatibility, infinite recursion, etc. the exception object. It contains information
Errors are usually beyond the control of the about the exception such as the name and
programmer and we should not try to handle description of the exception and state of the
errors. program when the exception occurred.

Java Exception Types


The exception hierarchy also has two branches: RuntimeException and IOException.
1. RuntimeException 2. IOException
A runtime exception happens due to a programming error. They An IOException is also known as
are also known as unchecked exceptions. These exceptions are a checked exception. They are
not checked at compile-time but run-time. Some of the common checked by the compiler at the
runtime exceptions are: compile-time and the programmer
i. Improper use of an API - IllegalArgumentException is prompted to handle these
ii. Null pointer access (missing the initialization of a exceptions. Some of the examples
variable) - NullPointerException of checked exceptions are:
iii. Out-of-bounds array access - i. Trying to open a file that
ArrayIndexOutOfBoundsException doesn’t exist results in
iv. Dividing a number by 0 – ArithmeticException FileNotFoundException
ii. Trying to read past the end
You can think about it in this way. “If it is a runtime exception, of a file
it is your fault”.

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

OVERVIEW OF I/O STREAMS

To bring in information, a program opens Similarly, a program can send information to an


a stream on an information source (a file, external destination by opening a stream to a
memory, a socket) and reads the information destination and writing the information out
sequentially, as shown here: sequentially, like this:

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

 open a stream  open a stream


 while more information  while more information
read information write information
 close the stream  close the stream

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).

JAVA FILE HANDLING

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

public class CreateFile {


public static void main(String[] args) {
try {
File myObj = new File("filename.txt");
if (myObj.createNewFile()) {
System.out.println("File created: " + myObj.getName());
} else {
System.out.println("File already exists.");
}
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
The output will be:
File created: filename.txt

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

public class WriteToFile {


public static void main(String[] args) {
try {
FileWriter myWriter = new FileWriter("filename.txt");
myWriter.write("Files in Java might be tricky, but it is fun enough!");
myWriter.close();
System.out.println("Successfully wrote to the file.");
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
The output will be:
Successfully wrote to the file.

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

public class ReadFile {


public static void main(String[] args) {
try {
File myObj = new File("filename.txt");
Scanner myReader = new Scanner(myObj);
while (myReader.hasNextLine()) {
String data = myReader.nextLine();
System.out.println(data);
}
myReader.close();
} catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
The output will be:
Files in Java might be tricky, but it is fun enough!

Get File Information


To get more information about a file, use any of the File methods:
Example:
import java.io.File; // Import the File class

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;

public class DeleteFolder {


public static void main(String[] args) {
File myObj = new File("C:\\Users\\MyName\\Test");
if (myObj.delete()) {
System.out.println("Deleted the folder: " + myObj.getName());
} else {
System.out.println("Failed to delete the folder.");
}
}}
The output will be:
Deleted the folder: Test

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.

Steps to designing a Swing GUI in NetBeans IDE:


1. Creating a Project: To create a new Yele application project:
i. Choose File > New Project. Alternately, you can click the New Project icon in the
IDE toolbar.
ii. In the Categories pane, select the Java node and in the Projects pane, choose Java
Application. Click Next.
iii. Enter JFsample as the Project Name field and specify the project location.
iv. Leave the Use Dedicated Folder for Storing Libraries checkbox unselected.
v. Ensure that the Set as Main Project checkbox is selected and clear the Create Main
Class field.
vi. Click Finish.

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.

The GUI Builder’s various windows include:


i) Design Area: The GUI Builder’s primary window for creating and editing Java GUI forms.
The toolbar’s Source button enables you to view a class’s source code, the Design button
allows you to view a graphical view of the GUI components, the History button allows you to
access the local history of changes of the file. The additional toolbar buttons provide
convenient access to common commands, such as choosing between Selection and
Connection modes, aligning components, setting component auto-resizing behavior, and
previewing forms.

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.

Adding Components: The Basics


1. To add a JPanel: In the Palette window, select the Panel component from the Swing
Containers category. The JPanel component appears in the JFsample form with orange
highlighting signifying that it is selected.
2. Resize the JPanel
3. To add title borders to the JPanels:
a. Select the top JPanel in the GUI Builder.
b. In the Properties window, click the ellipsis button (…) next to the Border property.
c. In the JPanel Border editor that appears, select the TitledBorder node in the Available
Borders pane.
d. In the Properties pane below, enter Name for the Title property.
e. Click the ellipsis (…) next to the Font property, select Bold for the Font Style, and
enter 12 for the Size. Click OK to exit the dialogs.
4. Adding Individual Components to the Form and resize accordingly: JLabel, JTextField,
JButton, etc.
5. Set Individual components' properties.
6. Attach codes to components...
7. Press Ctrl-S to save the file.

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.

Properties of Servlets are:


 It works on the server side.
 It capable of handling complex requests
obtained from the webserver.

How Servlet Works


i) The clients send the request to the webserver.
ii) The webserver receive the request.
iii) The webserver passes the request to the corresponding servlet through web deployment
(web.xml) in web container.
iv) The servlet processes the request and generates the response in the form of output.
v) The servlet sends the response back to the webserver.
vi) The webserver sends the response back to the web browser and the client browser displays it
on the screen.

JAVA Servlet Life-Cycle


The Java Servlet Life cycle includes three stages right from its start to the end until the Garbage
Collector clears it. These three stages are described below.
(1) init() (2) service() (3) destroy()

1. init(): The init() is the germinating stage of 2. service()


any Java Servlet. When a URL specific to a The service() method is the heart of the life cycle
particular servlet is triggered, the init() method is of a Java Servlet. Right after the Servlet's
invoked. With every server starting up, the initialization, it encounters the service requests
corresponding servlets also get started, and so from the client end.
does the init() method. The client may request various services like:
One important specialty of the init() method is  GET
the init() method only gets invoked once in the  PUT
entire life cycle of the Servlet, and the init()  UPDATE
method will not respond to any of the user's  DELETE
commands. The service() method takes responsibility to
The init() method Syntax: check the type of request received from the client
public void init() throws ServletException { and respond accordingly by generating a new
//init() method initializing thread or a set of threads per the requirement and
} implementing the operation through the
3. destroy() following methods.
Like the init() method, the destroy() method is  doGet() for GET
also called only once in the Java Servlet's entire  doPut() for PUT
life cycle. When the destroy() method is called,  doUpdate() for UPDATE
the Servlet performs the cleanup activities like,
 doDelete() for DELETE
 Halting the current or background threads
 Making a recovery list of any related data The service() method Syntax:
like cookies to Disk. public void service(ServletRequest request,
After that, the Servlet is badged, ready for the ServletResponse response) throws
Garbage collector to have it cleared. ServletException, IOException {
The destroy() method Syntax: //service() body
public void destroy() { }
//destroy() method finalizing }
21
Java Servlet Features
The Java Servlets carry over the features of Java Programming Language. The key features offered
by the Java Servlets are as follows: (i) Portable (ii) Efficient (iii) Scalable (iv) Robust
i. Portable ii. Efficient
The Java Servlet, by its nature, provides an
The Servlet program designed in one Operating instantaneous response to the client's request.
System's Platform can be run in a different Also, it can be portable and perform in every
Operating System Platform with ease. environmental condition regardless of the
operating system platform.
iii. Scalable iv. Robust
We consider Java Servlets to be highly scalable. The Java Servlets are best known for their robust
Servlets use completely lightweight threads for operating procedures. The servlets extend the
the processes and can simultaneously handle features of Java, which include.
multiple client requests by generating various 1. Java Security Manager
threads. 2. Java Garbage Collector
3. Exception Handling.

The Java Servlets operate in the form of Requests and Responses

Java Servlet Response


The second important part is the Response phase. The HttpResponse object is used to represent the
HTTP response to your request. A web application sends back a response page to the user to respond
to the HTTP request from the browser sent to your web application.

Java Servlet Advantages Java Servlet Disadvantages


The following are the significant Advantages of The following are the disadvantages of the Java
Java Servlets: Servlets:
i) Servlets create dynamic documents that i) Designing Java Servlets is known to be
are easier to write and faster to run. complicated.
ii) Servlets inherit the powerful features of ii) Java Servlets are heavy and sometimes
JAVA viz. Exception handling, Garbage slow down application performance.
collection & Java Security

How to Create a Servlet Using Netbeans & Glassfish / Tomcat


STEP 1: Click New Project Java Servlet Example
STEP 2: Choose Program
(i) Category: Select JAVA web <!DOCTYPE html>
(ii) Select Program (e.g. Web Application)
(iii) Click Next <html>
STEP 3: Name and Location <head>
(i) Project Name (e.g. ServletProject) <title>TODO supply a title</title>
(ii) Project Location (state the URL/path) <meta charset="UTF-8">
(iii) Click Next <meta name="viewport"
STEP 4: Server and Settings Server: content="width=device-width, initial-
(i) Select server (e.g. Glassfish, Tomcat, etc.) scale=1.0">
(ii) Java EE Version (e.g. JAVA EE 5)
(iii) Click Next </head>
STEP 5: Frameworks <body>
(i) Select frameworks you wish to use in your <div>TODO write content</div>
web application. </body>
(ii) Click Finish </html>

22

You might also like