0% found this document useful (0 votes)
3 views115 pages

Module-1ppt Java

Java is an object-oriented programming language created by James Gosling in the early 1990s, known for its platform independence and the promise of 'Write Once, Run Anywhere'. It features a robust environment with built-in support for multithreading and a rich standard library, making it suitable for various applications including desktop, web, and mobile. Key concepts of Java include classes, objects, inheritance, polymorphism, and encapsulation, which are essential for object-oriented programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views115 pages

Module-1ppt Java

Java is an object-oriented programming language created by James Gosling in the early 1990s, known for its platform independence and the promise of 'Write Once, Run Anywhere'. It features a robust environment with built-in support for multithreading and a rich standard library, making it suitable for various applications including desktop, web, and mobile. Key concepts of Java include classes, objects, inheritance, polymorphism, and encapsulation, which are essential for object-oriented programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 115

Programming in Java

23ECE505A
• Java is an object-oriented programming language developed by
James Gosling and colleagues at Sun Microsystems in the early
1990s.

• Java was started as a project called "Oak" by James Gosling in


June 1991. Gosling's goals were to implement a virtual machine
and a language that had a familiar C-like notation but with
greater uniformity and simplicity than C/C++.

• The first public implementation was Java 1.0 in 1995. It made


the promise of "Write Once, Run Anywhere", with free runtimes
on popular platforms.
DIFFERENCES BETWEEN C++ AND
JAVA

C++ JAVA
C++ is platform-dependent. Java is platform-independent.

C++ is mainly used for system Java is mainly used for application
programming. programming.

C++ supports the goto statement. Java doesn't support the goto
statement.

C++ supports multiple inheritance. Java doesn't support multiple


inheritance through class. It can be
achieved by interfaces in java.
C++ supports operator overloading. Java doesn't support operator
overloading.
DIFFERENCES BETWEEN C++ AND
JAVA

C++ JAVA
C++ uses compiler only Java uses compiler and interpreter
both.

C++ supports structures and unions. Java doesn't support structures and
unions.

C++ doesn't have built-in support for Java has built-in thread support.
threads. It relies on third-party libraries
for thread support.
C++ doesn't support documentation Java supports documentation
comment. comment (/** ... */) to create
documentation for java source code.
Allows both procedural programming Support object-oriented programming
and object-oriented programming. model.
JAVA ENVIRONMENT:
• Java environment includes a number of
development tools, classes and methods.
• The development tools are part of the system
known as Java Development Kit (JDK) and the
classes and methods are part of the Java
Standard Library (JSL), also known as the
Application Programming Interface (API).
• Java Development kit (JDK) – The JDK comes with a
set of tools that are used for developing and
running Java program. It includes:
• 1. Appletviewer - (It is used for viewing the applet)
• 2. Javac - (It is a Java Compiler)
• 3. Java - (It is a java interpreter)
• 4. Javap - (Java diassembler,which convert byte
code into program description)
• 5. Javah - (It is for java C header files)
• 6. Javadoc - (It is for creating HTML document) 7.
Jdb - (It is Java debugger)
• a) javac (Java compiler) In java, we can use any text
editor for writing program and then save that
program with “.java” extension.
• Java compiler convert the source code or program
in bytecode and interpreter convert “.java” file in
“.class” file.
• b) java(Java Interpreter) As we learn that, we can
use any text editor for writing program and then
save that program with “.java” extension.
• Java compiler convert the source code or program
in bytecode and interpreter convert “.java” file in
“.class” file.
Process of building and running java program
Java Virtual Machine(jvm)
All programming language compilers convert
the source code to machine code.
Same job done by Java Compiler to run a Java
program, but the difference is that Java compiler
convert the source code into Intermediate code
is called as bytecode for a machine that does not
exist.
This machine is called the Java Virtual machine
and it exits only inside the computer memory.
Compilation process
The Virtual machine code is not machine specific. The machine specific
code is generated by Java interpreter by acting as an intermediary between
the virtual machine and real machines shown below

Conversion of byte code to machine code.


Java’s Magic: The Bytecode

