You are on page 1of 197

JAVA PROGRAMMING

1
UNIT I

• Java programming – History of Java, comments, Java


Buzz words
• Data types, Variables, Constants, Scope and Lifetime of
variables, Operators, Type conversion and casting,
Enumerated types
• Control flow- block scope, conditional statements, loops,
break and continue statements
• arrays, class, object, and its methods constructors, and
methods, access control, this reference, overloading
constructors, recursion, exploring string class, garbage
collection.

2
Need for OOP Paradigm

 OOP is an approach to program organization and development,


which attempts to eliminate some of the drawbacks of
conventional programming methods by incorporating the best of
structured programming features with several new concepts.

 OOP allows us to decompose a problem into number of entities


called objects and then build data and methods (functions) around
these entities.

 The data of an object can be accessed only by the


methods
associated with the object.
3
History of Java
• Java is a object oriented programming language developed
by sun micro systems of USA in 1991.
• Originally it is called oak and inventor is James Gosling
• The name Oak was used by Gosling after an oak tree that
remained outside his office. Also, Oak is an image of
solidarity and picked as a national tree of numerous nations
like the U.S.A., France, Germany, Romania, etc. But they had
to later rename it as “JAVA” as it was already a trademark
by Oak Technologies.
• First it is designed for the development of software for
consumer electronic devices like TV’s, VCR’s and other
electronic devices
History of Java
• In 1993 , the world wide web appeared on the internet and
transformed text based internet into a graphical-rich
environment and later web applications by using a new
computers connected to the net
• In 1994, the team developed a web browser called “hot
JAVA” to locate and run applied programs on internet
• In 1995 many popular companies including net scape and
Microsoft announced their support to JAVA
• The most striking feature of JAVA is Platform independent.
History of Java
What is Java?

 Java was created by a team lead by James Gosling in 1995 for Sun
Microsystems

 Java is concurrent, class-based and object -oriented programming


language.

 Platform: Any hardware or software environment in which a


program runs, is known as a platform. Since Java has its own
runtime environment (JRE) and API, it is called platform.

 Java is a platform independent programming language that


follows the logic of “ Write once, Run anywhere”.
The Java Buzzwords(Features)
The Java Buzzwords(Features)

• The key considerations were summed up by the


Java team in the following list of buzzwords:
 Simple
 Secure
 Portable
 Object-oriented
 Robust
 High performance
 Distributed
 Dynamic
 Multithreaded
 Architecture-neutral
 Interpreted
• simple – Java is designed to be easy for the
professional programmer to learn and use.
• object-oriented: a clean, usable, pragmatic
approach to objects, not restricted by the need for
compatibility with other languages.
• Robust: restricts the programmer to find the
mistakes early, performs compile-time (strong
typing) and run-time (exception-handling) checks,
manages memory automatically.
• Secure: programs are confined to the Java
execution environment and cannot access other
parts of the computer.
• Portability: Many types of computers and operating
systems are in use throughout the world—and many are
connected to the Internet.
• For programs to be dynamically downloaded to all the
various types of platforms connected to the Internet,
some means of generating portable executable code is
needed. The same mechanism that helps ensure
security also helps create portability.
• Indeed, Java's solution to these two problems is both
elegant and efficient.
• Interpreted and high-performance: Java
programs are compiled into an intermediate
representation – byte code:
a) can be later interpreted by any JVM
b)can be also translated into the native machine code
for efficiency.
• Dynamic: substantial amounts of run-time type
information to verify and resolve access to objects at
run-time.
• Distributed: Java handles TCP/IP protocols, accessing
a resource through its URL much like accessing a
local file.
• Multithreaded: supports multi-threaded
programming for writing program that perform
concurrent computations
• Architecture-neutral: Java Virtual Machine
provides a platform independent environment for
the execution of Java byte code
Buzzwords/Java Features:
Compilation Process
The Java platform

Java programs are compiled to Java byte-codes,
a kind of machine independent representation.
The program is then executed by an interpreter
called the Java Virtual Machine (JVM).

Test.java Test.class Interpreter (JVM)

Compiler

5
The Java platform

The compiled code is independent of the
architecture of the computer.

The price to pay is a slower execution.
Linux

Test.java Test.class Interpreter (JVM)

Interpreter (JVM) Windows

Compiler
Interpreter (JVM)

6
Data Types
 A data type defines the type or/and behavior of a
data, it tells to the compiler about the type of data
which is going to be stored and the compiler reserves
the fixed number of bytes for that particular
variable/constant.

 Thus, we can say that, a data type defines two things:


-> Type of data
-> Memory blocks to be reserved for the data

 There are mainly two data types in Java


 Primitive data types
 Non-primitive data types
Data Types Contd..

(4 bytes)
(1 byte)
(1 byte) (2 bytes)

(2 bytes) (8 bytes)

(4 bytes)

(8 bytes)
Java Primitive Data Types
Data Characteristics Range
Type
byte 8 bit signed integer -128 to 127

short 16 bit signed integer -32768 to 32767

int 32 bit signed integer -2,147,483,648 to 2,147,483,647

long 64 bit signed integer -9,223,372,036,854,775,808 to-


9,223,372,036,854,775,807
float 32 bit floating point + 1.4E-45 to
number + 3.4028235E+38
double 64 bit floating point + 4.9E-324 to
number + 1.7976931348623157E+308
boolean true or false NA, note Java booleans cannot be
converted to or from other types
char 16 bit, Unicode Unicode character, \u0000 to \uFFFF
Can mix with integer types
Primitive Data Types Contd..

• byte: 8-bit integer type.


Range: -128 to 127.
Example: byte b = -15;
Usage: particularly
when working with
data streams.

• short: 16-bit integer type.


Range: -32768 to 32767.
Example: short c = 1000;
Usage: probably the
Primitive Data Types Contd..

• int: 32-bit integer type.


Range: -2147483648 to 2147483647.
Example: int b = -50000;
Usage:
1) Most common
integer type.
2)Typically used to control loops and to index
arrays.
3)Expressions involving the byte, short and int
values are promoted to int before calculation.
Primitive Data Types Contd..
• long: 64-bit integer type.
Range: -9223372036854775808 to 9223372036854775807.
Example: long l = 10000000000000000;

Usage: 1) useful when int type is not large enough to


hold the desired value

• float: 32-bit floating-point number.


Range: 1.4e-045 to 3.4e+038.
Example: float f = 1.5;
Usage:
1)fractional part is needed
2)large degree of precision is
Primitive Data Types Contd..

• double: 64-bit floating-point number.


Range: 4.9e-324 to 1.8e+308.
Example: double pi = 3.1416;
Usage:
1) accuracy over many
iterative calculations
2) manipulation of large-
valued numbers
Primitive Data Types
Contd..
char: 16-bit data type used to store characters.
Range: 0 to 65536.
Example: char c = ‘a’;
Usage:
1) Represents both
ASCII and Unicode
character sets;
Unicode defines a
character set with
characters found in
(almost) all human
languages.
2)Not the same as in C/C++ where char is 8-bit
Data Types Contd..

• boolean: Two-valued type of logical values.


Range: values true and false.
Example: boolean b = (1<2);
Usage:
1) returned by relational
operators, such as 1<2
2)required by branching expressions such as if
or for
keywords:
-> some words are reserved to represent some meaning or functionality.
Example: if ------> condition
-> There are 53 keywords are there in java.
-> all the keywords are written in lowercase.
-> 3/53---> reserved words |literals ---> true, false and null.
-> 2/50---> unused keywords ----> goto, const
-> 48/48--> pure keywords

Examples:
int
while
for
break
class
static
final etc
Identifiers in Java
Identifiers are used for class names, method names, and variable
names. In Java, there are several points to remember about
identifiers

 All identifiers should begin with a letter (A to Z or a to z),


currency character ($) or an underscore (_).
 After the first character, identifiers can have any combination
of characters.
 A keyword cannot be used as an identifier.
 Most importantly, identifiers are case sensitive. Java is case-
