0% found this document useful (0 votes)
18 views62 pages

Unit2 WP

This document provides an overview of Object-Oriented Programming (OOP) concepts, including key principles such as objects, classes, encapsulation, abstraction, polymorphism, and inheritance. It also highlights the features of Java as an object-oriented programming language, including its simplicity, security, portability, and robustness. Additionally, the document covers Java data types, variables, arrays, and the execution process of Java programs.

Uploaded by

sudharani.am
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views62 pages

Unit2 WP

This document provides an overview of Object-Oriented Programming (OOP) concepts, including key principles such as objects, classes, encapsulation, abstraction, polymorphism, and inheritance. It also highlights the features of Java as an object-oriented programming language, including its simplicity, security, portability, and robustness. Additionally, the document covers Java data types, variables, arrays, and the execution process of Java programs.

Uploaded by

sudharani.am
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 62

UNIT –2

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.

The object-oriented programming paradigm has the following core concepts.


1. Object
2. Class
3. Encapsulation
4. Abstraction
5. Polymorphism
6. Inheritance

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.

For example, if we want to drive a car,


we does not need to know about the internal functionality like how wheel system works? how
brake system works? how music system works?
Polymorphism

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.

Features of Java or Java Buzz Words

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++.

In a java programming language, many complicated features like pointers, operator


overloading, structures, unions, etc. have been removed. One of the most useful features is
the garbage collector it makes java more simple.
Secured

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

Java is said to be a pure object-oriented programming language. In java, everything is an


object. It supports all the features of the object-oriented programming paradigm. The
primitive data types java also implemented as objects using wrapper classes, but still, it
allows primitive data types to archive high-performance.
Robust

 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

 Usually a computer language is either compiled or Interpreted. Java combines both


this approach and makes it a two-stage system.
 Compiled : Java enables creation of a cross platform programs by compiling into an
intermediate representation called Java Bytecode.
 Interpreted : Bytecode is then interpreted, which generates machine code that can be
directly executed by the machine that provides a Java Virtual machine.
High performance

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).

Simple Java program


class Simple
{
public static void main(String args[])
{
System.out.println("Hello Java");
}
}
Execution Process of Java Program

The following three steps are used to create and execute a java program.

 Create a source code (.java file).


 Compile the source code using javac command.
 Run or execute .class file using java command.
Java Data Types

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.

 Primitive Data Types


 Non-primitive Data Types

Primitive Data Types

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

unsigned char 1 bit 0 or 1 0 (false)


boolean
Non-primitive Data Types

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.

In java, we use the following syntax to create variables.


Syntax
data_type variable_name;
(or)
data_type variable_name_1, variable_name_2,...;
(or)
data_type variable_name = value;
(or)
data_type variable_name_1 = value, variable_name_2 = value,...;

In java programming language variables are classified as follows.

 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();
}
}

Instance variables or member variables or global variables

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.

public class InstanceVariables {

int x = 100; //instance variables

public void show() {


System.out.println("Inside show method, x = " + x);
x = x + 100;
}
public void display() {
System.out.println("Inside display method, x = " + x);
}

public static void main(String[] args) {


InstanceVariables obj = new InstanceVariables();
obj.show();
obj.display();
}
}

Static variables or Class variables


o A static variable is a variable that declared using static keyword. The instance
variables can be static variables but local variables can not. Static variables are
initialized only once, at the start of the program execution. The static variable only
has one copy per class irrespective of how many objects we create. The static variable
gets memory only once in the class area at the time of class loading.The static variable
is access by using class name.

