0% found this document useful (0 votes)
11 views

S3 Java2020

Java 2020 notes

Uploaded by

mammusidhiq
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

S3 Java2020

Java 2020 notes

Uploaded by

mammusidhiq
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 65

CP1344: PROGRAMMING IN JAVA

CP1344: PROGRAMMING IN JAVA


S3 Bachelor in Computer Applications

Name : ……………………………………………………………………………………………

Candidate Code: ……………………………………………………………………………..

S3 Bachelor in Computer Applications 1


CP1344: PROGRAMMING IN JAVA

Module I: A simple Java Application, a simple Java Applet , Brief History of Java,
Special Features of Java, Data Type & Operators in Java, Arrays, Objects, the
Assignment Statement, Arithmetic Operators, Relational and Logical Operators in
Java, control Structures, The Java Class, Constructor, Finalizers, Classes inside
classes: composition

History of Java

• Java Programming Language was written by James Gosling along with two
other person ‘Mike Sheridan‘ and ‘Patrick Naughton‘, while they were
working at Sun Microsystems.
• It was Initially it was named oak .
• The latest Releases is : Java Version 1.8 is the current stable release which
was released this year (2015).
• Java is implemented over a number of places in modern world. It is
implemented as Standalone Application, Web Application, Enterprise
Application and Mobile Application. Games, Smart Card, Embedded
System, Robotics, Desktop, etc.

Five Goals which were taken into consideration while developing Java:

1. Keep it simple, familiar and object oriented.


2. Keep it Robust and Secure.
3. Keep it architecture-neural and portable.
4. Executable with High Performance.
5. Interpreted, threaded and dynamic

Special Features of Java


1.General Purpose
Java capabilities are not limited to any specific application domain rather it can be
used in various application domain and hence it is called General Purpose
Programming Language.

S3 Bachelor in Computer Applications 2


CP1344: PROGRAMMING IN JAVA

2.Class based
Java is a class based/oriented programming language which means Java supports
inheritance feature of object-oriented Programming Language.

3.Object oriented
Java is object-oriented means software developed in Java are combination of
different types of object.

4.Platform Independent
A Java code will run on any JVM (Java Virtual Machine). Literally you can run
same Java code on
Windows JVM, Linux JVM, Mac JVM or any other JVM practically and get same
result every time
5.Architecturally Neutral

A Java code is not dependent upon Processor Architecture. A Java Application


compiled on 64 bit architecture of any platform will run on 32 bit (or any other
architecture) system without any issue.

6.Multithreaded

A thread in Java refers to an independent program. Java supports multithread


which means Java is capable of running many tasks simultaneously, sharing the
same memory.

7.Dynamic

Java is a Dynamic programming language which means it executes many


programming behavior at Runtime and don’t need to be passed at compile time as
in the case of static programming.

8.Distributed

Java Supports distributed System which means we can access files over Internet
just by calling the methods.

9.Portable

A Java program when compiled produce bytecodes. Bytecodes are magic. These
bytecodes can be transferred via network and can be executed by any JVM, hence
came the concept of ‘Write once, Run Anywhere(WORA)’.

S3 Bachelor in Computer Applications 3


CP1344: PROGRAMMING IN JAVA

10.Robust

Java is a robust programming Language which means it can cope with error while
the program is executing as well as keep operating with abnormalities to certain
extent. Automatic Garbage collection, strong memory management, exception
handling and type checking further adds to the list.

11.Interpreted

Java is a compiled programming Language which compiles the Java program into
Java byte codes. This JVM is then interpreted to run the program.

12.Security

Unlike other programming Language where Program interacts with OS using User
runtime environment of OS, Java provides an extra layer of security by putting
JVM between Program and OS.

13.Simple Syntax

Java is an improved c++ which ensures friendly syntax but with removed
unwanted features and inclusion of Automatic Garbage collection.

14.High Level Programming Language

Java is a High Level Programming Language the syntax of which is human


readable. Java lets programmer to concentrate on what to achieve and not how to
achieve. The JVM converts a Java Program to Machine understandable language.

15.High Performance

Java make use of Just-In-Time compiler for high performance. Just-In-Time


compiler is a computer program that turns Java byte codes into instructions that
can directly be sent to compilers.

Data Types in Java


Data types specify the different sizes and values that can be stored in the variable.
There are two types of data types in Java:

1. Primitive data types: The primitive data types include boolean, char, byte,
short, int, long, float and double.

S3 Bachelor in Computer Applications 4


CP1344: PROGRAMMING IN JAVA

2. Non-primitive data types: The non-primitive data types include Classes,

Interfaces, and Arrays. DataType

Primitive Non primitive

Boolean Numbers Characters

Integers Floating

1.Byte 1.Float 1.Char 1.Class


2.Short 2.Double 2.String 2.Interfaces
3.Int 3.Array
4.Long

1.Java Primitive Data Types

• In Java language, primitive data types are the building blocks of data
manipulation. These are

the most basic data types available in Java language.


• A primitive data type specifies the size and type of variable values, and it
has no additional methods.
1.1 Booleans

A boolean data type is declared with the boolean keyword and can only take the
values true or false:

Example :

boolean a= true;
boolean b= false;
System.out.println(a); // Outputs true
System.out.println(b); // Outputs false

Boolean values are mostly used for conditional testing, which you will learn more
about in a later chapter.

S3 Bachelor in Computer Applications 5


CP1344: PROGRAMMING IN JAVA

1.2 Numbers

Primitive number types are divided into two groups:

• Integer types stores whole numbers, positive or negative (such as 123 or -


456), without decimals. Valid types are byte, short, int and long. Which
type you should use, depends on the numeric value.
• Floating point types represents numbers with a fractional part, containing
one or more decimals. There are two types: float and double.

( I )Integer Types
1.Byte
Thebyte data type can store whole numbers from -128 to 127. This canint or other
be used instead of
integer types to save memory when you are certain that the value will be within -
128 and 127:
Example: byte a = 100;
2.Short
Theshort data type can store whole numbers from -32768 to 32767:
Example : short a = 5000;

3.Int
Theint data type can store whole numbers from -2147483648 to 2147483647.In
general, and in our
tutorial, int data type is the preferred data type when we create variables with a
the numeric value.
int a= ;
100000

4.Long
Thelong data type can store whole numbers from -9223372036854775808 to
9223372036854775807.
This is used when int is not large enough to store the value. Note that you should
end the value with an
"L":
Example : long a = 15000000000L;

S3 Bachelor in Computer Applications 6


CP1344: PROGRAMMING IN JAVA

( II )Floating Point Types

You should use a floating point type whenever you need a number with a decimal,
such as 9.99 or 3.14515.

1.Float
Thefloat data type can store fractional numbers from 3.4e−038 to 3.4e+038. Note
that you should end
the value with an "f":
Eg:float a= 5.75f;

2.Double
Thedouble data type can store fractional numbers from 1.7e−308 to 1.7e+038. Note
that you should
end the value with a "d":
Eg:double a= 19.99d;

