Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
4 views

Web programming

Important topics
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Web programming

Important topics
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 49

Object-Oriented PrOgramming

Object-oriented programming (OOP) is a programming paradigm based on the concept of


“objects”, which may contain data, in the form of fields, often known as attributes; and code,
in the form of procedures, often known as methods.
Abstraction
Abstraction is one of the key concepts of object-oriented programming (OOP) languages. Its
main goal is to handle complexity by hiding unnecessary details from the user. This enables
the user to implement more complex logic on top of the provided abstraction without
understanding about all the hidden complexity.
For example, people do not think of a car as a set of tens of thousands of individual parts.
They think of it as a well-defined object with its own unique behavior. This abstraction
allows people to use a car to drive to the desired location without worrying about the
complexity of the parts that form the car. They can ignore the details of how the engine,
transmission, and braking systems work. Instead, they are free to utilize the object as a whole.
A powerful way to manage abstraction is through the use of hierarchical classifications. This
allows us to layer the semantics of complex systems, breaking them into more manageable
pieces.
• Hierarchical abstractions of complex systems can also be applied to computer programs.
• The data from a traditional process-oriented program can be transformed by abstraction
into its component objects.
• A sequence of process steps can become a collection of messages between these objects.
• Thus, each of these objects describes its own unique behavior.
• We can treat these objects as concrete entities that respond to messages telling them to do
something.
Objects and classes
Object Objects have states and behaviors.
Example: A dog has states - color, name, breed as well as behaviors – wagging the tail,
barking, eating. An object is an instance of a class.
class
A class can be defined as a template/blueprint that describes the behavior/state that the object
of its type support.
Objects in java
If we consider the real-world, we can find many objects around us, cars, dogs, humans, etc.
All these objects have a state and a behavior.
If we consider a dog, then its state is - name, breed, color, and the behavior is - barking,
wagging the tail, running.
If we compare the software object with a real-world object, they have very similar
characteristics.
Software objects also have a state and a behavior. A software object’s state is stored in fields
and behavior is shown via methods.
So in software development, methods operate on the internal state of an object and the object-
to-object communication is done via methods.
classes in java
A class is a blueprint from which individual objects are created.
Following is an example of a class.
public class Dog {
String breed;
int age;
String color;
void barking()
{
}
}
A class can contain any of the following variable types.
• Local variables − Variables defined inside methods, constructors or blocks are called
local variables. The variable will be declared and initialized within the method and
the variable will be destroyed when the method has completed.
• Instance variables − Instance variables are variables within a class but outside
any method. These variables are initialized when the class is instantiated. Instance
variables can be accessed from inside any method, constructor or blocks of that
particular class.
• Class variables − Class variables are variables declared within a class, outside any
method, with the static keyword.
A class can have any number of methods to access the value of various kinds of methods.
In the above example, barking(), hungry() and sleeping() are methods.
encapsulation
Encapsulation is the mechanism that binds together code and the data it manipulates, and
keeps both safe from outside interference and misuse.
• In Java, the basis of encapsulation is the class. There are mechanisms for hiding the
complexity of the implementation inside the class.
• Each method or variable in a class may be marked private or public.
• The public interface of a class represents everything that external users of the class
need to know, or may know.
• The private methods and data can only be accessed by code that is a member of the
class.
• Therefore, any other code that is not a member of the class cannot access a private
method or variable.

• Since the private members of a class may only be accessed by other parts of program
through the class’ public methods, we can ensure that no improper actions take
place.

inheritance
Inheritance is the process by which one object acquires the properties of another object.
For example, a Dog is part of the classification Mammal, which in turn is part of the Animal
class. Without the use of hierarchies, each object would need to define all of its
characteristics explicitly. However, by use of inheritance, an object need only define those
qualities that make it unique within its class. It can inherit its general attributes from its
parent. Thus, inheritance makes it possible for one object to be a specific instance of a more
general case.

Polymorphism
Polymorphism (from Greek, meaning “many forms”) is a feature that allows one interface to
be used for a general class of actions. The specific action is determined by the exact nature of
the situation.

For eg, a dog’s sense of smell is polymorphic. If the dog smells a cat, it will bark and run
after it. If the dog smells its food, it will salivate and run to its bowl. The same sense of smell
is at work in both situations. The difference is what is being smelled, that is, the type of data
being operated upon by the dog’s nose.
Consider a stack (which is a last-in, first-out LIFO list). We might have a program that
requires three types of stacks. One stack is used for integer values, one for floating-point
values, and one for characters. The algorithm that implements each stack is the same, even
though the data being stored differs

OOP CONCEPTS IN JAVA


OOP concepts in Java are the main ideas behind Java’s Object Oriented Programming.
They are:

Object
Any entity that has state and behavior is known as an object. It can be either physical or
logical.
For example: chair, pen, table, keyboard, bike etc.

class & instance


Collection of objects of the same kind is called class. It is a logical entity.
A Class is a 3-Compartment box encapsulating data and operations as shown in figure.

A class can be visualized as a three-compartment box, as illustrated:


1. Name (or identity): identifies the class.
2. Variables (or attribute, state, field): contain the static attributes of the class.
3. Methods (or behaviors, function, operation): contain the dynamic behaviors of the class.
An instance is an instantiation of a class. All the instances of a class have similar properties,
as described in the class definition. The term “object” usually refers to instance.

For example, we can define a class called “Student” and create three instances of the class
“Student” for “John”, “Priya” and “Anil”.
The following figure shows three instances of the class Student, identified as “John”, “Priya”
and “Anil”

abstraction
Abstraction refers to the quality of dealing with ideas rather than events. It basically deals
with hiding the details and showing the essential things to the user.
We all know how to turn the TV on, but we don’t need to know how it works in order to
enjoy it.
Abstraction means simple things like objects, classes, and variables represent more complex
underlying code and data. It avoids repeating the same work multiple times. In java, we use
abstract class and interface to achieve abstraction.

abstract class:
Abstract class in Java contains the ‘abstract’ keyword. If a class is declared abstract, it cannot
be instantiated. So we cannot create an object of an abstract class. Also, an abstract class can
contain abstract as well as concrete methods.

