0% found this document useful (0 votes)
9 views48 pages

Java_Chapter_1

Chapter 1 covers the basic syntactical constructs of Java, including its features such as being compiled and interpreted, platform independence, object-oriented nature, robustness, and dynamic capabilities. It also outlines the Java programming environment, including the Java Development Kit (JDK), Java Runtime Environment (JRE), and Java Virtual Machine (JVM), along with the process of defining classes, creating objects, and accessing methods. Additionally, the chapter discusses Java tokens, constants, variables, and their scopes.

Uploaded by

anuprajput8605
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
9 views48 pages

Java_Chapter_1

Chapter 1 covers the basic syntactical constructs of Java, including its features such as being compiled and interpreted, platform independence, object-oriented nature, robustness, and dynamic capabilities. It also outlines the Java programming environment, including the Java Development Kit (JDK), Java Runtime Environment (JRE), and Java Virtual Machine (JVM), along with the process of defining classes, creating objects, and accessing methods. Additionally, the chapter discusses Java tokens, constants, variables, and their scopes.

Uploaded by

anuprajput8605
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 48

Basic Syntactical Construct in 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.

Source Code compiler Byte Code

 Java interpreter generates machine code that can directly executed by


machine i.e. running the java program

Byte Code Interpreted Machine Code

2) Platform Independent and Portable


 Java program can be easily move from one computer system to another
, anywhere and anytime. Changes and upgrades in system resources will
not force any change in java program.
 Java insures “Portability” in two ways-
i. Java compiler generates byte code instructions that can be
implemented on any machine.
ii. The size of primitive datatype are machine independent.
3) Object Oriented
 Java is object oriented language all program code & data resides within
object & classes. Java comes with expensive set of classes arranged in
package that can use in our program by inheritance.
4) Robust and Secure

 Java is more robust language. It provides many protection to insure


reliable(trustful) code. It has strict compile time and run time checking
for data type.
 It is design as a garbage collected language which relives the
programmer all memory management problem.
 The concept of exception handling which captured serious error and
eliminate any risk of crashing entire system
 Java is used for programming on internet .Threads of virus and abuses of
resources are everywhere, Java system not only verify all memory access
but also ensures that no virus are communicated with an applet.
 The absence of pointer in java ensures that programs cannot gain access
to memory location without proper authorization.
5) Dynamic
 Java enable Dynamic linking in new class libraries , methods and object.
Java program support functioning other languages such as c and c++
language .These functions are known as “Native method “.
 This facility enables the programmer to use efficient function available in
these languages
 Native Methods linked dynamically at runtime.

* Java Programming Environment


Java environment include large number of development tools and
hundreds of classes and methods. The development tools are part of Java
Standard libraries (JSL) also known as Application Programming Interface
(API).

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 interpreter which runs applet and application by reading and


interpreting byte code files.
4) javap (java disassembler)

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)

It produce header file for used with native methods.


6) jdb (java debugger)

Java debugger which help us to find errors in our program.


7) javadoc (for creating HTML format document)

It creates HTML format documentation from java source file.


Application Program Interface (API)
 Java Standard Libraries include hundreds of classes and methods group
into several functional packages. Like
Language support packages
 Utilities packages
 Input output packages
 Networking packages
 AWT packages
 Applet packages
2) Java Runtime Environment (JRE)

 Java runtime environment contain JVM which is responsible for running


the java program. JDK itself contain JRE in order to run program after
development
 End user only uses JRE because end user only required to run program
instead of development.
3) Java Virtual Machine (JVM)

 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 ,Creating Object, and Accessing methods

 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:

ClassName object = new ClassName();

Rectangle rec;
Declare NULL

Instantiate rec = new Rectangle() rec

rec is reference to Rectangle class object. Rectangle Object

Both statement can be combine as


For eg. Rectangle rec= new Rectangle();

Accessing Methods of class


 The object is used to invoke the method. method can be directly access