1.3 Characters
1.char
Thechar data type is used to store a single character. The character must be
surrounded by single
quotes, like 'A' or 'c':
char a = 'B';

2.Strings
TheString data type is used to store a sequence of characters (text). String values
must be surrounded
by double quotes:

Example
String greeting = "Hello World";
2.Non-Primitive Data Types

Non-primitive data types are called reference types because they refer to objects.

The main difference between primitive and non-primitive data types are:
• Primitive types are predefined (already defined) in Java. Non-primitive types
are created by the

S3 Bachelor in Computer Applications 7


CP1344: PROGRAMMING IN JAVA

programmer and is not defined by JavaString).


(except for
• Non-primitive types can be used to call methods to perform certain
operations, while primitive
types cannot.
• A primitive type has always a value, while non-null.
primitive types can be
• A primitive type starts with a lowercase letter, while non-primitive types
starts with an
uppercase letter.
• The size of a primitive type depends on the data type, while non-primitive
types have all the same size.

Examples of non-primitive types are Strings, Arrays, Classes, Interface, etc. You
will learn more about these in a later chapter.

Java Type Casting


Type casting is when you assign a value of one primitive data type to another
type.

In Java, there are two types of casting:

1. Widening Casting (automatically) - converting a smaller type to a


larger type size byte -> short -> char -> int -> long -> float ->
double

2. Narrowing Casting (manually) - converting a larger type to a


smaller size type double -> float -> long -> int -> char -> short ->
byte

1.Widening Casting

Widening casting is done automatically when passing a smaller size type to a


larger size type:
int a = 9;
double b = a; // Automatic casting: int to double
System.out.println(a); // Outputs 9
System.out.println(b); // Outputs 9.0

S3 Bachelor in Computer Applications 8


CP1344: PROGRAMMING IN JAVA

2.Narrowing Casting

Narrowing casting must be done manually by placing the type in parantheses in


front of the value:

double a = 9.78; int b= (int) a; //


Manual casting: double to int

System.out.println(myDouble); // Outputs 9.78


System.out.println(myInt); // Outputs 9

Java Operators
Java provides a rich set of operators to manipulate variables. We can divide all
the Java operators into the following groups −

1. Arithmetic Operators
2. Relational Operators
3. Bitwise Operators
4. Logical Operators
5. Assignment Operators
6. Misc Operators

1.The Arithmetic Operators


Arithmetic operators are used in mathematical expressions in the same way that
they are used in algebra. The following table lists the arithmetic operators − Assume
integer variable A holds 10 and variable B holds 20, then −
Operator Description Example

+ (Addition) Adds values on either side of the operator. A + B will give


30

- (Subtraction) Subtracts right-hand operand from left-hand A - B will give -10


operand.
* Multiplies values on either side of the operator. A * B will give
(Multiplication) 200

S3 Bachelor in Computer Applications 9


CP1344: PROGRAMMING IN JAVA

/ (Division) Divides left-hand operand by right-hand B / A will give


operand. 2
% (Modulus) Divides left-hand operand by right-hand B % A will give
operand and returns remainder. 0
++ (Increment) Increases the value of operand by 1. B++ gives 21

-- (Decrement) Decreases the value of operand by 1. B-- gives


19

2.The Relational Operators


There are following relational operators supported by Java language.

Assume variable A holds 10 and variable B holds 20, then −

Show Examples
Operator Description Example

== (equal to) Checks if the values of two operands are equal or not, (A == B) is not
if yes then condition becomes true. true.

!= (not equal Checks if the values of two operands are equal or not, (A != B) is
to) if values are not equal then condition becomes true. true.

> (greater Checks if the value of left operand is greater than the (A > B) is not
than) value of right operand, if yes then condition becomes true.
true.

< (less than) Checks if the value of left operand is less than the (A < B) is true.
value of right operand, if yes then condition becomes
true.

>= (greater Checks if the value of left operand is greater than or


(A >= B) is not
than or equal equal to the value of right operand, if yes then
true.
to) condition becomes true.
<= (less than Checks if the value of left operand is less than or equal (A <= B) is
or equal to) to the value of right operand, if yes then condition true.
becomes true.
3.The Bitwise Operators

S3 Bachelor in Computer Applications 10


CP1344: PROGRAMMING IN JAVA

Java defines several bitwise operators, which can be applied to the integer types,
long, int, short, char, and byte.

Bitwise operator works on bits and performs bit-by-bit operation. Assume if a = 60


and b = 13; now in binary format they will be as follows − a = 0011 1100 b = 0000
1101

-----------------

a&b = 0000

1100 a|b = 0011

1101 a^b =

0011 0001

~a = 1100 0011
4.The Logical Operators
The following table lists the logical operators −

Assume Boolean variables A holds true and variable B holds false, then −

Show Examples
Operator Description Example
&& (logical Called Logical AND operator. If both the (A && B) is false
and) operands are non-zero, then the condition
becomes true.
|| (logical or) Called Logical OR Operator. If any of the (A || B) is true
two operands are non-zero, then the
condition becomes true.

! (logical Called Logical NOT Operator. Use to !(A && B) is true


not) reverses the logical state of its operand. If a
condition is true then Logical NOT operator
will make false.

S3 Bachelor in Computer Applications 11


CP1344: PROGRAMMING IN JAVA

5.The Assignment Operators


Following are the assignment operators supported by Java language −

Show Examples
Operator Description Example

= Simple assignment operator. Assigns values from C = A + B will


right side operands to left side operand. assign value of A
+ B into C
+= Add AND assignment operator. It adds right C += A is
operand to the left operand and assign the result to equivalent to
left operand. C=C+A

-= Subtract AND assignment operator. It subtracts C -= A is


right operand from the left operand and assign the equivalent to
result to left operand. C=C–A
*= Multiply AND assignment operator. It multiplies C *= A is
right operand with the left operand and assign the equivalent to
result to left operand. C=C*A

/= Divide AND assignment operator. It divides left C /= A is


operand with the equivalent to

right operand and assign the result to left operand. C=C/A

%= Modulus AND assignment operator. It takes C %= A is


modulus using two operands and assign the result to equivalent to
left operand. C=C%A

6.Miscellaneous Operators
There are few other operators supported by Java Language.

6.1 Conditional Operator ( ? : )


Conditional operator is also known as the ternary operator. This operator consists
of three operands and is used to evaluate Boolean expressions. The goal of the
operator is to decide, which value should be assigned to the variable.

S3 Bachelor in Computer Applications 12


CP1344: PROGRAMMING IN JAVA

6.2 instanceof Operator


This operator is used only for object reference variables. The operator checks
whether the object is of a particular type (class type or interface type). instanceof
operator is written as −

( Object reference variable ) instanceof (class/interface type)


If the object referred by the variable on the left side of the operator passes the IS-
A check for the class/interface type on the right side, then the result will be true.
Following is an example −

Java Syntax
In the previous chapter, we created a Java file called MyClass.java, and we used
the following code to print "Hello World" to the screen:

MyClass.java

public class MyClass

{
public static void main(String[] args)

{
System.out.println("Hello World");
}
}
Control Structures
I .Conditional
Statements 1.1 The if
Statement
Use f statement to specify a block of Java code to be executedtrue.
the i if a condition is
Syntax:
if (condition)
{
// block of code to be executed if the condition is true
}

Example:
if (20 > 18)

S3 Bachelor in Computer Applications 13


CP1344: PROGRAMMING IN JAVA

{
System.out.println("20 is greater
than 18"); }
1.2 If else Statement
Use the else statement to specify a block of code to be executed if the condition is false inside the if
block.
Syntax:
if (condition)
{
// block of code to be executed if the condition is true
}
else
{
// block of code to be executed if the condition is false
}
Example
: int time
= 20; if
(time <
18)
{
System.out.println("Good
day."); }

else

{
System.out.println("Good evening.");
}

1.3 The else if Statement

Use the else if statement to specify a new condition if the first condition is false.
Syntax
if (condition1)
{
// block of code to be executed if condition1 is true
} else if (condition2)
{
// block of code to be executed if the condition1 is false and condition2 is true
}

S3 Bachelor in Computer Applications 14


CP1344: PROGRAMMING IN JAVA

else
{
// block of code to be executed if the condition1 is false and condition2 is false
}

Example
: int time
= 22; if
(time <
10)
{
System.out.println("Good morning.");
} else if (time < 20)
{
System.out.println("Good day.");
}
Else
{
System.out.println("Good evening.");
}
// Outputs "Good evening."
1.4 Switch Statements

Use the switch statement to select one of many code blocks to be executed.

switch(expression)
{
case x:
// code
block
break;
case y: //
code block
break;
default: //
code block
}
This is how it works:

• The switch expression is evaluated once.


• The value of the expression is compared with the values of each case.
S3 Bachelor in Computer Applications 15
CP1344: PROGRAMMING IN JAVA

• If there is a match, the associated block of code is executed.


• The break and default keywords are optional, and will be described later in
this chapter

The example below uses the weekday number to calculate the weekday name:

int day = 4;
switch (day) {
case 1:

System.out.println("Mond
ay"); break; case 2:

System.out.println("Tuesd
ay"); break; case 3:

System.out.println("Wednes
day"); break; case 4:

System.out.println("Thurs
ay"); break; case 5:

System.out.println("Frid
ay"); break; case 6:

System.out.println("Saturd
ay"); break; case 7:

System.out.println("Sunday");
break;
}
// Outputs "Thursday" (day 4)

Java Loops
Loops can execute a block of code as long as a specified condition is reached.

1.Java While Loop

The while loop loops through a block of code as long as a specified condition is
true:

S3 Bachelor in Computer Applications 16


CP1344: PROGRAMMING IN JAVA

Syntax
while (condition)

{
// code block to be executed
}
In the example below, the code in the loop will run, over and over again, as long
as a variable (i) is less than 5:
Example
int i =0;
while(i < 5)
{

System.out.println(i)
; i++;
}

2.The Do/While Loop


Thedo/while loop is a variantwhile loop. This loop will execute the code block
of the once, before
checking if the condition is true, then it will repeat the loop as long as the condition
is true.
Syntax
do
{
// code block to be executed
}
while (condition);

Example
int i = 0;
do

System.out.println(i)
; i++;
}
while (i < 5);

S3 Bachelor in Computer Applications 17


CP1344: PROGRAMMING IN JAVA

3.Java For Loop


When you know exactly how many times you want to loop through a block of code,
use the for loop instead of a while loop:
Syntax
for (statement 1; statement 2; statement 3)

{
// code block to be executed
}

Statement 1 is executed (one time) before the execution of the code block.

Statement 2 defines the condition for executing the code block.

Statement 3 is executed (every time) after the code block has been executed.

The example below will print the numbers 0 to 4:


Example
for (int i = 0; i < 5; i++)

{
System.out.println(i);
}
Example explained
Statement 1 sets a variable before the loop starts (int i = 0).
Statement 2 defines the condition for the loop to run (i must be less than 5). If the
condition is true, the loop will start over again, if it is false, the loop will end.
Statement 3 increases a value (i++) each time the code block in the loop has been
executed.

4.For-Each Loop

There is also a "for-each" loop, which is used exclusively to loop through elements in
an array:

for (type variable : arrayname)

{
// code block to be executed

S3 Bachelor in Computer Applications 18


CP1344: PROGRAMMING IN JAVA

}
The following example outputs all elements in the cars array, using a "for-each" loop:
Example
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (String i : cars)

{
System.out.println(i);
}
Java Break and Continue
Java Break

You have already seen the break statement used in an earlier chapter of this tutorial. It
was used to "jump out" of a switch statement.

The break statement can also be used to jump out of a loop.

This example jumps out of the loop when i is equal to 4:


Example
for (int i = 0; i < 10; i++)
{
if (i == 4)
{
break;
}

System.out.println(i);
}
Java Continue
Thecontinue statement breaks one iteration (in the loop), if a specified condition
occurs, and continues
with the next iteration in the loop.
This example skips the value of 4:
Example
for (int i = 0; i < 10; i++)
{ if (i ==
4) {

S3 Bachelor in Computer Applications 19


CP1344: PROGRAMMING IN JAVA

continue;
}
System.out.println(i);
}
Java Arrays

• Arrays are used to store multiple values in a single variable, instead of declaring
separate variables for each value.
• To declare an array, define the variable type with square brackets:
• String[] cars;

• We have now declared a variable that holds an array of strings. To insert values
to it, we can use an array literal - place the values in a comma-separated list,
inside curly braces: String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};

To create an array of integers, you could write:

int[] myNum = {10, 20, 30, 40};

Access the Elements of an Array

• You access an array element by referring to the index number.


• This statement accesses the value of the first element in cars:

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};


System.out.println(cars[0]);

Array Length

To find out how many elements an array has, use the length property:
Example

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};


System.out.println(cars.length);
// Outputs 4

Loop Through an Array


You can loop through the arrayfor loop, and uselengthproperty to specify
elements with the the how

S3 Bachelor in Computer Applications 20


CP1344: PROGRAMMING IN JAVA

many times the loop should run.


The following example outputs all elements in the cars array:

Example

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"}; for (int i = 0; i < cars.length;
i++)

{
System.out.println(cars[i]);
}

Multidimensional Arrays

• A multidimensional array is an array containing one or more arrays.


• To create a two-dimensional array, add each array within its own set of curly
braces:
Example
int[][] a= { {1, 2, 3, 4}, {5, 6, 7} };

myNumbers is now an array with two arrays as its elements.

To access the elements of the a array, specify two indexes: one for the array, and one
for the element inside that array. This example accesses the third element (2) in the
second array (1) of a:
Example
int[][] a = { {1, 2, 3, 4}, {5, 6, 7} };
int x = a[1][2];
System.out.println(x); // Outputs 7

Constructor
Constructor in java is a special type of method that is used to initialize the object.Java
constructor is invoked at the time of object creation. It constructs the values i.e.
provides data for the object that is why it is known as constructor.

Rules for creating java constructor

There are basically two rules defined for the constructor.

S3 Bachelor in Computer Applications 21


CP1344: PROGRAMMING IN JAVA

• Constructor name must be same as its class name


• Constructor must have no explicit return type
Types of java constructors : There are two types of constructors:

1. Default constructor (no-argu constructor)


2. Parameterized constructor

1. Java Default Constructor


A constructor that have no parameter is known as default constructor.

Syntax of default constructor:

class_name()

Example of default constructor

In this example, we are creating the no-arg constructor in the Bike class. It will be
invoked at the time of object creation.

class Bike1
{
Bike1()
{
System.out.println("Bike is created");
} public static void
main(String args[])
{
Bike1 b=new Bike1();
}
}

Output:

S3 Bachelor in Computer Applications 22


CP1344: PROGRAMMING IN JAVA

Bike is created

Q) What is the purpose of default constructor?

Default constructor provides the default values to the object like 0, null etc.
depending on the type. Example of default constructor that displays the default
values

class Student3
{
int
id;
String name;
void display()
{
System.out.println(id+" "+name);
}
public static void main(String args[])
{
Student3 s1=new Student3();
Student3 s2=new
Student3();
s1.display();
s2.display();
}
}
Output:
0 null
0 null

Explanation:In the above class,you are not creating any constructor so compiler
provides you a default constructor.Here 0 and null values are provided by default
constructor.

S3 Bachelor in Computer Applications 23


CP1344: PROGRAMMING IN JAVA

2.Java parameterized constructor


• A constructor that have parameters is known as parameterized constructor.
• Parameterized constructor is used to provide different values to the distinct
objects.
• In this example, we have created the constructor of Student class that have
two parameters. We can have any number of parameters in the constructor.

class Student4
{
int id;
String name;
Student4(int i,String n)
{
id = i;
name = n;
}
void display()
{
System.out.println(id+" "+name);
}

public static void main(String args[])


{
Student4 s1 = new
Student4(111,"Karan");
Student4 s2 = new
Student4(222,"Aryan");
s1.display(); s2.display();
}
}
Output:
111 Karan
222 Aryan
Constructor Overloading in Java
Constructor overloading is a technique in Java in which a class can have any
number of constructors that differ in parameter lists.The compiler differentiates

S3 Bachelor in Computer Applications 24


CP1344: PROGRAMMING IN JAVA

these constructors by taking into account the number of parameters in the list and
their type. Example of Constructor Overloading

class Student5
{
int id;
String name;
int age;
Student5(int i,String n)
{
id = i;
name = n;
}
Student5(int i,String n,int a)
{
id = i;
name = n;
age=a;
}
void display()
{
System.out.println(id+" "+name+" "+age);
}
public static void main(String args[])
{
Student5 s1 = new
Student5(111,"Karan"); Student5
s2 = new Student5(222,"Aryan",25);
s1.display(); s2.display();
}
}
Output:
111 Karan 0
222 Aryan 25

Java Copy Constructor


• There is no copy constructor in java. But, we can copy the values of one
object to another like copy constructor in C++.

S3 Bachelor in Computer Applications 25


CP1344: PROGRAMMING IN JAVA

• There are many ways to copy the values of one object into another in java.
• They are:
In this example, we are going to copy the values of one object into another using
java constructor.

class Student6
{
int id;
String name;
Student6(int i,String n)
{
id = i;
name = n;
}

Student6(Student6 s)
{ id
= s.id;
name =s.name;
}
void display()
{
System.out.println(id+" "+name);
}

public static void main(String args[])


{
Student6 s1 = new Student6(111,"Karan");
Student6 s2 = new
Student6(s1);
s1.display();
s2.display();
}
}
Output:
111 Karan
111 Karan
Q) Does constructor return any value?

S3 Bachelor in Computer Applications 26


CP1344: PROGRAMMING IN JAVA

Ans:yes, that is current class instance (You cannot use return type yet it returns a
value).

Applet in java
An applet is a Java program that runs in a Web browser. An applet can be a fully
functional Java application because it has the entire Java API at its disposal.

There are some important differences between an applet and a standalone Java
application, including the following −

• An applet is a Java class that extends the java.applet.Applet class.


• A main() method is not invoked on an applet, and an applet class will not
define main().
• Applets are designed to be embedded within an HTML page.
• When a user views an HTML page that contains an applet, the code for the
applet is downloaded to the user's machine.
• A JVM is required to view an applet. The JVM can be either a plug-in of the
Web browser or a separate runtime environment.
• The JVM on the user's machine creates an instance of the applet class and
invokes various methods during the applet's lifetime.
• Applets have strict security rules that are enforced by the Web browser. The
security of an applet is often referred to as sandbox security, comparing the
applet to a child playing in a sandbox with various rules that must be
followed.
• Other classes that the applet needs can be downloaded in a single Java
Archive (JAR) file.

Life Cycle of an Applet


Four methods in the Applet class gives you the framework on which you build any
serious applet −

1. init − This method is intended for whatever initialization is needed for your
applet. It is called after the param tags inside the applet tag have been
processed.
2. start − This method is automatically called after the browser calls the init
method. It is also called whenever the user returns to the page containing the
applet after having gone off to other pages.

S3 Bachelor in Computer Applications 27


CP1344: PROGRAMMING IN JAVA

3. stop − This method is automatically called when the user moves off the page
on which the applet sits. It can, therefore, be called repeatedly in the same
applet.
4. destroy − This method is only called when the browser shuts down
normally. Because applets are meant to live on an HTML page, you should
not normally leave resources behind after a user leaves the page that contains
the applet.
5. paint − Invoked immediately after the start() method, and also any time the
applet needs to repaint itself in the browser. The paint() method is actually
inherited from the java.awt.

Example:

Import java.applet.*;
import java.awt.*;
public class myapplet extends Applet
{
public void paint (Graphics g) {
g.drawString ("Hello World", 25, 50);
}
}
Invoking an Applet
An applet may be invoked by embedding directives in an HTML file and viewing
the file through an applet viewer or Java-enabled browser.

The <applet> tag is the basis for embedding an applet in an HTML file. Following
is an example that invokes the "Hello, World" applet −

<html>

<applet code = "HelloWorldApplet.class" width = "320" height = "120">

</applet>

</html>

S3 Bachelor in Computer Applications 28


CP1344: PROGRAMMING IN JAVA

Finalize or Finalizer in Java


The java.lang.Object.finalize() is called by the garbage collector on an object when
garbage collection determines that there are no more references to the object. A
subclass overrides the finalize method to dispose of system resources or to perform
other cleanup.

Declaration

Following is the declaration for java.lang.Object.finalize() method

protected void finalize()

• There is no parameters in Finalizer method.


• This method does not have any return a value.
• Exception raised by this method is throwable

Nested Classes
In Java, just like methods, variables of a class too can have another class as its
member. Writing a class within another is allowed in Java. The class written within
is called the nested class, and the class that holds the inner class is called the outer
class.

Following is the syntax to write a nested class. Here, the class Outer_Demo is the
outer class and the class Inner_Demo is the nested class.

class Outer_Demo
{
class Nested_Demo
{
}
}
Inner Classes
• Inner Classes (Non-static Nested Classes)
• Inner classes are a security mechanism in Java.
• We know a class cannot be associated with the access modifier private, but if
we have the class as a member of other class, then the inner class can be
made private. And this is also used to access the private members of a class.

S3 Bachelor in Computer Applications 29


CP1344: PROGRAMMING IN JAVA

• Inner classes are of three types depending on how and where you define
them. They are −
• Creating an inner class is quite simple. You just need to write a class within
a class. Unlike a class, an inner class can be private and once you declare an
inner class private, it cannot be accessed from an object outside the class.
• Following is the program to create an inner class and access it. In the given
example, we make the inner class private and access the class through a
method. Example

class Outer_Demo
{
int num;
// inner
class
private class Inner_Demo
{
public void print()
{
System.out.println("This is an inner class");
}
}
// Accessing he inner class from the method
within void display_Inner()
{
Inner_Demo inner = new Inner_Demo();
inner.print();
}
}
public class My_class {

public static void main(String args[]) {


// Instantiating the outer class
Outer_Demo outer = new Outer_Demo();

// Accessing the display_Inner() method.


outer.display_Inner();
}
}

S3 Bachelor in Computer Applications 30


CP1344: PROGRAMMING IN JAVA

Here you can observe that Outer_Demo is the outer class, Inner_Demo is the inner
class, display_Inner() is the method inside which we are instantiating the inner
class, and this method is invoked from the main method.
If you compile and execute the above program, you will get the

following result − Output

This is an inner class.

Module II: Inheritance & Interface, Deriving Classes, Method Over-riding,


Method Overloading, Access Modifiers, Abstract Class and Method,
Interfaces, Packages, Imports and Class Path.

Inheritance
Inheritance can be defined as the process where one class acquires the properties
(methods and fields) of another. With the use of inheritance the information is
made manageable in a hierarchical order.

The class which inherits the properties of other is known as subclass (derived class,
child class) and the class whose properties are inherited is known as superclass
(base class, parent class). extends Keyword
extends is the keyword used to inherit the properties of a class. Following is
the syntax of extends keyword Syntax

class A
{
.....
.....
}
class B extends A
{
.....

S3 Bachelor in Computer Applications 31


CP1344: PROGRAMMING IN JAVA

.....
}
Following is an example demonstrating Java inheritance. In this example, you can
observe two classes namely Calculation and My_Calculation.
Using extends keyword, the My_Calculation inherits the methods addition() and
Subtraction() of Calculation class.

class Calculation
{
int z;
public void addition(int x, int y)
{
z = x + y;
System.out.println("The sum of the given numbers:"+z);
}
public void Subtraction(int x, int y)
{
z = x - y;
System.out.println("The difference between the given numbers:"+z);
}
}

public class My_Calculation extends Calculation


{
public void multiplication(int x, int y)
{
z = x * y;
System.out.println("The product of the given numbers:"+z);
}

public static void main(String args[])


{
int a = 20, b = 10;
My_Calculation demo = new
My_Calculation(); demo.addition(a,
b); demo.Subtraction(a, b);
demo.multiplication(a, b);
}

S3 Bachelor in Computer Applications 32


CP1344: PROGRAMMING IN JAVA

}
Output
The sum of the given numbers:30
The difference between the given numbers:10
The product of the given numbers:200

Super Keyword

• The super keyword is similar to this keyword. Following are the scenarios
where the super keyword is used.
• It is used to differentiate the members of superclass from the members of
subclass, if they have same names.
• It is used to invoke the superclass constructor from subclass.
Differentiating the Members

If a class is inheriting the properties of another class. And if the members of the
superclass have the names same as the sub class, to differentiate these variables we
use super keyword as shown below.

super.variable

super.method();

Types of Inheritance

S3 Bachelor in Computer Applications 33


CP1344: PROGRAMMING IN JAVA

Interface in Java
• An interface in java is a blueprint of a class. It has static constants and
abstract methods.
• The interface in java is a mechanism to achieve abstraction. There can be
only abstract methods in the java interface not method body. It is used to
achieve abstraction and multiple inheritance in Java.
• Java Interface also represents IS-A relationship.
• It cannot be instantiated just like abstract class.
Why use Java interface?

1. It is used to achieve abstraction.


2. By interface, we can support the functionality of multiple inheritance.
3. It can be used to achieve loose coupling.

Syntax

Interface interfacename
{
Interface methods();
}

Example
interface
printable
{
void print();
}
class A6 implements printable
{
public void print()
{
System.out.println("Hello");
}

public static void main(String args[])

S3 Bachelor in Computer Applications 34


CP1344: PROGRAMMING IN JAVA

{
A6 obj = new A6();
obj.print();
}
}

Multiple inheritance in Java by interface


If a class implements multiple interfaces, or an interface extends multiple interfaces
i.e. known as multiple inheritance.

interface Printable
{
void print();
}
interface Showable
{
void show();
}
class A7 implements Printable,Showable
{
public void
print(){System.out.println("Hello");}

S3 Bachelor in Computer Applications 35


CP1344: PROGRAMMING IN JAVA

public void
show(){System.out.println("Welcome")
}

public static void


main(String args[]){ A7 obj
= new A7(); obj.print();
obj.show();
}
}
Output:
Hello
Welcome

Multiple inheritance is not supported through class in java but it is possible by


interface, why?

As we have explained in the inheritance chapter, multiple inheritance is not


supported in case of class because of ambiguity. But it is supported in case of
interface because there is no ambiguity as implementation is provided by the
implementation class. For example:

Method- Overriding
• If a class inherits a method from its superclass, then there is a chance to
override the method provided that it is not marked final.
• The benefit of overriding is: ability to define a behavior that's specific to the
subclass type, which means a subclass can implement a parent class method
based on its requirement.
• In object-oriented terms, overriding means to override the functionality of an
existing method.

Example

class Animal
{
public void move()
{
System.out.println("Animals can move");

S3 Bachelor in Computer Applications 36


CP1344: PROGRAMMING IN JAVA

}
}
class Dog extends Animal
{
public void move() {
System.out.println("Dogs can walk and run");
}
}

public class TestDog


{

public static void main(String args[])


{
Animal a = new Animal(); // Animal reference and object
Animal b = new Dog(); // Animal reference but Dog object

a.move(); // runs the method in Animal class


b.move(); // runs the method in Dog class
}
}
This will produce the following result −

Output
Animals can move
Dogs can walk and run

Method Overloading
Method overloading is the way of implementing static/compile time polymorphism
in java. Method overloading means more than one methods in a class with same
name but different parameters. Parameters can be differing in types, numbers or
order.

Advantage of method overloading

• Method overloading increases the readability of the program.


• So, we perform method overloading to figure out the program quickly.

S3 Bachelor in Computer Applications 37


CP1344: PROGRAMMING IN JAVA

Different ways to overload the method

1. By changing the no. of arguments


2. By changing the data ty

1) Method Overloading: changing no. of arguments

• In this example, we have created two methods, first add() method performs
addition of two numbers and second add method performs addition of three
numbers.
• In this example, we are creating static methods so that we don't need to
create instance for calling methods.

class Adder
{
static int add(int a,int b)
{
return a+b;
}
static int add(int a,int b,int c)
{
return a+b+c;
}
}
class TestOverloading1
{
public static void main(String[] args)
{
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}
}
Output:
22
33

S3 Bachelor in Computer Applications 38


CP1344: PROGRAMMING IN JAVA

2) Method Overloading: changing data type of arguments


In this example, we have created two methods that differs in data type. The first
add method receives two integer arguments and second add method receives two
double arguments.

class Adder
{
static int add(int a, int b)
{
return a+b;
}

static double add(double a, double b)


{
return a+b;
}
}
class TestOverloading2
{
public static void main(String[] args)
{
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(12.3,12.6));
}
}
Output:
22
24.9

Abstraction in Java
• Abstraction is a process of hiding the implementation details and showing
only functionality to the user.
• Another way, it shows only essential things to the user and hides the internal
details, for example, sending SMS where you type the text and send the
message. You don't know the internal processing about the message delivery.
• Abstraction lets you focus on what the object does instead of how it does it.

There are two ways to achieve abstraction in java

S3 Bachelor in Computer Applications 39


CP1344: PROGRAMMING IN JAVA

1. Abstract class
2. Interface

Abstract class in Java


A class which is declared as abstract is known as an abstract class. It can have
abstract and non-abstract methods. It needs to be extended and its method
implemented. It cannot be instantiated.

o An abstract class must be declared with an abstract keyword.


o It can have abstract and non-abstract methods.
o It cannot be instantiated.
o It can have constructors and static methods also. o It can have final
methods which will force the subclass not to change the body of the method.

Example of abstract class

In this example, Bike is an abstract class that contains only one abstract method
run. Its implementation is provided by the Honda class.

abstract class Bike


{
abstract void run();
}
class Honda4 extends Bike
{
void run()
{
System.out.println("Abstrcat method running safely");
}
public static void main(String args[])
{
Bike obj = new Honda4();
obj.run();
}
}
Test it Now

S3 Bachelor in Computer Applications 40


CP1344: PROGRAMMING IN JAVA

OUTPUT: Abstrcat method running safely

Interface in Java
• An interface in java is a blueprint of a class. It has static constants and
abstract methods.
• The interface in Java is a mechanism to achieve abstraction. There can be
only abstract methods in the Java interface, not method body. It is used to
achieve abstraction and multiple inheritance in Java.
• In other words, you can say that interfaces can have abstract methods and
variables. It cannot have a method body.
• Java Interface also represents the IS-A relationship.
• It cannot be instantiated just like the abstract class.

There are mainly three reasons to use interface. They are given below.

o It is used to achieve abstraction.


o By interface, we can support the functionality of multiple
inheritance. o It can be used to achieve loose coupling.
How to declare an interface?

An interface is declared by using the interface keyword. It provides total


abstraction; means all the methods in an interface are declared with the empty
body, and all the fields are public, static and final by default. A class that
implements an interface must implement all the methods declared in the interface.

Syntax:

interface <interface_name>
{
// declare constant fields
// declare methods that abstract
// by default.
}
Java Interface Example

In this example, the Printable interface has only one method, and its
implementation is provided in the A6 class.

S3 Bachelor in Computer Applications 41


CP1344: PROGRAMMING IN JAVA

interface printable
{
void print();
}
class A6 implements printable
{
public void print()
{
System.out.println("Hello");
}

public static void main(String args[])


{
A6 obj = new A6();
obj.print();
}
}

Java Package
• A java package is a group of similar types of classes, interfaces and sub-
packages.
• Package in java can be categorized in two form, built-in package and user-
defined package.
• There are many built-in packages such as java, lang, awt, javax, swing, net, io,
util, sql etc.
• Here, we will have the detailed learning of creating and using user-defined
packages.

Advantage of Java Package


1) Java package is used to categorize the classes and interfaces so that they can be
easily maintained.
2) Java package provides access protection.
3) Java package removes naming collision.