• The key that allows Java to solve both the security and the
portability problems is that the output of a Java compiler is not
executable code. Rather, it is bytecode.
• Bytecode is a highly optimized set of instructions designed to
be executed by the Java run-time system, which is called the
Java Virtual Machine (JVM).
• In essence, the original JVM was designed as an interpreter for
bytecode.
• Translating a Java program into bytecode makes it much easier
to run a program in a wide variety of environments because
only the JVM needs to be implemented for each
platform.
• Although the details of the JVM will differ from platform to
platform, all understand the same Java bytecode.
• If a Java program were compiled to native code, then different
versions of the same program would have to exist for each
type of CPU connected to the Internet. This is, of course, not a
feasible solution.
• In general, when a program is compiled to an intermediate
form and then interpreted by a virtual machine, it runs slower
than it would run if compiled to executable code.
• Because bytecode has been highly optimized, the use of
bytecode enables the JVM to execute programs much faster
than you might expect.
The Java Buzzwords
Simple
• Java was designed to be easy for the
professional programmer to learn and use
effectively.
• Because Java inherits the C/C++ syntax and
many of the object-oriented features of C++,
most programmers have little trouble learning
Java.
Object-Oriented
• Although influenced by its predecessors, Java was not
designed to be source-code compatible with any other
language. This allowed the Java team the freedom to design
with a blank slate.
• Although influenced by its predecessors, Java was not
designed to be source-code compatible with any other
language. This allowed the Java team the freedom to design
with a blank slate.
• The object model in Java is simple and easy to extend, while
primitive types, such as integers, are kept as high-
performance nonobjects.
Robust
• The multi platformed environment of the Web places
extraordinary demands on a program, because the program
must execute reliably in a variety of systems. Thus, the ability
to create robust programs was given a high priority in the
design of Java.
• Because Java is a strictly typed language, it checks your code
at compile time. However, it also checks your code at run
time.
• Java virtually eliminates memory allocation and deallocation
problems by managing memory allocation and deallocation
for you.
Multithreaded
• Java was designed to meet the real-world requirement of
creating interactive, networked programs.
• To accomplish this, Java supports multithreaded
programming, which allows you to write programs that do
many things simultaneously.
• Java’s easy-to-use approach to multithreading allows you to
think about the specific behavior of your program, not the
multitasking subsystem.
Architecture-Neutral
• A central issue for the Java designers was that of code
longevity and portability. One of the main problems facing
programmers is that no guarantee exists that if you write a
program today, it will run tomorrow—even on the same
machine.
• Operating system upgrades, processor upgrades, and changes
in core system resources can all combine to make a program
malfunction.
• The Java designers made several hard decisions in the Java
language and the Java Virtual Machine in an attempt to alter
this situation. Their goal was “write once; run anywhere, any
time, forever.” To a great extent, this goal was accomplished.
Interpreted and High Performance
• Java enables the creation of cross-platform programs by
compiling into an intermediate representation called Java
bytecode. This code can be executed on any system that
implements the Java Virtual Machine.
• Java bytecode was carefully designed so that it would be easy
to translate directly into native machine code for very high
performance by using a just-in-time compiler. Java run-time
systems that provide this feature lose none of the benefits of
the platform-independent code.
Distributed

• Java is designed for the distributed environment of the


Internet because it handles TCP/IP protocols.
• In fact, accessing a resource using a URL is not much different
from accessing a file.
• Java also supports Remote Method Invocation (RMI). This
feature enables a program to invoke methods across a
network.
Dynamic

• Java programs carry with them substantial amounts of run-


time type information that is used to verify and resolve
accesses to objects at run time.
• This makes it possible to dynamically link code in a safe and
expedient manner.
• This is crucial to the robustness of the Java environment, in
which small fragments of bytecode may be dynamically
updated on a running system.
FEATURES OF
OBJECT ORIENTED PROGRAMMING

• Objects
• Classes
• Data Abstraction and
Encapsulation
• Inheritance
• Polymorphism
• Dynamic binding
• Message Passing
FEATURES OF OOP

OBJECTS
Objects are the basic run-time entities in an
object-oriented system. They may represent a
person, a place, a bank account, a table of data or
any item that the program has to handle.
FEATURES OF OOP

CLASSES
A Class is a collection objects of similar type.
For example, mango, apple and orange are
members of the class fruit;

fruit mango;
Will create an object mango belonging to the class
fruit
FEATURES OF OOP

