0% found this document useful (0 votes)
16 views216 pages

Java-Unit 1 Fundamentals of Java Programming

The document provides an overview of Java programming, covering its history, features, and applications. It explains the structure of a simple Java program, data types, variables, and the components of the Java platform including JDK, JRE, and JVM. Additionally, it highlights the different types of Java applications and their respective platforms.

Uploaded by

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

Java-Unit 1 Fundamentals of Java Programming

The document provides an overview of Java programming, covering its history, features, and applications. It explains the structure of a simple Java program, data types, variables, and the components of the Java platform including JDK, JRE, and JVM. Additionally, it highlights the different types of Java applications and their respective platforms.

Uploaded by

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

Java Programming

Unit-1
Fundamental Programming in
Java
Contents
• What is Java?
• History of Java
• Java Buzzwords
• Java Programming Environment- JVM, JIT Compiler, Byte Code
Concept
• A Simple Java Program
• Source File Declaration Rules
• Comments, Data Types, Variables, Operators
• Strings
• Input and Output
• Control Flow 2
Need of Programming Language

3
What is Java???
• Java is a general-purpose computer-programming language.

• It is object-oriented programming language similar to C++.


• Java is a programming language and a platform.

• As Java is a programming language, it is


• high level
• robust
• object-oriented
• class-based
• Concurrent
• Secure programming language.
4
What is Java????
• Java is free to access and can run on all platforms.
• It is programming language that produces a software for multiple
platforms.
• History:
• Java was developed by Sun Microsystems in the year 1991.
• Later it is acquired by Oracle Corporation. It is now subsidiary of
Oracle.
• Java is developed by James A. Gosling and Patrick Naughton.
• Before Java, its name was Oak.
• Since Oak was already a registered company, so James Gosling and his
team changed the name from Oak to Java.
5
Java Features
• Platform:
• Any hardware or software environment in which a program runs, is
known as a platform.
• Since Java has a runtime environment (JRE) and API, it is called a
platform.
• Java Features:
• The primary objective of Java programming language creation was to
make it portable, simple and secure programming language.
• Some excellent features which play an important role in the popularity of
this language.
• The features of Java are also known as Java buzzwords.
6
Java Features
• Simple
• Object-Oriented
• Portable
• Platform independent
• Secured
• Robust
• Architecture neutral
• Interpreted
• High Performance
• Multithreaded
• Distributed
• Dynamic 7
Java is Simple language
• Java is very easy to learn, and
• Its syntax is simple, clean and easy to understand.

• According to Sun Microsystem, Java language is a simple programming


language because:
• Java syntax is based on C++
• Java has removed many complicated and rarely-used features.
• Explicit pointers, operator overloading, etc.
• There is no need to remove unreferenced objects because there is
an Automatic Garbage Collection in Java.

8
Java is Object-oriented
• Java is an object-oriented programming language.
• Everything in Java is an object.

• Object-oriented means we organize software as a combination of


different types of objects that incorporate both data and behavior.

• Object-oriented programming (OOPs) is a methodology that simplifies


software development and maintenance by providing some rules.

• Basic concepts of OOPs are object, class, inheritance, polymorphism,


abstraction, encapsulation.
9
Java is platform independent
• Java is platform independent.
• It is different from other languages like C, C++

• A platform is the hardware or software environment


in which a program runs.
• Java code can be executed on multiple platforms.

• Java code is compiled by the compiler and converted


into bytecode.

• This bytecode is a platform-independent code


because it can be run on multiple platforms, i.e.,
Write Once and Run Anywhere (WORA).
10
Java is Secured
• Java is best known for its security.
• With Java, we can develop virus-free systems.

• Java is secured because:


• No explicit pointer
• Java Programs run inside a virtual machine sandbox
• Classloader
• Bytecode Verifier
• Security Manager

• Some security can also be provided by an application developer


explicitly through SSL, JAAS, Cryptography, etc.
11
Java is Robust
• Java is robust because:
• It uses strong memory management.
• There is a lack of pointers that avoids security problems.
• Java provides automatic garbage collection which runs on the JVM.
• Exception handling and the type checking mechanism in Java.
• All these points make Java robust.

• Portable
• Java is portable because it facilitates to carry the Java bytecode to
any platform.
• It doesn't require any implementation.
12
Java is Architecture-neutral
• Java is architecture neutral because there are no implementation
dependent features.
• E.g. The size of primitive types is fixed.

• In C programming,
• int data type occupies
2 bytes of memory for 32-bit architecture and
4 bytes of memory for 64-bit architecture.

• Int occupies 4 bytes of memory for both 32 and 64-bit architectures in


Java.
13
Java is Distributed
• Java is distributed because
• it facilitates users to create distributed applications in Java.
• RMI and RPC are used for creating distributed applications.
• This feature of Java makes us able to access files by calling the
methods from any machine on the internet.
• Dynamic
• Java is a dynamic language.
• It supports the dynamic loading of classes.
• It means classes are loaded on demand.
• It supports functions from its native languages, i.e., C and C++.
• Java supports dynamic compilation and automatic memory
management (garbage collection). 14
Applications of Java
• According to Sun, 3 billion devices run Java.
• There are many devices where Java is currently used.
• Applications of Java are as follows:
• Desktop Applications such as acrobat reader, media player, antivirus.
• Web Applications such as [Link].
• Enterprise Applications such as banking applications.
• Mobile Applications
• Embedded System
• Smart Card
• Robotics
• Games, etc.
15
Types of Java Applications
• Mainly 4 types of applications that can be created using Java
programming:
1) Standalone Application

2) Web Application

3) Enterprise Application

4) Mobile Application

16
Types of Java Applications
• Standalone applications

• Also known as desktop applications or window-based applications.


• These are traditional software that we need to install on every
machine.
• Examples- Media player, antivirus, etc.
• AWT and Swing are used in Java for creating standalone applications.

17
Types of Java Applications
• Enterprise Application

• Application that is distributed in nature is called an enterprise


application.
• Example- banking applications
• It has advantages like high-level security, load balancing, and
clustering.
• In Java, EJB is used for creating enterprise applications.
• EJB (Enterprise Java Bean) is used to develop scalable, robust and
secured enterprise applications in java.
18
Types of Java Applications
• Web Application
• An application that runs on the server side and creates a dynamic page is
called a web application.
• Servlet, JSP, Hibernate etc. technologies are used for creating web
applications in Java.
• online forms, shopping carts, email programs such as Gmail, Yahoo.

• Mobile Application
• Application which is created for mobile devices is called mobile
application
• Android and Java ME are used for creating mobile applications.
• Social Media Mobile Apps, Games/Entertainment Mobile Apps
• Google Play/App Store Search 19
Java Platforms / Editions

• There are 4 platforms or editions of Java:


1) Java SE (Java Standard Edition)

2) Java EE (Java Enterprise Edition)

3) Java ME (Java Micro Edition)

4) JavaFX

20
Java Platforms / Editions
1) Java SE (Java Standard Edition)
• It is a Java programming platform.
• It includes Java programming APIs
• [Link], [Link], [Link], [Link], [Link], [Link] etc.

• It includes core topics like OOPs, String, Exception, Inner classes,


Multithreading, I/O Stream, Networking, AWT, Swing, Collection, etc.

21
Java Platforms / Editions
2) Java EE (Java Enterprise Edition)
• It is an enterprise platform that is mainly used to develop web and
enterprise applications.
• It is built on top of the Java SE platform.
• It includes topics like Servlet, JSP, Web Services, EJB etc.
3) Java ME (Java Micro Edition)
• It is a micro platform that is dedicated to mobile applications.
4) JavaFX
• It is used to develop rich internet applications. It uses a lightweight
user interface API.
• Applications developed using JavaFX can run on Desktop Computers,
Mobile Phones, TVs, Tablets, etc. 22
Components of Java Platforms
• Java platform
• Any hardware or software environment in which a program runs, is
known as a platform.
• It helps to execute applications written in Java programming
language.
• It consists of a
• Java compiler,
• Set of libraries, and
• Execution engine.
• Java platform is independent of any particular OS.
• It makes Java programming language a platform-independent.
23
Components of Java Platforms
• Java platform components are:
• Java language
• The Java Development Kit (JDK)
• The Java Runtime Environment (JRE)
• The Java Compiler
• The Java Virtual Machine (JVM)

