Java Module 1
Java Module 1
Parikshith Nayaka S K
Asst. Professor
Dept of CSE
7/15/2025 1
Reference Book…
7/15/2025 2
◼ Java is related to C++, which is a direct descendent
of C
7/15/2025 3
◼ This language was initially called “Oak” but was
renamed “Java” in 1995
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
7/15/2025 5
Security
7/15/2025 7
Java’s Magic: The Bytecode
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
7/15/2025 10
◼ Sun supplies its Just In Time (JIT) compiler
for bytecode, which is included in the Java 2
release
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
7/15/2025 14
Object oriented
7/15/2025 15
Robust
7/15/2025 16
◼ Memory management can be a difficult, tedious task
in traditional programming environments
7/15/2025 17
◼ Java virtually eliminates these problems by
managing memory allocation and
deallocation for you
7/15/2025 18
Multithreaded
7/15/2025 20
Interpreted and High Performance
7/15/2025 21
Distributed
7/15/2025 22
Dynamic
7/15/2025 23
An Overview of Java
7/15/2025 24
◼ Object-oriented programming is at the core of
Java
7/15/2025 25
◼ That is, some programs are written around
“what is happening” and others are written
around “who is being affected.”
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:
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
7/15/2025 33
Compiling the Program
◼ C:\>javac Example.java
7/15/2025 34
• To actually run the program, you must use
the Java interpreter, called java.
• C:\>java Example
7/15/2025 35
• The keyword static allows main( ) to be
called without having to instantiate a
particular instance of the class
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;
7/15/2025 38
The for Loop:
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.
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
7/15/2025 49
The Simple Types
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++.
7/15/2025 55
• In Java char is a 16-bit type
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
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
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
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
7/15/2025 67
• In Java, the two major scopes are those defined by
a class and those defined by a method
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
7/15/2025 72
Casting Incompatible Types
• 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:
7/15/2025 76
Automatic Type Promotion in
Expressions
Example:
byte a = 40;
byte b = 50;
byte c = 100;
int d = a * b / c;
byte b = 50
b=b*2
// error: Cannot assign an int to a byte
7/15/2025 78
The Type Promotion Rules
7/15/2025 80
double result = (f * b) + (i / c) - (d * s);
7/15/2025 81
• The outcome of float plus an int is a float
7/15/2025 82
Arrays
7/15/2025 83
One-Dimensional Arrays
Example:
int month_days[] = new int[12]
7/15/2025 84
• Arrays can be initialized when they are
declared
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
7/15/2025 91
• When you allocate dimensions manually, you
do not need to allocate the same number of
elements for each dimension
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
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:
7/15/2025 97
Alternative Array Declaration Syntax
• There is a second form that may be used to declare
an array:
type[ ] var-name;
7/15/2025 98
Note:
• Java does not support or allow pointers
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
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;
+= 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
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
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
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
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.
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
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)
Example:
if (a > b) { max = a; } else { max = b; }
max = (a > b) ? a : b;
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
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
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
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( ; ; ) {
// ...
}
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
7/15/2025 144
Using break as a Form of Goto
7/15/2025 145
• A label is any valid Java identifier followed by
a colon
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
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
7/15/2025 155
• Thus, the same I/O classes and methods can be
applied to any type of device
7/15/2025 156
• Java defines two types of streams: byte and
character
7/15/2025 157
• Byte streams are defined by using two class
hierarchies
7/15/2025 158
• Character streams are defined by using two
class hierarchies
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
7/15/2025 163
• System also contains three predefined stream
variables: in, out, and err
7/15/2025 164
• System.out refers to the standard output stream
7/15/2025 166
Reading Console Input…
• In Java, console input is accomplished by reading
from System.in
7/15/2025 167
• Here, inputReader is the stream that is linked to
the instance of BufferedReader that is being
created
7/15/2025 168
• To obtain an InputStreamReader object that is
linked to System.in, use the following
constructor:
InputStreamReader(InputStream 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
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…
7/15/2025 174
static double Double.parseDouble(String str)
throws NumberFormatException
7/15/2025 175
static String toString(double num)
7/15/2025 176
static int Integer.parseInt(String str) throws
NumberFormatException
7/15/2025 177
static String toString(int num)
7/15/2025 178
static float Float.parseFloat(String str) throws
NumberFormatException
7/15/2025 179
static String toString(float num)
7/15/2025 180
static long parseLong(String str) throws
NumberFormatException
7/15/2025 181
static String toString(long num)
7/15/2025 182
static Long valueOf(long num)
7/15/2025 183
static Integer valueOf(int num)
7/15/2025 184
static Float valueOf(float num)
7/15/2025 185
static Double valueOf(double num)
7/15/2025 186
float floatValue( )
Similarly
double doubleValue( )
long longValue( )
int intValue( )
7/15/2025 187
Example…
Float.valueOf(param).floatValue();
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