DATA ABSTRACTION
Data abstraction refers to, providing only
essential information to the outside world
and hiding their background details.
ABSTRACTION
ABSTRACTION
FEATURES OF OOP

ENCAPSULATION
• Encapsulation is the mechanism
that binds together code (function)
and the data.

• It keeps both of them safe from


outside interference and misuse.
FEATURES OF OOP

POLYMORPHISM
• "One Interface, Multiple Methods.“ (One name, many

forms)

• Greek term which means ability to take more than one form.
FEATURES OF OOP

POLYMORPHISM
FEATURES OF OOP

INHERITANCE
• Process by which one object can acquire the

properties of other objects.

• Supports concept of hierarchical classification.

• Helps in reusability.
FEATURES OF OOP

DYNAMIC BINDING
Binding refers to the linking of a procedure call to
the code to be executed in response to the call.
Dynamic binding (also known as late binding)
means that the code associated with a given
procedure call is not known until the time of the
call at run time.
FEATURES OF OOP

MESSAGE PASSING
A message for an object is a request for execution of a
procedure, and therefore will invoke a
function(procedure) in the receiving object that generates
the desired result.
Message passing involves specifying the name of the
object, the name of the function (message) and the
information to be sent.
APPLICATIONS OF
JAVA

• Java is the most popular language, in today’s world billion of devices running on

a Java platform

• Java touched every field of development of software, java’s features make it the

most powerful language in the current market of software development

• It is most secured language in current world due to that all the banking

application development happen in java only, it is very easy to learn like C, C++

language.
APPLICATIONS OF
JAVA

Applications of Java in Real World


• Desktop GUI Application
• Scientific Application
• Enterprise Applications
• Web Applications
• Mobile Applications
• Web Servers and Application Servers
• Web Services
A SIMPLE JAVA PROGRAM

class Prg1
{
public static void main(String args[ ])
{
System.out.println(“Hello World!!!”);
}
}

Save this program as Prg1.java


To compile above program: javac Prg1.java
To run the program, we have to use Java application launcher called
java. That is, use the command : java Prg1
class is the keyword to declare a class

Prg1 is the name of the class


main() is name of the method from which the program execution starts
public is a keyword indicating the access specifier of the method
static The keyword static allows main() to be called without having to
instantiate a particular instance of the class.
void indicates that main() method is not returning anything

String args[ ] The main() method takes an array of String objects as a command-line
argument.

System is a predefined class (present in java.lang package) which gives access


to the system.

out is a static final field in System class which is of the type PrintStream .
Static fields and methods must be accessed by using the class name,
so we need to use System.out.
println is a public method in PrintStream class to print the data values
How to Read and Print an Integer value in Java
Steps for Input
1. The user enters an integer value when asked.
2. This value is taken from the user with the help of nextInt() method of Scanner Class.
3. The nextInt() method, in Java, reads the next integer value from the console into the specified variable

variableOfIntType = ScannerObject.nextInt();

where variableOfIntType is the variable in which the input value is to be stored.


And ScannerObject is the beforehand created object of the Scanner class.
Steps for Output

1. This entered value is now stored in the variableOfIntType.

2. Now to print this


value, System.out.println() or System.out.print() method is used.
The System.out.println() method, in Java, prints the value passed as
the parameter to it, on the console screen and the changes the cursor
to the next line on the console. Whereas System.out.print() method,
in Java, prints the value passed as the parameter to it, on the console
screen and the cursor remains on the next character of the console.
System.out.println(variableOfXType); printed
character on the console.
class GFG {
// main function
public static void main(String[] args)
{
// Declare the variables
int num;
// Input the integer
System.out.println("Enter the integer: ");
// Create Scanner object
Scanner s = new Scanner(System.in);
// Read the next integer from the screen
num = s.nextInt();
// Display the integer
System.out.println("Entered integer is: " + num);
// Close the Scanner object
s.close(); // Important to prevent resource leaks
}
}
+ num: The + operator is used here to concatenate (combine) the string with the
value of the variable num.
A SECOND SHORT PROGRAM
Here, we will discuss a program having variables. Variable is a
named memory location which may be assigned a value in the
program. A variable can be declared in the java program as:
type var_name;
Here, type is any built-in or user-defined data type. var_name is
any valid name given to the variable.
Program: Illustrating usage of variables
class Prg2
{

public static void main(String args[])


{
int n;

n=25;
System.out.println(“The value of n is:”+ n);

n= n*3;
System.out.print(“The current value of n is:” );
System.out.println(n);
}
}
class Main {

public static void main(String[] args) {

int first = 10;


int second = 20;

// add two numbers


int sum = first + second;
System.out.println(first + " + " + second + " = " + sum);
}
}