from the class where it is define.
 From outside the class instance variable and method cannot be
accessed directly. To do this object and (.) operator is required.
 Method can be access from outside of the class using dot (.) operator
along with the object as follows-
Object_name.variable_name= value;
Or for method
Object_name.methodName();

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.

abstract Assert boolean break byte


case Catch char class const*
continue Default do double else
enum Extends final finally float
For goto* if implements import
instanceof Int interface long native
New Package private protected public
return Short static strictfp super
switch Synchronized this throw throws
transient Try void volatile while

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

for eg- 10 , 205 , 786


b) floating point literals

for eg- 81.90 , 79.43, 91.18


c) character literals

for eg- ‘A’ , ‘E’ , ‘B’ .


d) string literals

for eg- “dhule”


e) boolean literals

for eg- true , false

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

Numeric Constant Non -Numeric Constant

Integer Real Single character String


constant constant 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

1) Single Character Constant –


Single character constant contain a single character enclosed within
single quate (‘ ‘).
For eg .- ‘a’ ,’7’ , ‘@’ , ‘$’ .

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”.

* Back Slash Character Constant

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 .

Constant Meaning Constant Meaning


\n New Line \t Horizontal tab
\v Vertical Line \b Back Space
\r Carriage return \a Alert
\” Double quate \’ Single quate
\\ Back slash \? Question Mark

* 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 .

Syntax- Final datatype variable_name= value ;


For eg - Final float PI =3.14159;

* 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

Process of giving initial value to a variable is known as initialization, the


variable is automatically initialize with 0 if not assign any other value.
Syntax- datatype variable_name= value;
For eg. -int age= 20;
Scope of Variables in Java

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

Numeric Non-Numeric Array class interface

Integer Real Character boolean

byte float true(1)


short double false(0)
int
long

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

Data Type Default Value Default size

Boolean False 1 bit

Char '\u0000' 2 byte

Byte 0 1 byte

Short 0 2 byte

Int 0 4 byte

Long 0L 8 byte

Float 0.0f 4 byte

double 0.0d 8 byte

Operators in Java

Operator in Java is a symbol that is used to perform operations. For example: +,


-, *, / etc.

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

+ (Addition) Adds values on either side of the operator.

Subtracts right-hand operand from left-hand


- (Subtraction)
operand.
* (Multiplication) Multiplies values on either side of the operator.

/ (Division) Divides left-hand operand by right-hand operand.

Divides left-hand operand by right-hand operand


% (Modulus)
and returns remainder.
The Relational Operators
There are following relational operators supported by Java language.
Assume variable A holds 10 and variable B holds 20, then −

Operator Description Example

Checks if the values of two operands are equal or (A == B) is


== (equal to)
not, if yes then condition becomes true. not true.

Checks if the values of two operands are equal or


!= (not (A != B) is
not, if values are not equal then condition
equal true.
becomes true.
to)
Checks if the value of left operand is greater than
(A > B) is not
> (greater than) the value of right operand, if yes then condition
true.
becomes true.

Checks if the value of left operand is less than the


(A < B) is
< (less than) value of right operand, if yes then condition
true.
becomes true.

>= (greater Checks if the value of left operand is greater


(A >= B) is
than or than or equal to the value of right operand, if
not true.
equal to) yes then condition becomes true.

Checks if the value of left operand is less than or


<= (less than or (A <= B) is
equal to the value of right operand, if yes then
equal to) true.
condition becomes true.
Increment /Decrement Operator
Java has increment operator which add 1 and decrement operator which
subtract 1 to the operand. Both are unary operator.
This Operator has two forms

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

The Bitwise Operators


Java defines several bitwise operators, which can be applied to the int types
Bitwise operator works on bits and performs bit-by-bit operation.

Operator Description

& bitwise AND

| 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

a & b = 0000 1100


a | b = 0011 1101
a ^ b = 0011 0001
~a = 1100 0011
The Logical Operators