public class StaticVariablesExample {

int x=10, y=20; // Instance variables


static int z; // Static variable
public void show() {
int a; // Local variables
System.out.println("Inside show method,");
System.out.println("x = " + x + ", y = " + y );
}

public static void main(String[] args) {


StaticVariablesExample obj_1 = new StaticVariablesExample();
obj_1.show();
z = 1000;
System.out.println(“z=”+z);

}
}

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 {

final int a = 10;

void show() {
System.out.println("a = " + a);
a = 20; //Error due to final variable cann't be modified
}

public static void main(String[] args) {

FinalVariableExample obj = new FinalVariableExample();


obj.show();
}

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.

 One Dimensional Array


 Multi Dimensional Array

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.

data_type array_name[ ] = new data_type[size];

(or)

data_type[ ] array_name = new data_type[size];

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:

int list[ ] = {10, 20, 30, 40, 50};

Example 1 : ( creating Array by new operator)

public class ArrayExample {

public static void main(String[] args) {

int list[] = new int[5];

list[0] = 10;
System.out.println("Value at index 0 - " + list[0]);
System.out.println("Length of the array - " + list.length);

Here length is to display the total size of elements in an array


One-Dimensional Arrays

To create an array, you first must create an array variable of the desired type.

The general form of a one-dimensional array declaration is

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[];

new is a special operator that allocates memory.

The general form of new as it applies to one-dimensional arrays appears as follows:

array-var = new type[size];


Multidimensional Array

In java, we can create an array with multiple dimensions. We can create 2-dimensional, 3-
dimensional, or any dimensional array.

In Java, multidimensional arrays are arrays of arrays. To create a multidimensional array


variable, specify each additional index using another set of square brackets. We use the
following syntax to create two-dimensional array.

Two-dimensional array

Syntax:

data_type array_name[ ][ ] = new data_type[rows][columns];

(or)

data_type[ ][ ] array_name = new data_type[rows][columns];

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

data_type array_name[ ][ ] = {{value1, value2}, {value3, value4}, {value5, value6},...};

For Example

The statement creates a two-dimensional array of three rows and two columns.

int matrix_a[ ][ ] = {{1, 2},{3, 4},{5, 6}};


For example

The following declares a two-dimensional array variable called twoD


int twoD[][] = new int[4][5]; //4 columns and 5 rows

for example:
int[][] a = new int[3][4];

// Demonstrate a two-dimensional array.


class TwoDArray {
public static void main(String args[]) {
int twoD[][]= new int[4][5];
int i, j, k = 0;
for(i=0; i<4; i++)
for(j=0; j<5; j++) {
twoD[i][j] = k;
k++;
}
for(i=0; i<4; i++) {
for(j=0; j<5; j++)
{
System.out.print(twoD[i][j] + " ");
}
System.out.println();
}

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

The Arithmetic Operators

Arithmetic operators are used in mathematical expressions in the same way that they are used
in algebra.

Assume integer variable A holds 10 and variable B holds 20, then

Operator Description Example


Adds values on either side of the
+ (Addition) A + B will give 30
operator.
Subtracts right-hand operand from
- (Subtraction) A - B will give -10
left-hand operand.
Multiplies values on either side of
* (Multiplication) A * B will give 200
the operator.
Divides left-hand operand by right-
/ (Division) B / A will give 2
hand operand.
Divides left-hand operand by right-
% (Modulus) hand operand and returns B % A will give 0
remainder.
The operands of the arithmetic operators must be of a numeric type. You cannot use
them on Boolean types.
Relational Operators
The relational operators determine the relationship that one operand has to the other.
Specifically, they determine equality and ordering. The relational operators are shown here

Assume variable A holds 10 and variable B holds 20, then –

Operator Description Example


Checks if the values of two operands are
== (equal to) equal or not, if yes then condition becomes (A == B) is not true.
true.
Checks if the values of two operands are
!= (not equal to) equal or not, if values are not equal then (A != B) is true.
condition becomes true.
Checks if the value of left operand is greater
> (greater than) than the value of right operand, if yes then (A > B) is not true.
condition becomes true.
Checks if the value of left operand is less
< (less than) than the value of right operand, if yes then (A < B) is true.
condition becomes true.
Checks if the value of left operand is greater
>= (greater than or
than or equal to the value of right operand, (A >= B) is not true.
equal to)
if yes then condition becomes true.
Checks if the value of left operand is less
<= (less than or equal
than or equal to the value of right operand, (A <= B) is true.
to)
if yes then condition becomes true.

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 −

Operator Description Example


Called Logical AND operator. If both the
&& (logical and) operands are non-zero, then the condition (A && B) is false
becomes true.
Called Logical OR Operator. If any of the two
|| (logical or) operands are non-zero, then the condition (A || B) is true
becomes true.
Called Logical NOT Operator. Use to reverses
! (logical not) the logical state of its operand. If a condition is !(A && B) is true
true then Logical NOT operator will make false.
Increment and Decrement Operators :

The ++ and the – – are Java’s increment and decrement operators.


The increment operator increases its operand by one.
The decrement operator decreases its operand by one.
For example,

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

Conditional Operator: (also known as Ternary Operator)

Java includes a special ternary (three-way) operator that can replace certain types of if-then-
else
statements.
Syntax:

expression1 ? expression2 : expression3

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);
}
}

The output generated by the program is shown here:


Absolute value of 10 is 10
Absolute value of -10 is 10

Assignment Operators:
Syntax:

var = expression;
Here, the type of var must be compatible with the type of expression.
Assignments operators in java are: =, +=, - =, *=, /=, %=

y = x would assign value of variable x to the variable.


y+=x is equal to y = y+x
y-=x is equal to y = y-x
y*=x is equal to y = y*x
y/=x is equal to y = y/x
y%=x is equal to y = y%x
Bitwise Operators:
Java defines several bitwise operators that can be applied to the integer types, long, int,
short,
char, and byte. These operators act upon the individual bits of their operands.

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

The following table lists the bitwise operators −


Assume integer variable A holds 60 and variable B holds 13 then −

Operator Description Example


Binary AND Operator copies a bit to the
result if it exists in both operands.
(A & B) will give 12 which
& (bitwise and) It returns bit by bit AND of input values,
is 0000 1100
i.e, if both bits are 1, it gives 1, else it
gives 0.
Binary OR Operator copies a bit if it
exists in either operand.
(A | B) will give 61 which
| (bitwise or) It returns bit by bit OR of input values,
is 0011 1101
i.e, if either of the bits is 1, it gives 1,
else it gives 0.
Binary XOR Operator copies the bit if it
is set in one operand but not both.
(A ^ B) will give 49 which
^ (bitwise XOR) It returns bit by bit XOR of input values,
is 0011 0001
i.e, if corresponding bits are different, it
gives 1, else it gives 0.
Binary Ones Complement Operator is
unary and has the effect of 'flipping' bits. (~A ) will give -61 which is
~ (bitwise It returns the one’s compliment 1100 0011 in 2's
compliment) representation of the input value, i.e, complement form due to a
with all bits inversed, means it makes signed binary number.
every 0 to 1, and every 1 to 0.
Binary Left Shift Operator. The left
operands value is moved left by the A << 2 will give 240 which
<< (left shift)
number of bits specified by the right is 1111 0000
operand.
>> (right shift) Binary Right Shift Operator. The left A >> 2 will give 15 which
operands value is moved right by the is 1111
number of bits specified by the right
operand.
Shift right zero fill operator. The left
operands value is moved right by the
>>> (zero fill right A >>>2 will give 15 which
number of bits specified by the right
shift) is 0000 1111
operand and shifted values are filled up
with zeros.

Special Operators:

Java provides some special operators as given below.

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

circle instanceof Shape

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()

Here we are accessing the method “getMarks” of the “student” object.


This operator also can be used to access classes, packages etc.

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.

Iteration statements enable


program execution to repeat one or more statements (that is, iteration statements form
loops).

Jump statements allow your program to execute in a nonlinear fashion.

Java’s Selection Statements

Java supports two selection statements: if and switch.

These statements allow you to control the


flow of your program’s execution based upon conditions known only during run time.

If

The if statement is Java’s conditional branch statement. It can be used to route program
execution through
two different paths.

Here is the general form of the if statement:

if(condition){
Statement(s);
}

Example of if statement

public class IfStatementExample {

public static void main(String args[]){


int num=70;
if( num < 100 ){
/* This println statement will only execute,
* if the above condition is true
*/
System.out.println("number is less than 100");
}
}
}

Output:

number is less than 100


If else statement in Java

This is how an if-else statement looks:

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.

Example of if-else statement


public class IfElseExample{

public static void main(String args[]){


int num=120;
if( num <50)
System.out.println("num is less than 50");

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{

public static void main(String args[]){


i
nt num=1234;
if(num <100&& num>=1){
System.out.println("Its a two digit number");
}
else if(num <1000&& num>=100){
System.out.println("Its a three digit number");
}
else if(num <10000&& num>=1000){
System.out.println("Its a four digit number");
}
else if(num <100000&& num>=10000){
System.out.println("Its a five digit number");
}
else{
System.out.println("number is not between 1 & 99999");

}} }

Output:

Its a four digit number


Switch:
Switch case statement is used when we have number of options (or choices) and we may
need to perform a different task for each choice.

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.

The syntax of Switch case statement looks like this –

switch(variable or an integer expression)


{
case constant:
//Java code
;
case constant:
//Java code
;
default:
//Java code
;
}

public class SwitchCaseExample1{

public static void main(String args[]){


int num=0;
switch(num+2)
{
case 1:
System.out.println("Case1: Value is: "+num);
case 2:
System.out.println("Case2: Value is: "+num);
break;
case 3:
System.out.println("Case3: Value is: "+num);
default:
System.out.println("Default: Value is: "+num);
}
}
}

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”:

// Demonstrate the while loop.


class WhileExample {
public static void main(String args[]) {
int n = 10;
while(n > 0) {
System.out.println("tick: " + n);
n--;
}
}
}

do-while :

The do-while loop always executes its body at least


once, because its conditional expression is at the bottom of the loop. Its general form is
do {
// body of loop
} while (condition);
Each iteration of the do-while loop first executes the body of the loop and then evaluates
the conditional expression. If this expression is true, the loop will repeat. Otherwise, the loop
terminates.

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.

Here is the general form of the traditional for statement:


for(initialization; condition; iteration) {
// body
}

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:

for(type itr-var : collection) statement-block

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.

// Use a for-each style for loop.


class ForEach {
public static void main(String args[]) {
int nums[] = { 56,78,120,43,90 };
int sum = 0;
// use for-each style for to display and sum the values
for(int x : nums) {
if(x>100)
break;
System.out.println("Value is: " + x);
sum += x;
}
System.out.println("Summation: " + sum);
}
}

Example2:

// Use break with a for-each style for.


class ForEach2 {
public static void main(String args[]) {
int sum = 0;
int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
// use for to display and sum the values
for(int x : nums) {
System.out.println("Value is: " + x);
sum += x;
if(x == 5) break; // stop the loop when 5 is obtained
}
System.out.println("Summation of first 5 elements: " + sum);
}
}

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.

// Using break to exit a loop.


class BreakLoop {
public static void main(String args[]) {
for(int i=0; i<100; i++) {
if(i == 10) break; // terminate loop if i is 10
System.out.println("i: " + i);
}
System.out.println("Loop complete.");
}}
Using continue

 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;

System.out.println("Before the return.");


if(t) return; // return to caller
System.out.println("This won't execute.");
}
}
The output from this program is shown here:
Before the return.

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

 A class is declared by use of the class keyword.


 A class is an entity that determines how an object will behave and what the object will
contain.
 A class is a blueprint from which individual objects are created. It represents the set of
properties or methods that are common to all objects of one type.
general form of a class definition is

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:

Box mybox = new Box(); // create a Box object called mybox

 mybox will be an instance of Box


The above statement combines the two steps just described. It can be rewritten like this to
show each step more clearly:

 Box mybox; // declare reference to object


 mybox = new Box(); // allocate a Box object
Introducing Methods
general form of a method:

type name(parameter-list)
{
// body of method
}

 type specifies the type of data returned by the method.


 This can be any valid data type, including class types that you create.
 If the method does not return a value, its return type must be void.
 The name of the method is specified by name. This can be any legal identifier other
than those already used by other items within the current scope.
 The parameter-list is a sequence of type and identifier pairs separated by commas.
Parameters are essentially variables that receive the value of the arguments passed to
the method when it is called. If the method has no parameters, then the parameter list
will be empty.

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;

Here, value is the value returned.

// This program includes a method inside the box class.


class Box
{
double width;
double height;
double depth;
// display volume of a box
void volume()
{
System.out.print("Volume is ");
System.out.println(width * height * depth);
}
}

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

// Now, volume() returns the volume of a box.


class Box
{
double width;
double height;
double depth;
// compute and return volume
double volume()
{
return width * height * depth;
}
}

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);
}
}