S3 Bachelor in Computer Applications 42


CP1344: PROGRAMMING IN JAVA

The package keyword is used to create a package in java.

//save as
Simple.java
package mypack;
public class Simple
{
public static void main(String args[])
{
System.out.println("Welcome to package");
}
}
How to access package from another package?

• We can invoke package in our program Using packagename.*

S3 Bachelor in Computer Applications 43


CP1344: PROGRAMMING IN JAVA

• If you use package.* then all the classes and interfaces of this package will
be accessible but not subpackages.
• The import keyword is used to make the classes and interface of another
package accessible to the current package.

Example of package that import the packagename.*

STEP 1: Create Package


//save by A.java
package pack;
public class A
{
public void msg()
{
System.out.println("Hello");
}
}

S3 Bachelor in Computer Applications 44


CP1344: PROGRAMMING IN JAVA

STEP 2: Call Package to Program

________________________________________//save by
B.java

package
mypack;
import pack.*;
class B
{
public static void main(String args[])
{
A obj = new A();
obj.msg();
}
}
Output:Hello

Module III: Exception Handling, The Try-Catch Statement, Catching more than
one Exception, The Finally Clause, Generating Exceptions, Threads: Introduction,
Creating Threads in Applications, Method in Thread Class, Threads in Applets.

Exception Handling in Java