To use an abstract class, we have to inherit it from another class where we have to provide
implementations for the abstract methods there itself, else it will also become an abstract
class.

interface:
Interface in Java is a collection of abstract methods and static constants. In an interface, each
method is public and abstract but it does not contain any constructor. Along with abstraction,
interface also helps to achieve multiple inheritance in Java.
So an interface is a group of related methods with empty bodies.
encapsulation
Binding (or wrapping) code and data together into a single unit is known as encapsulation.
It means to hide our data in order to make it safe from any modification.
The best way to understand encapsulation is to look at the example of a medical capsule,
where the drug is always safe inside the capsule. Similarly, through encapsulation the
methods and variables of a class are well hidden and safe.

A java class is the example of encapsulation.


Encapsulation can be achieved in Java by:

Declaring the variables of a class as private.


Providing public setter and getter methods to modify and view the variables values.

inheritance
This is a special feature of Object Oriented Programming in Java. It lets programmers create
new classes that share some of the attributes of existing classes.
For eg, a child inherits the properties from his father.
Similarly, in Java, there are two classes:
1. Parent class (Super or Base class)
2. Child class (Subclass or Derived class)
A class which inherits the properties is known as ‘Child class’ whereas a class whose
properties are inherited is known as ‘Parent class’.
Inheritance is classified into 4 types:

single inheritance
It enables a derived class to inherit the properties and behavior from a single parent
class.

Here, Class A is a parent class and Class B is a child class which inherits the properties
and behavior of the parent class.

multilevel inheritance
When a class is derived from a class which is also derived from another class, i.e. a class
having more than one parent class but at different levels, such type of inheritance is called
Multilevel Inheritance.

Here, class B inherits the properties and behavior of class A and class C inherits the
properties of class B. Class A is the parent class for B and class B is the parent class for C.
So, class C implicitly inherits the properties and methods of class A along with Class B.
Hierarchical inheritance
When a class has more than one child class (sub class), then such kind of inheritance is
known
as hierarchical inheritance.

Here, classes B and C are the child classes which are inheriting from the parent class A.
Hybrid inheritance
Hybrid inheritance is a combination of multiple inheritance and multilevel inheritance.
Since multiple inheritance is not supported in Java as it leads to ambiguity, this type of
inheritance can only be achieved through the use of the interfaces.

Here, class A is a parent class for classes B and C, whereas classes B and C are the parent
classes of D which is the only child class of B and C.
Polymorphism
Polymorphism means taking many forms, where ‘poly’ means many and ‘morph’ means
forms. It is the ability of a variable, function or object to take on multiple forms. In other
words, polymorphism allows us to define one interface or method and have multiple
implementations.

For eg, Bank is a base class that provides a method rate of interest. But, rate of interest
may differ according to banks. For example, SBI, ICICI and AXIS are the child classes that
provide different rates of interest.
Polymorphism in Java is of two types:
• Run time polymorphism
• Compile time polymorphism
run time polymorphism:
In Java, runtime polymorphism refers to a process in which a call to an overridden method
is resolved at runtime rather than at compile-time. Method overriding is an example of run
time polymorphism.
compile time polymorphism:
In Java, compile time polymorphism refers to a process in which a call to an overloaded
method is resolved at compile time rather than at run time. Method overloading is an example
of compile time polymorphism.

CHARACTERISTICS OF JAVA
simple :
• Java is Easy to write and more readable.
• Java has a concise, cohesive set of features that makes it easy to learn and use.
• Most of the concepts are drawn from C++, thus making Java learning simpler.

secure :
• Java program cannot harm other system thus making it secure.
• Java provides a secure means of creating Internet applications.
• Java provides secure way to access web applications.
Portable :
• Java programs can execute in any environment for which there is a Java run-time
system.
• Java programs can run on any platform (Linux, Window, Mac)
• Java programs can be transferred over world wide web (e.g applets)
Object-oriented :
• Java programming is object-oriented programming language.
• Like C++, java provides most of the object oriented features.
• Java is pure OOP Language. (while C++ is semi object oriented)
robust :
• Java encourages error-free programming by being strictly typed and performing
runtime checks.
multithreaded :
• Java provides integrated support for multithreaded programming.
architecture-neutral :
• Java is not tied to a specific machine or operating system architecture.
• Java is machine independent.
interpreted :
• Java supports cross-platform code through the use of Java bytecode.
• Bytecode can be interpreted on any platform by JVM (Java Virtual Machine).
High performance :
• Bytecodes are highly optimized.
• JVM can execute bytecodes much faster .
distributed :
• Java is designed with the distributed environment.
• Java can be transmitted over internet.

Data Types, Variables, and Arrays


Data Types in Java
Java is a statically typed and also a strongly typed language. in Java, each type of data
(such as integer, character, hexadecimal, etc. ) is predefined as part of the programming
language and all constants or variables defined within a given program must be described
with
one of the data types.
Data types represent the different values to be stored in the variable.

There are two types of Data Types in Java.

1. Primitive Data Type


2. Non-primitive Data Type

Primitive Data Type:


There are 8 primitive data types such as byte, short, int, long, float, double, char, and boolean.
Size of these 8 primitive data types wont change from one OS to other.

byte, short, int & long – stores whole numbers


float, double – stores fractional numbers
char – stores characters
boolean – stores true or false

Non-primitive Data Type:

Non-primitive data types include Classes, Interfaces and Arrays which we will learn in
coming tutorials.

Sample Program:

package classTwoVariables;

public class DataTypes {

public static void main(String[] args) {

byte byteDataType = 127;


//Change the value of byte data type to 128 and you will find an error. The range of byte is
from -128 to 128
//byte byteDataTypeNew = 128;
short shortDataType = 128;
//Change the value of byte data type to 32768 and you will find an error. The range of byte is
from -32768 to 32767
//short shortDataTypeNew = 32768;
int intDataType = 32768;
long longDataType = 2147483648L;
float floatDataType = 20.99F;
double doubleDataType = 49999999.9d;
char charDataType = ‘M’;
boolean booleanDataType = true;

System.out.println(byteDataType);
System.out.println(shortDataType);
System.out.println(intDataType);
System.out.println(longDataType);
System.out.println(floatDataType);
System.out.println(doubleDataType);
System.out.println(charDataType);
System.out.println(booleanDataType);
}
}
Output:

127
128
32768
2147483648
20.99
4.99999999E7
M
True

VARIABLES
A variable is the holder that can hold the value while the java program is executed. A variable
is assigned with a datatype. It is name of reserved area allocated in memory. In other words,
it is a name of memory location. There are three types of variables in java: local, instance and
static.
A variable provides us with named storage that our programs can manipulate. Each variable
in Java has a specific type, which determines the size and layout of the variable’s memory;
the range of values that can be stored within that memory; and the set of operations that can
be applied to the variable.

Before using any variable, it must be declared. The following statement expresses the
basic form of a variable declaration –
datatype variable [ = value][, variable [ = value] ...] ;
Here data type is one of Java’s data types and variable is the name of the variable. To declare
more than one variable of the specified type, use a comma-separated list.
Example
int a, b, c; // Declaration of variables a, b, and c.
int a = 20, b = 30; // initialization
byte B = 22; // Declaratrion initializes a byte type variable B.
Types of Variable
There are three types of variables in java:
• local variable
• instance variable
• static variable

Local variable
• Local variables are declared inside the methods, constructors, or blocks.
• Local variables are created when the method, constructor or block is entered
• Local variable will be destroyed once it exits the method, constructor, or block.
• Local variables are visible only within the declared method, constructor, or block.
• Local variables are implemented at stack level internally.
• There is no default value for local variables, so local variables should be declared and
an initial value should be assigned before the first use.
• Access specifiers cannot be used for local variables.

instance variable
• A variable declared inside the class but outside the method, is called instance
variable.
Instance variables are declared in a class, but outside a method, constructor or any
block.
• A slot for each instance variable value is created when a space is allocated for an
object in the heap.
• Instance variables are created when an object is created with the use of the keyword
‘new’ and destroyed when the object is destroyed.
• Instance variables hold values that must be referenced by more than one method,
constructor or block, or essential parts of an object’s state that must be present
throughout the class.
• Instance variables can be declared in class level before or after use.
• Access modifiers can be given for instance variables.
• The instance variables are visible for all methods, constructors and block in the
class. It is recommended to make these variables as private. However, visibility for
subclasses can be given for these variables with the use of access modifiers.
• Instance variables have default values.
○ numbers, the default value is 0,
○ Booleans it is false,
○ Object references it is null.
• Values can be assigned during the declaration or within the constructor.
• Instance variables cannot be declared as static.

Instance variables can be accessed directly by calling the variable name inside the class.
However, within static methods (when instance variables are given accessibility), they
should be called using the fully qualified name. ObjectReference.VariableName.

static variable
• Class variables also known as static variables are declared with the static keyword in
a class, but outside a method, constructor or a block.
• Only one copy of each class variable per class is created, regardless of how many
objects are created from it.
• Static variables are rarely used other than being declared as constants. Constants are
variables that are declared as public/private, final, and static. Constant variables never
change from their initial value.

Static variables are stored in the static memory. It is rare to use static variables other
than declared final and used as either public or private constants.
• Static variables are created when the program starts and destroyed when the program
stops.
• Visibility is same as instance variables. However, most static variables are declared
public since they must be available for users of the class.
• Default values are same as instance variables.
○ numbers, the default value is 0;
○ Booleans, it is false;
○ Object references, it is null.
• Values can be assigned during the declaration or within the constructor. Additionally,
values can be assigned in special static initializer blocks.
• Static variables cannot be local.
• Static variables can be accessed by calling with the class name ClassName.
VariableName.
• When declaring class variables as public static final, then variable names (constants)
are all in upper case. If the static variables are not public and final, the naming syntax
is the same as instance and local variables.

Java array is an object which contains elements of a similar data type. Additionally, The
elements of an array are stored in a contiguous memory location. It is a data structure where
we store similar elements. We can store only a fixed set of elements in a Java array.

Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd
element is stored on 1st index and so on.

In Java, array is an object of a dynamically generated class. Java array inherits the Object
class, and implements the Serializable as well as Cloneable interfaces. We can store primitive
values or objects in an array in Java

Advantages
o Code Optimization: It makes the code optimized, we can retrieve or sort
the data efficiently.
o Random access: We can get any data located at an index position.

Disadvantages
o Size Limit: We can store only the fixed size of elements in the array. It
doesn't grow its size at runtime. To solve this problem, collection
framework is used in Java which grows automatically.
Types of Array in java
There are two types of array.

o Single Dimensional Array


o Multidimensional Array

Single Dimensional Array in Java


Syntax to Declare an Array in Java

1. dataType[] arr; (or)


2. dataType []arr; (or)
3. dataType arr[];

Instantiation of an Array in Java

arrayRefVar=new datatype[size];
Example of Java Array
Let's see the simple example of java array, where we are going to declare,
instantiate, initialize and traverse an array.

//Java Program to illustrate how to declare, instantiate, initialize


