S3 Java2020
S3 Java2020
Name : ……………………………………………………………………………………………
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:
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
6.Multithreaded
7.Dynamic
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)’.
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.
15.High Performance
1. Primitive data types: The primitive data types include boolean, char, byte,
short, int, long, float and double.
Integers Floating
• In Java language, primitive data types are the building blocks of data
manipulation. These are
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.
1.2 Numbers
( 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;
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
Examples of non-primitive types are Strings, Arrays, Classes, Interface, etc. You
will learn more about these in a later chapter.
1.Widening Casting
2.Narrowing Casting
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
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.
Java defines several bitwise operators, which can be applied to the integer types,
long, int, short, char, and byte.
-----------------
a&b = 0000
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.
Show Examples
Operator Description Example
6.Miscellaneous Operators
There are few other operators supported by Java Language.
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 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)
{
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.");
}
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
}
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 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.
The while loop loops through a block of code as long as a specified condition is
true:
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++;
}
Example
int i = 0;
do
System.out.println(i)
; i++;
}
while (i < 5);
{
// code block to be executed
}
Statement 1 is executed (one time) before the execution of the code block.
Statement 3 is executed (every time) after the code block has been executed.
{
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:
{
// code block to be executed
}
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.
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) {
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"};
Array Length
To find out how many elements an array has, use the length property:
Example
Example
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"}; for (int i = 0; i < cars.length;
i++)
{
System.out.println(cars[i]);
}
Multidimensional Arrays
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.
class_name()
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:
Bike is created
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.
class Student4
{
int id;
String name;
Student4(int i,String n)
{
id = i;
name = n;
}
void display()
{
System.out.println(id+" "+name);
}
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
• 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);
}
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 −
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.
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>
</html>
Declaration
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.
• 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 {
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
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
{
.....
.....
}
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);
}
}
}
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
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?
Syntax
Interface interfacename
{
Interface methods();
}
Example
interface
printable
{
void print();
}
class A6 implements printable
{
public void print()
{
System.out.println("Hello");
}
{
A6 obj = new A6();
obj.print();
}
}
interface Printable
{
void print();
}
interface Showable
{
void show();
}
class A7 implements Printable,Showable
{
public void
print(){System.out.println("Hello");}
public void
show(){System.out.println("Welcome")
}
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");
}
}
class Dog extends Animal
{
public void move() {
System.out.println("Dogs can walk and run");
}
}
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.
• 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
class Adder
{
static int add(int a, int b)
{
return a+b;
}
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.
1. Abstract class
2. Interface
In this example, Bike is an abstract class that contains only one abstract method
run. Its implementation is provided by the Honda class.
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.
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.
interface printable
{
void print();
}
class A6 implements printable
{
public void print()
{
System.out.println("Hello");
}
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.
//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?
• 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.
________________________________________//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.
• In this page, we will learn about Java exceptions, its type and the difference
between checked and unchecked exceptions.
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.
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.
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...");
}
}
1. Checked Exception
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
3) Error
try
{
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.
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.
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.
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
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
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.
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
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().
Runnable interface
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.
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.lang Language support classes. They include classes for primitive types,
string, math functions, thread and exceptions.
Input/output support classes. They provide facilities for the input and
java.io
output of data.
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.
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.
OutputStream class
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.
The java.awt package provides classes for AWT api such as TextField, Label,
TextArea, RadioButton, CheckBox, Choice, List etc.
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.
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()
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.
The javax.swing package provides classes for java swing API such as JButton,
JTextField, JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.
There are many differences between java awt and swing that are given below.
1)AWT components are platform-dependent. Java swing components are platform independent.
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.
Types of Event
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:
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.
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.
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).
• 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.