• The Exception Handling in Java is one of the powerful mechanism to
handle the runtime errors so that normal flow of the application can be
maintained.

S3 Bachelor in Computer Applications 45


CP1344: PROGRAMMING IN JAVA

• In this page, we will learn about Java exceptions, its type and the difference
between checked and unchecked exceptions.

What is Exception in Java

• Exception is an abnormal condition.


• In Java, an exception is an event that disrupts the normal flow of the
program. It is an object which is thrown at runtime.

What is Exception Handling

• Exception Handling is a mechanism to handle runtime errors such as


ClassNotFoundException, IOException, SQLException, RemoteException,
etc.

Advantage of Exception Handling

• The core advantage of exception handling is to maintain the normal flow


of the application. An exception normally disrupts the normal flow of the
application that is why we use exception handling.

Java Exception Keywords

There are 5 keywords which are used in handling exceptions in Java.


Keyword Description

try The "try" keyword is used to specify a block where we should place
exception code. The try block must be followed by either catch or
finally. It means, we can't use try block alone.

catch The "catch" block is used to handle the exception. It must be


preceded by try block which means we can't use catch block alone. It
can be followed by finally block later.
finally The "finally" block is used to execute the important code of the
program. It is executed whether an exception is handled or not.

throw The "throw" keyword is used to throw an exception.