Output
10 + 20 = 30
Lexical Issues
Java programs are a collection of whitespace, identifiers, literals,
comments, operators, separators, and keywords.
Whitespace:
• Java is a free-form language. This means that there is no need
to follow any special indentation rules.
• In Java, whitespace is a space, tab, or newline.
Identifiers:
• Identifiers are used for class names, method names, and
variable names. An identifier may be any descriptive
sequence of uppercase and lowercase letters, numbers, or the
underscore and dollar-sign characters.
• They must not begin with a number, lest they be confused
with a numeric literal.
• Java is case-sensitive, so VALUE is a different
identifier than Value.
Literals:
• A constant value in Java is created by using a
literal representation of it.
Ex: 100 98.6 'X' "This is a test“
Comments:
i) single-line
ii) multiline
iii)documentation comment: This type of comment is used to
produce an HTML file that documents your program. The
documentation comment begins with a /** and ends with a */.
Separators:
In Java, there are a few characters that are used as separators .
The Java Keywords
• There are 50 keywords currently defined in the Java language.
These keywords, combined with the syntax of the operators and
separators, form the foundation of the Java language. These
keywords cannot be used as names for a variable, class, or
method.
Data Types, Variables, and Arrays
The Primitive Types
• Java defines eight primitive types of data: byte, short, int,
long, char, float, double, and boolean. The primitive types
are also commonly referred to as simple types.
Integers
Floating-Point Types

Characters
• In Java, the data type used to store characters is char.
• Java uses Unicode to represent characters. Unicode defines a fully
international character set that can represent all of the characters found
in all human languages.
• For this purpose, it requires 16 bits. Thus, in Java char is a 16-bit type.
The range of a char is 0 to 65,536. There are no negative chars.
• Although char is designed to hold Unicode characters, it can also be
thought of as an integer type on which you can perform arithmetic
operations. For example, you can add two characters together, or
increment the value of a character variable.
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.
Variables:
• In Java, all variables must be declared before they can be
used. The basic form of a variable declaration is shown here:
type identifier [ = value][, identifier [= value] ...] ;
• Java allows variables to be initialized dynamically, using any
expression valid at the time the variable is declared.
Type Conversion and Casting
1) Java’s Automatic Conversions:
• When one type of data is assigned to another type of variable,
an automatic type conversion will take place if the following
two conditions are met:
• The two types are compatible.
• The destination type is larger than the source type.
• When these two conditions are met, a widening conversion
takes place.
2) Casting Incompatible Types :
• To create a conversion between two incompatible types, you
must use a cast. A cast is simply an explicit type conversion. It
has this general form:
(target-type) value
Automatic Type Promotion in Expressions
• In an expression, the precision required of an intermediate
value will sometimes exceed the range of either operand.
• Consider:
byte a = 40; byte b = 50; byte c = 100;
int d = a * b / c;
• The result of the intermediate term a * b easily exceeds the
range of either of its byte operands. To handle this kind of
problem, Java automatically promotes each byte, short, or
char operand to int when evaluating an expression. This
means that the subexpression a * b is performed using
integers—not bytes.
Arrays
• An array is a group of like-typed variables that are referred to by
a common name. Arrays of any type can be created and may
have one or more dimensions. A specific element in an array is
accessed by its index. Arrays offer a convenient means of
grouping related information.
One-Dimensional Arrays:
A one-dimensional array is, essentially, a list of like-typed
variables.
• The general form of a one-dimensional array declaration is:
• type var-name[ ];
• Here, type declares the base type of the array. The base
type determines the data type of each element that
comprises the array.
• The general form of new as it applies to one-dimensional arrays appears
as follows:
• array-var = new type[size];
Ex: month_days = new int[12];
• All elements in the array will be initialized to zero.

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.");
}
}
Multidimensional Arrays
• In Java, multidimensional arrays are actually arrays of arrays.
• To declare a multidimensional array variable, specify each
additional index using another set of square brackets. For
example, the following declares a two dimensional array
variable called twoD.
• int twoD[][] = new int[4][5];
• When you allocate memory for a multidimensional array, you
need only specify the memory for the first (leftmost)
dimension. You can allocate the remaining dimensions
separately.
.
class TwoDArray {
public static void main(String args[]) {
int twoD[][]= new int[4][5];
//This line declares and initializes a 2D array with 4 rows and 5
columns.
int i, j, k = 0;
// i and j are loop variables, and k is initialized to 0. k will be used
to fill the array sequentially
for(i=0; i<4; i++) //This outer loop iterates over each row.
for(j=0; j<5; j++) //This inner loop iterates over each column in the
current row.
{
twoD[i][j] = k; // inside the loop, assigns the value of k to the
element at twoD[i][j] and then k++ increments k by 1
k++;
}
for(i=0; i<4; i++)
// After the array is filled, this loop iterates over each row to print
the elements.
{
for(j=0; j<5; j++)
System.out.print(twoD[i][j] + " ");
System.out.println();
} output
} 01234
} 56789
10 11 12 13 14
15 16 17
Operators
• Java provides a rich operator environment. Most of
its operators can be divided into the
• following four groups: arithmetic, bitwise, relational,
and logical.
Arithmetic Operators
• Arithmetic operators are used in mathematical expressions in
the same way that they are used in algebra. The operands of
the arithmetic operators must be of a numeric type. You
cannot use them on boolean types, but you can use them on
char types, since the char type in Java is, essentially, a subset
of int.
• The following table lists the arithmetic operators:
The Modulus Operator
• The modulus operator, %, returns the remainder of a division
operation. It can be applied to floating-point types as well as integer
types. The following example program demonstrates the %:
class Modulus {
public static void main(String args[]) {
int x = 42;
double y = 42.25;
System.out.println("x mod 10 = " + x % 10);
System.out.println("y mod 10 = " + y % 10);
}
}
When you run this program, you will get the following output:
x mod 10 = 2
y mod 10 = 2.25
Arithmetic Compound Assignment Operators:
• Java provides special operators that can be used to combine
an arithmetic operation with an assignment.
• There are compound assignment operators for all of the
arithmetic, binary operators. Thus, any statement of the form
• var = var op expression; eg: x = x+ can be rewritten as
• var op= expression; eg: x += 1

