0% found this document useful (0 votes)
4 views

Java - Module 1 PPT

The document provides an introduction to Object Oriented Programming (OOP) and Java fundamentals, explaining key concepts such as classes, objects, and programming paradigms. It outlines the four pillars of OOP: abstraction, encapsulation, inheritance, and polymorphism, along with the features of Java as an object-oriented language. Additionally, it covers Java's environment, including the Java Virtual Machine (JVM), Java Runtime Environment (JRE), and Java Development Kit (JDK), along with variable types and method declarations.

Uploaded by

chandru m
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Java - Module 1 PPT

The document provides an introduction to Object Oriented Programming (OOP) and Java fundamentals, explaining key concepts such as classes, objects, and programming paradigms. It outlines the four pillars of OOP: abstraction, encapsulation, inheritance, and polymorphism, along with the features of Java as an object-oriented language. Additionally, it covers Java's environment, including the Java Virtual Machine (JVM), Java Runtime Environment (JRE), and Java Development Kit (JDK), along with variable types and method declarations.

Uploaded by

chandru m
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 191

CS8392

Object Oriented Programming


Unit - 1
Introduction to OOP and Java
fundamentals
What is Object Oriented Programming?

● It is a programming paradigm where everything is treated as an object


● It is used to structure a software program into simple, reusable pieces of
code blueprints (called classes)
● Examples
○ C++
○ Python
○ Java
○ Simula
○ Smalltalk
What is Programming?

● It’s a way to instruct the computer to perform various tasks


● Instruct the computer
○ Set of statements or instructions written in a language
■ Adding two number
■ Rounding off a number
● Perform various tasks
○ carry out simple or complex task
■ Calculating simple interest, given that principal, rate, and time
■ Calculating the average return on a stock over last five years
Programming Paradigm

● Style or way of programming


● Approach to solve a problem
● Way to classify the programming languages according to their features
● Two programming paradigm
○ Imperative
○ Declarative
Programming Paradigm

● Imperative Programming Paradigm


○ Program closely related to machine architecture
○ Instruct the machine how to change its state
○ Three categories
■ Procedure oriented
● Groups the instructions into procedures
● C, Fortran, Basic
■ Object oriented
● Groups the instructions together with the part of the state they operate on
● C++, Simula, Java
■ Parallel processing
● Divide the instructions for multiple processors
● NESL, C/C++
Programming Paradigm
● Declarative Programming Paradigm
○ Programming by specifying the result you want, not how to get it
○ It expresses logic of computation without talking about its control flow
○ Three categories
■ Logic (Rule based)
● Expresses logic of computation without talking about its control flow
● Solves logial problems like puzzle, series etc.
● Prolog
■ Functional
● programs are treated as a sequence of stateless function evaluations
● Execute series of mathematical functions
● Javascript, Lisp, Scala
■ Database processing
● Program statements are defined by data rather than hard-coding a series of steps
● SQL
Procedural vs Object Oriented Programming
Procedure oriented programming Object oriented programming

Program Program

fun1() Obj1

Data fun2() Obj2

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

CLASS is a blueprint or a set of instructions to build a specific type of object.


OBJECT is an instance of a class.
Object
● Object is an real time entity
● It has state and behavior
● Physical or logical (tangible or intangible)
● Characteristics
○ State
○ Behaviour
○ identity
● It is an instance of a class
Object

Physical or Tangible objects Logical or Intangible objects


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

Four pillars of OOPs


Abstraction

OOP
Polymorphism Concept Inheritance

Encapsulation
Abstraction

● Shows only essential attributes


● Hides the unnecessary details from the users
● Selecting data from a larger pool to show only relevant details of the object to the user
● It helps in reducing programming complexity and efforts
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

● Wrapping up of data and functions into a single unit


● Keeps data and code safe from external interference
Abstraction vs Encapsulation
Inheritance

● Inherit means “to derive”


● Mechanism by which an object acquires the some/all properties of another
object.
● Example

○ Relationship between parent and child

■ Child acquires the properties of parent


Inheritance
Polymorphism

● Poly means “many forms”


● Same object can be represent in different form
Polymorphism
Types of Polymorphism

● Static – Compile time


○ Method overloading

● Dynamic – Run time


○ Method overriding
Features of Java
Object Oriented

● Object oriented programming language

● Everything in java is an object


