1. PROGRAMMING IN JAVA
Dr P PRABAKARAN
Assistant Professor
Department of Computer Applications
School of Computing Sciences
Vels Institute of Science Technology and Advanced Studies,
Chennai
2. Unit-I
Introduction to Java
Java is a programming language and a platform.
Java is a high level,
robust,
object-oriented and
secure programming language
3. Unit-I
Features of Java
Simple Object-Oriented
Portable Platform independent
Secured Robust
Architecture neutral Interpreted
High Performance Multithreaded
Distributed Dynamic
6. Unit-I
Data Types
Data types specify the different sizes and values that
can be stored in the variable.
Primitive data types
Non-primitive data types
7. Unit-I
Variables
A variable is a container which holds the value while
the Java program is executed.
Types of Variables
local variable
instance variable
static variable
8. Unit-I
Arrays
Arrays are used to store multiple values in a single
variable, instead of declaring separate variables for
each value.
Types of Array
Single Dimensional Array
Multidimensional Array
9. Unit-I
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
11. Unit-I
CONTROL STATEMENTS
However, Java provides statements that can be used to control the flow of Java code.
Such statements are called control flow statements. It is one of the fundamental
features of Java, which provides a smooth flow of program.
12. Unit-I
CONTROL STATEMENTS
Java provides three types of control flow statements.
Decision Making statements
if statements
switch statement
Loop statements
do while loop
while loop
for loop
for-each loop
Jump statements
break statement
continue statement
15. Unit-I
CONTROL STATEMENTS
if-else statement
The if-else statement is an extension to the if-statement, which uses another block of code, i.e., else
block. The else block is executed if the condition of the if-block is evaluated as false.
Syntax:
if(condition) {
statement 1; //executes when condition is true
}
else{
statement 2; //executes when condition is false
}
16. Unit-I
CONTROL STATEMENTS
if-else-if ladder
The if-else-if statement contains the if-statement followed by multiple else-if statements. In other words, we can say that it is the chain of if-else
statements that create a decision tree where the program may enter in the block of code where the condition is true.
Syntax of if-else-if statement is given below.
if(condition 1) {
statement 1; //executes when condition 1 is true
}
else if(condition 2) {
statement 2; //executes when condition 2 is true
}
else {
statement 2; //executes when all the conditions are false
}
17. Unit-I
CONTROL STATEMENTS
Switch Statement
The switch statement contains multiple blocks of code called cases and a single case is
executed based on the variable which is being switched. The switch statement is easier
to use instead of if-else-if statements. It also enhances the readability of the program.
19. Unit-I
CONTROL STATEMENTS
Loop Statements
Loop statements are used to execute the set of instructions in a repeated order. The
execution of the set of instructions depends upon a particular condition.
1. for loop
2. while loop
3. do-while loop
20. Unit-I
CONTROL STATEMENTS
Loop Statements
Loop statements are used to execute the set of instructions in a repeated order. The
execution of the set of instructions depends upon a particular condition.
1. for loop
2. while loop
3. do-while loop
21. Unit-I
CONTROL STATEMENTS
Loop Statements
For loop
We use the for loop only when we exactly know the number of times, we want to
execute the block of code.
for(initialization, condition, increment/decrement) {
//block of statements
}
22. Unit-I
CONTROL STATEMENTS
Loop Statements
Java while loop
It is also known as the entry-controlled loop since the condition is checked at the start of the loop. If the
condition is true, then the loop body will be executed; otherwise, the statements after the loop will be
executed.
The syntax of the while loop is given below.
while(condition){
//looping statements
}
23. Unit-I
CONTROL STATEMENTS
Loop Statements
do-while loop
The do-while loop checks the condition at the end of the loop after executing the loop statements. When the number of
iteration is not known and we have to execute the loop at least once, we can use do-while loop.
It is also known as the exit-controlled loop since the condition is not checked in advance. The syntax of the do-while loop is
given below.
do
{
//statements
} while (condition);
24. Unit-II
CLASSES
A class is a group of objects which have common
properties.
class <class_name>
{
field;
method;
}
25. Unit-II
OBJECTS
An entity that has state and behavior is known as an
object e.g., chair, bike, marker, pen, table, car, etc. It can
be physical or logical.
27. Unit-II
CONSTRUCTORS
A constructor initializes an object when it is created. It has the same name as
its class and is syntactically similar to a method.
Syntax
class ClassName
{
ClassName()
{
}
}
29. Unit-II
Example: Parameterized Constructor
class Stud
{
int id;
Stud (int i)
{
id = i;
}
void display()
{
System.out.println(id);
}
public static void main(String args[]
)
{
Stud s1 = new Stud (1);
Stud s2 = new Stud (10);
s1.display();
s2.display();
}
}
30. Unit-II
METHOD OVERLOADING
Class has multiple methods having same name but different in
parameters, it is known as Method Overloading.
Different ways to overload the method
By changing number of arguments
By changing the data type
31. Unit-II
ACCESS CONTROL
Private: The access level of a private modifier is only within the class. It cannot be
accessed from outside the class.
Default: The access level of a default modifier is only within the package. It cannot
be accessed from outside the package. If you do not specify any access level, it will
be the default.
Protected: The access level of a protected modifier is within the package and
outside the package through child class. If you do not make the child class, it cannot
be accessed from outside the package.
Public: The access level of a public modifier is everywhere. It can be accessed from
within the class, outside the class, within the package and outside the package.
32. Unit-II
STATIC AND FIXED METHODS
Static method
Apply static keyword with any method, it is known as static method.
A static method belongs to the class rather than the object of a class.
A static method can be invoked without the need for creating an instance of a class.
A static method can access static data member and can change the value of it.
33. Unit-II
STRING CLASS
Java String class provides a lot of methods to perform operations on strings such as
compare(), concat(), equals(), split(), length(), replace(), compareTo(), intern(),
substring() etc.
34. Unit-II
INHERITANCE
Inheritance in Java is a mechanism in which one object acquires all the properties and
behaviors of a parent object.
syntax of Inheritance
class Subclass-name extends Superclass-name
{
//methods and fields
}
The extends keyword
35. Unit-II
Types of Inheritance
1. Single inheritance
2. Multilevel inheritance
3. Hierarchical Inheritance
4. Hybrid inheritance
36. Unit-II
OVERRIDING METHODS
If a subclass provides the specific implementation of the method that has been
declared by one of its parent class, it is known as method overriding.
Rules for Method Overriding
The method must have the same name as in the parent class
The method must have the same parameter as in the parent class.
There must be an IS-A relationship (inheritance).
37. Unit-II
USING SUPER
The super keyword in Java is a reference variable which is used to refer immediate
parent class object.
Whenever you create the instance of subclass, an instance of parent class is created
implicitly which is referred by super reference variable.
38. Unit-II
ABSTRACT CLASS
A class which is declared with the abstract keyword is known as an abstract class.
An abstract class must be declared with an abstract keyword.
It can have abstract and non-abstract methods.
It cannot be instantiated.
It can have constructors and static methods also.
39. Unit-II
ABSTRACT CLASS
A class which is declared with the abstract keyword is known as an abstract class.
An abstract class must be declared with an abstract keyword.
It can have abstract and non-abstract methods.
It cannot be instantiated.
It can have constructors and static methods also.
40. UNIT-III – Programming in JAVA
PACKAGES
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.
Subpackages: Packages that are inside another package are the subpackages. These
are not imported by default, they have to imported explicitly.
41. UNIT-III – Programming in JAVA
PACKAGES
Creating a Package
While creating a package, you should choose a name for the package and include
a package statement along with that name at the top of every source file that contains the
classes, interfaces, enumerations, and annotation types that you want to include in the
package.
Advantage of Java Package
1) Java package is used to categorize the classes and interfaces so that they can be easily
maintained.
2) Java package provides access protection.
3) Java package removes naming collision.
42. UNIT-III – Programming in JAVA
ACCESS CONTROLS
Private: The access level of a private modifier is only within the class. It cannot be accessed
from outside the class.
Default: The access level of a default modifier is only within the package. It cannot be
accessed from outside the package. If you do not specify any access level, it will be the default.
Protected: The access level of a protected modifier is within the package and outside the
package through child class. If you do not make the child class, it cannot be accessed from
outside the package.
Public: The access level of a public modifier is everywhere. It can be accessed from within the
class, outside the class, within the package and outside the package.
43. UNIT-III – Programming in JAVA
IMPORTING PACKAGES
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.
44. UNIT-III – Programming in JAVA
INTERFACES
Interfaces can have abstract methods and variables. It cannot have a method body.
Interface cannot be instantiated just like the abstract class.
We can have default and static methods in an interface.
We can have private methods in an interface.
45. UNIT-III – Programming in JAVA
INTERFACES
Interfaces can have abstract methods and variables. It cannot have a method body.
Interface cannot be instantiated just like the abstract class.
We can have default and static methods in an interface.
We can have private methods in an interface.
46. UNIT-III – Programming in JAVA
INTERFACES
Interface keyword is implements
Syntax:
interface <interface_name>
{
// declare constant fields
// declare methods that abstract
// by default.
}
47. UNIT-III – Programming in JAVA
EXCEPTION HANDLING
An exception is an event that disrupts the normal flow of the program. It is an object
which is thrown at runtime.
Exception Handling is a mechanism to handle runtime errors such as
ClassNotFoundException, IOException, SQLException, RemoteException, etc.
Types of Java Exceptions
Checked
Unchecked
Error
48. UNIT-III – Programming in JAVA
EXCEPTION HANDLING
Keyword Description
try The "try" keyword is used to specify a block where we should place an exception code. It
means we can't use try block alone. The try block must be followed by either catch or finally.
catch The "catch" block is used to handle the exception. It must be preceded by try block which
means we can't use catch block alone. It can be followed by finally block later.
finally The "finally" block is used to execute the necessary code of the program. It is executed
whether an exception is handled or not.
throw The "throw" keyword is used to throw an exception.
throws The "throws" keyword is used to declare exceptions. It specifies that there may occur an
exception in the method. It doesn't throw an exception. It is always used with method
signature.
49. UNIT-III – Programming in JAVA
THREAD
Threads allows a program to operate more efficiently by doing multiple things at the
same time.
Threads can be used to perform complicated tasks in the background without
interrupting the main program.
Create a thread in Java
By extending Thread class
By implementing Runnable interface.
50. UNIT-III – Programming in JAVA
SYNCHRONIZATION
Synchronization in Java is the capability to control the access of multiple threads to any
shared resource.
Java Synchronization is better option where we want to allow only one thread to
access the shared resource.
Types of Synchronization
Process Synchronization
Thread Synchronization
51. UNIT-III – Programming in JAVA
MESSAGING
Java Message Service is an API that provides the facility to create, send and read
messages. It provides loosely coupled, reliable and asynchronous communication.
JMS is also known as a messaging service.
Messaging is a technique to communicate applications or software components.
52. UNIT-III – Programming in JAVA
RUNNABLE INTERFACE
Java runnable is an interface used to execute code on a concurrent thread. It is an
interface which is implemented by any class if we want that the instances of that class
should be executed by a thread.
Method Description
public void
run()
This method takes in no arguments. When the object of a class implementing
Runnable class is used to create a thread, then the run method is invoked in the
thread which executes separately.
53. UNIT-III – Programming in JAVA
INTER THREAD COMMUNICATION
Inter-thread communication or Co-operation is all about allowing synchronized threads to
communicate with each other.
Cooperation (Inter-thread communication) is a mechanism in which a thread is paused running
in its critical section and another thread is allowed to enter (or lock) in the same critical
section to be executed.It is implemented by following methods of Object class:
wait()
notify()
notifyAll()
54. Unit-IV
I/O STREAMS
The java.io package contains all the classes required for input and output operations.
Stream
A stream can be defined as a sequence of data. There are two kinds of Streams
InPutStream − The InputStream is used to read data from a source.
OutPutStream − The OutputStream is used for writing data to a destination.
57. Unit-IV
FILE STREAMS
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.
58. Unit-IV
APPLETS
Applet is a special type of program that is embedded in the webpage to generate the
dynamic content. It runs inside the browser and works at client side.
Lifecycle of Java Applet
Applet is initialized.
Applet is started.
Applet is painted.
Applet is stopped.
Applet is destroyed.
59. Unit-IV
STRING BUFFER
The java.lang.StringBuffer class is a thread-safe, mutable sequence of characters. Following
are the important points about StringBuffer
A string buffer is like a String, but can be modified.
It contains some particular sequence of characters, but the length and content of the
sequence can be changed through certain method calls.
They are safe for use by multiple threads.
Every string buffer has a capacity.
60. Unit-IV
CHAR ARRAY
Character Array in Java is an Array that holds character data types values.
A character array is different from a string array, and neither a string nor a character array
can be terminated by the NUL character.
The char data type can sore the following values:
Any alphabet
Numbers between 0 to 65,535 ( Inclusive)
special characters (@, #, $, %, ^, &, *, (, ), ¢, £, ¥)
61. Unit-IV
JAVA UTILITIES
Java.util package contains the collections framework, legacy collection classes, event
model, date and time facilities, internationalization, and miscellaneous utility classes.
Packages are divided into two categories:
Built-in Packages (packages from the Java API)
User-defined Packages (create your own packages)
62. Unit-IV
Built-in Packages
The Java API is a library of prewritten classes, that are free to use, included in the Java
Development Environment.
63. Unit-IV
RANDOM
Random numbers are the numbers that use a large set of numbers and selects a number
using the mathematical algorithm. It satisfies the following two conditions.
The generated values uniformly distributed over a definite interval.
It is impossible to guess the future value based on current and past values.
64. Unit-IV
VECTOR
Vector is like the dynamic array which can grow or shrink its size. Unlike array, we can store
n-number of elements in it as there is no size limit.
It is a part of Java Collection framework since Java 1.2. It is found in the java.util package
and implements the List interface, so we can use all the methods of List interface here.
65. Unit-IV
CALENDAR AND PROPERTIES
Java Calendar class is an abstract class that provides methods for converting date between
a specific instant in time and a set of calendar fields such as MONTH, YEAR, HOUR, etc. It
inherits Object class and implements the Comparable interface.
Calendar class declaration
Let's see the declaration of java.util.Calendar class
public abstract class Calendar extends Object
implements Serializable, Cloneable, Comparable<Calendar>
66. Unit-IV
CALENDAR AND PROPERTIES
Java Calendar class is an abstract class that provides methods for converting date between
a specific instant in time and a set of calendar fields such as MONTH, YEAR, HOUR, etc. It
inherits Object class and implements the Comparable interface.
Calendar class declaration
Let's see the declaration of java.util.Calendar class
public abstract class Calendar extends Object
implements Serializable, Cloneable, Comparable<Calendar>
67. Unit - V
NETWORKING
Java Networking is a concept of connecting two or more computing devices
together so that we can share resources.
Advantage of Java Networking
Sharing resources
Centralize software management
68. Unit - V
SOCKET PROGRAMMING
Sockets provide the communication mechanism between two computers using
TCP. A client program creates a socket on its end of the communication and
attempts to connect that socket to a server.
When the connection is made, the server creates a socket object on its end of
the communication. The client and the server can now communicate by
writing to and reading from the socket.
69. Unit - V
PROXY SERVER
Proxy server is an intermediary server between client and the internet. Proxy
servers offers the following basic functionalities:
Firewall and network data filtering.
Network connection sharing
Data caching
Proxy servers allow to hide, conceal and make your network id anonymous by
hiding your IP address.
70. Unit - V
Type of Proxies
1. Forward Proxies - the client requests its internal network server to forward
to the internet.
2. Open Proxies - Open Proxies helps the clients to conceal their IP address
while browsing the web.
3. Reverse Proxies - the requests are forwarded to one or more proxy servers
and the response from the proxy server is retrieved as if it came directly
from the original Server.
71. Unit - V
URL
The Java URL class represents an URL. URL is an acronym for Uniform Resource Locator. It
points to a resource on the World Wide Web.
A URL contains many information:
Protocol: In this case, http is the protocol.
Server name or IP Address: In this case, www.javatpoint.com is the server name.
Port Number: It is an optional attribute. If we write
http//ww.javatpoint.com:80/sonoojaiswal/ , 80 is the port number. If port number is not
mentioned in the URL, it returns -1.
File Name or directory name: In this case, index.jsp is the file name.
72. Unit - V
DATAGRAMS
Datagrams are groups(bundles) of information passed from one device to
another over the network.
When the datagram has been released for its intended target, there is no
assurance that it will arrive or even that someone will be there to catch the
datagram packets.
A datagram is self-contained, and an independent message is sent over a
network whose arrival time, and content is not guaranteed.
Java provides the DatagramSocket class and DatagramPacket class for
implementing UDP connections.
73. Unit - V
WORKING WITH WINDOWS USING AWT CLASSES
Java AWT (Abstract Window Toolkit) is an API to develop Graphical User Interface (GUI) or
windows-based applications in Java.
The java.awt package provides classes for AWT API such as
TextField,
Label,
TextArea,
RadioButton,
CheckBox,
Choice,
List etc.
75. Unit - V
AWT CONTROLS
Label
Buttons
Checkboxes
Dropdown Boxes
List Boxes
Text Fields
Text Areas
76. Unit - V
LAYOUT MANAGEMENT AND MENUS
Layout Management
The Layout managers enable us to control the way in which visual components are arranged in the
GUI forms by determining the size and position of components within the containers.
Types of Layout Managers
1. Flow Layout
2. Border Layout
3. Card Layout
4. Grid Layout
5. GridBag Layout
77. Unit - V
Menus
The object of MenuItem class adds a simple labeled menu item on menu. The items used in
a menu must belong to the MenuItem or any of its subclass.
The object of Menu class is a pull down menu component which is displayed on the menu
bar. It inherits the MenuItem class.
PopupMenu
PopupMenu can be dynamically popped up at specific position within a component. It
inherits the Menu class.