Java Notes by g1
Java Notes by g1
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
o Object
o Class
o Inheritance
o Polymorphism
o Abstraction
o Encapsulation
Java Operators
Operators are used to perform operations on variables and values.
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Bitwise operators
In Java, expression is the combination of values,
variables, operators, and method calls.
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:
example:
class objects
Car Volvo
Audi
Toyota
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.
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.
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.
3) Static variable
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.
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 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.
Example
Create an object called "myObj" and print the value of x:
int x = 5;
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:
public Main() {
// Outputs 5
int x;
public Main(int y) {
x = y;
System.out.println(myObj.x);
// Outputs 5
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.
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);
}
}
https://www.javatpoint.com/wrapper-class-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
Method Overloading
If a class has multiple methods having same name but different in parameters,
it is known as Method Overloading.
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.
Interfaces
Another way to achieve abstraction in Java, is with interfaces.
Multithreading in Java
Multithreading in Java is a process of executing multiple threads simultaneously.
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.
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.
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:
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.
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:
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.
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.
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.
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.
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.
o java.awt.Component
o java.lang.Object
It can be added to top-level container like Frame or a component like Panel. The
Scrollbar class extends the Component class.
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:
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.
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.
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.
ActionEvent ActionListener
MouseWheelEvent MouseWheelListener
KeyEvent KeyListener
ItemEvent ItemListener
TextEvent TextListener
AdjustmentEvent AdjustmentListener
WindowEvent WindowListener
ComponentEvent ComponentListener
ContainerEvent ContainerListener
FocusEvent FocusListener
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.
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.
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.
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.
6) Socket
A socket is an endpoint between two way communications.
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.
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.
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");
Class declaration
Let's see the declaration for Java.io.PrintStream class:
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(String name, Creates a random access file stream to read from, and
tring mode) optionally to write to, a file with the specified name.
Class declaration
Let's see the declaration for Java.io.BufferedWriter class:
Class declaration
Let's see the declaration for Java.io.PrintWriter class:
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.
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. }
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
o DriverManager class
o Blob class
o Clob class
o Types class
We can use JDBC API to handle database using Java program and can
perform the following activities:
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.