Week 2 - L4-L6

Download as pdf or txt
Download as pdf or txt
You are on page 1of 60

Subject Name: OOP

Unit No:1
Unit Name: Introduction to OOP

Faculty Name : Mr. Dayanand Dhongade


Index

Lecture 4 – Features of Java Language, JDK environment 3

Lecture 5 – Basic Constructs of Java Programming 13

Lecture 6 – Input and output functions in Java : Buffered reader class, Scanner class 39

2
Module No 1: Introduction to OOP

Lecture No: 4
Features of Java Language, JDK
environment
Introduction to JAVA

• A general purpose object oriented


programming language developed by
Sun Microsystems in 1991.
• Originally called Oak by James
Gosling, the first designer of Java and
implemented its original compiler and
virtual machine.
• Renamed as JAVA in 1995
• Versions
– Java 2 Micro Edition (J2ME)
– Java 2 Standard Edition (J2SE)
– Java 2 Enterprise Edition (J2EE)

4 Lecture 4- Features of Java Language, JDK environment


Features of Java

5 Lecture 4- Features of Java Language, JDK environment


Features of Java

• Simple:
 Easy to learn.
 removed many confusing and rarely-used features
e.g., explicit pointers, operator overloading etc.

• Object-oriented:
 Organize our software as a combination of different types of
objects that incorporates both data and behaviour.

6 Lecture 4- Features of Java Language, JDK environment


Features of Java

• Platform Independent:
 A platform is the hardware or software environment in which a
program runs.
 It has two components:
 Runtime Environment
 API(Application Programming Interface)
 “Write-Once Run-Anywhere”
 Java code can be run on multiple platforms e.g. Windows,
Linux, Sun Solaris, Mac/OS etc.

7 Lecture 4- Features of Java Language, JDK environment


Features of Java

• Robust:
 Strong memory management.
 No usage of pointers.
 Exception handling and type checking mechanisms.

“An Exception is the condition that is caused by run time


error in the program. If it occurred java interpreter creates
an exception object and throws it.”

8 Lecture 4- Features of Java Language, JDK environment


Features of Java

• Multi-threaded
 A thread is like a separate program, executing concurrently.
 Java programs deal with many tasks at once by defining
multiple threads.
 Doesn't occupy memory for each thread.
 Shares a common memory area.

9 Lecture 4- Features of Java Language, JDK environment


Features of Java

• Distributed and Network Oriented


Java grew up in the days of the Internet
 Inherently network friendly
 Original release of Java came with Networking libraries
 Newer releases contain even more for handling distributed
applications
- RMI, Transactions

10 Lecture 4- Features of Java Language, JDK environment


Features of Java

• Compiled and Interpreted


 Java works in two stage
– Java compiler translate the source code into byte code.
– Java interpreter converts the byte code into machine level
representation.
 Byte Code:
- A highly optimized set of instructions to be executed by the java
runtime system, known as java virtual machine (JVM).
- Not executable code.
 Java Virtual Machine (JVM):
- Need to be implemented for each platform.
- Although the details vary from machine to machine, all JVM
understand the same byte code.

11 Lecture 4- Features of Java Language, JDK environment


Java Virtual Machine
 Java compiler produces an intermediate code known as byte code for a
machine, known as JVM.
 It exists only inside the computer memory.

Java Program Virtual Machine


Java Compiler .class file (byte code)
.java file

 Machine code is generated by the java interpreter by acting as an


intermediary between the virtual machine and real machine.

Virtual machine Real machine


Java Interpreter
Bytecode Machine Code

12 Lecture 4- Features of Java Language, JDK environment


Module No 1: Introduction to OOP

Lecture No: 5
Basic Constructs of Java Programming
Simple Java Program

// Program to print Hello message


public class Hello
{

public static void main (String[ ] args)


{

System.out.print (“Hello”);
}

14 Lecture 5- Basic Constructs of Java Programming


Java Program Structure

// comments about the class


public class MyProgram
{
class header
// comments about the method

public static void main (String[ ] args)


{ class body
method header
method body
}

15 Lecture 5- Basic Constructs of Java Programming


Compile and Execute Java Program

Java program Type it in with the text editor of your


choice
filename.java

Java compiler

javac

Java byte code


filename.clas
To compile the program at s
the command line type
"javac filename.java" )
Java Interpreter

java

To run the interpreter, at


the command line type
"java filename"
16 Lecture 5- Basic Constructs of Java Programming
Basic Constructs of Java

