0% found this document useful (0 votes)
4 views195 pages

Java Module 1

The document provides an introduction to Java, detailing its history, features, and programming concepts. It explains Java's syntax, object-oriented principles, and the significance of bytecode and the Java Virtual Machine (JVM). Additionally, it covers data types, variables, and basic programming constructs in Java.

Uploaded by

cschinmayi01
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views195 pages

Java Module 1

The document provides an introduction to Java, detailing its history, features, and programming concepts. It explains Java's syntax, object-oriented principles, and the significance of bytecode and the Java Virtual Machine (JVM). Additionally, it covers data types, variables, and basic programming constructs in Java.

Uploaded by

cschinmayi01
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 195

Introduction to JAVA…

Parikshith Nayaka S K
Asst. Professor
Dept of CSE

7/15/2025 1
Reference Book…

The Complete Reference Java by Herbert


Schildt, Seventh Edition, 2007, Tata
McGraw-Hill

7/15/2025 2
◼ Java is related to C++, which is a direct descendent
of C

◼ From C, Java derives its syntax

◼ Many of Java’s object-oriented features were


influenced by C++

◼ Java was conceived by James Gosling, Patrick


Naughton, Chris Warth, Ed Frank, and Mike
Sheridan at Sun Microsystems, Inc. in 1991

7/15/2025 3
◼ This language was initially called “Oak” but was
renamed “Java” in 1995

◼ Java can be used to create two types of programs:


applications and applets

◼ An application is a program that runs on your


computer, under the operating system of that
computer

◼ An applet is an application designed to be


transmitted over the Internet and executed by a
Java-compatible Web browser

7/15/2025 4
◼ An applet is actually a tiny Java program,
dynamically downloaded across the network,
just like an image, sound file, or video clip

◼ An applet is a program that can react to user


input and dynamically change—not just run
the same animation or sound over and over

7/15/2025 5
Security

◼ When you use a Java-compatible Web


browser, you can safely download Java
applets without fear of viral infection or
malicious intent

◼ Java achieves this protection by confining a


Java program to the Java execution access
to other parts of the computer environment
and not allowing it
7/15/2025 6
◼ Java is portable across many types of
computers and operating systems that are in
use throughout the world

7/15/2025 7
Java’s Magic: The Bytecode

◼ 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)

7/15/2025 8
JVM is an interpreter for bytecode

7/15/2025 9
◼ Translating a Java program into bytecode helps
makes it much easier to run a program in a wide
variety of environments

◼ The reason is straightforward: only the JVM needs


to be implemented for each platform

◼ When a program is interpreted, it generally runs


substantially slower than it would run if compiled to
executable code

◼ The use of bytecode enables the Java run-time


system to execute programs much faster than you
might expect

7/15/2025 10
◼ Sun supplies its Just In Time (JIT) compiler
for bytecode, which is included in the Java 2
release

◼ When the JIT compiler is part of the JVM, it


compiles bytecode into executable code in
real time, on a piece-by-piece, demand basis

◼ The JIT compiles code as it is needed, during


execution

7/15/2025 11
7/15/2025 12
The Java Buzzwords (Features of Java)

◼ Simple
◼ Secure
◼ Portable
◼ Object-oriented
◼ Robust
◼ Multithreaded
◼ Architecture-neutral
◼ Interpreted
◼ High performance
◼ Distributed
◼ Dynamic

7/15/2025 13
Simple
◼ If you already understand the basic concepts of
object-oriented programming, learning Java will be
even easier

◼ Because Java inherits the C/C++ syntax and many


of the object-oriented features of C++, most
programmers have little trouble learning Java

◼ Beyond its similarities with C/C++, Java has another


attribute that makes it easy to learn: it makes an
effort not to have surprising features

7/15/2025 14
Object oriented

◼ The object model in Java is simple and easy


to extend, while simple types, such as
integers, are kept as high-performance
nonobjects

7/15/2025 15
Robust

◼ Ability to create robust programs was given a


high priority in the design of Java

◼ To better understand how Java is robust,


consider two of the main reasons for program
failure: memory management mistakes and
mishandled exceptional conditions (that
is, run-time errors)

7/15/2025 16
◼ Memory management can be a difficult, tedious task
in traditional programming environments

◼ For example, in C/C++, the programmer must


manually allocate and free all dynamic memory

◼ Programmers will either forget to free memory that


has been previously allocated or, worse, try to free
some memory that another part of their code is still
using

7/15/2025 17
◼ Java virtually eliminates these problems by
managing memory allocation and
deallocation for you

◼ Java provides object-oriented exception


handling

7/15/2025 18
Multithreaded

◼ Java supports multithreaded programming,


which allows you to write programs that do
many things simultaneously

◼ The Java run-time system comes with an


elegant yet sophisticated solution for
multiprocess synchronization that enables
you to construct smoothly running interactive
systems
7/15/2025 19
Architecture-Neutral

◼ Operating system upgrades, processor upgrades,


