0% found this document useful (0 votes)
37 views

Java Unit-1 Chapter2

Uploaded by

jagan83411
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
37 views

Java Unit-1 Chapter2

Uploaded by

jagan83411
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 51

Java Architecture

Java Architecture is a collection of components, i.e., JVM,


JRE, and JDK. It integrates the process of interpretation and compilation.
It defines all the processes involved in creating a Java program. Java
Architecture explains each and every step of how a program is compiled
and executed.

Java Architecture can be explained by using the following steps:

o There is a process of compilation and interpretation in Java.


o Java compiler converts the Java code into byte code.
o After that, the JVM converts the byte code into machine code.
o The machine code is then executed by the machine.
o The following figure represents the Java Architecture in which
each step is elaborate graphically.

Components of Java Architecture


The Java architecture includes the three main components:

o Java Virtual Machine (JVM)


o Java Runtime Environment (JRE)
o Java Development Kit (JDK)
Java Virtual Machine
The main feature of Java is WORA. WORA stands for Write Once Run
Anywhere. The feature states that we can write our code once and use it
anywhere or on any operating system. Our Java program can run any of
the platforms only because of the Java Virtual Machine. It is a Java
platform component that gives us an environment to execute java
programs. JVM's main task is to convert byte code into machine code.

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

JVM is an abstract machine that provides the environment in which Java


bytecode is executed.

The falling figure represents the architecture of the JVM.

ClassLoader: ClassLoader is a subsystem used to load class files.


ClassLoader first loads the Java code whenever we run it.
Java Runtime Environment
It provides an environment in which Java programs are executed. JRE
takes our Java code, integrates it with the required libraries, and then
starts the JVM to execute it. To learn more about the Java Runtime
Environment, click here.

Java Development Kit


It is a software development environment used in the development of Java
applications and applets. Java Development Kit holds JRE, a compiler, an
interpreter or loader, and several development tools in it

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.

Stack: It is also referred to as thread stack. It is created for a single


execution thread. The thread uses this area to store the elements like the
partial result, local variable, data used for calling method and returns etc.

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.

o Interpreter: It converts the byte code into native code and


executes. It sequentially executes the code. The interpreter
interprets continuously and even the same method multiple times.
This reduces the performance of the system, and to solve this, the
JIT compiler is introduced.
o JIT Compiler: JIT compiler is introduced to remove the drawback of
the interpreter. It increases the speed of execution and improves
performance.
o Garbage Collector: The garbage collector is used to manage the
memory, and it is a program written in Java. It works in two phases,
i.e., Mark and Sweep. Mark is an area where the garbage collector
identifies the used and unused chunks of memory. The Sweep
removes the identified object from the Mark

Primitive Types

Even though Java is an object-oriented programming language, not all


Java values are objects. Instead, some values belong to primitive
types. Four of these types are signed integer types, two are floating-
point number types, one is the character type char that is used in the
encoding for strings, and one is the boolean type for truth values.

Signed Integer types


The signed integer types are for numbers without fractional parts.
Negative values are allowed
Type Storage Range (inclusive)
Requirement
byte 1 byte -128 to 127
short 2 bytes -32,768 to 32,767
int 4 bytes -2,147,483,648 to
2.147,483,647 (just over 2
billion)
long 8 bytes -
9,223,372,036,854,775,808
to
9,223,372,036,854,775,807

 In most situations, the int type is the most practical. If you


want to represent the number of inhabitants of our planet,
you’ll need to resort to a long. The byte and short types are
mainly intended for specialized applications, such as low-
level file handling, or for large arrays when storage space is
at a premium. In Java, the ranges of the integer types do not
depend on the machine on which you will be running your
program.
 You write long integer literals with a suffix L. There is no
syntax for literals of type byte or short. Use the cast
notation, for example, (byte) 127. Hexadecimal literals have
a prefix 0x . Binary values have a prefix 0b. For example,
0b1001 is 9.

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)

 Many years ago, when memory was a scarce resource,