Increment and Decrement:


The ++ and the – – are Java’s increment and decrement
operators.
• The increment operator increases its operand by one. The
decrement operator decreases its operand by one.
The Bitwise Operators
• Java defines several bitwise operators that can be applied to
the integer types, long, int, short, char, and byte. These
operators act upon the individual bits of their operands. They
are summarized in the following table:
The Bitwise Logical Operators
The bitwise logical operators are &, |, ^, and ~. The following
table shows the outcome of each operation. The bitwise
operators are applied to each individual bit within each operand.

// Demonstrate the bitwise logical operators.


class BitLogic {
public static void main(String args[]) {
String binary[] = {
"0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111",
"1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111“ };
int a = 3; // 0 + 2 + 1 or 0011 in binary
int b = 6; // 4 + 2 + 0 or 0110 in binary
int c = a | b;
int d = a & b;
int e = a ^ b;
int f = (~a & b) | (a & ~b);
int g = ~a & 0x0f;
System.out.println(" a = " + binary[a]);
System.out.println(" b = " + binary[b]);
System.out.println(" a|b = " + binary[c]);
System.out.println(" a&b = " + binary[d]);
System.out.println(" a^b = " + binary[e]);
System.out.println("~a&b|a&~b = " + binary[f]);
System.out.println(" ~a = " + binary[g]);
}
}
output of the program:
a = 0011
b = 0110
a|b = 0111
a&b = 0010
a^b = 0101
~a&b|a&~b = 0101
~a = 1100
The Left Shift
• The left shift operator, <<, shifts all of the bits in
a value to the left a specified number of times.
• 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.
• Java’s automatic type promotions produce unexpected results
when you are shifting byte and short values. As you know, byte
and short values are promoted to int when an expression is
evaluated. Furthermore, the result of such an expression is also an
int.
• This means that the outcome of a left shift on a byte or short
value will be an int, and the bits shifted left will not be lost until
they shift past bit position 31.
• Furthermore, a negative byte or short value will be sign-extended
when it is promoted to int. Thus, the high-order bits will be filled
with 1’s.
• For these reasons, to perform a left shift on a byte or short
implies that you must discard the high-order bytes of the int
result.
• The easiest way to do this is to simply cast the result back into a
byte.
The 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.
• When a value has bits that are “shifted off,” those bits are
lost.
• Each time you shift a value to the right, it divides that
value by two—and discards any remainder.
• When you are shifting right, the top (leftmost)
bits exposed by the right shift are filled in with
the previous contents of the top bit.
• This is called sign extension and serves to
preserve the sign of negative numbers when
you shift them right. For example, –8 >> 1 is –
4, which, in binary, is
11111000 –8
>>1
1111100 –4
class GFG
{
public static void main (String[]
args) {
{
int number = 8;

// 2 bit signed right shift


int ans = number >> 2;
int ans1 = number<<2;

System.out.println(ans);
System.out.println(ans1);
}
}
}
Relational Operators
• The relational operators determine the relationship that one
operand has to the other.
• Specifically, they determine equality and ordering. The
outcome of these operations is a boolean value. The
relational operators are shown here:
class GFG {
public static void main(String[] args)
{
int var1 = 5, var2 = 10, var3 = 5;

System.out.println("Var1 = " + var1);


System.out.println("Var2 = " + var2);
System.out.println("Var3 = " + var3);

// Comparing var1 and var2 and


// printing corresponding boolean value
System.out.println("var1 != var2: "
+ (var1 != var2));

// Comparing var1 and var3 and


// printing corresponding boolean value
System.out.println("var1 != var3: "
+ (var1 != var3));
}
}
Boolean Logical Operators
• The Boolean logical operators shown here operate only on
boolean operands.
• All of the binary logical operators combine two boolean
values to form a resultant boolean value.
The Assignment Operator
• The assignment operator is the single equal sign, =.
• It has this general form:
• var = expression;
• Here, the type of var must be compatible with the type of
expression.
• The assignment operator allows you to create a chain of
assignments. For example, consider this fragment:
• int x, y, z;
• x = y = z = 100; // set x, y, and z to 100
The ? Operator

• Java includes a special ternary (three-way) operator that


can replace certain types of if-then-else statements.
This operator is the ?.
• The ? has this general form:
• expression1 ? expression2 : expression3
• Here, expression1 can be any expression that evaluates
to a boolean value. If expression1 is
true, then expression2 is evaluated; otherwise,
expression3 is evaluated. The result of the ?
• operation is that of the expression evaluated. Both
expression2 and expression3 are required
• to return the same type, which can’t be void.
class Ternary {
public static void main(String[] args)
{

// variable declaration
int n1 = 5, n2 = 10, max;
System.out.println("First num: " + n1);
System.out.println("Second num: " + n2);

// Largest among n1 and n2


max = (n1 > n2) ? n1 : n2;
// Print the largest number
System.out.println("Maximum is = " + max);
}
}
Operator Precedence
Control Statements
Java’s Selection Statements:
• Java supports two selection statements: if and
switch. These statements allow to control the flow
of your program’s execution based upon conditions
known only during run time.
if :
• The if statement is Java’s conditional branch
statement. It can be used to route program
execution through two different paths. Here is the
general form of the if statement:
if (condition) statement1;
else statement2;
Nested ifs
• A nested if is an if statement that is the target of another if or
else.
• When you nest ifs, the main thing to remember is that an
else statement always refers to the nearest if statement that
is within the same block as the else and that is
not already associated with an else.
• example:
if(i == 10) {
if(j < 20) a = b;
if(k > 100) c = d; // this if is
else a = c; // associated with this else
}
else a = d; // this else refers to if(i == 10)
The if-else-if Ladder
• A common programming construct that is based upon a
sequence of nested ifs is the if-else-if ladder. It looks like
this:
if(condition)
statement;
else if(condition)
statement;
else if(condition)
statement;
...
else
statement;
switch

• The switch statement is Java’s multiway branch statement. It provides an easy way to
dispatch execution to different parts of your code based on the value of an
expression.
• Here is the general form of a switch statement:
switch (expression) {
case value 1:
// statement sequence
break;
case value 2:
// statement sequence
break;
...
case value N:
// statement sequence
break;
default:
// default statement sequence
}
// 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.");
} } }
Iteration Statements
• Java’s iteration statements are for, while, and do-while. These statements
create loops. A loop repeatedly executes the same set of instructions until
a termination condition is met.
while:
• The while loop is Java’s most fundamental loop statement. It repeats a
statement or block while its controlling expression is true. Its general
form:
while(condition) {
// body of loop
}
• The condition can be any Boolean expression. The body of the loop will be
executed as long as the conditional expression is true.
• When condition becomes false, control passes to the next line of code
immediately following the loop.
• The curly braces are unnecessary if only a single statement is being
repeated.
// Demonstrate the while loop.
class While {
public static void main(String args[]) {
int n = 10;
while(n > 0) {
System.out.println("tick " + n);
n--;
}
}
}
• Since the while loop evaluates its conditional expression at the top of
the loop, the body of the loop will not execute even once if the
condition is false to begin with.
• The body of the while (or any other of Java’s loops) can be empty. This
is because a null statement (one that consists only of a semicolon) is
syntactically valid in Java.
// The target of a loop can be empty.
class NoBody {
public static void main(String args[]) {
int i, j;
i = 100;
j = 200;
// find midpoint between i and j
while(++i < --j) ; // no body in this loop
System.out.println("Midpoint is " + i);
}
}
This program finds the midpoint between i and j. It generates the
following output:
Midpoint is 150
do-while
• The do-while loop always executes its body at least
once, because its conditional expression is at the
bottom of the loop. Its general form is :
do {
// body of loop
} while (condition);
• Each iteration of the do-while loop first executes the
body of the loop and then evaluates the conditional
expression.
• If this expression is true, the loop will repeat.
Otherwise, the loop terminates. The condition must
be a Boolean expression.
for