and changes in core system resources can all
combine to make a program malfunction

◼ Java Virtual Machine in an attempt to alter this


situation

◼ Their goal was “write once; run anywhere, any time,


forever.”

7/15/2025 20
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 interpreted on any system that


provides a Java Virtual Machine

◼ the 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

7/15/2025 21
Distributed

◼ Java is designed for the distributed


environment of the Internet, because it
handles TCP/IP protocols

◼ Remote Method Invocation (RMI) feature of


Java brings an unparalleled level of
abstraction to client/server programming

7/15/2025 22
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.

7/15/2025 23
An Overview of Java

7/15/2025 24
◼ Object-oriented programming is at the core of
Java

◼ all computer programs consist of two


elements: code and data

◼ A program can be conceptually organized


around its code or around its data

7/15/2025 25
◼ That is, some programs are written around
“what is happening” and others are written
around “who is being affected.”

◼ The first way is called the process-oriented


model

◼ The process-oriented model can be thought


of as code acting on data

7/15/2025 26
◼ The second approach, Object-oriented
programming organizes a program around
its data (that is, objects) and a set of well-
defined interfaces to that data

7/15/2025 27
◼ Concept of Abstraction

7/15/2025 28
The Three OOP Principles:

◼ Encapsulation - is the mechanism that binds


together code and the data it manipulates,
and keeps both safe from outside
interference and misuse

◼ Inheritance - the process by which one


object acquires the properties of another
object

7/15/2025 29
7/15/2025 30
7/15/2025 31
◼ Polymorphism - is a feature that allows one
interface to be used for a general class of
actions

7/15/2025 32
A First Simple Program

/* This is a simple Java program.


Call this file "Example.java".*/
class Example {
// Your program begins with a call to main()
public static void main(String args[]) {
System.out.println("This is a simple Java program.");
}
}

7/15/2025 33
Compiling the Program

◼ C:\>javac Example.java

◼ The javac compiler creates a file called


Example.class that contains the bytecode
version of the program

• The output of javac is not code that can be


directly executed

7/15/2025 34
• To actually run the program, you must use
the Java interpreter, called java.

• C:\>java Example

• When a class member is preceded by public,


then that member may be accessed by code
outside the class in which it is declared

7/15/2025 35
• The keyword static allows main( ) to be
called without having to instantiate a
particular instance of the class

• The keyword void simply tells the compiler


that main( ) does not return a value

7/15/2025 36
A Second Short Program
class Example2 {
public static void main(String args[]) {
int num; // this declares a variable called num
num = 100; // this assigns num the value 100
System.out.println("This is num: " + num);
num = num * 2;
System.out.print("The value of num * 2 is ");
System.out.println(num);
}
}

7/15/2025 37
Two Control Statements

The if Statement:
if(condition) statement;

if(num < 100)


System.out.println("num is less than 100");

7/15/2025 38
The for Loop:

for(initialization; condition; iteration) statement;

class ForTest {
public static void main(String args[]) {
int x;
for(x = 0; x<10; x = x+1)
System.out.println("This is x: " + x);
}
}
7/15/2025 39
Using Blocks of Code:
using { and }

7/15/2025 40
Lexical Issues

• Whitespace:
– Java is a free-form language
– In Java, whitespace is a space, tab, or newline

• Identifiers:
- Identifiers are used for class names,
method names, and variable names
- Java is case-sensitive

7/15/2025 41
7/15/2025 42
Literals:
• A constant value in Java is created by using
a literal representation of it

7/15/2025 43
Comments
• There are three types of comments defined by Java.

• Single-line and multiline

• The third type is called a documentation comment

• This type of comment is used to produce an HTML


file that documents your program

• The documentation comment begins with /** and


ends with */

7/15/2025 44
Separators

7/15/2025 45
The Java Keywords
• There are 49 reserved keywords currently
defined in the Java language

7/15/2025 46
7/15/2025 47
Data Types, Variables,
and
Arrays

7/15/2025 48
Java Is a Strongly Typed Language

• Every variable has a type, every expression has a


type, and every type is strictly defined

• All assignments, whether explicit or via parameter


passing in method calls, are checked for type
compatibility

• The Java compiler checks all expressions and


parameters to ensure that the types are compatible

7/15/2025 49
The Simple Types

Java defines eight simple (or elemental)


types of data: byte, short, int, long, char,
float, double, and boolean

7/15/2025 50
Integers

7/15/2025 51
class Light {
public static void main(String args[]) {
int lightspeed;
long days;
long seconds;
long distance;
// approximate speed of light in miles per second
lightspeed = 186000;
days = 1000; // specify number of days here
seconds = days * 24 * 60 * 60; // convert to seconds
distance = lightspeed * seconds; // compute distance
System.out.print("In " + days);
System.out.print(" days light will travel about ");
System.out.println(distance + " miles.");
}
}

7/15/2025 52
Floating-Point Types