Live()

Plant()
Simple

● Easy to learn

● Syntax is simple

● Clean and easy to understand


Platform independent

● Written once and run anywhere (wora)

● Java code can be run on multiple platforms

● Compiled by a compiler produce byte code

● Byte code is platform independent


Secured

● Java is secured because

○ No explicit pointer

○ Runs on virtual machine


Robust

● Java is robust because

○ It uses strong memory management

○ Automatic garbage collector

○ Exception handling mechanism

○ Strict type checking


Architecture Neutral

● No implementation dependent features


● For example

○ size of primitive type is fixed

■ In C, int - 2 byte for 32bit architecture, 4 byte for 64 bit architecture

■ Java – 4 byte for int on both architecture


Portable

● Facilitate to carry java byte code to any platform

● It doesn’t require any implementation


High Performance

● Run faster than other programming languages

● Byte code is very close to native code

● Little bit slower than compiled languages due to .class file


Distributed

● Allow to create distributed applications

● RMI and EJB used to create distributed applications


Multithreaded

● Based on the concept of multithreaded programming

● Share common memory for multiple task


Dynamic

● Support dynamic loading of classes

● Classes are loaded on demand

● Support dynamic compilation and automatic memory management


Java Environment
JVM

● It is an abstract machine

● It is a specification that provides runtime environment in which java byte


code can be executed

● JVMs are available for many hardware and software platforms

● Its implementation is known as JRE (Java Runtime Environment)


Functionalities of JVM

● Loads code

● Verifies code

● Executes code

● Provides runtime environment


JVM Architecture
Classloader

● Classloader is a subsystem of JVM which is used to load class files


● There are three built-in classloaders in Java
○ Bootstrap ClassLoader
■ It loads the rt.jar file which contains all class files of Java Standard Edition
○ Extension ClassLoader
■ It loades the jar files located inside $JAVA_HOME/jre/lib/ext directory.
○ System/Application ClassLoader
■ It loads the classfiles from classpath
Memory area
● Class area
○ runtime constant pool, field and method data, the code for methods

● 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

● Program counter register


○ It contains the address of the Java virtual machine instruction currently being executed

● Native method stack


○ It contains all the native methods used in the application
Execution engine

● It contains

○ A virtual processor

○ Interpreter

■ Read byte code stream then execute the instructions

○ 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

● It provides an interface to communicate with another application written in


another language like C, C++, Assembly etc.

● 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 is used to provide the runtime environment

● It is the implementation of JVM

● It physically exists

● It contains a set of libraries + other files that JVM uses at runtime


JDK
● It is a software development environment which is used to develop Java
applications and applets

● It physically exists

● It contains JRE + development tools

● JDK Editions
○ Standard Edition Java Platform

○ Enterprise Edition Java Platform

○ Micro Edition Java Platform


Java source file structure
Documentation section Suggested

Package statement

Import statement
Optional
Interface section

Class definition

Main method class Essential


section
Documentation section

● 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

● Define classes other than main method class


● Can have ‘n’ number of classes
● Example
class Test{
int x=10;
public void prints(){
System.out.println(“x=“+x)
}
}
Main method class section

● 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

Hello.java File name

//Program to print Hello World Comment statement

package mypack; Package statement

import java.io.*; Import statement

