Java_Chapter_1
Java_Chapter_1
* Features of Java
1) Compile and Interpreted
Java combine both approaches compile and interpreted thus making
java two stage system.
Java compiler translate source code into byte code instructions, Byte
code instructions are not machine code instructions.
JVM
JRE
JDK
1) Java Development Kit
Java development kit comes with the collection of tools that are used for
developing and running java programs
1) appletviewer (for viewing java applets)
appletviewer are used for viewing java applet, it enables to run java a
pplet.
2) javac (java compiler)
Java compiler which translate java source code to byte code files that
the interpreter can understand.
3) java (java interpreter)
Java disassembler which enables us to convert the byte code file into
program description. This command displaying information about fields,
constructors & methods present in class file.
5) javah (java header for c header file)
All the programming language compiler translate the source code into
machine code. Java compiler also perform the same function. but the
difference is that java compiler produces the intermediate code known
as byte code for machine that does not exist.
This machine is called as Java Virtual Machine. It exits only inside the
computer memory. It is simulated computer and does all function of the
computer.
JVM is the one that actually call the main method present in java code
Defining a Class
Class is a user define data type they are primary and essential element
of a java program .Java program can contain multiple classes definition. The
number of classes used in program is depend upon the complexity of
program
Class is declared with class keyword which is object oriented construct
everything must be placed inside a class .Every class definition is begin with
“{ “and ends with “}".
Syntax of declaring class-
class ClassName
{
data_type variable_name; \\ instance variable
data_type variable_name2; \\instance variable
return_type methodName()
{
Body of method \\method declaration
}
}
Class is declared with class keyword and its body written in “{ “and “} “.
Class can contain variable and method definition also , all the variable
declare inside the class but outside the method are called as instance
variable of class , as methods and variable are written inside the class
they also called as member variable or member method of class.
Creating Object of Class
A class is a template or blueprint from which objects are created. So, an
object is the instance(result) of a class meaning it is a copy of a specific
class. Object can be created using the new keyword is the most popular
way to create an object or instance of the class. When we create an
instance of the class by using the new keyword, it allocates memory
(heap) for the newly created object and also returns the reference of
that object to that memory.
The syntax for creating an object is:
Rectangle rec;
Declare NULL
Where ,
Object_name is the name of object
Variable_name is the name of instance variable of class(i.e. the variables
which are declare inside the class but outside of the method)
methodName() is the name of method.
For eg.
class Demo
{
int a=30,b=40,c; // instance variable declaration
void add() // member method of class Demo
{
c=a+b;
System.out.println("Addition= "+c);
}
}
class DemoObject
{
public static void main (String args[])
{
Demo de= new Demo(); //object creation
de.add(); // method calling
}
}
* Java Tokens
“The smallest individual unit of program is called as token.”
Java program is collection of tokens, comments and whitespaces .
Java language include five types of tokens
i) Reserved Keywords.
ii)Identifier.
iii)Literals.
iv)Operator.
v)Separate.
i) Reserved Keywords-
“Keywords are the words whose meaning has already been
explain to the java compiler.”
Keywords are essential part of language definition. Java has 50 reserve
words as a keywords.
Keywords has specific meaning in java we can not used them as name of
variable, class, method and objects.
All keywords are written to be in lower case alphabets.
ii) Identifiers-
Identifier are programmer design tokens .They are used for name of
class, method, variable, object, labels, packages and interfaces in the java
program .
Rules for identifier
They can have alphabet, digit and only the special symbol of
underscore (_), dolor sign($)
They must not begin with digit
Uppercase(A-Z) and lowercase(a-z) are distinct i.e. different
They can be of any length
iii) Literals
“Literals in java are sequence of character (letter, digit & other
characters)that represent constant value to be store in variables.”
There are five type of literals.
a) integer literals
iv) Operator
“Operator is a special symbol that tells computer to perform certain
mathematical or logical operation.”
Operator is a symbol that takes one or more arguments(operands) and
operates on them to produce the result.
v) Separator
“Separator are symbol used to indicate where the group of code are
divided and arrange. They basically defined shape and function of our
code.”
a) [] Square bracket
used declare array types and for dereferencing array value.
For eg. Int a[]=new int [10];
b) () Parentheses
Used to enclosed parameters in method definition and invocation also
used for defining precedence expression and surrounding cast type.
For eg. add(int a)
c) {} Braces
defining a block of code for classes ,method and local scope.
d) ; Semicolon
used to separate statement.
e) , Comma
used to separate identity in variable declaration and also used to chain
statement together inside a for statement.
For eg. for(int i=1,j=2;i<10;i++,j++)
f) . Period
It is used to separate package name from sub packages and classes . It is
used to separate variables or method from reference variable.
For eg. Abc a1 Abc a1= new Abc();
a 1000 10000
10
reference variable created.
20
30
* Constant
Java Constant
“The constant reference to the fix value that do not change during program
execution.” Java support several types of constant
* Numeric Constant –
1) Integer Constant
An integer constant means sequence of digit .There are three types of
integer constant.
a) Decimal integer-
Decimal integer is consist of 0 to 9 digit combination set
For eg – 34, -91, 200
b) Octal Integer –
An octal integer constant are consist combination of digit from 0 to 7
with leading 0 (Zero).
For eg – 032, 04352
c) Hexadecimal Integer –
Hexadecimal integer a sequence of digit decided by OX or ox is consider
as Hexadecimal integer constant. They may include 0 to 9 and alphabet
From A to Z or a to z.
For eg – OX3456 , OXA23.
2) Real Constant
The number having fractional part are known as real numbers or floating
point constant.
A real number may also be express in exponential form
Floating point constant may consist of four parts – A whole number , decimal
point , fractional part and exponent
For eg –
0.65e4 , 12e-2
Exponential notation is useful for numbers that are either very large or very
small in magnitude.
For eg . (1) . 7500000000 will be written as 7.5 e 9
(2). -0.000000368 will be written as -3.68 e -7
* Non-Numeric Constant
2) String Constant-
String constant is sequence of character enclosed within double quate
(“ “).
The character may be alphabet , digit special character or blank space .
For eg – “Hello Java” , “2023”.
Java support some back slash character constant that are used in output
statement for getting more effect like tab , new line etc. This character
combination are also known as escape sequence .
* Symbolic Constant
Symbolic constant refers to the variables name having value which can
not be modify .
To distinguish from normal variable they can written in capital letter
after declaration of symbolic constant , they should not reassign any other
value . Symbolic constant are declare for type this is not done in C & C++ where
symbolic constant are define using #define statement .
They can not be declare inside a method . They should not be use only as class
data member in the beginning of class .
* Variable
A variable is a 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 affect that memory location.
In Java, all variables must be declared before use.
Declaration of variable
Syntax- datatype variable name;
For eg -int a;
float b;
Initialization of Variable
Scope of variable determine the life time of variable . It depends upon where
in program variable id declared. The area of program where variable is
accessible is called it’s scope.
1. Local Variables
2. Instance Variables
3. Static Variables
1. Local Variables
A variable defined within a block or method or constructor is called a local
variable.
These variables are created when the block is entered
The scope of these variables exists only within the block in which
the variables are declared, i.e we can access these variables only
within that block.
Initialization of the local variable is mandatory before using it in the
defined scope.
2. Instance Variables
Instance variables are non-static variables and are declared inside a class but
outside of any method, constructor, or block.
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.
Initialization of an instance variable is not mandatory. Its default
value is 0.
Instance variables can be accessed only by creating objects.
3. Static Variables
Static variables are also known as class variables.
These variables are declared similarly as instance variables. The
difference is that static variables are declared using the static
keyword within a class outside of any method, constructor or block.
we can only have one copy of a static variable per class, irrespective
of how many objects we create.
Static variables are created at the start of program execution and
destroyed automatically when execution ends.
Initialization of a static variable is not mandatory. Its default value is
0.
* Data Type
Data Types in Java
Primitive Non-Primitive
Type Casting
“Process of converting one data type into another one is called type casting.”
Typecasting occurs when there is need to store a value of one data type into a
variable of another data type
Casting is necessary when method returns a type different than one
required.
To type cast the value to be store by presiding it with type name in
parenthesis ().
Syntax-
Type variable1 = (type)variable2; For
eg.-
Float a=79.43f;
int b=(int)a;
Standard Default Values
Byte 0 1 byte
Short 0 2 byte
Int 0 4 byte
Long 0L 8 byte
Operators in Java
Arithmetic operators are used in mathematical expressions in the same way that
they are used in algebra. The following table lists the arithmetic operators −
Operator Description
a) Pre-fixed
A prefix operator first add or subtract 1 to the operand and then result is
assign to the variable on left hand side
For eg
x=5; x=5;
y=++x; y=--x;
x=6, y=6 x=4, y=4
a) Post-fixed
A postfix operator result is assign to the variable on left hand side and then
add or subtract 1 to the operand.
For eg
x=5; x=5;
y=x++; y=x--;
x=6, y=5 x=4, y=5
Operator Description
| bitwise OR
^ bitwise XOR
~ bitwise one’s compliment
<< (left Binary Left Shift Operator. The left operands value is
shift) moved left by the number of bits specified by the
right operand.
Binary Right Shift Operator. The left operands value is
>> (right moved right by the number of bits specified by the
shift) right operand.
Assume if a = 60 and b = 13; now in binary format they will be as follows −
a = 0011 1100
b = 0000 1101
Conditional Operator ( ? : )
Conditional operator is also known 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
Example
class Test
{
public static void main(String args[])
{
int a, b;
a = 10;
b = (a == 10) ? 20: 30;
System.out.println( "Value of b is : " + b );
}
}
instanceof Operator
This operator is used only for object reference variables. The operator checks
whether the object is of a particular class .
instanceof operator is written as −
( Object reference variable ) instanceof (classname)
If the object referred by the variable on the left side of the operator is object of
class on the right side, then the result will be true , otherwise result will be false.
Example
class car
{
`void display()
{
System.out.println(“inside car class”);
}
}
class Vehicle {
1) if statement
if statement is the most simple decision-making statement. It is used
to decide whether a certain statement or block of statements will be
executed or not i.e if a certain condition is true then a true block of
statements is executed otherwise not. Control goes to statement x
which is next immediate to if block.
Syntax-
if(condition)
{
// true block Statements
// condition is true
}
Statement x;
if the value is true then it will execute the block of statements under
it.
If we do not provide the curly braces ‘{‘ and ‘}’ after if( condition
) then by default if statement will consider the immediate one
statement to be inside its block.
2) if-else:
if else is the another decision making statement where if the
condition is true then the true block of statement will be executed
otherwise else block will be executed. And flow of control will be
transfer to the statement x .
Syntax:
if (condition)
{
// condition is true
}
else
{
// condition is false
}
Statement x;
For eg.
class Demo
{
public static void main(String args[])
{
int i = 10;
if (i < 15)
System.out.println(i+" is smaller than 15");
else
System.out.println(i+"is greater than 15");
}
}
3. nested-if:
A nested if is an if statement that is the target of another if or else.
Nested if statements mean an if statement inside an if statement.
Yes, java allows us to nest if statements within if statements. i.e, we
can place an if statement inside another if statement.
Syntax:
if (condition1)
{
// Executes when condition1 is true
if (condition2)
{
// Executes when condition2 is true
}
}
For eg.
import java.util.*;
class Demo
{
public static void main(String args[])
{
int i = 10;
if (i == 10 || i<15)
{
if (i < 15)
{
System.out.println(i+"is smaller than 15");
}
if (i < 12)
{
System.out.println(i+”is smaller than 12 too”);
}
}
else
{
System.out.println(i+”is greater than 15");
}
}
}
4. else-if or ladder if :
Here, a user can decide among multiple options. The if statements
are executed from the top down. As soon as one of the conditions
controlling the if is true, the statement associated with that ‘if’ is
executed, and the rest of the ladder is bypassed. If none of the
conditions is true, then the final else statement will be executed.
There can be as many as ‘else if’ blocks associated with one ‘if’ block
but only one ‘else’ block is allowed with one ‘if’ block.
Syntax-
if (condition)
statement;
else if (condition)
statement;
else
statement x;
For eg.
class Demo {
public static void main(String args[])
{
int i = 20;
if (i == 10)
{
System.out.println("i is 10");
}
else if (i == 15)
{
System.out.println("i is 15");
}
else if (i == 20)
{
System.out.println("i is 20");
}
else
{
System.out.println("i is not present");
}
}
}
*switch-case:
The switch statement is a multiway branch statement. It provides an easy
way to dispatch execution to different parts of code based on the value of the
expression.
Syntax:
switch (expression)
{
case value1: statement1;
break;
case value2: statement2;
break;
* continue Statement :
Sometimes it is useful to force an early iteration of a loop. That is, you might
want to continue running the loop but stop processing the remainder of the
code in its body for this particular iteration. continue statement performs
such an action.
class ContinueDemo
{
public static void main(String args[])
{
for (int i = 0; i < 10; i++)
{
if (i % 2 == 0)
continue;
* break Statement
While working with loops, it is sometimes desirable to skip some statements
inside the loop or terminate the loop immediately without checking the test
expression.
The break statement in Java terminates the loop immediately, and the control
of the program moves to the next statement following the loop.
It is almost always used with decision-making statements.
Looping Statements
For eg.
class Demo
{
public static void main (String[] args)
{
for (int i=0;i<=10;i++)
{
System.out.println(i);
}
}
}
for eg.
class Demo
{
public static void main (String[] args)
{
int i=0;
do
{
System.out.println(i);
i++;
}while(i<=10);
}
}
For-each is another array traversing technique like for loop, while loop, do-
while loop introduced in Java5.
}
For eg.
class Easy
{
public static void main(String[] args)
{
int ar[] = { 10, 50, 60, 80, 90 };
for (int element : ar)
{
System.out.print(element + " ");
}
}
}
Arrays
An array is typically a grouping of elements of the same kind that are stored in a single,
contiguous block of memory. An Array is a collection of similar or homogeneous or
related data type of elements which are stored in continues memory location
Array can be of any type and may have one or many dimensions ,specific element can
be access by index position
Declaration Of Array
dataType arr[];
or
dataType []arr;
Note: ArrayIndexOutOfBoundsException
In Java, the ArrayIndexOutOfBoundsException is a runtime exception thrown by the
Java Virtual Machine (JVM) when attempting to access an invalid index of an array.
This exception occurs if the index is negative, equal to the size of the array, or greater
than the size of the array while traversing the array.
String
String is basically an object that represents sequence of char values. In Java, objects of
the String class are immutable which means they cannot be changed once created.
Creating a String
There are two ways to create string in Java:
1. Using String literal
String s = “Java”;
2. Using new keyword
String s = new String (“Java”);
Example:
class StringDemo
{
public static void main (String[] args)
{
String s1="Java";
System.out.println(s1);
String s2= new String("Programming ");
System.out.println(s2);
}
}
Methods
1. int length()
Returns the number of characters in the String.
2. Char charAt(int i)
Returns the character at ith index.
String create string of fixed length and StringBuffer created string of flexible length
that can be modify so it is called as mutable class .
Java StringBuffer class is used to create mutable (modifiable) String objects. The
StringBuffer class in Java is the same as String class but it is mutable i.e. it can be
changed after creation of String.
Constructor
1) StringBuffer()
It creates an empty String buffer with the initial capacity of 16.
2) StringBuffer(String str)
It creates a String buffer with the specified string plus 16 block of memory.
3) StringBuffer(int capacity)
It creates an empty String buffer with the specified capacity as length plus 16
block of memory.
Methods
1) append()
Used to add text at the end of the existing text.
2) length()
The length of a StringBuffer can be found by the length( ) method.
3) capacity()
the total allocated capacity can be found by the capacity( ) method.
4) charAt()
This method returns the char value in this sequence at the specified index.
5) delete()
Deletes a sequence of characters from the invoking object.
6) deleteCharAt()
Deletes the character at the index specified by the loc.
7) insert()
Inserts text at the specified index position.
8) length()
Returns the length of the string.
10)reverse()
Reverse the characters within a StringBuffer object.
11)replace()
Replace one set of characters with another set inside a StringBuffer object.
Vector
Vector is like the dynamic array which can grow or shrink its size. Unlike array, we
can store n-number of elements in it as there is no size limit.
3) Vector(int size, int incr): Creates a vector whose initial capacity is specified by
size and increment is specified by incr. It specifies the number of elements to
allocate each time a vector is resized upward.
Vector<E> v = new Vector<E>(int size, int incr);
Methods
1) boolean add(E e)
This method appends the specified element to the end of this Vector.
3) int capacity()
This method returns the current capacity of this vector.
4) void clear()
This method removes all of the elements from this vector.
5) E elementAt(int index)
This method returns the component at the specified index.
6) boolean equals(Object o)
This method compares the specified Object with this Vector for equality.
7) E firstElement()
This method returns the first component (the item at index 0) of this vector.
8) E get(int index)
This method returns the element at the specified position in this Vector.
9) int indexOf(Object o)
This method returns the index of the first occurrence of the specified element in
this vector, or -1 if this vector does not contain the element.
12) E lastElement()
This method returns the last component of the vector.
Wrapper classes provide a way to use primitive data as objects. Wrapper class is
wrapper around primitive data types ,in Java 8 data types have dedicated to it this is
known as wrapper class .
The wrapper class are part of java.lang package which is imported by default in java
program by compiler .
Many built in classes work only with object in java (like Vector) for converting this data
types into objects Wrapper Classes are used in program .
The table below shows the primitive type and the equivalent wrapper class:
boolean Boolean
char Character
byte Byte
short Short
int Integer
long Long
float Float
double Double
1) byte byteValue()
returns the Byte object into byte primitive data type
2) short shortValue()
returns the Short object into short primitive data type
3) int intValue()
returns the Integer object into int primitive data type
4) float floatValue()
returns the Float object into float primitive data type
5) long longValue()
returns the Long object into long primitive data type
6) double doubleValue()
returns the Double object into double primitive data type
Constructor
2. Parameterized Constructor
When Parameters are added to the constructor or constructor takes parameters
is called as parameterized constructor
Example:
class Demo
{
int a,b;
Demo() //constructor
{
a=10;
b=20;
}
void add()
{
System.out.println(“Add=”+(a+b));
}
}
class Demo2
{
public static void main(String args[])
{
Demo d1=new Demo(); //calling to constructor
d1.add();
}
}
Use Of ‘this’
It may possible a local variable has same name as instance variable ,it will
produce ambiguity to name of local and instance variable to solve this problem
‘this’ can be used inside any method or constructor to refer the current object
i.e ‘this’ is always a reference to the object
For Example :
class Demo
{
int a,b;
Demo(int a, int b) //constructor
{
this.a=a; //this.a indicate that a is instance variable and only a is
//local variable
this.b=b; //this.b indicate that b is instance variable and only b is
//local variable
}
void add()
{
System.out.println(“Add=”+(a+b));
}
}
class Demo2
{
public static void main(String args[])
{
Demo d1=new Demo(10,20); //calling to constructor
d1.add();
}
}
Constructor Overloading
Like method constructor can be overloaded ,since the multiple constructor in a class
have same names as the class name and their signature are differ by parameter list
i.e when a class contain more than one constructor then it is called as constructor
overloading
for eg.
class Demo
{
int a,b;
Demo(int x, int y) //parameterized constructor
{
a=x;
b=y;
}
Demo() //normal constructor
{
a=30;
b=40;
}
void add()
{
System.out.println(“Add=”+(a+b));
}
}
class Demo2
{
public static void main(String args[])
{
Demo d1=new Demo(); //call to normal constructor
Demo d2=new Demo(10,20); //call to parametrized constructor
d1.add();
d2.add();
}
}
Garbage Collection
Garbage collection in Java is an automatic memory management process that helps
Java programs run efficiently. Java programs compile to bytecode that can be run on a
Java Virtual Machine (JVM). When Java programs run on the JVM, objects in the heap,
which is a portion of memory dedicated to the program. Eventually, some objects will
no longer be needed. The garbage collector finds these unused objects and deletes
them to free up memory.
In C/C++, programmers have to manually create and delete objects, which can
sometimes lead to memory leaks and errors when there isn’t enough memory
available. This happens when unused objects are not deleted properly.
In Java, this process is automated. The garbage collector automatically finds and
removes objects that are no longer needed, freeing up memory in the heap.
Finalization
Before destroying an object, the garbage collector calls the finalize() method to
perform cleanup activities. The method is defined in the Object class as follows:
Java command-line argument is an argument i.e. passed at the time of running the
Java program. In Java, the command line arguments passed from the console can be
received in the Java program and they can be used as input. The users can pass the
arguments during the execution bypassing the command-line arguments inside the
main() method.
For Example
class CLArg
{
public static void main(String args[])
{
int n;
n=Integer.parseInt(args[0]);
System.out.println(“n= “+n);
}
}
Private: The access level of a private modifier is only within the class. It cannot be
accessed from outside the class.
Default: The access level of a default modifier is only within the package. It cannot be
accessed from outside the package. If you do not specify any access level, it will be the
default it is also called as friendly access specifier or visibility mode .
Protected: The access level of a protected modifier is within the package and outside
the package through child class. If you do not make the child class, it cannot be
accessed from outside the package.
Public: The access level of a public modifier is everywhere. It can be accessed from
within the class, outside the class, within the package and outside the package.
Private protected :This modifier makes the field visible in all subclasses regardless of
what package they are in .
Access Same class Sub class in Other class Sub class in Other class
Modifier same in same other in other
package package package package
Private Y N N N N
Default Y Y N N N
Protected Y Y Y Y N
Public Y Y Y Y Y
Private Y Y N Y N
Protected