7/15/2025 53
class Area {
public static void main(String args[ ]) {
double pi, r, a;
r = 10.8; // radius of circle
pi = 3.1416; // pi, approximately
a = pi * r * r; // compute area
System.out.println("Area of circle is " + a);
}
}

7/15/2025 54
Characters
• char in Java is not the same as char in C or C++.

• In C/C++, char is an integer type that is 8 bits wide

• Instead, 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

7/15/2025 55
• In Java char is a 16-bit type

• The range of a char is 0 to 65,536

• There are no negative chars

7/15/2025 56
class CharDemo {
public static void main(String args[ ]) {
char ch1, ch2;
ch1 = 88; // code for X
ch2 = 'Y';
System.out.print("ch1 and ch2: ");
System.out.println(ch1 + " " + ch2);
}
}

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

7/15/2025 58
Booleans

• Can have only one of two possible values,


true or false

7/15/2025 59
class BoolTest {
public static void main(String args[]) {
boolean b;
b = false;
System.out.println("b is " + b);
b = true;
System.out.println("b is " + b);
// a boolean value can control the if statement
if(b) System.out.println("This is executed.");
b = false;
if(b) System.out.println("This is not executed.");
// outcome of a relational operator is a boolean value
System.out.println("10 > 9 is " + (10 > 9));
}
}
The output generated by this program is shown here:
b is false
b is true
This is executed.
10 > 9 is true
7/15/2025 60
• Integer Literals – Decimal, Hexa and Octal

• Floating-Point Literals
– For example, 2.0, 3.14159, and 0.6667 represent
valid standard - notation floating-point numbers

- Scientific notation uses a standard-notation,


floating-point number plus a suffix that specifies a
power of 10 by which the number is to be
multiplied eg. 6.022E23, 314159E–05, and
2e+100

7/15/2025 61
• Boolean Literals – true , false

• Character Literals
– Characters in Java are indices into the Unicode
character set
- They are 16-bit values that can be converted into
integers and manipulated with the integer
operators, such as the addition and subtraction
operators
- A literal character is represented inside a pair of
single quotes

7/15/2025 62
7/15/2025 63
String Literals
• “Hello World”
• “two\nlines”
• “\”This is in quotes\””

7/15/2025 64
Declaring a Variable

type identifier [ = value][, identifier [= value] ...] ;

7/15/2025 65
Dynamic Initialization

class DynInit {
public static void main(String args[]) {
double a = 3.0, b = 4.0;
// c is dynamically initialized
double c = Math.sqrt(a * a + b * b);
System.out.println("Hypotenuse is " + c);
}
}

7/15/2025 66
The Scope and Lifetime of Variables

• Java allows variables to be declared within


any block

• A block is begun with an opening curly brace


and ended by a closing curly brace

• A block defines a scope

7/15/2025 67
• In Java, the two major scopes are those defined by
a class and those defined by a method

• As a general rule, variables declared inside a scope


are not visible (that is, accessible) to code that is
defined outside that scope

• Scopes can be nested

• Objects declared in the outer scope will be visible to


code within the inner scope ; but reverse not true

7/15/2025 68
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);
}
}

7/15/2025 69
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);
}
}
}

7/15/2025 70
class ScopeErr {
public static void main(String args[]) {
int bar = 1;
{ // creates a new scope
int bar = 2; // Compile-time error – bar already defined!
}
}
}

7/15/2025 71
Type Conversion and Casting

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

7/15/2025 72
Casting Incompatible Types

• what if you want to assign an int value to a


byte variable?

• This conversion will not be performed


automatically, because a byte is smaller than
an int

• narrowing conversion

7/15/2025 73
(target-type) value
• target-type specifies the desired type to
convert the specified value to

int a;
byte b;
// ...
b = (byte) a;

7/15/2025 74
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);
}
}
7/15/2025 75
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

7/15/2025 76
Automatic Type Promotion in
Expressions
Example:
byte a = 40;
byte b = 50;
byte c = 100;
int d = a * b / c;

• Java automatically promotes each byte or


short operand to int when evaluating an
expression
7/15/2025 77
• Subexpression a * b is performed using
integer

byte b = 50
b=b*2
// error: Cannot assign an int to a byte

In this case we need to explicitly specify:


byte b = 50;
b = (byte) (b*2);

7/15/2025 78
The Type Promotion Rules

• All byte and short values are promoted to int

• If one operand is a long, the whole expression is


promoted to long

• If one operand is a float, the entire expression is


promoted to float

• If any of the operands is double, the result is


double
7/15/2025 79
class Promote {
public static void main(String args[ ]) {
byte b = 42;
char c = 'a';
short s = 1024;
int i = 50000;
float f = 5.67f;
double d = .1234;
double result = (f * b) + (i / c) - (d * s);
System.out.println((f * b) + " + " + (i / c) + " - " + (d * s));
System.out.println("result = " + result);
}
}

7/15/2025 80
double result = (f * b) + (i / c) - (d * s);