sensitive, so VALUE is a different identifier than Value
 classes start with capital letter
 variable name|function name|method name|class name|
interface name|block name.

 valid identifiers: age, $salary, _value, __1_value.


 invalid identifiers: 123abc, -salary.
Variables
• Java uses variables to store data.
• To allocate memory space for a variable JVM requires:
1) to specify the data type of the variable
2) to associate an identifier with the variable
3)optionally, the variable may be assigned an initial
value
4) Declaration ends with a semicolon(;)
• All these are done as part of variable declaration.
• In addition, all variables have a scope, which defines
their visibility, and a lifetime.
Variables Contd..
• Declaring the variables
Syntax: type identifier [ = value][, identifier [= value] ...] ;

• Type is one of Java’s atomic types, or the name of a class or


interface.
• Identifier is the name of the variable. You can initialize the variable
by specifying an equal sign and a value. To declare more than one
variable of the specified type, use a comma separated list.

• scope – how the variable is visible to other parts of the program


• lifetime – how the variable is created, used and destroyed
Basic Variable Declaration
Variable Declaration

• We can declare several variables at the same time:


type identifier [=value][, identifier [=value] …];
Examples:
int a, b, c;
int d = 3, e, f = 5;
byte g = 22;
double pi = 3.14159;
char ch = 'x';
Comments
Comments are not a part of the compiled program. They can be
used to explain Java code, and to make it more readable. It can
also be used to prevent execution when testing alternative code.

1. Single-line Comments: It starts with two forward slashes (//).


Any text between // and the end of the line is ignored by Java
(will not be executed).

2. Java Multi-line Comments: It starts with /* and ends with */.


Any text between /* and */ will be ignored by Java.
Comments Example
Type casting | Type conversion:
1.If an expression in a program contains more than one type of data then different types
have to be changed to single type.
converting lower data into higher data or higher into lower is the concept of TC|TC.
2. Compiler | Programmer.
3. May loss some information.
4. there are two types of typecasting
1. implicit casting
2. explicit casting
implicit casting:
----------------
1. automatic conversion of lower data type into higher data type is called as implicit.
2. compiler is responsible to do this.
3. no loss of information.
4. automatic conversion | widening | up casting.
5. diagram

byte(1)---->short(2)---->int (4)---->long(8)----->float(4)----->double(8)
^
|
|
char(2)
Example:
Examples:
class Test
class Test
{
{
public static void
public static void main(String[]
main(String[] args)
args)
{
{
char ch = 'a';
byte b = 10;
int i;
int i;
i = ch;//---> 2 byte
i = b;//---> 1 byte into
into 4 bytes
4 bytes
System.out.println(ch);//a
System.out.println(b);//10
System.out.println(i);//97
System.out.println(i);//10
}
}
}}
}
Example:

class Test
{
public static void main(String[] args)
{
int i=10;
boolean b;
b = i;
}
}

Output:
Test.java:7: error: incompatible types: int cannot be converted to boolean
b = i;
^
1 error
Explicit casting:
1. Manual conversion of higher data type into lower data type is called as explicit.
2. programmer is responsible to do this.
3. loss of information will be there.
4. manual conversion | narrowing | down casting.
5. diagram

byte(1)<----short(2)<----int(4)<----long(8)<-----float(4)<-----double(8)
|

char(2)

Syntax :
type variable=(new_type) variable;
Example:
double D=6.865;
int A=(int) D; // fractional part will not be considered

Note: Boolean type can not be type cast to any other type
class Conversion
{
public static void main(String args[])
{
byte b;
int i = 257;
double d = 323.142;
System.out.println("\nConversion of int to byte.");
b = (byte) i;
System.out.println("i and b " + i + " " + b);
System.out.println("\nConversion of double to int.");
i = (int) d; System.out.println("d and i " + d + " " + i);
System.out.println("\nConversion of double to byte.");
b = (byte) d; System.out.println ("d and b " + d + " " + b);
}
}

Output:
Conversion of int to byte.
i and b 257 1
Conversion of double to int.
d and i 323.142 323
Conversion of double to byte.
d and b 323.142 67
Example:

public static void main(String args[])


{
byte i = 50; // No casting needed for below conversion
short j = i;
int k = j;
long l = k;
float m = l;
double n = m;
System.out.println("byte value : "+i);
System.out.println("short value : "+j);
System.out.println("int value : "+k);
System.out.println("long value : "+l);
System.out.println("float value : "+m);
System.out.println("double value : "+n);
}

Output:
short value : 50
int value : 50
long value : 50
float value : 50.0
double value : 50.0
Variable Scope
• Scope determines the visibility of program elements with respect to other program
elements.
• Declare the variable before you use it
• In Java, scope is defined separately for classes and methods:

1) variables defined by a class have a global scope(class scope)


2) variables defined by a method have a local scope(method scope)

A scope is defined by a block:

{

}

A variable declared inside the scope is not visible outside:


{
int n;
}
n = 1;// this is illegal
Nested scope:
 Objects declared in the outer scope will be visible to code within the inner
scope, but the reverse is not true. Objects declared within the inner scope
will not be visible outside it.
 A variable defined in the outer block is visible in the inner blocks also and it
can not be redefined with the same name in the inner blocks.

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);
}
}
Nested scope:
 Cannot declare a variable to have the same name as one in an outer scope.

// This program will not compile


class ScopeErr
{
public static void main(String args[])
{
int bar = 1;
{
// creates a new scope
int bar = 2; // Compile-time error – Duplicate local variable bar
already defined!
}
}
}
Variable Lifetime
• Variables are created when their scope is entered by control
flow and destroyed when their scope is left.
• A variable declared in a block looses its value when the block
is left.
• So, a variable declared in a method will not hold its value
between different invocations of this method.
• Initialized in a block, a variable will be re-initialized with
every re-entry. Variables lifetime is confined to its scope!
• Thus , lifetime of a variable is confined to its scope.
• If a variable declaration includes an initializer, then that
variable will be reinitialized each time the block in which it
is declared is entered.
// Demonstrate lifetime of a variable.
class LifeTime
{
public static void main(String args[])
{
int x;
for(x = 0; x < 3; x++)
{
int y = -1; // y is initialized each time block is entered
System.out.println("y is: " + y); // this always prints -1 y = 100;
System.out.println("y is now: " + y);
}
}
}

Output
y is: -1
y is now: 100
y is: -1
y is now: 100
y is: -1
y is now: 100
output statements:
we can use output statements to print output on screen/console.

1. System.out.print() - print the info on the screen and control will be in the same
line

2. System.out.println() - it prints info on screen & control goes to next line

class Test
{
public static void main(String[] args)
{
System.out.print("Java\n"); // System.out.println("Java");
System.out.print("Python\n");
System.out.print("LINUX/UNIX");
}
}

Java
Python
LINUX/UNIX
Types of Variables

There are three types of variables in a class declaration:


1. Local variables: These variables are declared inside a
method or are arguments to a method
2. Instance variables: Declared anywhere in the class but
outside a method. Each object of a class keeps the values
of these variables in its memory
3. Static or Class variables: These variables are declared
using Static keyword .
-> only one copy of values are maintained by program
-> shared by all the objects of a class.
Operators Types
• Operator is a symbol that specify the operation to be
performed .
• An operator acts on variables called operands to get the desired
output
• Java operators are used to build value expressions.
• Based on operands, all the operators are divided into the
following types:
• If operator takes only one operand for its operation , it is called
unary operator
• If it takes two operands, it is called binary operator
• If it takes three operands, it is called ternary operator. There is
only one ternary operator.
• Java provides a rich set of operators:
1) Arithmetic operators
2) Assignment operators
3) Relational operators
4) Logical operators
5) Bitwise operators
6) Boolean operators
7) Increment/decrement operators
8) Ternary operator
9) Member (. ) operator
Arithmetic Operators

Name Meaning Example Result

+ Addition 34 + 1 35

- Subtraction 34.0 – 0.1 33.9

* Multiplication 300 * 30 9000

/ Division 1.0 / 2.0 0.5