• Java platform also contains


• Garbage collectors,
• Set of libraries and
• Additional components and tools that are required to efficiently run
the Java applications. 24
Java Language
• Java is a programming language
• It uses Java platform.

• Java is an object-oriented programming language whose


• syntax is derived from C and
• OOPs features are derived from C++.

• It has its syntax, rules, format, and programming paradigm.

25
Java Compiler
• This is a compiler for Java programming language (Javac)
• It translates java source code into byte code.

• It generates Java class files from the Java source code.


• Java class file contains a platform-independent Java byte code.

• After generating class files,


• JVM loads these class files and
• Interprets the byte code or compiles it to machine code using Just-in-
time (JIT) compiler
26
Java Virtual Machine (JVM)
• JVM is-
• Center of Java programming language and Java platform.
• An abstract machine.
• Specification that provides a run time environment to execute byte code.
• JVM
• loads class files and interprets the byte code or compiles it to machine code using
Just-in-time (JIT) compiler
• converts the byte code into machine-specific code (object code).
• JVM executes a byte code generated by compiler.
• Each OS has different JVM, but output is same across all OS.
• JVM is platform-independent
• (WORA – Write – Once – Run – Anywhere) 27
Java Runtime Environment (JRE)
• JRE is software package.
• It contains what is required to run a java program.
• It is runtime environment that is required to execute Java programs.

• JRE consists of
• Java Virtual Machine (JVM) and
• Class libraries
• other support classes to successfully execute Java programs by JVM.
• To execute any program written in Java, need JRE installed on system.

• JRE is platform dependent.


• Need to download and install JRE compatible with O.S and architecture. 28
Java Development Kit (JDK)
• Core component of any Java environment.
• It is tool necessary to
• Compile, debug, document, package java programs.

• Contains JRE along with Java compiler, Java debugger, other core classes.
• JDK is used for Java development.
• It provides the entire executable and binaries.

• JDK includes-
• Compiler (javac)
• Archiver (jar)
• Document generator (javadoc)
29
Components of JDK

30
Java Program Structure