for(initialization; condition; iteration) {


// body
}

// Demonstrate the for loop.


class ForTick {
public static void main(String args[]) {
int n;
for(n=10; n>0; n--)
System.out.println("tick " + n);
}
}
Nested Loops
// Loops may be nested.
class Nested {
public static void main(String args[]) {
int i, j;
for(i=0; i<10; i++) {
for(j=i; j<10; j++)
System.out.print(".");
System.out.println();
}
}
}
Jump Statements
Java supports three jump statements: break, continue, and
return. These statements transfer control to another part of your
program.

Using break :
• In Java, the break statement has three uses. First 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 while loop.
class BreakLoop2
{
public static void main(String args[])
{
int i = 0;
while(i < 100)
{
if(i == 10) break; // terminate loop if i is 10
System.out.println("i: " + i);
i++;
}
System.out.println("Loop complete.");
}
}
Using break as a Form of Goto
// 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");
}
System.out.println("This won't execute");
}
System.out.println("This is after second block.");
}}}
Running this program generates the following output:
Before the break.
This is after second block.
Using continue

• Sometimes it is useful to force an early iteration of a


loop.
• That is, you might want to continue running the loop
but stop processing the remainder of the code in its
body for this particular iteration.
• This is, in effect, a goto just past the body of the loop,
to the loop’s end. The continue
• statement performs such an action.
// Demonstrate continue.
class Continue {
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(“ ");
}
}
}
This code uses the % operator to check if i is even. If it is, the loop continues
without printing a newline.
Here is the output from this program:
01
23
45
67
89
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.
• As such, it is categorized as a jump statement.
• 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.
// Demonstrate return.
class Return {
public static void main(String args[]) {
boolean t = true;
System.out.println("Before the return.");
if(t) return; // return to caller
System.out.println("This won't execute.");
}
}
Output from this program :
Before the return.
Classes
• A class defines a new data type. Once defined, this new type can be
used to create objects of that type.
• A class is a template for an object, and an object is an instance of a
class.
The General Form of a Class:
• A class is declared by use of the class keyword.
• A class is declared by specifying the data that it contains and the code
that operates on that data.
• A simplified general form of a class definition is
shown here:
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
}
}
• The data, or variables, defined within a class are called
instance variables.
• The code is contained within methods. Collectively, the
methods and variables defined within a class are called
members of the class.
• Variables defined within a class are called instance variables
because each instance of the class (that is, each object of the
class) contains its own copy of these variables.
• Thus, the data for one object is separate and unique from the
data for another.
• Java classes do not need to have a main( ) method.
• You only specify one if that class is the starting point for your
program.
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);
}
}
Declaring Objects
Box mybox = new Box();
This statement combines the two steps just described. It can be
rewritten like this to show each step more clearly:
Box mybox; // declare reference to object
mybox = new Box(); // allocate a Box object
• The first line declares mybox as a reference to an object of
type Box.
• After this line executes, mybox contains the value null, which
indicates that it does not yet point to an actual object.
• Any attempt to use mybox at this point will result in a
compile-time error.
• The next line allocates an actual object and assigns a
reference to it to mybox.
• After the second line executes, you can use mybox as if it
were a Box object. But in reality, mybox simply holds the
memory address of the actual Box object.
• It is important to understand that new allocates memory
for an object during run time.
• Adding a Method to the Box Class
• methods define the interface to most classes. This allows the
class implementor to hide the specific layout of internal data
structures behind cleaner method abstractions.
• In addition to defining methods that provide access to data,
you can also define methods that are used internally by the
class itself.
class Box {
double width;
double height;
double depth;

// display volume of a box


void volume() {
System.out.print("Volume is ");
System.out.println(width * height * depth);
}
}
class BoxDemo3 {
public static void main(String args[]) {
Box mybox1 = new Box();
// assign values to mybox's instance variables
mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;
// display volume of the box
mybox1.volume();
}
}
Adding a Method That Takes Parameters
• Parameters allow a method to be generalized. That is, a parameterized
method can operate on a variety of data and/or be used in a number
of slightly different situations.