Operator Description Example

Called Logical AND operator. If all the


&& (logical and) conditions were true, then the result will (A && B) is false
be true.

Called Logical OR Operator. If any one of


|| (logical or) the condition become true, then the (A || B) is true
result will be true.

Called Logical NOT Operator. Use to


reverses the logical state of its operand. If
! (logical not) !(A && B) is true
a condition is true then Logical NOT
operator will make false.
Assignment Operators

Operator Description Example

Simple assignment operator. Assigns values from right side C=A+B


operands to left side operand. will assign
=
value of A
+ B into C

Add AND assignment operator. It adds right operand to C += A is


the left operand and assign the result to left operand. equivalent
+=
to C = C +
A

Subtract AND assignment operator. It subtracts right C -= A is


operand from the left operand and assign the result to left equivalent
-=
operand. to C = C –
A

Multiply AND assignment operator. It multiplies right C *= A is


operand with the left operand and assign the result to left equivalent
*=
operand. to C = C *
A

/= Divide AND assignment operator. It divides left operand C /= A is


with the right operand and assign the result to left equivalent
operand. to C = C /
A

Modulus AND assignment operator. It takes modulus using C %= A is


two operands and assign the result to left operand. equivalent
%=
to C = C %
A
C <<= 2 is
<<= Left shift AND assignment operator. same as C
= C << 2

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 {

public static void main(String args[]) {

Car a = new Car();


boolean result = a instanceof Car;
System.out.println( result );
}
}

Dot (.) Operator


The dot operator is used to access the instance variable method of the class. It
is use to access the classes and sub packages from package
For eg .
Person.getData();

* Precedence and Associativity of Operators


Operator precedence determines the grouping of terms in an expression. This
affects how an expression is evaluated. Certain operators have higher
precedence(priority) than others.
for example, the multiplication operator has higher precedence than the
addition operator −
For example, x = 7 + 3 * 2; here x is assigned 13, not 20 because operator * has
higher precedence than +, so it first gets multiplied with 3 * 2 and then adds into
7.Here, operators with the highest precedence appear at the top of the table,
those with the lowest appear at the bottom. Within an expression, higher
precedence operators will be evaluated first.
Associativity- when the multiple operators with similar precedence are
evaluated then the operation is executed with the particular sequence or order
is called Associativity.

Category Operator Associativity

Postfix a++ , b-- Left to right

Unary ++a , - -b Right to left

Multiplicative */% Left to right

Additive +- Left to right

Shift << >> >>> Left to right

Relational < > <= >= instanceof Left to right

Equality == != Left to right

Bitwise AND & Left to right

Bitwise XOR ^ Left to right

Bitwise OR | Left to right

Logical AND && Left to right

Logical OR || Left to right

Conditional ?: Right to left

Assignment = , += , -= , *= , /=, %=, ^= , |= , <<= ,>>= Right to left


Decision Making Statement
Decision Making in programming is similar to decision-making in real life. In
programming also face some situations where we want a certain block of
code to be executed when some condition is fulfilled.
A programming language uses control statements to control the flow of
execution of a program based on certain conditions. These are used to cause
the flow of execution to advance and branch based on changes to the state of
a program.

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;

case valueN: statementN;


break;
default: statementDefault;
}

* 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;

System.out.print(i + " ");


}
}
}

* 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

Looping in programming languages is a feature which facilitates the execution


of a set of instructions/functions repeatedly. Java provides three ways for
executing the loops. While all the ways provide similar basic functionality,
they differ in their syntax and condition checking time.
while loop

A while loop is a control flow statement that allows code to be executed


repeatedly based on a given Boolean condition. The while loop can be
thought of as a repeating if statement.
Syntax :
while (condition)
{
loop statements...
}
For eg.
class Demo
{
public static void main (String[] args)
{
int i=0;
while (i<=10)
{
System.out.println(i);
i++;
}
}
}

 While loop starts with the checking condition. If it evaluated to true,


