Java Notes by g1

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 53

History of java

Java was originally developed by James Gosling at Sun


Microsystems. It was released in May 1995 as a core component of Sun
Microsystems' Java platform.

Major Features of Java Programming Language


 Simple.
 Object-Oriented.
 Platform Independent.
 Portable.
 Robust.
 Secure.
 Interpreted.
 Multi-Threaded.

C++ vs Java
There are many differences and similarities between the C++
programming language and Java. A list of top differences between
C++ and Java are given below:

copy

OOPs (Object-Oriented Programming System)


Object means a real-world entity such as a pen, chair, table, computer, watch,
etc. Object-Oriented Programming is a methodology or paradigm to design a
program using classes and objects. It simplifies software development and maintenance
by providing some concepts:

o Object
o Class
o Inheritance
o Polymorphism
o Abstraction
o Encapsulation

How to java work


Java works in the same way, compiling source code into
bytecode first. The Java Virtual Machine can then compile the
bytecode into machine code (JVM). The JVM allows Java's
bytecode to execute on any device

Compilation and execution


https://www.geeksforgeeks.org/compilation-
execution-java-program/
Structure of Java Program
Java is an object-oriented programming, platform-
independent, and secure programming language that makes it popular. Using the Java
programming language, we can develop a wide variety of applications. So, before diving
in depth, it is necessary to understand the basic structure of Java program in detail

Java virtual machine concept


https://www.geeksforgeeks.org/jvm-works-
jvm-architecture/
Primitive Data Types
A primitive data type specifies the size and type of variable values, and it has
no additional methods.

There are eight primitive data types in Java:

A constant is a data item whose value cannot change during the


program’s execution. Thus, as its name implies – the value is
constant.
A variable is a data item whose value can change during the
program’s execution. Thus, as its name implies – the value can vary.

Java Operators
Operators are used to perform operations on variables and values.

Java divides the operators into the following groups:

 Arithmetic operators
 Assignment operators
 Comparison operators
 Logical operators
 Bitwise operators
In Java, expression is the combination of values,
variables, operators, and method calls.

Branching Statements in Java


Branching statements are the statements used to jump the flow of execution
from one part of a program to another. The branching statements are mostly
used inside the control statements. Java has mainly three branching
statements, i.e., continue, break, and return. The branching
statements allow us to exit from a control statement when a certain condition
meet.

In Java, continue and break statements are two essential branching


statements used with the control statements.

The break statement breaks or terminates the loop and transfers the control
outside the loop.

The continue statement skips the current execution and pass the control to
the start of the loop.

The return statement returns a value from a method and this process will be
done explicitly.
Jumping
Jumping statements are control statements that transfer execution
control from one point to another point in the program. There are two
Jump statements that are provided in the Java programming language:
1. Break statement.
2. Continue statement

Loops in Java
Java Simple for Loop
1. Initialization: It is the initial condition which is executed once when the
loop starts. Here, we can initialize the variable, or we can use an already
initialized variable. It is an optional condition.
2. Condition: It is the second condition which is executed each time to test
the condition of the loop. It continues execution until the condition is
false. It must return boolean value either true or false. It is an optional
condition.
3. Increment/Decrement: It increments or decrements the variable value.
It is an optional condition.
4. Statement: The statement of the loop is executed each time until the
second condition is false.

Flowchart:

Object oriented programming


Object-oriented programming has several advantages over procedural
programming:
 OOP is faster and easier to execute
 OOP provides a clear structure for the programs
 OOP helps to keep the Java code DRY "Don't Repeat Yourself", and
makes the code easier to maintain, modify and debug
 OOP makes it possible to create full reusable applications with less
code and shorter development time

Classes and objects are the two main aspects of object-oriented


programming.

example:

class objects
Car Volvo

Audi

Toyota

So, a class is a template for objects, and an object is an instance of a


class.

Defining a Class in Java


Java provides a reserved keyword class to define a class. The keyword must be
followed by the class name. Inside the class, we declare methods and
variables.

In general, class declaration includes the following in the order as it appears:

1. Modifiers: A class can be public or has default access.


2. class keyword: The class keyword is used to create a class.
3. Class name: The name must begin with an initial letter (capitalized by
convention).
4. Superclass (if any): The name of the class's parent (superclass), if any,
preceded by the keyword extends. A class can only extend (subclass)
one parent.
5. Interfaces (if any): A comma-separated list of interfaces implemented
by the class, if any, preceded by the keyword implements. A class can
implement more than one interface.
6. Body: The class body surrounded by braces, { }.

Java Variables
A variable is a container which holds the value while the Java program is
executed. A variable is assigned with a data type.

Variable is a name of memory location. There are three types of variables in


java: local, instance and static.

There are two types of data types in Java: primitive and non-primitive.

Types of Variables
There are three types of variables in Java:

o local variable
o instance variable
o static variable
1) Local Variable

A variable declared inside the body of the method is called local variable. You
can use this variable only within that method and the other methods in the
class aren't even aware that the variable exists.

A local variable cannot be defined with "static" keyword.

2) Instance Variable