% Remainder 20 % 3 2

52
Integer Division
+, -, *, /, and %

5 / 2 yields an integer 2.
5.0 / 2 yields a double value 2.5

5 % 2 yields 1 (the remainder of the division)

53
Examples:

class Test
{
public static void main(String[] args)
{
System.out.println(5+2); //7
System.out.println(5-2); //3
System.out.println(5*2); //10
System.out.println(5/2); //2
System.out.println(5%2); //1
}
}
-------------------------------------------------------------------------------------------------------------------
-
class Test
{
public static void main(String[] args)
{
System.out.println(5/2);//2
System.out.println(5.0/2);//2.5
System.out.println(5/2.0);//2.5
System.out.println(5.0/2.0);//2.5
Assignment Operator(=)

It is used to store some value into a variable and used in 3 ways:


Example:
1) int x=5 2) int x=y+5 3) int x=y

Note: 1. Can not use more than one variable at left hand side of = operator.
Example: x + y=15
2. can not use literal or constant at the left hand side Example: 15=x

Compact Notation when same variable have to be used on both the sides of the
operator:

55
Assignment Operator(=)
class Test
L ----> only variable {
R ----> variable | constant | expressions public static void main(String[] args)
{
int a=4,b=1;

class Test System.out.println(a);//4


{
public static void main(String[] args) System.out.println(b);//1
{ a = a * b;
int w,x,y,z; b = a / b;
w = 10;//constant a = a / b;
x = 20;//constant
y = w+x;//expression System.out.println(a);//1
z = y;//variable
System.out.println(b);//4
} }
} }
Relational operator
Relational Operators are used to compare data
== Equals to Apply to any type

!= Not equals to Apply to any type

> Greater than Apply to numerical type

< Less than Apply to numerical type

>= Greater than or equal Apply to numerical type

<= Less than or equal Apply to numerical type


--> nesting of relational operators is not
Example:
allowed in java.
class Test
Example:
{
class Test
public static void main(String[] args)
{
{
public static void main(String[] args)
System.out.println(5<2); //false
{
System.out.println(5<=2); //false
System.out.println(1<2<3);//CE:
System.out.println(5>2); //true
}
System.out.println(5>=2); //true
}
System.out.println(5==2); //false
System.out.println(5!=2); //true
}
}
Test.java:5: error: bad operand types for
binary operator '<'
System.out.println(1<2<3); //CE:
^
first type: boolean
second type: int
1 error
Logical operators
Used to combine more than one relational test into a
compound relational test
& op1 & op2 Logical AND
| op1 | op2 Logical OR
&& op1 && op2 Short-circuit
AND
|| op1 || op2 Short-circuit OR
! ! op Logical NOT
^ op1 ^ op2 Logical XOR
Bit wise operators
These operators act on individual bits(0 and 1)of the
operand. They act on only integer data types(byte, short, int
and long)
~ ~op Inverts all bits

& op1 & op2 Produces 1 bit if both operands are 1

| op1 |op2 Produces 1 bit if either operand is 1

^ op1 ^ op2 Produces 1 bit if exactly one operand is 1

>> op1 >> op2 Shifts all bits in op1 right by the value of
op2
<< op1 << op2 Shifts all bits in op1 left by the value of
op2
Bit wise operators
 Examples:

& Bitwise AND0110 & 0011  0010


| Bitwise OR 0110 | 0011  0111
^ Bitwise XOR0110 ^ 0011  0101
<< Left shift 01101110 << 2 
10111000
>> Right shift 01101110 >> 3 
00001101
~ One's complement ~0011  1100

 Notice: << and >> multiply/divide by 2n


 Don't confuse bitwise & | with logical && ||
Increment and Decrement Operators
 Can add or subtract 1 to or from variables

++ for Increment – – for Decrement


i = i + 1; //same as ++i i = i - 1; //same as – – I

They can go on either side of the modified variable

prefix form: variable is changed before expression is evaluated


postfix form: variable is changed after expression is evaluated
Increment and Decrement Operators, cont.

int i = 10; Same effect as


int newNum = 10 * i++; int newNum = 10 * i;
i = i + 1;

int i = 10; Same effect as


int newNum = 10 * (++i); i = i + 1;
int newNum = 10 * i;

63
Increment and Decrement Operators, cont.

 Using increment and decrement operators makes


expressions short, but it also makes them complex
and difficult to read.

 Avoid using these operators in expressions that


modify multiple variables, or the same variable for
multiple times such as this: int k = ++i + i.

64
The conditional Operator
 Ternary operator requires three operands (as opposed to
the unary’s single and the binary’s double operand
requirement)
 Syntax :-
variable = expression1? expression2 :expression3;

 expression1 is evaluated, If it is true then expression2


value is stored into the variable. If expression1 is false
expression3 values is stored into the variable.
Example:
(sales > 1000) ? Bonus = 500 : Bonus = 0;

(a > b) ? (ans = 10): (ans = 25);

ans = (a > b) ? (10): (25);


Example: WJP to check whether the number is even | odd.
==================================================
class Test
{
public static void main(String[] args)
{
int x=41;
System.out.println((x%2==0)?"even number":"odd number");//
}
}

Example: WJP to find biggest of two numbers


=====================================
class Test
{
public static void main(String[] args)
{
int x=41;
int y=45;
System.out.println((x>y)?x:y);//
}
}
Member Operator(.)
It is also called dot/period operator. This operator tells about member of a package
or a class.

Example:
We know that each class contains variables and methods. To refer to the variables of
class member operator is used.

Syntax:
classname . variablename;
objectname . variablename;

Similarly Method of a class can be accessed

classname . mehtodname;
objectname . mehtodname;
Control Statements
One-way if Statements
Java supports two selection statements: if and switch. These statements allow you to
control the flow of your program’s execution based upon conditions known only during
run time.

if (boolean-expression) if (radius >= 0)


{ {
statement(s); area = radius * radius * PI;
}
System.out.println("The area
for the circle of radius " +radius + " is "
+ area);
}
Following are the properties of an if statement:

 If the condition is true then the simple or compound


statements are executed.
 If the condition is false it does not do anything.
 The condition is given in parentheses and must be
evaluated as true (nonzero value) or false (zero value).
 If a compound statement is provided, it must be enclosed
in opening and closing braces.({ })
Note
if i > 0 { if (i > 0) {
System.out.println("i is positive"); System.out.println("i is positive");
} }
(a) Wrong (b) Correct

if (i > 0) { if (i > 0)
System.out.println("i is positive"); Equivalent System.out.println("i is positive");
}

(a) (b)
Note:
o The Boolean expression is enclosed in parentheses for all forms of the if
statement. Thus, the outer parentheses in the previous if statements are
required.

o The braces can be omitted if they enclose a single statement.


Simple if Demo
Write a program that prompts the user to enter an integer. If the
number is a multiple of 5, print HiFive. If the number is divisible by
2, print HiEven.
import java.util.Scanner;
public class SimpleIfDemo
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter an integer: ");
int number = input.nextInt();
if (number % 5 == 0)
System.out.println("HiFive");
if (number % 2 == 0)
System.out.println("HiEven");
}
}
if-else Example