then the loop body statements are executed otherwise first
statement following the loop is executed. For this reason it is also
called Entry control loop
 Once the condition is evaluated to true, the statements in the loop
body are executed. Normally the statements contain an update value
for the variable being processed for the next iteration.
 When the condition becomes false, the loop terminates which marks
the end of loop.
for loop
for loop provides a concise way of writing the loop structure. Unlike a while
loop, a for statement consumes the initialization, condition and
increment/decrement in one line thereby providing a shorter, easy to debug
structure of looping.
Syntax:
for (initialization condition; condition ;increment/decrement)
{
statement(s)
}

For eg.
class Demo
{
public static void main (String[] args)
{
for (int i=0;i<=10;i++)
{
System.out.println(i);
}
}
}

 Initialization condition: Here, we initialize the variable in use. It


marks the start of a for loop. An already declared variable can be
used or a variable can be declared, local to loop only.
 Testing Condition: It is used for testing the exit condition for a loop. It
is also an Entry Control Loop as the condition is checked prior to the
execution of the loop statements.
 Statement execution: Once the condition is evaluated to true, the
statements in the loop body are executed.
 Increment/ Decrement: It is used for updating the variable for next
iteration.
 Loop termination: When the condition becomes false, the loop
terminates marking the end of its life cycle.
do while loop
do while loop is similar to while loop with only difference that it checks for
condition after executing the statements, and therefore is an example
of Exit Control Loop.
Syntax
do
{
statements..
}
while (condition);

for eg.
class Demo
{
public static void main (String[] args)
{
int i=0;
do
{
System.out.println(i);
i++;
}while(i<=10);
}
}

 do while loop starts with the execution of the statement(s). There is no


checking of any condition for the first time.
 After the execution of the statements, and update of the variable
value, the condition is checked for true or false value. If it is evaluated
to true, next iteration of loop starts.
 When the condition becomes false, the loop terminates which marks
the end of its life cycle.
 It is important to note that the do-while loop will execute its
statements atleast once before any condition is checked, and therefore
is an example of exit control loop.
For-each loop

For-each is another array traversing technique like for loop, while loop, do-
while loop introduced in Java5.

 It starts with the keyword for like a normal for-loop.


 Instead of declaring and initializing a loop counter variable, you declare
a variable that is the same type as the base type of the array, followed
by a colon, which is then followed by the array name.
 In the loop body, you can use the loop variable you created rather than
using an indexed array element.

It’s commonly used to iterate over an array


Syntax-
for (type var : array)
{
Body of loop;
;

}
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

Types of Array in java

There are two types of array.


i. Single Dimensional Array
ii. Multidimensional Array

Single-Dimensional Array in Java

A single-dimensional array in Java is a linear collection of elements of the same data


type which can be given one variable name and only one subscript.

Declaration Of Array

dataType arr[];
or
dataType []arr;

Memory Allocation of an Array in Java


arr=new datatype[size];

Declaration and Memory allocation can be combine in single statement


dataType arr[]=new datatype[size];
or
dataType []arr=new datatype[size];

Initialization of Java Array


int a[]=new int[5];//declaration and memory allocation
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
or
a[]={10,20,30,40,50};
Example
Let's see the simple example of java array, where we are going to declare, instantiate,
initialize and traverse an array.
class ArrayDemo
{
public static void main(String args[])
{
int a[]=new int[5];//declaration and instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=30;
a[3]=40;
a[4]=50;
for(int i=0;i<a.length;i++)//length is property of array which returns size of array
{
System.out.println(a[i]);
}
}
}
Output:
10
20
30
40
50

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);
}
}

Java String class provides a lot of methods to perform operations on strings

Methods
1. int length()
Returns the number of characters in the String.

2. Char charAt(int i)
Returns the character at ith index.

3. String subString (int i)


Return the substring from the ith index character to end.

4. String substring (int i, int j)