 Constants
 Variables
 Data Types
 Operators and Expression
 Revision of Branching and Looping

17 Lecture 5- Basic Constructs of Java Programming


Constants

 The variable whose value is always constant (does not change).


 The reserved word final is used in constant declaration.
 Syntax:
final data_type constant_name=constant_value;

18 Lecture 5- Basic Constructs of Java Programming


Variables

 A variable can be thought of as a container which holds value for you,


during the life of a Java program.
 Every variable is assigned a data type which designates the type and
quantity of value it can hold.
 All variables must be declared before its use.
 Variables can be declared almost anywhere (scope rules apply)
 Variables have default initialization values
o Integers: 0
o Reals: 0.0
o Boolean: False
 Variables can be initialized in the declaration.
 Syntax:
[access_modifier] [static] [final] type name = [value];

19 Lecture 5- Basic Constructs of Java Programming


Data Types

20 Lecture 5- Basic Constructs of Java Programming


Data Types

 Primitive Data Types


o byte (1), -128 to 127
o short (2), -32768 to 32767
o int (4), -2147483648 to 2147483647
o long (8), -9223372036854775808 to 9223372036854775807
o float (4), -3.4E38 to 3.4E38, 7 digit precision
o double (8), -1.7E308 to 1.7E308, 17 digits precision
o char (2), unicode characters
o boolean (true, false), discrete values

 Non-primitive/ User-defined Data Types


o Array
o Class
o interface

21 Lecture 5- Basic Constructs of Java Programming


Keywords in Java

 These are the reserved words in JAVA which cannot be used as variable
names or identifiers.
abstract continue for new switch
assert*** default goto* package synchronized
boolean do if private this
break double implements protected throw
byte else import public throws
case enum**** instanceof return transient
catch extends int short try
char final interface static void
class finally long strictfp** volatile
const* float native super while

22 Lecture 5- Basic Constructs of Java Programming


Java Operators

 Operators/Order of Precedence

Operator Operation Precedence

() or [ ] or . or ++ or - - Parens, array indices, object 1


invocation, increment, decrement
+ or – or ~ Unary plus, unary minus, complement 2

* or / or % Multiplication, division, modulus 3


+ or - Addition, subtraction 4
<<,>> Bitwise shifts 5
& Bitwise AND 6
^ Bitwise XOR 7
| Bitwise OR 8

23 Lecture 5- Basic Constructs of Java Programming


Java Operators

 Example Usage

int anInt1 = 2, anInt2 = 1, anInt3;


double aDbl1;
anInt3 = anInt1 + anInt2 * 4; // anInt3 gets 6
anInt3 = (anInt1 + anInt2) * 4; // anInt3 gets 12
anInt3 = ++anInt2 * 2; // anInt3 gets 4
anInt2 = 1;
anInt3 = anInt2++ * 2; // anInt3 gets 2
anInt2 = 1;
anInt3 = anInt1 & anInt2; // anInt3 gets 0
anInt3 = anInt1 ^ anInt2; // anInt3 gets 3
anInt3 = anInt2 << 1; // anInt3 gets 2
anInt3 = 1 / 2; // anInt3 gets 0
aDbl1 = 1 / 2; // aDbl1 gets 0.0
aDbl1 = 1.0 / 2.0; // aDbl1 gets 0.5

24 Lecture 5- Basic Constructs of Java Programming


Java Operators…..

 Assignments
 General Format: variable = expression ;
Where variable is a previously declared identifier and
expression is a valid combo of identifiers, operators,
and method (a.k.a. procedure or function) calls
 Shortcuts:
var *= expr ; // Equivalent to var = var * (expr);
var /= expr ; // Equivalent to var = var / (expr);
var += expr ; // Equivalent to var = var + (expr);
var -= expr ; // Equivalent to var = var – (expr);
var %= expr ; // Equivalent to var = var % (expr);
var++; // Equivalent to var = var + 1;
var--; // Equivalent to var = var - 1;

25 Lecture 5- Basic Constructs of Java Programming


Control Statements in Java

1. Conditional Statements
 if-else statements
 switch case statements

2. Iterative Statements
 for loop
 while loop
 do-while loop

26 Lecture 5- Basic Constructs of Java Programming


Java Conditional Constructs