if (radius >= 0)
{
area = radius * radius * 3.14159;

System.out.println("The area for the circle of


radius " + radius + " is " + area);
}
else
{
System.out.println("Negative input");
}
The Two-way if Statement
if (boolean-expression)
{
statement(s) //for-the-true-case;
}
else
{
statement(s) //for-the-false-case;
}
Multiple Alternative if Statements
(Nested If)
 The statement in an if or if ... else statement can be any legal
Java statement, including another if or if ... else statement. The
inner if statement is said to be nested inside the outer if
statement.
 The inner if statement can contain another if statement.
 There is no limit to the depth of the nesting.
Multiple Alternative if Statements
(Nested If)
if (score >= 90.0) if (score >= 90.0)
System.out.print("A"); System.out.print("A");
else else if (score >= 80.0)
if (score >= 80.0) Equivalent System.out.print("B");
System.out.print("B"); else if (score >= 70.0)
else System.out.print("C");
if (score >= 70.0) else if (score >= 60.0)
System.out.print("C"); System.out.print("D");
else else
if (score >= 60.0) This is better and System.out.print("F");
System.out.print("D"); easier to read
else
System.out.print("F");

(a) (b)
Multi-Way if-else Statements
Trace if-else statement
animation

Suppose score is 70.0 The condition is false

if (score >= 90.0)


System.out.print("A");
else if (score >= 80.0)
System.out.print("B");
else if (score >= 70.0)
System.out.print("C");
else if (score >= 60.0)
System.out.print("D");
else
System.out.print("F");
Trace if-else statement
animation

Suppose score is 70.0 The condition is false

if (score >= 90.0)


System.out.print("A");
else if (score >= 80.0)
System.out.print("B");
else if (score >= 70.0)
System.out.print("C");
else if (score >= 60.0)
System.out.print("D");
else
System.out.print("F");
Trace if-else statement
animation

Suppose score is 70.0 The condition is true

if (score >= 90.0)


System.out.print("A");
else if (score >= 80.0)
System.out.print("B");
else if (score >= 70.0)
System.out.print("C");
else if (score >= 60.0)
System.out.print("D");
else
System.out.print("F");
Trace if-else statement
animation

Suppose score is 70.0 grade is C

if (score >= 90.0)


System.out.print("A");
else if (score >= 80.0)
System.out.print("B");
else if (score >= 70.0)
System.out.print("C");
else if (score >= 60.0)
System.out.print("D");
else
System.out.print("F");
Trace if-else statement
animation

Suppose score is 70.0 Exit the if statement

if (score >= 90.0)


System.out.print("A");
else if (score >= 80.0)
System.out.print("B");
else if (score >= 70.0)
System.out.print("C");
else if (score >= 60.0)
System.out.print("D");
else
System.out.print("F");
Note
The else clause matches the most recent if clause in the
same block.
Note, cont.
Nothing is printed from the preceding statement. To force
the else clause to match the first if clause, you must add a
pair of braces:
int i = 1;
int j = 2;
int k = 3;
if (i > j)
{
if (i > k)
System.out.println("A");
}
else
System.out.println("B");

Output: This statement prints B.


Common Errors
Adding a semicolon at the end of an if clause is a common mistake.
if (radius >= 0);
{
area = radius*radius*PI; Wrong
System.out.println( "The area for the circle of radius " + radius +
" is " + area);
}

This mistake is hard to find, because it is not a compilation error or


a runtime error, it is a logic error.

This error often occurs when you use the next-line block style.
TIP

if (number % 2 == 0) Equivalent
even = true; boolean even
else = number % 2 == 0;
even = false;
(a) (b)
CAUTION

Equivalent if (even)
if (even == true)
System.out.println( System.out.println(
"It is even."); "It is even.");
(a) (b)
Switch Statements
switch(control variable)
{
case value1:
//Statements Sequence
break;

case value2:
//Statements Sequence
break;
.
.
case value N:
//Statements Sequence
break;

default:
//Statements Sequence
}
Switch Statements
• The expression must be of type byte, short, int, or char; each of the
values specified in the case statements must be of a type compatible
with the expression
• Each case value must be a unique literal. Duplicate case values are not
allowed.

• Note that this statement does not allow less than, greater than, etc.
ONLY the equality operator (==) is used with a switch statement.

• The value of the expression is compared with each of the literal values
in the case statements. If a match is found, the code sequence
following that case statement is executed.

• The default statement is executed if none of the constants matches


the value of the expression is optional. If no case matches and no
default is present, then no further action is taken.
// A simple example of the switch.
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.");
}
}
• The break statement is used inside the switch to terminate a
statement sequence. When a break statement is encountered,
execution branches to the first line of code that follows the
entire switch statement(“Jumping out “of switch).

• The break statement is optional. If you omit the break,


execution will continue on into the next case. It is sometimes
desirable to have multiple cases without statements
between them.
animation

Trace switch statement


Suppose day is 2:

switch (day) {
case 1:
case 2:
case 3:
case 4:
case 5: System.out.println("Weekday"); break;
case 0:
case 6: System.out.println("Weekend");
}
animation

Trace switch statement


Match case 2

switch (day) {
case 1:
case 2:
case 3:
case 4:
case 5: System.out.println("Weekday"); break;
case 0:
case 6: System.out.println("Weekend");
}
animation

Trace switch statement


Fall through case 3

switch (day) {
case 1:
case 2:
case 3:
case 4:
case 5: System.out.println("Weekday"); break;
case 0:
case 6: System.out.println("Weekend");
}
animation

Trace switch statement


Fall through case 4

switch (day) {
case 1:
case 2:
case 3:
case 4:
case 5: System.out.println("Weekday"); break;
case 0:
case 6: System.out.println("Weekend");
}
animation

Trace switch statement


Fall through case 5

switch (day) {
case 1:
case 2:
case 3:
case 4:
case 5: System.out.println("Weekday"); break;
case 0:
case 6: System.out.println("Weekend");
}
animation

Trace switch statement


Encounter break

switch (day) {
case 1:
case 2:
case 3:
case 4:
case 5: System.out.println("Weekday"); break;
case 0:
case 6: System.out.println("Weekend");
}
animation

Trace switch statement


Exit the statement

switch (day) {
case 1:
case 2:
case 3:
case 4:
case 5: System.out.println("Weekday"); break;
case 0:
case 6: System.out.println("Weekend");
}
// In a switch, break statements are optional.
class MissingBreak
{
public static void main(String args[])
{
for(int i=0; i<12;i++)
switch(i)
{
case 0:
case 1:
case 2:
case 3:
case 4: System.out.println("i is less than 5");
break;
case 5:
case 6:
case 7:
case 8:
case 9: System.out.println("i is less than 10");
break;
default: System.out.println("i is 10 or more");
}}}
switch Statements
switch (status)
{
case 0:
compute taxes for single filers;
break;
case 1:
compute taxes for married file jointly;
break;
case 2:
compute taxes for married file separately;
break;
case 3:
compute taxes for head of household;
break;
default:
System.out.println("Errors: invalid status");
System.exit(1);
}
switch Statement Flow Chart
switch Statement Rules
The switch-expression
must yield a value of char, switch (switch-expression)
byte, short, or int type and {
must always be enclosed
in parentheses. case value1: statement(s)1;
break;
case value2: statement(s)2;
The value1, ..., and valueN must break;
have the same data type as the …
value of the switch-expression. case valueN: statement(s)N;
The resulting statements in the break;
case statement are executed when default: statement(s)-for-default;
the value in the case statement }
matches the value of the switch-
expression. Note that value1, ...,
and valueN are constant
expressions, meaning that they
cannot contain variables in the
expression, such as 1 + x.
switch Statement Rules

The keyword break is optional, switch (switch-expression) {


but it should be used at the end case value1: statement(s)1;
of each case in order to
break;
terminate the remainder of the
switch statement. If the break case value2: statement(s)2;
statement is not present, the break;
next case statement will be …
executed. case valueN: statement(s)N;
break;
The default case, which is default: statement(s)-for-default;
optional, can be used to }
perform actions when none of
the specified cases matches When the value in a case statement matches the value
the switch-expression. of the switch-expression, the statements starting from
this case are executed until either a break statement or
the end of the switch statement is reached.
Motivations
Suppose that you need to print a string (e.g., "Welcome to Java!") a
hundred times. It would be tedious to have to write the following
statement a hundred times:

System.out.println("Welcome to Java!");

So, how do you solve this problem?


Opening Problem
Problem:

System.out.println("Welcome to Java!");
System.out.println("Welcome to Java!");
System.out.println("Welcome to Java!");
System.out.println("Welcome to Java!");
System.out.println("Welcome to Java!");
System.out.println("Welcome to Java!");
100
times …


System.out.println("Welcome to Java!");
System.out.println("Welcome to Java!");
System.out.println("Welcome to Java!");
Introducing while Loops(Entry Controlled)
int count = 0;
while (count < 100)
{
System.out.println("Welcome to Java");
count++;
}