Returns the substring from i to j-1 index.
5. String concat( String str)
Concatenates specified string to the end of this string.

6. int indexOf (String s)


Returns the index within the string of the first occurrence of the specified string.
If String s is not present in input string then -1 is returned as the default value.

7. int indexOf (String s, int i)


Returns the index within the string of the first occurrence of the specified string,
starting at the specified index.

8. Int lastIndexOf( String s)


Returns the index within the string of the last occurrence of the specified string.
If String s is not present in input string then -1 is returned as the default value.

9. boolean equals( Object otherObj)


Compares this string to the specified object.

10. boolean equalsIgnoreCase (String anotherString)


Compares string to another string, ignoring case considerations.

11. String toLowerCase()


Converts all the characters in the String to lower case.

12. String toUpperCase()


Converts all the characters in the String to upper case.

13. String trim()


Returns the copy of the String, by removing whitespaces at both ends. It does not
affect whitespaces in the middle.

14. String replace (char oldChar, char newChar)


Returns new string by replacing all occurrences of oldChar with newChar.
StringBuffer Class

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.

1) Vector(): Creates a default vector of the initial capacity is 10.


Vector<E> v = new Vector<E>();

2) Vector(int size): Creates a vector whose initial capacity is specified by size.


Vector<E> v = new Vector<E>(int size);

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.

2) void addElement(E obj)


This method adds the specified component to the end of this vector, increasing its
size by one.

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.

10) void insertElementAt(E obj, int index)


This method inserts the specified object as a component in this vector at the
specified index.

11) boolean isEmpty()


This method tests if this vector has no components.

12) E lastElement()
This method returns the last component of the vector.

13) int lastIndexOf(Object o)


This method returns the index of the last occurrence of the specified element in
this vector, or -1 if this vector does not contain the element

14) E remove(int index)


This method removes the element at the specified position in this Vector

15) void removeAllElements()


This method removes all components from this vector and sets its size to zero

16) void setElementAt(E obj, int index)


This method sets the component at the specified index of this vector to be the
specified object

17) void setSize(int newSize)


This method sets the size of this vector

18) int size()


This method returns the number of components in this vector.

19) String toString()


This method returns a string representation of this Vector, containing the String
representation of each element.
Wrapper Class

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:

Primitive Type Wrapper class

boolean Boolean

char Character

byte Byte

short Short

int Integer

long Long

float Float

double Double

Instance Method of Wrapper Classes

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

In Java, a constructor is a block of codes similar to the method. It is called when an


instance of the class is created. At the time of calling constructor, memory for the
object is allocated in the memory.
It is a special type of method which is used to initialize the object.
Every time an object is created using the new keyword, at least one constructor is
called.
It calls a default constructor if there is no constructor available in the class. In such
case, Java compiler provides a default constructor by default.

Rules for Creating Java Constructor


There are following rules for defining a constructor:
1. Constructor name must be the same as its class name.
2. A Constructor must have no explicit return type.
3. A Java constructor cannot be abstract, static, final, and synchronized.

Types of Java Constructors


There are two types of constructors in Java:
1. Default Constructor
It calls a default constructor if there is no constructor available in the class. In
such case, Java compiler provides a default constructor by default.

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();
}
}

Parameterized Constructor Example


class Demo
{
int a,b;
Demo(int x, int y) //parameterized constructor
{
a=x;
b=y;
}
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();
}
}

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:

protected void finalize() throws Throwable


{
_________
_________
}

 The finalize() method is called by Garbage Collector, not JVM.


 The finalize() method is called only once per object.

Command Line Argument

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);
}
}

Complie through : javac CLArg.java


Run Through : java CLArg 79
(Enter number with running command )

Visibility Control /Access Specifier


The access specifiers in Java specifies the accessibility or scope of a field,
method, constructor, or class. We can change the access level of fields,
constructors, methods, and class by applying the access modifier on it.

There are five types of Java access specifiers :

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

You might also like