Adding a Method That Takes Parameters

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);

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 10 value of b is 20

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

Connecting a method call to the method body is known as binding.

There are two types of binding

1. Static Binding (also known as Early Binding).


2. Dynamic Binding (also known as Late 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.

There are two ways to overload the method in java

1. By changing number of arguments


2. By changing the data type

Example :By changing number of arguments

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));
}
}

Example: By changing the data type

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.

Program for MultiLevel Inheritance:


class Animal
{
void eat(){
System.out.println("eating...");
}
}
class Dog extends Animal{
void bark(){
System.out.println("barking...");
}
}
class BabyDog extends Dog{
void weep(){System.out.println("weeping...");}
}
classTestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();

}}
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.

Program for Hierarchical Inheritance:

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.

Accessing classes in a Built-in package in to a program :

1 ) import java.util.Vector; // import the Vector class from util package


or
2 ) import java.util.*; // import all the class from util package

 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.

javac -d Destination_folder file_name.java


How to run java package program:

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

The general form of the import statement:

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:

This code fragment shows both forms in use:

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.

 Using packagename  Using packagename.classname


//save by A.java If you import package.classname then
only declared class of this package will
package pack; be accessible.
public class A{ //save by A.java
public void msg() package pack;
{System.out.println("Hello");}
} public class A
{
//save by B.java public void msg()
{System.out.println("Hello");} }
package mypack;
import pack.*; //save by B.java