A variable declared inside the class but outside the body of the method, is
called an instance variable. It is not declared as static.

It is called an instance variable because its value is instance-specific and is not


shared among instances.

3) Static variable

A variable that is declared as static is called a static variable. It cannot be local.


You can create a single copy of the static variable and share it among all the
instances of the class. Memory allocation for static variables happens only
once when the class is loaded in the memory.

Method Declaration
The method declaration provides information about method attributes, such
as visibility, return-type, name, and arguments. It has six components that are
known as method header
Method Signature: Every method has a method signature. It is a part of the
method declaration. It includes the method name and parameter list.

Access Specifier: Access specifier or modifier is the access type of the


method. It specifies the visibility of the method. Java provides four types of
access specifier:

o Public: The method is accessible by all classes when we use public


specifier in our application.
o Private: When we use a private access specifier, the method is
accessible only in the classes in which it is defined.
o Protected: When we use protected access specifier, the method is
accessible within the same package or subclasses in a different package.
o Default: When we do not use any access specifier in the method
declaration, Java uses default access specifier by default. It is visible only
from the same package only.

Return Type: Return type is a data type that the method returns. It may have
a primitive data type, object, collection, void, etc. If the method does not
return anything, we use void keyword.

Method Name: It is a unique name that is used to define the name of a


method.

Parameter List: It is the list of parameters separated by a comma and


enclosed in the pair of parentheses. It contains the data type and variable
name. If the method has no parameter, left the parentheses blank.

Method Body: It is a part of the method declaration. It contains all the actions
to be performed. It is enclosed within the pair of curly braces.
Create an Object
In Java, an object is created from a class. We have already created the
class named Main, so now we can use this to create objects.

To create an object of Main, specify the class name, followed by the


object name, and use the keyword new:

Example
Create an object called "myObj" and print the value of x:

public class Main {

int x = 5;

public static void main(String[] args) {

Main myObj = new Main();

System.out.println(myObj.x);

Java Constructors
A constructor in Java is a special method that is used to initialize
objects. The constructor is called when an object of a class is created. It
can be used to set initial values for object attributes:

Java Default Constructor


A constructor is called "Default Constructor" when it doesn't have any
parameter.
Example
Create a constructor:

// Create a Main class

public class Main {

int x; // Create a class attribute

// Create a class constructor for the Main class

public Main() {

x = 5; // Set the initial value for the class attribute x

public static void main(String[] args) {

Main myObj = new Main(); // Create an object of class Main (This


will call the constructor)

System.out.println(myObj.x); // Print the value of x

// Outputs 5

Java Parameterized Constructor


A constructor which has a specific number of parameters is called a
parameterized constructor.
Example
public class Main {

int x;

public Main(int y) {

x = y;

public static void main(String[] args) {

Main myObj = new Main(5);

System.out.println(myObj.x);

// Outputs 5

Java Garbage Collection


In java, garbage means unreferenced objects.

Garbage Collection is process of reclaiming the runtime unused memory automatically.


In other words, it is a way to destroy the unused objects.

To do so, we were using free() function in C language and delete() in C++. But, in java it
is performed automatically. So, java provides better memory management.

Advantage of Garbage Collection


o It makes java memory efficient because garbage collector removes the
unreferenced objects from heap memory.
o It is automatically done by the garbage collector(a part of JVM) so we
don't need to make extra efforts.
String - String is an immutable class and its object can’t be modified after it
is created but definitely reference other objects. They are very useful in
multithreading environment because multiple threads can’t change the state
of the object so immutable objects are thread safe.
Stringbuffer - String buffer is mutable classes which can be used to do
operation on string object such as reverse of string, concating string and etc.
We can modify string without creating new object of the string. String buffer is
also thread safe.
o Also, string concat + operator internally uses StringBuffer or
StringBuilder class. Below are the differences.

Sr. Key String StringBuffer


No.

1 Basic String is an immutable class and String buffer is mutable


its object can’t be modified after it classes which can be
is created used to do operation
on string object

2 Methods Methods are not synchronized All methods are


synchronized in this
class.

3 Performance It is fast Multiple thread can’t


access at the same
time therefore it is slow

4. Memory Area If a String is created using Heap Space


constructor or method then those
strings will be stored in Heap
Memory as well as
SringConstantPool

Example of String
public class Main {
public static void main(String args[]) {
String s1 = "Hello Tutorials Point";
String upperCase = s1.toUpperCase();
System.out.println(upperCase);
}
}

Example of StringBuffer
public class StringBufferExample{
public static void main(String[] args){
StringBuffer buffer=new StringBuffer("Hi");
buffer.append("Java 8");
System.out.println("StringBufferExample" +buffer);
}
}

Wrapper classes in Java


The wrapper class in Java provides the mechanism to convert primitive into
object and object into primitive.

https://www.javatpoint.com/wrapper-class-in-java

USING JDK TOOLS


https://www.geeksforgeeks.org/jdk-in-java/

UNIT – 2
Inheritance
Inheritance is an important pillar of OOP(Object-Oriented
Programming). It is the mechanism in Java by which one class is
allowed to inherit the features(fields and methods) of another class. In
Java, Inheritance means creating new classes based on existing
ones. A class that inherits from another class can reuse the methods
and fields of that class. In addition, you can add new fields and
methods to your current class as well

Types of inheritance in java


On the basis of class, there can be three types of inheritance in java: single,
multilevel and hierarchical.

In java programming, multiple and hybrid inheritance is supported through


interface only. We will learn about interfaces later.

Note: Multiple inheritance is not supported in Java through class.

When one class inherits multiple classes, it is known as multiple inheritance.


For Example:
Why Do We Need Java Inheritance?
 Code Reusability: The code written in the Superclass is common
to all subclasses. Child classes can directly use the parent class
code.
 Method Overriding: Method Overriding is achievable only through
Inheritance. It is one of the ways by which Java achieves Run Time
Polymorphism.
 Abstraction: The concept of abstract where we do not have to
provide all details is achieved through inheritance. Abstraction only
shows the functionality to the user.

 Super Class/Parent Class: The class whose features are inherited


is known as a superclass(or a base class or a parent class).
 Sub Class/Child Class: The class that inherits the other class is
known as a subclass(or a derived class, extended class, or child
class). The subclass can add its own fields and methods in addition
to the superclass fields and methods.

How to Use Inheritance in Java?


The extends keyword is used for inheritance in Java.
.
Syntax :
class derived-class extends base-class
{ //methods and fields
}

Method Overloading
If a class has multiple methods having same name but different in parameters,
it is known as Method Overloading.

Method overloading increases the readability of the program.

Different ways to overload the method

There are two ways to overload the method in java


1. By changing number of arguments
2. By changing the data type

Abstract class in Java


A class which is declared with the abstract keyword is known as an abstract
class in Java. It can have abstract and non-abstract methods (method with the
body).

Java abstract class is a class that can not be initiated by itself, it needs
to be subclassed by another class to use its properties.

Illustration of Abstract class


abstract class Shape
{
int color;
// An abstract function
abstract void draw();
}

Interfaces
Another way to achieve abstraction in Java, is with interfaces.

An interface is a completely "abstract class" that is used to group


related methods with empty bodies:

The interface in Java is a mechanism to achieve abstraction. There


can be only abstract methods in the Java interface, not the 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.
// A simple interface
interface Player
{ final int id = 10;
int move();}

Multithreading in Java
Multithreading in Java is a process of executing multiple threads simultaneously.

A thread is a lightweight sub-process, the smallest unit of processing. Multiprocessing


and multithreading, both are used to achieve multitasking.

However, we use multithreading than multiprocessing because threads use a shared


memory area

Multithreading is a Java feature that allows concurrent execution of two or more


parts of a program for maximum utilization of CPU. Each part of such program
is called a thread. So, threads are light-weight processes within a process.
Threads can be created by using two mechanisms :
1. Extending the Thread class
2. Implementing the Runnable Interface

Thread creation by extending the Thread class


We create a class that extends the java.lang.Thread class. This class
overrides the run() method available in the Thread class. A thread begins its life
inside run() method. We create an object of our new class and call start()
method to start the execution of a thread. Start() invokes the run() method on
the Thread object.

Thread creation by implementing the Runnable Interface


We create a new class which implements java.lang.Runnable interface and
override run() method. Then we instantiate a Thread object and call start()
method on this object.

A thread goes through various stages in its lifecycle. For example, a thread is born,
started, runs, and then dies. The following diagram shows the complete life cycle of a
thread.
Following are the stages of the life cycle −

 New − A new thread begins its life cycle in the new state. It remains in this state
until the program starts the thread. It is also referred to as a born thread.
 Runnable − After a newly born thread is started, the thread becomes runnable.
A thread in this state is considered to be executing its task.
 Waiting − Sometimes, a thread transitions to the waiting state while the thread
waits for another thread to perform a task. Thread transitions back to the runnable
state only when another thread signals the waiting thread to continue executing.
 Timed Waiting − A runnable thread can enter the timed waiting state for a
specified interval of time. A thread in this state transitions back to the runnable
state when that time interval expires or when the event it is waiting for occurs.
 Terminated (Dead) − A runnable thread enters the terminated state when it
completes its task or otherwise terminates.

Thread synchronization

https://www.javatpoint.com/synchronization-in-
java

Thread scheduling

https://www.javatpoint.com/thread-scheduler-
in-java
Exceptions in Java
Exception Handling in Java is one of the effective means to handle the
runtime errors so that the regular flow of the application can be preserved. Java
Exception Handling is a mechanism to handle runtime errors such as
ClassNotFoundException, IOException, SQLException, RemoteException, etc.

Exception is an unwanted or unexpected event, which occurs during the


execution of a program, i.e. at run time, that disrupts the normal flow of the
program’s instructions. Exceptions can be caught and handled by the program.
When an exception occurs within a method, it creates an object. This object is
called the exception object. It contains information about the exception, such as
the name and description of the exception and the state of the program when
the exception occurred.
Major reasons why an exception Occurs
 Invalid user input
 Device failure
 Loss of network connection
 Physical limitations (out of disk memory)
 Code errors
 Opening an unavailable file

Errors represent irrecoverable conditions such as Java virtual machine (JVM)


running out of memory, memory leaks, stack overflow errors, library
incompatibility, infinite recursion, etc. Errors are usually beyond the control of
the programmer, and we should not try to handle errors.
Let us discuss the most important part which is the differences between Error
and Exception that is as follows:

 Error: An Error indicates a serious problem that a reasonable application


should not try to catch.
 Exception: Exception indicates conditions that a reasonable application
might try to catch.

Why does an Exception occur?


An exception can occur due to several reasons like a Network connection
problem, Bad input provided by a user, Opening a non-existing file in your
program, etc
Blocks & Keywords used for exception handling
1. try: The try block contains a set of statements where an exception can
occur.
try
{
// statement(s) that might cause exception
}

2. catch: The catch block is used to handle the uncertain condition of a try
block. A try block is always followed by a catch block, which handles the
exception that occurs in the associated try block.
catch
{
// statement(s) that handle an exception
// examples, closing a connection, closing
// file, exiting the process after writing
// details to a log file.
}
3. throw: The throw keyword is used to transfer control from the try block to the
catch block.
4. throws: The throws keyword is used for exception handling without try &
catch block. It specifies the exceptions that a method can throw to the caller
and does not handle itself.

UNIT – 3
Applet programming –
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 −
 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.

Life Cycle of an Applet


Four methods in the Applet class gives you the framework on which you build any
serious applet −
 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.

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

Local Applet
An applet developed locally and stored in a local system that is known as a Local
Applet. When a web page is trying to find a local applet, it doesn’t need to use the
Internet and the local system doesn’t require the Internet Connection.

Remote Applet
A remote applet is that which is developed by someone else and stored on a remote
computer connected to the Internet. If our system is connected to the Internet, we can
download the remote applet onto our system via the Internet.
Local Applet vs Remote Applet:
Local Applet Remote Applet

1. Local Applet is stored on our computer. 1. Remote Applet is not stored on our computer.

2. It is not required Internet Connection to access the 2. It is required Internet Connection to access the
applet. applet.

3. In a local applet, it don't need the applet's URL. 3. In a remote applet, it needs the applet's URL.

Application
 They are similar to Java programs.
 They can be executed independently without using web browser.
 It requires a ’main’ function for it to be executed.
 Java applications have full access to local file system and network.
 They can access all kinds of resources that are available to the system.
 They can execute the programs with the help of the local system.
 An application program is required when a task needs to be directly performed for
the user.

Applets
 They are small Java programs.
 They have been designed to be included with HTML documents.
 They need Java enabled web browser to be executed.
 It doesn’t need a main function to get executed.
 It doesn’t have local disk and network access.
 It can access the browser specific services only.
 They can’t access the local system.
 They can’t execute programs from local machines.
 It is required to perform small tasks or it can be used as a part of a task.

Take a moment to review the steps you took to create the Java applet. They will
be the same for every applet you make:

1. Write the Java code in a text file


2. Save the file
3. Compile the code
4. Fix any errors
5. Reference the applet in a HTML page
6. Run the applet by viewing the web page
Inserting applet in a web page-
Once you've written some code for your applet, you'll want to run your applet to test
it. To run an applet in a browser or in the JDK Applet Viewer, the applet needs to be
added to an HTML page, using the <APPLET> tag. You then specify the URL of the
HTML page to your browser or the Applet Viewer.
The Simplest Possible <APPLET> Tag
Here's the simplest form of the <APPLET> tag:
<APPLET CODE=AppletSubclass.class WIDTH=anInt HEIGHT=anInt>
</APPLET>

The HTML applet align attribute is used to specify the alignment of


the <applet> element or the content present inside the applet element.
Note: This attribute is not supported by HTML5.
Syntax:
<applet align="left | right | center | justify";>
Attribute Values:
 left: It sets the content to the left-align.
 right: It sets the content to the right-align.
 center: I sets the content element to the center.
 justify: It sets the content to the justify position.

Attributes: This tag accepts the following attributes:


 align: Specifies the alignment of an applet.
 alt: Specifies an alternate text for an applet.
 archive: Specifies the location of an archive file.
 border: Specifies the border around the applet panel.
 codebase: Specifies a relative base URL for applets specified in the code
attribute.
 height: Specifies the height of an applet.
 hspace: Defines the horizontal spacing around an applet.
 mayscript: Indicates whether the Java applet is allowed to access the
scripting objects of the web page.
 name: Defines the name for an applet (to use in scripts)
 vspace: Defines the vertical spacing around an applet.
 width: Specifies the width of an applet.
Java AWT Tutorial
Java AWT (Abstract Window Toolkit) is an API to develop Graphical User Interface (GUI)
or windows-based applications in Java.

Java AWT components are platform-dependent i.e. components are displayed according
to the view of operating system. AWT is heavy weight i.e. its components are using the
resources of underlying operating system (OS).

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

The AWT tutorial will help the user to understand Java GUI programming in simple and
easy steps.

For example, an AWT GUI with components like TextField, label and button will have different
look and feel for the different platforms like Windows, MAC OS, and Unix. The reason for this is
the platforms have different view for their native components and AWT directly calls the native
subroutine that creates those components.

Java AWT Hierarchy


The hierarchy of Java AWT classes are given below.
Components
All the elements like the button, text fields, scroll bars, etc. are called components. In
Java AWT, there are classes for each component as shown in above diagram. In order to
place every component in a particular position on a screen, we need to add them to a
container.

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.

Types of containers:

There are four types of containers in Java AWT:

1. Window
2. Panel
3. Frame
4. Dialog

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. We need to create an instance of
Window class to create this container.

Panel

The Panel is the container that doesn't contain title bar, border or menu bar. It is generic
container for holding the components. It can have other components like button, text
field etc. An instance of Panel class creates a container, in which we can add
components.

Frame

The Frame is the container that contain title bar and border and can have menu bars. It
can have other components like button, text field, scrollbar etc. Frame is most widely
used container while developing an AWT application.
Java AWT Label
The object of the Label class is a component for placing text in a container. It is used to
display a single line of read only text. The text can be changed by a programmer but a
user cannot edit it directly.

It is called a passive control as it does not create any event when it is accessed. To create
a label, we need to create the object of Label class.

AWT Label Class Declaration


1. public class Label extends Component implements Accessible

AWT Label Fields


The java.awt.Component class has following fields:

1. static int LEFT: It specifies that the label should be left justified.
2. static int RIGHT: It specifies that the label should be right justified.
3. static int CENTER: It specifies that the label should be placed in center.

Java AWT Button


A button is basically a control component with a label that generates an event when
pushed. The Button class is used to create a labeled button that has platform
independent implementation. The application result in some action when the button
is pushed.

When we press a button and release it, AWT sends an instance of ActionEvent to that
button by calling processEvent on the button. The processEvent method of the button
receives the all the events, then it passes an action event by calling its own
method processActionEvent. This method passes the action event on to action listeners
that are interested in the action events generated by the button.

AWT Button Class Declaration


public class Button extends Component implements Accessible
Java AWT Checkbox
The Checkbox class is used to create a checkbox. It is used to turn an option on (true) or
off (false). Clicking on a Checkbox changes its state from "on" to "off" or from "off" to
"on".

AWT Checkbox Class Declaration


public class Checkbox extends Component implements ItemSelectable, Accessible

Java AWT Choice


The object of Choice class is used to show popup menu of choices. Choice selected by
user is shown on the top of a menu. It inherits Component class.

AWT Choice Class Declaration


public class Choice extends Component implements ItemSelectable, Accessible

Java AWT TextArea


The object of a TextArea class is a multiline region that displays text. It allows the editing
of multiple line text. It inherits TextComponent class.

The text area allows us to type as much text as we want. When the text in the text area
becomes larger than the viewable area, the scroll bar appears automatically which helps
us to scroll the text up and down, or right and left.

AWT TextArea Class Declaration


public class TextArea extends TextComponent

Fields of TextArea Class


The fields of java.awt.TextArea class are as follows:

o static int SCROLLBARS_BOTH - It creates and displays both horizontal and vertical
scrollbars.
o static int SCROLLBARS_HORIZONTAL_ONLY - It creates and displays only the
horizontal scrollbar.
o static int SCROLLBARS_VERTICAL_ONLY - It creates and displays only the vertical
scrollbar.
o static int SCROLLBARS_NONE - It doesn't create or display any scrollbar in the text
area.

Java AWT List


The object of List class represents a list of text items. With the help of the List class, user
can choose either one item or multiple items. It inherits the Component class.

AWT List class Declaration


public class List extends Component implements ItemSelectable, Accessible

Methods Inherited by the List Class


The List class methods are inherited by following classes:

o java.awt.Component
o java.lang.Object

Java AWT Scrollbar


The object of Scrollbar class is used to add horizontal and vertical scrollbar. Scrollbar is
a GUI component allows us to see invisible number of rows and columns.

It can be added to top-level container like Frame or a component like Panel. The
Scrollbar class extends the Component class.

AWT Scrollbar Class Declaration


public class Scrollbar extends Component implements Adjustable, Accessible

Scrollbar Class Fields


The fields of java.awt.Image class are as follows:

o static int HORIZONTAL - It is a constant to indicate a horizontal scroll bar.


o static int VERTICAL - It is a constant to indicate a vertical scroll bar.

Java LayoutManagers
The LayoutManagers are used to arrange components in a particular manner. The Java
LayoutManagers facilitates us to control the positioning and size of the components in
GUI forms. LayoutManager is an interface that is implemented by all the classes of
layout managers. There are the following classes that represent the layout managers:

1. java.awt.BorderLayout
2. java.awt.FlowLayout
3. java.awt.GridLayout
4. java.awt.CardLayout
5. java.awt.GridBagLayout
6. javax.swing.BoxLayout
7. javax.swing.GroupLayout
8. javax.swing.ScrollPaneLayout
9. javax.swing.SpringLayout etc.

Java BorderLayout
The BorderLayout is used to arrange the components in five regions: north, south, east,
west, and center. Each region (area) may contain one component only. It is the default
layout of a frame or window. The BorderLayout provides five constants for each region:

1. public static final int NORTH


2. public static final int SOUTH
3. public static final int EAST
4. public static final int WEST
5. public static final int CENTER

Java FlowLayout
The Java FlowLayout class is used to arrange the components in a line, one after another
(in a flow). It is the default layout of the applet or panel.
Fields of FlowLayout class
1. public static final int LEFT
2. public static final int RIGHT
3. public static final int CENTER
4. public static final int LEADING
5. public static final int TRAILING

Java GridLayout
The Java GridLayout class is used to arrange the components in a rectangular grid. One
component is displayed in each rectangle.

Constructors of GridLayout class


1. GridLayout(): creates a grid layout with one column per component in a row.
2. GridLayout(int rows, int columns): creates a grid layout with the given rows and
columns but no gaps between the components.
3. GridLayout(int rows, int columns, int hgap, int vgap): creates a grid layout with the
given rows and columns along with given horizontal and vertical gaps.

Java CardLayout
The Java CardLayout class manages the components in such a manner that only one
component is visible at a time. It treats each component as a card that is why it is known
as CardLayout.

Constructors of CardLayout Class


1. CardLayout(): creates a card layout with zero horizontal and vertical gap.
2. CardLayout(int hgap, int vgap): creates a card layout with the given horizontal and
vertical gap.

Commonly Used Methods of CardLayout Class


o public void next(Container parent): is used to flip to the next card of the given
container.
o public void previous(Container parent): is used to flip to the previous card of the
given container.
o public void first(Container parent): is used to flip to the first card of the given
container.
o public void last(Container parent): is used to flip to the last card of the given
container.
o public void show(Container parent, String name): is used to flip to the specified card
with the given name.

UNIT – 4
Event and Listener (Java Event Handling)
Changing the state of an object is known as an event. For example, click on button, dragging mouse etc. The ja
classes and Listener interfaces for event handling.

Java Event classes and Listener interfaces


Event Classes Listener Interfaces

ActionEvent ActionListener

MouseEvent MouseListener and MouseMotionList

MouseWheelEvent MouseWheelListener

KeyEvent KeyListener

ItemEvent ItemListener

TextEvent TextListener
AdjustmentEvent AdjustmentListener

WindowEvent WindowListener

ComponentEvent ComponentListener

ContainerEvent ContainerListener

FocusEvent FocusListener

Steps to perform Event Handling


Following steps are required to perform event handling:

1. Register the component with the Listener

Registration Methods
For registering the component with the Listener, many classes provide
the registration methods. For example:

o Button
o public void addActionListener(ActionListener a){}
o MenuItem
o public void addActionListener(ActionListener a){}
o TextField
o public void addActionListener(ActionListener a){}
o public void addTextListener(TextListener a){}
o TextArea
o public void addTextListener(TextListener a){}
o Checkbox
o public void addItemListener(ItemListener a){}
o Choice
o public void addItemListener(ItemListener a){}
o List
o public void addActionListener(ActionListener a){}
o public void addItemListener(ItemListener a){}

Java Networking
Java Networking is a concept of connecting two or more computing
devices together so that we can share resources.

Java socket programming provides facility to share data between


different computing devices.

Advantage of Java Networking


1. Sharing resources
2. Centralize software management

The java.net package supports two protocols,

1. TCP: Transmission Control Protocol provides reliable


communication between the sender and receiver. TCP is used
along with the Internet Protocol referred as TCP/IP.
2. UDP: User Datagram Protocol provides a connection-less
protocol service by allowing packet of data to be transferred
along two or more nodes

Java Networking Terminology


The widely used Java networking terminologies are given below:

1. IP Address
2. Protocol
3. Port Number
4. MAC Address
5. Connection-oriented and connection-less protocol
6. Socket

1) IP Address
IP address is a unique number assigned to a node of a network e.g.
192.168.0.1 . It is composed of octets that range from 0 to 255.

It is a logical address that can be changed.

2) Protocol
A protocol is a set of rules basically that is followed for
communication. For example:

o TCP
o FTP
o Telnet
o SMTP
o POP etc.

3) Port Number
The port number is used to uniquely identify different applications. It
acts as a communication endpoint between applications.

The port number is associated with the IP address for communication


between two applications.

4) MAC Address
MAC (Media Access Control) address is a unique identifier of NIC
(Network Interface Controller). A network node can have multiple NIC
but each with unique MAC address.

For example, an ethernet card may have a MAC address of


00:0d:83::b1:c0:8e.

5) Connection-oriented and connection-less protocol


In connection-oriented protocol, acknowledgement is sent by the
receiver. So it is reliable but slow. The example of connection-oriented
protocol is TCP.

But, in connection-less protocol, acknowledgement is not sent by the


receiver. So it is not reliable but fast. The example of connection-less
protocol is UDP.

6) Socket
A socket is an endpoint between two way communications.

Visit next page for Java socket programming.


java.net package
The java.net package can be divided into two sections:

1. A Low-Level API: It deals with the abstractions of addresses i.e.


networking identifiers, Sockets i.e. bidirectional data
communication mechanism and Interfaces i.e. network interfaces.
2. A High Level API: It deals with the abstraction of URIs i.e.
Universal Resource Identifier, URLs i.e. Universal Resource
Locator, and Connections i.e. connections to the resource
pointed by URLs.

Datagram
Datagrams are collection of information sent from one device to
another device via the established network. When the datagram is
sent to the targeted device, there is no assurance that it will reach to
the target device safely and completely. It may get damaged or lost in
between. Likewise, the receiving device also never know if the
datagram received is damaged or not. The UDP protocol is used to
implement the datagrams in Java.

UNIT – 5
Java I/O Tutorial
Java I/O (Input and Output) is used to process the input and produce
the output.

Java uses the concept of a stream to make I/O operation fast. The
java.io package contains all the classes required for input and output
operations.

We can perform file handling in Java by Java I/O API.

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 the console.

1) System.out: standard output stream