public class Hello{ Main method class section

public static void main(String[] args){ Main method

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

Access Non Access


Modifiers Modifiers

public private protected default

final abstract static transient volatile synchronized


Access Modifiers/Specifiers
Access Modifiers
Private
● Access only within the class.
● It cannot be accessed from outside the class.
Default
● No keyword
● Access only within the package.
● It cannot be accessed from outside the package
Protected
● Access within the package
● Access outside the package through child class
Public
● It can be accessed from within the class, outside the class, within the
package and outside the package.
Variable
● A variable is a container which holds the value while the Java
Program is executed
● A variable is assigned with a data type
● Variable is a name of memory location
● It is the basic unit of storage in a program
● The value stored in a variable can be changed during
program execution.
● In Java, all the variables must be declared before use
● Also called as identifiers
● It can be used as class name, method name, interface name
and package name
Declaring a variable

Syntax
default
private
public Name of the
protected variable

Access-modifier data-type variable_name;

Access-modifier data-type variable_name=value;


Variable/Identifier naming rules

● Begin with a letter (A to Z or a to z), currency character ($) or an underscore


(_).
● After the first character, identifiers can have any combination of characters
● A keyword cannot be used as an identifier
● Most importantly, identifiers are case sensitive
● Examples of legal identifiers: age, $salary, _value, _ _1_value
● Examples of illegal identifiers: 123abc, -salary
Example of variable declaration and initialization

int ivar; int ivar=10 ;


private double dvar; private double dvar=12.34;
public char cvar; public char cvar=’c’;
protected String svar; protected String svar=”java”;
Types of variable (based on scope)

Three types

● Local variable

● Instance variable

● Class variable
Local variable

● variable defined within a block or method or constructor is called local


variable.

● Created when the block in entered or the function is called


● Destroyed after exiting from the block or when the call returns from the
function.

● Initialization of the variable is mandatory


● The scope of these variables exists only within the block in which the
variable is declared. i.e. we can access these variable only within that block.
Instance 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

● Variable which is declared as static is called static variable.


● It cannot be local.
● Only one copy of a static variable per class
● Variables are created at the start of program execution
● Destroyed automatically when execution ends
● Initialization of static Variable is not Mandatory. Its default value is 0
● Static variable can be accessed through either with class or an object
Example

class Variable {

int amount = 100; // instance variable

static int pin = 2315; // static variable

public static void main(String[ ] args) {

int age = 35; // local variable

}
Methods

Method statement can be

● Method declaration

● Method definition

● Method invocation/Call
Method Declaration

Syntax
default
private
public Type of input
protected Identifier
variable

access-specifier return-type methodName(data type of arguments);


Data type
Example- 1

void show();

● access-specifier – default

● return-type – void

● methodName – show

● data type of arguments – nil


Example- 2

void show(String);

● access-specifier – default

● return-type – void

● methodName – show

● data type of arguments – String


Example- 3

public int addValues(int, int);

● access-specifier – public

● return-type – int

● methodName – addValues

● data type of arguments – int, int


Method Definition

Syntax
default
private
public Declaration of
protected Data type Identifier
input variable

access-specifier return-type methodName(arguments){

method body;

}
Method example
Method example - 1

void show(){

System.out.println(“Object oriented programming”);

● access-specifier – default

● return-type – void

● methodName – show

● arguments – nil
Method example - 2

void show(String str){

System.out.println(str);

● access-specifier – default

● return-type – void

● methodName – show

● arguments – String str


Method example - 3
int addValues(int v1, int v2){
int v3 = v1 + v2
return v3;
}
● access-specifier – default
● return-type – int
● methodName – addValues
● arguments – int v1, int v2
Method definition
Method Invocation/Call

Syntax

Identifier input values for


the method

methodName(argument value(s));
Example

show();

show(“Java Programming”);

int sum=addValues(3, 4);

int large=max(7, 3);


Object

● Object is an instance of a class

● It is an real world entity

● Each object have state, behaviour and identity


Creating objects
Object in Java

Syntax

Name of the
Constructor
class

ClassName object_name=new ClassName();

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

public static void main(String[ ] args){

body of main method;

}
Input statement

Syntax
import java.util.*; //package final member from
System class of
type InputStream
Class from
class lang package

Scanner scan=new Scanner(System.in);

object constructor
Output statement

Syntax Method from


PrintStream class
Class from
lang package

System.out.print(“string value”);

final member of
System class of type
PrintStream
static keyword

● Variable

● Method

● Block

● Nested class
static variable

● Variable with static keyword


Syntax
● Also known as class variable
static data-type variable_name;
● Gets memory only once Example

● One memory space for a class static int var;

● Initialize with 0

● Can be accessed by class name


static method
Syntax
● Method with static keyword static return-type method_name(arguments){
method body;
● Can be accessed by class name }

Example
● Access only static members
static void show(String str){
System.out.println(str);
● It will preserve the last value
}

● Belongs to class rather than the object of a class


static block
Syntax
● Block with static keyword static{
statement(s);
● Executed prior to main() method }

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

boolean Stores true or false values false 1 bit

char Stores a single character/letter or ASCII values '\u0000' 2 byte

byte Stores whole numbers from -128 to 127 0 1 byte

short Stores whole numbers from -32,768 to 32,767 0 2 byte

int Stores whole numbers from -2,147,483,648 to 2,147,483,647 0 4 byte

long Stores whole numbers from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 0L 8 byte

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;

public class MyClass {


public static void main(String[] args) {
byte myNum = 100;
System.out.println(myNum);
}
}
Output
100
short data type

Syntax
short varname;

public class MyClass {


public static void main(String[] args) {
short myNum = 1000;
System.out.println(myNum);
}
}
Output
1000
int data type

Syntax
int varname;

public class MyClass {


public static void main(String[] args) {
int myNum = 10000;
System.out.println(myNum);
}
}
Output
10000
long data type

Syntax
long varname;

public class MyClass {


public static void main(String[] args) {
long myNum = 100000L;
System.out.println(myNum);
}
}
Output
100000
float data type

Syntax
float varname;

public class MyClass {


public static void main(String[] args) {
float myNum = 2.56f;
System.out.println(myNum);
}
}
Output
2.56
double data type

Syntax
double varname;

public class MyClass {


public static void main(String[] args) {
double myNum = 12.56d;
System.out.println(myNum);
}
}
Output
12.56
Scientific number
Syntax
float/double varname;

public class MyClass {


public static void main(String[] args) {
float myNum1 = 12e3f;
double myNum2 = 5e4d;
System.out.println(myNum1);
System.out.println(myNum2);
}
}
Output
12000.0
50000.0
boolean datatype
Syntax
boolean varname;

public class MyClass {


public static void main(String[] args) {
boolean isBlue = true;
boolean isRed = false;
System.out.println(isBlue);
System.out.println(isRed);
}
}
Output
true
false
char data type
Syntax
char varname;

public class MyClass {


public static void main(String[] args) {
char grade = ‘O’;
char alpha = 65;
System.out.println(grade);
System.out.println(alpha);
}
}
Output
O
A
String data type

Syntax
String varname;

public class MyClass {


public static void main(String[] args) {
String myString = “This is my string”;
System.out.println(myString);
}
}
Output
This is my string
Operators
Operator Type Category Precedence

Unary postfix expr++ expr--


prefix ++expr --expr +expr -expr ~ !
Arithmetic multiplicative */%
additive +-
Shift shift << >> >>>
Relational comparison < > <= >= instanceof
equality == !=
Bitwise bitwise AND &
bitwise exclusive OR ^
bitwise inclusive OR |
Logical logical AND &&
logical OR ||
Ternary ternary ?:
Assignment assignment = += -= *= /= %= &= ^= |= <<= >>= >>>=
Unary operator

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

Binary equivalent = 1010 0101

~a = 0101 = 3 (decimal) ~b = 1010 = 10 (decimal)

~10 = -11 ~5 = -6 (0101 + 1 = 0110)


Arithmetic operator
class ArithmeticOperator{
public static void main(String args[]){
int a=10;
int b=5;
System.out.println(a+b); //15
System.out.println(a-b); //5
System.out.println(a*b); //50
System.out.println(a/b); //2
System.out.println(a%b); //0
}
}
Arithmetic expression

class OperatorExample{

public static void main(String args[]){

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{

public static void main(String args[]){

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

● abstract: Java abstract keyword is used to declare abstract class. Abstract


class can provide the implementation of interface. It can have abstract and
non-abstract methods
● boolean: Java boolean keyword is used to declare a variable as a boolean
type. It can hold True and False values only.
● byte: Java byte keyword is used to declare a variable that can hold an 8-bit
data values.
● catch: Java catch keyword is used to catch the exceptions generated by try
statements. It must be used after the try block only
● class: Java class keyword is used to declare a class
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

● synchronized: Java synchronized keyword is used to specify the critical


sections or methods in multithreaded code
● this: Java this keyword can be used to refer the current object in a method or
constructor
● throw: The Java throw keyword is used to explicitly throw an exception. The
throw keyword is mainly used to throw custom exception. It is followed by an
instance
● throws: The Java throws keyword is used to declare an exception. Checked
exception can be propagated with throws
● transient: Java transient keyword is used in serialization. If you define any
data member as transient, it will not be serialized
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

Selection Iterative Jump

switch if statement while break

Simple if
do-while continue
if-else
for return
nested if

if-else-if for-each
Simple if

Syntax

if (condition) {

// block of code to be executed if the condition is true

}
Example for simple if

if (3 > 2) {

System.out.println(“3 is greater than 2”);

String branch=“CSE”;

if (branch.equals(“CSE”) ){

System.out.println(“belongs to CSE branch”);

}
if-else

Syntax

if (condition) {

// block of code to be executed if the condition is true

}else{

// block of code to be executed if the condition is false

}
Example for if-else

String branch=“CSE”;

if (branch.equals(“CSE”)) {

System.out.println(“belongs to CSE branch”);

} else {

System.out.println(“not belongs to CSE branch”);

}
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) {

System.out.println(“entered a negative value”);

} else if (value == 0) {

System.out.println(“entered a zero value”);

} else {

System.out.println(“entered a positive value”);

}
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

● for loop is used to iterate a part of the program several times

● If the number of iteration is fixed, it is recommended to use for loop

● three types of for loops


○ Simple for Loop

○ for-each or Enhanced For Loop

○ Labeled for Loop


Simple for loop

Syntax

for(initialization; condition; incr/decr){

//statement or code to be executed

}
Example for simple for loop

for(i=1; i<=10; i++){ Output


1
2
System.out.println(i); 3
4
} 5
6
7
8
9
10
for-each
Syntax

for (type variableName : arrayName) {

// code block to be executed

}
for-each - Example

String[] numbers={“one”, “two”, “three”, “four”, “five”};

for (String num : numbers) {

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

// code block to be executed

}
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 {

// code block to be executed

} 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

■ Also known as linear array

■ Elements are stored in a single row

○ Multidimensional

■ It is a combination of two or more arrays or nested arrays

■ Arrays of array with each element of the array holding the reference of other array

■ Also called Jagged Arrays


Single dimensional array

Syntax Example

data-type[] arrayName; int[] intArray;


or or
data-type arrayName[]; int intArray[];
Creating an array

● create an array by using the new operator

Syntax

arrayName=new data-type[size];

Example

intArray=new int[10];
Other ways to declare an array
Syntax

data-type[] arrayName=new data-type[size];

data-type[] arrayName={value1, value2, . . ., valueN};

Example

int[] intArray=new int[10];

int[] intArray={10, 20, 30, 40, 50};


Traversing array
int[] intArray={10, 20, 30, 40, 50};
for(int i=0;i<5;i++){
System.out.println(intArray[i]);
}
Output
10
20
30
40
50
Retrieve input from keyboard
Scanner scan=new Scanner(System.in);
Output
int[] intArray=new int[5];
10
//Read a value from keyboard 20
for(int i=0;i<5;i++){ 30
intArray[i]=scan.nextInt(); 40
50
}
//Print the array values
for(int i=0;i<5;i++){
System.out.println(intArray[i]);
}
Multidimensional array

Syntax for declaring an array Example

data-type[][] arrayName; int[][] intArray;


or or
data-type [][]arrayName; int [][]intArray;
or or
data-type arrayName[][]; int intArray[][];
or or
data-type []arrayName[]; int []intArray[];
Allocating memory to an array

Syntax

arrayName=new data-type[size1][size2];

Example

intArray=new int[5][5];
Initializing an array

int[][] intArray=new int[3][3];

intArray={1, 2, 3, 4, 5, 6, 7, 8, 9};

or

intArray={{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};


Traversing an array

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

● Package is a group of similar types of classes, interfaces and sub-packages


● categorized in two form

○ built-in package

■ lang, awt, javax, swing, net, io, util, sql etc.

○ 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

Syntax package mypack;


package packname; public class PackClass{

public void print(){


Example
System.out.println(“PackClass of mypack”);
package mypack;
}

Compile the package program

>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

nextBoolean() Reads a boolean value from the user

nextByte() Reads a byte value from the user

nextDouble() Reads a double value from the user

nextFloat() Reads a float value from the user

nextInt() Reads a int value from the user

nextLine() Reads a String value from the user

nextLong() Reads a long value from the user

nextShort() Reads a short value from the user

next() Read a string (single word)


Method overloading

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

● Data type of parameters


○ add(int, int)
○ add(int, float)

● Sequence of Data type of parameters


○ add(int, float)
○ add(float, int)
Quiz - 1
Quiz-2
Quiz - 3
Quiz - 4
Quiz - 5
Java Programming

● Creating class - Distance class, Time class


● Looping
● Constructors
● Static members

You might also like