class B{ package mypack;


public static void main(String args[]){ import pack.A;

A obj = new A(); class B{


obj.msg(); public static void main(String args[]){
} } A obj = new A();
obj.msg();
}
Complile: javac –d . B.java //(Because }
MainMethod occurs at B.java)

Run: java pack.B //(Because Output:Hello


MainMethod occurs at B.java)

Output:Hello

Interfaces

Defining an Interface

 An interface is a reference type in Java. It is similar to class. It is a collection of


abstract methods.
 A class implements an interface, thereby inheriting the abstract methods of the
interface.
 The interface in Java is a mechanism to achieve abstraction.
 There can be only abstract methods in the Java interface, not method body.
 Along with abstract methods, an interface may also contain constants, default
methods, static methods, and nested types.
 Method bodies exist only for default methods and static methods.

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

 To implement an interface, include the implements Keyword in a class definition, and


then create the methods defined by the interface.

 The methods that implement an interface in a class must be declared with public
accessSpecifier.

Syntax:

classclassname[extends superclass] [implements interface[,interface...]]


{
// class-body
}

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.

Example Program on interfaces:


interface Drawable{
void draw();
}
//Implementation: by second user
class Rectangle implements Drawable{
public void draw(){System.out.println("drawing rectangle");}
}
class Circle implements Drawable{
public void draw(){System.out.println("drawing circle");}
}
//Using interface: by third user
class TestInterface1{
public static void main(String args[]){
Drawable d=new Circle();//In real scenario, object is provided by method e.g. getDrawable()
d.draw();
}}

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