2) System.in: standard input stream

3) System.err: standard error stream

Let's see the code to print output and an error message to the
console.

1. System.out.println("simple message");
2. System.err.println("error message");

Let's see the code to get input from console.

1. int i=System.in.read();//returns ASCII code of 1st character


2. System.out.println((char)i);//will print the character
Java ByteArrayInputStream Class
The ByteArrayInputStream is composed of two words: ByteArray and
InputStream. As the name suggests, it can be used to read
byte array as input stream.

Java ByteArrayInputStream class contains an internal buffer which is


used to read byte array as stream. In this stream, the data is read
from a byte array.

The buffer of ByteArrayInputStream automatically grows according to


data.

Java ByteArrayInputStream class


declaration
Let's see the declaration for Java.io.ByteArrayInputStream class:

1. public class ByteArrayInputStream extends InputStream

Java ByteArrayOutputStream Class


Java ByteArrayOutputStream class is used to write common data into
multiple files. In this stream, the data is written into a byte array which
can be written to multiple streams later.

The ByteArrayOutputStream holds a copy of data and forwards it to


multiple streams.

The buffer of ByteArrayOutputStream automatically grows according


to data.
Java ByteArrayOutputStream class
declaration
Let's see the declaration for Java.io.ByteArrayOutputStream class:

1. public class ByteArrayOutputStream extends OutputStream

Java FileInputStream Class


Java FileInputStream class obtains input bytes from a file. It is used for
reading byte-oriented data (streams of raw bytes) such as image data,
audio, video etc. You can also read character-stream data. But, for
reading streams of characters, it is recommended to
use FileReader class.

Java FileInputStream class declaration


Let's see the declaration for java.io.FileInputStream class:

1. public class FileInputStream extends InputStream

Java FileOutputStream Class


Java FileOutputStream is an output stream used for writing data to
a file.

If you have to write primitive values into a file, use FileOutputStream


class. You can write byte-oriented as well as character-oriented data
through FileOutputStream class. But, for character-oriented data, it is
preferred to use FileWriter than FileOutputStream.
FileOutputStream class declaration
Let's see the declaration for Java.io.FileOutputStream class:

1. public class FileOutputStream extends OutputStream

Java PrintStream Class


The PrintStream class provides methods to write data to another
stream. The PrintStream class automatically flushes the data so there is
no need to call flush() method. Moreover, its methods don't throw
IOException.

Class declaration
Let's see the declaration for Java.io.PrintStream class:

1. public class PrintStream extends FilterOutputStream implements Clo


seable. Appendable

Java - RandomAccessFile
This class is used for reading and writing to random access file. A
random access file behaves like a large array of bytes. There is a cursor
implied to the array called file pointer, by moving the cursor we do the
read write operations. If end-of-file is reached before the desired
number of byte has been read than EOFException is thrown. It is a
type of IOException.
Constructor
Constructor Description