31
A Simple Java Program
[Link]
/* Line1
Line2 */
class Simple
{
public static void main(String args[])
{
[Link](“Welcome");
}
}
32
A Simple Java Program
• A multiline comment.
• This type of comment must begin with /* and end with */.
• A single-line comment, shown here: // Line1

• The keyword class to declare that a new class is being defined.


• Simple is an identifier that is the name of the class.

• Class definition, including all of its members, between the opening curly
brace ({) and the closing curly brace (}).

33
A Simple Java Program
• public static void main(String args[])
• This is the main( ) method
• All Java applications begin execution by calling main( ).
• The public keyword is an access modifier.
• It allows the programmer to control the visibility of class members.
• Member may be accessed by code outside the class in which it is
declared.
• Making the main() method public makes it globally available.
• The keyword static allows main( ) to be called without having to
instantiate a particular instance of the class.

34
A Simple Java Program
• The main() method is static so that JVM can invoke it without instantiating
the class.
• The keyword void
• It simply tells the compiler that main( ) does not return a value.
• Void is used to specify that a method doesn’t return anything.

• String args[ ]
• It declares a parameter named args, which is an array of instances of the
class String.
• It stores Java command line arguments and is an array of
type [Link] class.

• Output is actually accomplished by the built-in println( ) method. 35


A Simple Java Program- Steps
• Java program 🡪 Source file 🡪 [Link] (Source Code)

• Compile (Javac) 🡪 Class file 🡪 [Link] (Byte coded)

• Interpret (JIT/JVM) 🡪 Machine/object code 🡪 [Link]

• Execute (JRE)

• Java file compilation 🡪 javac [Link]


• Execution 🡪 java Simple
36
Data Types
• Defines types of data used in program.
• Java defines eight primitive types of data:
• byte, short, int, long, char, float, double, and boolean.

• The primitive types are also commonly referred to as simple types.


• These can be put in four groups:

• Integers
• byte, short, int, long.
• These are for whole-valued signed numbers.

37
Data Types
• Floating-point numbers
• This group includes float and double.
• These represent numbers with fractional precision.

• Characters
• This group includes char.
• These represents symbols in a character set, like letters and numbers.

• Boolean
• This group includes boolean.
• These is a special type for representing true/false values.
38
Data Types
Data Name Width Range
Type
Integer long 64 –9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
int 32 –2,147,483,648 to 2,147,483,647
short 16 –32,768 to 32,767
byte 8 –128 to 127
Floating double 64 4.9e–324 to 1.8e+308
point
float 32 1.4e–045 to 3.4e+038
Character char 16 0 to 65,536
Boolean boolean 1 0/1 (true/false)
39
Variables
• The variable is the basic unit of storage in a Java program.
• It is a container which holds the value while the Java program is executed.

• Variable is-
• Name which is associated with a value that can be changed.
• Assigned with a data type.
• Name of memory location.
• Name of a reserved area allocated in memory.
• Combination of "vary + able" which means its value can be changed.

• Variable must be declared before they can be used.


• All variables have a scope and a lifetime. Scope defines their visibility
40
Variable Declaration
• Variable is defined by combination of an identifier, type and a optional
initializer.
• Variable Declaration Syntax
type identifier;
data_type variable _name;
OR
data_type variable _name1, variable_name2, …. ;

• Example
• int number;
• char Grade;
• float percentage, Average;
41
Variable Initialization
• Variable is associated with a value that can be changed is called as variable
initialization.
• Syntax:
type identifier = value;
data_type variable _name = value;
OR
data_type variable _name1 = value1, variable_name2 = value2, …. ;
type identifier [ = value ][, identifier [= value ] …];
• Example
• byte z = 22; // initializes z.
• char x = 'x'; // the variable x has the value 'x'.
• int d = 3, f = 5; 42
Dynamic initialization
• Dynamic Initialization
• Java allows variables to be initialized dynamically, using any expression
valid at the time the variable is declared.

class DynInit {
public static void main(String args[]) {
double a = 3.0, b = 4.0; // c is dynamically initialized
double c = [Link](a * a + b * b);
[Link]("Hypotenuse is " + c);
}
} 43
Types of Variables
• Local Variable
• Instance Variable
• Static variable

44
Types of Variables
• Local Variable
• A variable declared inside the body of the method is called local
variable.
• Use this variable only within that method.
• Other methods in the class aren't aware that the variable exists.
• A local variable cannot be defined with "static" keyword.

• Instance Variable
• A variable declared inside the class but outside the body of the
method, is called an instance variable.
• It is not declared as static.
• Its value is instance-specific and is not shared among instances.
45
Types of Variables
• Static variable
• A variable that is declared as static is called a static variable.
• It cannot be local.
• You can create a single copy of the static variable and share it among
all the instances of the class.
• Memory allocation for static variables happens only once when the
class is loaded in the memory.

• Example-
• static int m=100; //static variable
46
Types of Variables- Example
class A {
static int m=100; //static variable
void method()
{
int n=90; //local variable
}
public static void main(String args[])
{
int data=50; //instance variable
}
} //end of class
47
Java Variable Example: Add Two Numbers

class Simple
{
public static void main(String[] args)
{
int a=10;
int b=10;
int c=a+b;
[Link](c);
}
}
48
Operators in Java
• Operator in Java is a symbol that is used to perform operations

• There are many types of operators in Java :


• Unary Operator
• Arithmetic Operator
• Relational Operator
• Bitwise Operator
• Logical Operator
• Assignment Operator
• Ternary Operator

49
Java unary Operator
• The Java unary operators class Operator {
require only one operand.
public static void main(String args[])
• Unary operators are used to
perform various operations {
i.e.: int x=10;
• incrementing/decrementing [Link](x++);
a value by one //10 (11)
• negating an expression [Link](++x); //12
• inverting the value of a [Link](x--); //12 (11)
boolean [Link](--x); //10
}
} 50
Arithmetic Operator
• Java arithmetic operators Java defines the following arithmetic
are used to perform operators:
• addition
• subtraction
• multiplication
• Division
• modulus
• Increment
• decrement

• They act as basic


mathematical operations.
51
Increment and Decrement
• The increment operator adds 1 to its operand.
• The decrement operator subtracts 1 from its operand.
• Therefore,
X=X+1; is the same as X++;
and X=X-1; is the same as X--;

• Both the increment and decrement operators can either precede


(prefix) or follow (postfix) the operand.

• Example
X=X+1 is written as ++X; prefix form
or as X++; postfix form 52
Arithmetic Operator |Increment &
Decrement
class Operator { class Operator {
public static void main(String args[]) public static void main(String args[])
{
{
int a=20;
int b=10; int x=10;
[Link](a+b); //30 [Link](x++); //10 (11)
[Link](a-b); //10 [Link](++x); //12
[Link](a*b); [Link](x--); //12 (11)
//200 [Link](--x); //10
[Link](a/b); //2 }
[Link](a%b); //0
}
}
53
}
Relational Operator
• The relational operators determine the relationship that one operand
has to the other.
• Specifically, they determine equality and ordering.
• Relational operators are :

54
Bitwise Operator
• Java defines several bitwise
operators that can be
applied to the integer types:
• long, int, short, char, byte.

• These operators act upon


the individual bits of their
operands.

• They are summarized in the


following table :

55
Logical Operator
• Logical refers to the ways in which true
and false values can be connected
together.

• The logical operators, &, |, ^, and !,


support the basic logical operations AND,
OR, XOR, and NOT, according to the
following truth table

56
Java AND Operator : Logical && and Bitwise &
• The logical && operator class Operator {
doesn't check the second public static void main(String args[])
condition if the first condition {
is false. int a=10;
int b=5;
• It checks the second
condition only if the first one int c=20;
is true. [Link](a<b&&a<c);
//false && true = false
• The bitwise & operator [Link](a<b&a<c);
always checks both
//false & true = false
conditions whether first
condition is true or false. }
} 57
Java OR Operator : Logical || and Bitwise |
• The logical || operator class Operator {
doesn't check the
public static void main(String args[]) {
second condition if the
first condition is true. int a=10;
int b=5;
• It checks the second int c=20;
condition only if the first [Link](a>b||a<c); //true || true = true
one is false.
[Link](a>b|a<c); //true | true = true
• The bitwise | operator [Link](a>b||a++<c);
//true || true = true
always checks both
conditions whether first [Link](a); //10 because second condition is not checked
condition is true or [Link](a>b|a++<c); //true | true = true
false. [Link](a); //11 because second condition is checked
}
58
}
Assignment Operator
• Java assignment operator is class Operator {
one of the most common
operators. public static void main(String args[])
{
int a=10;
• It is used to assign the
value on its right to the int b=20;
operand on its left. a+=4; //a=a+4 (a=10+4)
b-=4; //b=b-4 (b=20-4)
[Link](a);
[Link](b);
}
}
59
Assignment Operator Example
class Operator {
public static void main(String[] args){
int a=10;
a+=3;
[Link](a);
a-=4;
[Link](a);
a*=2;
[Link](a);
a/=2;
[Link](a);
} } 60
Control
Flow
Control Statements / Control Flow in Java

• A programming language uses control statements to cause the flow of


execution based on changes to the state of a program.

• Java compiler executes the code from top to bottom.

• The statements in the code are executed according to the order in


which they appear.

• Java provides statements that can be used to control the flow of Java
code/program. Such statements are called control flow statements.

61
Control
Flow
Control Statements

• Java’s program control statements are categorized:


• Selection/ Decision Making statements
• Iteration/ Loop statements
• Jump Statement

62
Control
Flow
Control Statements
• Selection statements
• It allows program to choose different paths of execution based upon
the outcome of an expression.

• Iteration statements
• It enable program execution to repeat one or more statements.
• These statements create/ form loops.

• Jump statements
• They allow program to execute in a nonlinear fashion.
• These statements transfer control to another part of your program.
63
Control
Flow
Control Statements
• Selection / Decision Making statements
• if statements
• switch statement

• Iteration / Loop statements


• do while loop
• while loop
• for loop

• Jump statements
• break statement
• continue statement
64
Control
Flow
Selection / Decision Making statements
• It allows program to choose different paths of execution based upon
the condition.
• It decides which statement to execute and when.
• It evaluates the Boolean expression (true and false).

• It controls program flow depending upon result of condition provided.

• Two types of Selection/decision-making statements-


• If statement
• Switch statement.

65
Control
Flow
If statement
• The "if" statement is used to evaluate a condition.

• Control of program is diverted depending upon the specific condition.

• The condition of If statement gives a Boolean value, either true or false.

• If statement uses the relational operator to check condition.

• There are four types of if-statements-


• Simple if statement
• if-else statement
• if-else-if ladder
• Nested if-statement
66
Control
Flow
Simple If statements
• It is the most basic statement among all control flow statements in
Java.
• It evaluates a condition which is a Boolean expression.
• If condition is true, then the statement is executed.
• If condition is false, then the statement is bypassed.
• It enables the program to enter a block of code if the expression
evaluates to true.
• Syntax of if statement is given below.
if(condition)
{
statement 1; //executes when condition is true
67
}
Control
Flow
If statements example
class Student {
public static void main(String[] args)
{
int x = 10;
int y = 12;
if(x+y > 20)
{
[Link]("x + y is greater than 20");
}
[Link]("x + y is Less than 20");
}
} 68
Control
Flow
If statements example
class Sample {
public static void main(String args[]) {
int x, y;
x = 10;
y = 20;
if(x < y)
[Link]("x is less than y");
x = x * 2;
if(x == y)
[Link]("x is equal to y");
x = x * 2;
if(x > y)
[Link]("x is greater than y");
}
} 69
Control
Flow
If-else statements
• The if-else statement is an extension to the if-statement.
• It uses another block of code, i.e., else block.
• The else block is executed if the condition of the if-block is evaluated
as false.
• It has two blocks of code
• If block
• Else block
• The if works like this:
• If the condition is true, then if block is executed.
• Otherwise, else block (if it exists) is executed
70
Control
Flow
If-else statements
• Syntax:
if(condition)
{
statement 1;
//executes when condition is true
}
else
{
statement 2;
//executes when condition is false
}

71
Control
Flow
If-else statements example
class Student {
public static void main(String[] args) {
int x = 10;
int y = 12;
if(x < y)
{
[Link]("x is less than y");
}
else
{
[Link]("x is greater than y");
}
}
} 72
Control
Flow
If-else statements example
class Student {
public static void main(String[] args) {
int x = 10;
int y = 12;
if(x+y < 10)
{
[Link]("x + y is less than 10");
}
else
{
[Link]("x + y is greater than 20");
}
}
} 73
Control
Flow
if-else-if ladder / statements
• The if-else-if statement contains the if-statement followed by multiple
else-if statements.
• It is the chain of if-else statements.
• It creates a decision tree where the program may enter in the block of
code where the condition is true.
• We can also define an else statement at the end of the chain.

74
Control
Flow
if-else-if statements
Syntax of if-else-if statement is
if(condition 1)
{
statement 1; //executes when condition 1 is true
}
else if(condition 2)
{
statement 2; //executes when condition 2 is true
}
else
{
statement 3;
//executes when all the conditions are false
}
75
Control
Flow
if-else-if statements
• The if statements are executed from the top down.
• One of the conditions controlling the if is true, the statement associated
with that if is executed and the rest of the ladder is bypassed.
• If none of the conditions is true, then the final else statement will be
executed.
• The final else acts as a default condition.
• If all other conditional tests fail, then the last else statement is performed.
• If there is no final else and all other conditions are false, then no action
will take place.
76
Control
Flow
if-else-if statements

77
Control
Flow
if-else-if statements example

78
Control
Flow
Nested-if statements
• In nested if-statements, the if statement can contain a if or
if-else statement inside another if or else-if statement.
• Syntax of nested if statement

79
Control
Flow
Nested-if statements
public class NestedIf {
public static void main(String[] args)
{
int age=20;
int weight=80;
if(age>=18) {
if(weight>50) {
[Link]("You are eligible to donate blood");
}
}
}
}
80
Control
Flow
Nested-if statements example
class NestedIf {
public static void main(String[] args)
{
int age=25;
int weight=48;
if(age>=18) {
if(weight>50) {
[Link]("You are eligible to donate blood");
}
else {
[Link]("You are not eligible to donate blood");
}
}
else{
[Link]("Age must be greater than 18");
}
}
} 81
Control
Flow
Switch statements
• switch statement executes one statement from multiple conditions.
• The switch statement is Java’s multiway branch statement.

• It dispatches execution to different parts of code based on the value of an


expression.
• The switch statement works with byte, short, int, long, enum types, String.

• The switch statement contains multiple blocks of code called cases.


• A single case is executed based on the variable which is being switched.

• The switch statement is easier to use instead of if-else-if statements.

82
Control
Flow
Switch statements
switch (expression)
{
case value1:
statement1;
break;
case value2:
statement2;
break;
.
case valueN:
statementN;
break;
default:
default statement;
} 83
Control
Flow
Switch statements

84
Control
Flow
Switch statements
• Points to be noted about switch statement:
• There can be one or N number of case values for a switch expression.
• Cases cannot be duplicate. The case values must be unique.
• Default statement is executed when any of the case doesn't match
the value of expression. It is optional.
• Break statement terminates the switch block when the condition is
satisfied.
It is optional, If a break statement is not found, next case is executed.
• The case expression will be of the same type as the variable.
However, it will also be a constant value.
85
Control
Flow
Switch statements example

86
Control
Flow
Switch statements example

87
Control
Flow
Switch statements example

88
Control
Flow
Iteration / Loop statements
• In programming,
• Sometimes we need to execute the block of code repeatedly while some
condition evaluates to true.
• Need to execute one or more statements repeatedly.
• Loop statements are used to execute the set of instructions in a
repeated order until a termination condition is satisfied.
• The execution of set of instructions depends upon a particular condition.
• In Java, three types of loops that execute similarly.
• for loop
• while loop
• do-while loop
• There are differences in their syntax and condition checking time. 89
For Loop
• In Java, for loop is similar to C and C++.
• We use the for loop only when we exactly know the number of times,
we want to execute the block of code.
• It enables us to
• initialize the loop variable,
• check the condition, and
• increment/decrement in a single line of code.
• Syntax:
for(initialization; condition; increment/decrement)
{ //block of statements
}
90
Control
Flow
For Loop
• Initialization portion
• It sets a loop control variable to an initial value.

• Condition
• It is a Boolean expression that tests the loop control variable.
• If the condition is true, the for loop continues to iterate/repeat.
• If it is false, the loop terminates.

• Iteration expression
• It increments/decrements control variable
• It determines how the loop control variable is changed each time the
loop iterates.
91
Control
Flow
For Loop flow chart and example
class For {
public static void main(String args[])
{
int n;
for(n=0; n<10; n++)
{
[Link](n);
}
}
}

92
Control For Loop example
Flow Program to print 0 to 9 numbers using for loop.

class For { Output-


public static void main(String args[]) 0
{ 1
int n; 2
for(n=0; n<10; n++) 3
{ 4
[Link](n); 5
} 6
} 7
} 8
9
93
Control
Flow
For Loop example
class For { class For {
public static void main(String args[]) public static void main(String args[])
{ {
for(int n=0; n<10; n++) for(int n=10; n>0; n--)
{ {
[Link](“Welcome”);
[Link](“Welcome”,+n);
}
}
}
}
}
}

94
Control For Loop example
Flow Program to print “Welcome” for ten times using for loop.
class For { class For {
Output-
public static void main(String args[]) public static void main(String args[])
Welcome10
{ {
Welcome9
for(int n=0; n<10; n++) for(int n=10; n>0; n--)
Welcome8
{ {
Welcome7
[Link](“Welcome”); [Link](“Welcome”,+n);
Welcome6
} }
Welcome5
} } Welcome4
} } Welcome3
Welcome2
Welcome1

95
Control
Flow
For Loop example
class For { class For {
public static void main(String args[]) public static void main(String args[])
{ {
for(int n=1; n<=10; n++) for(int n=10; n>0; n--)
{ {
[Link](n+ “ ”); [Link](n+ “ ”);
} }
} }
} }

96
Control For Loop example
Flow Java program to display 1 to 10 numbers in ascending and descending order.

class For { class For {


public static void main(String args[]) public static void main(String args[])
{ {
for(int n=1; n<=10; n++) for(int n=10; n>0; n--)
{ {
[Link](n+ “ ”); [Link](n+ “ ”);
} }
} }
} }

Output- Output-
1 2 3 4 5 6 7 8 9 10 10 9 8 7 6 5 4 3 2 1 97
Control
Flow
Nested For Loop
• A for loop inside the public class NestedFor {
another loop, it is public static void main(String[] args)
known as nested for {
loop. //loop of i
for(int i=1;i<=3;i++)
{
• The inner loop //loop of j
executes completely for(int j=1;j<=3;j++)
whenever outer loop {
executes. [Link](i+" "+j);
} //end of i
} //end of j
}
} 98
Control
Flow
Nested For Loop
Output- public class NestedFor {
11 public static void main(String[] args)
{
12 //loop of i
13 for(int i=1;i<=3;i++)
21 {
//loop of j
22 for(int j=1;j<=3;j++)
23 {
[Link](i+" "+j);
31 } //end of i
32 } //end of j
33 }
} 99
Control
Flow
Nested For Loop Example

10
0
Control Nested For Loop Example
Flow Java program to display star in triangular format.

Output-
*
**
***
****
*****

10
1
Control
Flow
Infinite For Loop Example
• If you use two semicolons ;; public class For {
in the for loop, it will be public static void main(String[] args)
infinitive for loop.
{ //Using no condition in for loop
• Syntax:
for(;;)
for(;;)
{
{
[Link]("infinitive loop");
//code to be executed }
}
} }
• Need to press ctrl+c to exit
from the program. 10
2
Control
Flow
Infinite For Loop Example
public class For1{
public static void main(String[] args) {
int x=1;
for(;;) {
[Link]("infinitive loop“ +x);
x++;
if(x>9)
break;
}
} }
10
3
Control
Flow
Infinite For Loop Example
Output- public class For1{
infinitive loop1 public static void main(String[] args) {
infinitive loop2 int x=1;
infinitive loop3 for(;;) {
infinitive loop4 [Link]("infinitive loop“ +x);
infinitive loop5 x++;
infinitive loop6 if(x>9)
infinitive loop7 break;
infinitive loop8 }
infinitive loop9 } }
10
4
Control
Flow
While Loop
• While loop is used to iterate number of statements multiple times
• If we don't know the number of iterations in advance, it is recommended
to use a while loop.
• The initialization and increment/decrement doesn't take place inside the
loop statement in while loop.
• It is also known as the entry-controlled loop
• The condition is checked at the start of the loop.
• If the condition is true, then the loop body will be executed
• otherwise, the statements after the loop will be executed.

10
5
Control
Flow
While Loop syntax and flow chart
• The syntax of the while loop:
while(condition)
{
//looping statements
}

• The condition is Boolean expression.


• The body of the loop will be
executed as long as the condition is
true.
10
6
Control
Flow
While Loop example
class While {
public static void main(String args[])
{
int n = 5;
while(n > 0)
{
[Link](“Welcome" + n);
n--;
}
}
} 10
7
Control
Flow
While Loop example
class While { Output-
public static void main(String args[]) Welcome5
{ Welcome4
int n = 5; Welcome3
while(n > 0) Welcome2
{ Welcome1
[Link](“Welcome" + n);
n--;
}
}
} 10
8
Control
Flow
While Loop example
public class While1 {
public static void main(String[] args) {
int i = 0;
[Link]("Printing the list of even numbers ");
while(i<=10)
{
[Link](i);
i = i + 2;
}
}
} 10
9
Control
Flow
While Loop example
public class While1 { Output-
public static void main(String[] args) { Printing list of
int i = 0; even numbers
[Link]("Printing the list of even numbers "); 0
while(i<=10) 2
{ 4
[Link](i); 6
i = i + 2; 8
} 10
}
} 11
0
Control
Flow
Infinite While Loop
• If you pass true in the while public class While3 {
loop, it will be infinitive while
loop. public static void main(String[] args)
{ // passing true to the condition
• Syntax: while(true)
while(true) {
{ [Link]("infinitive while loop");
//code to be executed
} }
}
• Enter Ctrl + C command to
terminate the infinite loop. }
11
1
Control
Flow
Do-while Loop
• The do-while loop is used to iterate a part of the program repeatedly,
until the specified condition is true.
• If the number of iteration is not fixed and you must have to execute
the loop at least once, we use a do-while loop.
• The do-while loop is called an exit control loop.
• The do-while check the condition at the end of loop body.
• The do-while first execute loop body and then checks condition.
• The do-while loop is executed at least once because condition is
checked after loop body.
11
2
Control
Flow
Do-while Loop syntax and flowchart

• Syntax:
do
{
//code/loop body
// update statement

}while (condition);

11
3
Control
Flow
Do-while Loop example
class Dowhile{ class Dowhile1{
public static void main(String[] args) public static void main(String[] args)
{ {
int i=1; int i = 0;
do{
[Link](i); [Link](“List of even numbers");
i++;
do {
}while(i<=5);
[Link](i);
}
i = i + 2;
}
}while(i<=14);
114
}
Control
Flow
Infinitive Do-while Loop
• If you pass true in the do- class DoWhile2 {
while loop, it will be infinitive public static void main(String[] args)
do-while loop.
{
do
• Syntax:
{
do{
[Link]("infinitive do
//code to be executed
while loop");
}while(true);
}while(true);
}
}
11
5
Control
Flow

11
6
Control
Flow
Jump Statements
• Jump statements
• They allow program to execute in a nonlinear fashion.

• Jump statements are used to transfer the execution control of the


program to the specific statements/other parts of program.

• Two types of jump statements


• break
• continue.

11
7
Control
Flow
Break Statements
• Break statement is used to-
• Break the current flow of the program and transfer the control to the
next statement outside a loop or switch statement.
• It breaks the loop/current flow if condition is true.
• It breaks only the inner loop in the case of the nested loop.

• It can only be written inside the loop or switch statement.


• The break statement cannot be used independently in the Java
program.

• We can use Java break statement in all types of loops.


11
8
Control
Flow
Break Statements syntax and flowchart

• Syntax:
jump-statement; //Condition
break;

11
9
Control
Flow
Break Statements Example
public class Break {
public static void main(String[] args) {
int number=20;
switch(number){
case 10: [Link]("10");
break;
case 20: [Link]("20");
break;
case 30: [Link]("30");
break;
default:[Link]("Not in Series");
}
}
12
} 0
Control
Flow
Break Statement with Loop
class Break1 {
public static void main(String[] args)
{
for(int i=1;i<=10;i++)
{
if(i==5)
{
//breaking the loop
break;
}
[Link](“Welcome”+i);
}
}
}
12
1
Control
Flow
Break Statement with Loop
class Break1 {
public static void main(String[] args) Output-
{ Welcome1
for(int i=1;i<=10;i++) Welcome2
{ Welcome3
if(i==5) Welcome4
{
//breaking the loop
break;
}
[Link](“Welcome”+i);
}
}
}
12
2
Control
Flow
Break Statements Example
public class Break3 {
public static void main(String[] args) {
int i=1;
do
{
if(i==5){
i++;
break; //it will break the loop
}
[Link](i);
i++;
}while(i<=10);
}
} 12
3
Control
Flow
Break Statements Example
public class Break3 {
public static void main(String[] args) {
Output-
int i=1;
1
do
2
{
3
if(i==5){
4
i++;
break; //it will break the loop
}
[Link](i);
i++;
}while(i<=10);
}
} 12
4
Control
Flow
Break Statements Example
class Break2 {
public static void main(String[] args) {
//outer loop
for(int i=1;i<=3;i++)
{ //inner loop
for(int j=1;j<=3;j++)
{
if(i==2 && j==2) {
break;
}
[Link](i+" "+j);
}
}
} }
12
5
Control
Flow
Break Statements Example
class Break2 {
public static void main(String[] args) { Output-
//outer loop 11
for(int i=1;i<=3;i++) 12
{ 13
//inner loop 21
for(int j=1;j<=3;j++) 31
{ 32
if(i==2&&j==2){ 33
break;
}
[Link](i+" "+j);
}
}
12
} } 6
Control
Flow
Continue Statements

• Continue statement doesn't break the loop.


• It skips the specific part of the loop and jumps to the next iteration of
the loop immediately.

• It can be used with for loop or while loop.


• Continue statement is used to continue the loop.
• It continues the current flow of the program and skips the remaining
code at the specified condition.

• In case of an inner loop, it continues the inner loop only.


12
7
Control
Flow
Continue Statements Example
class Continue {
public static void main(String args[])
{
for(int i=10;i>=1;i--)
{
if(i>5)
{
continue;
}
[Link](i+" ");
}
} } 12
8
Control
Flow
Continue Statements Example
class Continue {
Output-
public static void main(String args[])
5
{
4
for(int i=10;i>=1;i--)
3
{ 2
if(i>5) 1
{
continue;
}
[Link](i+" ");
}
} } 12
9
Control
Flow
Continue Statements Example
class Continue1 {
public static void main(String[] args)
{
for(int i=1;i<=3;i++)
{
for(int j=1;j<=3;j++)
{
if(i==2&&j==2)
{
continue;
}
[Link](i+" "+j);
}
}
}
}
13
0
Control
Flow
Continue Statements Example
class Continue1 {
public static void main(String[] args)
Output-
{ 11
for(int i=1;i<=3;i++) 12
{ 13
for(int j=1;j<=3;j++) 21
{
if(i==2&&j==2)
23
{ 31
continue; 32
} 33
[Link](i+" "+j);
}
}
}
}
13
1
Control
Flow
Continue Statements Example
class Continue { class Continue1 {
public static void main(String[] args)
public static void main(String[] args)
{
{ for(int i=1;i<=3;i++)
for(int i = 0; i<= 2; i++) { {
for (int j = i; j<=5; j++) { for(int j=1;j<=3;j++)
{
if(j == 4)
if(i==2&&j==2)
{ {
continue; continue;
} }
[Link](j);
[Link](i+" "+j);
}
}
}
} }
} } }

13
2
Arrays Arrays
• An array is a group of like-typed variables.
• An array is a collection of similar type of elements.
• The elements of an array are stored in a contiguous memory location.
• It is a data structure where we store similar elements.
• We can store only a fixed set of elements in a Java array.
• Array in Java is index-based.
• A specific element in an array is accessed by its index.
• The variables in array are ordered & each has an index beginning from 0.
• Arrays are objects in Java, we can find their length using the object
property length. 13
3
Arrays Arrays
• 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.

13
4
Arrays Types of Arrays

• There are two types of array.


• Single/One Dimensional Array
• Multidimensional Array
• Advantages
• Code Optimization:
• It makes the code optimized, we can retrieve or sort the data efficiently.

• Random access:
• We can get any data located at an index position.

13
5
Arrays Single/One-Dimensional Array
• A one-dimensional array is a list of like-typed variables.
• To create an array, first must create an array variable of the desired type.
• Declaration
• The general form of a one-dimensional array-
type var-name[ ];
OR
type[] var_name;
• Example- int month[];
OR
int[] month;
13
6
Arrays Single/One-Dimensional Arrays
• Instantiation of Array
• To allocate memory for arrays as contiguous memory location.
• new keyword is used to allocate memory for array.
• Syntax:
array-var=new type [size];
• Example: number=new int[5];
number[0] 🡨 Instantiation
number[1]
number[2]
number[3]
number[4] 13
7
Arrays Single/One-Dimensional Arrays
• Initialization of Array
• Assign values for array elements.
• First allocate memory for arrays using new keyword.
• Example: number=new int[5];
int number[ ]={10,20,30,40,50};

number[0]=10; 🡨 Initialization
number[1]=20;
number[2]=30;
number[3]=40;
number[4]=50; 13
8
Arrays Array Example
class Array{
public static void main(String args[]
class Array1{
) public static void main(String args[])
{ {
int a[]=new int[5];
a[0]=10; int a[]={10,20,30,40,50};
a[1]=20; for(int i=0;i<[Link];i++)
a[2]=70;
a[3]=40; [Link](a[i]);
a[4]=50; }
for(int i=0;i<[Link];i++) }
[Link](a[i]);
} 13

} 9
Arrays Array Example
ArrayIndexOutOfBoundsException

class ArrayException{
public static void main(String args[])
{
int arr[]={50,60,70,80};
for(int i=0;i<=[Link];i++)
{
[Link](arr[i]);
}
}
}
14
0
Arrays Array Example
public class Array3 {
public static void main (String[] args)
{
Student[] arr; // declares an Array of integers.
arr = new Student[5]; // allocating memory for 5 objects of type Student.
arr[0] = new Student(1,“Ajay"); // initialize the first elements of the array
arr[1] = new Student(2,“Vaibhav"); // initialize the second elements of the array
arr[2] = new Student(3,“Shital");
arr[3] = new Student(4,“Mahesh");
arr[4] = new Student(5,“Mohit");
// accessing the elements of the specified array
for (int i = 0; i < [Link]; i++)
[Link]("Element at " + i + " : " +arr[i].roll_no +" "+ arr[i].name);
}
}
14
1
Arrays Multi-Dimensional Arrays
• It is used when data is stored in row and column based index
• It is also known as matrix form.
• In Java, multidimensional arrays are actually arrays of arrays.
• These look and act like regular multidimensional arrays.
• To declare a multidimensional array variable, specify each additional
index using another set of square brackets.
• Declaration of two dimensional array variable :
int two[][] = new int[4][5]; //4 rows and 5 columns

14
2
Arrays Multi-Dimensional Arrays

14
3
Arrays Multi-Dimensional Arrays
• How to instantiate Multidimensional Array in Java.
int[][] arr=new int[3][3]; //3 rows and 3 columns
• arr[0][0]=1;
• arr[0][1]=2;
• arr[0][2]=3;
• arr[1][0]=4;
• arr[1][1]=5;
• arr[1][2]=6;
• arr[2][0]=7;
• arr[2][1]=8;
• arr[2][2]=9; 14
4
Arrays
Multi-Dimensional Arrays Example
Program to display elements of matrix using Multidimensional array.
class Array3{
public static void main(String args[])
{
//declaring and initializing 2D array
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
//printing 2D array
for(int i=0;i<3;i++){
for(int j=0;j<3;j++)
{
[Link](arr[i][j]+" ");
}
[Link]();
}
} } 14
5
Arrays Matrix Addition using Array

14
6
Multi-Dimensional Arrays Example
Arrays Program to perform matrix addition using multidimensional
array.
class Aarray5{
public static void main(String args[]){
int a[][]={{1,3,4},{3,4,5}}; //creating two matrices
int b[][]={{1,3,4},{3,4,5}};
int c[][]=new int[2][3]; //creating another matrix to store the sum of two matrices
//adding and printing addition of 2 matrices
for(int i=0;i<2;i++) {
for(int j=0;j<3;j++) {
c[i][j]=a[i][j]+b[i][j];
[Link]("\t"+c[i][j]);
}
[Link]();//new line
} } } 14
7
Arrays Jagged Array in Java

• If we are creating odd number of columns in a 2D array, it is


known as a Jagged array.

• It is an array of arrays with different number of columns.


• It is also called as Irregular Multidimensional Arrays.

14
8
Arrays Jagged Array in Java

14
9
Input
Output
Input and Output
• Input
• It represents data given to a program.
• Input is accepted from keyboard.

• Output
• It represents data displayed as a result of a program.
• Output is displayed on the screen.
• print() method is used to display output on the screen.
• It uses two statements:
• [Link]()
• [Link]()
15
0
Input
Output
Accepting Input from keyboard
• A stream is required to accept input from keyboard.
• A stream is a sequence of data.
• It represents flow of data from one place to another place.
• In Java, a stream is composed of bytes.
• It is like a stream of water that continues to flow.

• There are two kinds of Streams −


1. InputStream −
It is used to receive or read data from a source, one item at a time.
2. OutputStream −
It is used to send or write data to a destination, one item at a time.
15
1
Input
Output
Standard Streams
In Java, 3 streams are created and used with the console.
1) [Link]: Standard input stream.
- Used to feed the input to user's program,
- It represents standard input device, i.e. keyboard
2) [Link]: Standard output stream.
- Used to output/display the data
- It is used to display normal messages and results.
- It represents standard output device, i.e. computer screen
3) [Link]: Standard error stream.
- Used to display error message produced by the user's program
- Standard device is computer screen.
15
2
Input Reading Input from keyboard with
Output
Scanner class
• Scanner is a class of [Link] package.
• It is used to read input of the primitive types from keyboard or text file.

• Scanner class receives input and it breaks into pieces, called token.
• Token/input is received by creating an object of Scanner class with
different methods.

• To read input from keyboard, Scanner class is used by creating object:


Scanner sc=new Scanner([Link]);
• Example- int number=[Link]();
15
3
Input
Output Scanner class and methods to read input
Type Method Meaning
String next() To read a string value
Line nextLine() To read a string till end of line
Char [Link](0) To read a single value as character.
Byte nextByte() To read byte value.
Int nextInt() To read integer value
Float NextFloat() To read float value
Long nextLong() To read long value.
Double nextDouble() To read double value.
15
4
Input
Output Write a java program to read input from keyboard using Scanner class .

15
5
End of Unit-
I

15
6
Java Programming

Unit-1
Objects and Classes
Contents-
• Object-Oriented Programming Concepts,
• Declaring Classes,
• Declaring Member Variables,
• Defining Methods,
• Constructor,
• Passing Information to a Method or a Constructor,
• Creating and using objects,
• Controlling Access to Class Members,
• Static Fields and Methods,
• this keyword.

2
OOPs
Concept Object-Oriented Programming (OOP) Concept
• Object-Oriented Programming Concepts
• OOP is a paradigm that provides many concepts.

• The programming paradigm where everything is represented as an


object is known as object-oriented programming language.

• Simula is considered the first object-oriented programming language.

• Smalltalk is considered the first truly object-oriented programming


language.

• The popular object-oriented languages are Java, C#, PHP, Python, C++
etc.
3
OOPs
Concept OOPs: Object-Oriented Programming System
• Object means a real-world entity.

• Object-Oriented Programming is a methodology or paradigm to design


a program using classes and objects.

• It simplifies software development and maintenance by providing some


concepts:
• Object
• Class
• Abstraction
• Encapsulation
• Inheritance
• Polymorphism 4
OOPs
Concept Object-Oriented Programming (OOP) Concept

5
OOPs
Concept Object
• Any entity that has state and behavior is known as an object.
• For example, a chair, pen, table, keyboard, bike, etc.
• Object is a basic unit of Object Oriented Programming.
• Object represents a real-world entity.

• An object is a runtime entity.


• It can be physical or logical.

• Characteristics of an object are:


• State , Behavior, Identity, Method
6
OOPs
Concept Class
• Class Definition:
• Collection of objects is called class.
• A class is a group of objects which have common properties.
• It is defined as template or blueprint from which objects are created.
• It is a logical entity. It can't be physical.
• A class in Java can contain:
•Variables/data members
•Methods
•Constructors

7
OOPs
Concept Abstraction
• Hiding internal details and showing functionality in simple terms is known
as Abstraction.
• It is a process of identifying only the required characteristics of an object
ignoring the irrelevant details.
• The essential details are displayed to the user and non-essentials units
are not displayed to the user.
• Example- phone call, Car
• In java, abstraction is achieved by interfaces and abstract classes.
• Interfaces are used to achieve full (100%) abstraction.
• Abstract classes are used to achieve partial abstraction.
8
OOPs
Concept Encapsulation
• Binding (or wrapping) code and data together into a single unit are known as
encapsulation.
• It is a protective shield that prevents the data from being accessed by the code
outside this shield.
• In encapsulation,
• The variables of a class is hidden from any other class and accessed only
through class method, so also known as data-hiding.
• It keeps both data and code safe.
• It is used for access restrictions to a class members and methods.
• Encapsulation can be achieved with access modifiers-
• public, private and protected.
9
OOPs
Concept Inheritance
• When one object acquires all the properties and behaviors of a parent object, it is
known as inheritance.
• It is the mechanism in java by which one class is allowed to inherit the
features(variables and methods) of another class.
• Super Class:
• The class whose features are inherited is known as superclass.
• Also known as a base class or a parent class.
• Sub Class:
• The class that inherits the features of other class is known as a subclass.
• Also known as a derived class, extended class, or child class.
• It provides code reusability.
• The extends keyword is used to implement inheritance in Java.
10
OOPs
Concept Polymorphism
•The word "poly" means many and "morphs" means forms.
•Polymorphism means "many forms”.
•If one task is performed in different ways, it is known as polymorphism.
•It is a mechanism where object behaves differently in different situations.
•Polymorphism allows us to perform a single action in different ways.
•In Java polymorphism is mainly divided into two types:
• Compile-time Polymorphism
• Runtime Polymorphism
•In Java, method overloading and method overriding are used to achieve
polymorphism.
11
Object Object
• Any entity that has state and behavior is known as an object.
• For example, a chair, pen, table, keyboard, bike, etc.
• Object is a basic unit of Object Oriented Programming.
• Object represents the real life entities.
• It can be physical or logical.

• An Object can be defined as an instance of a class.


• Java program creates many objects, which interact by invoking methods.

• An object contains an address and takes up some space in memory.


• It communicates without knowing details of each other's data or code.
12
Object Characteristics of Object
• An object consists of:
• State :
• It is represented by attributes of an object.
• It also reflects the properties of an object.

• Behavior :
• It is represented by methods of an object.
• It reflects response of an object with other objects.

• Identity :
• It gives a unique name to an object and enables one
object to interact with other objects.

• Method:
• A method is a collection of statements that perform
some specific task and return result to the caller. 13
Object Object Definition and Example
• An object is a real-world entity.
• An object is a runtime entity.
• The object is an entity which has state and behavior.
• The object is an instance of a class.
• Objects correspond to things found in the real world.
• Graphics program may have objects such as “circle”, “square”, “menu”.
• An online shopping system have objects such as “shopping cart”, “customer”, and
“product”.

• Example of an object: dog

14
Class Class
• Definition:
• Collection of objects is called class.
• A class is a group of objects which have common properties.
• It is defined as template or blueprint from which objects are created.
• It is a logical entity.
• It can't be physical.
• Class doesn't consume any space
• It represents the set of properties or methods that are common to
all objects of one type 15
Class Class
• The values of those attributes, i.e. the state are unique for each object.
• A single class may have any number of instances.
• Example

16
Class Class components
• A class in Java can contain:
• Fields/Variables/data members
• Methods
• Constructors
• Blocks
• Nested class and interface
• Constructors are used for initializing new objects.
• Fields are variables that provides the state of the class and its objects.
• Methods are used to implement the behavior of the class and its
objects.
17
Class Declaring Classes
Class_name
class class_name {
class structure
type instance_variable1;
variable/attributes;
int number; type instance_variable2;
float marks; type method_name1(parameter-
method() list)
class declaration add(); {
class class_name // body of method
{ }
type variable; type method_name2(parameter-
type method1(); list)
type method2(parameter-list); {
} // body of method 18
Class Declaring Classes
• Class declarations can include following components
• Modifiers: A class can be public or has default access.
• class keyword: class keyword is used to create a class.
• Class name: The name should begin with an initial letter.
• Superclass(if any): The name of the class’s parent (superclass)
preceded by the keyword extends.
• Interfaces(if any): A comma-separated list of interfaces
implemented by the class preceded by the
keyword implements.
• Body: The class body surrounded by braces, { }.
19
Class Object Creation for a class

• When an object of a class is created, the class is said to be instantiated.


• All the instances share the attributes and the behavior of the class.

• Syntax to create object for a class


class_name object_name=new class_name();

• Create an object for class Student


Student s1=new Student();
Student s2=new Student():
20
Class Class and object Example
class Student {
int id; //field or data member or instance variable
String name;
//creating main method inside the Student class
public static void main(String args[])
{
//Creating an object or instance
Student s1=new Student(); //creating an object of Student
//Printing values of the object
[Link]([Link]);
//accessing member through reference variable
[Link]([Link]);
}
}
21
Class Class and object Example
class Student
{
int id;
String name;
}
//Creating another class TestStudent which contains the main method
class TestStudent
{
public static void main(String args[])
{
Student s1=new Student();
[Link]([Link]);
[Link]([Link]);
}
} 22
Class Class and object Example
class Student //Initializing objects
{ [Link]=101;
int id; [Link]=“Mahesh";
String name; [Link]=102;
} [Link]="Amit";
class TestStudent [Link]([Link]+" "+[Link]);
{
public static void main(String args[]) [Link]([Link]+" "+[Link]);
{
Student s1=new Student(); }
Student s2=new Student(); }

23
Method Method: Definition
• Classes usually consist of two things:
• Instance variables and
• Methods.
• A method is a way to perform some task.
• The method in Java is a collection of instructions that performs a specific
task.
• A method is
• a block of code or
• collection of statements/ instructions or
• a set of code grouped together to perform a certain task or operation.
24
Method Method : Uses

• It is used to achieve the reusability of code.

• We write a method once and use it many times.

• We do not require to write code again and again.

• It provides the easy modification and readability of code.

• The method is executed only when we call or invoke it.

• The most important method in Java is the main() method.

25
Method Method Declaration
• This is the general form of a method declaration:
type name(parameter-list)
{ // body of method
}

26
Method Method Declaration
• Return Type:
• Return type is a data type that the method returns.
• If the method does not return anything, then use void keyword.

• Method Name:
• It is a unique name that is used to define the name of a method.

• Parameter List:
• It is the list of parameters separated by a comma.
• It contains the data type and variable name.
• If the method has no parameter, left the parentheses blank.

• Method Body:
• It contains all the actions to be performed enclosed within the curly braces.
27
Method Method sample example
• Example
int add(int a, int b)
{ // method body;
}

• Example
void add()
{ // method body;
}

28
Method Method Types
• There are two types of methods in Java:
• Predefined Method

• User-defined Method

29
Predefined Method
• Predefined Method
• The method that is already defined in the Java class libraries is known as
predefined methods.
• It is also known as the standard library method or built-in method.
• We can directly use these methods just by calling them in the program at
any point.
• Some pre-defined methods are
• length(), equals(), compareTo(), sqrt(), etc.

• When we call any of the predefined methods in our program, a series of


codes related runs in the background that is already stored in the library.
30
Method Types
public class Demo
{
public static void main(String[] args)
{
// using the max() method of Math class
[Link]("The maximum number is: " + [Link](9,7));
}
}

31
User-defined Method
• The method written by the user or programmer is known as a user-
defined method.
• These methods are modified according to the requirement.
• Example
int EvenOdd(int num)
{ //method body
if(num%2==0)
[Link](num+" is even");
else
[Link](num+" is odd");
} 32
User-defined Method
import [Link];
public class EvenOdd
{
public static void main (String args[])
{
Scanner scan=new Scanner([Link]);
[Link]("Enter the number: ");
//reading value from the user
int num=[Link]();
//method calling
findEvenOdd(num);
} 33
Method Example
Program to display volume of Box using method.
class Box {
double width;
double height;
double depth;
void volume() // display volume of a box
{
[Link]("Volume is ");
[Link](width * height * depth);
}
}
34
Method Example
class BoxVolume {
public static void main(String args[]) {
Box obj1 = new Box();
Box obj2 = new Box(); // assign values to mybox1's instance variables
[Link] = 10;
[Link] = 20;
[Link] = 15;
[Link] = 3; /* assign different values to mybox2's instance variables */
[Link] = 6;
[Link] = 9;
[Link](); // display volume of first box
[Link](); // display volume of second box
} }
35
Adding a Method That Takes
Parameters
int square()
{
return 10 * 10;
}

int square(int i)
{
return i * i;
}

36
Method Overloading
• If a class has multiple methods having same name but different in
parameters, it is known as Method Overloading.
• If we have to perform only one operation, having same name of the
methods increases the readability of the program.
• Advantage of method overloading
• Method overloading increases the readability of the program.
• Different ways to overload the method
• There are two ways to overload the method in java
• By changing number of arguments
• By changing the data type
37
Method Overloading Example
int area(int r)
{
return 3.14 * r * r;
}

int area(int h, int l)


{
return h * l;
}

38
Method Overloading Example
class OverloadDemo { class Overload {
void test() {
[Link]("No parameters"); public static void main(String args[]) {
} OverloadDemo ob = new OverloadDemo();
// Overload test for one integer parameter.
void test(int a) { double result;
[Link]("a: " + a); [Link]();
}
// Overload test for two integer parameters. [Link](10);
void test(int a, int b) { [Link](10, 20);
[Link]("a and b: " + a + " " + b);
}
result = [Link](123.25);
// Overload test for a double parameter [Link]("Result of [Link](123.25):
double test(double a) { " + result);
[Link]("double a: " + a);
return a*a; }
}
} }
39
Method Overloading Example- Result
• This program generates the following output:
No parameters
a: 10
a and b: 10 20
double a: 123.25
Result of [Link](123.25): 15190.5625

40
Constructor
• In Java, a constructor is a block of codes similar to the method.
• It is called when an instance of the class is created.

• At the time of calling constructor, memory for the object is allocated in


the memory.
• It is a special type of method which is used to initialize the object.

• Every time an object is created using the new() keyword, at least one
constructor is called.

• It calls a default constructor if there is no constructor available in the class.


• In such case, Java compiler provides a default constructor by default.
41
Constructor
• It is called constructor because it constructs the values at the time of
object creation.
• It is not necessary to write a constructor for a class.

• It is because java compiler creates a default constructor if your class


doesn't have any.

• Rules for creating Java constructor


• There are two rules defined for the constructor.
• Constructor name must be the same as its class name
• A Constructor must have no explicit return type
• A Java constructor cannot be abstract, static, final.
42
Constructor Types
• There are two types of constructors in Java:
• Default constructor (no-arg constructor)
• Parameterized constructor

• Java Default Constructor


• A constructor is called "Default Constructor" when it doesn't have any
parameter.
• Syntax of default constructor:
<class_name>(){}

• The default constructor is used to provide the default values to the object
like 0, null, etc., depending on the type.
43
Constructor Types
• Java Parameterized Constructor
• A constructor which has a specific number of parameters is called a
parameterized constructor.
• The parameterized constructor is used to provide different values to
distinct objects.
• However, you can provide the same values also.
• Example
Student(int i,String n){
id = i;
name = n;
}
44
Constructor Example
class Bike1{ class Student {
//creating a default constructor int id;
Bike1() String name;
{ void display() {
[Link]("Bike is created"); [Link](id+" "+name);
} }
public static void main(String args[]) public static void main(String args[]) {
{ Student s1=new Student();
//calling a default constructor Student s2=new Student();
Bike1 b=new Bike1();
} //displaying values of the object
} [Link]();
[Link]();
}
} 45
Parameterized Constructor Example
class Student4{
int id;
public static void main(String args[])
String name;
{
//creating a parameterized constructor
//creating objects and passing values
Student4(int i,String n)
{
Student4 s1 = new Student4(111,"Karan");
id = i;
Student4 s2 = new Student4(222,"Aryan");
name = n;
}
[Link]();
[Link]();
void display()
}
{
}
[Link](id+" "+name);
}

46
Constructor Overloading in Java
• Constructor overloading in Java is a technique of having more than one
constructor with different parameter lists.

• They are arranged in a way that each constructor performs a different


task.

• They are differentiated by the compiler by the number of parameters in


the list and their types.

47
Constructor Overloading Example

48
49
Constructor Overloading Example-Result

• The output produced by this program is shown here:


• Volume of mybox1 is 3000.0
• Volume of mybox2 is -1.0
• Volume of mycube is 343.0

50
51
this keyword in Java
• In Java, this is a reference variable
that refers to the current object.

• Usage of Java this keyword


• this can be used to refer current class instance variable.
• this can be used to invoke current class method (implicitly)
• this() can be used to invoke current class constructor.
• this can be passed as an argument in the method call.
• this can be passed as argument in the constructor call.
• this can be used to return the current class instance from the method.
52
Program without this keyword
class Student{
class TestThis
int rollno;
String name; {
float fee; public static void main(String args[])
Student(int rollno,String name,float fee){ {
rollno=rollno; Student s1=new Student(111,“Ankit",5000f);
name=name;
Student s2=new Student(112,“Sumit",6000f);
fee=fee;
[Link]();
}
void display(){ [Link]();
[Link](rollno+" "+name+" "+fee); }
} } }
53
Program output
0 null 0.0
0 null 0.0

• Parameters (formal arguments/local veriables) and instance


variables are same.

• So, need to use this keyword to distinguish local variable and


instance variable.

54
Program with this keyword
class Student{
class TestThis
int rollno;
String name; {
float fee; public static void main(String args[])
Student(int rollno,String name,float fee){ {
[Link]=rollno; Student s1=new Student(111,“Ankit",5000f);
[Link]=name;
Student s2=new Student(112,“Sumit",6000f);
[Link]=fee;
[Link]();
}
void display(){ [Link]();
[Link](rollno+" "+name+" "+fee); }
} } }
55
Program without this keyword
class Student{
class TestThis
int rollno;
String name; {
float fee; public static void main(String args[])
Student(int r, String n, float f){ {
rollno=r; Student s1=new Student(111,“Ankit",5000f);
name=n;
Student s2=new Student(112,“Sumit",6000f);
fee=f;
[Link]();
}
void display(){ [Link]();
[Link](rollno+" "+name+" "+fee); }
} } }
56
static keyword in Java
• The static keyword in Java is used for memory management mainly.
• We can apply static keyword with variables, methods, blocks and nested
classes.
• The static keyword belongs to the class than an instance of the class.
• The static can be:
• Variable (also known as a class variable)
• Method (also known as a class method)
• Block
• Nested class
• If you declare any variable as static, it is known as a static variable.
57
static keyword in Java
• It makes your program memory efficient (i.e., it saves memory).
• Understanding the problem without static variable
class Student{
int rollno;
String name;
String college=“DYP-ATU";
}
• Suppose there are 500 students in my college.
• Now all instance data members will get memory each time when the object is created.
• "college" refers to the common property of all objects.
• If we make it static, this field will get the memory only once.
58
static keyword Example
public class TestStatic
class Student{
{
int rollno; //instance variable
public static void main(String args[]){
String name;
Student s1 = new Student(111,"Karan");
static String college =“DYP"; //static variable
Student s2 = new Student(222,"Aryan");
Student(int r, String n) { //constructor
rollno = r;
//[Link]=“DYP";
name = n;
}
[Link]();
void display ()
[Link]();
{
}
[Link](rollno+" "+name+" "+college);
}
}
}
59
End of Unit

60

You might also like