S3 Bachelor in Computer Applications 46


CP1344: PROGRAMMING IN JAVA

throws
The "throws" keyword is used to declare exceptions. It doesn't throw an
exception. It specifies that there may occur an exception in the method.
It is always used with method signature.

Java Exception Handling Example


Let's see an example of Java Exception Handling where we using a try-catch
statement to handle the exception.

public class A
{
public static void main(String args[])
{
Try
{
//code that may raise
exception int data=100/0;
}
catch(ArithmeticException e)
{
System.out.println(e);
}
//rest code of the program
System.out.println("rest of the code...");
}
}

Types of Java Exceptions


There are mainly two types of exceptions: checked and unchecked. Here, an error is
considered as the unchecked exception. According to Oracle, there are three types
of exceptions:

1. Checked Exception

S3 Bachelor in Computer Applications 47


CP1344: PROGRAMMING IN JAVA

2. Unchecked Exception
3. Error

1) Checked Exception

The classes which directly inherit Throwable class except RuntimeException and
Error are known as checked exceptions e.g. IOException, SQLException etc.
Checked exceptions are checked at compiletime.

2) Unchecked Exception

The classes which inherit RuntimeException are known as unchecked exceptions


e.g. ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException etc. Unchecked exceptions are not checked at
compile-time, but they are checked at runtime.

