Java-Unit 1 Fundamentals of Java Programming
Java-Unit 1 Fundamentals of 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.
8
Java is Object-oriented
• Java is an object-oriented programming language.
• Everything in Java is an object.
• 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.
2) Web Application
3) Enterprise Application
4) Mobile Application
16
Types of Java Applications
• Standalone applications
17
Types of Java Applications
• Enterprise Application
• 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
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.
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)
25
Java Compiler
• This is a compiler for Java programming language (Javac)
• It translates java source code into byte code.
• 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.
• 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
• 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.
• Execute (JRE)
• 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.
• 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
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
• 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.
55
Logical Operator
• Logical refers to the ways in which true
and false values can be connected
together.
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
• 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
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
• 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).
65
Control
Flow
If statement
• The "if" statement is used to evaluate a condition.
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.
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.
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.
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
}
• 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.
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.
• 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
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
• 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
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.
• 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.
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 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.
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.
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.
• 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”.
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
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
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.
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;
}
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.
• Every time an object is created using the new() keyword, at least one
constructor is called.
• 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.
47
Constructor Overloading Example
48
49
Constructor Overloading Example-Result
50
51
this keyword in Java
• In Java, this is a reference variable
that refers to the current object.
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