four-byte floating-point numbers were in common use. But
seven decimal digits don't go very far, and nowadays,
“double precision” numbers are the default. It only makes
sense to use float when you need to store a large number of
them.
 Numbers of type float have a suffix F (for example, 3.14F).
Floating-point literals without an F suffix (such as 3.14)
have type double. You can optionally supply the D suffix
(for example, 3.14D).

The char type


 The char type describes “code units” in the UTF-16
(Unicode Transformation Format-16) character encoding
used by Java. Occasionally, you may encounter character
literals, enclosed in single quotes. For example, 'J' is a
character literal with ASCII value 74.
 The special codes '\n', '\r', '\t', '\b' denote a line feed, carriage
return, tab, and backspace. Use a backslash to escape a single
quote '\'' and a backslash '\\'.
 In old languages like C and C++ we can use only ASCII
characters and to represent all ASCII characters 8-bits are
enough. Hence char size is 1 byte. But in Java we can use
Unicode characters which covers world wide all alphabets
sets. The number of Unicode characters is greater than 256
and hence 1 byte is not enough to represent all characters.
Hence we should go for 2 bytes.
 Unicode characters are prefixed with \u and can be expressed
as hexadecimal values that run from \u0000 to \uFFFF.

Booleans

Java has a primitive type, called boolean, for logical values. It


can have only one of two possible values, true or false. This is
the type returned by all relational operators, as in the case of a <
b. boolean is also the type required by the conditional
expressions that govern the control statements such as if and
for. Size of boolean is 1-bit.

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,

final int DAYS_PER_WEEK = 7;


By convention, uppercase letters are used for names of
constants.
 You can also declare a constant outside a method, using the
static keyword:

public class Calendar


{
public static final int DAYS_PER_WEEK = 7;
...
}
Then the constant can be used in multiple methods. Inside
Calendar, you refer to the constant as
DAYS_PER_WEEK. To use the constant in another class,
prepend the class name: Calendar.DAYS_PER_WEEK.

Write a JAVA program to find the area of circle

class Area
{

public static void main(String args[])

double pi, r, a;

r = 10.8; // radius of circle

pi = 3.1416; // pi, approximately

a = pi * r * r; // compute area

System.out.println("Area of circle is " + a);

Write a JAVA program to show the usage of Boolean variables


class Bool
{

public static void main(String args[])


{

boolean b;

b = false;

System.out.println("b is " + b);

b = true;

System.out.println("b is " + b);

// a boolean value can control the if statement


if(b) System.out.println("This is executed.");

b = false;

if(b) System.out.println("This is not executed.");

// outcome of a relational operator is a boolean value

System.out.println("10 > 9 is " + (10 > 9));


}
}
Write a JAVA program to show the usage of constants
class Constants
{
public static void main(String args[])
{
final int WIDTH=100;
final int LENGTH=150;
int a=50;
a=40;
System.out.println("value of constant WIDTH=" +
WIDTH);
System.out.println("value of constant LENGTH=" +
LENGTH);
System.out.println("value of variable a=" + a);
//WIDTH=50;
}
}

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

<< >> >>> (arithmetic shift) Left

< > <= >= instanceof Left


== != Left
& (bitwise and) Left
^ (bitwise exclusive or) Left
| (bitwise or) Left
&& (logical and) Left
|| (logical or) Left
? : (conditional) Left
= += -= *= /= %= <<= Right
>>= >>>= &= ^= |=

In this table, operators are listed by decreasing precedence.


For example, since + has a higher precedence than <<, the
value of 3 + 4 << 5 is (3 + 4) << 5. An operator is left-
associative when it is grouped left to right. For example, 3 - 4
- 5 means (3 - 4) - 5. But -= is right- associative, and i -= j -=
k means i -= (j -= k).

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;

Basic Arithmetic Operators