• In the first subexpression, f * b, b is promoted to a


float and the result of the subexpression
is float

• Next, in the subexpression i / c, c is promoted to int,


and the result is of type int

• In d * s, the value of s is promoted to double, and


the type of the subexpression is double

7/15/2025 81
• The outcome of float plus an int is a float

• Then the resultant float minus the last


double is promoted to double, which is the
type for the final result of the expression

7/15/2025 82
Arrays

• An array is a group of like-typed variables


that are referred to by a common name

• A specific element in an array is accessed by


its index

7/15/2025 83
One-Dimensional Arrays

• type var-name[ ]; - No array exists

• array-var = new type[size]; - allocating


memory

Example:
int month_days[] = new int[12]

7/15/2025 84
• Arrays can be initialized when they are
declared

• An array initializer is a list of comma-


separated expressions surrounded by curly
braces

• There is no need to use new

7/15/2025 85
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.");
}
}

7/15/2025 86
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);
}
}
7/15/2025 87
Multidimensional Arrays
• To declare a multidimensional array variable,
specify each additional index using another
set of square brackets
Example:
int twoD[][] = new int[4][5];

7/15/2025 88
7/15/2025 89
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;
k++;
}
for(i=0; i<4; i++) {
for(j=0; j<5; j++)
System.out.print(twoD[i][j] + " ");
System.out.println();
}
}
}

7/15/2025 90
• 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
Example:
int twoD[][] = new int[4][];
twoD[0] = new int[5];
twoD[1] = new int[5];
twoD[2] = new int[5];
twoD[3] = new int[5];

7/15/2025 91
• When you allocate dimensions manually, you
do not need to allocate the same number of
elements for each dimension

• Since multidimensional arrays are actually


arrays of arrays, the length of each array is
under your control

7/15/2025 92
class TwoDAgain {
public static void main(String args[]) {
int twoD[][] = new int[4][];
twoD[0] = new int[1];
twoD[1] = new int[2];
twoD[2] = new int[3];
twoD[3] = new int[4];
int i, j, k = 0;
for(i=0; i<4; i++)
for(j=0; j<i+1; j++) {
twoD[i][j] = k;
k++;
}
for(i=0; i<4; i++) {
for(j=0; j<i+1; j++)
System.out.print(twoD[i][j] + " ");
System.out.println();
}}}

7/15/2025 93
7/15/2025 94
• It is possible to initialize multidimensional
arrays

• You can use expressions as well as literal


values inside of array initializers

7/15/2025 95
class Matrix {
public static void main(String args[]) {
double m[ ][ ] = {
{ 0*0, 1*0, 2*0, 3*0 },
{ 0*1, 1*1, 2*1, 3*1 },
{ 0*2, 1*2, 2*2, 3*2 },
{ 0*3, 1*3, 2*3, 3*3 }
};
int i, j;
for(i=0; i<4; i++) {
for(j=0; j<4; j++)
System.out.print(m[i][j] + " ");
System.out.println();
}
}
}

7/15/2025 96
Output:

0.0 0.0 0.0 0.0


0.0 1.0 2.0 3.0
0.0 2.0 4.0 6.0
0.0 3.0 6.0 9.0

7/15/2025 97
Alternative Array Declaration Syntax
• There is a second form that may be used to declare
an array:
type[ ] var-name;

Example: These two are equivalent


int al[ ] = new int[3];
int[ ] a2 = new int[3];

The following declarations are also equivalent:


char twod1[ ][ ] = new char[3][4];
char[ ][ ] twod2 = new char[3][4];

7/15/2025 98
Note:
• Java does not support or allow pointers

• Java cannot allow pointers, because doing so would


allow Java applets to breach the firewall between
the Java execution environment and the host
computer

• Java is designed in such a way that as long as you


stay within the confines of the execution
environment, you will never need to use a pointer,
nor would there be any benefit in using one

7/15/2025 99
Operators

7/15/2025 100
Arithmetic Operators

7/15/2025 101
class BasicMath {
public static void main(String args[]) {
// arithmetic using integers
System.out.println("Integer Arithmetic");
int a = 1 + 1;
int b = a * 3;
int c = b / 4;
int d = c - a;
int e = -d;
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
System.out.println("d = " + d);
System.out.println("e = " + e);
// arithmetic using doubles
System.out.println("\nFloating Point Arithmetic");
double da = 1 + 1;
double db = da * 3;
double dc = db / 4;
double dd = dc - a;
double de = -dd;
System.out.println("da = " + da);
System.out.println("db = " + db);
System.out.println("dc = " + dc);
System.out.println("dd = " + dd);
System.out.println("de = " + de);
}
}

7/15/2025 102
• The modulus operator, %, returns the
remainder of a division operation

• It can be applied to floating-point types as


well as integer types

• This differs from C/C++, in which the % can


only be applied to integer types

7/15/2025 103
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
7/15/2025 104
Arithmetic Assignment Operators

• a = a + 4;