 “if” Statements

◦ if with code block

if (boolean_expr)
{
statements
}

◦ if with single statement

if (boolean_expr)
statement;

27 Lecture 5- Basic Constructs of Java Programming


Java Conditional Constructs

 if” Statements (Continued)

◦ if-else

if (boolean_expr) if
true false
{
statements for true
} statements statements
else
{
statements for false
}

28 Lecture 5- Basic Constructs of Java Programming


Java Conditional Constructs

 Boolean Expressions
 Boolean expressions use conditional operators such that they result in a
value of true or false
 Conditional Operators (Not by order of precedence)

Operators Operations
== or != Equality, not equal

> or < Greater than, less than

>= or <= Greater than or equal, less than or equal

! Unary negation (NOT)

& or && Evaluation AND, short circuit AND

| or || Evaluation OR, short circuit OR

29 Lecture 5- Basic Constructs of Java Programming


Java Conditional Constructs

 Boolean Expression Examples

int i1 = 1, i2 = 2, i3 = 3, i4 = 0;
boolean b1 = true, b2 = false, b3 = true;

i2 > i1 // true
(i3 – i2) > i1 // false
(i3 – i2) >= i1 // true
(i2 > i1) & (i2 < i3) // true
(i2 < i1) | (i2 > i1) // true
i2 != i1 // true
(i1 < i2) | ((i1/i4) > 1) // Divide by 0 exception
(i1 < i2) || ((i1/i4) > 1) // true
(i1 < i2) | (i1++ > 1) // true, i1 contains 2
(i1 < i2) || (i1++ > 1) // true, i1 contains 1
b1 && b2 && b3 // false
(b1 || b2) && b3 // true
b1 && (i1 == (i3 – i2)) // true

30 Lecture 5- Basic Constructs of Java Programming


Java Conditional Constructs

 if-else” Statement Example


class Example
{
static public void main(String args[])
{ if
// A very contrived example
true false
int i1 = 1, i2 = 2;
System.out.print(“Result: “);
if (i1 > i2)
{ statements statements
System.out.println(“i1 > i2”);
}
else
{
System.out.println(“i2 >= i1”);
}
}
}

31 Lecture 5- Basic Constructs of Java Programming


Java Conditional Constructs

 The Switch Statement


true
switch (integer_expression) if statements
{
case int_value_1: false
statements true
if statements
break;
case int_value_2: false
statements
break; true
if statements

case int_value_n: false
statements
break; statements
default:
statements
}

32 Lecture 5- Basic Constructs of Java Programming


Java Conditional Constructs

 Don’t forget the “break”


true
switch (integer_expression) if statements
{
false
case int_value_1:
statements true
if statements
// No break!
case int_value_2: false
statements
break; true
if statements

case int_value_n: false
statements
break; statements
default:
statements
}

33 Lecture 5- Basic Constructs of Java Programming


Java Conditional Constructs

 Example

int n = 5;
true
switch (n) if statements
{
false
case 1:
n = n + 1; true
if statements
break;
case 5: false
n = n + 2;
break; statements
default:
n = n – 1;
}

34 Lecture 5- Basic Constructs of Java Programming


Java Looping Constructs

 while loop
 Exit condition evaluated at top

 do loop
 Exit condition evaluated at bottom

 for loop
 Exit condition evaluated at top
 Includes a initialization statements
 Includes a update statements for each iteration

35 Lecture 5- Basic Constructs of Java Programming


Java Looping Constructs

 while loop
false if
while (boolean_expr)
true
{
statements statements
}

 do loop
statements
do
{
statements if true
}
false
while (boolean_expr)

36 Lecture 5- Basic Constructs of Java Programming


Java Looping Constructs

