Java Unit-1 Chapter2
Java Unit-1 Chapter2
JVM, first of all, loads the code into memory and verifies it. After that, it
executes the code and provides a runtime environment. Java Virtual
Machine (JVM) has its own architecture, which is given below:
JVM Architecture
Class Method Area: In the memory, there is an area where the class
data is stored during the code's execution. Class method area holds the
information of static variables, static methods, static blocks, and instance
methods.
Heap: The heap area is a part of the JVM memory and is created when
the JVM starts up. Its size cannot be static because it increase or decrease
during the application runs.
Native Stack: It contains the information of all the native methods used
in our application.
Execution Engine: It is the central part of the JVM. Its main task is to
execute the byte code and execute the Java classes. The execution engine
has three main components used for executing Java classes.
Primitive Types
Floating-Point types
The floating-point types denote numbers with fractional parts.
Type Storage Range
Requirement
float 4 bytes Approximately +-
3.4028347E+38F (6-7
significant decimal digits)
double 8 bytes Approximately +-
1.79769313486231570E+308(15
significant decimal digits)
Booleans
6.Variables
Variable Declarations
Java is a strongly typed language. Each variable can only hold
values of a specific type.
Following is the general form of a variable declaration:
type var-name;
Here, type specifies the type of variable being declared, and var-name
is the name of the variable. If you want to declare more than one
variable of the specified type, you may use a comma-separated list of
variable names. When you declare a variable, you need to specify the
type, the name, and an optional initial value.
For example,
int total = 0;
You can declare multiple variables of the same type in a
single statement:
int total = 0, count; // count is an uninitialized integer
Most Java programmers prefer to use separate
declarations for each variable. The name of a variable (as
well as a method or class) must begin with a letter. It can
consist of any letters, digits, and the symbols _ and $.
However, the $ symbol is intended for automatically
generated names, and you should not use it in your
names. Finally, the _ by itself is not a valid variable
name.
You cannot use spaces or symbols in a name. Finally,
you cannot use a keyword such as double as a name.
By convention, names of variables and methods start
with a lowercase letter, and names of classes start with
an uppercase letter. Java programmers like “camel
case,” where uppercase letters are used when names
consist of multiple words, like CountOfInvalidInputs.
Variable Initialization
When you declare a variable in a method, you must
initialize it before you can use it. For example, the following
code results in a compile-time error:
int count;
count++; // Error—uses an uninitialized variable
The compiler must be able to verify that a variable has been
initialized before it has been used. The variable is declared
at the point at which its initial value is available.
Constants
The final keyword denotes a value that cannot be changed
once it has been assigned. In other languages, one would
call such a value a constant. For example,
class Area
{
double pi, r, a;
a = pi * r * r; // compute area
boolean b;
b = false;
b = true;
b = false;
7.Arithmetic Operations
Java uses the familiar operators of any C-based language. We will
review them in the following sections.
Operators Associativity
[] . () (method call) Left
! ~ ++ -- + (unary) - Right
(unary) () (cast) new
* / % (modulus) Left
+ - Left
Assignment Operator
The statement
x = expression;
sets x to the value of the right-hand side, replacing the previous
value. When = is preceded by an operator, the operator
combines the left- and right-hand sides and the result is
assigned. For example,
amount -= 10;
is the same as
amount = amount - 10;
Relational Operators
The relational operators determine the relationship that
one operand has to the other. Specifically, they determine
equality and ordering. There are six relational operators ==
(Equal to), != (Not Equal to) , < (Less than), <= (Less than
or equal to), > (Greater than) and >= (Greater than or equal
to). The outcome of these operations is a boolean value.
The relational operators are most frequently used in the
expressions that control the if statement and the various
loop statements. Any type in Java, including integers,
floating-point numbers, characters, and Booleans can be
compared using the equality test, ==, and the inequality
test, !=. Notice that in Java equality is denoted with two
equal signs, not one. (Remember: a single equal sign is the
assignment operator.) Only numeric types can be
compared using the ordering operators. That is, only
integer, floating-point, and character operands may be
compared to see which is greater or less than the other. As
stated, the result produced by a relational operator is a
boolean value.
You can combine expressions of type boolean with the
&& (and), || (or), and !not) operators.
For example,
<= n && n < length
is true if n lies between zero (inclusive) and length
(exclusive).
If the first condition is false, the second condition is not
evaluated. This “short circuit” evaluation is useful when
the second condition could cause an error.
Finally, the conditional operator takes three operands:
a condition and two values. The result is the first of
the values if the condition is true, the second
otherwise. For example,
time < 12 ? "am" : "pm"
yields the string "am" if time < 12 and the string "pm"
otherwise.
Logical Operators
Logical operators are used to combine two or more relational
expressions. There are 3 Logical Operators - Logical AND(&&),
Logical OR(||) and Logical NOT(!).
A B A&&B A||B !A
False False False False True
True False False True False
False True False True True
True True True True False
Result is True in Logical AND if both the operands are True
otherwise False. In case of Logical OR, result is True if at least
one opened is True otherwise it is False.
Bitwise Operators
Bitwise operators are used to manipulate the bits of given data. In
case of bitwise operators, the operand is first converted por
represented in binary and then the bitwise operation is performed
on the bits of given data. There are six bitwise operators – Bitwise
AND(&), Bitwise OR(|), Bitwise XOR(^), Bitwise unary NOT(~),
Bitwise Left shift(<<) and Bitwise Right shift (>>).
A B A&B A|B A^B ~A
0 0 0 0 0 1
1 0 0 1 1 0
0 1 0 1 1 1
1 1 1 1 0 0
In case of Bitwise XOR the result is false if both the bits are same,
otherwise it is false.
Bitwise Left Shift (<<)
It has this general form:
value << num
Here, num specifies the number of positions to left-shift the value in
value. That is, the << moves all of the bits in the specified value to the
left by the number of bit positions specified by num. For each shift
left, the high-order bit is shifted out (and lost), and a zero is brought
in on the right. If we shift the value towards left by one bit position it
is equivalent to multiplying by 2.
Control Flow
In the following sections, you will see how to implement branches and
loops. The Java syntax for control flow statements is very similar to
that of other commonly used languages, in particular C/C++ and
JavaScript.
Branches
The if statement has a condition in parentheses, followed by either
one statement or a group of statements enclosed in braces.
if (count > 0)
{
double average = sum / count;
System.out.println(average);
}
You can have an else branch that runs if the condition is not
fulfilled.
if (count > 0) {
double average = sum / count;
System.out.println(average);
} else {
System.out.println(0);
}
The statement in the else branch may be another if statement:
if (count > 0)
{
double average = sum / count;
System.out.println(average);
}
else if (count == 0)
{
System.out.println(0);
}
else
{
System.out.println("Huh?");
}
When you need to test an expression against a finite number of
constant values, use the switch statement
switch(count)
{
case
0:
output =
"None";
break;
case 1:
outpu
t =
"One"
;
break;
case 2:
case 3:
case 4:
case 5:
output =
Integer.toString(count);
break;
default:
output =
"Many";
break;
}
Execution starts at the matching case label or, if there is no match, at
the default label (if it is present). All statements are executed until a
break or the end of the switch statement is reached.
In the preceding example, the case labels were integers. You can
use values of any of the following types:
• A constant expression of type char, byte, short, or int
• A string literal
• A value of an enumeration
}
System.out.println("Number of vowels= " + vcount);
System.out.println("Number of consonants= " + ccount);
}
}
Loops
The while loop keeps executing its body while more work needs
to be done, as determined by a condition.
For example, consider the task of summing up numbers until the
sum has reached a target. For the source of numbers, we will use a
random number generator, provided by the Random class in the
java.util package.
int next;
do
{
next =
generator.nextInt(10);
count++;
} while (next != target);
The loop body is entered, and next is set. Then the condition is
evaluated. As long as it is fulfilled, the loop body is repeated.
In the preceding examples, the number of loop iterations was not
known. However, in many loops that occur in practice, the
number of iterations is fixed. In those situations, it is best to use
the for loop.
This loop computes the sum of a fixed number of random values:
int i = 1;
while (i <= 20) {
int next =
generator.nextInt(10);
sum += next;
i++;
}
However, with the while loop, the initialization, test, and update of
the variable i
are scattered in different places. With the for loop, they stay neatly
together.
The initialization, test, and update can take on arbitrary forms. For
example, you can double a value while it is less than the target:
System.out.print("Interest rate in %:
");
double interestRate =
in.nextDouble();
double balance = 0;
int years = 0;
// update account balance while goal isn't
reached
while (balance < goal)
{
// add this year's payment and interest
balance += payment;
double interest = balance *
interestRate / 100;
balance += interest;
years++;
}
System.out.println("You can retire in "
+ years + " years.");
}
}
while (true)
{
String input = in.next();
if (input.equals("Q")) break; // Exits loop
Process input
}
// break jumps here
When the break statement is reached, the loop is exited immediately.
The continue statement is similar to break, but instead of jumping
to the end of the loop, it jumps to the end of the current loop
iteration. You might use it to skip unwanted inputs like this:
while
(in.hasNextInt())
{
int input =
in.nextInt();
if (input < 0) continue; // Jumps to test of in.hasNextInt()
Process input
}
In a for loop, the continue statement jumps to the next update
statement:
e
x
i
t
:
{
.
.
.
if (...) break exit;
...
}
// Labeled break jumps here
There is also a labeled continue statement that jumps to the next
iteration of a labeled loop
class BreakLoop
{
public static void main(String args[])
{
for(int i=0; i<3; i++)
{
System.out.print("Pass " + i + ": ");
for(int j=0; j<100; j++)
{
if(j == 10) break; // terminate loop if j is 10
System.out.print(j + " ");
}
System.out.println();
}
System.out.println("Loops complete.");
}
}
Write a JAVA program to show the usage of break as a
civilized form of goto
class Break_Civilized_Goto
{
boolean t = true;
first:
{
second:
{
third:
{
System.out.println("Before the
break.");
System.out.println("This won't
execute");
}
System.out.println();
System.out.println("Loops complete.");
if (i%2 == 0) continue;
System.out.println("");
}
while (...)
{
System.out.println(...);
String input = in.next(); // Scope of input starts here
...
// Scope of input ends here
}
In other words, a new copy of input is created for each loop
iteration, and the variable does not exist outside the loop.
The scope of a parameter variable is the entire method.
public static void main(String[] args) { // Scope of args starts here
...
// Scope of args ends here
}
Here is a situation where you need to understand scope rules. This
loop counts how many tries it takes to get a particular random
digit:
int next;
do
{
next =
generator.nextInt(10);
count++;
} while (next != target);
The variable next had to be declared outside the loop so it is
available in the condition. Had it been declared inside the loop, its
scope would only reach to the end of the loop body.
When you declare a variable in a for loop, its scope extends to the
end of the loop, including the test and update statements.
for (int i = 0; i < n; i++)
{ // i is in scope for the test and update
...
}
// i not defined here
If you need the value of i after the loop, declare the variable outside:
int i;
for (i = 0; !found && i < n; i++)
{
...
}
// i still available
In Java, you cannot have local variables with the same name in
overlapping scopes.
int i
= 0;
whi
le
(...)
{
String i = in.next(); // Error to declare another variable i
...
}
However, if the scopes do not overlap, you can reuse the same
variable name:
Object − Objects have states and behaviors. Example: A dog has states - color, name,
breed as well as behaviors – wagging the tail, barking, eating. An object is an instance
of a class.
Class − A class can be defined as a template/blueprint that describes the
behavior/state that the object of its type support.
Objects in Java
If we consider the real-world, we can find many objects around us, cars, dogs, humans, etc.
All these objects have a state and a behavior.
If we consider a dog, then its state is - name, breed, color, and the behavior is - barking,
wagging the tail, running.
If you compare the software object with a real-world object, they have very similar
characteristics.
Software objects also have a state and a behavior. A software object's state is stored in fields
and behavior is shown via methods.
So in software development, methods operate on the internal state of an object and the object-
to-object communication is done via methods.
What is an object in Java
An entity that has state and behavior is known as an object e.g., chair, bike, marker, pen,
table, car, etc. It can be physical or logical (tangible and intangible). The example of an
intangible object is the banking system.
Creating an Object
As mentioned previously, a class provides the blueprints for objects. So basically, an object is
created from a class. In Java, the new keyword is used to create new objects.
To create an object of MyClass, specify the class name, followed by the object name, and use
the keyword new:
Example
Output :
5
Classes in Java
Example
public class Dog {
String breed;
int age;
String color;
void barking() {
}
void hungry() {
}
void sleeping() {
}
}
A class can have any number of methods to access the value of various kinds of methods. In
the above example, barking(), hungry() and sleeping() are methods.
Local variables − Variables defined inside methods, constructors or blocks are called
local variables. The variable will be declared and initialized within the method and the
variable will be destroyed when the method has completed.
Instance variables − Instance variables are variables within a class but outside any
method. These variables are initialized when the class is instantiated. Instance
variables can be accessed from inside any method, constructor or blocks of that
particular class.
Class variables − Class variables are variables declared within a class, outside any
method, with the static keyword.
Constructors
When discussing about classes, one of the most important sub topic would be constructors.
Every class has a constructor. If we do not explicitly write a constructor for a class, the Java
compiler builds a default constructor for that class.
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.
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.
There are two types of constructors in Java: no-arg constructor, and parameterized
constructor.
Note: It is called constructor because it constructs the values at the time of object creation. It
is not necessary to write a constructor for a class. It is because java compiler creates a default
constructor if your class doesn't have any.
Each time a new object is created, at least one constructor will be invoked. The main rule of
constructors is that they should have the same name as the class. A class can have more than
one constructor.
class Bike1{
//creating a default constructor
Bike1(){System.out.println("Bike is created");}
//main method
public static void main(String args[]){
//calling a default constructor
Bike1 b=new Bike1();
}
}
Output:
Bike is created
class Student4{
int id;
String name;
//creating a parameterized constructor
Student4(int i,String n){
id = i;
name = n;
}
//method to display the values
void display(){System.out.println(id+" "+name);}