andomAccessFile(File Creates a random access file stream to read from, and


le, String mode) optionally to write to, the file specified by the File
argument.

andomAccessFile(String name, Creates a random access file stream to read from, and
tring mode) optionally to write to, a file with the specified name.

Java CharArrayWriter Class


The CharArrayWriter class can be used to write common data to multiple files. This class
inherits Writer class. Its buffer automatically grows when data is written in this stream. Calling
the close() method on this object has no effect.

Java CharArrayWriter class declaration


Let's see the declaration for Java.io.CharArrayWriter class:

1. public class CharArrayWriter extends Writer

Java CharArrayReader Class


The CharArrayReader is composed of two words: CharArray and
Reader. The CharArrayReader class is used to read character array as a
reader (stream). It inherits Reader class.
Java CharArrayReader class declaration
Let's see the declaration for Java.io.CharArrayReader class:

1. public class CharArrayReader extends Reader

Java BufferedReader Class


Java BufferedReader class is used to read the text from a character-
based input stream. It can be used to read data line by line by
readLine() method. It makes the performance fast. It
inherits Reader class.

Java BufferedReader class declaration


Let's see the declaration for Java.io.BufferedReader class

public class BufferedReader extends Reader

Java BufferedWriter Class


Java BufferedWriter class is used to provide buffering for Writer
instances. It makes the performance fast. It inherits Writer class. The
buffering characters are used for providing the efficient writing of
single arrays, characters, and strings.

