Java Study Material
Java Study Material
by
Kamesh
Technologies
Explain the JAVA features
The inventors of JAVA wanted a language, which could offer solutions to some of the problems
encountered in the modern programming. Sun Micro Systems officially describe JAVA with the following
attributes
SIMPLE
SECURE
PORTABLE
OBJECT-ORIENTED
ROBUST
MULTI THREADED
ARCHITECTURE NEUTRAL
COMPILED & INTERPRETED
HIGH PERFORMANCE
DISTRIBUTED
DYNAMIC
SIMPLE: Java was designed to be easy professional programmer to learn and use effectively. If you
already understand the basic concepts of Object-Oriented Programming, learning Java will be even
easier. Because Java inherits the C/C++ syntax and many of the OOP features of C++. Also, some of the
confusing concepts from C and C++ are either left out of Java or implemented in a cleaner, more
approachable manner.
SECURE: You can safely download Java Applets without fear of viral infection. Java achieves this
protecting by confining a Java program to the Java execution environment and not allowing it access to
other parts of the computer
PORTABLE: Java ensures portability in two ways. First, Java compiler generates byte code instructions
that can be implemented on any machine. Secondly, the size of the primitive data types is machine-
independent.
OBJECT ORIENTED: Java is a true Object-Oriented language. All program code and data reside within
objects and classes. The object model in java is simple and easy to extend.
ROBUST: It provides many safeguards to ensure reliable code. It has strict compile time and runtime
checking for data types. It is designed as a garbage-collected language relieving the programmers
virtually all memory management problems. Java also incorporates the concept of exception handling,
which captures serious of errors and eliminates any risk of crashing the system.
MULTI THREADED: Multi-threaded means handling multiple tasks simultaneously. This means that we
need not wait for the application to finish one task before beginning another.
ARCHITECTURE-NEUTRAL: Java programs can be easily moved from one computer to another,
anywhere and anytime. Changes and upgrades in operating systems, processor and system resources
will not force any changes in Java programs. The java designer’s goal was “WRITE ONCE: RUN
ANYWHERE, ANYTIME FOREVER”.
COMPILED & INTERPRETED: Usually a computer language is either compiled or interpreted. Java
combines both these features. First Java compiler translates source code into byte code. Byte codes are
not machine instructions; Java interpreter generates machine code that can be directly executed by the
machine.
HIGH PERFORAMANCE: Java architecture is designed to reduce overheads during runtime. Further the
incorporation of multithreading enhances the overall execution speed of the java program.
DISTRIBUTED: It has the ability to share both data programs. Java applications can open and access
remote objects on Internet as easily as they can do in a local system. This enables multiple
programmers at multiple remote locations to collaborate and work together on a single project.
DYNAMIC: Java is a dynamic language. Java is capable of dynamically linking in new class libraries,
methods and objects.
All language compilers translate source code into machine code for a specific computer. The Java
compiler produces an intermediate code known as Byte Code for a machine that does not exist. This
machine is called the Java Virtual Machine and it exists only inside the computer memory. It is a
simulated computer within the computer and does all major functions of a real computer.
Java naming convention is a rule to follow as you decide what to name your identifiers such as class,
package, variable, constant, method, etc. But, it is not forced to follow. So, it is known as convention
not rule. These conventions are suggested by several Java communities such as Sun Microsystems and
Netscape.
By using standard Java naming conventions, you make your code easier to read for yourself and other
programmers. Readability of Java program is very important. It indicates that less time is spent to figure
out what the code does.
The following table shows the popular conventions used for the different identifiers.
Data types specify the different sizes and values that can be stored in the variable. There are two types
of data types in JAVA:
Non-Primitive Data Types : The non-Primitive data types include Classes, Interfaces and Arrays. These
are popularly known as user-defined data types
1. Unary Operators
2. Binary Operators
3. Ternary Operators
Unary Operators : If an expression having one operator and one operand, then it is called Unary
Operator. Type casting operators, Increment/Decrement operators etc. are the examples for Unary
Operators.
Binary Operators : If an expression having one operator and two operands, then it is called Binary
Operators. Arithmetic, Relations, Logical etc. operators are the examples.
Ternary Operators : If an expression having more than one operator and one operand, then it is called
Ternary Operator. Conditional operator is the example for Ternary Operator.
Looping Statements:
The process of repeatedly executing a block of statements is known as looping. The statements in the
block may be executed any number of times. A program loop consists of two segments, one known as
the body of the loop and the other known as control statement. A looping process, in general, would
include the following steps:
1. Setting and initialization of a counter
2. Execution of the statements in the loop
3. Test for a specified condition for execution of the loop
4. Incrementing the counter
5.
Java language provides three constructs for performing loop operations. They are
The while is entry controlled loop statement. The test condition is evaluated and if the condition is true,
then the body of the loop is executed repeatedly until the test condition finally becomes false and the
control is transferred out of the loop.
Initialization;
While(test condition)
{
Body of the loop
}
The ‘do….while’ provides an exit controlled loop and therefore the body of the loop is always executed
at least once. At the end of the loop, the test condition in while statement is evaluated. If the condition
is true, the program continues to evaluate the body of the loop. When the condition becomes false, the
loop will be terminated.
Initialization;
Do
{
Body of the loop
}while(test condition);
The ‘for’ statement:
The for loop is another entry-controlled loop that provides a more concise loop control structure.
for(initialization;test condition;increment)
{
Body of the loop;
}
The value of the control variable is tested using the test condition. The test condition is a relational
expression, such as I < 10. If the condition is true, the body of the loop is executed otherwise the loop is
terminated.
Explain ‘BREAK’
An early exit from a loop can be accomplished by using the break statement. This statement can be
used with switch, while, do or for.
When the break statement is encountered inside a loop, the loop is immediately exited and the program
continues with the statement immediately following the loop.
When the loops are nested, the break would only exit from the loop containing it. That is, the break will
exit only a single loop.
General form……..
While(test condition)
{
…..
…..
If(condition) break;
…..
….. exit from loop
}
…….
……
Explain ‘CONTINUE’
Like the ‘break’ java supports another similar statement called continue. The continue as the name
implies, causes the loop to be continued with the next iteration after skipping nay statements in
between.
General form………..
while(test condition)
{
……. Continue next iteration
…….
If(condition) continue;
…….
…….
}
In java, we can give a label to a block of statements, and we can transfer the flow after ‘break’ or
‘continue’ can be branched to the specified label ie., if we want to jump outside a nested loops or to
continue a loop that is outside the current one, then we may have to use the labeled continue or break
statements.
eg :- abc : for(……………………)
{
continues While(……………)
outer loop {
If(condition) break abc;
Continue abc; jumping out
} of both loops
}
…………
0 1 2 3 4 5 6 7 8 9
10 20 30 40 50 60 70 80 90 100
0 1 2 3 4 5 6 7 8 9
Similar to a single Dimensional Arrays JAVA provides Double Dimensional Arrays. Allocating memory
space in rows and columns for one variable is called Double Dimensional Arrays.
Usage :
data_type variable[][]=new data type[row range][column range];
Eg.
int s[][] = { {1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,16},{17,18,19,20}}; will creates
0 1 2 3
0 1 2 3 4
1 5 6 7 8
2 9 10 11 12
3 13 14 15 16
4 17 18 19 20
s
Any element of the array can be accessed with its index. For example if we want to access an element
of 3rd row and 4th column can be wrote as s[2][3].
Explain String class and methods
In JAVA, string is an object that represents sequence of character values. To create such kind of objects
JAVA provides String class which was defined in java.lang package. And the string class provides lot of
methods to perform operations on string such as length(), compareTo(),substring(), equals(),
equalsIgnoreCase() etc.
Remember, Java String is immutable which means it cannot be changed, whenever we change any
string, a new instance is created.
1. By String Literal
2. By new Key word
String methods:
Explain OOP
Object is an identifiable entity with some characteristics and behavior. For instance, we can say ‘orange’
is an object. Its characteristics are: it is spherical shaped, its color is orange, etc., its behavior is: it is
juicy and it tastes sweet-sour. While programming using OOP approach, the characteristics of an object
are represented by its data, and its behavior is represented by its function associated. Therefore, in OO
Programming, object represents an entity that can store data and has its interface through functions.
Grady Booch, a renowned contributor to the development of object-oriented technology defined OOPs
as follows: OOP is a method of implementation in which programs are organized as co-operative
collections of objects, each of which represents an instance of some class and a class is a mechanism to
combine the both data as well as it’s associated code.
Explain OOP benefits
OOP offers several benefits to both the program designer and the user. Object-orientation contributes
to the solution of many problems associated with the development and quality of software products.
The principle advantages are:
Through inheritance, we can eliminate redundant code and extend the use of existing classes
called reusability
We can build programs from the standard working modules that communicate with one another
rather than having to start writing the code from the scratch.
The principle of data hiding helps the programmer to build secure programs that cannot be
invaded by code in other parts of the program.
It is possible to have multiple objects to coexist without any interference
It is possible to map objects in the problem domain to those objects in the program
It is easy to partition the work in a project based on objects
Object-Oriented Systems can be easily upgraded from small to large systems
Message passing techniques for communication between objects make the interface description
with external systems much simpler
Software complexity can be easily managed
OOP not only benefits programmers, but also the end-users by providing an object-oriented user
interface. It provides a communication between analysts, designers, programmers and end-users. The
following terms are the fundamental features of OOP:
CLASS: Class is an extension of the idea of structure used in C. It is a new way of creating and
implementing a user-defined data type. “ A class is a way to bind the data and its associated functions
together”. It allows the data and functions to be hidden, if necessary, from external use.
OBJECT: Uniting both the data and operations is an object. Every object will have data structures called
attributes (data members or fields) and behavior called operations (member functions or methods).
ENCAPSULATION: Encapsulation is a mechanism that associates the code and the data it manipulates
and keeps them safe from external interference and misuse by hiding the data.
DATA ABSTRACTION: Creating new data type using encapsulated-items, that are well suited to an
application to be programmed, is known as data abstraction.
INHERITANCE: Inheritance is the process, by which one object can acquire the properties of another. It
allows the declaration and implementation of one class to be based on an existing class.
POLYMORPHISM: It allows a single name to be used for more than one related purpose, which are
technically different.
DYNAMIC BINDING: The code associated with a given procedure call is not known until its call at run-
time and it is popularly called as runtime polymorphism.
What is a class?
A class is a user-defined data type with a template that secures to define its properties. Once the class
type has been defined, we can create variables of that type using declarations that are similar to the
basic type declaration. In Java, these variables are termed as instances of classes, which are the actual
objects.
Data is encapsulated in a class by placing data fields inside the body of the class definition. These
variables are called instance variables because they are created whenever an object of the class is
instantiated. Then we must add methods that are necessary for manipulating the data contained in the
class. Methods are declared inside the body of the class but immediately after the declaration of
instance variables.
The basic form of a class definition is:
Class ClassName
{
[ fields declaration; ]
[ methods declaration; ]
}
Everything inside the square brackets is optional.
Field declaration-------------- data type field;
Method declaration---------- type methodName(parameter list)
{
Method-body;
}
What is an Object?
An object in java is essentially a block of memory that contains space to store all the instance variables.
Creating an object is also referred to an instantiating an object.
Objects in Java are created using the ‘new’ operator. The ‘new’ operator creates an object of the
specified class and returns a reference to that object.
What is a Constructor?
Java supports a special type of method, called a ‘constructor’ that enables an object to initialize itself
when it is created.
Constructor has the same name as the class itself. They do not specify a return type, not even void.
This is because they return the instance of the class itself.
class Numbers
{
int a;
int b;
Numbers(int x, int y) // constructor method
{
a=x;
b=y;
}
….
….
}
What is Method Overloading?
Creating methods that have the same name, but different parameter lists and different definitions is
called method overloading. Method overloading is used when objects are required to perform similar
tasks but using different input parameters. When we call a method in an object, java matches up the
method name first and then the number and type of parameters to decide which one of the definitions
to execute. This process is known as polymorphism.
To create an overloaded method, all we have to do is to provide several different method definitions in
the class, all with the same name, but with different parameter lists. The difference may either be in the
number or type of arguments. That is, each parameter list should be unique.
A class basically contains two sections. One declares variables and the other declares methods. These
variables and methods are called instance variables and instance method. This is because every time
the class is instantiated, a new copy of each of them is created. They are accessed using the objects.
Let us assume that we want to define a member that is common to all the objects and accessed without
using a particular object. That is, the member belongs to the class as a whole rather than the objects
created from the class. Such member can be defined as….
static int a;
The members that are declared static are called static members. Since these members are associated
with the class itself rather than individual object. These members are called as class variable and class
methods.
The mechanism of deriving a new class from an old one is called inheritance. The old class is known as
base class or super class or parent class and the new one is called the sub class or derived class or child
class. Reusability is an important aspect of OOP paradigm. Java supports this concept. Java classes can
be reused in secured ways. Inheritance is one way to reuse the properties of existing ones.
Defining a sub class……..
Super Class A
Sub Class B
Sub Class C
Super Super
Super Class A Class A Class B
Sub Class C
Sub Sub Sub
Class B Class C Class D
What is method overriding?
When the method is called, the method defined in the sub class is invoked and executed instead of the
same method defined in the super class. This is known as overriding. This is possible by defining a
method in the subclass that has the same name, same arguments in the super class.
Eg.
class SuperClass
{
void display()
{
System.out.println(“Hellow”);
}
}
class SubClass extends SuperClass
{
void display() // here method defined to override
{
System.out.println(“Hai”);
}
}
class OverrideDemo
{
public static void main(String arg[])
{
SubClass s=new SubClass();
s.display();
}
} O/P is Hai
All methods and variables can be overridden by default in subclass. If we wish to prevent the subclasses
from overriding the members of the super class, we can declare them as final using keyword final as
modifier.
Eg. final int size=100;
final void display()
{
…..
…..
}
What is ‘final’ class?
Sometimes we may like to prevent a class being further subclasses for security reasons. A class that
cannot be sub classed is called Final class.
Eg. final class AClass
{
……
……
}
What is ‘finalize()’ method?
Constructor is used to initialize an object when it is declared. Similarly java supported a concept called
‘finalization’, which is just opposite to initialization. The garbage collector automatically frees up the
memory resources used by the objects. But objects may hold other non object resources such as file
descriptors or window system fonts. In order to frees these resources we must use a ‘finalize method’.
This is similar to destructors in C++.
What is Abstract method and class?
A method must always be redefined in a subclass, thus making overriding compulsions. This is done by
using the modifier keyword ‘abstract’ in the method definition.
Eg. abstract void display();
When a class contains one or more abstract methods, it should also be declared abstract.
Eg. abstract class AClass
{
abstract void display();
}
We cannot use abstract classes to instantiate objects directly, can be extended.
Interface A interface
Class A
D
implements
extends extends
interface interface
B E
Interface D Extends
Interface C
implements
Implements
Class B Class E
class D
Explain multithreaded programming?
Multithreaded is a conceptual programming paradigm where a program is divided into two or more
subprograms, which can be implemented at the same time in parallel.
In most of our compilers, we have only a single processor and therefore in reality, the processor is doing
one thing at a time. However the processors switches between the processes so fast that is appears to
human beings that all of them are being done simultaneously. A thread is similar to a program that has
a single flow of control. It has a beginning, a body, and an end and executes commands sequentially. In
fact the main program is called single-threaded program. Every program will have at least one thread.
A program that contains multi flows of control is known as MULTITHREADED PROGRAM.
Main Thread
………..
…………
start() start()
start()
The above figure illustrates a java program with four threads, one main thread and three sub threads.
The main thread actually the main () method module, which is designed to create and start other three
threads. Once initiated by the main thread, the sub threads A, B and C run concurrently and shares the
resources jointly. Threads running parallel do not really mean that they actually run at the same time.
Since all the threads are running on a single processor, the flow of execution is shared between threads.
During the lifetime of a thread, there are many states it can enter. They include….
stop()
Running Runnable Dead state
stop() .
suspend() resume()
sleep() notify()
wait() Blocked state
When we create a thread object, the thread is born and is said to be new born state, we can do only
two things with it, one is schedule it for running using start() method and another is kill it using stop()
method.
New Born
start() stop()
Runnable state:-
The runnable state means that the thread is ready for execution and is waiting for the availability of the
processor. That is the thread has joined the queue of threads that are waiting for execution. If we want
a thread to relinquish control to another thread of equal priority before its turn comes, we can do so by
calling the yield() method.
yield()
Running means that the processor has given its time to the thread for its execution. The thread runs
until it relinquishes control on its own or a higher priority thread prompts it. A running thread may
relinquish its control in one of the following situation.
1. It has been suspended using suspend () method. A suspended thread can be revoked by using
the resume () method.
suspend()
resume()
2. We can put a thread to sleep for a specified time period using the method sleep (time).
sleep(t)
after t
3.
4.
Running Runnable Sleeping
3. It has been told to wait until some event occurs. This is done using the wait () methods and
scheduled to run against the notify() method.
wait()
notify()
5.
6.
Running Runnable Waiting
Blocked state:-
A thread is said to be blocked when it is preventing from entering into the runnable state and
subsequently the running state. This happens when the thread is suspended, or waiting. A blocked
thread is considered “not runnable” but not dead and fully qualified to run again.
Dead state:-
Every thread has a life cycle, a running thread ends its life when it has completed executing its run()
method. It is a natural death. However, we can kill the thread by calling the stop method at any state.
It is a premature death.
Explain synchronization?
The threads use their own data and methods provided inside their run methods. If they try to use data
and methods outside themselves, on such occasions, they may compete for the main resources and may
lead to serious problems. For example, one thread may try reading a record from a file while another is
still writing to the same file. Depending on the same situations we may get strange results. Java
enables to overcome this problem using a technique known as synchronization. In this case the
keyword “synchronized” helps to solve such problems by keeping a watch on such locations.
When we declare a method synchronized, java creates a “monitor” and hands it over the thread that
calls the method first time. As long as the thread holds the monitor, no other thread can enter the
synchronized location of code. Whenever a thread has completed its work of using synchronized
method it will hand over the monitor to the next thread.
Applets are small java programs that are primarily used in Internet computing. They can be transported
over the Internet from one computer to another. An Applet can be run using the Applet viewer or any
web browser that supports java.
An Applet, like any application program, can do many things for us. It can perform arithmetic
operations, display graphics, play sounds, accept user input, create animation, and play interactive
games. A web page can now contain not only a simple text or static image but also a java applet, which
can produce graphics, sounds and moving images.
Actually Applets are 2 types. One is writing code in local system and embeds them into web page.
Second, we can download an applet from a remote computer system and then embed it into a web
page.
Applet life cycle :-
Every java applet inherits a set of default behaviors from the Applet class. As a result, when an Applet is
loaded, it undergoes a series of changes in its state.
Begin Born
(load initialization
applet)
start()
stop()
Running Idle
stopped
start())
display
paint() destroy()
Dead
End
destroyed
Exit of Browser
Series of changes in an Applet’s state:
The Applet states include
Born or initialization state
Running state
Idle state
Dead or destroyed state
Initialization state:-
Applet enters the initialization state when it is first loaded. This is achieved by calling the init () method
of Applet class. The initialization occurs only once in the Applet’s life cycle.
Running state:-
Applet enters the running state when the system calls the start () method of A oncan also occur if the
Applet is already ‘stopped’ (Idle) state. The start () method may be called more than once.
Idle or stopped state:-
An Applet becomes idle when it is stopped from running. Stopping occurs automatically when we leave
the page containing the currently running Applet. We can also stop the Applet by calling the stop()
method explicitly.
Dead state:-
An Applet is said to be dead when it is removed from memory. This occurs automatically by invoking the
destroy () method when we quit the browser like initialization, destroying stage occurs only once in the
Applet’s lifecycle.
Display state:-
Applet moves to the display state whenever it has to perform some output operations on the screen.
This happens immediately after the applet enters into the running state. The paint () method is called to
accomplish this task. Almost every applet will have paint () method.