Java - Module 1 PPT
Java - Module 1 PPT
Program Program
fun1() Obj1
fun3() Obj3
Procedural vs Object Oriented Programming
Object Oriented Programming
It is a programming style which is associated with the concept of class and
objects Object
Object
Class
Object
State? State
Name
Height
Behavior? Identity
Weight
Age …. Name or Aadhar
Identity?
Behavior
getName()
getHeight()
walk()
run()
Object
State? State
Brand
Color
Behavior? Identity
No. of gears
Model Registration No.
Identity? Or
Chasis No.
Behavior
drive()
brake()
Object
State? State
Brand
Size
Behavior?
Weight Identity
Speed Mac id or Product id
Identity?
Behavior
Program()
Paint()
Play()
Object
State? State
Day
Month
Behavior?
Year
Identity?
Behavior Identity
getDate() date
setDate()
DOB()
Object
State? State
Name
Balance
Behavior?
Identity?
Identity
Account Number
Behavior
deposit()
withdraw()
Class
● Class is a template or blueprint
● It describes the state (properties or attributes) and behavior (function or
method)
● Example
○ Car
○ Chair
○ Pen
Class vs Object
OOPs Concepts
OOP
Polymorphism Concept Inheritance
Encapsulation
Abstraction
Customer details
● Name
● Address
● Contact Number
● Tax Information
● Height
● Weight
● Favorite food
● Favorite actor
● Favorite brand
Abstraction
● Name
● Address
● Contact Number
● Tax Information
Providing only essential information to the outside world and hiding their background
details, i.e., to represent the needed information in program without presenting the
details
Encapsulation
Plant()
Simple
● Easy to learn
● Syntax is simple
○ No explicit pointer
● It is an abstract machine
● Loads code
● Verifies code
● Executes code
● Heap
○ It is the runtime data area in which objects are allocated
● Stack
○ It holds local variables and partial results, and plays a part in method invocation and return
● It contains
○ A virtual processor
○ Interpreter
○ Just-In-Time(JIT) compiler
■ JIT compiles parts of the byte code that have similar functionality at the same time,
and hence reduces the amount of time needed for compilation
Java native interface (JNI)
● It is a framework
● Java uses JNI framework to send output to the Console or interact with OS
libraries
JRE
● It is a set of software tools which are used for developing Java applications
● It physically exists
● It physically exists
● JDK Editions
○ Standard Edition Java Platform
Package statement
Import statement
Optional
Interface section
Class definition
● It is an optional section
● Used to improve the readability of the program
● It contains
○ Set of comment line statements
○ Name of the program
○ Purpose of the program
○ Author name and so on
● Represented as
○ // comment line - single line comment
○ /* comment */ - multiline comment
Package statement
● It is an optional statement
● First executable statement in a source file
● Used to declare the package name
● It informs the compiler that the classes defined belong to this package
● Example
○ package mypack;
Import statement
● It is an optional statement
● Instruct the interpreter to load the classes under a package
● Example
○ import java.io.*
Interface section
● It is an optional section
● Similar to class
● Contains group of method declaration
● Used to define multiple inheritance
● Example
interface MyInterface{
public void show();
}
Class definition
● It is an essential section
● main method is defined inside a class
● All the stand-alone java program must contain this section
● It is the starting point of execution of stand-alone java program
● Example
class Test{
public static void main(String[] args){
System.out.println(“test program”);
}
}
First program in java
System.out.println(“Hello World”);
}
}
Simple Java Program
MyProgram.java
public class MyProgram {
public static void main(String[] args){
System.out.println("My Program");
}
}
Compilation and Execution process
Class
It is an logical entity
Class
default
Syntax private
keyword Name of the class
public
protected
Attribute or property
access-specifier class ClassName{
variable declaration/definition;
method definition(){
Body of the method
}
}
Access Specifiers/Modifiers
Modifiers
Syntax
default
private
public Name of the
protected variable
Three types
● Local variable
● Instance variable
● Class variable
Local variable
● A variable declared inside the class but outside the body of the
method, is called instance variable
● Instance variables are non-static variables
● Created when an object of the class is created
● Destroyed when the object is destroyed.
● Initialization is not mandatory. Its default value is 0
● Instance Variable can be accessed only by objects
Class or Static variables
class Variable {
}
Methods
● Method declaration
● Method definition
● Method invocation/Call
Method Declaration
Syntax
default
private
public Type of input
protected Identifier
variable
void show();
● access-specifier – default
● return-type – void
● methodName – show
void show(String);
● access-specifier – default
● return-type – void
● methodName – show
● access-specifier – public
● return-type – int
● methodName – addValues
Syntax
default
private
public Declaration of
protected Data type Identifier
input variable
method body;
}
Method example
Method example - 1
void show(){
● access-specifier – default
● return-type – void
● methodName – show
● arguments – nil
Method example - 2
System.out.println(str);
● access-specifier – default
● return-type – void
● methodName – show
Syntax
methodName(argument value(s));
Example
show();
show(“Java Programming”);
Syntax
Name of the
Constructor
class
keyword
Example of an Object
Class with Object
Constructors
● Similar to method
● Method name is same as Class name
● No return type
● Can have arguments/parameters
● Cannot be invoked explicitly
● It is invoked when an instance of a class is created
● Can be overloaded
● Used to initialize the member of a class
● Two types
○ Default constructor
○ Parameterized constructor
Syntax for constructor
ClassName(argument(s) declaration) {
body of constructor;
}
Example
Class Example{
int ivar;
Example(){ //constructor
ivar=10;
}
public static void main(String[ ] args){
Example e1=new Example();
System.out.println(e1.ivar);
}
}
Types of constructors
● Default constructor
○ Constructor without parameter
● Parameterized constructor
○ Constructor with parameter
Example for Constructor
class Constructor{
Constructor(){
System.out.println(“Default constructor”);
}
Constructor(String str){
System.out.println(“Parameterized constructor”);
}
}
main() method
Syntax
}
Input statement
Syntax
import java.util.*; //package final member from
System class of
type InputStream
Class from
class lang package
object constructor
Output statement
System.out.print(“string value”);
final member of
System class of type
PrintStream
static keyword
● Variable
● Method
● Block
● Nested class
static variable
● Initialize with 0
Example
● Access only static members
static void show(String str){
System.out.println(str);
● It will preserve the last value
}
Example
● Used to initialize static members
static{
System.out.println(“static block ”);
● Executed only once
}
Data types
Data types
Data Type Description Default Default size
Value
float Stores fractional numbers. Sufficient for storing 6 to 7 decimal digits 0.0f 4 byte
3.4e−038 to 3.4e+038.
double Stores fractional numbers. Sufficient for storing 15 decimal digits 0.0d 8 byte
1.7e−308 to 1.7e+308
byte data type
Syntax
byte varname;
Syntax
short varname;
Syntax
int varname;
Syntax
long varname;
Syntax
float varname;
Syntax
double varname;
Syntax
String varname;
class UnaryOperator{
public static void main(String args[]){
int x=10;
System.out.println(x++); //10 (11)
System.out.println(++x); //12
System.out.println(x- -); //12 (11)
System.out.println(- -x); //10
}
}
Unary operator
class UnaryOperator{
public static void main(String args[]){
int a=10;
int b=10;
System.out.println(a++ + ++a); //10+12=22
System.out.println(b++ + b++); //10+11=21
}
}
Unary operator (~ and !)
class OperatorExample{
public static void main(String args[]){
int a=10;
int b=-10;
boolean c=true;
boolean d=false;
System.out.println(~a); //-11 (minus of total positive value which starts from 0)
System.out.println(~b); //9 (positive of total minus, positive starts from 0)
System.out.println(!c); //false (opposite of boolean value)
System.out.println(!d); //true
}
}
~ and ! operator
a = 10 b=5
class OperatorExample{
System.out.println(10*10/5+3-1*4/2); //21
}
Left shift operator
class LeftShiftOperator{
public static void main(String args[]){
System.out.println(10<<2); //10*2^2=10*4=40
System.out.println(10<<3); //10*2^3=10*8=80
System.out.println(20<<2); //20*2^2=20*4=80
System.out.println(15<<4); //15*2^4=15*16=240
}
}
Right shift operator
class RightShiftOperator{
System.out.println(10>>2); //10/2^2=10/4=2
System.out.println(20>>2); //20/2^2=20/4=5
System.out.println(20>>3); //20/2^3=20/8=2
}
Shift operator
class ShiftOperator{
public static void main(String args[]){
//For positive number, >> and >>> works same
System.out.println(20>>2); //5
System.out.println(20>>>2); //5
//For negative number, >>> changes parity bit (MSB) to 0
System.out.println(-20>>2); //-5
System.out.println(-20>>>2); //1073741819
}
}
Logical and Bitwise AND operators
class LogicalOperator{
public static void main(String args[]){
int a=10;
int b=5;
int c=20;
System.out.println(a<b&&a<c);//false && true = false
System.out.println(a<b&a<c);//false & true = false
}
}
Logical and Bitwise AND operators
class LogicalOperator{
public static void main(String args[]){
int a=10;
int b=5;
int c=20;
System.out.println(a<b&&a++<c); //false && true = false
System.out.println(a); //10 because second condition is not checked
System.out.println(a<b&a++<c); //false && true = false
System.out.println(a); //11 because second condition is checked
}
}
Logical and Bitwise OR operators
class LogicalOperator{
public static void main(String args[]){
int a=10;
int b=5;
int c=20;
System.out.println(a>b||a<c); //true || true = true
System.out.println(a>b|a<c); //true | true = true
//|| vs |
System.out.println(a>b||a++<c); //true || true = true
System.out.println(a); //10 because second condition is not checked
System.out.println(a>b|a++<c); //true | true = true
System.out.println(a); //11 because second condition is checked
}
}
Ternary operator
class TernaryOperator{
public static void main(String args[]){
int a=2;
int b=5;
int min=(a<b)?a:b;
System.out.println(min); //2
}
}
Assignment operator
class AssignmentOperator{
public static void main(String args[]){
int a=10;
int b=20;
a+=4; //a=a+4 (a=10+4)
b-=4; //b=b-4 (b=20-4)
System.out.println(a);
System.out.println(b);
}
}
Operation on short data type
class OperatorShortType{
public static void main(String args[]){
short a=10;
short b=10;
a=a+b; //Compile time error because 10+10=20 now int
System.out.println(a);
a=(short)(a+b); //20 which is int now converted to short
System.out.println(a);
}
}
Keywords
● default: Java default keyword is used to specify the default block of code in a
switch statement.
● enum: Java enum keyword is used to define a fixed set of constants. Enum
constructors are always private or default
● extends: Java extends keyword is used to indicate that a class is derived
from another class or interface
● final: Java final keyword is used to indicate that a variable holds a constant
value. It is applied with a variable. It is used to restrict the user
● finally: Java finally keyword indicates a block of code in a try-catch structure.
This block is always executed whether exception is handled or not
Keywords
● implements: Java implements keyword is used to implement an interface
● import: Java import keyword makes classes and interfaces available and
accessible to the current source code
● instanceof: Java instanceof keyword is used to test whether the object is an
instance of the specified class or implements an interface
● interface: Java interface keyword is used to declare an interface. It can have
only abstract methods
● native: Java native keyword is used to specify that a method is implemented
in native code using JNI (Java Native Interface)
● new: Java new keyword is used to create new objects
Keywords
● null: Java null keyword is used to indicate that a reference does not refer to
anything. It removes the garbage value
● short: Java short keyword is used to declare a variable that can hold a 16-bit
integer.
● static: Java static keyword is used to indicate that a variable or method is a
class method. The static keyword in Java is used for memory management
mainly
● strictfp: Java strictfp is used to restrict the floating-point calculations to
ensure portability
● super: Java super keyword is a reference variable that is used to refer parent
class object. It can be used to invoke immediate parent class method
Keywords
● try: Java try keyword is used to start a block of code that will be tested for
exceptions. The try block must be followed by either catch or finally block
● volatile: Java volatile keyword is used to indicate that a variable may change
asynchronously
Control flow
Control
Structures
Simple if
do-while continue
if-else
for return
nested if
if-else-if for-each
Simple if
Syntax
if (condition) {
}
Example for simple if
if (3 > 2) {
String branch=“CSE”;
if (branch.equals(“CSE”) ){
}
if-else
Syntax
if (condition) {
}else{
}
Example for if-else
String branch=“CSE”;
if (branch.equals(“CSE”)) {
} else {
}
if-else-if
Syntax
if (condition1) {
// block of code to be executed if the condition1 is true
}else if (condition2) {
// block of code to be executed if the condition1 is false and condition2 is true
} else{
// block of code to be executed if the condition1 is false and condition2 is false
}
Example for if-else-if
int value=scan.nextInt();
if (value < 0) {
} else if (value == 0) {
} else {
}
Nested if
Syntax
if (condition1) {
// block of code to be executed if the condition1 is true
if (condition2) {
// block of code to be executed if the condition2 is true
}
}
Example for nested if
int value1=scan.nextInt();
int value2=scan.nextInt();
if (value1 > 0) {
if (value2 > 0) {
System.out.println(value1/value2);
}
switch statement
Syntax
switch (expression) {
case value1:
// block of code
break;
case value2:
// block of code
break;
default:
// block of code
}
Example for switch statement
int value=scan.nextInt();
switch (value) {
case 0:
System.out.println(“Entered a zero value”);
break;
case 1:
System.out.println(“Entered a value one”);
break;
default:
System.out.println(“Entered value is greater than one”
}
Loops in java
for loop
Syntax
}
Example for simple for loop
}
for-each - Example
System.out.println(num);
}
Labeled for loop
Syntax
labelname:
for(initialization;condition;incr/decr){
//code to be executed
}
Example for labeled for loop
public class LabeledForExample {
public static void main(String[] args) {
aa:
for(int i=1;i<=3;i++){ Output
for(int j=1;j<=3;j++){ 11
if(i==2&&j==2){
12
break aa;
13
}
21
System.out.println(i+" "+j);
}
}
}
}
while loop
Syntax
while (condition) {
}
while loop - Example
int i = 1;
while (i < 5) {
System.out.println(i);
i = i + 1;
}
Output
1
2
3
4
do-while loop
Syntax
do {
} while (condition) ;
do-while loop - Example
int i = 1;
do {
System.out.println(i);
i = i + 1;
} while (i < 5);
Output
1
2
3
4
Arrays
● An array is a collection of similar types of data
● It is a container that holds data (values) of one single type
● The elements of an array are stored in a contiguous memory location
● We can store only a fixed set of elements in a Java array
● Array in Java is index-based, the first element of the array is stored at the 0th
index, 2nd element is stored on 1st index and so on
● Unlike C/C++, we can get the length of the array using the length member.
● They are created during runtime
● They are dynamic, created on the heap
Declaring an array
Types of array
● Two types
○ Single dimensional
○ Multidimensional
■ Arrays of array with each element of the array holding the reference of other array
Syntax Example
Syntax
arrayName=new data-type[size];
Example
intArray=new int[10];
Other ways to declare an array
Syntax
Example
Syntax
arrayName=new data-type[size1][size2];
Example
intArray=new int[5][5];
Initializing an array
intArray={1, 2, 3, 4, 5, 6, 7, 8, 9};
or
intArray={1, 2, 3, 4, 5, 6, 7, 8, 9};
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
System.out.println(intArray[i][j]);
}
Retrieve input from keyboard
Scanner scan=new Scanner(System.in);
int[][] arr=new int[3][3];
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
arr[i][j]=scan.nextInt();
}
}
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
System.out.println(arr[i][j]);
}
}
Packages
○ built-in package
○ user-defined package
■ User-defined packages are those which are developed by users in order to group related
classes, interfaces and sub packages.
Create a package
>javac –d . PackClass.java
Using package
import mypack.PackClass;
Class UsePack{
public static void main(String[] args){
PackClass pc=new PackClass();
pc.print();
}
}
Output
PackClass of mypack
Javadoc comments
● Javadoc is a tool which comes with JDK
● it is used for generating Java code documentation in HTML format from
Java source code
● >javadoc –d destination ProgramName.java
/** * The HelloWorld program implements an application that
simply displays "Hello World!" to the standard output.
* * @author Dr.G.Murugesan
* @version 1.0
* @since 2013-03-31 */
public class HelloWorld {
public static void main(String[] args) {
// Prints Hello, World! on standard output.
System.out.println("Hello World!");
}
}
Javadoc tags
Tag Description Syntax
@author Adds the author of a class. @author name-text
{@code} Displays text in code font without interpreting the text as HTML markup or
nested javadoc tags. {@code text}
{@docRoot} Represents the relative path to the generated document's root directory from
any generated page. {@docRoot}
@deprecated Adds a comment indicating that this API should no longer be used. @deprecated deprecatedtext
@exception Adds a Throws subheading to the generated documentation, with the
classname and description text. @exception class-name description
{@inheritDoc} Inherits a comment from the nearest inheritable class or implementable Inherits a comment from the immediate
interface. surperclass.
{@link} Inserts an in-line link with the visible text label that points to the
documentation for the specified package, class, or member name of a {@link package.class#member label}
referenced class.
{@linkplain} Identical to {@link}, except the link's label is displayed in plain text than code {@linkplain package.class#member
font. label}
Javadoc tags
Tag Description Syntax
@param Adds a parameter with the specified parameter-name followed by the specified @param parameter-name
description to the "Parameters" section. description
@return Adds a "Returns" section with the description text. @return description
@see Adds a "See Also" heading with a link or text entry that points to reference. @see reference
@serial Used in the doc comment for a default serializable field. @serial field-description | include
| exclude
@serialData Documents the data written by the writeObject( ) or writeExternal( ) methods. @serialData data-description
@serialField @serialField field-name field-
Documents an ObjectStreamField component. type field-description
@since Adds a "Since" heading with the specified since-text to the generated
documentation. @since release
@throws The @throws and @exception tags are synonyms. @throws class-name description
{@value} When {@value} is used in the doc comment of a static field, it displays the value of
that constant. {@value package.class#field}
@version Adds a "Version" subheading with the specified version-text to the generated docs
when the -version option is used. @version version-text
Example
import java.io.*;
/** Add Two Numbers!
The AddNum program implements an application that simply adds two given integer numbers and Prints the output on the screen.
* <p>
* <b>Note:</b> Giving proper comments in your program makes it more user friendly and it is assumed as a high quality code.
* @author Dr.G.Murugesani
* @version 1.0
* @since 2014-03-31 */
public class AddNum {
/** * This method is used to add two integers. This is a the simplest form of a class method, just to show the usage of various javadoc Tags.
* @param numA This is the first paramter to addNum method
* @param numB This is the second parameter to addNum method
* @return int This returns sum of numA and numB. */
public int addNum(int numA, int numB) {
return numA + numB;
}
/** * This is the main method which makes use of addNum method.
* @param args Unused.
* @return Nothing.
* @exception IOException On input error.
* @see IOException */
public static void main(String args[]) throws IOException {
AddNum obj = new AddNum();
int sum = obj.addNum(10, 20);
System.out.println("Sum of 10 and 20 is :" + sum);
}
}
Scanner class
Method Description
● Multiple methods can have the same name with different parameters
● Example
○ int add(int a, int b){
return a+b;
}
○ int add(int a, int b, int c){
return a+b+c;
}
Three ways to overload a method
● Number of parameters
○ add(int, int)
○ add(int, int, int)