Java Programming Study Notes MCS 024
Java Programming Study Notes MCS 024
Contents
Block 1.........................................................................................................................................................4
Unit 1 Object Oriented Methodology 1.......................................................................................................4
Components of Object Oriented Programming.......................................................................................4
Objects....................................................................................................................................................4
Class.........................................................................................................................................................5
Encapsulation..........................................................................................................................................6
Inheritance..............................................................................................................................................6
Salient Features of Object Oriented Programming..................................................................................8
JVM..........................................................................................................................................................8
Public static void main.............................................................................................................................9
Bytecode..................................................................................................................................................9
Java Platform Independence....................................................................................................................9
Unit 2 Object Oriented Methodology 2.....................................................................................................11
Forms of Inheritance.............................................................................................................................11
Benefits of Inheritance..........................................................................................................................11
Unit 3 – Java Language Basics....................................................................................................................13
Java Platform Independence..................................................................................................................13
Dynamic Initialization............................................................................................................................13
Unit 4 – Expression, Statements, and Arrays.............................................................................................15
Switch Statement...................................................................................................................................15
Block 2.......................................................................................................................................................17
Unit 1 – Class and Objects.........................................................................................................................17
Passing objects as parameters...............................................................................................................17
Static Methods.......................................................................................................................................19
Method Overloading.............................................................................................................................20
finalize() method...................................................................................................................................21
Creating Objects....................................................................................................................................23
Constructors..........................................................................................................................................23
Unit 2 – Inheritance and Polymorphism....................................................................................................25
Abstract Classes.....................................................................................................................................25
Public Access Specifier...........................................................................................................................26
Private Access Specifier.........................................................................................................................26
Method Overriding................................................................................................................................27
Final Keyword........................................................................................................................................29
Unit 3 – Packages and Interface.................................................................................................................31
Interfaces...............................................................................................................................................31
Implementing Interfaces........................................................................................................................31
Package..................................................................................................................................................34
CLASSPATH.............................................................................................................................................34
Interfaces and Abstract Class.................................................................................................................35
import keyword.....................................................................................................................................35
throws keyword.....................................................................................................................................35
Exception...............................................................................................................................................36
Causes of Exception...............................................................................................................................37
Block 3.......................................................................................................................................................38
Unit 1 – Multithreaded Programming........................................................................................................38
Notify and notifyAll................................................................................................................................38
Unit 2 – IO in Java......................................................................................................................................39
Unit 3 – Strings and Characters..................................................................................................................40
String Class Constructors.......................................................................................................................40
Unit 4 – Exploring Java IO..........................................................................................................................41
Serialization...........................................................................................................................................41
Block 4.......................................................................................................................................................42
Unit 1 – Applets.........................................................................................................................................42
Applets..................................................................................................................................................42
Events....................................................................................................................................................42
Applet LifeCycle.....................................................................................................................................43
Unit 2 – Graphic and User Interface..........................................................................................................44
Container...............................................................................................................................................44
Layout Manager.....................................................................................................................................44
Difference between swing and awt.......................................................................................................45
Block 1
Objects
- An object is a software bundle of variables and related methods
- Real-world objects share two characteristics: They all have state and
behavior. For example, cars have state (current gear, current speed,
front wheels, number of gears) and behavior (braking, accelerating,
slowing down, changing gears). Because Software objects are modeled
after real-world objects, they too have state and behavior.
- A software object maintains its state in one or more variables. A
variable is an item of data named by an identifier.
- A software object reflects its behavior with the help of method
implementation. A method is an implementation way of a function
associated with an object.
- Everything that the software object knows (state) and can do
(behavior) is expressed by the variables and the methods within that
object. For example, a software object that modeled your real-world
car would have variables that indicated the car’s current state: its
speed is 100 kmph, and its current gear is the 5th gear.
- These variables used to represent the object’s state are formally
known as instance variables, because they contain the state for a
particular car instance.
- In addition to its variables, the software car object would also have
methods to brake, change gears, etc. These methods are formally
known as instance methods because they impact or change the state
of a particular car instance.
- In object-oriented terminology, a particular object is called an instance
of the class to which it belongs.
Class
- A class is a blueprint, or prototype, that defines the variables and the
methods common to all objects of a certain kind.
- The class for a car would declare the instance variables necessary to
contain the current gear, the current speed, and so on, for each car
object.
- The class would also declare and provide implementations for the
instance methods that allow the driver to change gears, brake, etc.
- After you’ve created the car class, you can create any number of car
objects from the class. When you create an instance of a class, the
system allocates enough memory for the object and all its instance
variables. Each instance gets its own copy of all the instance variables
defined in the class.
- In addition to instance variables, classes can define class variables.
- A class variable contains information that is shared by all instances of
the class. For example, suppose that all cars had the same number of
gears (18). In this case, defining an instance variable to hold the
number of gears is inefficient; each instance would have its own copy
of the variable, but the value would be the same for every instance. In
such situations, you can define a class variable. All instances share this
variable. If one object changes the variable, it changes for all other
objects of that class.
- A class can also declare class methods. You can invoke a class method
directly from the class, whereas you must invoke instance methods
from a particular instance.
Encapsulation
- Packaging an object’s variables within the protective custody of its
methods is called encapsulation.
- This is one of the strong features of the object oriented approach. The
data is not directly accessible to the outside world. Only the functions,
which are wrapped in the class, can access it.
- Encapsulating related variables and methods into a neat software
bundle is a simple yet powerful idea that provides two primary
benefits to software developers:
o Modularity: The source code for an object can be written and
maintained independently of the source code for other objects.
Also, an object can be easily passed around in the system. You
can give your car to someone else, and it will still work.
o Information hiding: An object has a public interface that other
objects can use to communicate with it. The object can maintain
private information and methods that can be changed at any
time without affecting the other objects that depend on it. You
don’t need to understand the gear mechanism in your car to use
it.
Inheritance
- Inheritance is a language property specific to the object-oriented
paradigm.
- Inheritance is used for a unique form of code-sharing by allowing you
to take the implementation of any given class and build a new class
based on that implementation.
- Let us say class B, starts by inheriting all of the data and operations
defined in class A. This new subclass can extend the behavior by
adding additional data and new methods to operate on it.
- Basically during programming inheritance is used for extending the
existing property of a class. In other words, it can be said that
inheritance is “from-generalization-to-specialization”.
- By using a general class, a class with specific properties can be defined.
- Now let us take the example of BankAccount class, which is declared
as:
class BankAccount
{
data members
member functions
}
Data members and member functions of BankAccount class are used
to display characteristics of withdrawals, deposits, balance, etc.
- Now suppose you want to define a SavingAccount class. In the
SavingAccount class, you will definitely have basic characteristics of the
Bankaccount class mentioned above.
- In your SavingAccount class you can use the properties of BankAccount
class, without any modification in them using inheritance.
- To inherit a class into another class, extends keyword is used.
- SavingAccount class will inherit BankAccount class as given below.
class SavingAccount extends BankAccount
{
data members
member functions
}
JVM
- When a Java program is compiled, it is converted to byte code ,which
is then executed by the Java interpreter by translating the byte code
into machine instructions. Java interpreter is part of Java runtime
environment. Byte code is an intermediate code independent of any
machine and any operating system. Program in Java runtime
environment, which is used to interpret the byte code, is called Java
Virtual Machine (JVM).
- The JVM plays the main role to making Java portable.
- It provides a layer of abstraction between the compiled Java program
and the hardware platform and operating system.
- The JVM is central to Java’s portability because compiled Java
programs run on the JVM, independent of whatever hardware is used.
Bytecode
- Generally a language is either compiled or interpreted, but Java is both
compiled as well as interpreted.
- First, a Java program is compiled and comes in the form of "Java byte
code" (which is an intermediate code).
- Then, this Java byte code is run on interpreter to execute a program.
- This byte code is the actual power of Java to make it popular and
dominating over other programming languages.
Benefits of Inheritance
- Subclasses provide specialized behaviors from the basis of common
elements provided by the superclass. Through the use of inheritance,
programmers can reuse the code in the superclass many times. Once a
superclass is written and debugged, it need not be touched again but
initialized
Here, in this code, the variables h and b are declared and initialized to
some values in a single statement.
enclosing switch statement, and the flow of control continues with the
first statement following the switch block.
- The break statements are necessary because without them, the case
statements fall through. That is, without an explicit break, control will
flow sequentially through subsequent case statements.
Block 2
String name;
int percentage;
String grade;
Marks(String n, int m)
name = n;
percentage = m;
void Display()
[Link]("Percentage Marks:"+percentage);
[Link]("Grade : "+grade);
[Link]("*****************************");
class Object_Pass
Set_Grade(ob1);
[Link]("*****************************");
[Link]();
Set_Grade(ob2);
[Link]();
[Link] ="A";
[Link] = "B";
else
[Link] = "F";
Percentage Marks:75
Grade : A
*****************************
Percentage Marks:45
Grade : B
*****************************
Static Methods
- Methods and variables that are not declared as static are known as
instance methods and instance variables or in other words you can say
that they belong to objects of the class. To refer to instance methods
and variables, you must instantiate the class first then, obtain the
methods and variables from the instance.
- A static method is a characteristic of a class, not of the objects it has
created.
- Static variables and methods are also known as class variables or class
methods since each class variable and each class method occurs once
per class. Instance methods and variables occur once per instance of a
class or you can say every object is having its own copy of instance
variables.
- One very important point to note here is that a program can execute a
static method without creating an object of the class. All other
methods must be invoked through an object, and, therefore an object
must exist before they can be used.
- Every Java application program has one main() method. This method is
always static because Java starts execution from this main() method,
and at that time no object is created.
Method Overloading
- Sometimes two or more methods which are very similar in nature are
required.
- For example, you can take methods Area_S and Area_R in the given
program.
class Test
{
int Area_S( int i)
{
return i*i;
}
int Area_R(int a,int b)
{
return a*b;
}
}
Both the methods are finding area but the argument passed to them
and their implementation is different.
- All the methods of similar kinds in a class can have the same name, but
all the methods will have different prototypes. This concept is known
as method overloading.
finalize() method
- Sometimes it is required to take independent resources from some
object before the garbage collector takes the object. To perform this
operation, a method named finalize () is used.
Creating Objects
- An object of a class can be created by performing these two steps.
o 1. Declare an object of class.
o 2. Acquire space for and bind it to object.
- In the first step only a reference to a variable is created, no actual
object’s exists.
- For actual existence of an object memory is needed. That is acquired
by using new operator.
- The new operator in Java dynamically allocates memory for an object
returns a reference to object and binds the reference with the object.
- Here reference to object means address of object. So it is essential in
Java that all the objects must be dynamically allocated.
- Declaring Student object
o Step 1: Student student1; // declaring reference to object
o Step 2: student1 = new Student( ); // allocating memory
- In normal practice these two steps are written in a single statement as:
Student student1 = new Student( );
Constructors
- A constructor initializes object with its creation. It has the same name
as the name of its class.
- Once a constructor is defined, it is automatically called immediately
when the memory is allocated before the new operation completes.
- Constructor does not have any return type, its implicit return type is
class object.
- You can see constructor as a class type. Its job is to initialize the
instance variables of an object, so that the created object is usable just
after creation.
- Constructors can be defined in two ways.
o First , a constructor may not have parameter. This type of
constructor is known as non-parameterized constructor.
class Point
{
int x;
int y;
Point()
{
x = 2;
y = 4;
}
}
o The second, a constructor may take parameters. This type of
constructor is known as parameterized constructor.
class Point
{
int x;
int y;
Point(int a, int b)
{
x = a;
y = b;
}
}
name=vname;
}
public String getName() // regular method
{
return (name);
}
public abstract void Play();
// abstract method: no implementation
}
Method Overriding
- A subclass extending the parent class has access to all the non-private
data members and methods its parent class. Most of the time the
purpose of inheriting properties from the parent class and adding new
methods is to extend the behaviour of the parent class. However,
sometimes, it is required to modify the behaviour of parent class. To
modify the behaviour of the parent class overriding is used.
- Some important points that must be taken care while overriding a
method:
o i. An overriding method (largely) replaces the method it
overrides.
o ii. Each method in a parent class can be overridden at most once
in any one of the subclass.
o iii. Overriding methods must have exactly the same argument
lists, both in type and in order.
o iv. An overriding method must have exactly the same return type
as the method it overrides.
o v. Overriding is associated with inheritance.
- The following example program shows how member function area () of
the class Figure is overridden in subclasses Rectangle and Square.
class Figure
{
double sidea;
double sideb;
Figure(double a, double b)
{
sidea = a;
sideb = b;
}
Figure(double a)
{
sidea = a;
sideb = a;
}
double area( )
{
[Link]("Area inside figure is Undefined.");
return 0;
}
}
class Rectangle extends Figure
{
Rectangle( double a , double b)
{
super ( a, b);
}
double area ( )
{
[Link]("The Area of Rectangle:");
return sidea*sideb;
}
}
class Squre extends Figure
{
Squre( double a )
{
super (a);
}
double area( )
{
[Link]("Area of Squre: ");
return sidea*sidea;
}
}
class Area_Overrid
{
public static void main(String[] args)
{
Figure f = new Figure(20.9, 67.9);
Rectangle r = new Rectangle( 34.2, 56.3);
Squre s = new Squre( 23.1);
[Link]("***** Welcome to Override Demo ******");
[Link]();
[Link](" "+[Link]());
[Link](" "+[Link]());
}
}
Output:
***** Welcome to Override Demo ******
Area inside figure is Undefined.
The Area of Rectangle:
1925.46
Area of Squre:
533.61
Final Keyword
- In Java programming the final key word is used for three purposes:
- i. Making constants
- ii. Preventing method to be overridden
- iii. Preventing a class to be inherited
- The final keyword is a way of marking a variable as "read-only". Its
value is set once and then cannot be changed. For example, if year is
declared as
final int year = 2005;
Variable year will be containing value 2005 and cannot take any other
value after words.
- The final keyword can also be applied to methods, with similar
semantics: i.e. the definition will not change.
- You cannot override a final method in subclasses, this means the
definition is the “final” one.
- You should define a method final when you are concerned that a
subclass may accidentally or deliberately redefine the method
(override).
- If you want to prevent a class to be inherited, apply the final keyword
to an entire class definition. For example, if you want to prevent class
Personal to be inherited further, define it as follows:
final class Personal
{
// Data members
//Member functions
}
Now if you try to inherit from class Personal
class Sub_Personal extends Personal
It will be illegal. You cannot derive from Personal class since it is a final
class.
Implementing Interfaces
- To declare a class that implements an interface, include an implements
clause in the class declaration.
- Your class can implement more than one interface (the Java platform
supports multiple interface inheritance), so the implements keyword is
followed by a comma-separated list of the interfaces implemented by
the class.
- Remember that when a class implements an interface, it is essentially
signing a contract with the interface that the class must provide
method implementations for all of the methods declared in the
interface and its superinterfaces.
- If a class does not implement all the methods declared in the interface
the class must be declared abstract.
- The method signature (the name and the number and type of
arguments) for the method in the class must match the method
signature as it appears in the interface.
- Example of interface Calculate and implement it in a class:
public interface Calculate
//program
interface Calculate
int Ac_No;
int Amount;
double Rate_of_Int;
int time;
Ac_No = a;
Rate_of_Int = b;
time = c;
Amount = d;
void DisplayInt()
return( Amount*Rate_of_Int*time/100);
[Link]();
Output:
Package
- A package is a collection of related classes and interfaces providing
access protection and namespace management.
- Java programmer creates packages to partition classes.
- Partitioning of classes helps in managing the program. The package
statement is used to define space to store classes.
- In Java you can write your own package. Writing packages is just like
writing any other Java program. You just have to take care of some
points when writing packages. These are given below.
o There must be not more than one public class per file.
o All files in the package must be named name_of_class.Java
where name_of_class is the name of the single public class in
the file.
o The very first statement in each file in the package, before any
import statements or anything put the statement package
myPackageName;
CLASSPATH
- CLASSPATH is an environment variable of system. The setting of this
variable is used to provide the root of any package hierarchy to Java
compiler.
- Suppose you create a package named MyPak. It will be stored in
MyPak directory.
- Now let us say class named MyClass is in [Link] will store
[Link] in MyPak directory . To complie [Link] you have to
make
- MyPak as current directory and [Link] will be stored in MyPak.
- You cannot run [Link] file using Java interpreter from any
directory because [Link] is in package MyPak, so during
execution you will to refer to package hierarchy.
- For this purpose you have to set CLASSPATH variable for setting the top
of the hierarchy. Once you set CLASSPATH for MyPak , it can be used
from any directory.
- For example, if /home/MyDir/Classes is in your CLASSPATH and your
package is called MyPak1, then you would make a directory called
MyPak in /home/MyDir/Classes and then put all the .class files in the
package in /home/MyDir/Classes/MyPak1.
import keyword
- import is a Java keyword used to include a particular package or to
include specific classes or interfaces of any package.
- import keyword is used to:
o either include whole package by statement
import PackageName.*;
o or to import specific class or interface by statement
import [Link](or InterfaceName) .*;
throws keyword
- If you don't want to explicitly implement exception handling, you can
declare that your method throws an exception.
Exception
- An exceptional condition is considered as a problem, which stops
program execution from continuation from the point of occurrence of
it. Exception stops you from continuing because of lack of information
to deal with the exception condition. In other words it is not known
what to do in specific conditions.
- If the system does not provide it you would have to write your own
routine to test for possible errors. You need to write a special code to
catch exceptions before they cause an error.
- If you attempt in a Java program to carry out an illegal operation, it
does not necessarily halt processing at that point. In most cases, the
JVM sees for the possibility of catching the problem and recovering
from it.
- If the problems are such which can be caught and recovery can be
provided, then we say the problems are not fatal, and for this the term
exception is used rather than error.
Causes of Exception
- Exception arises at runtime due to some abnormal condition in
program for example when a method. E.g. division encounters an
abnormal condition that it can't handle itself, i.e. “divide by zero,” then
this method may throw an exception.
- If a program written in Java does not follow the rule of Java language
or violates the Java execution environment, constraints exception may
occur. There may be a manually generated exception to pass on some
error reports to some calling certain methods.
Block 3
Unit 2 – IO in Java
Block 4
Unit 1 – Applets
Applets
- Java Applets are essentially Java programs that run within a web page.
- Applet programs are Java classes that extend the [Link]
class and are embedded by reference within a HTML page.
- You can observe that when Applets are combined with HTML, they can
make an interface more dynamic and powerful than with HTML alone.
- While some Applets do nothing more than scroll text or play
animations, but by incorporating these basic features in web pages you
can make them dynamic.
- These dynamic web pages can be used in an enterprise application to
view or manipulate data coming from some source on the server.
- For example, an Applet may be used to browse and modify records in a
database or control runtime aspects of some other application running
on the server.
- Applets differ from Java applications in the way that they are not
allowed to access certain resources on the local computer, such as files
and serial devices (modems, printers, etc.), and are prohibited from
communicating with most other computers across a network.
- The common rule is that an Applet can only make an Internet
connection to the computer from which the Applet was sent.
Events
- In application environments, program logic doesn’t flow from the top
to the bottom of the program as it does in most procedural code.
- Rather, the operating system collects events and the program responds
to them.
- These events may be mouse clicks, key presses, network data arriving
on the Ethernet port, or any from about two dozen other possibilities.
- The operating system looks at each event, determines what program it
was intended for, and places the event in the appropriate program’s
event queue.
- Every application program has an event loop.
- This is just a while loop which loops continuously. On every pass
through the loop the application retrieves the next event from its
event queue and responds accordingly.
Applet LifeCycle
- 1. The browser reads the HTML page and finds any <APPLET> tags.
- 2. The browser parses the <APPLET> tag to find the CODE and possibly
CODEBASE attribute.
- 3. The browser downloads the Class file for the Applet from the URL
(Uniform Resource Locator) found in the last step.
- 4. The browser converts the raw bytes downloaded into a Java class,
that is a [Link] object.
- 5. The browser instantiates the Applet class to form an Applet object.
This requires the Applet to have a no-args constructor.
- 6. The browser calls the Applet’s init () method.
- 7. The browser calls the Applet’s start () method.
- 8. While the Applet is running, the browser passes all the events
intended for the Applet, like mouse clicks, key presses, etc. to the
Applet’s handle Event() method.
- 9. The default method paint() in Applets just draw messages or
graphics (such as lines, ovals etc.) on the screen. Update events are
used to tell the Applet that it needs to repaint itself.
- 10. The browser calls the Applet’s stop () method.
- 11. The browser calls the Applet’s destroy () method.
Layout Manager
- When you add a component to an applet or a container, the container
uses its layout manager to decide where to put the component.
Features of JavaBeans
- Individual Java Beans will vary in functionality, but most share certain
common defining features.
- Support for introspection allowing a builder tool to analyze how a
bean works.
- Support for customization allowing a user to alter the appearance and
behaviour of a bean.
- Support for events allowing beans to fire events, and informing builder
tools about both the events they can fire and the events they can
handle.
- Support for properties allowing beans to be manipulated
programmatically, as well as to support the customization mentioned
above.
- Support for allowing beans that have been customized in an
application builder to have their state saved and restored. Typically
persistence is used with an application builder’s save and load menu
commands to restore any work that has gone into constructing an
application.
RMI
- Java provides RMI (Remote Method Invocation), which is "a
mechanism that allows one to invoke a method on an object that
exists in another address space. The other address space could be on
the same machine or a different one. The RMI mechanism is basically
an object-oriented RPC mechanism."
- RPC (Remote Procedure Call) organizes the types of messages which
an application can receive in the form of functions. Basically it is a
management of streams of data transmission.
- RMI applications often comprised two separate programs: a server and
a client.
- A typical server application creates some remote objects, makes
references to them accessible, and waits for clients to invoke methods
on these remote objects. A typical client application gets a remote
reference to one or more remote objects in the server and then
invokes methods on them.
- RMI provides the mechanism by which the server and the client
communicate and pass information back and forth. Such an application
is sometimes referred to as a distributed object application.
Servlets
- Java has utility known as servlets for server side-programming.
- A servlet is a class of Java programming language used to extend the
capabilities of servers that host applications accessed via a request-
response programming model.
- Although servlets can respond to any type of request, they are
commonly used to extend the applications hosted by web servers.
- Java Servlet technology also defines HTTP-specific servlet classes. The
[Link] and [Link] packages provide interfaces and
classes for writing servlets.
- All servlets must implement the Servlet interface, which defines life-
cycle methods.
- When implementing a generic service, you can use or extend the
GenericServlet class provided with the Java Servlet API. The
HttpServlet class provides methods, such as doGet and doPost, for
handling HTTP-specific services.
JDBC
- During programming you may need to interact with database to solve
your problem. Java provides JDBC to connect to databases and work
with it.
- Using standard library routines, you can open a connection to the
database.
- Basically JDBC allows the integration of SQL calls into a general
programming environment by providing library routines, which
interface with the database.
- In particular, Java’s JDBC has a rich collection of routines which makes
such an interface extremely simple and intuitive.
JDBC Connection
Load the vendor specific driver:
- For example, an Oracle driver is loaded using the following code
snippet:
[Link]("[Link]")