//and traverse the Java array.
class Testarray{
public static void main(String args[]){
int a[]=new int[5];//declaration and instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//traversing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}}
Output:

10
20
70
40
50

Declaration, Instantiation and Initialization of Java


Array
We can declare, instantiate and initialize the java array together by:

int a[]={33,3,4,5};//declaration, instantiation and initialization

OPERATORS
Operator in java is a symbol that is used to perform operations. Java
provides a rich set
of operators to manipulate variables.For example: +, -, *, / etc.
All the Java operators can be divided into the following groups −
• Arithmetic Operators :
Multiplicative : * / %
Additive : + -
• Relational Operators
Comparison : < > <= >= instanceof
Equality : == !=
• Bitwise Operators
bitwise AND : &
bitwise exclusive OR : ^
bitwise inclusive OR : |
Shift operator: << >> >>>

• Logical Operators
logical AND : &&
logical OR : ||
logical NOT : ~ !
• Assignment Operators: =
• Ternary operator: ? :
• Unary operator
Postfix : expr++ expr—
Prefix : ++expr --expr +expr –expr

the arithmetic Operators


Arithmetic operators are used to perform arithmetic operations in the same way as they
are used in algebra. The following table lists the arithmetic operators −
Example:
int A=10,B=20;

// Java program to illustrate arithmetic operators


public class Aoperators
{
public static void main(String[] args)
{
int a = 20, b = 10, c = 0, d = 20, e = 40, f = 30;
String x = “Thank”, y = “You”;
System.out.println(“a + b = “+(a + b));
System.out.println(“a - b = “+(a - b));
System.out.println(“x + y = “+x + y);
System.out.println(“a * b = “+(a * b));
System.out.println(“a / b = “+(a / b));
System.out.println(“a % b = “+(a % b));
}
}

the relational Operators


The following relational operators are supported by Java language.
Example:
int A=10,B=20;

// Java program to illustrate relational operators


public class operators
{
public static void main(String[] args)
{
int a = 20, b = 10;
boolean condition = true;
//various conditional operators
System.out.println(“a == b :” + (a == b));
System.out.println(“a < b :” + (a < b));
System.out.println(“a <= b :” + (a <= b));
System.out.println(“a > b :” + (a > b));
System.out.println(“a >= b :” + (a >= b));
System.out.println(“a != b :” + (a != b));
System.out.println(“condition==true :” + (condition == true));
}
}
bitwise Operators
Java supports several bitwise operators, that can be applied to the integer types, long, int,
short, char, and byte. Bitwise operator works on bits and performs bit-by-bit operation.
Example:
int a = 60,b = 13;
binary format of a & b will be as follows −
a = 0011 1100
b = 0000 1101

// Java program to illustrate bitwise operators


public class operators
{
public static void main(String[] args)
{
int a = 10;
int b = 20;
System.out.println(“a&b = “ + (a & b));
System.out.println(“a|b = “ + (a | b));
System.out.println(“a^b = “ + (a ^ b));
System.out.println(“~a = “ + ~a);
}
}

Logical Operators
The following are the logical operators supported by java.
Example:
A=true;
B=false;

assignment Operators
The following are the assignment operators supported by Java

// Java program to illustrate assignment operators


public class operators
{
public static void main(String[] args)
{
int a = 20, b = 10, c, d, e = 10, f = 4, g = 9;
c = b;
System.out.println(“Value of c = “ + c);
a += 1;

b -= 1;
e *= 2;
f /= 2;
System.out.println(“a, b, e, f = “ +
a + “,” + b + “,” + e + “,” + f);
}
}
ternary Operator
Conditional Operator ( ? : )
Since the conditional operator has three operands, it is referred as the ternary operator.
This operator consists of three operands and is used to evaluate Boolean expressions. The
goal of the operator is to decide, which value should be assigned to the variable. The operator
is written as –
variable x = (expression) ? value if true : value if false
Following is an example −
Example:
public class example
{
public static void main(String args[])
{
int a, b;
a = 10;
b = (a == 0) ? 20: 30;
System.out.println( “b : “ + b );
}
}
unary Operators
Unary operators use only one operand. They are used to increment, decrement or negate
a value.

// Java program to illustrate unary operators


public class operators
{
public static void main(String[] args)
{
int a = 20, b = 10, c = 0, d = 20, e = 40, f = 30;
boolean condition = true;
c = ++a;
System.out.println(“Value of c (++a) = “ + c);
c = b++;
System.out.println(“Value of c (b++) = “ + c);
c = --d;
System.out.println(“Value of c (--d) = “ + c);
c = --e;
System.out.println(“Value of c (--e) = “ + c);
System.out.println(“Value of !condition =” + !condition);
}
}

CONTROL FLOW
Java Control statements control the flow of execution in a java program, based on data values
and conditional logic used. There are three main categories of control flow statements;

Selection statements: if, if-else and switch.


Loop statements: while, do-while and for.
Transfer statements: break, continue, return, try-catch-finally and assert

selection statements
The selection statements checks the condition only once for the program execution.

if statement:
The if statement executes a block of code only if the specified expression is true. If the
value is false, then the if block is skipped and execution continues with the rest of the
program.
The simple if statement has the following syntax:
if (<conditional expression>)
<statement action>
The following program explains the if statement.
public class programIF{
public static void main(String[] args)
{
int a = 10, b = 20;
if (a > b)
System.out.println(“a > b”);
if (a < b)
System.out.println(“b < a”);
}
}

the if-else statement


The if/else statement is an extension of the if statement. If the condition in the if statement
fails, the statements in the else block are executed. The if-else statement has the following
syntax:
if (<conditional expression>)
<statement action>
else
<statement action>
The following program explains the if-else statement.
public class ProgramIfElse
{
public static void main(String[] args)
{
int a = 10, b = 20;
if (a > b)
{
System.out.println(“a > b”);
}
else
{
System.out.println(“b < a”);
}
}
}
switch case statement
The switch case statement is also called as multi-way branching statement with several
choices. A switch statement is easier to implement than a series of if/else statements. The
switch statement begins with a keyword, followed by an expression that equates to a no long
integral value.

After the controlling expression, there is a code block that contains zero or more labeled
cases. Each label must equate to an integer constant and each must be unique. When the
switch statement executes, it compares the value of the controlling expression to the values
of each case label.
The program will select the value of the case label that equals the value of the controlling
expression and branch down that path to the end of the code block. If none of the case
label values match, then none of the codes within the switch statement code block will be
executed.
Java includes a default label to use in cases where there are no matches. A nested switch
within a case block of an outer switch is also allowed. When executing a switch statement,
the flow of the program falls through to the next case. So, after every case, you must insert a
break statement.

The syntax of switch case is given as follows:


switch (<non-long integral expression>) {
case label1
: <statement1>
case label2
: <statement2>

case labeln
: <statementn>
default: <statement>
} // end switch
The following program explains the switch statement.
public class ProgramSwitch
{
public static void main(String[] args)
{
int a = 10, b = 20, c = 30;
int status = -1;
if (a > b && a > c)
{
status = 1;
}
else if (b > c)
{
status = 2;
}
else
{
status = 3;
}
switch (status)
{
case 1:System.out.println(“a is the greatest”);

break;
case 2:System.out.println(“b is the greatest”);
break;
case 3:System.out.println(“c is the greatest”);
break;
default:System.out.println(“Cannot be determined”);
}
}
}
iteration statements
Iteration statements execute a block of code for several numbers of times until the condition
is true.

While statement
The while statement is one of the looping constructs control statement that executes a
block of code while a condition is true. The loop will stop the execution if the testing
expression evaluates to false. The loop condition must be a boolean expression. The syntax of
the
while loop is
while (<loop condition>)
<statements>

The following program explains the while statement.


public class ProgramWhile
{
public static void main(String[] args)
{
int count = 1;
System.out.println(“Printing Numbers from 1 to 10”);
while (count <= 10)
{
System.out.println(count++);}
}
}
}
do-while Loop statement
The do-while loop is similar to the while loop, except that the test condition is performed
at the end of the loop instead of at the beginning. The do—while loop executes atleast once
without checking the condition.
It begins with the keyword do, followed by the statements that making up the body of the
loop. Finally, the keyword while and the test expression completes the do-while loop. When
the loop condition becomes false, the loop is terminated and execution continues with the
statement immediately following the loop.

The syntax of the do-while loop is


do
<loop body>
while (<loop condition>);
The following program explains the do--while statement.
public class DoWhileLoopDemo {
public static void main(String[] args) {
int count = 1;
System.out.println(“Printing Numbers from 1 to 10”);
do {
System.out.println(count++);
} while (count <= 10);
}
}

for Loop
The for loop is a looping construct which can execute a set of instructions for a specified
number of times. It’s a counter controlled loop.

The syntax of the loop is as follows:

for (<initialization>; <loop condition>; <increment expression>)


<loop body>

• initialization statement executes once before the loop begins. The <initialization>
section can also be a comma-separated list of expression statements.
• test expression. As long as the expression is true, the loop will continue. If this
expression is evaluated as false the first time, the loop will never be executed.

• Increment(Update) expression that automatically executes after each repetition of the


loop body.
• All the sections in the for-header are optional. Any one of them can be left empty, but
the two semicolons are mandatory.
The following program explains the for statement.
public class ProgramFor {
public static void main(String[] args) {
System.out.println(“Printing Numbers from 1 to 10”);
for (int count = 1; count <= 10; count++) {
System.out.println(count);
}
}
}
transfer statements
Transfer statements are used to transfer the flow of execution from one statement to another.

continue statement
A continue statement stops the current iteration of a loop (while, do or for) and causes
execution to resume at the top of the nearest enclosing loop. The continue statement can be
used when you do not want to execute the remaining statements in the loop, but you do not
want to exit the loop itself.
The syntax of the continue statement is

continue; // the unlabeled form


continue <label>; // the labeled form

It is possible to use a loop with a label and then use the label in the continue statement.
The label name is optional, and is usually only used when you wish to return to the outermost
loop in a series of nested loops.

The following program explains the continue statement.


public class ProgramContinue
{
public static void main(String[] args) {
System.out.println(“Odd Numbers”);
for (int i = 1; i <= 10; ++i) {
if (i % 2 == 0)
continue;
System.out.println(i + “\t”);
}
}
}
break statement
The break statement terminates the enclosing loop (for, while, do or switch statement).
Break statement can be used when we want to jump immediately to the statement following
the enclosing control structure. As continue statement, can also provide a loop with a label,
and then use the label in break statement. The label name is optional, and is usually only used
when you wish to terminate the outermost loop in a series of nested loops.

The Syntax for break statement is as shown below;


break; // the unlabeled form
break <label>; // the labeled form

The following program explains the break statement.


public class ProgramBreak {
public static void main(String[] args) {
System.out.println(“Numbers 1 - 10”);
for (int i = 1;; ++i) {
if (i == 11)
break;
// Rest of loop body skipped when i is even
System.out.println(i + “\t”);
}
}
}

What is a class in Java


A class is a group of objects which have common properties. It is a
template or blueprint from which objects are created. It is a logical entity.
It can't be physical.

A class in Java can contain:

o Fields
o Methods
o Constructors
o Blocks
o Nested class and interface

Syntax to declare a class:


1. class <class_name>{
2. field;
3. method;
4. }

Instance variable in Java


A variable which is created inside the class but outside the method is
known as an instance variable. Instance variable doesn't get memory at
compile time. It gets memory at runtime when an object or instance is
created. That is why it is known as an instance variable.
Method in Java
In Java, a method is like a function which is used to expose the behavior of
an object.

Advantage of Method
o Code Reusability
o Code Optimization

new keyword in Java


The new keyword is used to allocate memory at runtime. All objects get
memory in Heap memory area.

Object and Class Example: main within the class


In this example, we have created a Student class which has two data
members id and name. We are creating the object of the Student class by
new keyword and printing the object's value.

Here, we are creating a main() method inside the class.

//Java Program to illustrate how to define a class and fields


//Defining a Student class.
class Student{
//defining fields
int id;//field or data member or instance variable
String name;
//creating main method inside the Student class
public static void main(String args[]){
//Creating an object or instance
Student s1=new Student();//creating an object of Student
//Printing values of the object
System.out.println(s1.id);//accessing member through reference varia
ble
System.out.println(s1.name);
}
}
Output:

0
null

advantages of methods
• Program development and debugging are easier
• Increases code sharing and code reusability
• Increases program readability
• It makes program modular and easy to understanding
• It shortens the program length by reducing code redundancy
types of methods
There are two types of methods in Java programming:
• Standard library methods (built-in methods or predefined methods)
• User defined methods
standard library methods
The standard library methods are built-in methods in Java
programming to handle tasks
such as mathematical computations, I/O processing, graphics, string
handling etc. These methods are already defined and come along with
Java class libraries, organized in packages.
In order to use built-in methods, we must import the corresponding
packages
java.lang.Math
All maths related methods are defined in this class
acos()
exp()
abs()
log()
sqrt()
pow()

java.lang.String
All string related methods are defined in this class
charAt()
concat()
compareTo()
indexOf()
toUpperCase()

java.awt
contains classes for
graphics
add()
setSize()
setLayout()
setVisible()

Example:
Program to compute square root of a given number using built-in
method.
public class MathEx {
public static void main(String[] args) {
System.out.print(“Square root of 14 is: “ + Math.sqrt(14));
}
}
Sample Output:
Square root of 14 is: 3.7416573867739413

user-defined methods
The methods created by user are called user defined methods.
Every method has the following.
• Method declaration (also called as method signature or method
prototype)
• Method definition (body of the method)
• Method call (invoke/activate the method)
method declaration
The syntax of method declaration is:
Syntax:
return_type method_name(parameter_list);
Here, the return_type specifies the data type of the value returned by
method. It will be void if the method returns nothing. method_name
indicates the unique name assigned to the method. parameter_list
specifies the list of values accepted by the method.
method Definition
Method definition provides the actual body of the method. The
instructions to complete a specific task are written in method
definition. The syntax of method is as follows:
Syntax:
modifier return_type method_name(parameter_list){
// body of the method
}
Here,
Modifier – Defines the access type of the method i.e accessibility region
of method in the application
return_type – Data type of the value returned by the method or void if
method returns nothing
method_name – Unique name to identify the method. The name must
follow
the rules of identifier
parameter_list – List of input parameters separated by comma. It must
be
like
datatype parameter1,datatype parameter2,……
List will be empty () in case of no input parameters.
method body – block of code enclosed within { and } braces to perform
specific task

The first line of the method definition must match exactly with the
method prototype. A
method cannot be defined inside another method.
method call
A method gets executed only when it is called. The syntax for method
call is.
syntax:
method_name(parameters);
When a method is called, the program control transfers to the method
definition where the actual code gets executed and returns back to the
calling point. The number and type of parameters passed in method
call should match exactly with the parameter list mentioned in method
prototype.
Inheritance in Java
Inheritance in Java is a mechanism in which one object acquires all the
properties and behaviors of a parent object. It is an important part
of OOPs (Object Oriented programming system).

Inheritance represents the IS-A relationship which is also known as


a parent-child relationship.

Syntax:
class Subclass-name extends Superclass-name
{
//methods and fields
}

advantages of Inheritance:
• Code reusability - public methods of base class can be reused in
derived classes
• Data hiding – private data of base class cannot be altered by
derived class
• Overriding--With inheritance, we will be able to override the
methods of the baseclass in the derived class

Example:
// Create a superclass.
class BaseClass{
int a=10,b=20;
public void add(){
System.out.println(“Sum:”+(a+b));

}
// Create a subclass by extending class BaseClass.
public class Main extends BaseClass
{
public void sub(){
System.out.println(“Difference:”+(a-b));
}
public static void main(String[] args) {
Main obj=new Main();
/*The subclass has access to all public members of its superclass*/
obj.add();
obj.sub();
}
}
Sample Output:
Sum:30
Difference:-10

types of inheritance
Single Inheritance :
In single inheritance, a subclass inherit the features of one superclass.
example:
class Shape{
int a=10,b=20;
}
class Rectangle extends Shape{
public void rectArea(){
System.out.println(“Rectangle Area:”+(a*b));
}
}
public class Main
{
public static void main(String[] args) {
Rectangle obj=new Rectangle();
obj.rectArea();
}
}
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 i.e. a derived class in turn acts as a base
class for another class.

Example:
class Numbers{
int a=10,b=20;
}
class Add2 extends Numbers{
int c=30;
public void sum2(){
System.out.println(“Sum of 2 nos.:”+(a+b));
}
}
class Add3 extends Add2{
public void sum3(){
System.out.println(“Sum of 3 nos.:”+(a+b+c));
}
}
public class Main
{
public static void main(String[] args) {
Add3 obj=new Add3();
obj.sum2();
obj.sum3();
}
}
Sample Output:
Sum of 2 nos.:30
Sum of 3 nos.:60

hierarchical Inheritance:
In Hierarchical Inheritance, one class serves as a superclass (base class) for more than
one sub class.

Example:
class Shape{
int a=10,b=20;
}
class Rectangle extends Shape{
public void rectArea(){
System.out.println(“Rectangle Area:”+(a*b));
}
}
class Triangle extends Shape{
public void triArea(){
System.out.println(“Triangle Area:”+(0.5*a*b));
}
}
public class Main
{
public static void main(String[] args) {
Rectangle obj=new Rectangle();
obj.rectArea();
Triangle obj1=new Triangle();
obj1.triArea();
}
}
Sample Output:
Rectangle Area:200
Triangle Area:100.0
Multiple inheritance
Java does not allow multiple inheritance:
• To reduce the complexity and simplify the language
• To avoid the ambiguity caused by multiple inheritance

For example, Consider a class C derived from two base classes A and B. Class C inherits
A and B features. If A and B have a method with same signature, there will be ambiguity to
call method of A or B class. It will result in compile time error.
class A{
void msg(){System.out.println(“Class A”);}
}
class B{
void msg(){System.out.println(“Class B “);}
}
class C extends A,B{//suppose if it were
Public Static void main(String args[]){
C obj=new C();
obj.msg();//Now which msg() method would be invoked?
}
}
Sample Output:
Compile time error

access control in Inheritance


The following rules for inherited methods are enforced −
• Variables declared public or protected in a superclass are inheritable in subclasses.
• Variables or Methods declared private in a superclass are not inherited at all.
• Methods declared public in a superclass also must be public in all subclasses.
• Methods declared protected in a superclass must either be protected or public in
subclasses; they cannot be private.
Example:
// Create a superclass
class A{
int x; // default specifier
private int y; // private to A
public void set_xy(int a,int b){
x=a;
y=b;
}
}
// A’s y is not accessible here.
class B extends A{
public void add(){
System.out.println(“Sum:”+(x+y)); //Error: y has private access in A – not inheritable
}
}
class Main{
public static void main(String args[]){
B obj=new B();
obj.set_xy(10,20);
obj.add();
}
}
In this example since y is declared as private, it is only accessible by its own class members.
Subclasses have no access to it.
Java Package

A java package is a group of similar types of classes, interfaces and sub-


packages.

Package in java can be categorized in two form, built-in package and user-
defined package.

There are many built-in packages such as java, lang, awt, javax, swing,
net, io, util, sql etc.

Advantage of Java Package

1) Java package is used to categorize the classes and interfaces so that


they can be easily maintained.

2) Java package provides access protection.

