Java Unit-1
Java Unit-1
UNIT - I
Object oriented thinking and Java Basics- Need for oop paradigm, summary of oop concepts, coping with
complexity, abstraction mechanisms. A way of viewing world – Agents, responsibility, messages, methods,
History of Java, Java buzzwords, data types, variables, scope and lifetime of variables, arrays, operators,
expressions, control statements, type conversion and casting, simple java program, concepts of classes, objects,
constructors, methods, access control, this keyword, garbage collection, overloading methods and constructors,
method binding, inheritance, overriding and exceptions, parameter passing, recursion, nested and inner classes,
exploring string class.
UNIT - II
Inheritance, Packages and Interfaces – Hierarchical abstractions, Base class object, subclass, subtype,
substitutability, forms of inheritance specialization, specification, construction, extension, limitation,
combination, benefits of inheritance, costs of inheritance. Member access rules, super uses, using final with
inheritance, polymorphism- method overriding, abstract classes, the Object class. Defining, Creating and
Accessing a Package, Understanding CLASSPATH, importing packages, differences between classes and
interfaces, defining an interface, implementing interface, applying interfaces, variables in interface and extending
interfaces. Exploring java.io.
UNIT - III
Exception handling and Multithreading-- Concepts of exception handling, benefits of exception handling,
Termination or resumptive models, exception hierarchy, usage of try, catch, throw, throws and finally, built in
exceptions, creating own exception subclasses. String handling, Exploring java.util. Differences between
multithreading and multitasking, thread life cycle, creating threads, thread priorities, synchronizing threads, inter
thread communication, thread groups, daemon threads. Enumerations, autoboxing, annotations, generics.
UNIT - IV
Event Handling: Events, Event sources, Event classes, Event Listeners, Delegation event model, handling mouse
and keyboard events, Adapter classes. The AWT class hierarchy, user interface components- labels, button,
canvas, scrollbars, text components, check box, checkbox groups, choices, lists panels – scrollpane, dialogs,
menubar, graphics, layout manager – layout manager types – border, grid, flow, card and grid bag.
UNIT - V
Applets – Concepts of Applets, differences between applets and applications, life cycle of an applet, types of
applets, creating applets, passing parameters to applets. Swing – Introduction, limitations of AWT, MVC
architecture, components, containers, exploring swing- JApplet, JFrame and JComponent, Icons and Labels, text
fields, buttons – The JButton class, Check boxes, Radio buttons, Combo boxes, Tabbed Panes, Scroll Panes,
Trees, and Tables.
Unit-1
Object means a real word entity such as pen, chair, table etc. Object-Oriented Programming is a
methodology or paradigm to design a program using classes and objects. It simplifies the software
development and maintenance by providing some concepts:
o Object
o Class
o Inheritance
o Polymorphism
o Abstraction
o Encapsulation
Object
Any entity that has state and behavior is known as an object. For example: chair, pen, table,
keyboard, bike etc. It can be physical and logical.
Class
Inheritance
When one object acquires all the properties and behaviours of parent object i.e. known as
inheritance. It provides code reusability. It is used to achieve runtime polymorphism.
Polymorphism
When one task is performed by different ways i.e. known as polymorphism. For example: to
convince the customer differently, to draw something e.g. shape or rectangle etc.
Another example can be to speak something e.g. cat speaks meaw, dog barks woof etc.
Abstraction
Hiding internal details and showing functionality is known as abstraction. 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.
A java class is the example of encapsulation. Java bean is the fully encapsulated class because all
the data members are private here.
Benefits of Inheritance
One of the key benefits of inheritance is to minimize the amount of duplicate code.
Inheritance can also make application code more flexible
Reusability - facility to use public methods of base class without rewriting the same.
Extensibility - extending the base class logic as per business logic of the derived class.
Data hiding - base class can decide to keep some data private so that it cannot be
altered by the derived class.
Responsibility
• In object-oriented design, the chain-of-responsibility pattern is a design pattern consisting of a source of
command objects and a series of processing objects..
• Each processing object contains logic that defines the types of command objects that it can handle; the rest are
passed to the next processing object in the chain. A mechanism also exists for adding new processing objects to
the end of this chain.
Primary motivation is the need for a platform-independent (that is, architecture- neutral) language that could
be used to create software to be embedded in various consumer electronic devices, such as microwave ovens
and remote controls.
• Objects with clear responsibilities
• Each class should have a clear responsibility.
• If you can't state the purpose of a class in a single, clear sentence, then perhaps your class structure needs
some thought.
• In object-oriented programming, the single responsibility principle states that every class should have a
single responsibility, and that responsibility should be entirely encapsulated by the class. All its services should
be narrowly aligned with that responsibility.
Messages
• Message implements the Part interface. Message contains a set of attributes and a "content".
• Message objects are obtained either from a Folder or by constructing a new Message
object of the appropriate subclass. Messages that have been received are normally retrieved from a folder
named "INBOX".
• A Message object obtained from a folder is just a lightweight reference to the actual message. The Message
is 'lazily' filled up (on demand) when each item is requested from the message.
• Note that certain folder implementations may return Message objects that are pre-filled with certain user-
specified items. To send a message, an appropriate subclass of Message (e.g., Mime Message) is instantiated,
the attributes and content are filled in, and the message is sent using the Transport. Send method.
• We all like to use programs that let us know what's going on. Programs that keep us informed often do so by
displaying status and error messages.
• These messages need to be translated so they can be understood by end users around the world.
• The Section discusses translatable text messages. Usually, you're done after you move a message String into
a Resource Bundle.
• If you've embedded variable data in a message, you'll have to take some extra steps to prepare it for
translation.
Methods
• The only required elements of a method declaration are the method's return type, name, a pair of
parentheses, (), and a body between braces, {}.
• Two of the components of a method declaration comprise the method signature—the method's name and
the parameter types.
• More generally, method declarations have six components, in order:
• Modifiers—such as public, private, and others you will learn about later.
The return type—the data type of the value returned by the method, or void if the method
does not return a value.
• The method name—the rules for field names apply to method names as well, but the convention is a little
different.
• The parameter list in parenthesis—a comma-delimited list of input parameters, preceded by their data
types, enclosed by parentheses, (). If there are no parameters, you must use empty parentheses.
• The method body, enclosed between braces—the method's code, including the declaration of local
variables, goes here.
Naming a Method
Although a method name can be any legal identifier, code conventions restrict method names. By convention,
method names should be a verb in lowercase or a multi-word name that begins with a verb in lowercase,
followed by adjectives, nouns, etc. In multiword names, the first letter of each of the second and following
words should be capitalized. Here are some examples:
run
run Fast
getBackground
getFinalData
compareTo setX isEmpty
Typically, a method has a unique name within its class. However, a method might have
the same name as other methods due to method overloading.
Overloading Methods
• The Java programming language supports overloading methods, and Java can distinguish between methods
with different method signatures. This means that methods within a class can have the same name if they
have different parameter lists (there are some qualifications to this that will be discussed in the lesson titled
"Interfaces and Inheritance").
The history of java starts from Green Team. Java team members (also known as Green Team), initiated
a revolutionary task to develop a language for digital devices such as set-top boxes, televisions etc.
For the green team members, it was an advance concept at that time. But, it was suited for internet
programming. Later, Java technology as incorporated by Netscape.
Currently, Java is used in internet programming, mobile devices, games, e-business solutions etc. There are
given the major points that describes the history of java.
1) James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language project in June 1991.
The small team of sun engineers called Green Team.
2) Originally designed for small, embedded systems in electronic appliances like set- top boxes.
3) Firstly, it was called "Greentalk" by James Gosling and file extension was .gt.
4) After that, it was called Oak and was developed as a part of the Green project.
Java Version History
1. Java is simple :- Java is Easy to write and more readable and eye catching. Java has a concise, cohesive
set of features that makes it easy to learn and use. Most of the concepts are drew from C++ thus making
Java learning simpler.
2. Java is secure :-Java program cannot harm other system thus making it secure. Java provides a secure
means of creating Internet applications. Java provides secure way to access web applications.
3. Java is portable :-Java programs can execute in any environment for which there is a Java run-time
system.(JVM) Java programs can be run on any platform (Linux,Window,Mac) Java programs can be
transferred over world wide web (e.g applets)
4. Java is object-oriented :- Java programming is object-oriented programming language. Like C++ java
provides most of the object oriented features. Java is pure OOP. Language. (while C++ is semi object
oriented)
5.Java is robust:-Java encourages error-free programming by being strictly typed and performing run-
time checks.
7.Java is architecture-neutral Java is not tied to a specific machine or operating system architecture.
Machine Independent i.e Java is independent of hardware .
8. Java is interpreted Java supports cross-platform code through the use of Java bytecode. Bytecode can
be interpreted on any platform by JVM.
9. Java’s performance Bytecodes are highly optimized. JVM can executed them much faster
10.Java is distributed Java was designed with the distributed environment. Java can be transmit,run over
internet.
11.Java is dynamic Java programs carry with them substantial amounts of run-time type information that
is used to verify and resolve accesses to objects at run time.
Java Comments
The java comments are statements that are not executed by the compiler and interpreter. The
comments can be used to provide information or explanation about the variable, method, class
or any statement. It can also be used to hide program code for specific time.
Syntax:
Example:
}
}
Output:
10
Syntax:
/*
This
is
multi line
comment
*/
Example:
Output:
10
The documentation comment is used to create documentation API. To create documentation API, you
need to use javadoc tool.
Syntax:
/**
This
is
documentatio
n comment
*/
Example:
/** The Calculator class provides methods to get addition and subtraction of given 2 numbers.*/
}
Data Types
Data types represent the different values to be stored in the variable. In java, there are two types of data types:
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0L 8 byte
int a=10;
int b=10;
int c=a+b;
System.out.println(c);
}}
Output:20
Variables and Data Types in Java
Variable is a name of memory location. There are three types of variables in java: local, instance
and static.
Types of Variable
There are three types of variables in java:
o local variable
o instance variable
o static variable
1) Local Variable
2) Instance Variable
A variable which is declared inside the class but outside the method, is called instance variable . It
is not declared as static.
3) Static variable
Integer constants:- refers to sequence of digits.There are three types of integers namely decimal integer,
octal integer and hexadecimal integer.
Decimal integes consist of a set of digits 0 through 9,preceded by an optional minus sign.
Ex: 123 -321 0 654321
Real constants:Integer numbers are inadequate to represent quantities that vary continuously,such as
diatances,heights ,temperatures ,prices and so on.
Ex:17.548
Single Character Constants:A single character constant contains a single character enclosed within a pair of
single quote marks.
Ex:’5’ ‘x’
String Constants:A string constant is a sequence of characters enclosed between double quotes.The characters
may be alphabets,digits ,special characters and blank spaces.
Ex:”hello” “1997” “X”
The scope of a variable defines the section of the code in which the variable is visible. As a
general rule, variables that are defined within a block are not accessible outside that block. The
lifetime of a variable refers to how long the variable exists before it is destroyed. Destroying
variables refers to deallocating the memory that was allotted to the variables when declaring it.
There are three types of variables: instance variables, argument variables or class variables and
local variables.
Instance variables
Instance variables are those that are defined within a class itself and not in any method or
constructor of the class. They are known as instance variables because every instance of the
class (object) contains a copy of these variables. The scope of instance variables is determined
by the access specifier that is applied to these variables. We have already seen about it earlier.
The lifetime of these variables is the same as the lifetime of the object to which it belongs.
Object once created do not exist for ever. They are destroyed by the garbage collector of Java
when there are no more reference to that object. We shall see about Java's automatic garbage
collector later on.
int x=0;
{
. Block1
int n=5;
Block2
.
{
}
.
int m=10;
Local variables
A local variable is the one that is declared within a method or a constructor (not in the header).
The scope and lifetime are limited to the method itself.
One important distinction between these three types of variables is that access specifiers can
be applied to instance variables only and not to argument or local variables.
In addition to the local variables defined in a method, we also have variables that are defined
in bocks life an if block and an else block. The scope and is the same as that of the block itself.
Operators in java
Operator in java is a symbol that is used to perform operations. For example: +, -, *, / etc.
There are many types of operators in java which are given below:
Operators Hierarchy
Expressions
Expressions are essential building blocks of any Java program, usually created to produce a new
value, although sometimes an expression simply assigns a value to a variable. Expressions are
built using values, variables, operators and method calls.
Types of Expressions
While an expression frequently produces a result, it doesn't always. There are three types of
expressions in Java:
X=a-b/3+c*2-1
Finally x=10.
For Example, in java the numeric data types are compatible with each other but no automatic
conversion is supported from numeric type to char or boolean. Also, char and boolean are not
compatible with each other.
TYPE CASTING
The process of a local conversion is known as casting a value.The general form of a cast is
(type_name)expression
Where type_name is one of the standard data types.the expression may be a constant ,variable or an
expression.
Use of Casts
Java Enum
from JDK 1.5. Java Enums can be thought of as classes that have fixed
set of constants.
Output:
WINTER SPRING
SUMMER
FALL
}}
Java has very flexible three looping mechanisms. You can use one of the following three
loops:
while Loop
do...while Loop
for Loop
1.while loop
SYNTAX:
The syntax of a while loop is:
while(Boolean_expression)
{
//Statements
}
EXAMPLE
int x = 10;
while( x < 20 ) {
System.out.print("value of x : " + x );
x++;
System.out.print("\n");
}
}
}
value of x : 19
2.do…while loop
SYNTAX:
EXAMPLE:
public class Test {
public static void main(String args[]){
int x = 10;
do{
System.out.print("value of x : " + x );
x++;
System.out.print("\n");
}while( x < 20 );
}
}
This would produce the following result:
value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19
{
//Statements
}
EXAMPLE:
System.out.print("\n");
}
}
}
This would produce the following result:
value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19
Branching statement:
There are two types of decision making statements in Java. They are:
if statements
switch statements
1. The if Statement:
SYNTAX:
System.out.print("This is if statement");
}
}
}
This would produce the following result:
This is if statement
An if statement can be followed by an optional else statement, which executes when the
Boolean expression is
false.
SYNTAX:
System.out.print("This is if statement");
}else{
System.out.print("This is else statement");
}
}
}
This would produce the following result:
This is else statement.
System.out.print("Value of X is 30");
}else{
System.out.print("This is else statement");
}
}
}
This would produce the following result:
Value of X is 30
SYNTAX:
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( y == 10 ){
System.out.print("X = 30 and Y = 10");
}
}
}
}
This would produce the following result:
X = 30 and Y = 10.
case value2 :
//Statements
break; //optional
//You can have any number of case statements.
default : //Optional
//Statements
}
EXAMPLE:
{
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);
}
}
This would produce the following
Well done
Your grade is a C
Jump statements
The jump statements are break and continue.
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.
EXAMPLE:
break;
}
System.out.print( x );
System.out.print("\n");
}
}
}
This would produce the following result:
0
1
2
System.out.print( x );
System.out.print("\n");
}
}
}
class Sample{
o/p:hello world
Arrays
Java provides a data structure, the array, which stores a fixed-size sequential
collection of elements of the same type. An array is used to store a collection of
data, but it is often more useful to think of an array as a collection of variables of
the same type.
You can create an array by using the new operator with the following syntax:
Example:
Following statement declares an array variable, myList, creates an array of 10
elements of double type and assigns its reference to myList:
Example:
class Arraystr{
public static void main(String args[])
{
int num[3]={56,48,39}
for(int k=0;k<=3;k++)
{
if(num[k]>50 && num[k]<100)
{
System.out.println("the value is"+num[k]);
}
} } }
Example:
class Arraystr{
public static void main(String args[])
{
int num[3]={56,48,39}
for(int k:num)
{
if(k>50 && k<100)
{
System.out.println("the value is"+k);
}
} } }
{
public static void main(String[] args)
{
int n=a.length;
int i,j,temp;
System.out.println("given list is ");
for(i=0;i<n;i++)
{
System.out.println("the numbers are"+a[i]);
}
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if (a[i] > a[j])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
System.out.println("the sorted order is");
for(i=0;i<n;i++)
{
System.out.println("the numbers are"+a[i]);
}
}
}
O/P:the sorted order is :
1
4
6
7
10
import java.util.Scanner;
public class Twodim
{
int row,col,i,j;
int [][]a=new int[5][5];
{
a[i][j]=s.nextInt();
}
}
{
System.out.println(a[i][j]+” ”);
}
System.out.println();
}
A[]={1,2,3,4,5}
A[0]=1
A[1]=2
A[2]=3
A[3]=4
A[4]=5
Jagged Arrays
A[0] 1 23
1 A[1] 4567
2 A[2] 8 9 10 11 12
class JaggedA
{
public static void main(String []args)
{
int i,j;
int[][]a=new int[3][];
a[0]=new int[2];
a[1]=new int[3];
a[2]=new int[4];
int count=0;
for(i=0;i<a.length;i++)
for(j=0;j<a[i].length;j++)
{
a[i][j]=count++;
}
for(i=0;i<a.length;i++)
{
System.out.println();
for(j=0;j<a[i].length;j++)
{
System.out.print(a[i][j]+" ");
}
}}
}
Java is a true object oriented language and therefore the underlying structure of all java programs
is classes.Anything we wish to represent in a java program must be encapsulated in a class that
defines the state and behavior of the basic program components known as objects.Classes create
objects and objects use methods to communicate between them.
Class declaration
Field’s declaration
Method’s Declaration
Type methodname(parameter-list)
{
Method-body;
}
Ex:
Example Program :
class add
int len,wdth,c;
len=x;
wdth=y;
c=len*wdth;
// System.out.println(c);
void disp()
System.out.println(c);
a.getdata(2,4);
a.disp();
}
Constructor:
Java supports a special type of method called a constructor ,that enables an object to initialize itself
when it is created .Constructors have the same name as the class itself .Secondly they do not
specify a return type ,not even void .This is because they return the instance of the class itself.
class abc
{
int len,wdth;
abc(int x,int y) //constructor
{
len=x;wdth=y;
}
// System.out.println(c);
}
int rectArea()
{
return len*wdth;
}
// void disp()
//{
// System.out.println(c);
//}
}
public class Constrctore
{
public static void main(String []args)
{
add a=new add(10,20);
int b= a.rectArea();
System.out.println(b);
}
}
a class basically contains two sections .one declares variables and the other declares
methods.These variables and methods are called instance variables and instance
methods.This is because every time the class is instantiated ,a new copy of each of them
is created.They are accessed using the objects(with dot oprator).
class oper
{
static float mul(float x,float y)
{
return x*y;
}
static float divide(float x,float y)
{
return x/y;
}
}
class Oneop
[
public static void main(String []args)
{
float a=oper.mul(4.0,5.0);
float b=oper.divide(a,2.0);
System.out.println(“b=”+b);
}
}
Nesting of methods
class nesting
{
int m,n;
nesting(int x,int y)
{
m=x; n=y;
}
int largest()
{
if (m>=n)
return(m);
else
return(n);
}
void display()
{
int large=largest();
System.out.println("the largest value is="+large);
}
}
public class NestTest
{
public static void main(String[]args)
{
nesting nest=new nesting(50,40);
nest.display();
}
}
Access Modifier within class within package outside package by subclass only outside
package
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
Private
class A{
private int data=40;
private void msg()
{
System.out.println("Hello java");}
}
If you make any class constructor private, you cannot create the instance of that class from outside
the class. For example:
class A{
private A(){}//private constructor
void msg(){System.out.println("Hello java");}
}
public class Simple{
public static void main(String args[]){
A obj=new A();//Compile Time Error
}
}
Protected
package pack;
public class A
{
protected void msg()
{
System.out.println("Hello");}
}
package mypack;
import pack.*;
class B extends A{
public static void main(String args[])
{
B obj = new B();
obj.msg();
}
}
The public access modifier is accessible everywhere. It has the widest scope among all other
modifiers.
package pack;
public class A
{
public void msg()
{
System.out.println("Hello");
}
}
package mypack;
import pack.*;
class B
{
public static void main(String args[])
{
A obj = new A();
obj.msg();
}
}
Constructor overloading
A constructor initializes an object immediately upon creation. It has the same name as the class in
which it resides and is syntactically similar to a method. Once defined, the constructor is
automatically called when the object is created, before the new operator completes. Constructors
look a little strange because they have no return type, not even void.
class Box
{
double width, height, depth;
Box()
{
width = height = depth = 0;
Box(double len)
{
width = w;
height = h;
depth = d;
double volume()
{
double vol;
vol = mybox1.volume();
vol = mybox2.volume();
System.out.println(" Volume of mybox2 is " + vol);
vol = mycube.volume();
System.out.println(" Volume of mycube is " + vol);
Recursion in java
Recursion in java is a process in which a method calls itself continuously. A method in java
that calls itself is called recursive method.
class Factorial {
static int factorial( int n ) {
if (n != 0) // termination condition
return n * factorial(n-1); // recursive call
else
return 1;
}
class facto
{
THIS reference
The this is a keyword in Java which is used as a reference to the object of the current class, with
in an instance method or a constructor. Using this you can refer the members of a class such as
constructors, variables and methods.
class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
rollno=rollno;
name=name;
fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+fee);}
}
class TestThis1{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}}
class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
this.rollno=rollno;
this.name=name;
this.fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+fee);}
}
class TestThis2{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}}
Garbage collection
Since objects are dynamically allocated by using the new operator,how such objects are destroyed
and their memory released for later reallocation. In some languages, such as traditional C++,
dynamically allocated objects must be manually released by use of a delete operator. Java takes a
different approach; it handles deallocation automatically. The technique that accomplishes this is
called garbage collection.
int c;
c=x+y;
for(int i=0;i<1000;i++)
a.add(i,i);
In Java, it is also possible to nest classes (a class within a class). The purpose
of nested classes is to group classes that belong together, which makes your
code more readable and maintainable.
To access the inner class, create an object of the outer class, and then create
an object of the inner class:
class OuterClass {
int x = 10;
class InnerClass {
int y = 5;
}
}
class Demostring
int n=a.length;
System.out.println("length is"+n);
for(int i=0;i<n;i++)
System.out.print(a[i]+" ");
}
}
String s2=s1.toLowerCase();
System.out.println(s2);
String s3=s1.toUpperCase();
System.out.println(s3);
String s4=s1.replace('j','n');
System.out.println(s4);
System.out.println(s5);
String s6="hello";
String s7="hello";
boolean b=s6.equals(s7);
System.out.println(b);
String s8="HELLO";
boolean c=s6.equalsIgnoreCase(s8);
System.out.println(c);
String s9=s8.concat(s1);
System.out.println(s9);
}
Sorting of Strings
import java.util.*;
int count;
String temp;
count = scan.nextInt();
str[i] = scan2.nextLine();
scan.close();
scan2.close();
if (str[i].compareTo(str[j])>0)
temp = str[i];
str[i] = str[j];
str[j] = temp;