• a += 4;

Any statement of the form


var = var op expression;
can be rewritten as
var op= expression;
7/15/2025 105
Operator Example Equivalent To

+= x += y x=x+y
-= x -= y x=x-y
*= x *= y x=x*y
/= x /= y x=x/y
%= x %= y x=x%y

7/15/2025 106
The Bitwise Operators
~ Bitwise unary NOT
& Bitwise AND
| Bitwise OR
^ Bitwise XOR
>> Shift Right
>>> Shift Right zero fill
<< Shift left
&= Bitwise AND Assignment
|= Bitwise OR Assignment
^= Bitwise XOR Assignment
>>= Shift Right Assignment
>>>= Shift Right zero fill Assignment
<<= Shift Left Assignment

7/15/2025 107
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]);
}
}

7/15/2025 108
The Left Shift
It has this general form:
value << num
• If you left-shift a byte value, that value will first be
promoted to int and then shifted

• This means that you must discard the top three


bytes of the result if what you want is the result of a
shifted byte value

• The easiest way to do this is to simply cast the result


back into a byte

7/15/2025 109
class ByteShift {
public static void main(String args[]) {
byte a = 64, b;
int i;
i = a << 2;
b = (byte) (a << 2);
System.out.println("Original value of a: " + a);
System.out.println("i and b: " + i + " " + b);
}
}
Output:
Original value of a: 64
i and b: 256 0
7/15/2025 110
The Right Shift

• The right shift operator, >>, shifts all of the bits in a


value to the right a specified number of times

value >> num

int a = 32;
a = a >> 2; // a now contains 8

int a = 35;
a = a >> 2; // a still contains 8

7/15/2025 111
11111000 –8
>>1
11111100 –4
• Sign extension

7/15/2025 112
// Masking sign extension.
class HexByte {
static public void main(String args[]) {
char hex[] = {
'0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
};
byte b = (byte) 0xf1;
System.out.println("b = 0x" + hex[(b >> 4) & 0x0f] +
hex[b & 0x0f]);
}
}
7/15/2025 113
The Unsigned Right Shift

• Unsigned, shift-right operator, >>>, which always shifts zeros into


the high-order bit

int a = -1;
a = a >>> 24;
Here is the same operation in binary form to further illustrate what is
happening:
11111111 11111111 11111111 11111111 –1 in binary as an int
>>>24
00000000 00000000 00000000 11111111 255 in binary as an int

7/15/2025 114
// Unsigned shifting a byte value.
class ByteUShift {
static public void main(String args[]) {
char hex[] = {
'0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
};
byte b = (byte) 0xf1;
byte c = (byte) (b >> 4);
byte d = (byte) (b >>> 4);
byte e = (byte) ((b & 0xff) >> 4);
System.out.println(" b = 0x“ + hex[(b >> 4) & 0x0f] + hex[b & 0x0f]);
System.out.println(" b >> 4 = 0x“ + hex[(c >> 4) & 0x0f] + hex[c & 0x0f]);
System.out.println(" b >>> 4 = 0x“ + hex[(d >> 4) & 0x0f] + hex[d & 0x0f]);
System.out.println("(b & 0xff) >> 4 = 0x“ + hex[(e >> 4) & 0x0f] + hex[e & 0x0f]);
}
}

7/15/2025 115
Output

b = 0xf1
b >> 4 = 0xff
b >>> 4 = 0xff
(b & 0xff) >> 4 = 0x0f

7/15/2025 116
Bitwise Operator Assignments

a = a >> 4;
a >>= 4;

a = a | b;
a |= b;

7/15/2025 117
Relational Operators

> greater than


>= greater than or equal to
< less than
<= less than or equal to
== equal to
!= not equal to

7/15/2025 118
int a = 4;
int b = 1;
boolean c = a < b;

int done;
// ...
if(!done) ... // Valid in C/C++
if(done) ... // but not in Java.

In Java, these statements must be written like this:


if(done == 0)) ... // This is Java-style.
if(done != 0) ...

7/15/2025 119
In Java, true and false are nonnumeric
values which do not relate to zero or nonzero

7/15/2025 120
Boolean Logical Operators

7/15/2025 121
Short-Circuit Logical Operators

• Java will not bother to evaluate the right-hand


operand when the outcome of the expression
can be determined by the left operand alone

Example 1:
if (denom != 0 && num / denom > 10)

Example 2:
if(c==1 && e++ < 100) d = 100;
7/15/2025 122
The Assignment Operator

var = expression;

int x, y, z;
x = y = z = 100; // set x, y, and z to 100

7/15/2025 123
The ?: Operator (ternary if)

expression1 ? expression2 : expression3

Example:
if (a > b) { max = a; } else { max = b; }
max = (a > b) ? a : b;

ratio = (denom == 0) ? 0 : num / denom;

7/15/2025 124
Operator Precedence
Highest
1. () [] .
2. ++ -- ~ !
3. * / %
4. + -
5. >> >>> <<
6. > >= < <=
7. == !=
8. &
9. ^
10. |
11. &&
12. ||
13. ?:
14. = op=
Lowest

7/15/2025 125
Example:
a | 4 + c >> b & 7
(a | (((4 + c) >> b) & 7))

7/15/2025 126
• Parentheses (redundant or not) do not
degrade the performance of your program

• Therefore, adding parentheses to reduce


ambiguity does not negatively affect your
program

7/15/2025 127
Control Statements

7/15/2025 128
If:
if (condition) statement1;
else statement2;

Nested If:
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)

7/15/2025 129
The if-else-if Ladder:
if(condition)
statement;
else if(condition)
statement;
else if(condition)
statement;
...
else
statement;
7/15/2025 130
switch
switch (expression) {
case value1:
// statement sequence
break;
case value2:
// statement sequence
break;
...
case valueN:
// statement sequence
break;
default:
// default statement sequence
}
• The expression must be of type byte, short, int, or char;

7/15/2025 131
Nested switch Statements
switch(count) {
case 1:
switch(target) { // nested switch
case 0:
System.out.println("target is zero");
break;
case 1: // no conflicts with outer switch
System.out.println("target is one");
break;
}
break;
case 2: // ...

7/15/2025 132
Iteration Statements

While:
while(condition) {
// body of loop
}

7/15/2025 133
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);
}
}