3) Java package removes naming collision.

Simple example of java package


The package keyword is used to create a package in java.
1. //save as Simple.java
2. package mypack;
3. public class Simple{
4. public static void main(String args[]){
5. System.out.println("Welcome to package");
6. }
7. }

How to compile java package

If you are not using any IDE, you need to follow the syntax given below:

javac -d directory javafilename


To Compile: javac -d . Simple.java
To Run: java mypack.Simple
Output:Welcome to package

How to access package from another package?


There are three ways to access the package from outside the package.

1. import package.*;
2. import package.classname;
3. fully qualified name.

Example of package that import the packagename.*

1. //save by A.java
2. package pack;
3. public class A{
4. public void msg(){System.out.println("Hello");}
5. }
1. //save by B.java
2. package mypack;
3. import pack.*;
4.
5. class B{
6. public static void main(String args[]){
7. A obj = new A();
8. obj.msg();
9. }
10. }
Output:Hello

Interfaces

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


collection of abstract

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

An interface is similar to a class in the following ways:

• An interface can contain any number of methods.

• An interface is written in a file with a .java extension, with the name


of the interface

matching the name of the file.

• The byte code of an interface appears in a .class file.

• Interfaces appear in packages, and their corresponding bytecode


file must be in a

directory structure that matches the package name.