Class declaration
Let's see the declaration for Java.io.BufferedWriter class:

1. public class BufferedWriter extends Writer


Java PrintWriter class
Java PrintWriter class is the implementation of Writer class. It is used
to print the formatted representation of objects to the text-output
stream.

Class declaration
Let's see the declaration for Java.io.PrintWriter class:

1. public class PrintWriter extends Writer

Serialization and Deserialization in


Java
Serialization in Java is a mechanism of writing the state of an object
into a byte-stream. It is mainly used in Hibernate, RMI, JPA, EJB and
JMS technologies.

The reverse operation of serialization is called deserialization where


byte-stream is converted into an object. The serialization and
deserialization process is platform-independent, it means you can
serialize an object on one platform and deserialize it on a different
platform.

For serializing the object, we call the writeObject() method


of ObjectOutputStream class, and for deserialization we call
the readObject() method of ObjectInputStream class.
We must have to implement the Serializable interface for serializing
the object.

Advantages of Java Serialization


It is mainly used to travel object's state on the network (that is known
as marshalling).

java.io.Serializable interface
Serializable is a marker interface (has no data member and method).
It is used to "mark" Java classes so that the objects of these classes
may get a certain capability. The Cloneable and Remote are also
marker interfaces.

The Serializable interface must be implemented by the class whose