3) Error

Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError,


AssertionError etc.

Java Multi-catch block


A try block can be followed by one or more catch blocks. Each catch block must
contain a different exception handler. So, if you have to perform different tasks at
the occurrence of different exceptions, use java multi-catch block.

o At a time only one exception occurs and at a time only one


catch block is executed. o All catch blocks must be ordered from
most specific to most general, i.e. catch for ArithmeticException must
come before catch for Exception.

Let's see a simple example of java multi-catch block.

public class MultipleCatchBlock1


{

public static void main(String[] args)


{

try

S3 Bachelor in Computer Applications 48


CP1344: PROGRAMMING IN JAVA

{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
}
Java finally block

• Java finally block is a block that is used to execute important code such as
closing connection, stream etc.
• Java finally block is always executed whether exception is handled or not.
• Java finally block follows try or catch block.

S3 Bachelor in Computer Applications 49


CP1344: PROGRAMMING IN JAVA

class TestFinallyBlock
{
public static void main(String args[])
{
try
{
int data=25/5;
System.out.println(data);
}
catch(NullPointerException e)
{
System.out.println(e);
}
finally
{
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
}
Output:
finally block is always
executed rest of the code...

Thread in java
A thread is a lightweight sub process, a smallest unit of processing. It is a separate
path of execution.Threads are independent, if there occurs exception in one thread,
it doesn't affect other threads. It shares a common memory area.

S3 Bachelor in Computer Applications 50


CP1344: PROGRAMMING IN JAVA

As shown in the above figure, thread is executed inside the process. There is
context-switching between the threads. There can be multiple processes inside the
OS and one process can have multiple threads.

Life cycle of a Thread (Thread States)

A thread can be in one of the five states. According to sun, there is only 4 states
in thread life cycle in javanew, runnable, non-runnable and terminated. There
is no running state.

But for better understanding the threads, we are explaining it in the 5 states.

The life cycle of the thread in java is controlled by JVM. The java thread states
are as follows:
1. New
2. Runnable
3. Running
4. Non-Runnable (Blocked)
5. Terminated

S3 Bachelor in Computer Applications 51


CP1344: PROGRAMMING IN JAVA

1) New

The thread is in new state if you create an instance of Thread class but before the
invocation of start() method.

2) Runnable

The thread is in runnable state after invocation of start() method, but the thread
scheduler has not selected it to be the running thread.

3) Running

The thread is in running state if the thread scheduler has selected it.

4) Non-Runnable (Blocked)