Uses of interface:

• Since java does not support multiple inheritance in case of class, it


can be achieved

by using interface.

• It is also used to achieve loose coupling.

• Interfaces are used to implement abstraction.


Defining an Interface An interface is defined much like a class.

Syntax:

accessspecifier interface interfacename

return-type method-name1(parameter-list);

return-type method-name2(parameter-list);

type final-varname1 = value;

type final-varname2 = value;

// ...

return-type method-nameN(parameter-list);

type final-varnameN = value;

• The java file must have the same name as the interface.

• The methods that are declared have no bodies. They end with a semicolon after the

parameter list. They are abstract methods; there can be no default implementation of any
method specified within an interface.

• Each class that includes an interface must implement all of the methods.

• Variables can be declared inside of interface declarations. They are implicitly final

and static, meaning they cannot be changed by the implementing class. They must also be
initialized.

• All methods and variables are implicitly public

Sample Code:

The following code declares a simple interface Animal that contains two methods called

eat() and travel() that take no parameter.

/* File name : Animal.java */


interface Animal {

public void eat();

public void travel();

Implementing an Interface

Once an interface has been defined, one or more classes can implement that interface. To

implement an interface, the ‘implements’ clause is included in a class definition and then the

methods defined by the interface are created.

Syntax:

class classname [extends superclass] [implements interface [,interface...]]

// class-body

properties of java interface

• If a class implements more than one interface, the interfaces are separated with a

comma.

• If a class implements two interfaces that declare the same method, then the same

method will be used by clients of either interface.

• The methods that implement an interface must be declared public.

• The type signature of the implementing method must match exactly the type
signature

specified in the interface definition.

rules

• A class can implement more than one interface at a time.

• A class can extend only one class, but can implement many interfaces.

• An interface can extend another interface, in a similar way as a class can extend
another class.

Sample Code 1:

The following code implements an interface Animal shown earlier.

/* File name : MammalInt.java */

public class Mammal implements Animal

public void eat()

System.out.println(“Mammal eats”);

public void travel()

System.out.println(“Mammal travels”);

public int noOfLegs()

return 0;

public static void main(String args[])

Mammal m = new Mammal();

m.eat();

m.travel();

}
Output:

Mammal eats

Mammal travels

Exception Handling in Java


The Exception Handling in Java is one of the powerful mechanism to
handle the runtime errors so that the normal flow of the application can
be maintained

What is Exception in Java?


Dictionary Meaning: Exception is an abnormal condition.

In Java, an exception is an event that disrupts the normal flow of the


program. It is an object which is thrown at runtime.

What is Exception Handling?


Exception Handling is a mechanism to handle runtime errors such as
ClassNotFoundException, IOException, SQLException, RemoteException,
etc.

Advantage of Exception Handling

The core advantage of exception handling is to maintain the normal


flow of the application. An exception normally disrupts the normal flow
of the application; that is why we need to handle exceptions. Let's
consider a scenario:

1. statement 1;
2. statement 2;
3. statement 3;
4. statement 4;
5. statement 5;//exception occurs
6. statement 6;
7. statement 7;
8. statement 8;
9. statement 9;
10. statement 10;
Suppose there are 10 statements in a Java program and an exception
occurs at statement 5; the rest of the code will not be executed, i.e.,
statements 6 to 10 will not be executed. However, when we perform
exception handling, the rest of the statements will be executed. That is
why we use exception handling in Java.

Hierarchy of Java Exception classes


The java.lang.Throwable class is the root class of Java Exception hierarchy
inherited by two subclasses: Exception and Error. The hierarchy of Java
Exception classes is given below:

Types of Java Exceptions


There are mainly two types of exceptions: checked and unchecked. An
error is considered as the unchecked exception. However, according to
Oracle, there are three types of exceptions namely:
1. Checked Exception
2. Unchecked Exception
3. Error

Difference between Checked and Unchecked


Exceptions
1) Checked Exception

The classes that directly inherit the Throwable class except


RuntimeException and Error are known as checked exceptions. For
example, IOException, SQLException, etc. Checked exceptions are
checked at compile-time.

2) Unchecked Exception

The classes that inherit the RuntimeException are known as unchecked


exceptions. For example, ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException, etc. Unchecked exceptions are not
checked at compile-time, but they are checked at runtime.

3) Error