 for loop

for (init_stmnt; bool_expr; update_stmnt)


{
statements init
}

false
if

true

statements update

37 Lecture 5- Basic Constructs of Java Programming


Java Looping Constructs

class Example
{ static public void main(String args[])
{
int i = 0;
System.out.println("while loop");
while (i < 10)
{
System.out.println(i);
i++;
}
System.out.println("do loop");
do
{
System.out.println(i);
i--;
}
while (i > 0);
System.out.println("for loop");
for (i = 0; i < 10; i++)
{
System.out.println(i);
}
} // End main
} // End Example

38 Lecture 5- Basic Constructs of Java Programming


Module No 1: Introduction to OOP

Lecture No: 6
Input and output functions in Java : Buffered
reader class, Scanner class
Input/Output

• Java I/O (Input and Output) is used to process the input and produce the
output.

• Java uses the concept of a stream to make I/O operation fast.

• The java.io package contains all the classes required for input and output
operations.

• We can perform file handling in Java by Java I/O API.

Lecture 6- Input and output functions in Java : Buffered reader class,


40
Scanner class
Input/Output

• Stream - A stream is a sequence of data. In Java, a stream is composed of


bytes. It's called a stream because it is like a stream of water that continues
to flow.

• In Java, 3 streams are created for us automatically. All these streams are
attached with the console.

– System.out: standard output stream

– System.in: standard input stream

– System.err: standard error stream

Lecture 6- Input and output functions in Java : Buffered reader class,


41
Scanner class
OutputStream vs InputStream

• OutputStream - Java application uses an output stream to write data to a


destination; it may be a file, an array, peripheral device or socket.

• InputStream - Java application uses an input stream to read data from a


source; it may be a file, an array, peripheral device or socket.

42 Lecture 6- Input and output functions in Java : Buffered reader class, Scanner class
OutputStream class

• OutputStream class is an abstract class. It is the superclass of all classes


representing an output stream of bytes. An output stream accepts output
bytes and sends them to some sink.

• Useful methods of OutputStream

Method Description

1) public void write(int)throws IOException is used to write a byte to the current output stream.

2) public void write(byte[])throws IOException is used to write an array of byte to the current
output stream.

3) public void flush()throws IOException flushes the current output stream.

4) public void close()throws IOException is used to close the current output stream.

43 Lecture 6- Input and output functions in Java : Buffered reader class, Scanner class
OutputStream class

• OutputStream Hierarchy

44 Lecture 6- Input and output functions in Java : Buffered reader class, Scanner class
InputStream class

• InputStream class is an abstract class. It is the superclass of all classes


representing an input stream of bytes.

• Useful methods of OutputStream

Method Description

1) public abstract int read()throws reads the next byte of data from the input
IOException stream. It returns -1 at the end of the file.

2) public int available()throws IOException returns an estimate of the number of bytes that
can be read from the current input stream.

3) public void close()throws IOException is used to close the current input stream.

45 Lecture 6- Input and output functions in Java : Buffered reader class, Scanner class
InputStream class

• InputStream Hierarchy

46 Lecture 6- Input and output functions in Java : Buffered reader class, Scanner class
Classes used for Reading Information

• BufferedReader (has always been there)


– import java.io.*;

• Scanner (specific to JAVA 5 and beyond)


– import java.util.*;

Lecture 6- Input and output functions in Java : Buffered reader class,


47
Scanner class
java.io.BufferedReader

• The BufferedReader class can only read Strings

• However we can transform those Strings into numbers of any kind.

• This one is always safe.

Lecture 6- Input and output functions in Java : Buffered reader class,


48
Scanner class
Two Objects and one Exception

• In the class:
public static void main(String args[ ]) throws IOException{
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);

• The method:
String readLine( )

Lecture 6- Input and output functions in Java : Buffered reader class,


49
Scanner class
Reading a String with BufferedReader

• Reading a String
InputStreamReader isr = new InputStreamReader (System.in);
BufferedReader br = new BufferedReader(isr);
String sName;

System.out.print(“What is your name? “);


sName = br.readLine( );
System.out.println(“So your name is “ + sName);

Lecture 6- Input and output functions in Java : Buffered reader class,


50
Scanner class
Reading integers with BufferedReader

• Reading an int number