This is the state when the thread is still alive, but is currently not eligible to run.

5) Terminated

A thread is in terminated or dead state when its run() method exits.

S3 Bachelor in Computer Applications 52


CP1344: PROGRAMMING IN JAVA

How to create thread


There are two ways to create a thread:

1. By extending Thread class


2. By implementing Runnable interface.

1. Thread class:

Thread class provide constructors and methods to create and perform operations
on a thread.Thread class extends Object class and implements Runnable
interface.

Commonly used Constructors of Thread class:

o Thread() o
Thread(Strin
g name) o
Thread(Runn
able r) o
Thread(Runn
able r,String name)
Java Thread
Example by
extending Thread
class

class Multi extends Thread


{
public void run()
{
System.out.println("thread is running...");
}

S3 Bachelor in Computer Applications 53


CP1344: PROGRAMMING IN JAVA

public static void main(String args[])


{
Multi t1=new Multi();
t1.start();
}
}
Output:thread is running...
________________________________________

2.Runnable interface:

The Runnable interface should be implemented by any class whose instances are
intended to be executed by a thread. Runnable interface have only one method
named run().

1. public void run(): is used to perform action

for a thread. 2) Java Thread Example by implementing

Runnable interface

class Multi3 implements Runnable


{
public void run()
{
System.out.println("thread is running...");
}

public static void main(String args[])


{
Multi3 m1=new Multi3();
Thread t1 =new
Thread(m1);
t1.start();
}
}

S3 Bachelor in Computer Applications 54


CP1344: PROGRAMMING IN JAVA

Output:thread is running...

Starting a thread:

start() method of Thread class is used to start a newly created thread. It performs
following tasks:
o A new thread starts(with new callstack). o The thread
moves from New state to the Runnable state. o When the
thread gets a chance to execute, its target run() method will
run.

S3 Bachelor in Computer Applications 55


CP1344: PROGRAMMING IN JAVA

Module IV: Java APIs – overview of APIs, IO Packages, Java Input Stream Classes,
Java Output Stream Classes, File Class, Graphic & Sound: AWT and Swing,
Graphic methods, Fonts, Loading and Viewing Images, Loading and Playing
Sound, AWT & Event Handling, Layouts, JDBC.

API Packages
Java APl(Application Program Interface) provides a large numbers of classes
grouped into different packages according to functionality Following figure shows
the system packages that are frequently used in the programs.

Java System Packages and Their Classes

java.lang Language support classes. They include classes for primitive types,
string, math functions, thread and exceptions.

Language utility classes such as vectors, hash tables, random numbers,


java.util
data, etc.

Input/output support classes. They provide facilities for the input and
java.io
output of data.

java.applet Classes for creating and implementing applets.

java.net Classes for networking. They include classes for communicating with
local computers as well as with internet servers.

java.awt Set of classes for implementing graphical user interface. They include
classes for windows, buttons, lists, menus and so on.

S3 Bachelor in Computer Applications 56


CP1344: PROGRAMMING IN JAVA

Java I/O
Java I/O (Input and Output) is used to process the input and produce the output.
Java uses the concept of 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.

Stream
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 console.
1) System.out: standard output stream
2) System.in: standard input stream
3) System.err: standard error stream

OutputStream vs InputStream
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.

S3 Bachelor in Computer Applications 57