 Addition, subtraction, multiplication, and division are
denoted by + - * /.
For example, 2 * n + 1 means to multiply 2 and n and
add 1.
You need to be careful with the / operator. If both
operands are integer types, it denotes integer division,
discarding the remainder. For example, 17 / 5 is 3,
whereas 17.0 / 5 is 3.4. An integer division by zero gives
rise to an exception which, if not caught, will terminate
your program.
 A floating-point division by zero yields an infinite value or
NaN (Not a Number) without causing an exception.
 The % operator yields the remainder. For example, 17 % 5
is 2, the amount that remains from 17 after subtracting 15
(the largest integer multiple of 5 that “fits” into 17). If the
remainder of a % b is zero, then a is an integer multiple of
b.

 Java has increment and decrement operators:


n++; // Adds one to n
n--; // Subtracts one from n

As in other C-based languages, there is also a prefix form of


these operators. Both n++ and ++n increment the variable
n, but they have different values when they are used inside an
expression. The first form yields the value before the
increment, and the second the value after the increment.

Write a JAVA program to perform arithmetic operations


class Arithmetic_Operations
{
public static void main(String args[])
{
int a=10, b=20;
int c=a+b;
int d=b-a;
int e=a*b;
int f=b/a;
int g=a%b;
int h=b%a;
System.out.print(" Addition of a & b = "+c);
System.out.println(" Subtraction of a & b = "+d);
System.out.println(" Multiplication of a & b = "+e);
System.out.println(" Division of a & b = "+f);
System.out.println(" Modulus of a & b = "+g);
System.out.println(" Modulus of b & a = "+h);
}
}

Write a JAVA program to show the usage of increment


operator
class Increment
{
public static void main(String args[])
{
char ch1;
ch1 = 'X';
System.out.println("ch1 contains " + ch1);
ch1++; // increment ch1
System.out.println("ch1 is now " + ch1);
}
}

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.

Bitwise Right Shift (>>)


The right shift operator, >>, shifts all of the bits in a value to the right
a specified number of times. Its general form is shown here:
value >> num
Here, num specifies the number of positions to right-shift the value in
value. That is, the >> moves all of the bits in the specified value to the
right the number of bit positions specified by num.
The following code fragment shifts the value 32 to the right by two
positions, resulting in a being set to 8:
int a = 32;
a = a >> 2; // a now contains 8
If we shift the value towards right by one bit position it is equivalent
to dividing by 2. If we shift by 2 bit position, it is equivalent to
dividing by 4.

Write a JAVA program to show the usage of relational, logical


and bitwise operators
class A
{
public static void main(String args[])
{
int a=10,b=5;
boolean c=(a>b);
boolean d=(a<b);
boolean e=(a!=b);
boolean f=(a==b);
boolean n=true,p=false;
boolean g=(n&&p);
boolean h=(n||p);
boolean i=(!n);
int j=(a&b);
int k=(a|b);
int l=(a<<1);
int m=(a>>1);
System.out.println("Result of relational greater than
operation=" + c);
System.out.println("Result of relational less than
operation=" + d);
System.out.println("Result of relational not equal to
operation=" + e);
System.out.println("Result of relational equality
operation=" + f);
System.out.println("Result of logical and operation=" + g);
System.out.println("Result of logical or operation=" + h);
System.out.println("Result of logical not operation=" + i);
System.out.println("Result of bitwise and operation=" + j);
System.out.println("Result of bitwise or operation=" + k);
System.out.println("Result of bitwise left shift operation="
+ l);
System.out.println("Result of bitwise right shift than
operation=" + m);
System.out.println("Result of relational greater than
operation=" + c);
}
}

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

Write a JAVA program to find the largest of 2 numbers using if-


else statement
import java.util.Scanner;
class If_Else
{
public static void main(String args[])
{
int a,b;
System.out.println(" enter 2 numbers: ");
Scanner in = new Scanner(System.in);
a=in.nextInt();
b=in.nextInt();
if(a>b)
System.out.println(“Largest of 2 numbers=” + a);
else
System.out.println(“Largest of 2 numbers=” + b);
}
}

Write a JAVA program to show the usage of else-if ladder


statement
import java.util.Scanner;
class Else_If
{
public static void main(String args[])
{
System.out.println(" enter a integer value : ");
Scanner in = new Scanner(System.in);
int month = in.nextInt();
String season;
if(month == 12 || month == 1 || month == 2)
season = "Winter";
else if(month == 3 || month == 4 || month == 5)
season = "Spring";
else if(month == 6 || month == 7 || month == 8)
season = "Summer";
else if(month == 9 || month == 10 || month == 11)
season = "Autumn";
else
season = "Bogus Month";
System.out.println("Month entered is a " + season +"
season.");
}
}

Write a JAVA program to find largest of 3 numbers using nested-


if statement
import java.util.Scanner;
class Nested_If
{
public static void main(String args[])
{
int a,b,c;
Scanner s=new Scanner(System.in);
System.out.println(“Enter 3 numbers:”);
a=s.nextInt();
b=s.nextInt();
c=s.nextInt();
if(a>b)
{
if(a>c)
System.out.println(“Largest number=” + a);
else
System.out.println(“Largest number=” + c);
}
else
{
if(b>c)
System.out.println(“Largest number=” + b);
else
System.out.println(“Largest number=” + c);
}
}
}
Write a JAVA program to show the implementation of basic
calculator using switch statement
import java.util.Scanner;
class Calculator
{
public static void main(String args[ ])
{
double a,b,result=0;
char operator;
Scanner reader = new Scanner(System.in);
System.out.println("Enter the operands: ");
a= reader.nextDouble( );
b= reader.nextDouble( );
System.out.print("Enter an operator (+, -, *, /): ");
operator = reader.next( ).charAt(0);
switch(operator)
{
case '+':
result = a+b;;
break;
case '-':
result = a-b;
break;
case '*':
result = a*b;
break;
case '/':
result = a/b;
break;
// operator doesn't match any case constant (+, -, *, /)
default:
System.out.println("Error! operator is not
correct");
}
System.out.printf("%f %c %f = %f", a, operator, b,
result);
}
}
Write a JAVA program to show the usage of switch statement
class SampleSwitch
{
public static void main(String args[])
{
for(int i=0; i<6; i++)
{
switch(i)
{
case 0: System.out.println("i is zero.");
break;
case 1: System.out.println("i is one.");
break;
case 2: System.out.println("i is two.");
break;
case 3: System.out.println("i is three.");
break;
default: System.out.println("i is greater than
3.");
}
}
}
}

Write a JAVA program to count the number of vowels and


consonants in a string
class CountVowelConsonant
{
public static void main(String[] args)
{
int vcount = 0, ccount = 0;
String str = "Hi I am studying 2nd year Engineering in
REVA";
str = str.toLowerCase();
for(int i = 0; i < str.length(); i++)
{
if(str.charAt(i) == 'a' || str.charAt(i) == 'e' || str.charAt(i)
== 'i' || str.charAt(i) == 'o' || str.charAt(i) == 'u')
{
vcount++;
}
else
{
if(str.charAt(i)!=' ')
{
ccount++;
}
}

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

Random generator = new Random();


This call gets a random integer between 0 and 9:

int next = generator.nextInt(10);


Here is the loop for forming the sum:

while (sum < target) {


int next =
generator.nextInt(10);
sum += next;
count++;
}
This is a typical use of a while loop. While the sum is less than the
target, the loop keeps executing.
Sometimes, you need to execute the loop body before you can
evaluate the condition. Suppose you want to find out how long it
takes to get a particular value. Before you can test that condition,
you need to enter the loop and get the value. In this case, use a
do/while loop:

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:

for (int i = 1; i <= 20; i++)


{
int next =
generator.nextInt(10);
sum += next;
}
This loop runs 20 times, with i set to 1, 2, ..., 20 in each loop
iteration.
You can rewrite any for loop as a while loop. The loop above is
equivalent to

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:

for (int i = 1; i < target; i *= 2)


{ System.out.println(i);
}
Instead of declaring a variable in the header of the for loop, you
can initialize an existing variable:
for (i = 1; i <= target; i++) // Uses existing variable i
You can declare or initialize multiple variables and provide
multiple updates, separated by commas. For example,

for (int i = 0, j = n - 1; i < j; i++, j--)


If no initialization or update is required, leave them blank. If you
omit the condition, it is deemed to always be true.
for (;;) // An infinite loop
You will see in the next section how you can break out of such a
loop.

Write a JAVA program to print the numbers from 1 2 3 ……n


using while loop
import java.util.Scanner;
class While_Example
{
public static void main(String args[])
{
int i=1,n;
Scanner s=new Scanner(System.in);
System.out.println(“Enter the value of n:”);
n=s.nextInt();
while(i<=n)
{
System.out.println(i);
i++;
}
}
}
Write a JAVA program to show the usage of while loop
public class while_ex
{
public static void main(String[] args)
{
Scanner in = new
Scanner(System.in);
System.out.print("How much money
do you need to retire? ");
double goal = in.nextDouble();
System.out.print("How much
money will you contribute every year?");
double payment = in.nextDouble();

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

Write a JAVA program to print the numbers from 1 2 3 ……n


using do-while loop
import java.util.Scanner;
class Do_While_Example
{
public static void main(String args[])
{
int i=1,n;
Scanner s=new Scanner(System.in);
System.out.println(“Enter the value of n:”);
n=s.nextInt();
do
{
System.out.println(i);
i++;
}while(i<=n);
}
}
Write a JAVA program to show the usage of do-while loop
import java.util.Scanner;
class Do_While
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
System.out.print("How much money will you contribute
every year?");
double payment = in.nextDouble();
System.out.print("Interest rate in %: ");
double interestRate = in.nextDouble();
double balance = 0;
int year = 0;
String input;
// update account balance while user isn't ready to retire
do
{
// add this year's payment and interest
balance += payment;
double interest = balance * interestRate / 100;
balance += interest;
year++;
// print current balance
System.out.printf("After year %d, your balance is
%,.2f%n", year, balance);
// ask if ready to retire and get input
System.out.print("Ready to retire? (Y/N) ");
input = in.next();
}while (input.equals("N"));
}
}

Write a JAVA program to print odd numbers from 1 to n using


for loop
import java.util.Scanner;
class For_Example
{
public static void main(String args[])
{
int i,n;
Scanner s=new Scanner(System.in);
System.out.println(“Enter the value of n:”);
n=s.nextInt();
for(i=1;i<=n;i+=2)
{
System.out.println(i);
}
}
}
Write a JAVA program to show the usage of for loop
import java.util.*;
public class for_loop
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
System.out.print("How many numbers do you need to
draw? ");
int k = in.nextInt();
System.out.print("What is the highest number you can
draw? ");
int n = in.nextInt();
/*
* compute binomial coefficient
n*(n-1)*(n-2)*...*(n-k+1)/(1*2*3*...*k)
*/
int lotteryOdds = 1;
for (int i = 1; i <= k; i++)
lotteryOdds = lotteryOdds * (n - i + 1) / i;
System.out.println("Your odds are 1 in " + lotteryOdds +
". Good luck!");
}
}
Breaking and Continuing
If you want to exit a loop in the middle, you can use the break
statement. For example, suppose you want to process words until
the user enters the letter Q. Here is a solution that uses a boolean
variable to control the loop:
boolean done =
false;
while (!done)
{
String input =
in.next();
if
("Q".equals(inpu
t))
{
done = true;
}
else
{
Process input
}
}
This loop carries out the same task with a break statement:

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:

for (int i = 1; i <= target; i++)


{
int input = in.nextInt();
if (n < 0) continue; // Jumps to i++
Process input
}
The break statement only breaks out of the immediately enclosing
loop or switch. If you want to jump to the end of another
enclosing statement, use a labeled break statement. Label the
statement that should be exited, and provide the label with the
break like this:
outer:
while (...)
{
...
while (...)
{
...
if (...) break outer;
...
}
...
}
// Labeled break jumps here
The label can be any name.
A regular break can only be used to exit a loop or switch, but a
labeled break
can transfer control to the end of any statement, even a block
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

Write a JAVA program to show the usage of break for


breaking a 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
{

public static void main(String args[])


{

boolean t = true;

first:
{

second:
{

third:
{

System.out.println("Before the
break.");

if(t) break second; // break out of


second block

System.out.println("This won't
execute");
}

System.out.println("This won't execute");

System.out.println("This is after second block.");

Write a JAVA program to show the usage of break


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 continue


statement
class Continue_Ex
{
public static void main(String args[])
{

for(int i=0; i<10; i++)


{

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

if (i%2 == 0) continue;

System.out.println("");
}

Local Variable Scope


Now that you have seen examples of nested blocks, it is a good
idea to go over the rules for variable scope. A local variable is any
variable that is declared in a method, including the method's
parameter variables. The scope of a variable is the part of the
program where you can access the variable. The scope of a local
variable extends from the point where it is declared to the end of
the enclosing block.

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:

for (int i = 0; i < n / 2; i++) { ... }


for (int i = n / 2; i < n; i++) { ... } // OK to redefine i

Write a JAVA program to demonstrate scope of a variable within


a block
class Scope
{
public static void main(String args[])
{
int x; // known to all code within main
x = 10;
if(x == 10)
{ // start new scope
int y = 20; // known only to this block
// x and y both known here.
System.out.println("x and y: " + x + " " + y);
x = y * 2;
}
// y = 100; // Error! y not known here
// x is still known here.
System.out.println("x is " + x);
}
}
Classes and Objects.

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

An object has three characteristics:

 State: represents the data (value) of an object.


 Behavior: represents the behavior (functionality) of an object such as deposit,
withdraw, etc.
 Identity: An object identity is typically implemented via a unique ID. The value of
the ID is not visible to the external user. However, it is used internally by the JVM to
identify each object uniquely.

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.

There are three steps when creating an object from a class −

 Declaration − A variable declaration with a variable name with an object type.


 Instantiation − The 'new' keyword is used to create the object.
 Initialization − The 'new' keyword is followed by a call to a constructor. This call
initializes the new object.

To create an object of MyClass, specify the class name, followed by the object name, and use
the keyword new:

Example

Create an object called "obj" and print the value of x:

public class MyClass {


int x = 5;

public static void main(String[] args) {


MyClass Obj = new MyClass();
System.out.println(Obj.x);
}
}

Output :

5
 Classes in Java

A class is a blueprint from which individual objects are created.

Following is a sample of a class.

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.

A class can contain any of the following variable types.

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

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.

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.

Rules for creating Java constructor

There are two rules defined for the 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

Following is an example of a constructor −

public class Puppy {


public Puppy() {
}

public Puppy(String name) {


// This constructor has one parameter, name.
}
}

Types of Java constructors

There are two types of constructors in Java:

1. Default constructor (no-arg constructor)


2. Parameterized constructor
3. Copy constructor

Example of default constructor


In this example, we are creating the no-arg constructor in the Bike class. It will be invoked at
the time of object creation.
Java Program to create and call a default 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

Java Parameterized Constructor

Java Program to demonstrate the use of the parameterized constructor.

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

public static void main(String args[]){


//creating objects and passing values
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
//calling method to display the values of object
s1.display();
s2.display();
}
}
Output:
111 Karan
222 Aryan
Note : java does not support destructors. All freeing the memory task is done by GARBAGE
COLLECTOR. Java has it's own memory management feature using garbage collector. When
you use finalize() the object becomes available for garbage collection and you don't need to
explicitly call for the destructor

3. A copy constructor in a Java class is a constructor that creates an object using


another object of the same Java class.
That’s helpful when we want to copy a complex object that has several fields, or when we
want to make a deep copy of an existing object.
2. How to Create a Copy Constructor
To create a copy constructor, we can first declare a constructor that takes an object of the
same type as a parameter:
public class Employee {
private int id;
private String name;

public Employee(Employee employee) {


}
}Copy
Then, we copy each field of the input object into the new instance:
public class Employee {
private int id;
private String name;

public Employee(Employee employee) {


this.id = employee.id;
this.name = employee.name;
}
}

You might also like