String sPlaceHolder;
int iAge =0;
int iYear = 2023;

System.out.print(“How old are you? “);


sPlaceHolder = br.readLine( );
iAge = Integer.parseInt(sPlaceHolder);
System.out.println(“So you are “ + iAge + “ years old”);
System.out.println(“you were probably born in “+ (iYear - iAge));

Lecture 6- Input and output functions in Java : Buffered reader class,


51
Scanner class
Reading doubles with BufferedReader

• Reading a double number


final double dGoal = 1000000; //constant
double dEarnings = 0;
double dMissing = 0;

System.out.print(“How much do you make per hour? “);


sPlaceHolder = br.readLine( )
dEarnings = Double.parseDouble(sPlaceHolder);
dMissing = dGoal - dEarnings;
System.out.println(“\nIn one hours you will only need “ + iMissing + “more
to earn your goal”);

Lecture 6- Input and output functions in Java : Buffered reader class,


52
Scanner class
Scanner syntax

• The Scanner class is found in the java.util package.


import java.util.*; // so you can use Scanner

• Constructing a Scanner object to read console input:


Scanner name = new Scanner(System.in);

• Example:
Scanner sc = new Scanner(System.in);

Lecture 6- Input and output functions in Java : Buffered reader class,


53
Scanner class
Scanner Class -The Methods

• Constructor
Scanner sc = new Scanner(System.in);

• Reading a String
String sc.nextLine( );

• Reading an int
int sc.nextInt( );

• Reading a double
double sc.nextDouble( );

Lecture 6- Input and output functions in Java : Buffered reader class,


54
Scanner class
Scanner methods

Method Description
nextInt() reads an integer from the user
nextDouble() reads a double from the user
next() reads a one-word String from the user
nextLine() reads a one-line String from the user

• Each method waits until the user presses Enter.


• The value typed by the user is returned.
• Example: System.out.print("How old are you? "); // prompt
int age = sc.nextInt();
System.out.println("You typed " + age);

Lecture 6- Input and output functions in Java : Buffered reader class,


55
Scanner class
Reading a String with the Scanner class

• Reading a String
Scanner scan = new Scanner(System.in);

String str;

System.out.print(“What is your name? “);


str = scan.nextLine( );
System.out.println(“So your name is “ + str);

Lecture 6- Input and output functions in Java : Buffered reader class,


56
Scanner class
Reading integers with the Scanner class

• Reading an int number


Scanner scan = new Scanner(System.in);

int iAge = 0;
Int iYear = 2023;

System.out.print(“How old are you? “);


iAge = scan.nextInt( );
iYear = iYear - iAge;
System.out.println(“\nSo you were born around “ + iYear);

Lecture 6- Input and output functions in Java : Buffered reader class,


57
Scanner class
Reading doubles with the Scanner Class

• Reading a double number


Scanner scan = new Scanner(System.in);

final double dGoal = 1000000; //constant


double dEarnings = 0;
double dMissing = 0;

System.out.print(“How much do you make per hour? “);


dEarnings = scan.nextDouble( );
dMissing = dGoal - dEarnings;
System.out.println(“\nIn one hours you will only need “ + iMissing +
“more to earn your goal”);

Lecture 6- Input and output functions in Java : Buffered reader class,


58
Scanner class
Difference between Scanner and BufferReader Class in Java

Sr. No. Key Scanner Class BufferReader Class

Synchronous Scanner is not synchronous in nature BufferReader is synchronous in nature.


and should be used only in single During multithreading environment,
1
threaded case. BufferReader should be used.

Buffer Memory Scanner has little buffer of 1 KB char BufferReader has large buffer of 8KB
2 buffer. byte Buffer as compared to Scanner.

Processing Scanner is bit slower as it need to parse BufferReader is faster than Scanner as it
3
Speed data as well. only reads a character stream.

Methods Scanner has methods like nextInt(), BufferReader has methods like
4
nextShort() etc. parseInt(), parseShort() etc.

Read Line Scanner has method nextLine() to read BufferReader has method readLine() to
5
a line. read a line.

59 Lecture 6- Input and output functions in Java : Buffered reader class, Scanner class
Thank You

You might also like