Java Total Notes
Java Total Notes
1
[Link] DEPARTEMENT OF COMPUTERS ,USHODAYA DEGREE COLLEGE,CHODAVARAM
BSC COMPUTER SCIENCE JAVA SEMESTER-III
UNIT-1
UNIT-II
DECISION MAKING & BRANCHING: Introduction, Decision making with if statement, Simple if
statement, if. Else statement, Nesting of if. else statements, the else if ladder, the switch statement, the
conditional operator. LOOPING: Introduction, The While statement, the do-while statement, the for
statement, Jumps in loops.
CLASSES, OBJECTS & METHODS: Introduction, Defining a class, Adding variables, Adding
methods, Creating objects, Accessing class members, Constructors, Method overloading, Static
members, Nesting of methods;
UNIT-III
INHERITANCE: Extending a class, Overloading methods, Final variables and methods, Final classes,
Abstract methods and classes;
ARRAYS, STRINGS AND VECTORS: Arrays, One-dimensional arrays, Creating an array, Two –
dimensional arrays, Strings, Vectors, Wrapper classes;
UNIT-IV
MULTITHREADED PROGRAMMING: Introduction, Creating Threads, Extending the Threads, Stopping
and Blocking a Thread, Lifecycle of a Thread, Using Thread Methods, Thread Exceptions, Thread Priority,
Synchronization, Implementing the ‘Runnable’ Interface.
MANAGING ERRORS AND EXCEPTIONS: Types of errors : Compile-time errors, Run-time errors,
Exceptions, Exception handling, Multiple Catch Statements, Using finally statement ,
UNIT-V
APPLET PROGRAMMING: local and remote applets, Applets and Applications, Building Applet
code, Applet Life cycle: Initialization state, Running state, Idle or stopped state, Dead state, Display stat
PACKAGES: Introduction, Java API Packages, Using System Packages, Naming conventions, Creating
Packages, Accessing a Package, using a Package.
2
[Link] DEPARTEMENT OF COMPUTERS ,USHODAYA DEGREE COLLEGE,CHODAVARAM
BSC COMPUTER SCIENCE JAVA SEMESTER-III
Any entity that has state and behavior is known as an object. For example a chair,
pen, table, keyboard, bike, etc. It can be physical or logical.
An Object can be defined as an instance of a class. An object
contains an address and takes up some space in memory.
Objects can communicate without knowing the details of each
other's data or code. The only necessary thing is the type of
message accepted and the type of response returned by the
objects.
Class
Collection of objects is called class. It is a logical entity.
A class can also be defined as a blueprint from which you can create an individual
object. Class doesn't consume any space.
Polymorphism
If one task is performed by different ways, it is known as polymorphism. For example:
to convince the customer differently, to draw something, for example, shape, triangle,
rectangle, etc.
In Java, we use method overloading and method overriding to achieve polymorphism.
Another example can be to speak something; for example, a cat speaks meow, dog
barks woof, etc.
3
[Link] DEPARTEMENT OF COMPUTERS ,USHODAYA DEGREE COLLEGE,CHODAVARAM
BSC COMPUTER SCIENCE JAVA SEMESTER-III
Inheritance
Inheritance is one such concept where the properties of one class can be inherited by the other. It
helps to reuse the code and establish a relationship between different classes.
As we can see in the image, a child inherits the properties from his father. Similarly, in Java, there
are two classes:
1. Parent class ( Super or Base class)
2. Child class (Subclass or Derived class )
A class which inherits the properties is known as Child Class whereas a class whose properties are
inherited is known as Parent class.
Inheritance is further classified into 4 types:
So let’s begin with the first type of inheritance i.e. Single Inheritance:
1. Single Inheritance:
In single inheritance, one class inherits the properties of
another.
Here, Class A is your parent class and Class B is your child
class which inherits the properties and behavior of the
parent class.
4
[Link] DEPARTEMENT OF COMPUTERS ,USHODAYA DEGREE COLLEGE,CHODAVARAM
BSC COMPUTER SCIENCE JAVA SEMESTER-III
2. Multilevel Inheritance:
A class having more than one parent class but at different levels, such type
If we talk about the flowchart, class B inherits the properties and behavior of
class A and class C inherits the properties of class B. Here A is the parent
3. Hierarchical Inheritance:
When a class has more than one child classes (sub classes) or
in other words, more than one child classes have the same
parent class, then such kind of inheritance is known
as hierarchical.
If we talk about the flowchart, Class B and C are the child
classes which are inheriting from the parent class i.e Class A.
Let’s see the syntax for hierarchical inheritance in Java:
1
2 Class A{
---
3 }
Class B extends A{
4 ---
}
5 Class C extends A{
---
6 }
5
[Link] DEPARTEMENT OF COMPUTERS ,USHODAYA DEGREE COLLEGE,CHODAVARAM
BSC COMPUTER SCIENCE JAVA SEMESTER-III
4. Hybrid Inheritance:
Hybrid inheritance is a combination of multiple inheritance
and multilevelinheritance.
If we talk about the flowchart, class A is a parent class for
class B and C, whereas Class B and C are the parent
class of D which is the only child class of B and C.
Encapsulation
Encapsulation is a wrapping up of data and
code together as a single unit. It also means to
hide your data in order to make it safe from any
modification .
Example : medical capsule,
where the drug is always safe inside the
capsule.
Abstraction
Hiding internal details and showing functionality is known as abstraction. For example
phone call, we don't know the internal processing.
Benefits of OOPS
There are several benefits of OOP to both program designer and the user. Object orientation solves
many problems which are associated with the development and quality of software products. New
technology gives greater programmer productivity, good quality of software and low maintanance
cost. The main advantages are:
We can eliminate redundant code and extend the use of existing classes.
Programs can be build from the standard working modules that communicate with one
another and to start writing the code from scratch. This shows to saving of development time and
higher productivity.
The data hiding rules helps the programmer to make secure programs that cannot be
invaded by code in other parts of the program.
It has multiple objects to coexist without any interference.
It has map objects in the problem domain to those objects in the program.
partition of work is easy in a project based on objects.
The data-centered design approach capture more details of a model in an implementable
form.
Object oriented systems can be easily upgraded from small to large systems.
It is possible to easily manage software complexity.
6
[Link] DEPARTEMENT OF COMPUTERS ,USHODAYA DEGREE COLLEGE,CHODAVARAM
BSC COMPUTER SCIENCE JAVA SEMESTER-III
History of Java
The history of Java is very interesting. Java was originally designed for interactive
television, but it was too advanced technology for the digital cable television industry
at the time. The history of java starts with Green Team. Java team members (also
known as Green Team), initiated this project to
develop a language for digital devices such as set-top
boxes, televisions, etc. However, it was suited for
internet programming. Later, Java technology was
incorporated by Netscape.
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.
6) In 1995, Oak was renamed as "Java" because it was already a trademark by Oak
Technologies.
7
[Link] DEPARTEMENT OF COMPUTERS ,USHODAYA DEGREE COLLEGE,CHODAVARAM
BSC COMPUTER SCIENCE JAVA SEMESTER-III
Features of Java
Simple:
The Java language is easy to learn. Java code is easy to read
and write.
* Familiar:
Java is similar to C/C++ but it removes the drawbacks and
complexities of C/C++ like pointers and multiple inheritances.
So if you have background in C/C++, you will find Java
familiar and easy to learn.
* Object-Oriented:
Unlike C++ which is semi object-oriented, Java is a fully
object-oriented programming language. It has all OOP
features such as abstraction, encapsulation, inheritance and polymorphism.
Robust
Robust simply means strong. Java is robust because:
Secured
Java is best known for its security. With
Java, we can develop virus-free
systems. Java is secured because:
o No explicit pointer
o Java Programs run inside a
virtual machine sandbox
Portable
Java is portable because it facilitates
you to carry the Java bytecode to any platform. It doesn't require any implementation.
Architecture-neutral
Java is architecture neutral because there are no implementation dependent features, for
example, the size of primitive types is fixed.
In C programming, int data type occupies 2 bytes of memory for 32-bit architecture and 4
bytes of memory for 64-bit architecture. However, it occupies 4 bytes of memory for both 32
and 64-bit architectures in Java.
* Platform Independence:
Java code is compiled into intermediate format
(bytecode), which can be executed on any systems
for which Java virtual machine is ported. That means
you can write a Java program once and run it on
Windows, Mac, Linux or Solaris without re-compiling.
Thus the slogan “Write once, run anywhere” of Java.
Dynamic
Java is a dynamic language. It supports dynamic loading of classes. It means classes
are loaded on demand. It also supports functions from its native languages, i.e., C and
C++.
9
[Link] DEPARTEMENT OF COMPUTERS ,USHODAYA DEGREE COLLEGE,CHODAVARAM
BSC COMPUTER SCIENCE JAVA SEMESTER-III
o Install the JDK if you don't have installed it, download the JDK and install it.
o Set path of the jdk/bin directory
o Create the java program
o Compile and run the java program
1. class Simple
2. {
3. public static void main(String args[])
4. {
5. [Link]("Hello Java");
6. }
7. }
save this file as [Link]
Output:Hello Java
Compilation Flow:
When we compile Java program using javac tool, java compiler converts the source
code into byte code.
10
[Link] DEPARTEMENT OF COMPUTERS ,USHODAYA DEGREE COLLEGE,CHODAVARAM
BSC COMPUTER SCIENCE JAVA SEMESTER-III
Java Tokens
Java Tokens are the smallest individual building block or smallest unit of a Java
program; the Java compiler uses it for constructing expressions and statements. Java
program is a collection of different types of tokens, comments, and white spaces.
11
[Link] DEPARTEMENT OF COMPUTERS ,USHODAYA DEGREE COLLEGE,CHODAVARAM
BSC COMPUTER SCIENCE JAVA SEMESTER-III
Reserved Keywords
Identifiers
Literals
Operators
Separators
class first
{
12
[Link] DEPARTEMENT OF COMPUTERS ,USHODAYA DEGREE COLLEGE,CHODAVARAM
BSC COMPUTER SCIENCE JAVA SEMESTER-III
Now, the interpreter looks for the main method in the program and begins execution
13
[Link] DEPARTEMENT OF COMPUTERS ,USHODAYA DEGREE COLLEGE,CHODAVARAM
BSC COMPUTER SCIENCE JAVA SEMESTER-III
14
[Link] DEPARTEMENT OF COMPUTERS ,USHODAYA DEGREE COLLEGE,CHODAVARAM
BSC COMPUTER SCIENCE JAVA SEMESTER-III
15
[Link] DEPARTEMENT OF COMPUTERS ,USHODAYA DEGREE COLLEGE,CHODAVARAM
BSC COMPUTER SCIENCE JAVA SEMESTER-III
1. Variable Declaration
2. ariable Initialization
Variable Declaration:
To declare a variable, you must specify the data type & give the variable a unique name.
float pi;
double d;
char a;
Variable Initialization:
To initialize a variable, you must assign it a valid value.
do =20.22d;
a=’v’;
Example :
int a=2,b=4,c=6;
float pi=3.14f;
double do=20.22d;
char a=’v’;
16
[Link] DEPARTEMENT OF COMPUTERS ,USHODAYA DEGREE COLLEGE,CHODAVARAM
BSC COMPUTER SCIENCE JAVA SEMESTER-III
Types of variables
1. Local Variables
2. Instance Variables
3. Static Variables
1) Local Variables
Local Variables are a variable that are declared inside the body of a method.
2) Instance Variables
Instance variables are defined without the STATIC keyword .They are defined Outside a method
declaration. They are Object specific and are known as instance variables.
3) Static Variables
Static variables are initialized only once, at the start of the program execution. These variables
should be initialized first, before the initialization of any instance variables.
Data types classify the different values to be stored in the variable. In java, there are two types of data types:
17
[Link] DEPARTEMENT OF COMPUTERS ,USHODAYA DEGREE COLLEGE,CHODAVARAM
BSC COMPUTER SCIENCE JAVA SEMESTER-III
There are 8 primitive types: byte, short, int, long, char, float, double, and boolean Integer data
types
byte (1 byte)
short (2 bytes)
int (4 bytes)
long (8 bytes)
double (8 bytes)
Textual Data Type
char (2 bytes)
Logical
boolean (1 byte) (true/false)
Points to Remember:
18
[Link] DEPARTEMENT OF COMPUTERS ,USHODAYA DEGREE COLLEGE,CHODAVARAM
BSC COMPUTER SCIENCE JAVA SEMESTER-III
A variable of one type can receive the value of another type. Here there are 2 cases -
In such cases, you have to explicitly specify the type cast operator. This process is known as Type
Casting.
In case, you do not specify a type cast operator; the compiler gives an error. Since this rule is
enforced by the compiler, it makes the programmer aware that the conversion he is about to do may
cause some loss in data and prevents accidental losses.
class Demo {
public static void main(String args[]) {
byte x;
int a = 270;
double b = 128.128;
[Link]("int converted to byte");
x = (byte) a;
[Link]("a and x " + a + " " + x);
[Link]("double converted to int");
19
[Link] DEPARTEMENT OF COMPUTERS ,USHODAYA DEGREE COLLEGE,CHODAVARAM
BSC COMPUTER SCIENCE JAVA SEMESTER-III
a = (int) b;
[Link]("b and a " + b + " " + a);
[Link]("\ndouble converted to byte");
x = (byte)b;
[Link]("b and x " + b + " " + x);
}
}
Output:
20
[Link] DEPARTEMENT OF COMPUTERS ,USHODAYA DEGREE COLLEGE,CHODAVARAM
BSC COMPUTER SCIENCE JAVA SEMESTER-III
operators
An operator is a character that represents an action, for example + is an arithmetic operator that represents
addition.
Types of Operator in Java
1) Basic Arithmetic Operators
2) Assignment Operators
3) Auto-increment and Auto-decrement Operators
4) Logical Operators
5) Comparison (relational) operators
6) Bitwise Operators
7) Ternary Operator
1) Basic Arithmetic Operators
Basic arithmetic operators are: +, -, *, /, %
+ is for addition.
– is for subtraction.
* is for multiplication.
/ is for division.
% is for modulo.
Note: Modulo operator returns remainder, for example 10 % 5 would return 0
2) Assignment Operators
21
[Link] DEPARTEMENT OF COMPUTERS ,USHODAYA DEGREE COLLEGE,CHODAVARAM
BSC COMPUTER SCIENCE JAVA SEMESTER-III
4) Logical Operators
Logical Operators are used with binary variables. They are mainly used in conditional statements
and loops for evaluating a condition.
5) Comparison(Relational) operators
We have six relational operators in Java: ==, !=, >, <, >=, <=
== returns true if both the left side and right side are equal
!= returns true if left side is not equal to the right side of operator.
> returns true if left side is greater than right.
< returns true if left side is less than right side.
>= returns true if left side is greater than or equal to right side.
<= returns true if left side is less than or equal to right side.
6) Bitwise Operators
There are six bitwise Operators: &, |, ^, ~, <<, >>
num1 = 11; /* equal to 00001011*/
num2 = 22; /* equal to 00010110 */
7) Ternary Operator
This operator evaluates a boolean expression and assign the value based
on the result.
Syntax:
,
22
[Link] DEPARTEMENT OF COMPUTERS ,USHODAYA DEGREE COLLEGE,CHODAVARAM
BSC COMPUTER SCIENCE JAVA SEMESTER-III
UNIT – I (QUESTIONS)
23
[Link] DEPARTEMENT OF COMPUTERS ,USHODAYA DEGREE COLLEGE,CHODAVARAM
BSC COMPUTER SCIENCE JAVA SEMESTER-III
UNIT-II
Control flow statements/Conditions
When we need to execute a set of statements based on a condition then we need to use control flow
statements.
a) if statement
b) nested if statement
c) if-else statement
d) if-else-if statement
Java if Statement
The Java if statement tests the condition. It executes
the if block if condition is true.
Syntax:
if(condition){
//code to be executed
}
Example:
Output:
Age is greater than 18
24
[Link] DEPARTEMENT OF COMPUTERS ,USHODAYA DEGREE COLLEGE,CHODAVARAM
BSC COMPUTER SCIENCE JAVA SEMESTER-III
Syntax:
if(condition){
//code if condition is true
}else{
//code if condition is false
}
Example:
Syntax:
if(condition1){
//code to be executed if condition1 is true
}else if(condition2){
//code to be executed if condition2 is true
}
else if(condition3){
//code to be executed if condition3 is true
}
...
else{
//code to be executed if all the conditions are false
}
25
[Link] DEPARTEMENT OF COMPUTERS ,USHODAYA DEGREE COLLEGE,CHODAVARAM
BSC COMPUTER SCIENCE JAVA SEMESTER-III
Example:
if(marks<50){
[Link]("fail");
}
else if(marks>=50 && marks<60){
[Link]("D grade");
}
else if(marks>=60 && marks<70){
[Link]("C grade");
}
else if(marks>=70 && marks<80){
[Link]("B grade");
}
else if(marks>=80 && marks<90){
[Link]("A grade");
}else if(marks>=90 && marks<100){
[Link]("A+ grade");
}else{
[Link]("Invalid!");
}
}
}
Output:
C grade
Syntax:
switch(expression){
case value1:
//code to be executed;
break; //optional
case value2:
26
[Link] DEPARTEMENT OF COMPUTERS ,USHODAYA DEGREE COLLEGE,CHODAVARAM
BSC COMPUTER SCIENCE JAVA SEMESTER-III
//code to be executed;
break; //optional
......
default:
code to be executed if all cases are not ma
tched;
}
27
[Link] DEPARTEMENT OF COMPUTERS ,USHODAYA DEGREE COLLEGE,CHODAVARAM
BSC COMPUTER SCIENCE JAVA SEMESTER-III
Loops in Java
In programming languages, loops are used to execute a set of instructions/functions repeatedly
when some conditions become true. There are three types of loops in java.
o for loop
o while loop
o do-while loop
Defi The Java for loop is a control The Java while loop is The Java do while
nitio flow statement that iterates a a control flow loop is a control flow
n part of the programs multiple statement that statement that
times. executes a part of the executes a part of
programs repeatedly the programs at
on the basis of given least once and the
boolean condition. further execution
depends upon the
given boolean
condition.
28
[Link] DEPARTEMENT OF COMPUTERS ,USHODAYA DEGREE COLLEGE,CHODAVARAM
BSC COMPUTER SCIENCE JAVA SEMESTER-III
Syntax:
for(initialization;condition;incr/decr){
//statement or code to be executed
}
Example
Syntax:
while(condition){
//code to be executed
}
Example
29
[Link] DEPARTEMENT OF COMPUTERS ,USHODAYA DEGREE COLLEGE,CHODAVARAM
BSC COMPUTER SCIENCE JAVA SEMESTER-III
The Java do-while loop is executed at least once because condition is checked after loop body.
Syntax:
do{
//code to be executed
}while(condition);
Example
The Java break is used to break loop or switch statement. It breaks the current flow of the
program atspecified condition. In case of inner loop, it breaks only inner loop.
We can use Java break statement in all types of loops such as for loop, while loop and do-while
loop.
Syntax:
jump-statement;
break;
8. }
9. [Link](i);
10. }
11. }
12. }
The Java continue statement is used to continue the loop. It continues the current flow of the
program and skips the remaining code at the specified condition. In case of an inner loop, it
continues the inner loop only.
We can use Java continue statement in all types of loops such as for loop, while loop and do-
while loop.
Syntax:
1. jump-statement;
2. continue;
example
31
[Link] DEPARTEMENT OF COMPUTERS ,USHODAYA DEGREE COLLEGE,CHODAVARAM
BSC COMPUTER SCIENCE JAVA SEMESTER-III
32
[Link] DEPARTEMENT OF COMPUTERS ,USHODAYA DEGREE COLLEGE,CHODAVARAM
BSC COMPUTER SCIENCE JAVA SEMESTER-III
Methods in Java
Method describe behavior of an object. A method is a collection of statements that are group
together to perform an operation.
Syntax :
return-type methodName(parameter-list)
{
//body of method
}
Example of a Method
public String getName(String st)
{
String name="StudyTonight";
name=name+st;
return name;
}
Modifier : Modifier are access type of method. We will discuss it in detail later.
Return Type : A method may return value. Data type of value return by a method is declare in
method heading.
Method name : Actual name of the method.
Parameter : Value passed to a method.
Method body : collection of statement that defines what method does.
33
[Link] DEPARTEMENT OF COMPUTERS ,USHODAYA DEGREE COLLEGE,CHODAVARAM
BSC COMPUTER SCIENCE JAVA SEMESTER-III
34
[Link] DEPARTEMENT OF COMPUTERS ,USHODAYA DEGREE COLLEGE,CHODAVARAM
BSC COMPUTER SCIENCE JAVA SEMESTER-III
50
Method overloading
If two or more method in a class have same name but different parameters, it is known as
method overloading. Overloading always occur in the same class(unlike method overriding).
Method overloading is one of the ways through which java supports polymorphism. Method
overloading can be done by changing number of arguments or by changing the data type of
arguments. If two or more method have same name and same parameter list but differs in
return type are not said to be overloaded method
Note: Overloaded method can have different access modifiers.
Different ways of Method overloading
There are two different ways of method overloading
Method overloading by changing data type of Arguments
Example :
class Calculate
{
void sum (int a, int b)
{
[Link]("sum is"+(a+b)) ;
}
void sum (float a, float b)
{
[Link]("sum is"+(a+b));
}
Public static void main (String[] args)
{
Calculate cal = new Calculate();
[Link] (8,5); //sum(int a, int b) is method is called.
[Link] (4.6f, 3.8f); //sum(float a, float b) is called.
}
}
Sum is 13
Sum is 8.4
You can see that sum() method is overloaded two times. The first takes two integer arguments,
the second takes two float arguments.
35
[Link] DEPARTEMENT OF COMPUTERS ,USHODAYA DEGREE COLLEGE,CHODAVARAM
BSC COMPUTER SCIENCE JAVA SEMESTER-III
Area is 40
Area is 48
Method Overriding
When a method in a sub class has same name, same number of arguments and same type
signature as a method in its super class, then the method is known as overridden method.
Method overriding is also referred to as runtime polymorphism. The key benefit of overriding is
the abitility to define method that's specific to a particular subclass type.
Example of Method Overriding
class Animal
{
public void eat()
{
[Link]("Generic Animal eating");
}
}
36
[Link] DEPARTEMENT OF COMPUTERS ,USHODAYA DEGREE COLLEGE,CHODAVARAM
BSC COMPUTER SCIENCE JAVA SEMESTER-III
37
[Link] DEPARTEMENT OF COMPUTERS ,USHODAYA DEGREE COLLEGE,CHODAVARAM
BSC COMPUTER SCIENCE JAVA SEMESTER-III
38
[Link] DEPARTEMENT OF COMPUTERS ,USHODAYA DEGREE COLLEGE,CHODAVARAM
BSC COMPUTER SCIENCE JAVA SEMESTER-III
Constructors in Java
In Java, a constructor is a block of codes similar to the method. It is called when an instance
of the object is created, and memory is allocated for the object.
It is a special type of method which is used to initialize the object.
When is a constructor called
Every time an object is created using new() keyword, at least one constructor is called. It
calls a default constructor.
Note: It is called constructor because it constructs the values at the time of object creation.
It is not necessary to write a constructor for a class. It is because java compiler creates a
default constructor if your class doesn't have any.
Rules for creating Java constructor
There are two rules defined for the constructor.
1. Constructor name must be the same as its class name
2. A Constructor must have no return type
3. A Java constructor cannot be abstract, static, final, and synchronized
Note: We can use access modifiers while declaring a constructor. It controls the object creation. In
other words, we can have private, protected, public or default constructor in Java.
39
[Link] DEPARTEMENT OF COMPUTERS ,USHODAYA DEGREE COLLEGE,CHODAVARAM
BSC COMPUTER SCIENCE JAVA SEMESTER-III
Output:
Bike is created
The default constructor is used to provide the default values to the object like 0, null, etc.,
depending on the type.
40
[Link] DEPARTEMENT OF COMPUTERS ,USHODAYA DEGREE COLLEGE,CHODAVARAM
BSC COMPUTER SCIENCE JAVA SEMESTER-III
3. class Student3{
4. int id;
5. String name;
6. //method to display the value of id and name
7. void display(){[Link](id+" "+name);}
8.
9. public static void main(String args[]){
10. //creating objects
11. Student3 s1=new Student3();
12. Student3 s2=new Student3();
13. //displaying values of the object
14. [Link]();
15. [Link]();
16. }
17. }
Output:
0 null
0 null
Explanation:In the above class,you are not creating any constructor so compiler provides you
a default constructor. Here 0 and null values are provided by default constructor.
The parameterized constructor is used to provide different values to the distinct objects.
However, you can provide the same values also.
9. }
10. //method to display the values
11. void display(){[Link](id+" "+name);}
12.
13. public static void main(String args[]){
14. //creating objects and passing values
15. Student4 s1 = new Student4(111,"Karan");
16. Student4 s2 = new Student4(222,"Aryan");
17. //calling method to display the values of object
18. [Link]();
19. [Link]();
20. }
21. }
Output:
111 Karan
222 Aryan
Constructor overloading in Java is a technique of having more than one constructor with
different parameter lists. They are arranged in a way that each constructor performs a different
task.
42
[Link] DEPARTEMENT OF COMPUTERS ,USHODAYA DEGREE COLLEGE,CHODAVARAM
BSC COMPUTER SCIENCE JAVA SEMESTER-III
16. }
17. void display(){[Link](id+" "+name+" "+age);}
18.
19. public static void main(String args[]){
20. Student5 s1 = new Student5(111,"Karan");
21. Student5 s2 = new Student5(222,"Aryan",25);
22. [Link]();
23. [Link]();
24. }
25. }
Output:
111 Karan 0
222 Aryan 25
43
[Link] DEPARTEMENT OF COMPUTERS ,USHODAYA DEGREE COLLEGE,CHODAVARAM
BSC COMPUTER SCIENCE JAVA SEMESTER-III
There are many ways to copy the values of one object into another in java. They are:
o By constructor
o By assigning the values of one object into another
o By clone() method of Object class
In this example, we are going to copy the values of one object into another using java
constructor.
Output:
111 Karan
111 Karan
44
[Link] DEPARTEMENT OF COMPUTERS ,USHODAYA DEGREE COLLEGE,CHODAVARAM
BSC COMPUTER SCIENCE JAVA SEMESTER-III
o The static variable can be used to refer to the common property of all objects (which is
not unique for each object), for example, the company name of employees, college
name of students, etc.
o The static variable gets memory only once in the class area at the time of class loading.
Suppose there are 500 students in my college, now all instance data members will get memory
each time when the object is created. All students have its unique rollno and name, so instance
data member is good in such case. Here, "college" refers to the common property of all objects.
If we make it static, this field will get the memory only once.
45
[Link] DEPARTEMENT OF COMPUTERS ,USHODAYA DEGREE COLLEGE,CHODAVARAM
BSC COMPUTER SCIENCE JAVA SEMESTER-III
6. //constructor
7. Student(int r, String n){
8. rollno = r;
9. name = n;
10. }
11. //method to display the values
12. void display (){[Link](rollno+" "+name+" "+college);}
13. }
14. //Test class to show the values of objects
15. public class TestStaticVariable1{
16. public static void main(String args[]){
17. Student s1 = new Student(111,"Karan");
18. Student s2 = new Student(222,"Aryan");
19. //we can change the college of all objects by the single line of code
20. //[Link]="BBDIT";
21. [Link]();
22. [Link]();
23. }
24. }
Test it Now
Output:
46
[Link] DEPARTEMENT OF COMPUTERS ,USHODAYA DEGREE COLLEGE,CHODAVARAM
BSC COMPUTER SCIENCE JAVA SEMESTER-III
1. class Student{
2. int rollno;
3. String name;
4. float fee;
5. Student(int rollno,String name,float fee){
6. rollno=rollno;
7. name=name;
8. fee=fee;
9. }
10. void display(){[Link](rollno+" "+name+" "+fee);}
11. }
12. class TestThis1{
13. public static void main(String args[]){
14. Student s1=new Student(111,"ankit",5000f);
47
[Link] DEPARTEMENT OF COMPUTERS ,USHODAYA DEGREE COLLEGE,CHODAVARAM
BSC COMPUTER SCIENCE JAVA SEMESTER-III
Output:
0 null 0.0
0 null 0.0
In the above example, parameters (formal arguments) and instance variables are same. So, we
are using this keyword to distinguish local variable and instance variable.
Output:
If local variables(formal arguments) and instance variables are different, there is no need to
use this keyword like in the following program:
48
[Link] DEPARTEMENT OF COMPUTERS ,USHODAYA DEGREE COLLEGE,CHODAVARAM
BSC COMPUTER SCIENCE JAVA SEMESTER-III
Output:
49
[Link] DEPARTEMENT OF COMPUTERS ,USHODAYA DEGREE COLLEGE,CHODAVARAM
BSC COMPUTER SCIENCE JAVA SEMESTER-III
50
[Link] DEPARTEMENT OF COMPUTERS ,USHODAYA DEGREE COLLEGE,CHODAVARAM
BSC COMPUTER SCIENCE JAVA SEMESTER-III
UNIT-III
Inheritance in Java
Inheritance in Java is a mechanism in which one object acquires all the properties and
behaviors of a parent object. It is an important part of OOPs (Object Oriented programming
system).
The idea behind inheritance in Java is that you can create new classes that are built upon
existing classes. When you inherit from an existing class, you can reuse methods and fields of
the parent class. Moreover, you can add new methods and fields in your current class also.
The extends keyword indicates that you are making a new class that derives from an existing
class. The meaning of "extends" is to increase the functionality.
In the terminology of Java, a class which is inherited is called a parent or superclass, and the
new class is called child or subclass.
51
[Link] DEPARTEMENT OF COMPUTERS ,USHODAYA DEGREE COLLEGE,CHODAVARAM
BSC COMPUTER SCIENCE JAVA SEMESTER-III
As displayed in the above figure, Programmer is the subclass and Employee is the superclass.
The relationship between the two classes is Programmer IS-A Employee. It means that
Programmer is a type of Employee.
1. class Employee{
2. float salary=40000;
3. }
4. class Programmer extends Employee{
5. int bonus=10000;
6. public static void main(String args[]){
7. Programmer p=new Programmer();
8. [Link]("Programmer salary is:"+[Link]);
9. [Link]("Bonus of Programmer is:"+[Link]);
10. }
11. }
Test it Now
In the above example, Programmer object can access the field of own class as well as of
Employee class i.e. code reusability.
52
[Link] DEPARTEMENT OF COMPUTERS ,USHODAYA DEGREE COLLEGE,CHODAVARAM
BSC COMPUTER SCIENCE JAVA SEMESTER-III
In java programming, multiple and hybrid inheritance is supported through interface only. We
will learn about interfaces later.
1. class Animal{
2. void eat(){[Link]("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){[Link]("barking...");}
6. }
7. class TestInheritance{
53
[Link] DEPARTEMENT OF COMPUTERS ,USHODAYA DEGREE COLLEGE,CHODAVARAM
BSC COMPUTER SCIENCE JAVA SEMESTER-III
Output:
barking...
eating...
1. class Animal{
2. void eat(){[Link]("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){[Link]("barking...");}
6. }
7. class BabyDog extends Dog{
8. void weep(){[Link]("weeping...");}
9. }
10. class TestInheritance2{
11. public static void main(String args[]){
12. BabyDog d=new BabyDog();
13. [Link]();
14. [Link]();
15. [Link]();
16. }}
Output:
weeping...
barking...
eating...
54
[Link] DEPARTEMENT OF COMPUTERS ,USHODAYA DEGREE COLLEGE,CHODAVARAM
BSC COMPUTER SCIENCE JAVA SEMESTER-III
55
[Link] DEPARTEMENT OF COMPUTERS ,USHODAYA DEGREE COLLEGE,CHODAVARAM
BSC COMPUTER SCIENCE JAVA SEMESTER-III
1. variable
2. method
3. class
1. class Bike9{
2. final int speedlimit=90;//final variable
3. void run(){
4. speedlimit=400;
5. }
6. public static void main(String args[]){
7. Bike9 obj=new Bike9();
8. [Link]();
9. }
10. }//end of class
Test it Now
56
[Link] DEPARTEMENT OF COMPUTERS ,USHODAYA DEGREE COLLEGE,CHODAVARAM
BSC COMPUTER SCIENCE JAVA SEMESTER-III
57
[Link] DEPARTEMENT OF COMPUTERS ,USHODAYA DEGREE COLLEGE,CHODAVARAM
BSC COMPUTER SCIENCE JAVA SEMESTER-III
Abstraction in Java
Abstraction is a process of hiding the implementation details and showing only functionality to
the user.
Another way, it shows only essential things to the user and hides the internal details, for
example, sending SMS where you type the text and send the message. You don't know the
internal processing about the message delivery.
Abstraction lets you focus on what the object does instead of how it does it.
running safely
58
[Link] DEPARTEMENT OF COMPUTERS ,USHODAYA DEGREE COLLEGE,CHODAVARAM
BSC COMPUTER SCIENCE JAVA SEMESTER-III
59
[Link] DEPARTEMENT OF COMPUTERS ,USHODAYA DEGREE COLLEGE,CHODAVARAM
BSC COMPUTER SCIENCE JAVA SEMESTER-III
Java Array
Normally, an array is a collection of similar type of elements that have a contiguous memory
location.
Java array is an object which contains elements of a similar data type. It is a data structure
where we store similar elements. We can store only a fixed set of elements in a Java array.
Array in java is index-based, the first element of the array is stored at the 0 index.
1. arrayRefVar=new datatype[size];
Example of Java Array
Let's see the simple example of java array, where we are going to declare, instantiate, initialize
and traverse an array.
1. class Testarray{
2. public static void main(String args[]){
3. int a[]=new int[5];//declaration and instantiation
4. a[0]=10;//initialization
5. a[1]=20;
6. a[2]=70;
7. a[3]=40;
8. a[4]=50;
9. //traversing array
10. for(int i=0;i<[Link];i++)//length is the property of array
11. [Link](a[i]);
12. }}
60
[Link] DEPARTEMENT OF COMPUTERS ,USHODAYA DEGREE COLLEGE,CHODAVARAM
BSC COMPUTER SCIENCE JAVA SEMESTER-III
Test it Now
Output:
10
20
70
40
50
1. class Testarray1{
2. public static void main(String args[]){
3. int a[]={33,3,4,5};//declaration, instantiation and initialization
4. //printing array
5. for(int i=0;i<[Link];i++)//length is the property of array
6. [Link](a[i]);
7. }}
Test it Now
Output:
33
3
4
5
Let's see the simple example to get the minimum number of an array using a method.
61
[Link] DEPARTEMENT OF COMPUTERS ,USHODAYA DEGREE COLLEGE,CHODAVARAM
BSC COMPUTER SCIENCE JAVA SEMESTER-III
9. min=arr[i];
10.
11. [Link](min);
12. }
13.
14. public static void main(String args[]){
15. int a[]={33,3,4,5};//declaring and initializing an array
16. min(a);//passing array to method
17. }}
Output:3
1. arr[0][0]=1;
2. arr[0][1]=2;
3. arr[0][2]=3;
4. arr[1][0]=4;
5. arr[1][1]=5;
6. arr[1][2]=6;
7. arr[2][0]=7;
8. arr[2][1]=8;
9. arr[2][2]=9;
62
[Link] DEPARTEMENT OF COMPUTERS ,USHODAYA DEGREE COLLEGE,CHODAVARAM
BSC COMPUTER SCIENCE JAVA SEMESTER-III
Output:
1 2 3
2 4 5
4 4 5
63
[Link] DEPARTEMENT OF COMPUTERS ,USHODAYA DEGREE COLLEGE,CHODAVARAM
BSC COMPUTER SCIENCE JAVA SEMESTER-III
64
[Link] DEPARTEMENT OF COMPUTERS ,USHODAYA DEGREE COLLEGE,CHODAVARAM
BSC COMPUTER SCIENCE JAVA SEMESTER-III
65
[Link] DEPARTEMENT OF COMPUTERS ,USHODAYA DEGREE COLLEGE,CHODAVARAM
BSC COMPUTER SCIENCE JAVA SEMESTER-III
66
[Link] DEPARTEMENT OF COMPUTERS ,USHODAYA DEGREE COLLEGE,CHODAVARAM
BSC COMPUTER SCIENCE JAVA SEMESTER-III
Interface in Java
An interface in java is a blueprint of a class. It has static constants and abstract methods.
The interface in Java is a mechanism to achieve abstraction.
.
Why use Java interface?
There are mainly three reasons to use interface. They are given below.
o It is used to achieve abstraction.
o By interface, we can support the functionality of multiple inheritance.
o It can be used to achieve loose coupling.
How to declare an interface?
An interface is declared by using the interface keyword. It provides total abstraction; means all
the methods in an interface are declared with the empty body, and all the fields are public,
static and final by default. A class that implements an interface must implement all the
methods declared in the interface.
Syntax:
1. interface <interface_name>{
2.
3. // declare constant fields
4. // declare methods that abstract
5. // by default.
6. }
67
[Link] DEPARTEMENT OF COMPUTERS ,USHODAYA DEGREE COLLEGE,CHODAVARAM
BSC COMPUTER SCIENCE JAVA SEMESTER-III
1. interface Printable{
2. void print();
3. }
4. interface Showable{
5. void show();
6. }
7. class A7 implements Printable,Showable{
8. public void print(){[Link]("Hello");}
9. public void show(){[Link]("Welcome");}
10.
11. public static void main(String args[]){
12. A7 obj = new A7();
13. [Link]();
14. [Link]();
15. }
16. }
Test it Now
Output:Hello
Welcome
1. interface Printable{
2. void print();
68
[Link] DEPARTEMENT OF COMPUTERS ,USHODAYA DEGREE COLLEGE,CHODAVARAM
BSC COMPUTER SCIENCE JAVA SEMESTER-III
3. }
4. interface Showable{
5. void print();
6. }
7.
8. class TestInterface3 implements Printable, Showable{
9. public void print(){[Link]("Hello");}
10. public static void main(String args[]){
11. TestInterface3 obj = new TestInterface3();
12. [Link]();
13. }
14. }
Test it Now
Output:
Hello
As you can see in the above example, Printable and Showable interface have same methods but
its implementation is provided by class TestTnterface1, so there is no ambiguity.
Interface inheritance
A class implements an interface, but one interface extends another interface.
1. interface Printable{
2. void print();
3. }
4. interface Showable extends Printable{
5. void show();
6. }
7. class TestInterface4 implements Showable{
8. public void print(){[Link]("Hello");}
9. public void show(){[Link]("Welcome");}
10.
11. public static void main(String args[]){
12. TestInterface4 obj = new TestInterface4();
13. [Link]();
14. [Link]();
15. }
16. }
Test it Now
Output:
Hello
Welcome
69
[Link] DEPARTEMENT OF COMPUTERS ,USHODAYA DEGREE COLLEGE,CHODAVARAM
BSC COMPUTER SCIENCE JAVA SEMESTER-III
70
[Link] DEPARTEMENT OF COMPUTERS ,USHODAYA DEGREE COLLEGE,CHODAVARAM
BSC COMPUTER SCIENCE JAVA SEMESTER-III
UNIT-IV
In Java, an exception is an event that disrupts the normal flow of the program. It is an object
which is thrown at runtime.
71
[Link] DEPARTEMENT OF COMPUTERS ,USHODAYA DEGREE COLLEGE,CHODAVARAM
BSC COMPUTER SCIENCE JAVA SEMESTER-III
1. Checked Exception
2. Unchecked Exception
3. Error
The classes which directly inherit Throwable class except RuntimeException and Error are
known as checked exceptions e.g. IOException, SQLException etc. Checked exceptions are
checked at compile-time.
2) Unchecked Exception
The classes which inherit RuntimeException are known as unchecked exceptions e.g.
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc. Unchecked
exceptions are not checked at compile-time, but they are checked at runtime.
3) Error
Keyword Description
try The "try" keyword is used to specify a block where we should place exception code. The
try block must be followed by either catch or finally. It means, we can't use try block
alone.
catch The "catch" block is used to handle the exception. It must be preceded by try block
which means we can't use catch block alone. It can be followed by finally block later.
finally The "finally" block is used to execute the important code of the program. It is executed
whether an exception is handled or not.
throw The "throw" keyword is used to throw an exception.
72
[Link] DEPARTEMENT OF COMPUTERS ,USHODAYA DEGREE COLLEGE,CHODAVARAM
BSC COMPUTER SCIENCE JAVA SEMESTER-III
Output:
In the above example, 100/0 raises an ArithmeticException which is handled by a try-catch block
If an exception occurs at the particular statement of try block, the rest of the block code will not execute.
So, it is recommended not to keeping the code in try block that will not throw an exception.
73
[Link] DEPARTEMENT OF COMPUTERS ,USHODAYA DEGREE COLLEGE,CHODAVARAM
BSC COMPUTER SCIENCE JAVA SEMESTER-III
The catch block must be used after the try block only. You can use multiple catch block with a single try
block.
Example 4
Here, we handle the exception using the parent class exception.
Output:
[Link]: / by zero
rest of the code
Points to remember
o At a time only one exception occurs and at a time only one catch block is executed.
o All catch blocks must be ordered from most specific to most general, i.e. catch for
ArithmeticException must come before catch for Exception.
74
[Link] DEPARTEMENT OF COMPUTERS ,USHODAYA DEGREE COLLEGE,CHODAVARAM
BSC COMPUTER SCIENCE JAVA SEMESTER-III
Example 1
Let's see a simple example of java multi-catch block.
Output:
finally clause
A finally keyword is used to create a block of code that follows a try block. A finally block of code is always
executed whether an exception has occurred or not. Using a finally block, it lets you run any cleanup type
statements that you want to execute, no matter what happens in the protected code. A finally block appears at
the end of catch block.
75
[Link] DEPARTEMENT OF COMPUTERS ,USHODAYA DEGREE COLLEGE,CHODAVARAM
BSC COMPUTER SCIENCE JAVA SEMESTER-III
Out of try
Exception in thread main java. Lang. exception array Index out of bound exception.
76
[Link] DEPARTEMENT OF COMPUTERS ,USHODAYA DEGREE COLLEGE,CHODAVARAM
BSC COMPUTER SCIENCE JAVA SEMESTER-III
77
[Link] DEPARTEMENT OF COMPUTERS ,USHODAYA DEGREE COLLEGE,CHODAVARAM
BSC COMPUTER SCIENCE JAVA SEMESTER-III
Threads
What is Thread in java
A thread is a lightweight subprocess, the smallest unit of processing. It is a separate path of execution.
Threads are independent. If there occurs exception in one thread, it doesn't affect other threads. It uses a
shared memory area.
As shown in the above figure, a thread is executed inside the process. There is context-
switching between the threads. There can be multiple processes inside the OS, and one process
can have multiple threads.
Multithreading in Java
Multithreading in java is a process of executing multiple threads simultaneously.
A thread is a lightweight sub-process, the smallest unit of processing. Multiprocessing and
multithreading, both are used to achieve multitasking.
Java Multithreading is mostly used in games, animation, etc.
3) Threads are independent, so it doesn't affect other threads if an exception occurs in a single thread.
78
[Link] DEPARTEMENT OF COMPUTERS ,USHODAYA DEGREE COLLEGE,CHODAVARAM
BSC COMPUTER SCIENCE JAVA SEMESTER-III
Multitasking
Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to utilize the
CPU. Multitasking can be achieved in two ways:
A thread can be in one of the five states. According to sun, there is only 4 states in thread life cycle in
java new, runnable, non-runnable and terminated. There is no running state.
But for better understanding the threads, we are explaining it in the 5 states.
The life cycle of the thread in java is controlled by JVM. The java thread states are as follows:
1. New
2. Runnable
3. Running
4. Non-Runnable (Blocked)
5. Terminated
79
[Link] DEPARTEMENT OF COMPUTERS ,USHODAYA DEGREE COLLEGE,CHODAVARAM
BSC COMPUTER SCIENCE JAVA SEMESTER-III
1) New
The thread is in new state if you create an instance of Thread class but before the invocation of start() method.
2) Runnable
The thread is in runnable state after invocation of start() method, but the thread scheduler has not
selected it to be the running thread.
3) Running
The thread is in running state if the thread scheduler has selected it.
4) Non-Runnable (Blocked)
This is the state when the thread is still alive, but is currently not eligible to run.
5) Terminated
A thread is in terminated or dead state when its run() method exits.
Thread class:
Thread class provide constructors and methods to create and perform operations on a [Link] class
extends Object class and implements Runnable interface.
80
[Link] DEPARTEMENT OF COMPUTERS ,USHODAYA DEGREE COLLEGE,CHODAVARAM
BSC COMPUTER SCIENCE JAVA SEMESTER-III
Runnable interface:
The Runnable interface should be implemented by any class whose instances are intended to be executed b
Runnable interface have only one method named run().
Starting a thread
start() method of Thread class is used to start a newly created thread. It performs following
tasks:
o A new thread starts(with new callstack).
o The thread moves from New state to the Runnable state.
o When the thread gets a chance to execute, its target run() method will run.
81
[Link] DEPARTEMENT OF COMPUTERS ,USHODAYA DEGREE COLLEGE,CHODAVARAM
BSC COMPUTER SCIENCE JAVA SEMESTER-III
Syntax:
public void join()throws InterruptedException
Output:1
2
3
4
5
1
1
2
2
3
3
4
4
5
5
82
[Link] DEPARTEMENT OF COMPUTERS ,USHODAYA DEGREE COLLEGE,CHODAVARAM
BSC COMPUTER SCIENCE JAVA SEMESTER-III
Synchronization in Java
Synchronization in java is the capability to control the access of multiple threads to any shared
resource.
Java Synchronization is better option where we want to allow only one thread to access the
shared resource.
Types of Synchronization
There are two types of synchronization
1. Process Synchronization
2. Thread Synchronization
Here, we will discuss only thread synchronization.
Java synchronized method
If you declare any method as synchronized, it is known as synchronized method.
Synchronized method is used to lock an object for any shared resource.
When a thread invokes a synchronized method, it automatically acquires the lock for that object and
releases it when the thread completes its task.
1. //example of java synchronized method
2. class Table{
3. synchronized void printTable(int n){//synchronized method
4. for(int i=1;i<=5;i++){
5. [Link](n*i);
6. try{
7. [Link](400);
8. }catch(Exception e){[Link](e);}
9. }
10.
11. }
12. }
13.
14. class MyThread1 extends Thread{
15. Table t;
16. MyThread1(Table t){
17. this.t=t;
18. }
19. public void run(){
20. [Link](5);
21. }
22.
23. }
24. class MyThread2 extends Thread{
25. Table t;
26. MyThread2(Table t){
27. this.t=t;
28. }
29. public void run(){
30. [Link](100);
31. }
32. }
33.
34. public class TestSynchronization2{
35. public static void main(String args[]){
36. Table obj = new Table();//only one object
83
[Link] DEPARTEMENT OF COMPUTERS ,USHODAYA DEGREE COLLEGE,CHODAVARAM
BSC COMPUTER SCIENCE JAVA SEMESTER-III
84
[Link] DEPARTEMENT OF COMPUTERS ,USHODAYA DEGREE COLLEGE,CHODAVARAM
BSC COMPUTER SCIENCE JAVA SEMESTER-III
85
[Link] DEPARTEMENT OF COMPUTERS ,USHODAYA DEGREE COLLEGE,CHODAVARAM
BSC COMPUTER SCIENCE JAVA SEMESTER-III
UNIT-V
Java Applet
Applet is a special type of program that is embedded in the webpage to generate the dynamic content. It
runs inside the browser and works at client side.
Advantage of Applet
There are many advantages of applet. They are as follows:
o It works at client side so less response time.
o Secured
o It can be executed by browsers running under many plateforms, including Linux, Windows, Mac Os
etc.
Drawback of Applet
o Plugin is required at client browser to execute applet.
Hierarchy of Applet
86
[Link] DEPARTEMENT OF COMPUTERS ,USHODAYA DEGREE COLLEGE,CHODAVARAM
BSC COMPUTER SCIENCE JAVA SEMESTER-III
[Link] class
For creating any applet [Link] class must be inherited. It provides 4 life cycle methods of
applet.
1. public void init(): is used to initialized the Applet. It is invoked only once.
2. public void start(): is invoked after the init() method or browser is maximized. It is used to start
the Applet.
3. public void stop(): is used to stop the Applet. It is invoked when Applet is stop or browser is
minimized.
4. public void destroy(): is used to destroy the Applet. It is invoked only once.
[Link] class
The Component class provides 1 life cycle method of applet.
1. public void paint(Graphics g): is used to paint the Applet. It provides Graphics class object that
can be used for drawing oval, rectangle, arc etc.
1. By html file.
2. By appletViewer tool (for testing purpose).
1. //[Link]
2. import [Link];
3. import [Link];
4. public class First extends Applet{
5.
6. public void paint(Graphics g){
7. [Link]("welcome",150,150);
8. }
9.
10. }
[Link]
1. <html>
2. <body>
3. <applet code="[Link]" width="300" height="300">
4. </applet>
5. </body>
6. </html>
87
[Link] DEPARTEMENT OF COMPUTERS ,USHODAYA DEGREE COLLEGE,CHODAVARAM
BSC COMPUTER SCIENCE JAVA SEMESTER-III
1. //[Link]
2. import [Link];
3. import [Link];
4. public class First extends Applet{
5.
6. public void paint(Graphics g){
7. [Link]("welcome to applet",150,150);
8. }
9.
10. }
11. /*
12. <applet code="[Link]" width="300" height="300">
13. </applet>
14. */
c:\>javac [Link]
c:\>appletviewer [Link]
88
[Link] DEPARTEMENT OF COMPUTERS ,USHODAYA DEGREE COLLEGE,CHODAVARAM
BSC COMPUTER SCIENCE JAVA SEMESTER-III
Java Package
A java package is a group of similar types of classes, interfaces and sub-packages.
Package in java can be categorized in two form, built-in package and user-defined package.
There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.
Here, we will have the detailed learning of creating and using user-defined packages.
Advantage of Java Package
1) Java package is used to categorize the classes and interfaces so that they can be easily
maintained.
2) Java package provides access protection.
3) Java package removes naming collision.
//save as [Link]
1. package mypack;
2. public class Simple{
3. public static void main(String args[]){
4. [Link]("Welcome to package");
5. }
6. }
1. import package.*;
2. import [Link];
3. fully qualified name.
89
[Link] DEPARTEMENT OF COMPUTERS ,USHODAYA DEGREE COLLEGE,CHODAVARAM
BSC COMPUTER SCIENCE JAVA SEMESTER-III
1) Using packagename.*
If you use package.* then all the classes and interfaces of this package will be accessible but not
subpackages.
The import keyword is used to make the classes and interface of another package accessible to the
current package.
2) Using [Link]
If you import [Link] then only declared class of this package will be accessible.
1. /save as [Link]
2. package mypack;
3. public class Simple{
4. public static void main(String args[]){
5. [Link]("Welcome to package");
6. }
7. }
To Compile:
To Run:
To run this program from e:\source directory, you need to set classpath of the directory where the class file resides.
91
[Link] DEPARTEMENT OF COMPUTERS ,USHODAYA DEGREE COLLEGE,CHODAVARAM
BSC COMPUTER SCIENCE JAVA SEMESTER-III
To run this program from e:\source directory, you can use -classpath switch of java that tells where to
look for class file. For example:
Output:Welcome to package
92
[Link] DEPARTEMENT OF COMPUTERS ,USHODAYA DEGREE COLLEGE,CHODAVARAM
BSC COMPUTER SCIENCE JAVA SEMESTER-III
93
[Link] DEPARTEMENT OF COMPUTERS ,USHODAYA DEGREE COLLEGE,CHODAVARAM
BSC COMPUTER SCIENCE JAVA SEMESTER-III
Java uses the concept of a stream to make I/O operation fast. The [Link] package contains all the classes
required for input and output operations.
Stream
A stream is a sequence of data. In Java, a stream is composed of bytes. It's called a stream because it is
like a stream of water that continues to flow.
In Java, 3 streams are created for us automatically. All these streams are attached with the console.
Let's see the code to print output and an error message to the console.
1. [Link]("simple message");
2. [Link]("error message");
OutputStream vs InputStream
The explanation of OutputStream and InputStream classes are given below:
OutputStream
Java application uses an output stream to write data to a destination; it may be a file, an array, peripheral
device or socket.
InputStream
Java application uses an input stream to read data from a source; it may be a file, an array, peripheral
device or socket.
Let's understand the working of Java OutputStream and InputStream by the figure given below.
94
[Link] DEPARTEMENT OF COMPUTERS ,USHODAYA DEGREE COLLEGE,CHODAVARAM
BSC COMPUTER SCIENCE JAVA SEMESTER-III
OutputStream class
OutputStream class is an abstract class. It is the superclass of all classes representing an
output stream of bytes. An output stream accepts output bytes and sends them to some sink.
1) public void write(int)throws IOException is used to write a byte to the current output
stream.
4) public void close()throws IOException is used to close the current output stream
OutputStream Hierarchy
95
[Link] DEPARTEMENT OF COMPUTERS ,USHODAYA DEGREE COLLEGE,CHODAVARAM
BSC COMPUTER SCIENCE JAVA SEMESTER-III
InputStream class
InputStream class is an abstract class. It is the superclass of all classes representing an input
stream of bytes.
1) public abstract int read()throws reads the next byte of data from the input
IOException stream. It returns -1 at the end of the file.
3) public void close()throws IOException is used to close the current input stream.
InputStream Hierarchy
96
[Link] DEPARTEMENT OF COMPUTERS ,USHODAYA DEGREE COLLEGE,CHODAVARAM