INTRODUCTION JAVA
JAVA was developed by Sun Microsystems Inc in 1991, later acquired by
Oracle Corporation. It was developed by James Gosling and Patrick Naughton. It is
a simple programming language and a platform. Writing, compiling and
debugging a program is easy in java.
Java is a high level, robust, secured and object-oriented programming language.
Platform: Any hardware or software environment in which a program runs, is
known as a platform. Since Java has its own runtime environment (JRE) and API.
It is called platform
JAVA DEVELOPMENT KIT(JDK) :. As the name suggests this is complete java
development kit that includes JRE (Java Runtime Environment), compilers and
various tools like JavaDoc, Java debugger etc. In order to create, compile and
run Java program you would need JDK installed on your computer
JAVA RUNTIME ENVIRONMENT (JRE) : JRE is a part of JDK which means that JDK
includes JRE. When you have JRE installed on your system, you can run a java
program however you won’t be able to compile it. JRE includes JVM, browser
plugins and applets support. When you only need to run a java program on your
computer, you would only need JRE.
JVM (JAVA VIRTUAL MACHINE) : Java is a high level programming language. A
program written in high level language cannot be run on any machine directly.
First, it needs to be translated into that particular machine language. The javac
compiler does this thing, it takes java program (.java file containing source code)
and translates it into machine code (referred as byte code or .class file).
The Java Virtual machine (JVM) is the virtual machine that runs on actual
machine (your computer) and executes Java byte code. The JVM doesn’t
understand Java source code, that’s why we need to have javac compiler that
compiles *.java files to obtain *.class files that contain the byte codes understood
by the JVM. JVM makes java portable (write once, run anywhere). Each operating
system has different JVM, however the output they produce after execution of
byte code is same across all operating systems.
Heap : Heap is a part of JVM memory where objects are allocated. JVM creates a
Class object for each .class file.
Stack : Stack is a also a part of JVM memory but unlike Heap, it is used for storing
temporary variables.
Garbage collection : A class instance is explicitly created by the java code and
after use it is automatically destroyed by garbage collection for memory
management.
FEATURES OF JAVA
Java is a platform independent language : A program that is compiled on
windows can run on Linux and vice-versa. 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.
Java is an Object Oriented language : Object oriented programming is a way of
organizing programs as collection of objects, each of which represents an
instance of a class.
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.
Robust Language : Robust means reliable. Java programming language is
developed in a way that puts a lot of emphasis 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.
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.
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.
Multithreading : Java supports multithreading. Multithreading is a Java feature
that allows concurrent execution of two or more parts of a program for maximum
utilisation of CPU.
Portable : 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.
CLASSPATH
Classpath is a parameter in the Java Virtual Machine or the Java compiler that
specifies the location of user-defined classes and packages. The parameter may
be set either on the command- line, or through an environment variable.
Install JDK C:\Program Files\Java\jdk1.8.0_71\bin (Copy this path) Rightclick My
computer
Advanced system settings Environment variables Paste the copied path there.
VARIABLES
A variable is the name given to a memory location. It is the basic unit of storage in a
program.
The value stored in a variable can be changed during program execution.
A variable is only a name given to a memory location, all the operations done on
the variable effects that memory location.
In Java, all the variables must be declared before they can be used.
How to declare variables?
We can declare variables in java as follows:
datatype : Type of data that can be stored in this variable.
variable_name : Name given to the variable.
value : It is the initial value stored in the variable.
Examples:
float simpleInterest; //Declaring float variable
int time = 10, speed = 20; //Declaring and Initializing integer
variable char var = 'h'; // Declaring and Initializing character
variable
Variables naming cannot contain white spaces, for example: int num ber =
100; is invalid because the variable name has space in it.
Variable name can begin with special characters such as $ and _
As per the java coding standards the variable name should begin with a
lower case letter,for example int number; For lengthy variables names that
has more than one words do it like this: int smallNumber; int bigNumber;
(start the second word with capital letter).
Variable names are case sensitive in java
There are 3 types of variables in java
1. Static (or class) variable
2. Instance variable
3. Local variable
STATIC (OR CLASS) VARIABLE : Static variables are also known as Class variables.
o These variables are declared similarly as instance variables, the
difference is that static variables are declared using the static keyword
within a class outside any method constructor or block.
o Unlike instance variables, we can only have one copy of a static variable
per class irrespective of how many objects we create.
o Static variables are created at start of program execution and destroyed
automatically when execution ends.
To access static variables, we need not to create any object of that class, we can
simply access the variable as:
class_name.variable_name;
Instance variable : Instance variables are non-static variables and are declared
in a class outside any method, constructor or block.
o As instance variables are declared in a class, these variables are created
when an object of the class is created and destroyed when the object is
destroyed.
o Unlike local variables, we may use access specifiers for instance
variables. If we do not specify any access specifier then the default
access specifier will be used.
Local Variable : A variable defined within a block or method or constructor is
called local variable.
o These variable are created when the block in entered or the function is
called and destroyed after exiting from the block or when the call returns
from the function.
o The scope of these variables exists only within the block in which the
variable is declared. i.e. we can access these variable only within that
block.
DATA TYPES
Integers: This group includes byte, short, int, and long, which are for whole-
valued signed numbers.
Floating-point numbers: This group includes float and double, which represent
numbers with fractional precision.
Characters: This group includes char, which represents symbols in a character
set, like letters and numbers.
Boolean: This group includes boolean, which is a special type for representing true/false
values.
Operators Precedence
postfix
expr++ expr--
unary
++expr --expr +expr -expr ~ !
multiplicative
*/%
additive
+-
Shift
<< >> >>>
relational
< > <= >= instanceof
equality
== !=
bitwise AND
&
bitwise exclusive OR
^
bitwise inclusive OR
|
logical AND
&&
logical OR
||
ternary
?:
assignment
= += -= *= /= %= &= ^= |= <<= >>= >>>=
CONTROL STRUCTURES
When we need to execute a set of statements based on a condition then we
need to use control flow
IF STATEMENT :
If statement consists a condition, followed by statement or a set of statements as shown
below:
if(condition){
Statement(s);
}
The statements gets executed only when the given condition is true. If the
condition is false then the statements inside if statement body are completely
ignored.
Nested if statement in Java :
When there is an if statement inside another if statement then it is called the
nested if statement.
The structure of nested if looks like this:
If(condition1){
Statement1(s);
If(condition2)
Statement2(s);
Statement1 would execute if the condition_1 is true. Statement2 would only
execute if both the conditions( condition_1 and condition_2) are true.
If else statement in Java
This is how an if-else statement looks:
If(condition)
{Statements}
else
{Statements}
The statements inside “if” would execute if the condition is true, and the
statements inside “else” would execute if the condition is false.
Switch case statement :
It is used when we have number of options (or choices) and we may need to
perform a different task for each choice.
The syntax of Switch case statement looks like this –
switch (variable or an integer expression)
{
case constant:
//Java code
case constant:
//Java code
default:
//Java code ; }
Switch Case statement is mostly used with break statement even though it is
optional. We will first see an example without break statement and then we will
discuss switch case with break
A Simple Switch Case Example
public class SwitchCaseExample1 {
public static void
main(String
args[]){ int
num=2;
switch(num+2)
case 1:
System.out.println("Case
1: Value is: "+num); case 2:
System.out.println("Case
2: Value is: "+num); case 3:
System.out.println("Case3
: Value is: "+num); default:
System.out.println("Default: Value is: "+num);
}
}
Java While Loop: The Java while loop is used to iterate a part of the program
several times. If the number of iteration is not fixed, it is recommended to use
while loop.
Syntax: while(condition){
//code to be executed }
Java Infinitive While Loop: If you pass true in the while loop, it will be infinitive while
loop.
Syntax: while(true){
//code to be executed }
Java do-while Loop: The Java do-while loop is used to iterate a part of the
program several times. If the number of iteration is not fixed and you must have to
execute the loop at least once, it is recommended to use do-while loop.
The Java do-while loop is executed at least once because condition is checked after loop
body.
Syntax: do{ //code to be executed
}while(condition);
Java For Loop
The Java for loop is used to iterate a part of the program several times. If the
number of iteration is fixed, it is recommended to use for loop.
There are three types of for loop in java.
Simple For Loop
For-each or Enhanced For Loop
Labeled For Loop
Java Simple For Loop
The simple for loop is same as C/C++. We can initialize variable, check condition
and increment/decrement value.
Syntax: labelname:
for(initialization;condition;incr/decr){
//code to be executed
}
Java For-each Loop
The for-each loop is used to traverse array or collection in java. It is easier to use
than simple for loop because we don't need to increment value and use subscript
notation.It works on elements basis not index. It returns element one by one in
the defined variable.
Syntax: for(Type var:array){
//code to be executed
}
Java Labeled For Loop
We can have name of each for loop. To do so, we use label before the for loop. It
is useful if we have nested for loop so that we can break/continue specific for
loop.
Normally, break and continue keywords breaks/continues the inner most for loop only.
Syntax: labelname:
for(initialization;condition;incr/decr){
//code to be executed
}
Java Infinitive For Loop
If you use two semicolons ;; in the for loop, it will be infinitive for loop.
Syntax: for(;;){
//code to be executed
}
Java Scanner class
There are various ways to read input from the keyboard, the
java.util.Scanner class is one of them. The Java Scanner class breaks the input
into tokens using a delimiter that is whitespace by default. It provides many
methods to read and parse various primitive values. Java Scanner class is widely
used to parse text for string and primitive types using regular expression. Java
Scanner class extends Object class and implements Iterator and Closeable
interfaces.
JAVA ARRAY
Normally, array is a collection of similar type of elements that have contiguous memory
location.
Java array is an object the contains elements of similar data type. It is a data
structure where we store similar elements. We can store only fixed set of
elements in a java array.
Array in java is index based, first element of the array is stored at 0 index.
Advantage of Java Array
Code Optimization: It makes the code optimized, we can retrieve or sort the data easily.
Random access: We can get any data located at any index position.
Disadvantage of Java Array
Size Limit: We can store only 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.
Types of Array in Java
Single Dimensional Array
MultiDimensional Array
Syntax:
Datatype[] arr;
Or datatype arr[];
INSTANTIATION OF AN ARRAY IN JAVA
arrayRefVar=new datatype[size];
MULTIDIMENSIONAL ARRAY IN JAVA
In such case, data is stored in row and column based index (also known as matrix form).
Syntax to Declare Multidimensional Array in java
Datatype[][] arrref;
Datatype arref[][];
STRING
In java, string is basically an object that represents sequence of char values. An
array of characters works same as java string. For example:
char[] ch={'j','a','v','a','t',}
String s=new String(ch);
is same as
String s=javat;
Java String class provides a lot of methods to perform operations on string such
as compare(), concat(), equals(), split(), length(), replace(), compareTo(), intern(),
substring() etc
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
string object.
STRING METHODS :
charAt()
compareTo()
equals()
trim()
substring()
concat()
replace()
OBJECT ORIENTED PROGRAMMING (OOP)
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. It simplifies the software development and maintenance by
providing some concepts:
Object
Class
Inheritance
Polymorphism
Abstraction
Encapsulation
OBJECT: 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.
CLASS : Collection of objects is called class. It is a logical entity.
INHERITANCE : When one object acquires all the properties
and behaviours of parent object i.e. known as inheritance. It
provides code reusability. It is used to achieve runtime
polymorphism.
Syntax: Inheritance in Java
To inherit a class we use extends keyword. Here class A is child class and class B is parent
class.
class A extends B{ ……. }
TYPES OF INHERITANCE
Single inheritance is damn easy to understand. When a class extends
another one class only then we call it a single inheritance. The below flow
diagram shows that class B extends only one class which is A. Here A is a parent
class of B and B would be a child class of A.
1. Multiple Inheritance
“Multiple Inheritance” refers to the concept of one class extending (Or
inherits) more than one base class. The inheritance we learnt earlier had the
concept of one base class or parent. The problem with “multiple inheritance” is
that the derived class will have to manage the dependency on two base classes.
When one class extends more than one classes then this is called multiple
inheritance. For example: Class C extends class A and B then this type of
inheritance is known as multiple inheritance. Java doesn’t allow multiple
inheritance. why java doesn’t allow multiple inheritance and how we can use
interfaces instead of classes to achieve the same purpose.
1. Multilevel Inheritance
Multilevel inheritance refers to a mechanism in OO technology where one can
inherit from a derived class, thereby making this derived class the base class for
the new class. As you can see in below flow diagram C is subclass or child class of
B and B is a child class of A.
Hierarchical Inheritance
In such kind of inheritance one class is inherited by many sub classes. In below
example class B,C and D inherits the same class A. A is parent class (or base
class) of B,C & D.
POLYMORPHISM:
When one task is performed by different ways i.e. known as polymorphism. For
example: to convince the customer differently, to draw something e.g. shape or
rectangle etc.In java, we use method overloading and method overriding to achieve
polymorphism. Another example can be to speak something e.g. cat speaks meaw, dog
barks woof etc.
Types of Polymorphism
1. Static Polymorphism
2. Dynamic Polymorphism
Static Polymorphism:
Polymorphism that is resolved during compiler time is known as static polymorphism.
Method overloading can be considered as static polymorphism example.
Method Overloading: This allows us to have more than one methods with same name
in a class that differs in signature.
Dynamic Polymorphism:
It is also known as Dynamic Method Dispatch. Dynamic polymorphism is a process in
which a call to an overridden method is resolved at runtime rather, thats why it is
called runtime polymorphism.
ABSTRACTION :
Hiding internal details and showing functionality is known as abstraction. For
example: phone call, we don't know the internal processing.In java, we use
abstract class and interface to achieve abstraction.
Abstract Class and methods in OOPs Concepts Abstract method:
1. A method that is declared but not defined. Only method signature no body.
2. Declared using the abstract keyword
3. Example : abstract public void playInstrument();
4. These cannot be abstract
Constructors
Static methods
Private methods
Methods that are declared “final”
Abstract Class
An abstract class outlines the methods but not necessarily implements all the
methods.
INTERFACES IN JAVA
An interface is a blueprint of a class, which can be declared by using
interface keyword. Interfaces can contain only constants and abstract
methods (methods with only signatures no body).Like abstract classes,
Interfaces cannot be instantiated, they can only be implemented by classes
or extended by other interfaces. Interface is a common way to achieve full
abstraction in Java.
Note:
Java does not support Multiple Inheritance, however a class can implement
more than one interfaces
Interface is similar to an abstract class but it contains only abstract methods.
Interfaces are created by using interface keyword instead of the keyword class
We use implements keyword while implementing an interface(similar to
extending a class with extends keyword)
ENCAPSULATION : Binding (or wrapping) code and data together into a single unit
is known as encapsulation. For example: capsule, it is wrapped with different
medicines.
A java class is the example of encapsulation. Java bean is the fully encapsulated class
because all the data members are private here.
CONSTRUCTOR IN JAVA
Constructor in java is a special type of method that is used to initialize the object.
Java constructor is invoked at the time of object creation. It constructs the values i.e.
provides data for the object that is why it is known as constructor.
Rules for creating java constructor
There are basically two rules defined for the constructor.
1. Constructor name must be same as its class name
2. Constructor must have no explicit return type
Types of java constructors
1. Default constructor (no-arg constructor)
2. Parameterized constructor
Java Default Constructor
A constructor that have no parameter is known as default constructor.
Java parameterized constructor
A constructor that have parameters is known as parameterized constructor.
ACCESS CONTROL MODIFIERS
There are 4 types of java access Modifiers
1. private
2. default
3. protected
4. public
PRIVATE ACCESS MODIFIER
The private access modifier is accessible only within class.
DEFAULT :
If you don't use any modifier, it is treated as default bydefault. The default modifier is
accessible only within package.
PROTECTED ACCESS MODIFIER
The protected access modifier is accessible within package and outside the package but through
inheritance only.The protected access modifier can be applied on the data member, method and
constructor. It can't be applied on the class.
PUBLIC ACCESS MODIFIER
The public access modifier is accessible everywhere. It has the widest scope among all
other modifiers.
EXCEPTION HANDLING IN JAVA
The exception handling in java is one of the powerful mechanism to handle the
runtime errors so that normal flow of the application can be maintained.
In this page, we will learn about java exception, its type and the difference
between checked and unchecked exceptions.
What is exception : Dictionary Meaning: Exception is an abnormal condition.
In java, 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 ClassNotFound,
IO, SQL, Remote etc.
TYPES OF EXCEPTION
There are mainly two types of exceptions: checked and unchecked where error is
considered as unchecked exception. The sun microsystem says there are three types
of exceptions:
1. Checked Exception
2. Unchecked Exception
3. Error