What is Java?
Java is a purely object oriented, platform
independent, open source programming
language.
Developed by James Gosling at Sun
Microsystems in the year 1991 earlier
known as “Oak”
In the year 1995 it was officially renamed
to “Java”
Features of Java
Compiled and Interpreted
Platform independent and Portable
Object Oriented
Robust and Secure
Distributed
Familiar, Simple and Small
Multithreaded and Interactive
High Performance
Dynamic and Extensible
Classes in Java
A class is a blueprint for an object. It tells
the virtual machine how to make an object
of that particular type. For example, you
might use the Button class to make dozens
of different buttons, and each button might
have its own colour, size, shape, label and so
on.
Classes define the structure of an object.
It defines two things of an object :
1) What the object knows (Variables)
2) What is object does (Methods)
How and Where objects are
created?
Objects are created based on it’s classes.
JVM created objects during the execution
of our java program.
Objects of classes are created in “Heap
Memory”
Heap Memory is a runtime memory which
is allocated during the execution of our java
program.
Java Data types
Data types specify the different sizes and
values that can be stored in the variable.
There are two types of data types in Java:
Primitive data types: The primitive data
types include boolean, char, byte, short, int,
long, float and double.
Non-primitive data types: The non-
primitive data types include Classes,
Interfaces, and Arrays.
Type Casting in java
Assigning a value of one type to a variable
of another type is known as Type Casting.
Automatic Type casting take place when,
1)the two types are compatible
2) the target type is larger than the source
type
When you are assigning a larger type value to a
variable of smaller type, then you need to perform
explicit type casting.
Arrays in Java
Java array is an object which contains
elements of a similar data type. 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 0
index.
Variables in java
A variable is a container which holds the
value while the java program is executed. A
variable is assigned with a data type.
int data=50; //Here data is variable
Local Variable
A variable declared inside the body of the
method is called local variable. You can use
this variable only within that method and
the other methods in the class aren't even
aware that the variable exists
Eg :
public void show()
{
int a;
}
Instance Variable A variable declared inside the body of the method is
called local variable. You can use this variable only within
that method and the other methods in the class aren't
even aware that the variable exists
public class Vehicle
{
◦ int speed; // instance variable
◦ int color; // instance variable
◦ public void drive()
◦ {
◦ }
}
Static Variable
When a variable is declared as static, then a single
copy of variable is created and shared among all
objects at class level. Static variables are,
essentially, global variables. All instances of the
class share the same static variable.
Rules for declaring variables in java
A variable name can consist of Capital letters A-Z,
lowercase letters a-z, digits 0-9 and two special
characters such as underscore and dollar sign.
The first character must be a letter.
Blank spaces cannot be used in variable names.
Java keywords cannot be used as variable names.
Variable names are case-sensitive.
Java Tokens
A token is the smallest element of a
program that is meaningful to the
compiler. They are :
Reserved Keywords
Identifiers
Literals
Operators
Separators
Identifiers
In programming languages, identifiers are used
for identification purpose. In Java, an
identifier can be a class name, method name,
variable name or a label.
public class Test
{
public static void main(String[] args)
{
int a = 20;
}
}
Literals
Any constant value which can be assigned
to the variable is called as literal/constant.
Eg: int x = 100; // Here x is a literal
There are :
Integer Literal
Floating point literal
Character literals
String literals
Boolean literals
Operators Operator in java is a symbol that is used to perform
operations. For example: +, -, *, / etc.
Types of operators :
1) Arithmetic
2) Relational
3) Logical
4) Assignment
5) Increment and Decrement
6) Conditional
7) Bitwise
8) Special
Arithmetic Operator
They are used to perform simple arithmetic
operations on primitive data types.
* : Multiplication
/ : Division
% : Modulo
+ : Addition
– : Subtraction
Relational Operator
These operators are used to check for
relations like equality, greater than, less than.
They return boolean result after the
comparison and are extensively used in
looping statements as well as conditional if
else statements.
Relational Operator ==, Equal to : returns true of left hand side is equal to
right hand side.
!=, Not Equal to : returns true of left hand side is not
equal to right hand side.
<, less than : returns true of left hand side is less than
right hand side.
<=, less than or equal to : returns true of left hand side
is less than or equal to right hand side.
>, Greater than : returns true of left hand side is greater
than right hand side.
>=, Greater than or equal to: returns true of left hand
side is greater than or equal to right hand side.
Logical Operator
These operators are used to perform “logical AND” and
“logical OR” operation, i.e. the function similar to AND
gate and OR gate in digital electronics.
&&, Logical AND : returns true when both conditions
are true.
||, Logical OR : returns true if at least one condition is
true.
Assignment Operator
Assignment operator is used to assign a value to any
variable. It has a right to left associativity, i.e value given on
right hand side of operator is assigned to the variable on
the left and therefore right hand side value must be
declared before using it or should be a constant.
Eg: variable = value;
Assignment Operator
+=, for adding left operand with right operand and then
assigning it to variable on the left.
-=, for subtracting left operand with right operand and
then assigning it to variable on the left.
*=, for multiplying left operand with right operand and
then assigning it to variable on the left.
/=, for dividing left operand with right operand and then
assigning it to variable on the left.
%=, for assigning modulo of left operand with right
operand and then assigning it to variable on the left.
Increment && Decrement Operator
Increment Operator : It is used to increment a value by 1.
There are two varieties of increment operator:
Post-Increment (i++) : Value is first used for computing
the result and then incremented.
Pre-Increment (++i) :Value is incremented first and
then result is computed.
Decrement Operator : It is used for decrementing the
value by 1. There are two varieties of decrement operator.
Post-decrement (i--) :Value is first used for computing
the result and then decremented.
Pre-decrement (--i) :Value is decremented first and
then result is computed.
Increment && Decrement Operator
public class Test {
public static void main(String[] args)
{
int a = 10;
int b = ++a;
System.out.println(b);
}
}
Conditional Operator
The character pair ? : is a ternary operator
available in Java. This operator is used to
construct conditional expression of the
form
exp1 ? exp2 : exp3
Example :
a= 10; b= 15;
x= (a >b) ? a : b
Bitwise Operator
These operators are used to perform manipulation of individual bits of a number. They can be used with any of the integer types.
&, Bitwise AND operator: returns bit by bit AND of input values.
|, Bitwise OR operator: returns bit by bit OR of input values.
^, Bitwise XOR operator: returns bit by bit XOR of input values.
~, Bitwise Complement Operator: This is a unary operator which returns the one’s compliment representation of the input value, i.e. with all bits inversed.
Special Operator
Java supports some special operators such as
instance of operator and member selection
operator (.)
The instance of is an object reference operator
and returns true if the object on the left hand
side is an instance of the class given on the right
hand side. The operator allows us to determine
whether the object belongs to a particular class
or not.
Eg : employee.age //reference to variable age
Employee.salary() //reference to method salary
If statement in java
The Java if statement tests the condition. It
executes the if block if condition is true.
Syntax :
if(condition){
//code to be executed
}
If statement in java
public class IfExample {
public static void main(String[] args) {
//defining an 'age' variable
int age=20;
//checking the age
if(age>18){
System.out.print("Age is greater than 18);
}
}
}
If- else statement in java
The Java if-else statement also tests the
condition. It executes the if block if
condition is true otherwise else block is
executed.
if(condition){
//code if condition is true
}else{
//code if condition is false
}
If- else-if ladder in java The if-else-if ladder statement executes one
condition from multiple statements.
if(condition1){
//code to be executed if condition1 is true
}else if(condition2){
//code to be executed if condition2 is true
}
else if(condition3){
//code to be executed if condition3 is true
}
...
else{
//code to be executed if all the conditions are false
}
Nested if in java
The nested if statement represents the if
block within another if block. Here, the inner
if block condition executes only when
outer if block condition is true.
if(condition){
//code to be executed
if(condition){
//code to be executed
}
}
While loop in java
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.
while(condition){
//code to be executed
}
Do While loop in java
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.
do{
//code to be executed
}while(condition);
For loop in java
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.
for(initialization;condition;incr/decr){
//statement or code to be executed
}
Switch statement in java
The Java switch statement executes one statement from multiple conditions.
switch(expression){
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
......
default:
code to be executed if all cases are not matched;
}
break statement in java
When a break statement is encountered
inside a loop, the loop is immediately
terminated and the program control
resumes at the next statement following
the loop.
jump-statement;
break;
continue statement in java
The continue statement is used in loop
control structure when you need to jump
to the next iteration of the loop
immediately. It can be used with for loop
or while loop.
jump-statement;
continue;
Constructor in Java
Constructors are used to allocate memory
to the object in heap memory.
It is a member method
It has same name as class name
It does not return anything
It gets automatically called
Parameterized Constructor
A constructor that has parameters is
known as parameterized constructor. If we
want to initialize fields of the class with
your own values, then use a parameterized
constructor.
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
class Subclass-name extends Superclass-name
{
//methods and fields
}
The extends keyword indicates that you are
making a new class that derives from an existing
class. The meaning of "extends" is to increase the
functionality.
Super keyword in java
The super keyword in Java is a reference
variable which is used to refer immediate
parent class object.
Whenever you create the instance of
subclass, an instance of parent class is
created implicitly which is referred by
super reference variable.
Usage Super keyword in java
It is used to call immediate parent class
instance variables
It is used to call immediate parent class
methods
It is used to call immediate parent class
constructor
String Manipulation in Java
Strings, which are widely used in Java
programming, are a sequence of characters.
Syntax : String stringname;
String greeting = "Hello world!";
String Array :
Syntax : String arrayname[] = new String[3];
char charArray[] = new char[4]
charArray[0]=’J’
charArray[1]=’A’
charArray[2]=’V’
charArray[3]=’A’
String Methods
s2= s1.toLowerCase – Converts the string s1 to
all lowercase
s2=s1.toUpperCase – Converts the string s1 to
all uppercase
s2=s1.replace(‘x’, ‘y’) – Replaces all appearances
of x with y
s2=s1.trim() – Remove white spaces at the
beginning and end of the string s1
s1.equals(s2) – Returns true if s1 is equal to s2
s1.length()- Gives the length of s1
s1.charAt(n) – Gives the nth character of
s1
s1.compareTo(s2) – Returns negative if s1
< s2, positive if s1>s2 and zero if s1 is
equal to s2
s1.concat(s2) - Concatenates s1 and s2
s1.substring(n)- Gives substring starting
from nth character
s1.substring(n,m)- Gives substring
starting from nth character up to mth
String.valueOf(variable) – Converts the
parameter value to string representation
S1.equalsIgnoreCase(s2) – Returns true if s1 =
s2,ignoring the rest of the unequal cases
S1.toString() – Create a string representation of
the object s1
S1.indexOf(x) – Gives the position of the first
occurrence of ‘x’ in the string s1
S1.indexOf(‘x’,n) – Gives the position of x that
occurs after nth position in the string s1
String Tokenizers
The java.util.StringTokenizer class
allows an application to break a string
into tokens.
import java.util.StringTokenizer;
public class Main
{
public static void main(String[] args) {
StringTokenizer st1 = new StringTokenizer("Hi! I am good. How about you?");
for (int i = 1; st1.hasMoreTokens(); i++)
{
System.out.println("Token "+i+":“ +st1.nextToken());
}
}
}
String Buffer
Java StringBuffer class is used to create
mutable (modifiable) string. The
StringBuffer class in java is same as String
class except it is mutable i.e. it can be
changed.
We can use StringBuffer to append,
reverse, replace, concatenate and
manipulate Strings or sequence of
characters.
StringBuffer append() method
class StringBufferExample{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello”);
sb.append("Java");//now original string is change
d
System.out.println(sb);//prints Hello Java
}
}
StringBuffer insert() method
class StringBufferExample2{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello ");
sb.insert(1,"Java");//now original string is chang
ed
System.out.println(sb);//prints HJavaello
}
}
StringBuffer replace() method
class StringBufferExample3{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.replace(1,2,"Java");
System.out.println(sb);//prints HJallo
}
}
StringBuffer delete() method
class StringBufferExample4{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.delete(1,3);
System.out.println(sb);//prints Hlo
}
}
StringBuffer reverse() method
class StringBufferExample5{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.reverse();
System.out.println(sb);//prints olleH
}
}
StringBuffer capacity() method
The capacity() method of StringBuffer class
returns the current capacity of the buffer. The
default capacity of the buffer is 16. If the
number of character increases from its current
capacity, it increases the capacity by
(oldcapacity*2)+2. For example if your current
capacity is 16, it will be (16*2)+2=34.
class StringBufferExample6{
public static void main(String args[]){
StringBuffer sb=new StringBuffer();
System.out.println(sb.capacity());//default 16
sb.append("Hello");
System.out.println(sb.capacity());//
sb.append("java is my favourite language");
System.out.println(sb.capacity());//now (16*2)+
2=34 i.e (oldcapacity*2)+2
}
}
Polymorphism
Polymorphism is the ability of an object to take on many forms. The most common use of polymorphism in OOP occurs when a parent class reference is used to refer to a child class object.
Types of polymorphism
1) Static Polymorphism
2) Dynamic Polymorphism
Method Overloading (Static Poly.)
A function with same name same class but different
arguments. Also known as compile time polymorphism
Abstraction in Java
A class which is declared with the abstract
keyword is known as an abstract class in
Java.
It can have abstract and non-abstract
methods.
An abstract class cannot have objects.
Non - Abstract Methods
A method which is defined is a non-
abstract method.
Example:
public void call()
{
System.out.println(“Calling”);
}
Abstract Methods
A method which is declared is an abstract method.
Example:
abstract class Mobile
{
public void call()
{System.out.println(“Calling”);
}
abstract void dance(); // abstract method
}
Packages
Package in java is a mechanism to encapsulate a group of
classes, sub packages and interfaces.
Built-in Packages These packages consist of a large number of classes
which are a part of Java API. Some of the commonly
used built-in packages are:
1) java.lang: Contains language support classes(e.g
classed which defines primitive data types, math
operations). This package is automatically imported.
2) java.io: Contains classed for supporting input /
output operations.
3) java.util: Contains utility classes which implement
data structures like Linked List, Dictionary and support
; for Date / Time operations.
4) java.applet: Contains classes for
creating Applets.
5) java.awt: Contain classes for
implementing the components for
graphical user interfaces (like button ,
;menus etc).
6) java.net: Contain classes for
supporting networking operations.
Encapsulation
Encapsulation in Java is a mechanism of wrapping
the data (variables) and code acting on the data
(methods) together as a single unit. In
encapsulation, the variables of a class will be
hidden from other classes, and can be accessed
only through the methods of their current class.
Therefore, it is also known as data hiding.
Public member
If we declare a method as public, then we
can access that member from anywhere
but corresponding class should be public.
How to access public class from
another class?
First we need to import the package.
In our case it was
javaapplication1.newpackage -> Only
then we can extend NewClass.java file and
use the variable abc defined as public in
JavaApplication1.java file.
Default member
If a member is declared as default, then we
can access that member only within
current package & we can’t access from
outside of package.
Default access also known as package level
access.
Here the default member is rollno
accessible only in same package subclass
and non-subclass.
Protected member
If a member is declared as protected, then we can access
that member within current package anywhere, but
outside the package only in child class and not in main
class.
Within current package, we can access protected
members either by parent reference or by child
reference.
Outside package, we can access protected members only
by giving child reference.
Here we have protected member shown in main class as
int caseno which is accessible from different subclasses
within the package as well as outside the package
Private member
If a member is declared as private, then we can
access that member only within the current class.
Interfaces
Since multiple inheritance is not possible in java we have the concept of interfaces.
A Java class can implement multiple Java Interfaces.
Syntax:
interface <interface-name>
{
//methods
} All methods in an interface are implicitly public and abstract.