7/15/2025 134
do-while

do {
// body of loop
} while (condition);

7/15/2025 135
// Using a do-while to process a menu selection
class Menu {
public static void main(String args[])
throws java.io.IOException {
char choice;
do {
System.out.println("Help on:");
System.out.println(" 1. if");
System.out.println(" 2. switch");
System.out.println(" 3. while");
System.out.println(" 4. do-while");
System.out.println(" 5. for\n");
System.out.println("Choose one:");
choice = (char) System.in.read();
} while( choice < '1' || choice > '5');
System.out.println("\n");
switch(choice) {
case '1':
System.out.println("The if:\n");
System.out.println("if(condition) statement;");
System.out.println("else statement;");
break;
case '2':

7/15/2025 136
System.out.println("The switch:\n");
System.out.println("switch(expression) {");
System.out.println(" case constant:");
System.out.println(" statement sequence");
System.out.println(" break;");
System.out.println(" // ...");
System.out.println("}");
break;
case '3':
System.out.println("The while:\n");
System.out.println("while(condition) statement;");
break;
case '4':
System.out.println("The do-while:\n");
System.out.println("do {");
System.out.println(" statement;");
System.out.println("} while (condition);");
break;
case '5':
System.out.println("The for:\n");
System.out.print("for(init; condition; iteration)");
System.out.println(" statement;");
break;
}
}
}

7/15/2025 137
for

for(initialization; condition; iteration) {


// body
}

7/15/2025 138
class Comma {
public static void main(String args[]) {
int a, b;
for(a=1, b=4; a<b; a++, b--) {
System.out.println("a = " + a);
System.out.println("b = " + b);
}
}
}

7/15/2025 139
Some for Loop Variations

boolean done = false;


for(int i=1; !done; i++) {
// ...
if(interrupted()) done = true;
}

7/15/2025 140
// Parts of the for loop can be empty.
class ForVar {
public static void main(String args[]) {
int i;
boolean done = false;
i = 0;
for( ; !done; ) {
System.out.println("i is " + i);
if(i == 10) done = true;
i++;
}
}
}

7/15/2025 141
for( ; ; ) {
// ...
}

• This loop will run forever, because there is no


condition under which it will terminate

• Nested Loops - concept

7/15/2025 142
Jump Statements
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; // terminate loop if i is 10
System.out.println("i: " + i);
}
System.out.println("Loop complete.");
}
}
7/15/2025 143
• More than one break statement may appear
in a loop

• Too many break statements have the


tendency to destructure your code

• The break that terminates a switch


statement affects only that switch statement
and not any enclosing loops

7/15/2025 144
Using break as a Form of Goto

• Java defines an expanded form of the break


statement

• By using this form of break, you can break


out of one or more blocks of code

• The general form of the labeled break


statement is :
break label;

7/15/2025 145
• A label is any valid Java identifier followed by
a colon

• You can use a labeled break statement to


exit from a set of nested blocks

• You cannot use break to transfer control to a


block of code that does not enclose the
break statement

7/15/2025 146
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.");
}
}
}

7/15/2025 147
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");
}
System.out.println("Loops complete.");
}
}

7/15/2025 148
// This program contains an error.
class BreakErr {
public static void main(String args[]) {
one: for(int i=0; i<3; i++) {
System.out.print("Pass " + i + ": ");
}
for(int j=0; j<100; j++) {
if(j == 10) break one; // WRONG
System.out.print(j + " ");
}
}
}
7/15/2025 149
Using 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("");
}
}
}

7/15/2025 150
• As with the break statement, continue may specify a label to
describe which enclosing loop to continue

