Unit2 WP
Unit2 WP
Object-Oriented Concepts
OOP stands for Object-Oriented Programming. OOP is a programming paradigm in which
every program is follows the concept of object. In other words, OOP is a way of writing
programs based on the object concept.
Object:
An entity that has state and behaviour is known as an object e.g., chair, bike, marker, pen,
table, car, etc. It can be physical or logical.
The example of a logical object is the banking system.For Example, Pen is an object. Its
name is Reynolds; color is white, known as its state. It is used to write, so writing is its
behaviour.
An object is an instance of a class.
Class:
A class is a template or blueprint from which objects are created. It is a logical entity. It can't
be physical.A class in java contains fields and methods
Syntax to declare a class:
class <class_name>
{
field;
method;
}
Encapsulation
The wrapping up of data and code(Methods) into single unit(called class) is known as
Encapsulation.Here the data is not Accessible to the outside world and only those methods
which are wrapped in the class can access it.
Abstraction
Abstraction is hiding the internal details and showing only essential functionality. In the
abstraction concept, we do not show the actual implementation to the end user, instead we
provide only essential things.
Polymorphism is the process of defining same method with different implementation. That
means creating multiple methods with different behaviours.
Inheritance
Inheritance is the process of acquiring properties and behaviours from one object to
another object or one class to another class.
In the inheritance concept, the class which provides properties is called as parent class
and the class which receives the properties is called as child class.
Java is the most popular object-oriented programming language developed by James Gosling
in the year 1995.The following are the features of Java.
1. Simple
2. Secure
3. Portable
4. Object-oriented
5. Robust
6. Architecture-neutral
7. Platform Independent
8. Multi-threaded
9. Compiled and Interpreted
10. High performance
11. Distributed
12. Dynamic
Simple
Java programming language is very simple and easy to learn, understand, and code. Most of
the syntax in java follow basic programming language C and object-oriented programming
concepts are similar to C++.
Java is best known for its security. With Java, we can develop virus-free systems. Java
language provides these securities by default. Some security can also be provided by an
application developer explicitly through SSL, JAAS, Cryptography, etc.
Portable
Portability is one of the core features of java which enables the java programs to run on any
computer or operating system. For example, an applet developed using java runs on a wide
variety of CPUs, operating systems, and browsers connected to the Internet.
Object-oriented
It provides many features that make the program execute reliably in variety of
environments.
Java is a strictly typed language. It checks code both at compile time and runtime.
Java takes care of all memory management problems with garbage-collection.
Java, with the help of exception handling captures all types of serious errors and
eliminates any risk of crashing the system.
Architecture Neutral
Java language and Java Virtual Machine helped in achieving the goal of “write once;
run anywhere, any time, forever.”
Changes and upgrades in operating systems, processors and system resources will not
force any changes in Java Programs.
Multi-threaded
A thread is like a separate program, executing concurrently. We can write Java programs that
deal with many tasks at once by defining multiple threads. The main advantage of multi-
threading is that it doesn't occupy memory for each thread. It shares a common memory area.
Threads are important for multi-media, Web applications, etc.
Compiled and Interpreted
Java provides high performance with the help of features like JVM, interpretation, and its
simplicity.
Distributed
Java programming language supports TCP/IP protocols which enable the java to support the
distributed environment of the Internet. Java also supports Remote Method Invocation (RMI),
this feature enables a program to invoke methods across a network.
Dynamic
Java is said to be dynamic because the java byte code may be dynamically updated on a
running system and it has a dynamic memory allocation and deallocation (objects and
garbage collector).
The following three steps are used to create and execute a java program.
Java programming language has a rich set of data types. The data type is a category of data
stored in variables. In java, data types are classified into two types and they are as follows.
The primitive data types are built-in data types and they specify the type of value stored in a
variable and the memory size. The primitive data types do not have any additional methods.
In java, primitive data types includes byte, short, int, long, float, double, char, and boolean.
The following table provides more description of each primitive data type.
Data Memory Default
Meaning Range
type size Value
byte Whole numbers 1 byte -128 to +127 0
short Whole numbers 2 bytes -32768 to +32767 0
int Whole numbers 4 bytes -2,147,483,648 to +2,147,483,647 0
-9,223,372,036,854,775,808 to
Whole numbers 8 bytes 0L
long +9,223,372,036,854,775,807
Fractional -Stores fractional numbers. Sufficient for
float 4 bytes 0.0f
numbers storing 6 to 7 decimal digits
Fractional -Stores fractional numbers. Sufficient for
double 8 bytes 0.0d
numbers storing 15 decimal digits
char Single character 2 bytes 0 to 65535 \u0000
In java, non-primitive data types are the reference data types or user-created data types. All
non-primitive data types are implemented using object concepts. Every variable of the non-
primitive data type is an object. The non-primitive data types may use additional methods to
perform certain operations. The default value of non-primitive data type variable is null.
In java, examples of non-primitive data types are String, Array, List, Queue, Stack, Class,
Interface, etc.
Java Variables
A variable is a named memory location used to store a data value. A variable can be defined
as a container that holds a data value.
Local variables
Instance variables or Member variables or Global variables
Static variables or Class variables
Final variables
Local variables
The variables declared inside a method or a block are known as local variables. A local
variable is visible within the method in which it is declared. The local variable is created
when execution control enters into the method or block and destroyed after the method or
block execution completed.
public class LocalVariables {
public void show() {
int a = 10;
//static int x = 100;
System.out.println("Inside show method, a = " + a);
}
public void display() {
int b = 20;
System.out.println("Inside display method, b = " + b);
// trying to access variable 'a' - generates an ERROR
//System.out.println("Inside display method, a = " + a);
}
public static void main(String args[]) {
LocalVariables obj = new LocalVariables();
obj.show();
obj.display();
}
}
The variables declared inside a class and outside any method, constructor or block are known
as instance variables or member variables. These variables are visible to all the methods of
the class. The changes made to these variables by method affects all the methods in the class.
These variables are created separate copy for every object of that class. These variables are
accessed with the object of the class.
}
}
Final variables
A final variable is a variable that declared using final keyword. The final variable is
initialized only once, and does not allow any method to change it's value again. The variable
created using final keyword acts as constant. All variables like local, instance, and static
variables can be final variables.
Let's look at the following example java program to illustrate final variable in java.
public class FinalVariableExample {
void show() {
System.out.println("a = " + a);
a = 20; //Error due to final variable cann't be modified
}
Java Arrays
An array is a collection of similar data values with a single name. An array can also be
defined as, a special type of variable that holds multiple values of the same data type at a
time.
In java, arrays are objects and they are created dynamically using new operator. Every array
in java is organized using index values. The index value of an array starts with '0' and ends
with size-1'. We use the index value to access individual elements of an array.
In java, there are two types of arrays and they are as follows.
Creating an array
In the java programming language, an array must be created using new operator and with a
specific size. The size must be an integer value but not a byte, short, or long. We use the
following syntax to create an array.
(or)
In java, an array can also be initialized at the time of its declaration. When an array is
initialized at the time of its declaration, it need not specify the size of the array and use of
the new operator. Here, the size is automatically decided based on the number of values that
are initialized.
For example:
list[0] = 10;
System.out.println("Value at index 0 - " + list[0]);
System.out.println("Length of the array - " + list.length);
To create an array, you first must create an array variable of the desired type.
type var-name[ ];
Here, type declares the base type of the array. The base type determines the data type of each
element that comprises the array.
For example:
int month_days[];
In java, we can create an array with multiple dimensions. We can create 2-dimensional, 3-
dimensional, or any dimensional array.
Two-dimensional array
Syntax:
(or)
When we create a two-dimensional array, it created with a separate index for rows and
columns. The individual element is accessed using the respective row index followed by the
column index. A multidimensional array can be initialized while it has created using the
following syntax.
Syntax
For Example
The statement creates a two-dimensional array of three rows and two columns.
for example:
int[][] a = new int[3][4];
output:
01234
56789
10 11 12 13
15 16 17 18
OPERATORS IN JAVA
Java provides a rich set of operators to manipulate variables. We can divide all the Java
operators into the following groups –
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Increment and Decrement Operators
5. Conditional Operators
6. Assignment Operators
7. Bitwise Operators
8. Special Operators
Arithmetic operators are used in mathematical expressions in the same way that they are used
in algebra.
Logical Operators:
Logical Operators are used with binary variables. They are mainly used in conditional
statements and loops for evaluating a condition.
Assume Boolean variables A holds true and variable B holds false, then −
this statement:
x = x + 1;
can be rewritten like this by use of the increment operator:
x++;
Similarly, this statement:
x = x - 1;
is equivalent to
x--;
publicclassAutoOperatorDemo{
publicstaticvoid main(String args[]){
int num1=100;
int num2=200;
num1++;
num2--;
System.out.println("num1++ is: "+num1);
System.out.println("num2-- is: "+num2);
}
}
Output:
num1++is:101
num2--is:199
Java includes a special ternary (three-way) operator that can replace certain types of if-then-
else
statements.
Syntax:
Here, expression1 can be any expression that evaluates to a boolean value. If expression1 is
true, then expression2 is evaluated; otherwise, expression3 is evaluated. The result of the ?
operation is that of the expression evaluated. Both expression2 and expression3 are required
to return the same type, which can’t be void.
class Ternary {
public static void main(String args[]) {
int i, k;
i = 10;
k = i < 0 ? -i : i; // get absolute value of i
System.out.print("Absolute value of ");
System.out.println(i + " is " + k);
i = -10;
k = i < 0 ? -i : i; // get absolute value of i
System.out.print("Absolute value of ");
System.out.println(i + " is " + k);
}
}
Assignment Operators:
Syntax:
var = expression;
Here, the type of var must be compatible with the type of expression.
Assignments operators in java are: =, +=, - =, *=, /=, %=
Bitwise operator works on bits and performs bit-by-bit operation. Assume if a = 60 and b =
13; now in binary format they will be as follows −
a = 0011 1100
b = 0000 1101
-----------------
a&b = 0000 1100
a|b = 0011 1101
a^b = 0011 0001
~a = 1100 0011
Special Operators:
1. instanceof Operator
2. Dot operator
1.instanceof Operator:
This operator is used to know if an object is an instance of a particular class or not. This
operator returns “true” if an object given at the left hand side is an instance of the class given
at right hand side. Otherwise, it returns “false”.
Example
The above statement checks if the object “circle” is an instance of the class “Shape”. If yes, it
returns “true”, else returns “false”
2. Dot operator:
This operator is used to access the variables and methods of a class.
Example 1
student.mark
Here we are accessing the variable “mark” of the “student” object
Example 2:
student.getMarks()
Control Statements
control statements can be put into the following categories: selection, iteration, and
jump.
Selection statements allow your program to choose different paths of execution based
upon the outcome of an expression or the state of a variable.
If
The if statement is Java’s conditional branch statement. It can be used to route program
execution through
two different paths.
if(condition){
Statement(s);
}
Example of if statement
Output:
if(condition){
Statement(s);
}
else{
Statement(s);
}
The statements inside “if” would execute if the condition is true, and the statements inside
“else” would execute if the condition is false.
else
System.out.println("num is greater than or equal 50");
}
}
Output:
num is greater than or equal 50
Nested if:
if-else-if statement is used when we need to check multiple conditions. In this statement we
have only one “if” and one “else”, however we can have multiple “else if”. It is also known
as if else if ladder.
if(condition)
statement;
else if(condition)
statement;
else if(condition)
statement;
...
else
statement;
Note: The most important point to note here is that in if-else-if statement, as soon as the
condition is met, the corresponding set of statements get executed, rest gets ignored. If none
of the condition is met then the statements inside “else” gets executed.
Example of if-else-if
public class IfElseIfExample{
}} }
Output:
First the variable, value or expression which is provided in the switch parenthesis is evaluated
and then based on the result, the corresponding case block is executed that matches the result.
Output:
Default:Valueis:2
Iteration Statements
Java’s iteration statements are for, while, and do-while. These statements create what we
commonly call loops.
while
The while loop is Java’s most fundamental loop statement. It repeats a statement or block
while its controlling expression is true. Here is its general form:
while(condition) {
// body of loop
}
The condition can be any Boolean expression. The body of the loop will be executed as long
as the conditional expression is true. When condition becomes false, control passes to the
next line of code immediately following the loop. The curly braces are unnecessary if only a
single statement is being repeated.
Here is a while loop that counts down from 10, printing exactly ten lines of “tick”:
do-while :
class DoWhileLoopExample{
public static void main(String args[]){
int i=10;
do{
System.out.println(i);
i--;
}while(i>0);
}
}
FOR:
There are two forms of the for loop. The first is the traditional form
that has been in use since the original version of Java. The second is the new “for-each” form.
Note: If only one statement is being repeated, there is no need for the curly braces.
When the loop first starts, the initialization portion of the loop is executed.
(Generally, this is an expression that sets the value of the loop control variable, which
acts as a counter that controls the loop. It is important to understand that the
initialization expression is only executed once.)
Next, condition is evaluated. This must be a Boolean expression. It usually tests the
loop control variable against a target value. If this expression is true, then the body of
the loop is executed. If it is false, the loop terminates.
Next, the iteration portion of the loop is executed. This is usually an expression that
increments or decrements the loop control variable. The loop then iterates, first
evaluating the conditional expression, then executing the body of the loop, and then
executing the iteration expression with each pass. This process repeats until the
controlling expression is false.
Example:
class ForLoopExample{
public static void main(String args[]){
for(int i=10; i>1; i--){
System.out.println("The value of i is: "+i);
}
}
}
for-each:
A second form of for was defined that implements a “for-each” style loop.
A foreach style loop is designed to cycle through a collection of objects, such as an
array, in strictly sequential fashion, from start to finish.
Unlike some languages, such as C#, that implement a for-each loop by using the
keyword foreach, Java adds the for-each capability by enhancing the for statement.
The advantage of this approach is that no new keyword is required, and no preexisting
code is broken. The for-each style of for is also referred to as the enhanced for loop.
The general form of the for-each version of the for is shown here:
Here, type specifies the type and itr-var specifies the name of an iteration variable that will
receive the elements from a collection, one at a time, from beginning to end.
The collection being cycled through is specified by collection. There are various types of
collections that
can be used with the for, but the only type used as an Array shown below.
ex:
int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int sum = 0;
for(int x: nums) sum += x;
With each pass through the loop, x is automatically given a value equal to the next element
in nums. Thus, on the first iteration, x contains 1; on the second iteration, x contains 2; and
so on.
Example2:
Jump Statements
Java supports three jump statements: break, continue, and return. These statements transfer
control to another part of your program.
Using break:
In Java, the break statement has three uses. First, as you have seen, it terminates a statement
sequence in a switch statement. Second, it can be used to exit a loop. Third, it can be used as
a “civilized” form of goto.
Sometimes it is useful to force an early iteration of a loop. That is, you might want to
continue running the loop but stop processing the remainder of the code in its body
for this particular iteration.
This is, in effect, a goto just past the body of the loop, to the loop’s end.
The continue statement performs such an action. In while and do-while loops, a
continue statement causes control to be transferred directly to the conditional
expression that controls the loop.
In a for loop, control goes first to the iteration portion of the for statement and then to
the conditional expression.
For all three loops, any intermediate code is bypassed.
// Demonstrate continue.
class Continue {
public static void main(String args[]) {
for(int i=1; i<10; i++) {
System.out.print(i + " ");
if (i%2 == 0) continue;
System.out.println("");
}
}
}
Return
The last control statement is return. The return statement is used to explicitly return
from a method.
That is, it causes program control to transfer back to the caller of the method.
As such, it is categorized as a jump statement.
// Demonstrate return.
class Return {
public static void main(String args[]) {
boolean t = true;
As you can see, the final println( ) statement is not executed. As soon as return is executed,
control passes back to the caller.
Class Fundamentals
class classname {
type instance-variable1;
type instance-variable2;
// ...
type instance-variableN;
type methodname1(parameter-list) {
// body of method
}
type methodname2(parameter-list) {
// body of method
}
// ...
type methodnameN(parameter-list) {
// body of method
}
}
The data, or variables, defined within a class are called instance variables.
The code is contained within methods.
The methods and variables defined within a class are called members of the class.
A Simple Class
Here is a class called Box that defines three instance variables: width, height, and depth.
Currently, Box does not contain any methods.
class Box
{
double width;
double height;
double depth;
}
// This class declares an object of type Box.
class BoxDemo {
public static void main(String args[]) {
Box mybox = new Box();
double vol;
// assign values to mybox's instance variables
mybox.width = 10;
mybox.height = 20;
mybox.depth = 15;
// compute volume of box
vol = mybox.width * mybox.height * mybox.depth;
System.out.println("Volume is " + vol);
}
}
The output produced by this program is shown here:
Volume is 3000.0
Declaring Objects:
A class defines a new type of data. In this case, the new data type is called Box.
We will use this name to declare objects of type Box. It is important to remember that a class
declaration only creates a template;
To actually create a Box object, you will use a statement like the following:
type name(parameter-list)
{
// body of method
}
Methods that have a return type other than void return a value to the calling routine using the
following form of the return statement:
return value;
class BoxDemo3
{
public static void main(String args[]) {
Box mybox1 = new Box();
Box mybox2 = new Box();
// assign values to mybox1's instance variables
mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;
/* assign different values to mybox2's
instance variables */
mybox2.width = 3;
mybox2.height = 6;
mybox2.depth = 9;
// display volume of first box
mybox1.volume();
// display volume of second box
mybox2.volume();
}
}
This program generates the following output, which is the same as the previous version.
Volume is 3000.0
Volume is 162.0
Returning a Value
class BoxDemo4 {
public static void main(String args[]) {
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
// assign values to mybox1's instance variables
mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;
/* assign different values to mybox2's
instance variables */
mybox2.width = 3;
mybox2.height = 6;
mybox2.depth = 9;
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
}
While working under calling process, arguments is to be passed. These should be in the
same order as their respective parameters in the method specification. Parameters can be
passed by value or by reference.
Passing by value means that, whenever a call to a method is made, the parameters are
evaluated, and the result value is copied into a portion of memory. When the parameter is
used inside the method, either for read or write, we are actually using the copy, not the
original value which is unaffected by the operations inside the method.
On the other hand, when a programming language uses passing by reference, the changes
over a parameter inside a method will affect the original value. This is because what the
method is receiving is the reference, i.e the memory address, of the variable.
Some programming languages support passing by value, some support passing by reference,
and some others support both.
pass-by-value example:
class Swapper
{
int a;
int b;
Swapper(int x, int y) // Constructor ( next topic)
{
a = x;
b = y;
}
void swap(int x, int y)
{
int temp;
temp = x;
x = y;
y = temp;
}
}
class SwapDemo
{
public static void main(String[] args)
{
Swapper obj = new Swapper(10, 20);
System.out.println("Before swapping value of a is "+obj.a+" value of b is
"+obj.b);
obj.swap(obj.a, obj.b);
pass-by-reference example:
class Swapper
{
int a;
int b;
Swapper(int x, int y)// Constructor ( next topic)
{
a = x;
b = y;
}
void swap(Swapper ref)
{
int temp;
temp = ref.a;
ref.a = ref.b;
ref.b = temp;
}
}
class SwapDemo
{
public static void main(String[] args)
{
Swapper obj = new Swapper(10, 20);
System.out.println("Before swapping value of a is "+obj.a+" value of b is
"+obj.b);
obj.swap(obj);
System.out.println("After swapping value of a is "+obj.a+" value of b is
"+obj.b);
}
}
Output of the above programming will be:
Before swapping value of a is 10 value of b is 20
After swapping value of a is 20 value of b is 10
Method Binding
Method overloading
If a class has multiple methods having same name but different in parameters, it is known
as Method Overloading. If we have to perform only one operation, having same name of the
methods increases the readability of the program. Suppose you have to perform addition of
the given numbers but there can be any number of arguments, if you write the method such as
a(int,int) for two parameters, and b(int,int,int) for three parameters then it may be difficult for
you as well as other programmers to understand the behavior of the method because its name
differs.
class Adder{
static int add(int a,int b)
{
return a+b;
}
static int add(int a,int b,int c)
{
return a+b+c;
}
}
class TestOverloading1{
public static void main(String[] args)
{
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}
}
class Adder
{
static int add(int a, int b)
{
return a+b;
}
static double add(double a, double b)
{return a+b;
}
}
class TestOverloading2{
public static void main(String[] args)
{
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(12.3,12.6));
}}
Inheritance
Inheritance can be defined as the process where one class acquires the properties (methods
and fields) of another. With the use of inheritance the information is made manageable in a
hierarchical order.
The class which inherits the properties of other is known as subclass (derived class, child
class) and the class whose properties are inherited is known as superclass (base class, parent
class).
Types of inheritance:
1. Single Inheritance : In single inheritance, subclasses inherit the features of one superclass.
In image below, the class A serves as a base class for the derived class B.
// A simple example of
inheritance.
// Create a superclass.
class A {
int i, j;
void showij() {
System.out.println("i and j: " + i + " " + j);
}
}
// Create a subclass by extending class A.
class B extends A {
int k;
void showk() {
System.out.println("k: " + k);
}
void sum() {
System.out.println("i+j+k: " + (i+j+k));
}
}
class SimpleInheritance {
public static void main(String args[]) {
A superOb = new A();
B subOb = new B();
// The superclass may be used by itself.
superOb.i = 10;
superOb.j = 20;
System.out.println("Contents of superOb: ");
superOb.showij();
System.out.println();
/* The subclass has access to all public members of
its superclass. */
subOb.i = 7;
subOb.j = 8;
subOb.k = 9;
System.out.println("Contents of subOb: ");
subOb.showij();
subOb.showk();
System.out.println();
System.out.println("Sum of i, j and k in subOb:");
subOb.sum();
}
}
2.Multilevel Inheritance : In Multilevel Inheritance, a derived class will be inheriting a base
class and as well as the derived class also act as the base class to other class. In below image,
the class A serves as a base class for the derived class B, which in turn serves as a base class
for the derived class C. In Java, a class cannot directly access the grandparent’s members.
}}
3. Hierarchical Inheritance : In Hierarchical Inheritance, one class serves as a superclass
(base class) for more than one sub class.In below image, the class A serves as a base class for
the derived class B,C and D.
class A
{
private void methodA()
{
System.out.println("method of Class A");
}
}
class B extends A
{
public void methodB()
{
System.out.println("method of Class B");
}
}
class C extends A
{
public void methodC()
{
System.out.println("method of Class C");
}
}
class D extends A
{
public void methodD()
{
System.out.println("method of Class D");
}
}
class JavaExample
{
public static void main(String args[])
{
B obj1 = new B();
C obj2 = new C();
D obj3 = new D();
//All classes can access the method of class A
obj1.methodA();
obj2.methodA();
obj3.methodA();
}
}
4. MultipleInheritance (Through Interfaces) : I
To reduce the complexity and simplify the language, multiple inheritance is not supported in
java.
n Multiple inheritance ,one class can have more than one superclass and inherit features from
all parent classes. Please note that Java does not support multiple inheritance with classes. In
java, we can achieve multiple inheritance only through Interfaces. In image below, Class C is
derived from interface A and B.
Packages in Java
Packages in Java are a way of grouping similar types of classes / interfaces together.
It is a great way to achieve reusability.
We can simply import a class providing the required functionality from an existing
package and use it in our program. A package basically acts as a container for group
of related classes.
The concept of package can be considered as means to achieve data encapsulation.
Packages are categorized as:
1 ) Built-in packages ( standard packages which come as a part of Java Runtime
Environment )
2 ) User-defined packages ( packages defined by programmers to bundle group of
related classes )
Built-in Packages:
These packages consists of a large number of classes which are a part of Java API.
For e.g: we have used java.io package previously which contain classes to support input /
output operations in Java. Similarly, there are other packages which provides different
functionality.
Some of the commonly used built-in packages are shown in the table below :
Package
Description
Name
Contains language support classes ( fore.g classes which defines primitive data
java.lang
types, math operations, etc.) . This package is automatically imported.
java.io Contains classes for supporting input / output operations.
Contains utility classes which implement data structures like Linked List, Hash
java.util
Table, Dictionary, etc and support for Date / Time operations.
java.applet Contains classes for creating Applets.
Contains classes for implementing the components of graphical user interface (
java.awt
like buttons, menus, etc. ).
java.net Contains classes for supporting networking operations.
First statement imports Vector class from util package which is contained inside java
package.
Second statement imports all the classes from util package.
User-defined packages:
Creating a Package:
While creating a package, you should choose a name for the package and include a
package statement along with that name at the top of every source file that contains
the classes, interfaces, enumerations, and annotation types that you want to include in
the package.
forExample: packageMypack;
The package statement should be the first line in the source file. There can be only one
package statement in each source file, and it applies to all types in the file.
To compile the Java programs with package statements, you have to use -d option as shown
below.
You need to use fully qualified name e.g. mypack.Simpleetc to run the class.
Compile:javac -d .file_name.java
Run:java mypack.file_name
Importing Packages
importpkg1[.pkg2].(classname|*);
Here, pkg1 is the name of a top-level package, and pkg2 is the name of a subordinate package
inside the outer package separated by a dot (.).
There is no practical limit on the depth of a package hierarchy, except that imposed by the
file system.
either an explicit classname or a star (*), which indicates that the Java compiler should
import the entire package.
ForExample:
import java.util.Scanner;
import java.io.*;
The basic language functions are stored in a package inside of the java package called
java.lang. (Default Package)
This is equivalent to the following line being at the top of all of your programs:
Import java.lang.*;
There are three ways to access the package from outside the package.
import package.*;
import package.classname;
fully qualified name.
Output:Hello
Interfaces
Defining an Interface
Syntax:
access_specifier interface name {
return-type method-name (parameter-list); //Abstract Method
type final-varname1 = value;
type final-varname2 = value; //variables
default method-name (parameter-list)
{ //default method body; }
staticmethod-name (parameter-list)
{ //method body }
}
In other words, Interface fields are public, static and final by default, and the methods are
public and abstract.
Implementing Interfaces
Once an interface has been defined, one or more classes can inherit that interface by
using implements Keyword
The methods that implement an interface in a class must be declared with public
accessSpecifier.
Syntax:
If a class implements more than one interface, the interfaces are separated with a comma.
As shown in the figure given below, a class extends another class, an interface extends
another interface, but a class implements an interface.
Output:
drawing circle
Exception Handling in Java
Exception Hierarchy
All exception and errors types are sub classes of class Throwable, which is base class of
hierarchy.
Error:
An Error indicates serious problem that a reasonable application should not try to catch.Error
is irrecoverable
Exception:
⮚ checked Exceptions
⮚ unchecked Exception
⮚ Checked Exception:
● The classes which are directly inherit from Throwable class ,which are checked at
Compilation Process are known as checked exceptions.
● Checked exceptions are checked at compile-time.
⮚ Unchecked Exception
● The classes which are inherit from Throwable classes ,which are occurred at
Runtime(Execution) Process are known as unchecked exceptions.
● Unchecked exceptions are not occurred at checked at compile-time, but they are
checked at runtime are also known as Runtime Exceptions
CHECKE
EXCEPTIONS DESCRIPTION UNCHECKED
D
Arithmetic errors such -
ArithmeticException YES
as a divide by zero
ArrayIndexOutOfBoundsExcepti Arrays index is not
- YES
on within array.length
Related Class not
ClassNotFoundException YES -
found
InputOuput field not
IOException YES -
found
Illegal argument when
IllegalArgumentException - YES
calling a method
One thread has been
InterruptedException interrupted by another YES -
thread
NoSuchMethodException Nonexistent method YES -
Invalid use of null
NullPointerException - YES
reference
Invalid string for
NumberFormatException - YES
conversion to number
Exception Handling
Exception handling is a framework that is used to handle runtime errors only, compile time
errors are not handled by exception handling in java.
We use specific keywords in java program to create an exception handler block.
Java exception handling is managed via five keywords: try, catch, throw, throws, and
finally.
Exception Description
Keyword
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.
For Example:
class test
{
public static void main(String args[])
{
int a=10,b=0,c;
try
{
c=a/b;
System.out.println(“result=”+c);
}
catch (ArithmeticException e)
{
System.out.println(“divide by Zero”);
}
System.out.println(“After try Catch Block”);
}
}
The following example traps two different exception types:
int a = args.length;
}
catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Array index oob: " + e);
}
}
}
if(n<=0)
throw new MyException("number is not positive");
else{
System.out.println(“number=”+n);
}
}
public static void main(String args[])
{
try{
positiveNumberCheck(-10);
}
catch(MyException e)
{
System.out.println(e.getMessage());
}
finally{
System.out.println(“Program ended”);
}
}
}
MultiThreading
What Is a Thread?
A single thread also has a beginning, an end, a sequence, and at any given time during the
runtime of the thread there is a single point of execution. However, a thread itself is not a
program. It cannot run on its own, but runs within a program.
A thread is considered lightweight because it runs within the context of a full-blown program
and takes advantage of the resources allocated for that program and the program's
environment.
Creating threads:
In Java, an object of the Thread class can represent a thread. Thread can be implemented
through any one of two ways:
Example 1:
System.out.println("thread is running...");
t1.start();
Java I/O (Input and Output) is used to process the input and produce the output.
Java uses the concept of a stream to make I/O operation fast. The java.io package contains all
the classes required for input and output operations.
We can perform file handling in Java by Java I/O API.
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.
1) System.out: standard output stream
2) System.in: standard input stream
3) System.err: standard error stream
Let's see the code to print output and an error message to the console.
1. System.out.println("simple message");
2. System.err.println("error message");
Let's see the code to get input from console.
int i=System.in.read();//returns ASCII code of 1st character
System.out.println((char)i);//will print the character
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.
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.
Useful methods of OutputStream
Method Description
1) public void write(int)throws IOException is used to write a byte to the current output stream.
2) public void write(byte[])throws is used to write an array of byte to the current output
IOException stream.
4) public void close()throws IOException is used to close the current output stream.
OutputStream Hierarchy
InputStream class
InputStream class is an abstract class. It is the superclass of all classes representing an input
stream of bytes.
Useful methods of InputStream
Method Description
1) public abstract int read()throws reads the next byte of data from the input stream. It returns -1 at
IOException the end of the file.
2) public int available()throws returns an estimate of the number of bytes that can be read from
IOException the current input stream.
File:
Files are a primary source and destination for data within many programs. Although there
are severe restrictions on their use within applets for security reasons, files are still a central
resource for storing persistent and shared information. A directory in Java is treated simply
as a File with one additional property—a list of filenames that can be examined by the list (
) method.
File(String directoryPath)
File(String directoryPath, String
filename) File(File dirObj, String
filename)
File(URI uriObj)
File defines many methods that obtain the standard properties of a File object. For
example, getName( ) returns the name of the file, getParent( ) returns the name of the
parent directory,
and exists( ) returns true if the file exists, false if it does not. The File class, however, is
not symmetrical. By this, we mean that there are a few methods that allow you to examine
the properties of a simple file object, but no corresponding function exists to change those
attributes.
When you run this program, you will see something similar to the
following: File Name: COPYRIGHT
Path:
/java/COPYRIGHT
Abs Path:
/java/COPYRIGHT
Parent: /java
exists
is
wri
tea
ble
is
rea
dab
le
is not a
directory
is normal
file
is absolute
File last modified:
812465204000 File size:
695 Bytes
FileInputStream
The FileInputStream class creates an InputStream that you can use to read bytes from a
file. Its two most common constructors are shown here:
FileInputStream(String
filepath)
FileInputStream(File fileObj)
Either can throw a FileNotFoundException. Here, filepath is the full path name of a file,
and fileObj is a File object that describes the file. The following example creates two
FileInputStreams that use the same disk file and each of the two constructors:
Although the first constructor is probably more commonly used, the second allows us to
closely examine the file using the File methods, before we attach it to an input stream.
When a FileInputStream is created, it is also opened for reading. FileInputStream
overrides six of the methods in the abstract class InputStream. The mark( ) and reset( )
methods are not overridden, and any attempt to use reset( ) on a FileInputStream will
generate an IOException.
try{
System.out.print((char)i);
fin.close();
}catch(Exception e){System.out.println(e);}
Output: W
try{
int i=0;
while((i=fin.read())!=-1){
System.out.print((char)i);
fin.close();
}catch(Exception e){System.out.println(e);}
FileOutputStream
FileOutputStream creates an OutputStream that you can use to write bytes to a file.
Its most commonly used constructors are shown here:
FileOutputStream(String filePath)
FileOutputStream(File fileObj)
FileOutputStream(String filePath, boolean append)
FileOutputStream(File fileObj, boolean append)
write byte:
public class writebyte {
try{
fout.write(65);
fout.close();
System.out.println("success...");
}catch(Exception e){
System.out.println(e);
import java.io.FileOutputStream;
try{
fout.write(b);
fout.close();
System.out.println("success...");
}catch(Exception e){System.out.println(e);}
}
Copying From one File to another by using FileInputSream and FileOutputStream
classes:
import java.io.*;
public class CopyFile{
int c;
while((c =in.read())!=-1){
out.write(c);
}
}finally{
if(in!=null){
in.close();
}
if(out!=null){
out.close();
}
}
}
}
Utility Classes
Java.util package contains the collection's framework, legacy collection classes, event
model, date and time facilities, internationalization, and miscellaneous utility classes (a string
tokenizer, a random-number generator, and a bit array). Here is the list of most commonly
used top ten Java utility classes:
1. Java Arrays Class
Java.util package provides an Arrays class that contains a static factory that allows arrays to
be viewed as lists. The class contains various methods for manipulating arrays like sorting
and searching. The methods in this class throw a NullPointerException, if the specified array
reference is null.
2. Java Vector Class
Java.util package provides a vector class that models and implements vector data structure. A
vector is a sequence container implementing array that can change in size. Unlike an array,
the size of a vector changes automatically when elements are appended or deleted. It is
similar to ArrayList, but with two differences:
Vector is synchronized.
Vector contains many legacy methods that are not part of the collections framework.
3. Java LinkedList Class
Java.util package provides a LinkedList class that has Doubly-linked list implementation of
the List and Deque interfaces. The class has all optional list operations, and permits all
elements (including null). Operations that index into the list will traverse the list from the
beginning or the end, whichever is closer to the specified index.
4. Java Calendar Class
Java.util package provides a Calendar class that represents a specific instant in time, with
millisecond precision.
5. Java Collections Class
Java.util package provides a Collections class which consists exclusively of static methods
that operate on or return collections. It contains polymorphic algorithms that operate on
collections, “wrappers”, which return a new collection backed by a specified collection. The
methods of this class all throw a NullPointerException if the collections or class objects
provided to them are null.
6. Java HashMap Class
A Hashtable models and implements the Map interface. This implementation provides all the
optional map operations and permits null values and the null key. A HashMap class is
roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls. This class
makes no guarantees as to the order of the map. It does not guarantee that the order will
remain constant over time.
7. Java Random Class
Java.util package provides a Random class. An instance of this class is used to generate a
stream of pseudorandom numbers. The class uses a 48-bit seed, which is modified using a
linear congruential formula. The algorithms implemented by class Random use a protected
utility method that on each invocation can supply up to 32 pseudorandomly generated bits.
8. Java Scanner Class
Java.util package provides a Scanner class. A simple text scanner parse primitive types and
strings using regular expressions. A Scanner breaks its input into tokens using a delimiter
pattern, which by default matches whitespace. The resulting tokens may then be converted
into values of different types using the various next methods.
A scanning operation may block waiting for input and not safe for multi-threaded use without
external synchronization.
9. Java ArrayList Class
Java.util package provides an ArrayList class that provides resizable-array implementation
of the list interface. It implements all optional list operations and permits all elements
including null. Along with this, the class provides methods to manipulate the size of the array
that is used internally to store the list. This class is almost equivalent to Vector class except
the implementation is not synchronized.
}}
Java String class provides a lot of methods to perform operations on string such as
compare(), concat(), equals(), split(), length(), replace(), compareTo(), intern(), substring()
etc.
String Concatenation by + (string concatenation)
Java string concatenation operator (+) is used to add strings.
For Example:
class TestStringConcatenation1{
public static void main(String args[]){
Substring in Java
A part of string is called substring. In other words, substring is a subset of another string. In
case of substring startIndex is inclusive and endIndex is exclusive.
You can get substring from the given string object by one of the two methods:
1. public String substring(int startIndex): This method returns new String object
containing the substring of the given string from specified startIndex (inclusive).
2. public String substring(int startIndex, int endIndex): This method returns new
String object containing the substring of the given string from specified startIndex to
endIndex.
In case of string:
startIndex: inclusive
endIndex: exclusive
Let's understand the startIndex and endIndex by the code given below.
1. String s="hello";
2. System.out.println(s.substring(0,2));//he
The java.lang.String class provides a lot of methods to work on string. By the help of these
methods, we can perform operations on string such as trimming, concatenating, converting,
comparing, replacing strings etc.
Java String is a powerful concept because everything is treated as a string if you submit any
form in window based, web based or mobile application.
The java string toUpperCase() method converts this string into uppercase letter and string
toLowerCase() method into lowercase letter.
public class Testmethodofstringclass{
public static void main(String args[]){
String s="Sachin";
System.out.println(s.toUpperCase());//SACHIN
System.out.println(s.toLowerCase());//sachin
System.out.println(s);//Sachin(no change in original)
}
}
output:
SACHIN
sachin
Sachin
Output:
T
The java string compareTo() method compares the given string with current string
lexicographically. It returns positive number, negative number or 0.
It compares strings on the basis of Unicode value of each character in the strings.
If first string is lexicographically greater than second string, it returns positive number
(difference of character value). If first string is less than second string lexicographically, it
returns negative number and if first string is lexicographically equal to second string, it
returns 0.
Example:
public class CompareToExample{
public static void main(String args[]){
String s1="hello";
String s2="hello";
String s3="meklo";
String s4="hemlo";
String s5="flag";
System.out.println(s1.compareTo(s2));//0 because both are equal
System.out.println(s1.compareTo(s3));//-5 because "h" is 5 times lower than "m"
System.out.println(s1.compareTo(s4));//-1 because "l" is 1 times lower than "m"
System.out.println(s1.compareTo(s5));//2 because "h" is 2 times greater than "f"
}}