object needs to be persisted.

The String class and all the wrapper classes implement


the java.io.Serializable interface by default.
Let's see the example given below:

Student.java

1. import java.io.Serializable;
2. public class Student implements Serializable{
3. int id;
4. String name;
5. public Student(int id, String name) {
6. this.id = id;
7. this.name = name;
8. }
9. }

Java JDBC Tutorial


JDBC stands for Java Database Connectivity. JDBC is a Java API to
connect and execute the query with the database. It is a part of JavaSE
(Java Standard Edition). JDBC API uses JDBC drivers to connect with
the database. There are four types of JDBC drivers:

o JDBC-ODBC Bridge Driver,


o Native Driver,
o Network Protocol Driver, and
o Thin Driver

We can use JDBC API to access tabular data stored in any relational
database. By the help of JDBC API, we can save, update, delete and
fetch data from the database. It is like Open Database Connectivity
(ODBC) provided by Microsoft.
JAVA.SQL package
The java.sql package contains classes and interfaces for JDBC API. A
list of popular interfaces of JDBC API are given below:

o Driver interface
o Connection interface
o Statement interface
o PreparedStatement interface
o CallableStatement interface
o ResultSet interface
o ResultSetMetaData interface
o DatabaseMetaData interface
o RowSet interface

A list of popular classes of JDBC API are given below:

o DriverManager class
o Blob class
o Clob class
o Types class

Why Should We Use JDBC


Before JDBC, ODBC API was the database API to connect and execute
the 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).

We can use JDBC API to handle database using Java program and can
perform the following activities:

1. Connect to the database


2. Execute queries and update statements to the database
3. Retrieve the result received from the database.

JDBC-ODBC bridge driverU


The JDBC-ODBC bridge driver uses ODBC driver to connect to the
database. The JDBC-ODBC bridge driver converts JDBC method calls
into the ODBC function calls. This is now discouraged because of thin
driver.
Advantages:
o easy to use.
o can be easily connected to any database.

Disadvantages:
o Performance degraded because JDBC method call is converted
into the ODBC function calls.
o The ODBC driver needs to be installed on the client machine.

Java Database Connectivity with 5


Steps
There are 5 steps to connect any java application with the database using JDBC.
are as follows:

o Register the Driver class


o Create connection
o Create statement
o Execute queries
o Close connection
1) Register the driver class
The forName() method of Class class is used to register the driver class. This me
to dynamically load the driver class.

Syntax of forName() method


1. public static void forName(String className)throws ClassNotFoundE
xception

2) Create the connection object


The getConnection() method of DriverManager class is used to establish connect
database.
Syntax of getConnection() method
1. 1) public static Connection getConnection(String url)throws SQLExce
ption

3) Create the Statement object


The createStatement() method of Connection interface is used to create statemen
of statement is responsible to execute queries with the database.

Syntax of createStatement() method


1. public Statement createStatement()throws SQLException

4) Execute the query


The executeQuery() method of Statement interface is used to execute queries to t
This method returns the object of ResultSet that can be used to get all the records

Syntax of executeQuery() method


1. public ResultSet executeQuery(String sql)throws SQLException

5) Close the connection object


By closing connection object statement and ResultSet will be closed automatically
method of Connection interface is used to close the connection.

Syntax of close() method


1. public void close()throws SQLException

You might also like