class ContinueLabel {
public static void main(String args[]) {
outer: for (int i=0; i<10; i++) {
for(int j=0; j<10; j++) {
if(j > i) {
System.out.println();
continue outer;
}
System.out.print(" " + (i * j));
}
}
System.out.println();
}
}
7/15/2025 151
Output:

0
01
024
0369
0 4 8 12 16
0 5 10 15 20 25
0 6 12 18 24 30 36
0 7 14 21 28 35 42 49
0 8 16 24 32 40 48 56 64
0 9 18 27 36 45 54 63 72 81
7/15/2025 152
return
• Used to explicitly return from a method

• The return statement immediately terminates the


method in which it is executed

class Return {
public static void main(String args[]) {
boolean t = true;
System.out.println("Before the return.");
if(t==true) return; // return to caller
System.out.println("This won't execute.");
}}

7/15/2025 153
return causes execution to return to the Java
run-time system, since it is the run-time
system that calls main( )

7/15/2025 154
I/O
• Java programs perform I/O through streams

• A stream is an abstraction that either produces or


consumes information

• A stream is linked to a physical device by the Java I/O


system

• All streams behave in the same manner, even if the


actual physical devices to which they are linked differ

7/15/2025 155
• Thus, the same I/O classes and methods can be
applied to any type of device

• This means that an input stream can abstract


many different kinds of input: from a disk file, a
keyboard, or a network socket

• Likewise, an output stream may refer to the


console, a disk file, or a network connection

7/15/2025 156
• Java defines two types of streams: byte and
character

• Byte streams provide a convenient means for


handling input and output of bytes

• Byte streams are used, for example, when reading


or writing binary data

• Character streams provide a convenient means for


handling input and output of characters

7/15/2025 157
• Byte streams are defined by using two class
hierarchies

• At the top are two abstract classes:


InputStream and OutputStream

• Each of these abstract classes has several


concrete subclasses that handle the differences
between various devices, such as disk files,
network connections, and even memory buffers

7/15/2025 158
• Character streams are defined by using two
class hierarchies

• At the top are two abstract classes, Reader and


Writer

• These abstract classes handle Unicode


character streams

• Java has several concrete subclasses of each of


these

7/15/2025 159
7/15/2025 160
7/15/2025 161
7/15/2025 162
• All Java programs automatically import the
java.lang package

• This package defines a class called System,


which encapsulates several aspects of the run-
time environment

7/15/2025 163
• System also contains three predefined stream
variables: in, out, and err

• These fields are declared as public, static, and


final within System

• This means that they can be used by any other


part of your program and without reference to a
specific System object

7/15/2025 164
• System.out refers to the standard output stream

• By default, this is the console

• System.in refers to standard input, which is the


keyboard by default

• System.err refers to the standard error stream,


which also is the console by default

• However, these streams may be redirected to any


compatible I/O device
7/15/2025 165
• System.in is an object of type InputStream

• System.out and System.err are objects of type


PrintStream

• These are byte streams, even though they


typically are used to read and write characters
from and to the console

7/15/2025 166
Reading Console Input…
• In Java, console input is accomplished by reading
from System.in

• To obtain a character based stream that is attached


to the console, wrap System.in in a BufferedReader
object

• BufferedReader supports a buffered input stream Its


most commonly used constructor :
BufferedReader(Reader inputReader)

7/15/2025 167
• Here, inputReader is the stream that is linked to
the instance of BufferedReader that is being
created

• Reader is an abstract class

• One of its concrete subclasses is


InputStreamReader, which converts bytes to
characters

7/15/2025 168
• To obtain an InputStreamReader object that is
linked to System.in, use the following
constructor:

InputStreamReader(InputStream inputStream)

• Because System.in refers to an object of type


InputStream, it can be used for inputStream.

7/15/2025 169
• Putting it all together, the following line of code
creates a BufferedReader that is connected to the
keyboard:
• InputStreamReader varname=new
InputStreamReader(System.in)
• BufferedReader d = new BufferedReader (
varname);
or
BufferedReader d = new BufferedReader ( new
InputStreamReader(System.in));
• After this statement executes, d is a character-
based stream that is linked to the console through
System.in
7/15/2025 170
Reading Characters…
// Use a BufferedReader to read characters from the console.
import java.io.*;
class BRRead {
public static void main(String args[]) throws IOException
{
char c;
BufferedReader d = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter characters, 'q' to quit.");
// read characters
do {
c = (char) d.read();
System.out.println(c);
} while(c != 'q');
}
}

7/15/2025 171
Reading Strings…
• To read a string from the keyboard, use the
version of readLine( ) that is a member of the
BufferedReader class

• Its general form is shown here:

String readLine( ) throws IOException

it returns a String object.