The syntax for the while loop is as follows:


while (loop-continuation-condition)
{
// loop-body Statement(s);
}
Introducing while Loops
• The braces enclosing a while loop or any other loop can be
omitted only if the loop body contains one or no statement. The
while loop flowchart is in Figure (a).
• The loop-continuation-condition, a Boolean expression, must
appear inside the parentheses. It is always evaluated before the
loop body is executed.
• If its evaluation is true, the loop body is executed; if its
evaluation is false, the entire loop terminates, and the program
control turns to the statement that follows the while loop.

Note
• Make sure that the loop-continuation-condition eventually
becomes false so that the program will terminate.
• A common programming error involves infinite loops.
while Loop Flow Chart
int count = 0;
while (loop-continuation-condition) {
while (count < 100) {
// loop-body;
System.out.println("Welcome to Java!");
Statement(s); count++;
} }
animation
Trace while Loop
Initialize count
int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}
animation
Trace while Loop, cont.
(count < 2) is true
int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}
animation
Trace while Loop, cont.
Print Welcome to Java
int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}
animation
Trace while Loop, cont.
Increase count by 1
int count = 0; count is 1 now
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}
animation
Trace while Loop, cont.
(count < 2) is still true since count
int count = 0; is 1
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}
animation
Trace while Loop, cont.
Print Welcome to Java
int count = 0;
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}
animation
Trace while Loop, cont.
Increase count by 1
int count = 0; count is 2 now
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}
animation
Trace while Loop, cont.
(count < 2) is false since count is 2
int count = 0; now
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}
animation
Trace while Loop
The loop exits. Execute the next
int count = 0; statement after the loop.
while (count < 2) {
System.out.println("Welcome to Java!");
count++;
}
Example

public class Factwhile


{
public static void main(String[] args)
{
int fact = 1;
int x = 5;
while(x>=1)
{
fact = fact * x;
x--;
}
System.out.println("Factorial of the given number is:: "+fact);
}
}
//Sum of first n natural numbers

public class SumNatural


{
public static void main(String[] args)
{
int num = 50, i = 1, sum = 0;
while(i <= num)
{
sum += i; i++;
}
System.out.println("Sum = " + sum);
}
}
The “do while” statement

 Syntax
do {
statement;
statement;
} while (condition);
statement

// Do not Forget ”;”


The “do while” statement(Exit Controlled)

• The loop body is executed first. Then the loop-continuation- condition


is evaluated.
• If the evaluation is true, the loop body is executed again; if it is false,
the do-while loop terminates.
• The major difference between a while loop and a do-while loop is the
order in which the loop-continuation-condition is evaluated and the loop
body executed.
• The while loop and the do-while loop have equal expressive power.
• Sometimes one is a more convenient choice than the other.
• Tip: Use the do-while loop if you have statements inside the loop that
must be executed at least once.
Example

public class Factdo


{
public static void main(String[] args)
{
int fact=1,x = 5;
do
{
fact *= x;
x = x-1;
} while (x > 1);

System.out.printf("Factorial of 5=%d", fact);


}
}
for Loops
for (initial-action; loop-continuation-condition; action-after-each-iteration)
{
// loop body;
int i;
Statement(s);
for (i = 0; i < 100; i++)
}
{
System.out.println("Welcome to Java!");}
animation
Trace for Loop
Declare i
int i;
for (i = 0; i < 2; i++) {
System.out.println(
"Welcome to Java!");
}
animation
Trace for Loop, cont.
Execute initializer
int i; i is now 0
for (i = 0; i < 2; i++) {
System.out.println(
"Welcome to Java!");
}
animation
Trace for Loop, cont.
(i < 2) is true
int i; since i is 0
for (i = 0; i < 2; i++) {
System.out.println( "Welcome to Java!");
}
animation
Trace for Loop, cont.
Print Welcome to Java
int i;
for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!");
}
animation
Trace for Loop, cont.
Execute adjustment statement
int i; i now is 1
for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!");
}
animation
Trace for Loop, cont.
(i < 2) is still true
int i; since i is 1
for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!");
}
animation
Trace for Loop, cont.
Print Welcome to Java
int i;
for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!");
}
animation
Trace for Loop, cont.
Execute adjustment statement
int i; i now is 2
for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!");
}
animation
Trace for Loop, cont.
(i < 2) is false
int i; since i is 2
for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!");
}
animation
Trace for Loop, cont.
Exit the loop. Execute the next
int i; statement after the loop
for (i = 0; i < 2; i++) {
System.out.println("Welcome to Java!");
}
Example

public class Factfor


{
public static void main(String[] args)
{
int fact=1,x = 5,i;
for(i=1;i<=x;i++)
{
fact *= i;

System.out.printf("Factorial of 5=%d", fact);


}
}
public class SumNatural
{
public static void main(String[] args)
{
int num = 100, sum = 0;
for(int i = 1; i <= num; ++i)
{
// sum = sum + i;
sum += i;
}
System.out.println("Sum = " + sum);
}
}
Note
The initial-action in a for loop can be a list of zero or more
comma-separated expressions. The action-after-each-
iteration in a for loop can be a list of zero or more comma-
separated statements. Therefore, the following two for
loops are correct. They are rarely used in practice,
however.
for (int i = 1; i < 100; System.out.println(i++));

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


{
// Do something
}
Note
If the loop-continuation-condition in a for loop is omitted,
it is implicitly true. Thus the statement given below in (a),
which is an infinite loop, is correct. Nevertheless, it is
better to use the equivalent loop in (b) to avoid confusion:

for ( ; ; ) { Equivalent while (true) {


// Do something // Do something
} }
(a) (b)
Caution
Adding a semicolon at the end of the for clause before
the loop body is a common mistake, as shown below:
Logic
Error

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


{
System.out.println("i is " + i);
}
Caution, cont.
Similarly, the following loop is also wrong:
int i=0;
while (i < 10); Logic Error
{
System.out.println("i is " + i);
i++;
}

In the case of the do loop, the following semicolon is needed


to end the loop.
int i=0;
do {
System.out.println("i is " + i);
i++; Correct
} while (i<10);
Which Loop to Use?
The three forms of loop statements, while, do-while, and for, are
expressively equivalent; that is, you can write a loop in any of these
three forms. For example, a while loop in (a) in the following figure
can always be converted into the following for loop in (b):
while (loop-continuation-condition) { Equivalent for ( ; loop-continuation-condition; )
// Loop body // Loop body
} }
(a) (b)

A for loop in (a) in the following figure can generally be converted into the
following while loop in (b) except in certain special cases (see Review Question
3.19 for one of them):
for (initial-action; initial-action;
loop-continuation-condition; Equivalent while (loop-continuation-condition) {
action-after-each-iteration) { // Loop body;
// Loop body; action-after-each-iteration;
} }
(a) (b)
Jumping Statements:
• Java supports three jump statements: break, continue, and return.
These statements transfer control to another part of your program.

• In Java, the break statement has three uses.


 First, as you have seen, it terminates a statement sequence in a switch
statement.
 Second, it can be used to exit a loop.
 Third, it can be used as a “civilized” form of goto.

Using break to Exit a Loop:

• By using break, you can force immediate termination of a loop,


bypassing the conditional expression and any remaining code in the body
of the loop.

• When a break statement is encountered inside a loop, the loop is


terminated and program control resumes at the next statement following
the loop.
// Using break to exit a loop.

class BreakLoop
{
public static void main(String args[])
{
for(int i=0; i<=100;i++)
If(i==10)
break;
System.out.println("i: " + i);
}
System.out.println("Loop complete.");
}
}
output:
i: 0
i: 1
i: 2
i: 3
i: 4
i: 5
i: 6
i: 7
i: 8
i: 9
Loop complete.
Using break as a Form of Goto:
• Java does not have a goto statement because it provides a way to branch
in an arbitrary and unstructured manner.

• The general form of the labeled break statement is shown here:


break label;

• Most often, label is the name of a label that identifies a block of code.
This can be a stand-alone block of code but it can also be a block that is
the target of another statement.

• When this form of break executes, control is transferred out of the named
block. The labeled block must enclose the break statement, but it does
not need to be the immediately enclosing block.

• To name a block, put a label at the start of it. A label is any valid Java
identifier followed by a colon. Once you have labeled a block, you can
then use this label as the target of a break statement.
// Using break as a civilized form of goto.
class Break
{
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");
} // Third
System.out.println("This won't execute");
} // Second
System.out.println("This is after second block.");
} //First
}
}

OUTPUT:
Before the break.
This is after second block.
// Using break to exit from nested loops

class BreakLoop4
{
public static void main(String args[])
{
outer: for(int i=0; i<3;i++)
{
System.out.print("Pass " + i + ": ");
for(int j=0; j<100;j++)
{
if(j == 10)
break outer; // exit both loops
System.out.print(j + " ");
}
System.out.println("This will not print");
} //outer
System.out.println("Loops complete.");
}
}

Output:
Pass 0: 0 1 2 3 4 5 6 7 8 9 Loops complete.
Using continue:
• Continue is used inside a loop to repeat the next iteration of the loop.
• When continue is executed subsequent statements in the loop are not executed
and control of execution goes back to the next iteration of the loop
Syntax: continue;

// Demonstrate continue.
class DemoContinue
{
public static void main(String args[])
{
for(int i=10; i>=1;i--)
{
if (i>5) continue;
System.out.println(i+" ");
}
}
}

Output: 5 4 3 2 1
Note: As with the break statement, continue may specify a label to describe which
enclosing loop to continue.
Return:
• The last control statement is return. The return statement is used to explicitly
return from a method. That is, it causes program control to transfer back to
the caller of the method.
• At any time in a method the return statement can be used to cause execution
to branch back to the caller of the method.
• Thus, the return statement immediately terminates the method in which it is
executed.
public class Demo
{
public static void main(String args[])
{
int res=DemoReturn.myMethod(10);
System.out.println("Result is="+res);
}

static int myMethod(int num)


{
return num*num;
}

}
Array
s
• An array is a group of liked-typed variables referred to
by a common name
• Individual variables accessed by their index.
• Arrays are:
1) declared
2) created
3) initialized
4) used
• Also, arrays can have one or several dimensions.
Array Declaration
• Array declaration involves:
1) declaring an array identifier
2) declaring the number of dimensions
3) declaring the data type of the array elements

• Two styles of array declaration:


type array-variable[];
(Or)
type [] array-variable;
Example: int month_days[];
Array Creation
• After declaration, no array actually exists.
• In order to create an array, we use the new operator:
type array-variable[];
array-variable = new type[size];
• This creates a new array to hold size elements of
type type, which reference will be kept in the
variable array-variable.
Array Indexing

• Later we can refer to the elements of this


array through their indexes:
• array-variable[index]
• The array index always starts with zero!
• The Java run-time system makes sure that all
array indexes are in the correct range,
otherwise raises a run-time error.
Array Initialization

• Arrays can be initialized when they are declared:


• int monthDays[] = {31,28,31,30,31,30,31,31,30,31,30,31};
• Note:
1) there is no need to use the new operator
2) the array is created large enough to hold all
specified elements
// An improved version of the previous program.

class Array
{
public static void main(String args[])
{
int month_days[];
month_days = new int[12];
month_days[0] = 31;
month_days[1] = 28;
month_days[2] = 31;
month_days[3] = 30;
month_days[4] = 31;
month_days[5] = 30;
month_days[6] = 31;
month_days[7] = 31;
month_days[8] = 30;
month_days[9] = 31;
month_days[10] = 30;
month_days[11] = 31;
System.out.println("April has " + month_days[3] + " days.");
}
}
// An improved version of the previous program.

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


{
int month_days[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
System.out.println("April has " + month_days[3] + " days.");
}
}

// Average an array of values. class Average


{
public static void main(String args[])
{
double nums[] = {10.1, 11.2, 12.3, 13.4, 14.5};
double result = 0;
int i;
for(i=0; i<5;i++)
result=result+nums[i];
System.out.println(“Average is:”+result/5);
}
}
Multidimensional Arrays

• Multidimensional arrays are arrays of arrays:


1) declaration: int array[][];
2) creation: int array = new int[2][3];
3) initialization
int array[][] = { {1, 2, 3}, {4, 5, 6} };
// Demonstrate a two-dimensional array.
class TwoDArray
{
public static void main(String args[])
{
int twoD[][]= new int[4][5];
int i, j, k = 0;
for(i=0; i<4;i++)
for(j=0; j<5;j++)
{
twoD[i][j]=k; //Storing values in array
k++;
}

for(i=0; i<4;i++)
{
for(j=0; j<5;j++)
System.out.Print(twoD[i][j]+ ””);
System.out.println();
}
}
}
Class
• A class is a user defined datatype to define the properties. A class
contains variables and methods that operate on those variables.

• In fact, Objects are variables of the type class. Once a class has been
defined, we can create any number of objects belonging to that
class.
• Classes are data types based on which objects are created. Objects
with similar properties and methods are grouped together to form a
Class. Thus a Class represents a set of individual objects
• A class is thus a collection of objects of similar type .
for example: mango, apple, and orange are members of the class
fruit . ex: fruit mango; will create an object mango belonging to the
class fruit.
Syntax:
class classname
{
type instance-variable1;
type instance-variable2;
// ...
type instance-variableN;

type methodname1(parameter-list)
{
// body of method
}

type methodname2(parameter-list)
{
// body of method
}

// ...
type methodnameN(parameter-list)
{
// body of method
}
}
Class:
A class is declared by use of the class keyword. Class name is the name of
the class we are declaring.

The data, or variables, defined within a class are called instance variables.
The code is contained within methods. Collectively methods and variables
defined inside a class are called members of the class.

a class declaration only creates a template, it does not create an actual


object.

Example:
class Box
{
double width;
double height;
double depth;
}
Where new data type is Box.
Creating an object:
Instance is an Object of a class which is an entity with its own attribute values and
methods.
class_name object_name=new class_name()

Example:
NULL
Box mybox ; Height
mybox== new Box(); Width
mybox Breadth
(OR)
Box mybox = new Box(); // create a Box object called mybox

-> Each time when an instance of a class is created, you are creating an
object that contains its own copy of each instance variable defined by the
class.

-> Thus, every Box object will contain its own copies of the instance variables
width, height, and depth.

-> To access these variables, you will use the dot (.) operator. The dot operator links
the name of the object with the name of an instance variable.
Example:
class Box
{
double width;
double height;
double depth;
}
// This class declares an object of type Box.
class BoxDemo
{
public static void main(String args[])
{
Box mybox = new Box();
double vol;

// assign values to mybox's instance variables


mybox.width = 10;
mybox.height = 20;
mybox.depth = 15;

// compute volume of box


vol = mybox.width * mybox.height * mybox.depth;
System.out.println("Volume is " + vol);
}
}
• Suppose if we create two Box objects, each has its own copy of depth,
width, and height.

• It is important to understand that changes to the instance variables of


one object have no effect on the instance variables of another.

// This program declares two Box objects.

class Box
{
double width;
double height;
double depth;
}
class BoxDemo2
{
public static void main(String args[])
{
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
// assign values to mybox1's instance variables
mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;
/* assign different values to mybox2's instance variables */
mybox2.width = 3;
mybox2.height = 6;
mybox2.depth = 9;
// compute volume of first box
vol = mybox1.width * mybox1.height * mybox1.depth;
System.out.println("Volume is " + vol);
// compute volume of second box
vol = mybox2.width * mybox2.height * mybox2.depth;
System.out.println("Volume is " + vol);
}
} Volume is 3000.0 Volume is 162.0
Methods:
classes usually consist of two things: instance variables and methods

We can add number of methods to class. This is the general form of a method:

type name(parameter-list)
{
// body of method
}