for e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.

Exception:

An exception is an unwanted or unexpected event, which occurs during the execution of a


program i.e at run time that disrupts the normal flow of the program’s instructions
Types of Java Exceptions:

There are mainly two types of exceptions:

⮚ 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.

for e.g. IOException, SQLException etc.

⮚ 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

for e.g. ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc.

⮚ The java.lang package defines several classes and exceptions.


Some of these classes are unchecked while some other classes are checked.

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.

Exception Handling Keywords

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.

Throw We know that if any exception occurs, an exception object is getting


created and then Java runtime starts processing to handle them. To
manually throw an exception, use the keyword throw. The throw
keyword is mainly used to throw custom exceptions.

throws The "throws" keyword is used to declare exceptions. It doesn't throw an


exception. It specifies that there may occur an exception in the method.
It is always used with method signature.

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:

// Demonstrate multiple catch statements.


class MultiCatch {
public static void main(String args[]) {
try {

int a = args.length;

System.out.println("a = " + a);


int b = 42 / a;
int c[] = { 1 };
c[42] = 99;
}
catch(ArithmeticException e) {
System.out.println("Divide by 0: " + e);

}
catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Array index oob: " + e);
}

System.out.println("After try/catch blocks.");

}
}

Program to demonstrate all the keywords of Exception Handling

class MyException extends Exception {


public MyException(String msg){
//super(msg);
System.out.println(msg);
}
}

