Java_CH_1
Java_CH_1
CH 1
Introduction to programming paradigm
In layman's terms, programming paradigms are a fundamental style of
computer programming.
In technical terms, a programming paradigm is a way to deal with tackle
issues utilizing some programming language. Additionally, we can say that
it is a strategy to take care of an issue using tools and techniques that are
accessible to us following some methodology.
It differs in the concepts and methods that are used to represent the
elements (such as objects, variables, functions, and constraints) of a
program. And the steps that involve a calculation (like assignations,
evaluation, continuations, and data flows). The lowest programming
paradigm is machine code.
There are lots of things for programming languages that are known.
However, every one of them needs to follow some procedure when they
are executed and this approach/methodology is a paradigm.
1
A) Imperative Programming Paradigm
Advantages
o Easy to implement.
o It contains loops, variables, etc.
o It is efficient.
Disadvantages
o We cannot choose it for solving complex problems.
o It is less efficient and less productive.
o It is not suitable for parallel programming.
o Order is crucial.
o Object-oriented Programming
o Procedural Programming
o Parallel Processing Approach
Object-oriented Programming
Since objects work independently, they are encapsulated into modules. we can
communicate with an object by using message passing.
The paradigm deals with procedure calls that are called routines or functions. the
functions contain a series of computational commands to be carried out to
achieve a certain outcome.
It is just like a procedure, with a list of step-by-step instructions for the computer
program to follow. The code can easily be reused in different parts of the
program. The advantage of the paradigm is that the code can be easy to learn and
read in simple programs. Though, while dealing with a complex problem, we run
the risk of ending up with a huge volume of code.
The parallel programming paradigm breaks the problem or task into chunks that
are distributed among multiple processors. These chunks work on the same
problem, simultaneously. It reduces the total time to solve a problem. It connects
multiple processors to the memory. It is either pooled across all processors or
distributed over a network.
Advantages
o Efficient and shortcode
o Referential Transparency
o Idempotence
o Error recovery
3
o Readability
o Commutativity
o Easy optimization
Disadvantages
o Difficult to understand.
o It is abed on an unfamiliar conceptual model.
o Difficult to accept characteristics of specific applications into account
while programming.
Functional Programming
Logical Programming
4
The data-driven programming paradigm depends on information and its
development. In this paradigm, the program statements are characterized by data
instead of hard-coding a progression of steps. A data set program is the core of a
business data framework and gives document creation, information section,
update, query, and reporting functions.
There are a few programming dialects that are developed for the most part for
data set applications. For example, SQL. It is applied to surges of organized
information, for filtering, transforming, aggregating, or calling different projects.
So, it has its own wide application.
Multi-Paradigm
5
Imperative Vs. Declarative Programming Paradigm
Basis of Imperative Paradigm Declarative Paradigm
Comparison
Programming Its style is step by step. Define what the problem is and
Style what data transformations are
needed.
Decision The user makes decisions and It allows the compiler to make
Capability instructs the compiler. decisions.
6
Basic Of OOP :-
1) What is Class ?
o Fields
o Methods
o Constructors
o Blocks
o Nested class and interface
7
class <class_name>{
field;
method;
}
2) What is Object ? :-
An entity that has state and behavior is known as an object e.g., chair, bike,
marker, pen, table, car, etc. It can be physical or logical (tangible and
intangible). The example of an intangible 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 behavior.
Object Definitions:
3) Abstraction :-
Data abstraction is the process of hiding certain details and showing only essential
information to the user. Abstraction can be achieved with either abstract classes or
interfaces.
Data Abstraction may also be defined as the process of identifying only the
required characteristics of an object ignoring the irrelevant details. The
properties and behaviors of an object differentiate it from other objects of
similar type and also help in classifying/grouping the objects.
Consider a real-life example of a man driving a car. The man only knows that
pressing the accelerators will increase the speed of a car or applying brakes
will stop the car, but he does not know how on pressing the accelerator the
speed is actually increasing, he does not know about the inner mechanism of
the car or the implementation of the accelerator, brakes, etc in the car.
4) Encapsulation
8
We can create a fully encapsulated class in Java by making all the data members
of the class private. Now we can use setter and getter methods to set and get the
data in it.
5) Inheritance
Inheritance in Java is a concept that acquires the properties from one class to
other classes; for example, the relationship between father and son. Inheritance
in Java is a process of acquiring all the behaviours of a parent object.
The idea behind inheritance in Java is that you can create new classes that are
built upon existing classes. When you inherit from an existing class, you can
reuse methods and fields of the parent class. Moreover, you can add new
methods and fields in your current class also.
Why use inheritance in java
o For Method Overriding (so runtime polymorphism can be achieved).
o For Code Reusability.
Advantages of Inheritance
Flexibility: Inheritance makes the code flexible to change, as you will adjust
only in one place, and the rest of the code will work smoothly.
Overriding: With the help of Inheritance, you can override the methods of the
base class.
Data Hiding: The base class in Inheritance decides which data to be kept
private, such that the derived class will not be able to alter it.
6) What is Polymorphism
• initially java was Develop for Making the software for consumer
Electronic Devices like TV, microwave(sensor technology)
• The Developer team has reviewed the existing Language like c and
c++ and combine the advantage of both language and remove
the limitation and then develop the simple ,reliable ,portable
and power tool language that is called Java as we can show in
below figure
10
• so become two stage system in it first stage java compiler
translate source code to machine independent byte code in the
second stage java interpreter will run this byte code in the
destination machine.
• Compiler: - C, C++, VB, FOXPRO….
• Interpreter: - Scripting language, HTML, PHP
2.Platform independent
• This is the most important and power full future of JAVA
program can run anyway any time changes on upgrade in
operation system or any other system recourses will not affect the
JAVA program to run.
• This is the reason why JAVA become most popular language on
the internet because on internet each and every pc will have
different configuration.
3. Object oriented
• Java is pure object oriented programming and that’s while
everything in java is an object
4.Secure and robust
• When we have a language for internet base programming security
is the first and for most issues security in the sense of protection
from wireless or security of data
• Java does not support * pointer so direct access of memory will
not allow and that why ever program and data will become secure
and robust
5. Distributed
• JAVA programming language has the ability to run program on
distributed network so that it allow us that multiple location can
develop a single project
6.Simple, small & familiar
11
• JAVA is simple language because all the feature like if condition
,for loop ,while loop , switch case, and so on of the most popular
language like C,C++
• JAVA is small language because it consists of only six packages.
The package is same feature combination of C and C++ which we
can familiar this language.
7. Dynamic
• JAVA is dynamic language because one can add new feature all
new feature all new classes.
• To the java itself we can also call it as extension language which
can be extend whenever needed.
8.Multithreading
• Multithreading meaning handling of multiple task at a time.
• Java supports multithreaded programming this means that we
does not have to wait for a process to complete instead of that we
can start new process while the current process running.
9.High performance
• When you develop at require very much less memory as well as
high speed that’s while its give us high performance.
What is JDK?
The Java Development Kit (JDK) is an implementation of either one of the Java
SE, Java EE or Java ME platforms released by Oracle Corporation in the form of a
binary product aimed at Java developers on Solaris, Linux, Mac OS X or Windows.
JDK Tool Meaning Use
Javac Java Compiler Compiles the source code (.java file) &
translates it into Bytecode.
12
Javah Java Header It produces header files for the program
13
• You can think of Java bytecodes as the machine code instructions
for the Java Virtual Machine (JVM).
• Every Java interpreter, whether it's a development tool or a Web
browser that can run applets, is an implementation of the JVM.
• Java byte codes help make "write once, run anywhere" possible.
14
Java Runtime Environment (JRE)
The Java Runtime Environment (JRE), also known as Java
Runtime,
Steps for compiling and running your first java program using the
Java Development kit from Sun Microsystems
Step2:
15
Notepad would ask if you want to create the file. Click on Yes. This
would create the file and you can type the code in it
Step3:
Type the following code. All this code does is print Hello World! on the
screen. Remember Java is case sensitive
class a1
{
public static void main(String[] args){
System.out.println("Hello RPBC");
}
}
Step4:
Compilation Now Save the file and get back to the command prompt
and type the following command as shown.
javac a1.java
This command would compile a1.java and produce a1.class which
contains Java byte code which is machine independent.
Step5:
Running the program If you have any errors, you would see them on
the screen.
java a1
Please go back to notepad and correct the errors and resave the file.
If you see a blank output after the javac command,
it means there were no errors and you are ready to run the program.
You could run the program using the command as shown in the
screen shot.
Hello RPBC
16
Data Type in Java
Data Type Range Size
(Byte)
Byte -128 to 127 1
Short -32768 to 32767 2
Int -2147483648 to 4
2147483647
Long -9223372036854775808 to 8
9223372036854775807
Float 3.4*10-38 to 3.438 4
Double 1.7*10-308 to 1.7*10+308 8
Char Single character 2
Boolean Either true or false 1
Answer :
class xyz
{
public static void main (String args [])
{
System.out.println (“hello”);
}
}
17
In above example we can see xyz is a class name and the description of
public static void main (String args []) as we can see bellow.
public:-
The public keyword is access specified which means that the
contain of the following block accessible from all other classes.
static:-
The keyword static allow main to be called without having
instance of class (duplication copy of object).
void:-
The keyword void tell to the compiler that main () does not return
value.
main ()
String args []
Declare a parameter name which is an array of instance
of the class string args receive and command line argument precision
when the program is executed.
System.out.println()
System is predefining classes that provide access to the system.
Out is the output stream that is connecting to the console.
Output is a complies by the build in println method.
18
1. Documentation section
In this section you can write the documentation for your program
like, program definition, author information, the logic of your
program etc. this is optional section.
It is written in comment lines (//) or (/* …………..*/)
2. Package statement
If you want to save your program in a package(directory) then the
package statement is included. This is also an optional section.
3. Import statement
If you want to import any library or user-defined package, the
import statement is used. Now from this imported package, you
can use its classes & methods. This is also an optional section.
Ex : import java.util.Date;
4. Class Definition
You can define classes in this section. Use class keyword to
declare a class. There can be member variable & methods in this
class. This is required & its compulsory section.
5. Main method
In your program, you can more than one class, but there should
be one class that contains the main method.
This class is run to generate output because the main method is
the entry point for program execution. This is compulsory
section.
19
Java Tokens
Comments
There are three types of comment in java.
1. Single line comments : Double slashes are used to indicate single line
comment.
Ex. //This is a single line comment.
2. Multi-line comments :
The text written between /* and */ are considered comments.
Ex : /*
This is documentation comment
Rpbc
*/
Operator in Java
Operators
In java language there are same operators which we was used in the C and C++.
There are
Arithmetic Operators
Arithmetic operators are used in mathematical expression in the same way that
they are used in algebra. The following table lists the arithmetic operators:
Operator Result
+ Addition
- Subtraction(also unary minus)
* Multiplication
/ Division
% Modulus
++ Increment
+= Addition Assignment
-= Subtraction Assignment
/= Division Assignment
%= Modulus Assignment
*/ Multiplication Assignment
-- Decrement
20
In Arithmetic Assignment Operators
Java provides special operators that can be used to combine an arithmetic
operation with an assignment. As you probably know, statements like the
following are quite common in programming.
a = a + 4;
The compound assignment operator provides two benefits. First, they save you a
bit of typing, because they are “shorthand” for their equivalent long forms.
Second, they are implemented more efficiently by the java run-time system than
are their equivalent long forms. For these reasons, you will often see the
compound assignment operators used in professionally written java programs.
Increment and Decrement Operators
The ++ and -- are Java’s increment and decrement operators.
The ++ (Increment Operators) increase its operand by one.
The -- (decrement Operators) decrease its operand by one. For example, this
statement.
x = x + 1; x = x – 1;
can be rewritten like this by use of the
x++; ++x; x--; --x;
These operators are unique in that they can appear in prefix (++x) and postfix
(x++) form. For example:-
The Bitwise Operators
Bitwise and bit shift operators are used on integral types (byte, short, int and
long) to perform bit-level operations.
Java Bitwise and Bit Shift Operators
Operator Description
| Bitwise OR
& Bitwise AND
~ Bitwise Complement
^ Bitwise XOR
<< Left Shift
>> Right Shift
>>> Unsigned Right Shift
21
Bitwise OR
Bitwise OR is a binary operator (operates on two operands). It's denoted by |.
The | operator compares corresponding bits of two operands. If either of the bits
is 1, it gives 1. If not, it gives 0. For example,
12 = 00001100 (In Binary)
25 = 00011001 (In Binary)
Bitwise AND
Bitwise AND is a binary operator (operates on two operands). It's denoted by &.
The & operator compares corresponding bits of two operands. If both bits are 1,
it gives 1. If either of the bits is not 1, it gives 0. For example,
12 = 00001100 (In Binary)
25 = 00011001 (In Binary)
Bitwise Complement
Bitwise complement is an unary operator (works on only one operand). It is
denoted by ~.
The ~ operator inverts the bit pattern. It makes every 0 to 1, and every 1 to 0.
35 = 00100011 (In Binary)
It's because the compiler is showing 2's complement of that number; negative
notation of the binary number.
22
Bitwise XOR
Bitwise XOR is a binary operator (operates on two operands). It's denoted by ^.
The ^ operator compares corresponding bits of two operands. If corresponding
bits are different, it gives 1. If corresponding bits are same, it gives 0. For
example,
12 = 00001100 (In Binary)
25 = 00011001 (In Binary)
Program
class RightShift {
public static void main(String[] args) {
The relational Operators determine the relationship that one operand has to
another. Specifically, they determine equality and ordering. The relational
operators are shown here.
Operator Result
== Equal to
!= Not Equal to
> Greater than
< Less than
>= Greater than or Equal to
<= Less than or Equal to
The relational operators have always BOOLEAN value either true or false.
These operators are use in control statement line IF condition and loop. It is
same as C and C++.
1. Implicit casting
2. Explicit casting
This is done implicitly by the JVM. The lower size is widened to higher
size. This is also named as automatic type conversion.
Examples:
24
int x = 10; // occupies 4 bytes
double y = x; // occupies 8 bytes
System.out.println(y); // prints 10.0
byte –> short –> int –> long –> float –> double
2. Explicit casting (narrowing conversion)
This is not done implicitly by the JVM and requires explicit casting; a
casting operation to be performed by the programmer.
double x = 10.5;
int y = (int) x;
That is, byte can be assigned to short implicitly but short to byte
requires explicit casting.
25
public class Demo
double d1 = ch1;
double d2 = 66.0;
System.out.println(ch2); // prints B }
Decision Statements
The decision statements also known as selection statements in java. There are
two decision statements are if and switch.
if statements:-
If statements in Java are used to control the program flow based on some
condition, it’s used to execute some statement code block if expression is
evaluated to true, otherwise it will get skipped. This is a simplest way to modify
the control flow of the program.
Syntex:-
if(condition)
{
Statement;
}
Nested ifs:-
A nested if is a statement that is the target of another if or else. Nested if are very
commonly in programming. When you nest ifs, the main thing to remember is
that an else statement always refers to the nearest if statement that is within the
same block as the else not already associated with an else. Example:-
if(i == 100)
{
if(j < 20) a=b;
26
if(k > 100) c=d;
else a =c;
}
else
a = d;
if(condition)
statements;
else if(condition)
statements;
else if(condition)
statements;
.
.
.
else
statement;
Switch..case
A switch statement allows a variable to be tested for equality against a list of
values. Each value is called a case, and the variable being switched on is checked
for each case.
Syntax
switch(expression) {
case value :
// Statements
break; // optional
case value :
// Statements
break; // optional
Looping Statement
There may be a situation when you need to execute a block of code several
number of times. In general, statements are executed sequentially: The first
statement in a function is executed first, followed by the second, and so on.
Programming languages provide various control structures that allow for more
complicated execution paths.
A loop statement allows us to execute a statement or group of statements
multiple times and following is the general form of a loop statement in most of
the programming languages
Java programming language provides the following types of loop to handle
looping requirements. Click the following links to check their detail.
Sr.No. Loop & Description
while loop
1 Repeats a statement or group of statements while a given condition is true. It
tests the condition before executing the loop body.
for loop
2 Execute a sequence of statements multiple times and abbreviates the code that
manages the loop variable.
do...while loop
3 Like a while statement, except that it tests the condition at the end of the loop
body.
28
While loop:-
A while loop statement in Java programming language repeatedly executes a
target statement as long as a given condition is true.
Syntax
The syntax of a while loop is −
while(Boolean_expression) {
// Statements
}
Here, statement(s) may be a single statement or a block of statements.
The condition may be any expression, and true is any non zero value.
When executing, if the boolean_expression result is true, then the actions inside
the loop will be executed. This will continue as long as the expression result is
true.
When the condition becomes false, program control passes to the line
immediately following the loop.
for loop;-
A for loop is a repetition control structure that allows you to efficiently write a
loop that needs to be executed a specific number of times.
A for loop is useful when you know how many times a task is to be repeated.
Syntax
The syntax of a for loop is −
for(initialization; Boolean_expression; update) {
// Statements
}
Here is the flow of control in a for loop −
The initialization step is executed first, and only once. This step allows
you to declare and initialize any loop control variables and this step ends
with a semi colon (;).
Next, the Boolean expression is evaluated. If it is true, the body of the loop
is executed. If it is false, the body of the loop will not be executed and
control jumps to the next statement past the for loop.
After the body of the for loop gets executed, the control jumps back up to
the update statement. This statement allows you to update any loop control
variables. This statement can be left blank with a semicolon at the end.
The Boolean expression is now evaluated again. If it is true, the loop
executes and the process repeats (body of loop, then update step, then
Boolean expression). After the Boolean expression is false, the for loop
terminates.
29
For-each loop (Advanced or Enhanced For loop):
As of Java 5, the enhanced for loop was introduced. This is mainly used to
traverse collection of elements including arrays. The advantage of for-each loop
is that it eliminates the possibility of bugs and makes the code more readable.
Syntax
Following is the syntax of enhanced for loop −
for(declaration : expression) {
// Statements
}
Declaration − The newly declared block variable, is of a type compatible
with the elements of the array you are accessing. The variable will be
available within the for block and its value would be the same as the
current array element.
Expression − This evaluates to the array you need to loop through. The
expression can be an array variable or method call that returns an array.
class For1
{
public static void main(String a[])
{
int numbers[]={10,20,30,40,50};
for(int x : numbers)
{
if(x==30)
break;
System.out.println(x);
}
}
}
do…while Loop;-
A do...while loop is similar to a while loop, except that a do...while loop is
guaranteed to execute at least one time.
Syntax
Following is the syntax of a do...while loop −
do {
// Statements
}while(Boolean_expression);
Notice that the Boolean expression appears at the end of the loop, so the
statements in the loop execute once before the Boolean is tested.
30
If the Boolean expression is true, the control jumps back up to do statement, and
the statements in the loop execute again. This process repeats until the Boolean
expression is false.
Jumping Statement
Break:-
The break statement in Java programming language has the following two
usages −
When the break statement is encountered inside a loop, the loop is
immediately terminated and the program control resumes at the next
statement following the loop.
It can be used to terminate a case in the switch statement (covered in the
next chapter).
Syntax
The syntax of a break is a single statement inside any loop −
break;
continue:-
The continue keyword can be used in any of the loop control structures. It causes
the loop to immediately jump to the next iteration of the loop.
In a for loop, the continue keyword causes control to immediately jump to
the update statement.
In a while loop or do/while loop, control immediately jumps to the
Boolean expression.
Syntax
The syntax of a continue is a single statement inside any loop −
continue
Array
An array stores a group of data items all of the same type.
dataType[] variableName;
Instantiating Arrays
Instantiate an array object using new, the data type, and an array size
in square brackets
int[] nums;
nums = new int[10];
31
The second line constructs a new array object with 10 integer
elements, all initialized to 0, and stores the reference into nums.
int[] moreNums;
int size = 7;
moreNums = new int[size];
int[] nums;
nums = new int[10];
nums = new int[20];
Initializing Arrays
An array can be initialized when it is created
or
32
String[] names = new String[]{ "hello", "rpbc", "student" };
int x = 5;
int y = 5;
arr1[0][x] = "hello";
arr1[0][y] = "rpbc";
You can pass argument to the main() method. This can be done at
runtime.
class test1
33
public static void main(String args[]) {
for(int i=0;i<arrg.length;i++)
javac test1.java
java test1 hi hello bye
output
Argument 0: hi
Argument 1: hello
Argument 2: bye
34
To do so, we were using free() function in C language and delete() in C++. But,
in java it is performed automatically. So, java provides better memory
management.
1) By nulling a reference:
Employee e=new Employee();
e=null;
2) By assigning a reference to another:
Employee e1=new Employee();
Employee e2=new Employee();
e1=e2;//now the first object referred by e1 is available for garbage collection
3) By anonymous object:
new Employee();
public class TestGarbage1{
public void finalize(){System.out.println("object is garbage collected");}
public static void main(String args[]){
TestGarbage1 s1=new TestGarbage1();
TestGarbage1 s2=new TestGarbage1();
s1=null;
s2=null;
System.gc();
}
}
35