• Type specifies the type of data returned by the method. If the method does not return a
value, its return type must be void.

• The name of the method can be any legal identifier.

• The parameter-list is a sequence of type and identifier pairs separated by commas.


Parameters are essentially variables that receive the value of the arguments passed to the
method when it is called. If the method has no parameters, then the parameter list will be
empty.

• If a method return type is other than void, then method return value to calling function by
using below statement.
return value;
Adding a Method to the Box Class: class BoxDemo3
{
// This program includes a method inside public static void main(String args[])
the box class. {
Box mybox1 = new Box();
class Box Box mybox2 = new Box();
{
double width; // assign values to mybox1's instance variables
double height; mybox1.width = 10;
double depth; mybox1.height = 20;
mybox1.depth = 15;
// display volume of a box
void volume() /* assign different values to mybox2's instance
{ variables */
System.out.print("Volume is "); mybox2.width = 3;
System.out.println(width * height * depth); mybox2.height = 6;
} mybox2.depth = 9;
}
// display volume of first box
mybox1.volume();

Note: Volume() is not returning result to // display volume of second box


calling function, just printing inside mybox2.volume();
method. }
When mybox1.volume( ) is executed, the Java run-time system transfers control to the
code defined inside volume( ).

After the statements inside volume( ) have executed, control is returned to the calling
routine, and execution resumes with the line of code following the call.

Returning a Value:

what if another part of your program wanted to know the volume of a box, but not
display its value?

So it is better to implement volume( ) to compute the volume of the box and return the
result to the caller.
class Box
{ /* assign different values to mybox2's instance
double width; variables */
double height; mybox2.width = 3;
double depth; mybox2.height = 6;
mybox2.depth = 9;
// compute and return volume
double volume() Call 1
{ // get volume of first box
return width * height * depth; Return 1 vol = mybox1.volume();
} System.out.println("Volume is " + vol);
} Call 2

class BoxDemo4 Return 2 // get volume of second box


{ vol = mybox2.volume();
public static void main(String args[]) System.out.println("Volume is " + vol);
{ }
Box mybox1 = new Box(); }
Box mybox2 = new Box();
double vol;

// assign values to mybox1's instance variables


mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;
Adding a Method That Takes Parameters:

Some times we may forget to set a dimension and also in well-


designed Java programs, instance variables should be accessed only
through methods defined by their class.

A parameterized method can operate on a variety of data and/or be


used in a number of slightly different situations.

In the future, you can change the behavior of a method, but you can’t
change the behavior of an exposed instance variable.
// This program uses a parameterized class BoxDemo5
method. {
class Box public static void main(String args[])
{ {
double width; Box mybox1 = new Box();
double height; Box mybox2 = new Box();
double depth; double vol;

// compute and return volume double // initialize each box


volume() mybox1.setDim(10, 20, 15);
{ mybox2.setDim(3, 6, 9);
return width * height * depth;
} // get volume of first box
vol = mybox1.volume();
System.out.println("Volume is " + vol);
// sets dimensions of box
void setDim(double w, double h, double d) // get volume of second box
{ vol = mybox2.volume();
width = w; System.out.println("Volume is " + vol);
height = h;
depth = d; }
} }
}
Constructor

• Java supports a special method called constructor which initializes the


instance variables of an object.
• It is called immediately after the object is created but before the new
operator completes.
1) it is syntactically similar to a method:
2) it has the same name as the name of its class
3) it is written without return type; the default return type of a
class
4) Constructors can not be inherited.
• constructor is the same class. When the class has no constructor, the
default constructor automatically initializes all its instance variables
with zero. Default constructor does not accept no parameters.
Example: Default Constructor
class Box
{
double width;
double height;
double depth;

Box()
{
System.out.println("Constructing Box");
width = 10;
height = 10;
depth = 10;
}

double volume()
{
return width * height * depth;
}
}
class BoxDemo6
{
public static void main(String args[])
{
// declare, allocate, and initialize Box objects
Box mybox1 = new Box(); parentheses are needed after the
Box mybox2 = new Box(); class name because the constructor
for the class is being called.
double vol;

// get volume of first box


vol = mybox1.volume();
System.out.println("Volume is " + vol);

// get volume of second box


vol = mybox2.volume();
System.out.println("Volume is " + vol); Constructing Box
} Constructing Box
Volume is 1000.0
} Volume is 1000.0
Parameterized Constructor
In the previous example constructor just initialize the a Box object and it is not
very useful. A constructor that takes parameters is called parameterized
constructor.