Error is irrecoverable. Some example of errors are OutOfMemoryError,


VirtualMachineError, AssertionError etc.

Java Exception Keywords


Java provides five keywords that are used to handle the exception. The following table
describes each.

Keyword Description

try The "try" keyword is used to specify a block where we should place an
exception code. It means we can't use try block alone. The try block must be
followed by either catch or finally.

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 necessary code of the program. It is
executed whether an exception is handled or not.
throw The "throw" keyword is used to throw an exception.

throws The "throws" keyword is used to declare exceptions. It specifies that there may
occur an exception in the method. It doesn't throw an exception. It is always
used with method signature.

Java Exception Handling Example


Let's see an example of Java Exception Handling in which we are using a
try-catch statement to handle the exception.

JavaExceptionExample.java

1. public class JavaExceptionExample{


2. public static void main(String args[]){
3. try{
4. //code that may raise exception
5. int data=100/0;
6. }catch(ArithmeticException e){System.out.println(e);}
7. //rest code of the program
8. System.out.println("rest of the code...");
9. }
10. }
11. Output:
12. Exception in thread main java.lang.ArithmeticException:/ by zero
13. rest of the code...

here are given some scenarios where unchecked exceptions may occur. They are as follows:

1) A scenario where ArithmeticException occurs

If we divide any number by zero, there occurs an ArithmeticException.

1. int a=50/0;//ArithmeticException
2) A scenario where NullPointerException occurs

If we have a null value in any variable, performing any operation on the


variable throws a NullPointerException.

1. String s=null;
2. System.out.println(s.length());//NullPointerException
A scenario where NumberFormatException occurs
1. String s="abc";
2. int i=Integer.parseInt(s);//NumberFormatException
A scenario where ArrayIndexOutOfBoundsException occurs
1. int a[]=new int[5];
2. a[10]=50; //ArrayIndexOutOfBoundsException

Multithreading in Java

Multithreading in Java is a process of executing multiple threads


simultaneously.

A thread is a lightweight sub-process, the smallest unit of processing.


Multiprocessing and multithreading, both are used to achieve
multitasking.

Advantages of Java Multithreading


1) It doesn't block the user because threads are independent and you
can perform multiple operations at the same time.

2) You can perform many operations together, so it saves time.

3) Threads are independent, so it doesn't affect other threads if an


exception occurs in a single thread.

Multitasking
Multitasking is a process of executing multiple tasks simultaneously. We
use multitasking to utilize the CPU. Multitasking can be achieved in two
ways:

o Process-based Multitasking (Multiprocessing)


o Thread-based Multitasking (Multithreading)

1) Process-based Multitasking (Multiprocessing)


o Each process has an address in memory. In other words, each process
allocates a separate memory area.
o A process is heavyweight.
o Cost of communication between the process is high.
o Switching from one process to another requires some time for saving and
loading registers, memory maps, updating lists, etc.
2) Thread-based Multitasking (Multithreading)
o Threads share the same address space.
o A thread is lightweight.
o Cost of communication between the thread is low.
o What is Thread in java
o A thread is a lightweight subprocess, the smallest unit of processing.
It is a separate path of execution.
o Threads are independent. If there occurs exception in one thread, it
doesn't affect other threads. It uses a shared memory area.

Java Thread class


Java provides Thread class to achieve thread programming. Thread class
provides constructors and methods to create and perform operations on a
thread. Thread class extends Object class and implements Runnable
interface.
// Java code for thread creation by extending
// the Thread class
class MultithreadingDemo extends Thread {
public void run()
{
try {
// Displaying the thread that is running
System.out.println(
"Thread " + Thread.currentThread().getId()
+ " is running");
}
catch (Exception e) {
// Throwing an exception
System.out.println("Exception is caught");
}
}
}

// Main Class
public class Multithread {
public static void main(String[] args)
{
int n = 8; // Number of threads
for (int i = 0; i < n; i++) {
MultithreadingDemo object
= new MultithreadingDemo();
object.start();
}
}
}
Output
Thread 15 is running
Thread 14 is running
Thread 16 is running
Thread 12 is running
Thread 11 is running
Thread 13 is running
Thread 18 is running
Thread 17 is running

Java I/O Tutorial


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.

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.

System.out.println("simple message");
System.err.println("error message");

int i=System.in.read();//returns ASCII code of 1st character


System.out.println((char)i);//will print the character

Java FileOutputStream Example 1: write byte


1. import java.io.FileOutputStream;
2. public class FileOutputStreamExample {
3. public static void main(String args[]){
4. try{
5. FileOutputStream fout=new FileOutputStream("D:\\testout.txt");
6. fout.write(65);
7. fout.close();
8. System.out.println("success...");
9. }catch(Exception e){System.out.println(e);}
10. }
11. }

Output:

Success...
The content of a text file testout.txt is set with the data A.

testout.txt

works same as Java string. For example:

1. char[] ch={'j','a','v','a','t','p','o','i','n','t'};
2. String s=new String(ch);

is same as:

1. String s="javatpoint";

Java String class provides a lot of methods to perform operations on


strings such as compare(), concat(), equals(), split(), length(), replace(),
compareTo(), intern(), substring() etc.

The java.lang.String class implements Serializable, Comparable and


CharSequence interfaces.

What is String in Java?


Generally, String is a sequence of characters. But in Java, string is an
object that represents a sequence of characters. The java.lang.String class
is used to create a string object.

How to create a string object?


There are two ways to create String object:

1. By string literal
2. By new keyword

1) String Literal
Java String literal is created by using double quotes. For Example:

1. String s="welcome";
By new keyword
1. String s=new String("Welcome");//creates two objects and one reference
variable

Java String Example


StringExample.java

1. public class StringExample{


2. public static void main(String args[]){
3. String s1="java";//creating string by Java string literal
4. char ch[]={'s','t','r','i','n','g','s'};
5. String s2=new String(ch);//converting char array to string
6. String s3=new String("example");//creating Java string by new keyword
7. System.out.println(s1);
8. System.out.println(s2);
9. System.out.println(s3);
10. }}

Output:

java
strings
example

You might also like