Pdfcoffee.com Java Notes 3 PDF Free
Pdfcoffee.com Java Notes 3 PDF Free
Java Programming
(B.Tech)
Deepti Gupta
Lecture
Deptt. of Information Technology
Biyani Girls College, Jaipur
2
Published by :
Think Tanks
Biyani Group of Colleges
Edition : 2013
Price :
While every effort is taken to avoid errors or omissions in this Publication, any
mistake or omission that may have crept in is not intentional. It may be taken note of
that neither the publisher nor the author will be responsible for any damage or loss of
any kind arising to anyone in any manner on account of such errors and omissions.
Preface
I am glad to present this book, especially designed to serve the needs of the
students. The book has been written keeping in mind the general weakness in
understanding the fundamental concepts of the topics. The book is self-explanatory
and adopts the “Teach Yourself” style. It is based on question-answer pattern. The
language of book is quite easy and understandable based on scientific approach.
Any further improvement in the contents of the book by making corrections,
omission and inclusion is keen to be achieved based on suggestions from the
readers for which the author shall be obliged.
I acknowledge special thanks to Mr. Rajeev Biyani, Chairman & Dr. Sanjay
Biyani, Director (Acad.) Biyani Group of Colleges, who are the backbones and main
concept provider and also have been constant source of motivation throughout this
Endeavour. They played an active role in coordinating the various stages of this
Endeavour and spearheaded the publishing work.
I look forward to receiving valuable suggestions from professors of various
educational institutions, other faculty members and students for improvement of the
quality of the book. The reader may feel free to send in their comments and
suggestions to the under mentioned address.
Note: A feedback form is enclosed along with think tank. Kindly fill the
feedback form and submit it at the time of submitting to books of
library, else NOC from Library will not be given.
Author
Syllabus
CONCURRENCY: Processes and Threads, Thread Objects, Defining and Starting a Thread,
Pausing Execution with Sleep, Interrupts, Joins, Synchronization. APPLET: Applet
Fundamentals, using paint method and
drawing polygons.
Unit – I
Let‟s take your “hand” as an example. The “hand” is a class. Your body has two
objects of type hand, named left hand and right hand. Their main functions are
controlled/ managed by a set of electrical signals sent through your shoulders
(through an interface). So the shoulder is an interface which your body uses to
interact with your hands. The hand is a well architected class. The hand is being re-
used to create the left hand and the right hand by slightly changing the properties of
it.
Polymorphism
Polymorphism is the ability of an object to take on many forms. The most common
use of polymorphism in OOP occurs when a parent class reference is used to refer to
a child class object.
It is important to know that the only possible way to access an object is through a
reference variable. A reference variable can be of only one type. Once declared the
type of a reference variable cannot be changed.
Inheritance
Inheritance means to take something that is already made. It is one of the most
important feature of Object Oriented Programming. It is the concept that is used for
reusability purpose. Inheritance is the mechanism through which we can derived
classes from other classes. The derived class is called as child class or the subclass or
we can say the extended class and the class from which we are deriving the subclass
is called the base class or the parent class.
Encapsulation
Encapsulation is the technique of making the fields in a class private and providing
access to the fields via public methods. If a field is declared private, it cannot be
accessed by anyone outside the class, thereby hiding the fields within the class. For
this reason, encapsulation is also referred to as data hiding.
Abstraction
Abstraction refers to the ability to make a class abstract in OOP. An abstract class is
one that cannot be instantiated. All other functionality of the class still exists, and its
fields, methods, and constructors are all accessed in the same manner. You just
cannot create an instance of the abstract class.
Classes
A class can be defined as a template/ blue print that describe the behaviors/states that
object of its type support.
Objects
Objects have states and behaviors. Example: A dog has states-color, name, breed as
well as behaviors -wagging, barking, eating. An object is an instance of a class.
Method
byte:
short:
int:
long:
float:
double:
boolean:
char:
! Right is false
7) Conditional ?:
2-D Array
It denote rows and column. Like myArray has 4 rows and 4 column.
Unit – II
Ans There are two types of decision making statements in Java. They are:
if statements
switch statements
The if Statement:
Syntax:
if(Boolean_expression)
{
//Statements will execute if the Boolean expression is true
}
If the boolean expression evaluates to true then the block of code inside the if
statement will be executed. If not the first set of code after the end of the if
statement(after the closing curly brace) will be executed.
Example:
if( x < 20 ){
System.out.print("This is if statement");
}
}
This is if statement
Syntax:
if(Boolean_expression){
//Executes when the Boolean expression is true
}else{
//Executes when the Boolean expression is false
}
Example:
if( x < 20 ){
System.out.print("This is if statement");
}else{
System.out.print("This is else statement");
}
}
}
When using if , else if , else statements there are few points to keep in mind.
An if can have zero or one else's and it must come after any else if's.
An if can have zero to many else if's and they must come before the else.
Once an else if succeeds, none of he remaining else if's or else's will be tested.
Syntax:
if(Boolean_expression 1){
//Executes when the Boolean expression 1 is true
}else if(Boolean_expression 2){
//Executes when the Boolean expression 2 is true
}else if(Boolean_expression 3){
//Executes when the Boolean expression 3 is true
}else {
//Executes when the none of the above condition is true.
}
Example:
if( x == 10 ){
System.out.print("Value of X is 10");
}else if( x == 20 ){
System.out.print("Value of X is 20");
}else if( x == 30 ){
System.out.print("Value of X is 30");
}else{
System.out.print("This is else statement");
}
}
}
Value of X is 30
It is always legal to nest if-else statements, which means you can use one if or else if
statement inside another if or else if statement.
Syntax:
if(Boolean_expression 1){
//Executes when the Boolean expression 1 is true
if(Boolean_expression 2){
//Executes when the Boolean expression 2 is true
}
}
You can nest else if...else in the similar way as we have nested if statement.
Example:
if( x == 30 ){
if( y == 10 ){
System.out.print("X = 30 and Y = 10");
}
}
}
X = 30 and Y = 10
A switch statement allows a variable to be tested for equality against a list of values.
Each value is called a case, and the variable being switched on is checked for each
case.
Syntax:
switch(expression){
case value :
//Statements
break; //optional
case value :
//Statements
break; //optional
//You can have any number of case statements.
default : //Optional
//Statements
}
Example:
switch(grade)
{
case 'A' :
System.out.println("Excellent!");
break;
case 'B' :
case 'C' :
System.out.println("Well done");
break;
case 'D' :
System.out.println("You passed");
case 'F' :
System.out.println("Better try again");
break;
default :
System.out.println("Invalid grade");
}
System.out.println("Your grade is " + grade);
}
}
A for loop is a repetition control structure that allows you to efficiently write a loop
that needs to execute a specific number of times.
A for loop is useful when you know how many times a task is to be repeated.
Syntax:
The initialization step is executed first, and only once. This step allows you to declare
and initialize any loop control variables. You are not required to put a statement here,
as long as a semicolon appears.
Next, the Boolean expression is evaluated. If it is true, the body of the loop is
executed. If it is false, the body of the loop does not execute and flow of control
jumps to the next statement past the for loop.
After the body of the for loop executes, the flow of control jumps back up to the
update statement. This statement allows you to update any loop control variables.
This statement can be left blank, as long as a semicolon appears after the Boolean
expression.
The Boolean expression is now evaluated again. If it is true, the loop executes and the
process repeats itself (body of loop, then update step,then Boolean expression). After
the Boolean expression is false, the for loop terminates.
Example:
As of java 5 the enhanced for loop was introduced. This is mainly used for Arrays.
Syntax:
for(declaration : expression)
{
//Statements
}
Example:
for(int x : numbers ){
System.out.print( x );
System.out.print(",");
}
System.out.print("\n");
String [] names ={"James", "Larry", "Tom", "Lacy"};
for( String name : names ) {
System.out.print( name );
System.out.print(",");
}
}
}
A while loop is a control structure that allows you to repeat a task a certain number of
times.
Syntax:
while(Boolean_expression)
{
//Statements
}
When executing, if the boolean_expression result is true then the actions inside the
loop will be executed. This will continue as long as the expression result is true.
Example:
while( x < 20 ) {
System.out.print("value of x : " + x );
x++;
System.out.print("\n");
}
}
}
A do...while loop is similar to a while loop, except that a do...while loop is guaranteed
to execute at least one time.
Syntax:
do
{
//Statements
}while(Boolean_expression);
The Boolean expression appears at the end of the loop, so the statements in the loop
execute once before the Boolean is tested.
If the Boolean expression is true, the flow of control jumps back up to do, and the
statements in the loop execute again. This process repeats until the Boolean
expression is false.
Example:
do{
System.out.print("value of x : " + x );
x++;
System.out.print("\n");
}while( x < 20 );
}
}
The break keyword is used to stop the entire loop. The break keyword must be used
inside any loop or a switch statement.
The break keyword will stop the execution of the innermost loop and start executing
the next line of code after the block.
Syntax:
break;
Example:
public class Test {
for(int x : numbers ) {
if( x == 30 ) {
break;
}
System.out.print( x );
System.out.print("\n");
}
}
}
10
20
Continue statement
The continue keyword can be used in any of the loop control structures. It causes the
loop to immediately jump to the next iteration of the loop.
Syntax:
continue;
Example:
for(int x : numbers ) {
if( x == 30 ) {
continue;
}
System.out.print( x );
System.out.print("\n");
}
}
}
10
20
40
50
The last control statement is return. The return statement is used to explicitly
return from a method.
That is, it causes program control to transfer back to the caller of the method.
the return statement immediately terminates the method in which it is
executed.
class Return1
{
public static void main(String args[])
{
boolean t = true;
System.out.println("Before the return.");
if(t)
return; // return to caller
System.out.println("This won't execute.");
}
}
Output :
Before the return.
Ans If we consider the real-world we can find many objects around us, Cars, Dogs,
Humans etc. All these objects have a state and behavior.
If we consider a dog then its state is - name, breed, color, and the behavior is -
barking, wagging, running
If you compare the software object with a real world object, they have very similar
characteristics.
Software objects also have a state and behavior. A software object's state is stored in
fields and behavior is shown via methods.
So in software development methods operate on the internal state of an object and the
object-to-object communication is done via methods.
Ans A class is a blue print from which individual objects are created.
void barking(){
}
void hungry(){
}
void sleeping(){
}
}
int length;
int breadth;
int height;
int getVolume()
{
return (length * breadth * height);
}
Cube1()
{
length = 10;
breadth = 10;
height = 10;
}
Cube1(int l, int b, int h)
{
length = l;
breadth = b;
height = h;
}
}
}
Simple Inheritance
Multilevel Inheritance
Example
class A
{
int x;
int y;
int get(int p, int q)
{
x=p;
y=q;
return(0);
}
void Show()
{
System.out.println(x);
}
}
Class B extends A
{
public static void main(String args[])
{
A a = new A();
a.get(5,6);
a.Show();
}
void display()
{
System.out.println(x);
}
}
super is used to access the members of the super class.It is used for two purposes in
java.
1) To access the hidden data variables of the super class hidden by the sub class.
e.g. Suppose class A is the super class that has two instance variables as int a and
float b. class B is the subclass that also contains its own data members named a and b.
then we can access the super class (class A) variables a and b inside the subclass class
B just by calling the following command.
super.member;
Here member can either be an instance variable or a method. This form of super most
useful to handle situations where the local members of a subclass hides the members
of a super class having the same name. The following example clarify all the
confusions.
class A
{
int a;
float b;
void Show()
{
System.out.println("b in super class: " + b);
}
class B extends A
{
int a;
float b;
B ( int p, float q)
{
a = p;
super.b = q;
}
void Show(){
super.Show();
System.out.println("b in super class: " + super.b);
System.out.println("a in sub class: " + a);
}
Use the abstract keyword to declare a class abstract. The keyword appears in the
class declaration somewhere before the class keyword.
Final Variables
A final variable can only once assigned a value. This value cannot be changed latter.
If final variable used in class then it must assigned a value in class constructor.
Attempting to change the value of final variable/field will generate error.
Example-
[...]
}
Final Method
A final method cannot be overridden by sub class. To declare a final method put the
final after the access pacifier and before the return type.
Example-
Final Class
A class declared final cannot be sub classed. Other classes cannot extend final class.
It provides some benefit to security and thread safety.
Example-
Unit – III
Ans Package is a mechanism for organizing a group of related files in the same directory.
In a computer system, we organize files into different directories according to their
functionality, usability and category.Some of the existing packages in Java are::
Package names are written in all lowercase to avoid conflict with the names of classes
or interfaces.
The directory name must be same as the name of package that is created using
"package" keyword in the source file.
Before running a program, the class path must be picked up till the main directory (or
package) that is used in the program.
If we are not including any package in our java source file then the source file
automatically goes to the default package.
In general, we start a package name begins with the order from top to bottom level.
In case of the internet domain, the name of the domain is treated in reverse (prefix)
order.
Ans Java provides a number of access modifiers to set access levels for classes, variables,
methods and constructors. The four access levels are:
1) Default
2) Public
3) Private
4) Protected
Default access modifier means we do not explicitly declare an access modifier for a
class, field, method etc.
A variable or method declared without any access control modifier is available to any
other class in the same package. The default modifier cannot be used for methods,
fields in an interface.
Example:
Variables and methods can be declared without any modifiers, as in the following
examples:
boolean processOrder()
{
return true;
Methods, Variables and Constructors that are declared private can only be accessed
within the declared class itself.
Example:
A class, method, constructor, interface etc declared public can be accessed from any
other class.
Example:
Variables, methods and constructors which are declared protected in a superclass can
be accessed only by the subclasses in other package or any class within the package
of the protected members' class.
Example:
The following parent class uses protected access control, to allow its child class
override openSpeaker() method:
class AudioPlayer {
protected boolean openSpeaker(Speaker sp) {
// implementation details
}
}
class StreamingAudioPlayer {
boolean openSpeaker(Speaker sp) {
// implementation details
}
}
Ans An interface is not a class. Writing an interface is similar to writing a class, but they
are two different concepts. A class describes the attributes and behaviors of an object.
An interface contains behaviors that a class implements.
Declaring Interfaces:
Syntax:
import java.lang.*;
//Any number of import statements
Example:
Implementing Interfaces:
Mammal eats
Mammal travels
Ans Strings, which are widely used, are a sequence of characters. In the Java
programming language, strings are objects.
Creating Strings:
The String class has eleven constructors that allow you to provide the initial value of
the string using different sources, such as an array of characters:
hello
int length()
Returns the length of this string.
Unit - IV
The Exception class has two main subclasses : IOException class and RuntimeException
Class.
Ans Exception is a run-time error which arises during the execution of java program. The
term exception in java stands for an exceptional event. It can be defined as abnormal
event that arises during the execution and normal flow of program.
Ans Uncaught exceptions are those exception which are not handled in the program.
class Exc2
{
public static void main(String args[])
{
int d, a;
d = 0;
a = 42 / d;
System.out.println("This will not be printed.");
}
}
The first step in constructing an exception handler is to enclose the code that might
throw an exception within a try block. In general, a try block looks like the
following:
try {
code
}
Catch ()
{}
You associate exception handlers with a try block by providing one or more catch
blocks directly after the try block. No code can be between the end of the try block
and the beginning of the first catch block.
try {
Each catch block is an exception handler and handles the type of exception indicated
by its argument. If the program has multiple catch statement , it comes under the
category of multiple catch statement.
class Exc2
{
public static void main(String args[])
{
int d, a;
try
catch (ArithmeticException e)
Division by zero.
After catch statement.
import java.io.IOException;
<statements>
<statements>
<statements>
if (error){
throw new IOException("error reading file");
}
}
<statements>
if (error){
UNIT - V
THREAD
Ans Multithreading refers to two or more tasks executing concurrently within a single
program. A thread is an independent path of execution within a program. Many
threads can run concurrently within a program. Every thread in Java is created and
controlled by the java.lang.Thread class. A Java program can have many threads,
and these threads can run concurrently, either asynchronously or synchronously.
EXAMPLE
{
System.out.println("Child Thread : " + i);
Try
{
Thread.sleep(50);
}
catch(InterruptedException ie)
{
System.out.println("Child thread interrupted! " + ie);
}
}
/*
* To create new thread, use
* Thread(Runnable thread, String threadName)
* constructor.
*
*/
* Please note that, after creation of a thread it will not start running until
we call start method.
*/
t.start();
try{
Thread.sleep(100);
}
catch(InterruptedException ie){
System.out.println("Child thread interrupted! " + ie);
}
}
System.out.println("Main thread finished!");
}
}
Main thread : 0
Child Thread : 0
Child Thread : 1
Main thread : 1
Main thread : 2
Child Thread : 2
Child Thread : 3
Main thread : 3
Main thread : 4
Child Thread : 4
Child thread finished!
Main thread finished!
XThread()
{}
XThread(String threadName)
{
super(threadName); // Initialize thread.
System.out.println(this);
start();
}
public void run() {
//Display info about this particular thread
System.out.println(Thread.currentThread().getName());
}
}
try {
//The sleep() method is invoked on the main thread to cause a one second delay.
Thread.currentThread().sleep(1000);
}
catch (InterruptedException e)
{
}
System.out.println(Thread.currentThread());
}
}
Output
Thread[thread5,5,main]
thread1
thread5
thread2
Thread-3
Thread-2
Thread[main,5,main]
Ans Thread has many different state through out its life.
1 Newborn State
2 Runnable State
3 Running State
4 Blocked State
5 Dead State
Thread should be in any one state of above and it can be move from one state to
another by different methods and ways.
1 Newborn State
We can move it to running mode by invoking the start() method and it can be killed
by using stop() method.
2 Runnable State
It means that thread is now ready for running and its waiting to give control.
3 Running State
It means thread is in its execution mode becaause the control of cpu is given to that particular
thread.
These all are different methods which can be apply on running thread and how the state is
changing and how we can come in our original previous state using different methods are
shown in above figure.
4 Blocked State
A thread is called in Blocked State when it is not allowed to entering in Runnable State or
Running State.
5 Dead State
When a thread is completed executing its run() method the life cycle of that particular thread
is end.
We can kill thread by invoking stop() method for that particular thread and send it to be in
Dead State
Web browsers, which are often equipped with Java virtual machines, can interpret
applets from Web servers. Because applets are small in files size, cross-platform
compatible, and highly secure (can't be used to access users' hard drives), they are
ideal for small Internet applications accessible from a browser.
It is of five types
1. Init()
2. Start()
3. Paint()
4. Stop()
5. Destroy()
Init():- This is a method which initializes the applet with the required components
inside it. This method executes only once of the life cycle of an applet.
Start():- This method is responsible for activating the applet. This method executes
when applet will be restored or visible in the web browser. This method executes
more than once in the life cycle of an applet.
Paint():- This method can be used to draw different components or graphical shape
into the applet. This method can be executed repeatedly during the applet execution.
Destroy():- When the browser containing the applet will be closed then this method
will be called. This method execute only once in the life cycle of an applet.
Applet viewer is a command line program to run Java applets. It is included in the
SDK. The applet viewer command connects to the documents or resources
designated by urls. It displays each applet referenced by the documents in its own
window.
Where the URL specifies the location of the applet program and the Options
argument specifies how to run the Java applet.
The following program shows how to build an applet and the HTML file for it. Firstly
create a class. Then start the applet using init method. After that enter a string as str =
"This is my first applet". Use paint method to give the dimensions of the applet.
Beneath that is the HTML file which shows how to give the body for applet.
import java.applet.*;
import java.awt.*;
public class Myapplet extends Applet{
String str;
public void init(){
str = "This is my first applet";
}
public void paint(Graphics g){
g.drawString(str, 50,50);
}
}
<HTML>
<BODY>
<applet code="Myapplet",height="200" width="200">
</applet>
</BODY>
</HTML>
avac>appletviewer Myapplet.html
CAfter building the program, run the applet and the applet viewer as shown below.
C:\javac>appletviewer Myapplet.html
Gi
C
Q.8 Give an example to draw shapes in java ?
Ans In this program we will see how to draw the different types of shapes like line, circle
and rectangle. There are different types of methods for the Graphics class of the
java.awt.*; package have been used to draw the appropriate shape. Explanation of the
methods used in the program is given just ahead :
Graphics.drawLine() :
The drawLine() method has been used in the program to draw the line in the applet.
Here is the syntax for the drawLine() method :
Graphics.drawString() :
The drawSring() method draws the given string as the parameter. Here is the syntax
of the drawString() method :
Graphics.drawOval() :
The drawOval() method draws the circle. Here is the syntax of the drawOval()
method :
Graphics.drawRect() :
The drawRect() method draws the rectangle. Here is the syntax of the
drawRect() method :
import java.applet.*;
import java.awt.*;
<HTML>
<HEAD>
</HEAD>
<BODY>
<div align="center">
<APPLET CODE="CircleLine.class" WIDTH="800" HEIGHT="500"></APPLET>
</div>
</BODY>
</HTML>
MCQ’s
11. From these which one is the compulsory section in a java program?
A. Package statement
B. Import statement
C. Documentation section
D. Class declaration section
15. Which one of these lists contains only Java programming language keywords?
18. In java , if you do not give a value to a variable before using it ,______
A. It will contain a garbage value