class Box
{
double width;
double height;
double depth;

Box(double w, double h, double d)


{
width = w; height = h; depth = d;
}

double volume()
{
return width * height * depth;
}
class BoxDemo7
{
public static void main(String args[])
{
// declare, allocate, and initialize Box objects
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box(3, 6, 9);
double vol;

// get volume of first box


vol = mybox1.volume();
System.out.println("Volume is " + vol);

// get volume of second box


vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
} Volume is 3000.0
Volume is 162.0
Overloading Constructors

-> what if you want to be able to initialize a cube by specifying only one value that
would be used for all three dimensions?
-> What if you simply wanted a box and did not care (or know) what its initial dimensions
were?. As the Box class is currently written, these other options are not available to you.

Solution : simply overload the Box constructor so that it handles the situations just described
-> A class can have multiple constructors, all the constructors have the same name as
corresponding to the class name that they differ only in terms of their number of arguments
and order.

class Box
{
double width;
double height;
double depth;

// constructor used when all dimensions specified


Box(double w, double h, double d)
{
width = w;
height = h;
depth = d;
}
// constructor used when no dimensions specified
Box()
{
width = -1; // use -1 to indicate
height = -1; // an uninitialized
depth = -1; // box
}

// constructor used when cube is created


Box(double len)
{
width = height = depth = len;
}

// compute and return volume


double volume()
{
return width * height * depth;
}
}
class OverloadCons
{
public static void main(String args[])
{
// create boxes using the various constructors
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box();
Box mycube = new Box(7);
Output:
double vol;
Volume of mybox1 is 3000.0
Volume of mybox2 is -1.0
// get volume of first box
Volume of mycube is 343.0
vol = mybox1.volume();
System.out.println("Volume of mybox1 is " + vol);

// get volume of second box


vol = mybox2.volume();
System.out.println("Volume of mybox2 is " + vol);

// get volume of cube


vol = mycube.volume();
System.out.println("Volume of mycube is " + vol);
}
}
The this Keyword

• Sometimes a method will need to refer to the object that


invoked it. So ‘this’ can be used inside any method to refer to
the current object.

• ‘this’ is always a reference to the object on which the method


was invoked. You can use this anywhere a reference to an object
of the current class’ type is permitted

// A redundant use of this.


Box(double width, double height, double depth)
{
this.width = width;
this.height = heigh;
this.depth = depth;
}
package sec4java; class thisDemo
{
class Student public static void main(String args[])
{
{
int rollno;
Student s1=new Student(111,"ankit",5000f);
String name;
Student s2=new Student(112,"sumit",6000f);
float fee;
s1.display();
Student(int rollno, String name, float fee) s2.display();
{ }
this.rollno=rollno; }
this.name=name;
this.fee=fee; Output:
} 0 null 0.0
0 null 0.0
void display()
{ Output using this keyword:
System.out.println(rollno+" "+name+" "+fee); 111 ankit 5000.0
} 112 sumit 6000.0
}

In the above example, parameters (formal arguments) and instance variables are same.
So, we are using this keyword to distinguish local variable and instance variable.
Recursion:
Recursion is the process of defining something in terms of itself. A method that calls itself is
said to be recursive.

Example: computation of the factorial of a number using recursive method.

// A simple example of recursion.


class Recursion
class Factorial
{
{
public static void main(String args[])
// this is a recursive method
{
int fact(int n)
Factorial f = new Factorial();
{
System.out.println("Factorial of 3 is " + f.fact(3));
int result;
System.out.println("Factorial of 4 is " + f.fact(4));
if(n==1)
System.out.println("Factorial of 5 is " + f.fact(5));
return 1;
}
result = fact(n-1) * n;
return result;
}
}
}

When fact( ) is called with an argument of 1, the function returns 1;


otherwise, it returns the product of fact(n–1)*n. To evaluate this expression, fact( ) is called
with n–1. This process repeats until n equals 1 and the calls to the method begin returning.
Recursion:
• When writing recursive methods, you must have an if statement somewhere to force
the method to return without the recursive call being executed. If you don’t do this,
once you call the method, it will never return

• When a method calls itself, new local variables and parameters are allocated storage
on the stack, and the method code is executed with these new variables from the start.

• As each recursive call returns, the old local variables and parameters are removed from
the stack, and execution resumes at the point of the call inside the method

• Recursive versions of programs execute a bit more slowly than the iterative equivalent
because of the added overhead of the additional function calls.

• The main advantage to recursive methods is that they can be used to create clearer
and simpler versions of several algorithms than can their iterative relatives

Examples: Where we use recursive methods


-> Quicksort sorting algorithm
-> some types of AI-related algorithms are most easily implemented using recursive
solutions.
Access Control: Data Hiding and
Encapsulation
• Java provides control over the visibility of variables and methods.
• Encapsulation, safely sealing data within the capsule of the class
Prevents programmers from relying on details of class
implementation, so you can update without worry
• Helps in protecting against accidental or wrong usage.
• Keeps code elegant and clean (easier to maintain)

• We can use access specifiers to protect both a class variables


and its methods. They are private, protected, public
Access Modifiers: Public, Private,
Protected
• Public: keyword applied to a class, makes it available/visible
everywhere. Applied to a method or variable, completely visible.

• Default(No visibility modifier is specified): it behaves like public in its


package and can not be accessed outside the package. Default Public
keyword applied to a class, makes it available/visible everywhere.
Applied to a method or variable, completely visible.

• Private fields or methods for a class only visible within that class.
Private members can not be inherited by subclass or they are not
accessible in subclasses.
• Protected members of a class are visible within the class, subclasses
and also within all classes that are in the same package as that class.
protected applies only when inheritance is involved.
/* This program demonstrates the difference between public and private. */
class Test
{
int a; // default access
public int b; // public access private
int c; // private access

// methods to access c
void setc(int i)
{
// set c's value
c = i;
}

int getc()
{
// get c's value
return c;
}

}
class AccessTest
{
public static void main(String args[])
{
Test ob = new Test();

// These are OK, a and b may be accessed directly


ob.a = 10;
ob.b = 20;

// This is not OK and will cause an error


// ob.c = 100; // Error!
// You must access c through its methods
ob.setc(100); // OK
System.out.println("a, b, and c: " + ob.a + " " + ob.b + " " + ob.getc());
}
}
Visibility
public class Circle
{
private double x,y,r;
// Constructor
public Circle (double x, double y, double r)
{ this.x = x;
this.y = y;
this.r = r;
}
//Methods to return circumference and area
public double circumference()
{
return 2*3.14*r;
}
public double area()
{
return 3.14 * r * r; }
}}
Enumerated:
• The Enum in Java is a data type which contains a fixed set of constants.
• To create an enum, use the enum keyword . and separate the constants with a comma.
Note that they should be in uppercase letters.
• Enums are often used in switch statements to check for corresponding values:

Example:
days – {SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, and SATURDAY}
directions – {NORTH, SOUTH, EAST, and WEST)
season- {SPRING, SUMMER, WINTER, and AUTUMN or FALL}
colors – {RED, YELLOW, BLUE, GREEN, WHITE, and BLACK}

public class Main


{
enum Level { LOW, MEDIUM, HIGH }

public static void main(String[] args)


{
Level myVar = Level.MEDIUM;
System.out.println(myVar);
System.out.println(Level.valueOf(“HIGH"));
}
}
class EnumExample1
{
//defining the enum inside the class
public enum Season { WINTER, SPRING, SUMMER, FALL }

//main method
public static void main(String[] args)
{

//traversing the enum


for (Season s : Season.values())
System.out.println(s);
}
}

To get the enum for a given integer, we simply have to call the valueOf method

Season s1=s
String Handling
• String is probably the most commonly used class in Java's class library. The
obvious reason for this is that strings are a very important part of
programming.
• The first thing to understand about strings is that every string you create
is actually an object of type String. Even string constants are actually
String objects.
• For example, in the statement System.out.println("This is a String, too");
the string "This is a String, too" is a String constant

Creating Strings:
String s;
S=“Hello”;
(or)
String s=“Hello”;
• The String class contains several methods that you can use. Here are a few.

• Test two strings for equality by using equals( ).


• You can obtain the length of a string by calling the length( ) method.
• You can obtain the character at a specified index within a string by calling
charAt( ).
• To compare two strings for equality, use equals( ) and to perform a
comparison that ignores case differences, call equalsIgnoreCase( )
• compareTo( )- it is not enough to simply know whether two strings are
identical. For sorting applications, you need to know which is less than,
equal to, or greater than the next. A string is less than another if it comes
before the other in dictionary order. A string is greater than another if it
comes after the other in dictionary order
• indexOf( ) Searches for the first occurrence of a character or
substring.
• lastIndexOf( ) Searches for the last occurrence of a character or
substring.
• we can extract a substring using substring( ). 103
• concat( ) performs the same function as +.
• replace( ): The replace( ) method has two forms.
1) The first replaces all occurrences of one character in the invoking string with
another character. It has the following general form:

String replace(char original, char replacement)


Ex: String s = "Hello".replace('l', 'w');

2) The second form of replace( ) replaces one character sequence with


another. It has this general form:
String replace(CharSequence original, CharSequence replacement)
• trim( ): The trim( ) method returns a copy of the invoking string from which any leading
and trailing whitespace has been removed. It has this general form:

String trim( )
Ex: String s = " Hello World ".trim();

• The startsWith( ) method determines whether a given String begins with a specified
string. Conversely, endsWith( ) determines whether the String in question ends with a
specified string.
boolean startsWith(String str)
boolean endsWith(String str)
WAP to design a String class that performs String methods (Equal, Reverse the string, and change
the case etc).

package project1;
public class StringDemo
{
public static void main(String[] args)
{
String str = "This is some sample String with some words that have been repeated
some times";
System.out.println("Total no. of characters : " + str.length());
System.out.println("To Upper Case : " + str.toUpperCase());
System.out.println("To Lower Case : " + str.toLowerCase());
System.out.println("Original String : " + str);
System.out.println(str.substring(8));
System.out.println(str.substring(8,19));
System.out.println(str.indexOf("some"));
String s = " " + str + " ";
System.out.println(s);
System.out.println("[" + s.trim() + "]");
System.out.println(str.replace("s","$$##"));
String sh = "parth is a good boy";
System.out.println(sh + " -> " + new StringBuffer(sh).reverse());
}
}
Garbage Collection

Objects are dynamically allocated by using the new operator, such objects are
destroyed automatically and their memory is released for later reallocation in
java. This techniques is called garbage collection.

• C uses free() to release allocated memory.


• C++, dynamically allocated objects must be manually released by use of a
delete operator.
• But java takes a different approach, it handles deallocation automatically.
• It works like this: when no references to an object exist, that object is
assumed to be no longer needed, and the memory occupied by the object
can be reclaimed.
• 1. By default garbage collection method
• 2. Finalize() method -> it contains actions that must be performed before
an object is destroyed

• Finalize() is the method of Object class. This method is called just before an
object is garbage collected. finalize() method overrides to dispose system
resources, perform clean-up activities and minimize memory leaks.
Garbage Collection Example:
package sec4java;
Syntax: public class JavafinalizeExample1
{
protected void finalize() public static void main(String args[])
{ {
//finalization code JavafinalizeExample1 obj=new JavafinalizeExample1();
} //obj=null;
System.gc();
System.out.println("end of garbage collection");
}
//override
protected void finalize()
{
System.out.println("finalize method called");
}

Output:
end of garbage collection
finalize method called

You might also like