// This program uses a parameterized method.


class Box {
double width;
double height;
double depth;
double volume() {
return width * height * depth;
}
void setDim(double w, double h, double d) {
width = w;
height = h;
depth = d;
}}
class BoxDemo5 {
public static void main(String args[]) {
Box mybox1 = new Box();
double vol;
// initialize each box
mybox1.setDim(10, 20, 15);
// get volume of the box
vol = mybox1.volume();
System.out.println("Volume is " + vol);
}}
Constructors
• A constructor initializes an object immediately upon creation.
It has the same name as the class in which it resides and is
syntactically similar to a method.
• Once defined, the constructor is automatically called
immediately after the object is created, before the new
operator completes.
• Constructors have no return type, not even void. This is
because the implicit return type of a class’ constructor is the
class type itself.
• It is the constructor’s job to initialize the internal state of an
object so that the code creating an instance will have a fully
initialized, usable object immediately.
class Box {
double width;
double height;
double depth;

// This is the constructor for Box.


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

// compute and return volume


double volume() {
return width * height * depth;
}
}
class BoxDemo6 {
public static void main(String args[])
{
// declare, allocate, and initialize Box objects
Box mybox1 = new Box();
double vol;

// get volume of first box


vol = mybox1.volume();
System.out.println("Volume is " + vol);
}
}
Parameterized Constructors
class Box {
double width;
double height;
double depth;

// This is the constructor for Box.


Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
// compute and return volume
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);
double vol;
// get volume of the box
vol = mybox1.volume();
System.out.println("Volume is " + vol);
}
}
The this Keyword
• Sometimes a method will need to refer to the object that invoked
it.
• To allow this, Java defines the this keyword. 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.

Box(double w, double h, double d) {


this.width = w;
this.height = h;
this.depth = d;
}
Instance Variable Hiding

• it is illegal in Java to declare two local variables with the same


name inside the same or enclosing scopes.
• you can have local variables, including formal parameters to
methods, which overlap with the names of the class’ instance
variables.
• when a local variable has the same name as an instance
variable, the local variable hides the instance variable.
• Because this lets us refer directly to the object, it can be used
to resolve any name space collisions that might occur
between instance variables and local variables.
// Use this to resolve name-space collisions.
Box(double width, double height, double depth) {
this.width = width;
this.height = height;
this.depth = depth;
}
Garbage Collection
• Since objects are dynamically allocated by using the new
operator, java handles deallocation for you automatically. The
technique that accomplishes this is called garbage collection.
• 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. There is no explicit need to destroy
objects.
• Garbage collection only occurs sporadically (if at all) during
the execution of your program.

You might also like