Java Notes
Java Notes
PROGRAMMING
Java Programming
Chapter 1
Introduction to JAVA
History of JAVA
JAVA Versions
Major release versions of Java, along with their release dates:
JDK 1.0 (January 21, 1996)
JDK 1.1 (February 19, 1997)
J2SE 1.2 (December 8, 1998)
J2SE 1.3 (May 8, 2000)
J2SE 1.4 (February 6, 2002)
J2SE 5.0 (September 30, 2004)
Java SE 6 (December 11, 2006)
Java SE 7 (July 28, 2011)
Java SE 8 (March 18, 2014)
1
Java Programming
JAVA Editions
JAVA features
Simple
Java Inherits the C/C++ syntax and many of the object oriented features C++.
Many confusing features like pointers and operator overloading are removed from java.
So for the professional programmers learning java is easy.
Java Is Object-Oriented
Java is a true object oriented language which supports all the features of OOP like Inheritance,
Encapsulation and Polymorphism. Almost everything is an object in java. All program code and
data reside within classes.
Java Is Distributed
Java is designed for the distributed environment of the internet, because it handles TCP/IP
protocols like HTTP and FTP.
Java supports network programming to communicate with remote objects distributed over the
network. Java provides libraries like RMI and CORBA to develop network applications.
2
Java Programming
Architectural Neutral
The java Compiler generates byte code, which has nothing to do with particular computer
architecture; hence a Java program is easy to interpret on any machine.
Portable
Java Byte code can be carried to any platform. No implementation dependent features.
Everything related to storage is predefined, example: size of primitive data types.
Robust
Robust simply means strong. Java uses strong memory management. There is automatic garbage
collection in java. There is exception handling and type checking mechanism in java which
makes java robust.
Multithreaded
Java multithreading feature makes it possible to write program that can do many tasks
simultaneously. Benefit of multithreading is that it utilizes same memory and other resources to
execute multiple threads at the same time.
Ex: While typing in MS Word, grammatical errors are checked along.
Platform Independent
Java programs can be run on computer systems with different OS and processor environment.
Java code is compiled by the compiler and converted into byte code. This byte code is a platform
independent code because it can be run on multiple platforms.
Secure
Java security feature enable us to develop virus free applications. Java programs always run in
Java runtime environment with null interaction with system OS that restricts them from
introducing virus, deleting or modifying files in the host computers, hence it is more secure.
3
Java Programming
SL.NO. C JAVA
1 C is procedure oriented programming JAVA is Object oriented programming
language. Language
2 Pointers concept is used Pointers concept is not used
3 C has goto statement No goto statement
4 #define,typedef and header files are #define,typedef and header files are not
available in C available in JAVA
5 Supports sizeof operator JAVA does not supports sizeof operator
6 Supports structures and unions JAVA does not supports structures and
unions
7 Manual memory management in C Automatic memory management in JAVA
8 C supports storage classes and C supports storage classes and
signed,unsigned modifiers signed,unsigned modifiers
JDK Components: JDK includes the following command line development tools
4
Java Programming
javac The compiler for the java programming language. Using this tool we can
compile java programs and generates byte codes.
Java The interpreter for java applications used to execute the java byte codes.
javadoc API documentation generator used to generate documentation for our java
programs.
Jdb Java debugger used to debug our java programs to find out any errors.
Javah C header and stub generator.Used to write native methods.
The Java APIs are pre written Java code that can be used by other programmers to create Java
applications. The java API is the set of huge number of classes and methods grouped into
packages and it is included with the java development environment.
5
Java Programming
6
Java Programming
7
Java Programming
Execution Engine:
The Execution Engine is Responsible for executing the program and it contains two parts.
Interpreter.
JIT Compiler (just in time compiler).
The java code will be executed by both interpreter and JIT compiler simultaneously
which will reduce the execution time and them by providing high performance. The code
that is executed by JIT compiler is called as HOTSPOTS (company).
What is JIT?
The current version of Sun Hotspot JVM uses a technique called Just-in-time (JIT) compilation
to compile the byte code to the native instructions understood by the CPU on the fly at run time.
Documentation section
Package Statement
Import Statement
Interface Statement
Class Statement
a. Documentation section: A set of comment lines like: name of the program, author name,
date of creation, etc.
b. Package statement: This is the first statement allowed in Java file, this statement declares a
package names.
c. Import statement: This statement imports the packages that the classes and methods of
particular package can be used in the current program.
d. Interface statement: An interface is like a class but includes group of methods declaration.
Inter face is used to implement the multiple inheritance in the program.
e. Class definition/statements: A Java program may contains one more class definitions.
f. Main method class: Every Java standalone program requires a main method, as it begins
the execution, this is essential part of Java program
8
Java Programming
9
Java Programming
Object
Any entity that has state and behavior is known as an object. For example: chair, pen, table,
keyboard, bike etc. It can be tangible or intangible entity.
Class
Collection of similar type objects is called class.
Ex: Apple, Mango, orange are the objects of class FRUITS.
Inheritance
When one object acquires all the properties and behaviors of parent object i.e. known as
inheritance. It provides extensibility.
Polymorphism
Information Hiding
Controlling access to the information provided to the user using access specifies.
For example: phone call, we don't know the internal processing.
Encapsulation
Binding (or wrapping) code and data together into a single unit is known as encapsulation. For
example: capsule, it is wrapped with different medicines.
10
Java Programming
Java Tokens: Tokens are the basic building-blocks of the java language.
Keywords: The Java programming language has total of 50 reserved keywords which have
special meaning for the compiler and cannot be used as variable names. Following is a list of
Java keywords in alphabetical order, click on an individual keyword to see its description and
usage example.
abstract assert boolean break byte
11
Java Programming
Identifier: Identifier is case sensitive names given to variable, methods, class, object, packages
etc
Integer literals:
Integer data that can be expressed in decimal (base 10), hexadecimal (base 16) or octal (base 8)
number systems as well.
Prefix 0 is used to indicate octal and prefix 0x indicates hexadecimal when using these number
systems for literals.
Ex:
1) int decimal = 100;
2) int octal = 0144;
3) int hexa = 0x64;
Floating literals: Floating point data consist of float and double values.
Ex: 0.6D, 33.7F, 2.6F…….
12
Java Programming
Separators: They are character used to group and arrange Java source code into segments.
Java uses 6 types of separators:
Comments:
A comment is a non executable portion of a program that is used to document the program.
Data types:
Java is strongly typed language. Data type specifies the type of value that can be stored in a
variable.
}
public static void main(String args[])
{
Scope Ob1, Ob2, Ob3;
}
1. Static variables
2. Static methods
3. Static block
14
Java Programming
Static variable: They are also called as class variables & static variable can be before any
objects of its class are created.. Static variables creates single memory block & are common to
the all object.
x
Ex: static int x;
40
Obj1 Obj4
Obj2 Obj3
A static variable can be accessed by directly by the class name & no need of an object.
Static block: The static block is used to initialize all the static variables before using them in
computation.
The static block gets executed exactly once when the class is first loaded.
15
Java Programming
Ex:
class StaticBlock
{
static int a=7;
static int b;
void printValues()
{
System.out.println(“a:”+a);
System.out.println(“b:”+b);
}
static // static block
{
System.out.println(“Inside Static Block”);
b=a+5;
}
public static void main(String args[])
{
StaticBlock obj=new StaticBlock();
obj. printvalues();
}
}
Command Line arguments: The values passed in the command line to the program during
execution after the file name are called command line arguments.
Command line arguments are stored in args[] array of main() method.
It is a way of providing input to the java program.
Control Statements
The control statements are used to control the flow of execution of the program.
Java contains the following types of control statements:
1) Selection Statements / Decision making statements: if, if-else, switch.
2) Repetition Statements / Looping Statements: while, do-while, for.
3) Branching Statements / Jumping Statements: break, continue, and return.
Selection statements:
if Statement:
This is a control statement to execute a single statement or a block of code, when the given
condition is true and if it is false then it skips if block and rest code of program is executed .
Syntax: if (conditional expression) {
<statements>;
}
Ex: If n%2 evaluates to 0 then the "if" block is executed. Here it evaluates to 0 so if block is
executed. Hence "This is even number" is printed on the screen.
int n = 10;
if (n%2 = = 0){
System.out.println ("This is even number");
}
if-else Statement:
The "if-else" statement is an extension of if statement that provides another option when 'if'
statement evaluates to "false" i.e. else block is executed if "if" statement is false.
Syntax:
if(conditional expression){
<statements>;
}
else{
<statements>;
}
17
Java Programming
Ex: If n%2 doesn't evaluate to 0 then else block is executed. Here n%2 evaluates to 1 that is not
equal to 0 so else block is executed. So "This is not even number" is printed on the screen.
int n = 11;
if(n%2 = = 0){
System.out.println("This is even number");
}
else{
System.out.println("This is not even number");
}
switch Statement:
The keyword "switch" is followed by an expression that should evaluates to byte, short, char or
int primitive data types ,only. In a switch block there can be one or more labeled cases. The
switch expression is matched with each case label. Only the matched case is executed, if no case
matches then the default statement (if present) is executed.
Syntax:
switch(expression){
case expression 1:<statement>;break;
case expression 2:<statement>;break;
...
case expression n: <statement>;break;
default:<statement>;
}//end switch
Ex: Here expression "day" in switch statement evaluates to 5 which matches with a case labeled
"5" so code in case 5 is executed that results to output "Friday" on the screen.
int day = 5;
switch (day) {
case 1: System.out.println("Monday"); break;
case 2: System.out.println("Tuesday"); break;
case 3: System.out.println("Wednesday");break;
case 4: System.out.println("Thrusday"); break;
case 5: System.out.println("Friday"); break;
case 6: System.out.println("Saturday");break;
case 7: System.out.println("Sunday");break;
default: System.out.println("Invalid entry");
}
18
Java Programming
Repetition Statements:
while:
This is a looping or repeating statement. It executes a block of code or statements till the given
condition is true.
Syntax:
while(expression){
<statement>;
}
Ex: Here expression i<=10 is the condition which is checked before entering into the loop
statements. When i is greater than value 10 control comes out of loop and next statement is
executed.
int i = 1;
//print 1 to 10
i++;
19
Java Programming
Ex: Here num is initialized to value "1", condition is checked whether num<=10. If it is so then
control goes into the loop and current value of num is printed. Now num is incremented and
checked again whether num<=10.If it is so then again it enters into the loop. This process
continues till num>10. It prints values 1 to10 on the screen.
Branching Statements:
Break statements:
The break statement is used for breaking the execution of a loop (while, do-while and for). It also
terminates the switch statements.
Syntax:
break; // breaks the innermost loop or switch statement.
break label; // breaks the outermost loop in a series of nested loops.
Ex: When if statement evaluates to true it prints "data is found" and comes out of the loop and
executes the statements just following the loop.
20
Java Programming
Continue statements:
This is a branching statement that are used in the looping statements (while, do-while and for) to
skip the current iteration of the loop and resume the next iteration .
Syntax: continue;
Ex:
21
Java Programming
return statements:
It is a special branching statement that transfers the control to the caller of the method. This
statement is used to return a value to the caller method and terminates execution of method.
Syntax: return;
return values;
return; //This returns nothing. So this can be used when method is declared with void return
type.
return expression; //It returns the value evaluated from the expression.
Ex: Here Welcome () function is called within println() function which returns a String value
"Welcome to roseIndia.net". This is printed to the screen.
22
Java Programming
Write a program to accept two numbers and print the addition of two numbers
import java.io.*;
public class SumOfTwoNumbers
{
public static void main (String args[]) throws IOException
{
int a, b, c;
DataInputStream ds = new DataInputStream(System.in)
System.out.println(“Enter 2 numbers”);
a=Ineger.parseInt(ds.readLine());
b=Ineger.parseInt(ds.readLine());
c=a+b;
System.out.println (“Sum=”+c);
}
}
23
Java Programming
Arrays
“An array is a collection of elements of the same data type”.
One-dimensional array:
Second,you should allocate the memory for an array using new and assign it to the array
variable
Syntax: variable_name =new datatype[size];
The elements in the array allocated by new will automatically be initialized to zero.
Ex 1:
class ArrayDemo
{
public static void main(String args[])
{
int a[]=new int[10];
a[0]=10;
a[1]=20;
System.out.println(a[0]);
System.out.println(a[1]);
}
}
24
Java Programming
Ex 2:
class ArrayDemo1
{
public static void main(String args[])
{
int a[]=new int[10];
int count=10;
for(int i=0;i<4;i++)
{
a[i]=count;
count=count+10;
}
for(int i=0;i<4;i++)
{
System.out.println(a[i]);
}
}
}
Multidimensional array:
Multidimensional arrays are declared by specifying another set of subscript operator for each
index.
25
Java Programming
Questions:
1. What is Domain Name Service? (Nov-2010:1-marks) (Nov-2012:1-marks)
2. Write the use of Web server? (Nov-2012:1-marks)
3. Who developed Java & when?
4. Explain the features of JAVA.
5. What is instance of operator? (Nov-2010:1-marks)
6. What is the role of JVM & explain its components? (Nov-2012:7-marks)
7. Write the difference between Java & c++. (Nov-2010:3-marks)
8. Explain JDK components.
9. Explain public static void main(String args[]). (Nov-2010:3-marks)
10. How Java is platform independent? (Nov-2010:1-marks)
11. Explain Java API packages.
12. What are the types of Java program.
13. What are the different phases of Java program development? (Nov-2012:3-marks)
14. Explain the structure of Java program.
15. What are the disadvantages of Java.
16. What are Java Tokens. (Nov-2012:1-marks)
17. What is typecasting?
18. Why java is Architecture neutral language ? Justify. (Nov-2012:3-marks)
19. Explain scope of a variable.
20. Explain conditional operator in Java with an example. (Nov-2010:2-marks)
21. Explain the creation of arrays.
22. Explain the operators in Java. (Nov-2012:4-marks)
23. Write a java program to find the factorial of a given integer number. (Nov-2012:3-marks)
24. What are the Data types in Java. (Nov-2011:1-marks) (Nov-2012:3-marks)
25. Write a program to print the multiplication table for a given number. (Nov-2010:5-marks)
26
Java Programming
Chapter-2
Object: object is an instance of a class used to access the both Data member & member
functions outside the class also.
Defining a class:
Syntax:
<access_ specifier> class <class_name><extends><super_class><implements><interface_list>
{
//data member
//member function
}
Note: If we declare a class as private then it is not visible to java compiler & hence we get
compile time error but inner class can be declared as private.
27
Java Programming
}
}
Note: In java no classes are terminated in semicolon.
Creating object:
Syntax: <class_name> <object_name>=new <class_name>(arguments_list)
Write a program to accept two numbers & calculating its sum using Class & Object.
class Sum
{
int a,b,ans;
DataInputStream ds=new DataInputStream(System.in);
void accept()
{
System.out.println(“Enter the two Numbers”);
a=Integer.parseInt(ds.readLine());
b=Integer.parseInt(ds.readLine());
}
void cal()
{
ans=a+b;
}
28
Java Programming
void display()
{
System.out.println(“Ans=”+ans);
}
}
public class Ex
{
public static void main(string args[])
{
Sum S=new Sum();
S.accept();
S.cal();
S.display();
}
}
Constructors:
They are used to initialize the object, constructor having the same name as the class name and
executes automatically when the object is created.
Ex: class XYZ
{
int x;
XYZ() //constructor
{
x=10;
}
}
Types of constructor :
Constructors are three types:
1. Default constructor (Non-parameterized constructor)
2. Parameterized constructor
3. Constructor overloading
1. Default constructor:-
Default constructor having no parameters & Executed automatically when the object is created.
If we doesn’t give the default constructor in the class, java automatically provides default
constructors that initializes the variables as ‘0’ or ‘NULL’.
Ex: class XYZ
{
int a,b;
XYZ() //default constructor or non-parameterised constructor
{
a=10;
b=20;
29
Java Programming
}
}
public class Ex
{
public static void main(String args[])
{
XYZ obj=new XYZ();
}
}
2. Parameterized constructor :-
The constructor having one or more parameters that is used to initialize the variable is called
parameterized constructor.
Ex: class XYZ
{
int a,b;
XYZ(int x, int y) //parameterised constructor
{
a=x;
b=y;
}
}
public class Ex
{
public static void main(String args[])
{
XYZ obj=new XYZ(10,20);
}
}
3. Overloaded constructor:
Two or more constructors having different parameters is called overloaded constructor.
Ex:
class XYZ
{
int a,b,c;
XYZ()
{
a=1;
b=2;
c=3;
}
XYZ(int x, int y)
{
a=x;
30
Java Programming
b=y;
c=20;
}
XYZ(int x, int y, int z)
{
a=x;
b=y;
c=z;
}
}
public class Ex
{
public static void main(String args[])
{
XYZ obj1=new XYZ();
XYZ obj2=new XYZ(10,20);
XYZ obj3=new XYZ(10,20,30);
}
}
}
public class Lab4
{
public static void main(String args[])
{
cube obj1=new cube();
cube obj2=new cube(10);
cube obj3=new cube(10,20,30);
obj1.display();
obj2.display();
obj3.display();
}
}
Method overloading:
Method names are same but parameters are different is called as method overloading.
Ex: class Ex
{
void add()
{
…………..
}
void add(int x,int y)
{
……………
}
void add(int x,int y,int z)
{
……………
}
}
Note: method overloading is one of the way to implement polymorphism in Java.
Write a program to find the area of different shapes using method overloading
class Area
{
DataInputStream ds=new DataInputStream(System.in);
void circle()throws IOException
{
double r,pi=3.142;
System.out.println("Enter the radius");
r=Double.parseDouble(ds.readLine());
System.out.println("Area of circle="+(pi*r*r));
}
void square()throws IOException
32
Java Programming
{
int s;
System.out.println("Enter the Sides of a SQUARE");
s=Integer.parseInt(ds.readLine());
System.out.println("Area of Square="+(s*s));
}
void rect()throws IOException
{
int b,l;
System.out.println("Enter the Bredth and Length");
b=Integer.parseInt(ds.readLine());
l=Integer.parseInt(ds.readLine());
System.out.println("Area of Rectangle="+(b*l));
}
void triangle()throws IOException
{
DataInputStream ds=new DataInputStream(System.in);
int br,h;
System.out.println("Enter the Bredth and Length");
br=Integer.parseInt(ds.readLine());
h=Integer.parseInt(ds.readLine());
System.out.println("Area of Trangle ="+(0.5*br*h));
}
}
public class Lab5
{
public static void main(String args[])throws IOException
{
Area obj=new area();
obj.circle();
obj.rect();
obj.square();
obj.triangle();
}
}
33
Java Programming
‘this’ Keyword
"this keyword refers to the current object”. It always points object that is currently executing.
Ex: class Xyz
{
int x,y;
{
this.x=a;
this.y=b;
}
void display()
{
System.out.println(“X=”+x);
System.out.println(“Y=”+y);
}
}
public class Ex
{
public static void main(String args[])
{
Xyz obj1=new Xyz(10,20);
Xyz obj2=new Xyz(100,200);
obj1.display();
obj2.display();
}
}
34
Java Programming
Inheritance
Definition: “Deriving a new class from an existing class or acquiring the properties of super
object from the sub class object
object”.
Concepts of Inheritance:
The derived class members can access all the features of base class.
Code reusability is one of the most powerful features of inheritance.
Reusing of code saves time, money and effort.
Syntax:
class <subclass_name> extends <superclass_name>
{
------------/data
/data member
------------/member
/member function
}
We can derive a sub class from an existing class using Extends.
Types of inheritance:-
1. Single inheritance
2. Multilevel inheritance
3. Hierarchical inheritance
4. Multiple inheritance
1. Single inheritance: One derived class derives to one base class is known as single
inheritance.
Or
One base class derives one derived class is known as single inheritance.
35
Java Programming
Example:
class A
{
}
class B extends A
{
Write a program to accept regno & name in base class & accept total marks & percentage
in derived class and display the same.
class A
{
String name;
int regno;
void accept ()
{
DataInputStream ds=new DataInputStream(System.in);
System.out,println(“enter the name”);
name=ds.readLine();
System.out,println(“enter the Register number”);
regno=Integer.parseInt(ds.readLine());
}
void display()
{
System.out.println(“Name=”+name);
System.out.println(“Register number=”+regno);
}
}
class B extends class A
{
void accept2()
{
36
Java Programming
int m1,m2,m3,total,per;
System.out,println(“enter the 3 subject marks ”);
m1=Integer.parseInt(ds.readLine());
m2=Integer.parseInt(ds.readLine());
ger.parseInt(ds.readLine());
m3=Integer.parseInt(ds.readLine());
}
void display2()
{
System.out.println(“Toal=”+(m1+m2+m3));
System.out.println(“Average=”+((m1+m2+m3)/3));
}
}
public class Ex
{
public static void main(String args[])
{
B obj=new B();
obj.accept();
obj.accept2();
obj.display();
obj.display2();
}
}
Multilevel inheritance:-
A class can be derived from another derived class is known as multilevel inheritance.
Example:
class A
{
}
class B extends A
37
Java Programming
}
class C extends B
{
Write a program to accept regno & name in base class & accept total marks & percentage
in derived class and display the same.
class A
{
String name;
int regno;
void accept()
{
DataInputStream ds=new DataInputStream(System.in);
System.out,println(“enter the name”);
name=ds.readLine();
System.out,println(“enter the Register number”);
regno=Integer.parseInt(ds.readLine());
}
void display()
{
System.out.println(“Name=”+name);
System.out.println(“Register number=”+regno);
}
}
class B extends A
{
void accept2()
{
String course, college;
System.out,println(“enter Your course ”);
course=ds.readLine();
college=ds.readLine();
}
void display2()
{
System.out.println(“Collage=”+collage);
System.out.println(“Course=”+course);
}
}
38
Java Programming
class C extends B
{
void accept3()
{
int m1,m2,m3,total,per;
System.out,println(“enter the 3 subject marks ”);
m1=Integer.parseInt(ds.readLine());
m2=Integer.parseInt(ds.readLine());
m3=Integer.parseInt(ds.readLine());
}
void display3()
{
System.out.println(“Toal=”+(m1+m2+m3));
System.out.println(“Average=”+((m1+m2+m3)/3));
}
}
public class Ex
{
public static void main(String args[])
{
C obj=new C();
obj.accept();
obj.accept2();
obj.accept3();
obj.display();
obj.display2();
obj.display3();
}
}
Hierarchical inheritance:-
One base class derives from two are more derived classes is called as hierarchical inheritance.
39
Java Programming
Example:
class A
{
}
class B extends A
{
}
class C extends A
{
}
class D extends A
{
write a program to accept regno & name in base class & accept total marks & percentage
in derived class and display the same.
class course
{
String name,regno;
void accept()
{
DataInputStream ds=new DataInputStream(System.in);
System.out,println(“enter the name”);
Name=ds.readLine();
System.out,println(“enter the Register number”);
regno=ds.readLine();
System.out.println(“Name=”+name);
System.out.println(“Register number=”+regno);
}
}
class bca extends course
{
void accept2()
{
Int total,per;
System.out,println(“enter total marks ”);
total=Integer.parseInt(ds.readLine());
System.out,println(“enter average ”);
per=Integer.parseInt(ds.readLine());
40
Java Programming
System.out.println(“Toal=”+total);
System.out.println(“Average=”+averag);
}
}
class bsc extends course
{
void accept3()
{
int total,per;
System.out,println(“enter total marks ”);
total=Integer.parseInt(ds.readLine());
System.out,println(“enter average ”);
per=Integer.parseInt(ds.readLine());
System.out.println(“Toal=”+total);
System.out.println(“Average=”+averag);
}
}
class bcom extends course
{
void accept4()
{
int total,per;
System.out,println(“enter total marks ”);
total=Integer.parseInt(ds.readLine());
System.out,println(“enter average ”);
per=Integer.parseInt(ds.readLine());
System.out.println(“Toal=”+total);
System.out.println(“Average=”+averag);
}
}
public class Ex
{
public static void main(String args[])
{
bca obj=new bca();
bsc obj2=new bsc();
bcom obj3=new bcom();
obj.accept();
obj.accept2();
obj2.accept3();
obj3.accept4();
}
}
41
Java Programming
Multiple inheritance:-
A derived class having two or more base classes is known as multiple inheritances
inheritances”
Java does not supports multiple inheritance, it will be implemented by “Interface concept”.
Method overriding
The return type, argument list, method names are same in both base class and derived class is
called as method overriding..
We cannot call the base class method from the derived class object.
Ex:
class A
{
void display()
{
System.out.println(“Class A”);
}
}
class B extends A
{
void display() //Overriding Method
{
System.out.println(“Class B”);
}
}
42
Java Programming
public class Ex
{
public static void main(String args[])
{
B obj=new B();
Obj.display();
Obj.display();
}
}
Super Keyword:-
The super keyword refers to the super class object.
If we want to call super class contractor explicitly, then the keyword super in java is used.
Super keyword is also used to access data member and member function of the super class that
has been hidden by a member of a sub class.
43
Java Programming
}
B(int y)
{
super(10);
b=y;
System.out.println(“Class B”+y);
}
}
Class Ex
{
public static void main(String args[])
{
B obj1=new B();
B obj2=new B(100);
}
}
44
Java Programming
final variable:
Declaring a variable with the final keyword makes that variable at constant once we design the
value to final variable, we can’t change it again.
Final variable are used to create Constant variable.
Ex: class A
{
final int x=10; // x is a constant variable
void display()
{
int x=20; // not allowed
System.out,println(“X=”+x);
}
}
public class Ex
{
45
Java Programming
final method:
A method can declared as Final to prevent sub classes from overriding it. The final method can’t
be overridden.
Ex:
class A
{
final void display()
{
System.out.println(“HELLO”);
}
}
class B extends A
{
void display() // not allowed
{
System.out.println(“BYE”);
}
}
final class:- The keyword final can also be used for class if we declare an class has final then
that class cannot be inherited.
The java has lot of built in final class likes String, Math, etc.
Ex:
final class A
{
void display()
{
System.out,println(“Hai”);
}
}
class B extends A // not allowed
{
void display()
{
System.out.println(“BYE”);
}
}
46
Java Programming
}
}
Ex:
abstract class College
{
abstract void accept();
abstract void display();
}
class Bca extends College
{
void accept()
{
47
Java Programming
}
void display()
{
}
}
class Bsc extends College
{
void accept()
{
}
void display()
{
}
}
Garbage collection:
Java automatically release the allocated memory is called as the automatic garbage collection.
Every object created for the particular class, there is a memory is allocated to that objects, if
there is no use of object references then it will canceled to be garbage. The java releases the
memory automatically.
JVM is responsible for realizing the memory allocated to a garbage collection.
Finalize method: we can do some cleanup operations this operation is known as finalization.
An object is garbage collected the memory will be cleanup using the finalize method & it reuse
for the further operation or memory allocations. This method is a member of the java.lang.object
class.
class XYZ
{
protected void finalize() throws IOException
{
System.out.println(“Garbage collection object”);
}
}
{
System.out.println(dept+" "+salary+" "+bonus+" "+total);
}
}
class accounts extends dept
{
void cal(double sal)
{
salary=sal;
bonus=salary*0.5;
total=salary+bonus;
}
}
class sales extends dept
{
void cal(double sal)
{
salary=sal;
bonus=salary*0.7;
total=salary+bonus;
}
}
class mange extends dept
{
void cal(double sal)
{
salary=sal;
bonus=salary*0.9;
total=salary+bonus;
}
}
public class Ex
{
public static void main(String args[])
{
accounts nn1=new accounts();
sales nn2=new sales();
mange nn3=new mange();
nn1.cal(10000);
nn2.cal(12000);
nn3.cal(15000);
nn1.display("accounts");
nn2.display("sales");
nn3.display("mange");
}
}
49
Java Programming
Strings
A combination or collection of characters is called as string.
The strings are objects in java of the class ‘String’.
System.out.println(“Welcome to java”);
The string “welcome to java” is automatically converted into a string object by java.
A string in java is not a character array and it is not terminated with “NULL”.
1. Length:
public int length();
It will give the length of a string.
2. concat:
public String concat(String str);
It used to concating of two string.
50
Java Programming
3. equals:
public Boolean equals(String obj);
This method also check weather two strings are equal or not . it returns true if the two
strings are equal otherwise it returns false.
4. equalsIgnoreCase:-
public Boolean equalsIgnoreCase(String obj);
The method ignores the case while comparing the content, It return Truewhen the two
strings character are in the different cases.
5. toLowerCase:-
public String toLowerCase();
This method converts all the character to Lower case.
6. toUpperCase:-
public String toUpperCase();
This method converts all the character to Upper case.
This method is also replace the old string to the new string.
String str1=”JAVA”
String str2=str1.replace(‘JAVA’, ‘KAVA’);
1. append(): This method is used to concatenating the two strings, It is affected to the
current object.
Ex: StringBuffer s1=new StringBuffer(“vvfgc”);
StringBuffer s2=new StringBuffer(“college”);
System.out.println(“Append=”+s1.append(s2));
2. insert(): Insert the string s2 at the position ‘n’ of the string s1.
Ex: StringBuffer s1=new StringBuffer(“vvfgc”);
StringBuffer s2=new StringBuffer(“fgc”);
s1.insert(3,s2);
3. SetLength():This method is used to set the length from the string to ‘n’.
Syntax: s1.SetLength(n);
Ex: StringBuffer s1=new StringBuffer(“vvfgc”);
s1.setLngth(3);
th
4. SetcharAt(): This method is used to set the n character to the given new character.
Syntax: s1.SetcharAt(n,char new);
Ex: StringBuffer s2=new StringBuffer(“java”);
53
Java Programming
s2.setcharAt(0,’k’);//kava
5. reverse(): This method is used to reverse the character with in an object of the string
buffer class.
Syntax: s1.reverse();
Ex: StringBuffer s1=new StringBuffer(“vvfgc”);
s1.reverse();
Vector:
“A vector is a class that provides the capability to implement a growable array of object”.
Vector class is constructed under the java.util.package.
Vectors are array list with extended properties which follow the dynamic and automatic addition
of data at runtime.
54
Java Programming
add():
void add(int);
void add(int pos, int ele);
capacity():
int capacity();
It returns the current capacity of this vector.
remove():
remove(int pos);
It removes the element at specified position in this vector.
size():
int size();
It returns the no. of elements in this vector.
clear():
void clear();
It removes all the elements from this vector.
Ex:
public class Ex
{
public static void main(String args[])
{
Vector v = new Vector();
for(int i=1;i<=10;i++)
v.add(i);
v.add(4,100);
System.out.println(“vector elements : “+v);
v.remove(3);
}
}
Wrapper classes:
“Wrapper classes are used to represent primitive values when all object is required, the wrapper
class encapsulate a single value for the primitive data type”.
Before we can instantiate a wrapper class, we need to know it’s name and arguments it’s
constructor accepts. The name of the wrapper class corresponding to each primitive data type
along with the args it’s constructor accepts.
55
Java Programming
We can also create the wrapper class object by using valueOf() method.
Integer n = Integer.valueOf(“101011”,2); //43
valueOf converts 101011 to 43 and assigns to the object ‘n’;
56
Java Programming
Chapter-3
Interface
Java class not support multiple inheritance (two or more base class derives one derived class)
(Class D extends A, B, C is invalid)
(Class D extends, extends A, extends B, extends C is invalid)
For the above disadvantages java implements new concepts call it as interface.
“An interface is an alternate approach to support the concepts of multiple inheritance and
contains final variable & abstract methods”.
Syntax:
interface <interface_name>
{
final fields
abstract methods
}
All the methods in an interface are an implicitly extract and public variable declared implicitly
final
57
Java Programming
Extending interface
interface interface
A B
C interface
An interface can only be extended from another interface and can also extend from multiple
interface.
Implementing interface:
Syntax:
class <class_name> implements <interface_name1>, <interface_name2>, ....
{
......
}
‘implements’ is a keyword used to specify that a class inherits the behaviour from an interface
and as return the function definition(implements) for every method of an interface.
A class can implements multiple interfaces.
The interface extends interface.
Class implements interface
Class extends class implements interface
interface addition
{
void add();
}
interface subtraction
{
void sub();
}
interface multiplication
{
void mult();
}
class Arithmetic implements addition, subtraction, multiplication
{
void add ()
{
System.out.println (“This is addition”);
}
void sub ()
58
Java Programming
{
System.out.println (“This is subtraction”);
}
void mult ()
{
System.out.println (“This is multiplication”);
}
}
public class Ex
{
public static void main (static args[])
{
Arithmetic obj=new arithmetic ()
obj.add ();
obj.sub ();
obj.mult ();
}
}
B C
class Class
B
Class C interface
59
Java Programming
private: - It is access able only with in the class and it does not allow to access its data member
and member function from outside. It is also called as most restrictive access specifies.
Ex:
private int x;
private void accept ();
60
Java Programming
public: Any variable or methods is declared as public, than it is entire class and also visible to
outside the class. It is also called as least restrictive access specifier.
Ex: public int x;
public void accept ();
protected: Any variable or method is declared as protected, it is visible only to sub class in same
package and all sub class in other package.
Ex: -protected int x;
protected void accept ()
Ex: int x;
void accept();
61
Java Programming
Packages
Types of packages:
Java packages are classified into two catagerious
java API packages.
user defined packages (built in packages).
Java
Java
Util
Date
Time
[Note: - The details of all the API packages are in the 1st chapter]
62
Java Programming
Java uses separate directory or folder to manage the packages. We can’t create a hirarachils of
packages also. The package can also contain another package called sub package.
63
Java Programming
Syntax: -
import package_name.*;
Or
import package_name.class_name;
Or
import pack1.pack2.pack3.pack4.*;
Or
import pack1.pack2.pack3.pack4.class_name:
Here pack1 is the name of the top level package,
pack2 is the name of next level package,
pack3 is the name of the next level of package. So on
The statement must terminate with a (;) semicouln
The import java.io.*; appear before class definition in program.
Ex:
package pack1;
import java.io.*;
public class EX
{
public void display ()
{
System.out.println (“this is a pack1.package”);
}
}
Save the file in pack1 folder as Ex.java
Compile Ex.java file successfully then it will creates EX. class file
Save this file as xyz.java in outside the pack1 folder & executes this file
C:\>d:
D:\>cd pack1
D:\>pack1>set path=c:\programfiles\java\jdk1.6\bin
D:\pack1>javac Ex.java
64
Java Programming
D:\pack1>cd….
D:\>javac xyz.java
D:\>java xyz
This is pack1 package
65
Java Programming
Chapter 4
Multithreaded Programming
Ex: - An MS word program can check the spelling of word while we type the document.
Java program make use of both process based and thread based multitasking.
Thread=>”A single line of execution”
Multithreaded=>”Multiple line of execution”
Type of threads
Daemon threads
User threads
Daemon thread usually designed to run in the background for the purpose of servicing user
thread.
User thread: - The main thread is a user thread made a variable by JVM. This thread is a
launched in public static void main method. From there main thread we can create all other
threads. We already work with one particular thread since from our java first program i.e. main
thread
Creating threads:
Threads can created in two different ways.
66
Java Programming
}
}
Output
Thread A: 1
Thread B: 1
Thread A: 2
Thread B: 2
Thread A: 3
Thread B: 3
Thread A: 5
Thread B: 5
Exit from B
Exit from A
Born Stage
Start()
run()
Stop()
Runnable Running
Dead Stage
sleep() Stop()
wait() Notify()
suspend() resume(
Blocked Stage
During the life time of a Thread there are many stages of a Thread can enter they are
1. Born state
2. Runnable state
3. Running state
69
Java Programming
4. Blocked state
5. Dead state
1. Born state:- While creating the object for a thread class and this object is not yet running.
Then the Thread is new born state.
2. Runnable state :- When the start() is called the Thread object, the thread is in the runnable
state.
3. Running state:- A thread currently being executed by the cpu is in the running state.
4. Blocked state:- When the thread is suspended, sleeping or waiting in order to satisfied certain
requirement then the thread is in blocked state.
5. Dead state:- A running thread ends its life when it has computed its execution (Run()), then it
is called a natural death.
Thread Priorities:-
Thread priority is an integer value that identifies the relative order in which it should be executed
with respect to others. The Thread priority values ranging from 1 to 10 & default value is 5. But
if a Thread has highest priority does not means that will execute 1st , the Thread scheduling
depends on the operating system.
setPriority :- It is used to set the priority that can increase the chances of the
execution.
(Public final void setPriority (int value);)
t1.setPriority(10);
PROGRAM:
import java.io.*;
import java.lang.*;
class A extends Thread
{
public void run ()
{
for(int i=1;i<=5;i++)
System.out println(“Thread A “+i);
System.out.println (“Exit from A”);
}
}
class B extends Thread
{
public void run ()
{
for (int i=1;i<=5;i++)
System.out.println (“Thread B“+i);
System.out.println (“Exit from B”);
}
}
public class Ex
{
public static void main (String args[])
{
A obj=new A ();
B obj=new B ();
obj2.setPriority (10);
obj1.setPriority (1);
obj1.setName (“1st Thread”);
obj2.setName (“2nd Thread);
obj1.start ();
obj2.start ();
System.out.println (“Thread 1 Name=”+obj1.getName ());
71
Java Programming
Synchronization :-
“It is the process of avoiding multiple Thread to act on same data or method”
Synchronization is uses while execution time, the one Thread is under execution process there
is no possibility to enter another Thread into execution.
Synchronize block :-
Synchronized block is used to synchronize block of statement in a method
Syntax:-
Synchronized(object)
{
……..
……..
……..
}
72
Java Programming
Chapter 5
EXCEPTION HANDLING
Exception Handling
“The mechanism of handling runtime errors or exceptions is called Exception handling.”
Types of Exceptions
Exception
73
Java Programming
try :
try
{
……………
…………… //java statements
}
The try block consists of a executable statements that can possible to throw exceptions
implicitly.
try block throw the exceptions implicitly, if the exception occurs in this block.
catch block:
try
{
……
…… //java statements
}
catch(exception_type e)
{
……
……. //processing of exception
}
Example:
import java.io.*;
public class Ex
{
public static void main(String args[])
{
int d=0;
try
{
System.out.println(10/d);
}
catch(ArithmeticException e)
{
System.out.println(e.getMessage());
}
}
}
We can also use multiple catch blocks to handle different types of Exceptions. If the try block
throw an Exception,that will matches the catch block Exception type and processing the
Exception in the particular catch block.
Ex: try
{
int y=a[1]/a[0];
System.out.println(“Y=”+y);
em.out.println(“Y=”+y);
a[2]=30;
}
catch(Arithmeticexception e)
{
System.out.println(“Don’t’t divide by zero”);
}
catch(ArrayIndexoutOfBoundsException e)
{
System.out.println(“It is Array Index Out of Bounds”);
}
catch(ArrayStoreException e)
{
System.out.println(e.getMessage());
}
}
[Note: Checked Exception classes and Unchecked Exception classes see the Text book or browse
in the Internet.]
catch(NegativearraySizeException e)
76
Java Programming
Example:
import java.io.*;
public class Ex
{
public static void main(string args[])
{
int size;
int[] a=new int[10];
size=Integer.parseint(args[0]);
try
{
if(size<0)
throw new negativeArraySizeException(“Plz enter positive size”);
for(int i=0;i<size;i++)
a[i]=i+1;
}
catch(NegativeArraySizeException e)
{
System.out.println(e);
}
}
}
throws keyword(clause)
“The throws keyword is used when the programmer doesn’t wants to handle the exception in the
method(inside the method) and throw it out of method.”
The method must declare it using the ‘throws’ keyword. ‘throws’ keyword appears at the end of
a method signature ,if multiple exceptions are there ,we can separate it with comma operator(,).
Syntax:
return_typemethod_name(parameter_list)throws Exception_type1,Exception_type2,…..
{
……..
……..
}
Ex:
public class Ex
{
public static void main(String args[])throws IOException,NumberFormatException
{
…….
…….
}
}
77
Java Programming
finally block
“A finally block of code always executes whether an Exception as occurred or not.”
Finally block appears at the end of the catch block or at the end of try block.
try
No Exception Exception
finally catch
finally
Syntax:
try
{
………
……….
}
catch(Exception_type e)
{
…….
…….
}
finally
{
……..
…….. //finally block always excecutes.
}
finally block is commonly used for:
Closing a file.
Closing a result set.
Closing the connection established with connection.
[Note: finally block is optional.]
78
Java Programming
Ex:
importjava.io.*;
public class Ex
{
public static void main(String args[])
{
int size;
int[] a=new int[10];
size=Integer.parseint(args[0]);
try
{
if(size<0)
throw new NegativeArraySizeException(“Plz enter positive size”);
for(int i=0;i<size;i++)
a[i]=i+1;
}
finally
{
System.out.println(“This is Finally Block”);
}
}
}
Here we have created our own exception class called as Vvfgc, which is a sub class os
NegativeArraySizeException. By running the program with negative value, the output will be,
Vvfgc: plz enter +ve array size.
Propagation of Errors.
Another feature of Java Exception is the ability to propagate error reporting of the call of
methods using exception classes.
Note:
* We can have nesting of try statements, which means, we can have try-catch block within try
block.
* If we keep System.exit(0); in try block, then it will not go to the finally block.
80
Java Programming
Chapter 6
Applets
Definition: “Applet is a small application that is embedded into an HTML page, which is
accessed and transported over the Internet.”
Applets can be used to provide dynamic user-interface and a variety of graphical effects for web
pages.
Differences between Applets and applications
Applets Applications
Applets do not have main() method Applications have main() method
Applets can be embedded into HTML Applications cannot be embedded into
pages HTML pages
Applets only are executed within a Java Application program can be compatible
browser or applet viewer executed using Java interpreter
init(): It’s the method used to initialize the applet before it gets loaded.
start():It’s used to provide startup behavior for an applet.
stop():Its used to stop any operations which are started using start() method.
destroy(): Its used when an applet has finished its execution.
These methods are called automatically by the JVM .In the Applets life cycle methods, start and
stop methods can be called multiple times whereas init() and destroy() can be called only once
in the entire life span of an Applet.
81
Java Programming
init ()
Begin Born
start ()
stop ()
Running Idle
paint ()
start ()
destroy()
Dead
init():This is the first method called by an applet once it has been loaded by the browser. The
applet is born at this stage and loading images, initial values, setup colors etc.
public void init()
{
..... //action
}
start(): This method occurs automatically after the applet is initialized, any calculations and
processing of the data should be done in this method
public void start()
{
..... //action
}
stop(): stop() method occurs automatically when we leave the page. if user minimized the
webpage, the this method is called and when user again comes back to the page the start()
method is called.
public void stop()
{
..... //action
}
destroy(): This method is called when an applet is being terminated from memory. The stop()
method will always be called before destroy().
public void destroy()
{
..... //action
}
paint(): This method is not a part of an aplet life cycle. Applets moves to the display state when
it has to perform some output operations on the screen. It occurs immediately after applet runs
into start() method.
public void paint(Graphics g)
{
..... //User interface elements and display strings
}
82
Java Programming
Run this .html page using either appletviewer through command prompt
…\bin>appletviewer <filename.html>
Or
Open the <filename.html> via web browser.
84
Java Programming
In our applet program these parameters are passed when it is load init() method of applet
String name;
String size:
public void init()
{
Name=getParameter(“font”);
Size=getParameter(“size”);
}
e.g:
import java.applet.Applet;
import java.awt.Graphics;
public class Ex extends Applet
{
int x,y;
public void init()
{
x=Integer.parseInt(getParameter(“xvalue”));
y=Integer.parseInt(getParameter(“yvalue”));
}
public void paint(Graphics g)
{
g.drawString(“Vidyavahini”,x,y);
}
}
<html>
<body>
<applet code=”Ex.class” width=400 height=400>
<PARAM Name=xvalue value=100>
<PARAM Name=yvalue value=100>
</applet>
</body>
</html>
SIT Extension<br>
Tumkur
</body>
</html>
86
Java Programming
update() Method
This method is used to redraw the portion of its window. Update() method performs all necessary
display activities.
public void update(Graphics g)
{
}
public void paint(Graphics g)
{
update(g);
}
repaint() method:
When every our applet needs to update the information displayed in its window,it simply calls
repaint() is used to repaint the window.
void repaint(int left, int width,int height);
Specified region that will be repainted.
void repaint();
Causes window to be repainted.
Advantages of Applets
Applets can ran on windows, MsOs and Linux platform.
Applets can work all the version of the JavaPlugin.
Applets can work without security approval.
Applets are supported by most web browsers.
Applets are quick to load when returning to web pages.
Disadvantages of Applets
Java plugin is required to run applet.
Java applet requires JVM, so first time it takes some small startup time.
It is difficult to design and build good user interface in applets compared to other technologies.
Awt Controls
Labels
Buttons
Textfields
Check Boxes
Lists
All these controls are subclasses of component class. To add controls to a window we can use add()
methods.
87
Java Programming
Labels
Label ()
Label (String str)
Label (String str,int align)
Label L1=new Label (“Student Name:”);
add (L1);
Text fields
TextField()
TextField(int <no of char>)
TextField(String str)
TextField(String str, int <no of char>)
TextField t=new TextField();
add(t);
Buttons
Button()
Button(String Str);
Button b=new Button(“submit”);
add(b);
Graphics Programming
The graphics class with in the abstract windowing tool kit (AWT)makes it possible for a java
programmer to draw simple geometric shapes, print text and position images with in the
borders of a component, such as a applet, frame, panel or canvas.
The graphics class used draw lines, shapes, characters and images to the screen inside an
applet.
The graphics co-ordinate system
To draw an object on the screen, you call one of the drawing methods available in the graphics
class. All the drawing methods have arguments representing end points, sorting locations of the
objects as values in the applet’s co-ordinate system.
X
(10,10)
(100,100)
88
Java Programming
Drawing Lines
void drawLine(int x1, int y1, int x2, int y1);
The drawLine() takes four arguments (x1, y1)co-ordinates of the starting point and (x2, y2) co-
ordinates of the ending point.
public void point(Graphics g)
{
g.drawLine(50,50,200,200);
}
Drawing Rectangles
There are 3 kinds of rectangles :
Plain rectangles.
Rounded rectangles.
Three dimensional rectangles.
public void point(Graphics g)
{
g.drawRect(100,100,200,200);
g.fillRect(200,200,300,300);
}
public void point(Graphics g)
{
g.drawRoundRect(20,20,60,60,50,50);
g.fillRoundRect(120,20,60,60,25,25);
}
public void point(Graphics g)
{
g.draw3DRect(20,20,60,60,true);
g.draw3DRect(120,20,60,60,false);
}
void drawRect(int x1,int y1,int x2,int y2);
89
Java Programming
Drawing Arcs
An arc is a part of an Oval, the easiest way to think of an arc is as a complete Oval.
void drawArc(int x1,int y1,int x2,int y2,int rectangle, int
arcangle);
public void point(Graphics g)
{
g.drawArc(50,50,80,60,45,120);
g.fillArc(150,50,80,60,45,120);
}
Drawing polygons
Polygons are shapes with an unlimited number of sides. To draw a polygon, we need a set of ‘x’
and ‘y’ co-ordinates.
The drawPolygon() and fillPolygon() methods takes 3 arguments:
An array of integers representing x-co-ordinates.
An array of integers representing y-co-ordinates.
An integer for the total number of points.
90
Java Programming
Chapter 7
I/O stream
Streams are mainly used to move data from one place to another.
The java.io package contains a large No of stream classes that provide capabilities processing all
type of data.
Streams are basically divided into 2 categories:
Byte stream classes
Character stream classes
91
Java Programming
OutputStream
OutputStream is an abstract class that provides the framework from all output stream is
derived.
Writer
Writer is an abstract class that provides that framework from which all other writer stream are
derived.
92
Java Programming
Creating Files
Whenever we need to store data permanently then we use the concept of files. We can create
a file, write data into file, read data from an existing file. We can copy the contents of our file to
another file. To perform all these operation we use i/o stream.
Prog. To illustrates the use of FileInputStream
import java.io.*;
class Ex
{
public static void main(String args[])throws IOException
{
try
{
FileInputStream fis=new FileInputStream(“ster.txt”);
int c;
While((c=fis.read())!=-1)
System.out.print(c);
fis.close();
}
Catch(FileNotFoundExecption e)
{
System.out.println(“File Not Found”);
}
}
}
FileInputStream
A prog. to read data from the user & writer this into a file.
import jave.io.*;
public class Ex
{
public static void main(String args[])
try
{
DataInputStream ds=new DataInputStream(System.in);
System.out.println(“Enter the data”);
String s=ds.readLine();
FileInputStream f=new FileInputStream(“xyz.txt”);
byte b[]=s.getbyte()
f.write(b);
f.close();
}
Catch(IOException e)
{
System.out.println(“Exception Occurred”);
}
93
Java Programming
}
}
{
try
{
FileInputStream f=new FileInputStream(“xyz.txt”);
int size=f.avaliable();
byte b[]=new byte[size];
f.read(b);
String s=new String(b);
System.out.println(“the file context are:”+s);
f.close();
}
Catch(IOException e)
{
System.out.print(“Exception Occurred”);
}
}
}
94