public class MyTest {


static void positiveNumberCheck(int n) throws MyException
{

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 thread is a single sequential flow of control within a program.

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:

● Extending the java.lang.Thread Class


● Implementing the java.lang.Runnable Interface
There are two ways to create a thread:

1. By extending Thread class


2. By implementing Runnable interface.

Example 1:

class Multi extends Thread{

public void run(){

System.out.println("thread is running...");

public static void main(String args[]){

Multi t1=new Multi();

t1.start();

Example 2: Creating Multiple Threads

class Mythread extends Thread{


Mythread(String s){
super(s);
start();
}
public void run(){
for(int i=0;i<5;i++){
System.out.println("Thread Name :"
+Thread.currentThread().getName());
try{
Thread.sleep(1000);
}catch(Exception e){}
}
}
}
public class threadmult{
public static void main(String args[]){
System.out.println("Thread Name :"
+Thread.currentThread().getName());
Mythread m1=new Mythread("My Thread 1");
Mythread m2=new Mythread("My Thread 2");
}
}
Input/Output

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.

3) public void flush()throws IOException flushes the current output 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.

3) public void close()throws is used to close the current input stream.


IOException
InputStream Hierarchy

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.

The following constructors can be used to create File objects:

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.

The following example demonstrates several of the File methods:


// Demonstrate
File. import
java.io.File;
class FileDemo {
static void p(String s) {
System.out.println(s);
}
public static void main(String args[])
{
File f1 = new
File("/java/COPYRIGHT"); p("File
Name: " + f1.getName());
p("Path: " + f1.getPath());
p("Abs Path: " + f1.getAbsolutePath());
p("Parent: " + f1.getParent());
p(f1.exists() ? "exists" : "does not exist");
p(f1.canWrite() ? "is writeable" : "is not
writeable"); p(f1.canRead() ? "is readable" : "is not
readable"); p("is " + (f1.isDirectory() ? "" : "not" +
" a directory"));
p(f1.isFile() ? "is normal file" : "might be a named
pipe"); p(f1.isAbsolute() ? "is absolute" : "is not
absolute");
p("File last modified: " + f1.lastModified());
p("File size: " + f1.length() + " Bytes");
}
}

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:

FileInputStream f0 = new FileInputStream("/input.txt") ;

File f = new File("/input.txt");


FileInputStream f1 = new FileInputStream(f);

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.

read single character


import java.io.FileInputStream;

public class DataStreamExample {

public static void main(String args[]){

try{

FileInputStream fin=new FileInputStream("D:\\testout.txt");


int i=fin.read();

System.out.print((char)i);

fin.close();

}catch(Exception e){System.out.println(e);}

Output: W

read all characters:


import java.io.FileInputStream;

public class DataStreamExample {

public static void main(String args[]){

try{

FileInputStream fin=new FileInputStream("D:\\testout.txt");

int i=0;

while((i=fin.read())!=-1){

System.out.print((char)i);

fin.close();

}catch(Exception e){System.out.println(e);}

Output: Welcome to java

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 {

public static void main(String args[]){

try{

FileOutputStream fout=new FileOutputStream("D:\\testout.txt");

fout.write(65);

fout.close();

System.out.println("success...");

}catch(Exception e){

System.out.println(e);

write string into a file with present data

import java.io.FileOutputStream;

public class writestring {

public static void main(String args[]){

try{

FileOutputStream fout=new FileOutputStream("D:\\testout.txt");

String s="Welcome to JAVA.";

byte b[]=s.getBytes();//converting string into byte array

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{

public static void main(String args[]) throws IOException{


try{
FileInputStream in=new FileInputStream("input.txt");
FileOutputStream out=new FileOutputStream("output.txt");

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.

String Handling (Exploring String class)


In Java a string is a sequence of characters.
Java implements strings as objects of Data type String.
Implementing strings as built-in objects allows Java to provide a full complement of features
that make string handling convenient.
For example,
 Java has methods to compare two strings,
 search for a substring, concatenate two strings,
 and change the case of letters within a string.
 Also, String objects can be constructed a number of ways, making it easy to obtain a
string when needed.
In java, string is basically an object that represents sequence of char values. An array of
characters works same as java string.
For example:
char[] ch={'j','a','v','a','t','p','o','i','n','t'};
String s=newString(ch);
is same as:
String s="javatpoint";
Example:
public class StringExample
{
public static void main(String args[]){
String s1="java";
char ch[]={'s','t','r','i','n','g','s'};
String s2=new String(ch);
String s3=new String("example");
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);

}}

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[]){

String s="Sachin"+" Tendulkar";


System.out.println(s);//Sachin Tendulkar
}
} Output:Sachin Tendulkar

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

public class TestSubstring


{
public static void main(String args[]){

String s="Sachin Tendulkar";


System.out.println(s.substring(6));//Tendulkar
System.out.println(s.substring(0,6));//Sachin
}
}
o/p:
Tendulkar
Sachin

String toUpperCase() and toLowerCase() method

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

Java String charAt()


The index number starts from 0 and goes to n-1, where n is length of the string. It returns
StringIndexOutOfBoundsException if given index number is greater than or equal to this
string length or a negative number.

public class CharAtExample{


public static void main(String args[]){
String name="javatpoint";
char ch=name.charAt(4);//returns the char value at the 4th index
System.out.println(ch);
}}

Output:
T

Java String compareTo()

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"
}}

You might also like