Unit 1
Unit 1
The term paradigm describes a set of techniques, methods, theories and standards
that together represent a way of thinking for problem solving.
Language paradigms were associated with classes of languages. First the
paradigms are defined. Thereafter, programming languages according to the
different paradigms are classified.
The language paradigms are divided into two parts, imperative and declarative
paradigms
Imperative languages can be further classified into procedural and object
oriented approach.
Declarative languages can be classified into functional languages and logical
languages.
POP OOP
POP follows Top Down approach. OOP follows Bottom Up approach.
In POP, program is divided into small parts In OOP, program is divided into parts called
called functions. objects.
POP does not have any proper way for OOP provides Data Hiding so provides
hiding data so it is less secure. more security.
Their is no provision of inheritance. Inheritance achieved in three modes public
private and protected.
Operator overloading is not allowed. Operator overloading is allowed.
Example of POP are : C,FORTRAN, Example of OOP are : C++, JAVA,
Pascal. VB.NET, C#.NET.
Java terminology
3. bytecode
javac compiler of JDK compiles the java source code into bytecode so that it can be
executed by JVM. The bytecode is saved in a .class file by compiler.
So, now that we understood that the primary function of JVM is to execute the bytecode
produced by compiler. Each operating system has different JVM, however the output they
produce after execution of bytecode is same across all operating systems. That is why we
call java as platform independent language.
5. API:
An application programming interface (API), in the context of Java, is a collection
of prewritten packages, classes, and interfaces with their respective methods, fields and
constructors. Similar to a user interface, which facilitates interaction between humans and
computers, an API serves as a software program interface facilitating interaction.
In Java, most basic programming tasks are performed by the API’s classes and
packages, which are helpful in minimizing the number of lines written within pieces of
code.
After referring to the available API classes and packages, the programmer easily
invokes the necessary code classes and packages for implementation.
Class
Object
Abstraction
Encapsulation
Inheritance
Polymorphism
1. Class
class<class_name>{
field;
method;
}
2. Object
Object means a real word entity such as pen, chair, table etc. Object-Oriented
Programming is a methodology or paradigm to design a program using classes and
objects.
Any entity that has state and behavior is known as an object. For example: chair,
pen, table, keyboard, bike etc. It can be physical and logical. Object is the physical as
well as logical entity whereas class is the logical entity only.
For Example: Pen is an object. Its name is Reynolds, color is white etc. known as its
state. It is used to write, so writing is its behavior.
3. Abstraction
One of the most fundamental concept of OOPs is Abstraction. Abstraction is a
process where you show only “relevant” data and “hide” unnecessary details of an object
from the user. For example, when you login to your Amazon account online, you enter
your user_id and password and press login, what happens when you press login, how the
input data sent to amazon server, how it gets verified is all abstracted away from the you.
Another example of abstraction: A car in itself is a well-defined object, which is
composed of several other smaller objects like a gearing system, steering mechanism,
engine, which are again have their own subsystems. But for humans car is a one single
object, which can be managed by the help of its subsystems, even if their inner details are
unknown.
4. Encapsulation
Encapsulation is:
Binding the data with the code that manipulates it.
It keeps the data and the code safe from external interference
Looking at the example of a power steering mechanism of a car. Power steering of a car
is a complex system, which internally have lots of components tightly coupled together,
they work synchronously to turn the car in the desired direction. It even controls the
power delivered by the engine to the steering wheel. But to the external world there is
only one interface is available and rest of the complexity is hidden. Moreover, the
steering unit in itself is complete and independent. It does not affect the functioning of
any other mechanism.
5. Inheritance
Inheritance is the mechanism by which an object acquires the some/all properties
of another object.
It supports the concept of hierarchical classification.
For example: Car is a four wheeler vehicle so assume that we have a class
FourWheeler and a sub class of it named Car. Here Car acquires the properties of a class
FourWheeler. Other classifications could be a jeep, tempo, van etc. FourWheeler defines
a class of vehicles that have four wheels, and specific range of engine power, load
carrying capacity etc. Car (termed as a sub-class) acquires these properties from
FourWheeler, and has some specific properties, which are different from other
classifications of FourWheeler, such as luxury, comfort, shape, size, usage etc.
A car can have further classification such as an open car, small car, big car etc, which
will acquire the properties from both Four Wheeler and Car, but will still have some
specific properties. This way the level of hierarchy can be extended to any level.
6. Polymorphism
Polymorphism means to process objects differently based on their data type.
In other words it means, one method with multiple implementation, for a certain
class of action. And which implementation to be used is decided at runtime
depending upon the situation (i.e., data type of the object)
Lets us look at same example of a car. A car have a gear transmission system. It has four
front gears and one backward gear. When the engine is accelerated then depending upon
which gear is engaged different amount power and movement is delivered to the car. The
action is same applying gear but based on the type of gear the action behaves differently
or you can say that it shows many forms (polymorphism means many forms)
2. Simple
Java is considered as one of simple language because it does not have complex
features like Operator overloading, Multiple inheritance, pointers and Explicit memory
allocation.
3. Robust Language
Robust means reliable. Java programming language is developed in a way that
puts a lot of importance on early checking for possible errors, that’s why java compiler is
able to detect errors that are not easy to detect in other programming languages. The main
features of java that makes it robust are garbage collection, Exception Handling and
memory allocation.
4. Secure
We don’t have pointers and we cannot access out of bound arrays (you get
ArrayIndexOutOfBoundsException if you try to do so) in java. That’s why several
security flaws like stack corruption or buffer overflow is impossible to exploit in Java.
5. Java is distributed
Using java programming language we can create distributed applications.
RMI(Remote Method Invocation) and EJB(Enterprise Java Beans) are used for creating
distributed applications in java. In simple words: The java programs can be distributed on
more than one systems that are connected to each other using internet connection. Objects
on one JVM (java virtual machine) can execute procedures on a remote JVM.
6. Multithreading
Java supports multithreading. Multithreading is a Java feature that allows
concurrent execution of two or more parts of a program for maximum utilization of CPU.
7. Portable
As discussed above, java code that is written on one machine can run on another
machine. The platform independent byte code can be carried to any platform for
execution that makes java code portable.
Applications of OOPs:
Advantages of OOPs:
OOP offers several benefits to both the program developer and the user. The new
technology provides greater programmer productivity, better quality of software and
lesser maintenance cost. The major benefits are:
Ease in division of job: Since it is possible to map objects of the problem domain
to those objects in the program, the work can be easily partitioned based on
objects.
Reduce complexity: Software complexity can be easily managed.
Provide extensibility: Object Oriented systems can be easily upgraded from small
to large system.
Eliminate redundancy: Through inheritance we can eliminate redundant code
and extend the use of existing classes.
Saves development time and increases productivity: Instead of writing code
from scratch, solutions can be built by using standard working modules.
Allows building secure programs: Data hiding principle helps programmer to
build secure programs that cannot be accessed by code in other parts of the
program.
Types of java programming:
There are many types of Java programs which run differently:
Java Applet - small program written in Java and that is downloaded from a
website and executed within a web browser on a client computer.
Application - executes on a client computer. If online, it has to be downloaded
before being run.
JAR file (Java ARchive) - used to package Java files together into a single file
(almost exactly like a .zip file).
Servlet - runs on a web server and helps to generate web pages.
Swing application - used to build an application that has a GUI (windows,
buttons, menus, etc.).
EJB - runs on a web server and is used to develop large, complex websites.
Step 4: After compilation the .java file gets translated into the .class file(byte code). Now
we can run the program. To run the program, type the following command and hit enter:
java FirstJavaProgram
Tokens
Java Keywords
Keywords are predefined, reserved words used in Java programming that have special
meanings to the compiler.
For example: int score;
Here, int is a keyword. It indicates that the variable score is of integer type.
You cannot use keywords like int, for, class etc as variable name (or identifiers) as they
are part of the Java programming language syntax. Here's the complete list of all
keywords in Java programming.
Java Keywords List
abstract assert boolean break byte
case catch char class const
continue default do double else
enum extends final finally float
for goto if implement impor
s t
instanceo int interfac long native
f e
new package private protected public
return short static strictfp super
switch synchronize this throw throw
d s
transient try void volatile while
Java identifiers
Identifiers are the name given to variables, classes, methods etc.
Example: int score;
Here, score is a variable (an identifier). You cannot use keywords as variable name. It's
because keywords have predefined meaning.
Rules for Naming an Identifier
Identifier cannot be a keyword.
Identifiers are case-sensitive.
It can have a sequence of letters and digits. However, it must begin with a letter, $
or _. The first letter of an identifier cannot be a digit.
It's convention to start an identifier with a letter rather and $ or _.
Whitespaces are not allowed.
Similarly, you cannot use symbols such as @, #, and so on.
Literals in Java
A literal is a fixed value that we assign to a variable in a Program.
int num=10;
Here value 10 is a Integer literal.
char ch ='A';
Here A is a char literal
Integer Literal
Integer literals are assigned to the variables of data type byte, short, int and long.
byte b =100;
short s =200;
int num =13313131;
long l =928389283L;
Float Literals
Used for data type float and double.
double num1 =22.4;
float num2 =22.4f;
Note: Always suffix float value with the “f” else compiler will consider it as double.
Char and String Literal
Used for char and String type.
char ch ='Z';
String str ="BeginnersBook";
Separators in Java
Separators help define the structure of a program. The separators used in HelloWorld are
parentheses( ), braces,{ }, the period,., and the semicolon,;. The table lists the six Java
separators (nine if you count opening and closing separators as two).
Separators in Java
Variable
A Java variable is a piece of memory that can contain a data value. A variable thus has a
data type. Variables are typically used to store information which your Java program
needs to do its job.
In the code example below, the main() method contains the declaration of a single integer
variable named number. The value of the integer variable is first set to 10, and then 20 is
added to the variable afterwards.
public class MyClass {
public static void main(String[] args) {
int number = 10;
number = number + 20;
}
}
Java Variable Types
In Java there are four types of variables:
1. Non-static fields
2. Static fields
3. Local variables
4. Parameters
1. A non-static field is a variable that belongs to an object. Objects keep their internal
state in non-static fields. Non-static fields are also called instance variables,
because they belong to instances (objects) of a class. Non-static fields are covered
in more detail in the text on Java fields.
2. A static field is a variable that belongs to a class. A static field has the same value
for all objects that access it. Static fields are also called class variables. Static
fields are also covered in more detail in the text on Java fields.
3. A local variable is a variable declared inside a method. A local variable is only
accessible inside the method that declared it. Local variables are covered in more
detail in the text on Java methods.
4. A parameter is a variable that is passed to a method when the method is called.
Parameters are also only accessible inside the method that declares them, although
a value is assigned to them when the method is called. Parameters are also covered
in more detail in the text on Java methods.
Scope and Lifetime of Variables. The scope of a variable defines the section of the code
in which the variable is visible. As a general rule, variables that are defined within a
block are not accessible outside that block. The lifetime of a variable refers to how
long the variable exists before it is destroyed.
Constants in Java.
A constant is a variable which cannot have its value changed after declaration. It uses
the 'final' keyword.
Data Types
Data type defines the values that a variable can take, for example if a variable has int
data type, it can only take integer values.
In java we have two categories of data type:
1) Primitive data types 2) Non-primitive data types – Arrays and Strings are non-
primitive data types.
1) Primitive data types
In Java, we have eight primitive data types: boolean, char, byte, short, int, long, float and
double. Java developers included these data types to maintain the portability of java as
the size of these primitive data types do not change from one operating system to another.
byte, short, int and long data types are used for storing whole numbers.
float and double are used for fractional numbers.
char is used for storing characters(letters).
boolean data type is used for variables that holds either true or false.
byte:
This can hold whole number between -128 and 127. Mostly used to save memory and
when you are certain that the numbers would be in the limit specified by byte data type.
Default size of this data type: 1 byte.
Default value: 0
Example:
classJavaExample{
public static void main(String[] args){
byte num;
num =113;
System.out.println(num);
}
}
Output:
113
Try the same program by assigning value assigning 150 value to variable num, you would
get type mismatch error because the value 150 is out of the range of byte data type. The
range of byte as I mentioned above is -128 to 127.
short:
This is greater than byte in terms of size and less than integer. Its range is -32,768 to
32767.
Default size of this data type: 2 byte
short num=45678;
int:
Used when short is not large enough to hold the number, it has a wider range:
-2,147,483,648 to 2,147,483,647
Default size: 4 byte
Default value: 0
Example:
classJavaExample{
publicstaticvoid main(String[] args){
short num;
num =150;
System.out.println(num);
}
}
Output:
150
long:
Used when int is not large enough to hold the value, it has wider range than int data type,
ranging from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807.
size: 8 bytes
Default value: 0
Example:
classJavaExample{
publicstaticvoid main(String[] args){
long num =-12332252626L;
System.out.println(num);
}
}
Output:
-12332252626
double:
Sufficient for holding 15 decimal digits
size: 8 bytes
Example:
classJavaExample{
publicstaticvoid main(String[] args){
float:
Sufficient for holding 6 to 7 decimal digits
size: 4 bytes
classJavaExample{
publicstaticvoid main(String[] args){
float num =19.98f;
System.out.println(num);
}
}
Output:
19.98
boolean:
Holds either true of false.
classJavaExample{
publicstaticvoid main(String[] args){
boolean b =false;
System.out.println(b);
}
}
Output:
false
char:
Holds characters.
Size: 2 bytes
classJavaExample{
publicstaticvoid main(String[] args){
char ch ='Z';
System.out.println(ch);
}
}
Output:
Z
Java Command Line Arguments
The java command-line argument is an argument i.e. passed at the time of running
the java program. The arguments passed from the console can be received in the java
program and it can be used as an input. So, it provides a convenient way to check the
behavior of the program for the different values.
Example:
In this example, we are receiving only one argument and printing it. To run this java
program, you must pass at least one argument from the command prompt.
class CommandLineExample{
public static void main(String args[]){
System.out.println("Your first argument is: "+args[0]);
}
}
compileby>javac CommandLineExample.java
runby>java CommandLineExamplesonoo
Java Comments
The java comments are statements that are not executed by the compiler and interpreter.
The comments can be used to provide information or explanation about the variable,
method, class or any statement. It can also be used to hide program code for specific
time.
1. Single Line Comment
Example:
/*
This
is
multi line
comment
*/
Basic Examples:
In this program we will see how to read an integer number entered by user. Scanner class
is in java.util package. It is used for capturing the input of the primitive types like int,
double etc. and strings.
import java.util.Scanner;
publicclassDemo{
publicstaticvoid main(String[] args){
Scanner scan =newScanner(System.in);
System.out.print("Enter any number: ");
// This method reads the number provided using keyboard
int num = scan.nextInt();
// Closing Scanner after the use
scan.close();
// Displaying the number
System.out.println("The number entered by user: "+num);
}
}
Output:
Enter any number:101
The number entered by user:101
publicclassAddTwoNumbers{
publicstaticvoid main(String[] args){
int num1 =5, num2 =15, sum;
sum = num1 + num2;
System.out.println("Sum of these numbers: "+sum);
}
}
Output:
Sum of these numbers:20
Exercise:
1.Write a program to print Sum of two numbers using Scanner
import java.util.Scanner;
public class AddTwoNumbers2{
public static void main(String[] args){
int num1, num2, sum;
Scanner sc =newScanner(System.in);
System.out.println("Enter First Number: ");
num1 = sc.nextInt();
System.out.println("Enter Second Number: ");
num2 = sc.nextInt();
sc.close();
sum = num1 + num2;
System.out.println("Sum of these numbers: "+sum);
}
}
Output:
EnterFirstNumber:
121
EnterSecondNumber:
19
Sum of these numbers:140
2. Write a Java program to swap two variables.
int a, b, temp;
a = 15;
b = 27;
System.out.println("Before swapping : a, b = "+a+", "+ + b);
temp = a;
a = b;
b = temp;
System.out.println("After swapping : a, b = "+a+", "+ + b);
}
}
3. Write a Java program that reads a number and display the square, cube, and fourth
power.
import java.util.Scanner;
public class square {