7/15/2025 172
// Read a string from console using a BufferedReader.
import java.io.*;
class BRReadLines {
public static void main(String args[])
throws IOException
{
// create a BufferedReader using System.in
BufferedReader d = new BufferedReader(new InputStreamReader(System.in));
String str;
System.out.println("Enter lines of text.");
System.out.println("Enter 'stop' to quit.");
do {
str = d.readLine();
System.out.println(str);
} while(!str.equals("stop"));
}
}

7/15/2025 173
We can use DataInputStream class also…

• DataInputStream d = new DataInputStream(System.in);


:
:
:
String s = d.readLine()
:
:

7/15/2025 174
static double Double.parseDouble(String str)
throws NumberFormatException

• Returns the double equivalent of the number


contained in the string specified by str using
radix 10

7/15/2025 175
static String toString(double num)

• Returns the string equivalent of the value


specified by num

7/15/2025 176
static int Integer.parseInt(String str) throws
NumberFormatException

• Returns the integer equivalent of the number


contained in the string specified by str using
radix 10.

7/15/2025 177
static String toString(int num)

• Returns a string that contains the decimal


equivalent of num

7/15/2025 178
static float Float.parseFloat(String str) throws
NumberFormatException

• Returns the float equivalent of the number


contained in the string specified by str using
radix 10

7/15/2025 179
static String toString(float num)

• Returns the string equivalent of the value


specified by num

7/15/2025 180
static long parseLong(String str) throws
NumberFormatException

• Returns the long equivalent of the number


contained in the string specified by str in radix 10

7/15/2025 181
static String toString(long num)

• Returns a string that contains the decimal


equivalent of num

7/15/2025 182
static Long valueOf(long num)

• Returns a Long object containing the value


passed in num.

static Long valueOf(String str) throws


NumberFormatException

• Returns a Long object that contains the value


specified by the string in str

7/15/2025 183
static Integer valueOf(int num)

• Returns an Integer object containing the value


passed in num.

static Integer valueOf(String str) throws


NumberFormatException

• Returns an Integer object that contains the value


specified by the string in str

7/15/2025 184
static Float valueOf(float num)

• Returns a Float object containing the value


passed in num.

static Float valueOf(String str) throws


NumberFormatException

• Returns the Float object that contains the value


specified by the string in str

7/15/2025 185
static Double valueOf(double num)

• Returns a Double object containing the value


passed in num.

static Double valueOf(String str) throws


NumberFormatException

• Returns a Double object that contains the value


specified by the string in str

7/15/2025 186
float floatValue( )

Returns the value of the invoking object as a


float

Similarly
double doubleValue( )
long longValue( )
int intValue( )

7/15/2025 187
Example…

Float.valueOf(param).floatValue();

• Param could be String or float number…

7/15/2025 188
import java.io.*;
class A1
{
int a, b;
public static void main(String args[])
{
A1 obj = new A1();
DataInputStream in = new DataInputStream(System.in);
String s = new String();
// String s = null;
try
{
s = in.readLine();
}
catch(IOException ie)
{ }

7/15/2025 189
try
{
obj.a = Integer.parseInt(s);
obj.b = obj.a + 20;
System.out.println("a=" + obj.a + " b=" + obj.b);
int c;
c=Integer.valueOf(s).intValue();
c=c+1;
System.out.println("c=" + c);
}
catch(NumberFormatException ne)
{
System.out.println("Number Format Not Proper");
}
}
}

7/15/2025 190
Scanner Class
• The Scanner class is used to get user input, and it is found in the java.util package.
• To use the Scanner class, create an object of the class and use any of the available
methods found in the Scanner class documentation.
• import java.util.Scanner; // Import the Scanner class
class MyClass {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in); // Create a Scanner object
System.out.println("Enter username");
String userName = myObj.nextLine(); // Read user input
System.out.println("Username is: " + userName); // Output user input

}
}

7/15/2025 191
Vector Class
• The Vector class implements a growable array of objects.
Vectors basically fall in legacy classes but now it is fully
compatible with collections.
• Constructor:
– Vector(): Creates a default vector of initial capacity is 10.
– Vector(int size): Creates a vector whose initial capacity is
specified by size.
– Vector(int size, int incr): Creates a vector whose initial
capacity is specified by size and increment is specified by
incr. It specifies the number of elements to allocate each
time that a vector is resized upward.
– Vector(Collection c): Creates a vector that contains the
elements of collection c.
7/15/2025 192
• Vector defines three protected data member:
– int capacityIncreament: Contains the increment
value.
– int elementCount: Number of elements currently in
vector stored in it.
– Object elementData[]: Array that holds the vector is
stored in it.

7/15/2025 193
// Java code illustrating add() method
import java.util.*;
class Vector_demo {
public static void main(String[] arg)
{
// create default vector
Vector v = new Vector();
v.add(1);
v.add(2);
v.add("geeks");
v.add(“GITAM");
v.add(3);
System.out.println("Vector is " + v);
}
}
OUTPUT: [1, 2, geeks, GITAM, 3]
7/15/2025 194
Thank You …

7/15/2025 195

You might also like