CP1344: PROGRAMMING IN JAVA

OutputStream class

OutputStream class is an abstract class. It is the super class of all classes


representing an output stream of bytes. An output stream accepts output bytes and
sends them to some sink.

Useful methods of OutputStream

Method Description
1) public void write(int)throws IOException is used to write a byte to the
current output stream.
2) public void write(byte[])throws is used to write an array of byte to the current
output
IOException stream.
3) public void flush()throws IOException flushes the current output stream.
4) public void close()throws IOException is used to close the current output stream.
OutputStream Hierarchy

InputStream class

InputStream class is an abstract class. It is the super class of all classes representing
an input stream of bytes.

Java AWT
Java AWT (Abstract Window Toolkit) is an API to develop GUI or window-based
applications in java.

S3 Bachelor in Computer Applications 58


CP1344: PROGRAMMING IN JAVA

Java AWT components are platform-dependent i.e. components are displayed


according to the view of operating system. AWT is heavyweight i.e. its
components are using the resources of OS.

The java.awt package provides classes for AWT api such as TextField, Label,
TextArea, RadioButton, CheckBox, Choice, List etc.

Java AWT Hierarchy

The hierarchy of Java AWT classes are given below.

Container

The Container is a component in AWT that can contain another components like
buttons, textfields, labels etc. The classes that extends Container class are known as
container such as Frame, Dialog and Panel.

S3 Bachelor in Computer Applications 59


CP1344: PROGRAMMING IN JAVA

Window

The window is the container that have no borders and menu bars. You must use
frame, dialog or another window for creating a window.

Panel

The Panel is the container that doesn't contain title bar and menu bars. It can have
other components like button, textfield etc.

Frame

The Frame is the container that contain title bar and can have menu bars. It can
have other components like button, textfield etc.

AWT Example

Let's see a simple example of AWT where we are inheriting Frame class. Here,
we are showing Button component on the Frame. import java.awt.*; class First
extends Frame

First()

Button b=new Button("click me");

b.setBounds(30,100,80,30);// setting button

position add(b);//adding button into frame

setSize(300,300);//frame size 300 width and 300

height setLayout(null);//no layout manager

setVisible(true);//now frame will be visible, by

default not visible

S3 Bachelor in Computer Applications 60


CP1344: PROGRAMMING IN JAVA

public static void main(String args[])

First f=new First();

Output

Java Swing
Java Swing tutorial is used to create window-based applications. It is built on the
top of AWT (Abstract Windowing Toolkit) API and entirely written in java.

Unlike AWT, Java Swing provides platform-independent and lightweight


components.

The javax.swing package provides classes for java swing API such as JButton,
JTextField, JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.

Difference between AWT and Swing

There are many differences between java awt and swing that are given below.

S3 Bachelor in Computer Applications 61


CP1344: PROGRAMMING IN JAVA

No. Java AWT Java Swing

1)AWT components are platform-dependent. Java swing components are platform independent.

2) AWT components are heavyweight. Swing components are lightweight.

3) AWT doesn't support pluggable look and feel. Swing supports pluggable
look and feel.
Swing provides more
powerful components such as tables, lists, 4) AWT provides less
components than Swing.
scrollpanes, colorchooser,
tabbedpane etc.

5) AWT doesn't follows MVC(Model View Controller) where Swing follows


MVC.
model represents data, view represents presentation and
controller acts as an interface between model and view.

Event Handling in AWT


Change in the state of an object is known as event i.e. event describes the change in
state of source. Events are generated as result of user interaction with the graphical
user interface components. For example, clicking on a button, moving the mouse,
entering a character through keyboard,selecting an item from list, scrolling the page
are the activities that causes an event to happen.

Types of Event

The events can be broadly classified into two categories:

• Foreground Events - Those events which require the direct interaction of


user.They are generated as consequences of a person interacting with the
graphical components in Graphical User Interface. For example, clicking on
a button, moving the mouse, entering a character through keyboard,selecting
an item from list, scrolling the page etc.
• Background Events - Those events that require the interaction of end user
are known as background events. Operating system interrupts, hardware or
software failure, timer expires, an operation completion are the example of
background events.

S3 Bachelor in Computer Applications 62


CP1344: PROGRAMMING IN JAVA

What is Event Handling?

Event Handling is the mechanism that controls the event and decides what should
happen if an event occurs. This mechanism have the code which is known as event
handler that is executed when an event occurs. Java Uses the Delegation Event
Model to handle the events. This model defines the standard mechanism to generate
and handle the events.Let's have a brief introduction to this model.

The Delegation Event Model has the following key participants namely:

• Source - The source is an object on which event occurs. Source is


responsible for providing information of the occurred event to it's handler.
Java provide as with classes for source object.
• Listener - It is also known as event handler.Listener is responsible for
generating response to an event. From java implementation point of view the
listener is also an object. Listener waits until it receives an event. Once the
event is received , the listener process the event an then returns.

The benefit of this approach is that the user interface logic is completely separated
from the logic that generates the event. The user interface element is able to delegate
the processing of an event to the separate piece of code. In this model ,Listener needs
to be registered with the source object so that the listener can receive the event
notification. This is an efficient way of handling the event because the event
notifications are sent only to those listener that want to receive them.

Steps involved in event handling

• The User clicks the button and the event is generated.


• Now the object of concerned event class is created automatically and
information about the source and the event get populated with in same
object.
• Event object is forwarded to the method of registered listener class.
• the method is now get executed and returns.

Java JDBC
Java JDBC is a java API to connect and execute query with the database. JDBC
API uses jdbc drivers to connect with the database.

S3 Bachelor in Computer Applications 63


CP1344: PROGRAMMING IN JAVA

Why use JDBC

Before JDBC, ODBC API was the database API to connect and execute query with
the database. But, ODBC API uses ODBC driver which is written in C language (i.e.
platform dependent and unsecured). That is why Java has defined its own API (JDBC
API) that uses JDBC drivers (written in Java language).

Common JDBC Components

The JDBC API provides the following interfaces and classes –

• DriverManager: This class manages a list of database drivers. Matches


connection requests from the java application with the proper database driver
using communication sub protocol. The first driver that recognizes a certain
subprotocol under JDBC will be used to establish a database Connection.
• Driver: This interface handles the communications with the database server.
You will interact directly with Driver objects very rarely. Instead, you use
DriverManager objects, which manages objects of this type. It also abstracts
the details associated with working with Driver objects.
• Connection: This interface with all methods for contacting a database. The
connection object represents communication context, i.e., all communication
with database is through connection object only.

S3 Bachelor in Computer Applications 64


CP1344: PROGRAMMING IN JAVA

• Statement: You use objects created from this interface to submit the SQL
statements to the database. Some derived interfaces accept parameters in
addition to executing stored procedures.
• ResultSet: These objects hold data retrieved from a database after you execute
an SQL query using Statement objects. It acts as an iterator to allow you to
move through its data.
• SQLException: This class handles any errors that occur in a database
application.

S3 Bachelor in Computer Applications 65

You might also like