Java for beginners in java and want to write vtu exams
SagarBS12
22 views
163 slides
May 11, 2024
Slide 1 of 163
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
About This Presentation
Java ppt for notes
Size: 7.1 MB
Language: en
Added: May 11, 2024
Slides: 163 pages
Slide Content
What is Java
Java is aprogramming languageand
aplatform.
Java was developed bySun Microsystems in
1995
James Goslingis known as the father of Java.
5/11/2024 2Prof.Mithuna H.R,Dept of ISE,AcIT
All java applications are compiled and interpreted.
It generates byte codes rather than object code.
Bytecodeis a highly optimized set of instructions
designed to be executed by the Java run-time system,
which is called the Java Virtual Machine (JVM).
This provides greater level of flexibility for the
developers to implement the logic specific to JVM
rather to any platform or device.
5/11/2024 3Prof.Mithuna H.R,Dept of ISE,AcIT
JVM is an interpreter for bytecode.
The fact that a Java program is executed by JVM
helps solve the major problems associated with
downloading programs over the Internet.
Translating a Java program into bytecodehelps makes
it much easier to run a program in a wide variety of
environments.
5/11/2024 Prof.Mithuna H.R,Dept of ISE,AcIT 4
This is because only the JVM needs to be
implemented for each platform.
Sun provides a facility called Just In Time (JIT)
compiler for byte code.
It is not possible to compile an entire Java program
into executable code all at once, because Java
performs various run-time checks that can be done
only at run time.
5/11/2024 5Prof.Mithuna H.R,Dept of ISE,AcIT
JIT compiles the code.
Job of JVM is to read this bytecode and convert into
machine dependent instructions.
JVM’s needs to be platform specific but not the
developer’s code. JVM is an interpreter for Bytecode
5/11/2024 Prof.Mithuna H.R,Dept of ISE,AcIT 6
5/11/2024 7Prof.Mithuna H.R,Dept of ISE,AcIT
5/11/2024 8Prof.Mithuna H.R,Dept of ISE,AcIT
Bytecode generated after compiling in Mac, Windows,
Linux or Unix will be same which makes Bytecode
platform independent.So, Bytecode compiled in one
platform can be executed into another platform.
5/11/2024 9Prof.Mithuna H.R,Dept of ISE,AcIT
Java’s Magic –Just in Time (JIT):
Justintime(JIT)isapartofJavaVirtualMachine(JVM)
architecture.
ThejobofJITinsideJVMistocompilebytecodeintomachine
executablecodeinrealtime,onapiece-by-piece,demandbasis.
5/11/2024 13Prof.Mithuna H.R,Dept of ISE,AcIT
WhenJavaprogramsareexecuted,JVMdoesnotread
theentireBytecodeandconvertsitintomachine
instructions.
IfJVMtriestodothisapproachthentheprogram
executiontimewillbedelayedforhours.
5/11/2024 14Prof.Mithuna H.R,Dept of ISE,AcIT
•JREdoesNOTcontainanydevelopmenttoolssuchas
compiler,debugger,etc.anditisNOTfordevelopment
purpose.
5/11/2024 20Prof.Mithuna H.R,Dept of ISE,AcIT
Java’s Magic –Java Development Kit (JDK)
Java Development Kit (JDK) is a set of development tools
installed on the local machine to write and compile Java
programs.
JDK = JRE + Java Development Tools + Libraries
5/11/2024 21Prof.Mithuna H.R,Dept of ISE,AcIT
Application of Java
Desktop Applications such as acrobat reader, media
player, antivirus, etc.
Web Applications such as irctc.co.in
Enterprise Applications such as banking applications.
Mobile
Embedded System
Smart Card
Robotics
Games, etc.
5/11/2024 22Prof.Mithuna H.R,Dept of ISE,AcIT
Types of Java Applications
Standalone Application
Web Application
Enterprise Application
Mobile Application
5/11/2024 23Prof.Mithuna H.R,Dept of ISE,AcIT
5/11/2024 24Prof.Mithuna H.R,Dept of ISE,AcIT
Java Buzzwords or Features of Java
The Java programming language is a high-level language that can be characterized by all of the
following buzzwords:
5/11/2024 25Prof.Mithuna H.R,Dept of ISE,AcIT
1.ObjectOriented:
Java is true object oriented language.
Almost “Everything is an Object” paradigm. All program code and data
reside within objects and classes.
The object model in Java is simple and easy to extend.
Java comes with an extensive set of classes, arranged in packages that
can be used in our programs through inheritance.
Java follows object oriented model.
It supports all the features of object oriented model like:
Encapsulation
Inheritance
Polymorphism
Abstraction
5/11/2024 26Prof.Mithuna H.R,Dept of ISE,AcIT
2. Simple:
Java was designed to be easy for professional programmer
to learn and use effectively.
It’s simple and easy to learn if you already know the basic
concepts of Object Oriented Programming.
Java is easy to learn
It is easy to write programs using Java
Expressiveness is more in Java.
Most of the complex or confusing features in C++ are
removed in Java like pointers etc.
5/11/2024 27Prof.Mithuna H.R,Dept of ISE,AcIT
3. Secure:
Java provides a “firewall” between a networked application and the
computer.
When a Java Compatible Web browser is used, downloading can be done
safely without fear of viral infection or malicious intent.
Java achieves this protection by confining a Java program to the java
execution environment and not allowing it to access other parts of the
computer.
Java provides data security through encapsulation.
5/11/2024 28Prof.Mithuna H.R,Dept of ISE,AcIT
Also we can write applets in Java which provides security.
An applet is a small program which can be downloaded from
one computer to another automatically.
There is no need to worry about applets accessing the system
resources which may compromise security.
Applets are run within the JVM which protects from
unauthorized or illegal access to system resources
5/11/2024 Prof.Mithuna H.R,Dept of ISE,AcIT 29
4. Platformindependent
Platform independentlanguage means once compiled you can execute the
program on anyplatform(OS).
Javaisplatform independent. Because theJavacompiler converts the
source code to bytecode, which is Intermidiate Language.
Bytecode can be executed on anyplatform(OS) using JVM(JavaVirtual
Machine).
Platform independence is one of the most significant advantages that Java
has over other programming languages, particularly for systems that need to
work on many different platforms.
5/11/2024 30Prof.Mithuna H.R,Dept of ISE,AcIT
5. Robust
It provides many features that make the program execute
reliably in variety of environments.
Java is a strictly typed language. It checks code both at compile
time and runtime.
Java takes care of all memory management problems with
garbage-collection.
Java, with the help of exception handling captures all types of
serious errors and eliminates any risk of crashing the system.
5/11/2024 31Prof.Mithuna H.R,Dept of ISE,AcIT
A program or an application is said to be
robust(reliable) when it is able to give some response
in any kind of context.
Java’s features help to make the programs robust.
Some of those features are:
Type checking
Exception handling
5/11/2024 Prof.Mithuna H.R,Dept of ISE,AcIT 32
6. Portable
Java Provides a way to download programs
dynamically to all the various types of platforms
connected to the Internet.
It helps in generating Portable executable code.
Applications written using Java are portable in the
sense that they can be executed on any kind of
computer containing any CPU or any operating
system.
5/11/2024 33Prof.Mithuna H.R,Dept of ISE,AcIT
When an application written in Java is compiled, it
generates an intermediate code file called as
“bytecode”.
Bytecode helps Java to achieve portability.
This bytecode can be taken to any computer and
executed directly.
5/11/2024 Prof.Mithuna H.R,Dept of ISE,AcIT 34
Bytecode can be executed on computers having any
kind of operating system or any kind of CPU.
Since Java applications can run on any kind of CPU,
Java is architecture –neutral.
5/11/2024 Prof.Mithuna H.R,Dept of ISE,AcIT 36
Libraries are dynamically linked during runtime.
So, even if you make dynamic changes to pieces of
code, the program is not affected.
5/11/2024 Prof.Mithuna H.R,Dept of ISE,AcIT 38
In Java 1.0 version there is an interpreter for executing the
bytecode. As interpreter is quite slow when compared to a
compiler, java programs used to execute slowly.
After Java 1.0 version the interpreter was replaced with
JIT(Just-In-Time) compiler.
JIT compiler uses Sun Microsystem’sHot Spot technology.
JIT compiler converts the byte code into machine code piece by
piece and caches them for future use.
This enhances the program performance means it executes
rapidly.5/11/2024 Prof.Mithuna H.R,Dept of ISE,AcIT 40
10. High performance
Java performance is high because of the use of bytecode.
The bytecode was used, so that it was easily translated into
native machine code.
5/11/2024 41Prof.Mithuna H.R,Dept of ISE,AcIT
11. Multithreaded
Multi-threaded Programs handled multiple tasks
simultaneously, which was helpful in creating interactive,
networked programs.
Java supports multithreading which is not supported by C and
C++.
A thread is a light weight process.
5/11/2024 42Prof.Mithuna H.R,Dept of ISE,AcIT
Multithreading increases CPU efficiency.
A program can be divided into several threads and each thread
can be executed concurrently or in parallel with the other
threads.
Real world example for multithreading is computer. While we
are listening to music, at the same time we can write in a word
document or play a game.
5/11/2024 Prof.Mithuna H.R,Dept of ISE,AcIT 43
12. Distributed
Java is designed for distributed environment of the Internet. It’s
used for creating applications on networks.
Java applications can access remote objects on Internet as
easily as they can do in local system.
Java enables multiple programmers at multiple remote
locations to collaborate and work together on a single project.
5/11/2024 44Prof.Mithuna H.R,Dept of ISE,AcIT
Java supports distributed computation using Remote Method
Invocation (RMI) concept.
The server and client(s) can communicate with another and the
computations can be divided among several computers which
makes the programs to execute rapidly.
In distributed systems, resources are shared.
5/11/2024 Prof.Mithuna H.R,Dept of ISE,AcIT 45
The simple java program creation
We can write a simple hello java program easily after installing the JDK.
To create a simple java program, you need to create a class that contains
main method. Let's understand the requirement first.
Requirement for Hello Java Example
For executing any java program, you need to
Install the JDK
set path of the jdk/bin directory.
create the java program
compile and run the java program
5/11/2024 46Prof.Mithuna H.R,Dept of ISE,AcIT
Java Version History
JDK Alpha and Beta (1995)
JDK 1.0 (23rd Jan 1996)
JDK 1.1 (19th Feb 1997)
J2SE 1.2 (8th Dec 1998)
J2SE 1.3 (8th May 2000)
J2SE 1.4 (6th Feb 2002)
J2SE 5.0 (30th Sep 2004)
Java SE 6 (11th Dec 2006)
Java SE 7 (28th July 2011)
Java SE 8 (18th Mar 2014)
Java SE 9 (21st Sep 2017)
Java SE 10 (20th Mar 2018)
5/11/2024 47Prof.Mithuna H.R,Dept of ISE,AcIT
Java Platforms / Editions
Java SE (Java Standard Edition)
We can develop stand-alone applications. This provides the different
packages like java.lang,java.util etc.
Java EE (Java Enterprise Edition)
we can develop Enterprise applications. This includes API’s like Servlets,
WebSocket, JavaServerFaces, Unified Expression Language.
Java ME (Java Micro Edition)
wecandevelopapplicationsthatrunonsmallscaledeviceslikemobile
phones.
5/11/2024 48Prof.Mithuna H.R,Dept of ISE,AcIT
5/11/2024 49Prof.Mithuna H.R,Dept of ISE,AcIT
Creating Hello World Example
classSimple{
publicstaticvoidmain(Stringargs[]){
System.out.println("HelloJava");
}
}
5/11/2024 50Prof.Mithuna H.R,Dept of ISE,AcIT
Compilation Flow
To compile: javac Simple.java
To execute: java Simple
Output:HelloJava
5/11/2024 51Prof.Mithuna H.R,Dept of ISE,AcIT
Understanding first java program
Let's see what is the meaning of class, public, static,
void, main, String[], System.out.println().
classkeyword is used to declare a class in java.
publickeyword is an access modifier which represents
visibility, it means it is visible to all.
staticis a keyword, if we declare any method as static,
it is known as static method. The core advantage of
static method is that there is no need to create object
to invoke the static method. The main method is
executed by the JVM, so it doesn't require creating
object to invoke the main method. So it saves memory.
5/11/2024 52Prof.Mithuna H.R,Dept of ISE,AcIT
voidis the return type of the method, it means it
doesn't return any value.
mainrepresents startup of the program.
String[] argsis used for command line argument.
System.out.println()is used print statement.
To write the simple program, open notepad bystart
menu -> All Programs -> Accessories ->
notepadand write simple program as displayed
below:
5/11/2024 Prof.Mithuna H.R,Dept of ISE,AcIT 53
As displayed in the above diagram, write the simple program of java in notepad and
saved it as Simple.java.
To compile and run this program, you need to open command prompt by
start menu -> All Programs -> Accessories -> command prompt.
5/11/2024 54Prof.MithunaH.R,Deptof ISE,AcIT
5/11/2024 55Prof.Mithuna H.R,Dept of ISE,AcIT
Can you save a java source file by
other name than the class name?
To compile: javac Hard.java
To execute: java Simple
5/11/2024 56Prof.Mithuna H.R,Dept of ISE,AcIT
Can you have multiple classes in a
java source file?
5/11/2024 57Prof.Mithuna H.R,Dept of ISE,AcIT
Object
Any entity that has state and behavior is known as an object.
5/11/2024 59Prof.Mithuna H.R,Dept of ISE,AcIT
Class
Collection of objectsis called class. It is a logical entity.
A class can also be defined as a blueprint from which
you can create an individual object. Class doesn't
consume any space.
5/11/2024 60Prof.Mithuna H.R,Dept of ISE,AcIT
Inheritance
When one object acquires all the properties and
behaviors of a parent object, it is known as inheritance.
It provides code reusability.
It is used to achieve runtime polymorphism.
5/11/2024 61Prof.Mithuna H.R,Dept of ISE,AcIT
Polymorphism
Ifone task is performed in different ways, it is known as
polymorphism
5/11/2024 62Prof.Mithuna H.R,Dept of ISE,AcIT
Abstraction
Hiding internal details and showing functionalityis
known as abstraction.
For example phone call, we don't know the internal
processing.
In Java, we use abstract class and interface to achieve
abstraction.
5/11/2024 63Prof.Mithuna H.R,Dept of ISE,AcIT
Encapsulation
Binding (or wrapping) code and data together into a single
unit are known as encapsulation.
A java class is the example of encapsulation because all the data
members are private here.
5/11/2024 64Prof.Mithuna H.R,Dept of ISE,AcIT
What is a class in Java
A class is a group of objects which have common
properties. It is a template or blueprint from which
objects are created. It is a logical entity. It can't be
physical.
A class in Java can contain:
Fields
Methods
Constructors
Blocks
Nested class and interface
5/11/2024 65Prof.Mithuna H.R,Dept of ISE,AcIT
Creating an Object
In Java, the new keyword is used to create new objects.
There are three steps when creating an object from a
class −
Declaration− A variable declaration with a variable
name with an object type.
Instantiation− The 'new' keyword is used to create
the object.
Initialization− The 'new' keyword is followed by a
call to a constructor. This call initializes the new
object.
5/11/2024 Prof.Mithuna H.R,Dept of ISE,AcIT 66
Accessing Instance Variables and Methods
Instance variables and methods are accessed via
created objects. To access an instance variable,
following is the fully qualified path −
/* First create an object */
Datatype ObjectReference = new Constructor();
Example: A a=new A();
/* Now call a variable as follows */
ObjectReference.variableName;
/* Now you can call a class method as follows */
ObjectReference.MethodName();
5/11/2024 Prof.Mithuna H.R,Dept of ISE,AcIT 67
Java command line arguments:
Commandlineargumentsaretheparametersthataresuppliedtothe
applicationprogramatthetimewhentheyareinvoked.
Themain()methodofJavaprogramwilltakethecommandlinearguments
astheparameteroftheargs[]variablewhichisastringarray.
5/11/2024 Prof.Mithuna H.R,Dept of ISE,AcIT 71
Example:
Class Comlinetest
{
public static void main(String args[ ] )
{
int count, n = 0; string str;
count = args.length;
System.out.println ( “ Number of arguments :” + count);
while ( n < count )
{
str = args[ n ]; n = n + 1;
System.out.println( n + “ : “ + str);
}
}
}
5/11/2024 Prof.Mithuna H.R,Dept of ISE,AcIT 72
Run/Calling the program:
javac Comlinetest.java
java Comlinetest Java c cpp fortran
Output:
1: Java
2: c
3: cpp
4: fortran
5/11/2024 Prof.Mithuna H.R,Dept of ISE,AcIT 73
Java API
Java standard library includes hundreds of classes
and methods grouped into several functional
packages. Most commonly used packages are:
Language support Package.
Utilities packages.
Input/output packages
Networking packages
AWT packages.
Applet packages.
5/11/2024 Prof.Mithuna H.R,Dept of ISE,AcIT 74
User Input from Keyboard
AcceptingkeyboardinputinJavaisdoneusingaScannerobject.
Considerthefollowingstatement
Scannerconsole=newScanner(System.in);
Thisstatementdeclaresareferencevariablenamedconsole.The
Scannerobjectisassociatedwithstandardinputdevice(System.in).
Togetinputfromkeyboard,youcancallmethodsofScannerclass.For
exampleinfollowingstatmentnextInt()methodofScannertakesan
integerandreturnstovariablex:
intx=console.nextInt();
5/11/2024 Prof.Mithuna H.R,Dept of ISE,AcIT 77
Input Types
5/11/2024 78Prof.Mithuna H.R,Dept of ISE,AcIT
Data Types, Variables, Operators, Control Statements in
Java
Data types:
There are two data types available in Java
Primitive Data Types
Non Primitive Data Types
Reference/Object Data Types
5/11/2024 Prof.Mithuna H.R,Dept of ISE,AcIT 79
Types of data types
5/11/2024 Prof.Mithuna H.R,Dept of ISE,AcIT 80
5/11/2024 Prof.Mithuna H.R,Dept of ISE,AcIT 81
Reference Data types:
Referencevariablesarecreatedusingdefinedconstructorsofthe
classes.
Theyareusedtoaccessobjects.Thesevariablesaredeclaredtobeofa
specifictypethatcannotbechanged.Forexample,Employee,Students
etc.
Classobjectsandvarioustypesofarrayvariablescomeunderreference
datatype.
Defaultvalueofanyreferencevariableisnull.
Areferencevariablecanbeusedtoreferanyobjectofthedeclaredtype
oranycompatibletype.
Example:Animalanimal=newAnimal("giraffe");
5/11/2024 Prof.Mithuna H.R,Dept of ISE,AcIT 82
Types of Variable
There are three types of variables in java:
local variable
instance variable
static variable
5/11/2024 Prof.Mithuna H.R,Dept of ISE,AcIT 84
Local Variable
A variable which is declared inside the method is
called local variable.
Instance Variable
A variable which is declared inside the class but
outside the method, is called instance variable.
It is not declared as static.
Static variable
A variable that is declared as static is called static
variable.
It cannot be local.
5/11/2024 Prof.Mithuna H.R,Dept of ISE,AcIT 85
Example to understand the types of variables in java
classA{
intdata=50;//instancevariable
staticintm=100;//staticvariable
voidmethod()
{
intn=90;//localvariable
}
}//endofclass
5/11/2024 Prof.Mithuna H.R,Dept of ISE,AcIT 86
Operators:
Operatorin java is a symbol that is used to perform
operations.
For example: +, -, *, / etc.
There are many types of operators in java which are
given below:
Unary Operator,
Arithmetic Operator,
shift Operator,
Relational Operator,
Bitwise Operator,
Logical Operator,
Ternary Operator and
Assignment Operator.
5/11/2024 Prof.Mithuna H.R,Dept of ISE,AcIT 87
Instanceof Operator
This operator is used only for object reference variables.
The operator checks whether the object is of a particular type (class type or
interface type). instanceof operator is written as
( Object reference variable ) instanceof (class/interface type)
If the object referred by the variable on the left side of the operator passes
the IS-A check for the class/interface type on the right side, then the result
will be true.
5/11/2024 Prof.Mithuna H.R,Dept of ISE,AcIT 88
class Test
{
public static void main(String args[])
{
String name ="James";
// following will return true since name is type of String
boolean result = name instanceof String;
System.out.println( result );
}
}
Class A
A obj=new A();
boolean result=obj instanceof A
5/11/2024 Prof.Mithuna H.R,Dept of ISE,AcIT 89
5/11/2024 Prof.Mithuna H.R,Dept of ISE,AcIT 91
Advantage of Java Array
Code Optimization:It makes the code optimized, we can
retrieve or sort the data easily.
Random access:We can get any data located at any index
position.
Disadvantage of Java Array
Size Limit:We can store only fixed size of elements in the
array. It doesn't grow its size at runtime. To solve this problem,
collection framework is used in java.
Types of Array in java
There are two types of array.
Single Dimensional Array.
Multidimensional Array
Single Dimensional Array in java
Syntax to Declare an Array in java
Touseanarrayinaprogram,youmustdeclareavariableto
referencethearray,andyoumustspecifythetypeofarraythe
variablecanreference.
5/11/2024 Prof.Mithuna H.R,Dept of ISE,AcIT 92
syntax for declaring an array variable
Here is the syntax for declaring an array variable:
int a[4];
dataType[]arrayRefVar;(or)int[] a;
dataType[]arrayRefVar;(or)
dataTypearrayRefVar[];
5/11/2024 Prof.Mithuna H.R,Dept of ISE,AcIT 93
The following code snippets are examples of this
syntax:
int[] myList;
(or)
int []myList;
(or)
int myList[];
5/11/2024 Prof.Mithuna H.R,Dept of ISE,AcIT 94
Creating Arrays:
You can create an array by using the new operator with the
following syntax:
arrayRefVar = new dataType[arraySize];
The above statement does two things:
It creates an array using new dataType[arraySize];
It assigns the reference of the newly created array to the
variable arrayRefVar.
5/11/2024 Prof.Mithuna H.R,Dept of ISE,AcIT 95
Declaring an array variable, creating an array, and assigning the
reference of the array to the variable can be combined in one
statement, as shown below:
dataType[] arrayRefVar = new dataType[arraySize];
Alternatively you can create arrays as follows:
dataType[] arrayRefVar = {value0, value1, ..., valuek};
The array elements are accessed through the index. Array
indices are 0-based; that is, they start from 0 to
arrayRefVar.length-1.
5/11/2024 Prof.Mithuna H.R,Dept of ISE,AcIT 96
Example:
Following statement declares an array variable, myList,
creates an array of 10 elements of double type and
assigns its reference to myList:
double[] myList = new double[10];
Following picture represents array myList. Here, myList
holds ten double values and the indices are from 0 to 9
5/11/2024 Prof.Mithuna H.R,Dept of ISE,AcIT 97
5/11/2024 Prof.Mithuna H.R,Dept of ISE,AcIT 98
Example of single dimensional java
array
classTestarray
{
publicstaticvoidmain(Stringargs[])
{
inta[]=newint[5];//declarationan
dinstantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
5/11/2024 Prof.Mithuna H.R,Dept of ISE,AcIT 99
//printingarray
for(inti=0;i<a.length;i++)//lengthis
thepropertyofarray
System.out.println(a[i]);
}
}
Output: 10
20
70
40
50
Declaration, Instantiation and Initialization of Java Array
We can declare, instantiate and initialize the java array together
by:
inta[]={33,3,4,5};//declaration,instantiationandinitialization
Let's see the simple example to print this array.
classTestarray1
{
publicstaticvoidmain(Stringargs[])
{
inta[]={33,3,4,5};//declaration,instantiationandinitialization
//printingarray
for(inti=0;i<a.length;i++)//lengthisthepropertyofarray
System.out.println(a[i]);
}
}
5/11/2024 Prof.Mithuna H.R,Dept of ISE,AcIT 100
Passing Array to method in java
We can pass the java array to method so that we can reuse the same
logic on any array.
classTestarray2
{
staticvoidmin(intarr[])
{
intmin=arr[0];//33
for(inti=1;i<arr.length;i++)
if(min>arr[i])//33>3
min=arr[i];//3
System.out.println(min);
}
5/11/2024 Prof.Mithuna H.R,Dept of ISE,AcIT 101
publicstaticvoidmain(Stringargs[])
{
inta[]={33,3,4,5};
min(a);//passingarraytomethod
}
}
Output:3
Multidimensional array in java
In such case, data is stored in row and column based
index (also known as matrix form).
Syntax to Declare Multidimensional Array in java
dataType[][]arrayRefVar;(or)
dataType[][]arrayRefVar;(or)
dataTypearrayRefVar[][];(or)
dataType[]arrayRefVar[];
5/11/2024 Prof.Mithuna H.R,Dept of ISE,AcIT 102
Example to instantiate Multidimensional Array in
java
int[][]arr=newint[3][3];//3rowand3column
Example to initialize Multidimensional Array in
java
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;
5/11/2024 Prof.Mithuna H.R,Dept of ISE,AcIT 103
Example of Multidimensional java array
Let's see the simple example to declare, instantiate, initialize and print the
2Dimensional array.
classTestarray3
{
publicstaticvoidmain(Stringargs[])
{//declaringandinitializing2Darray
intarr[][]={{1,2,3},{2,4,5},{4,4,5}};
//printing2Darray
for(inti=0;i<3;i++)
{ for(intj=0;j<3;j++)
{
System.out.print(arr[i][j]+"");
}
System.out.println();
}
}}
5/11/2024 Prof.Mithuna H.R,Dept of ISE,AcIT 104
Output:
1 2 3
2 4 5
4 4 5
Control Statements:
A program executes from top to bottom except when
we use control statements, we can control the order of
execution of the program, based on logic and values.
In Java, control statements can be divided into the
following three categories:
Selection Statements
Iteration Statements
Jump Statements
5/11/2024 Prof.Mithuna H.R,Dept of ISE,AcIT 106
Selection Statements
Selection statements allow you to control the flow of
program execution on the basis of the outcome of an
expression or state of a variable known during
runtime.
Selection statements can be divided into the following
categories:
The if and if-else statements
The if-else statements
The if-else-if statements
The switch statements
5/11/2024 Prof.Mithuna H.R,Dept of ISE,AcIT 107
If Statements
The first containedstatement (that can be a block) of
an if statement only executes when the specified
condition is true.
If the condition is false and there is not else keyword
then the first containedstatement will be skipped and
execution continues with the rest of the program.
The condition is an expression that returns a boolean
value.
5/11/2024 Prof.Mithuna H.R,Dept of ISE,AcIT 108
The if-else statements
In if-else statements, if the specified condition in the if
statement is false, then the statement after the else
keyword (that can be a block) will execute.
5/11/2024 Prof.Mithuna H.R,Dept of ISE,AcIT 110
The if-else-if statements
This statement following the else keyword can be another if or if-else statement.
That would looks like this:
if(condition)
statements;
else if (condition)
statements;
else if(condition)
statement;
else
statements;
Whenever the condition is true, the associated statement will be executed and
the remaining conditions will be bypassed. If none of the conditions are true
then the else block will execute.
5/11/2024 Prof.Mithuna H.R,Dept of ISE,AcIT 112
The Switch Statements
The switch statement is a multi-way branch statement.
The switch statement of Java is another selection
statement that defines multiple paths of execution of a
program.
It provides a better alternative than a large series of if-
else-if statements.
5/11/2024 Prof.Mithuna H.R,Dept of ISE,AcIT 114
Each of the values specified in the case statement must
be of a type compatible with the expression.
Duplicate case values are not allowed.
The break statement is used inside the switch to
terminate a statement sequence.
The break statement is optional in the switch
statement.
5/11/2024 Prof.Mithuna H.R,Dept of ISE,AcIT 116
Iteration Statements
Repeatingthesamecodefragmentseveraltimesuntil
aspecifiedconditionissatisfiediscallediteration.
Iterationstatementsexecutethesamesetof
instructionsuntilaterminationconditionismet.
Java provides the following loop for iteration
statements:
The while loop
The for loop
The do-while loop
The for each loop
5/11/2024 Prof.Mithuna H.R,Dept of ISE,AcIT 117
The while loop
Itcontinuallyexecutesastatement(thatisusuallybea
block)whileaconditionistrue.Theconditionmust
returnaBooleanvalue.
5/11/2024 118Prof.Mithuna H.R,Dept of ISE,AcIT
The for loop
Aforloopexecutesastatement(thatisusuallyablock)
aslongastheBooleanconditionevaluatestotrue.A
forloopisacombinationofthethreeelements
initializationstatement,Booleanexpressionand
incrementordecrementstatement.
Syntax:
for(<initialization>;<condition>;<increment or decrement
statement>)
{
<block of code>
}
5/11/2024 Prof.Mithuna H.R,Dept of ISE,AcIT 122
The For each loop
TheJavafor-eachlooporenhancedforloopis
introducedsinceJ2SE5.0.Itprovidesanalternative
approachtotraversethearrayorcollectioninJava.Itis
mainlyusedtotraversethearrayorcollection
elements.
For-eachisanotherarraytraversingtechniquelikefor
loop,whileloop,do-whileloopintroducedinJava5.
5/11/2024 125Prof.Mithuna H.R,Dept of ISE,AcIT
syntax:
for (type var : array)
{
statements using var;
}
is equivalent to:
for (int i=0; i<arr.length; i++)
{
type var = arr[i];
statements using var;
}
5/11/2024 127Prof.Mithuna H.R,Dept of ISE,AcIT
Example
class ForEachExample1
{
public static void main(String args[])
{
int arr[]={12,13,14,44};
for(int i:arr)
{
System.out.println(i);
}
} }
5/11/2024 128Prof.Mithuna H.R,Dept of ISE,AcIT
Advantages
It makes the code more readable.
It eliminates the possibility of programming errors.
It is known as the for-each loop because it traverses
each element one by one.
5/11/2024 130Prof.Mithuna H.R,Dept of ISE,AcIT
Drawback of the enhanced for loop
Itcannottraversetheelementsinreverseorder.
wedonothavetheoptiontoskipanyelementbecause
itdoesnotworkonanindexbasis.Moreover,we
cannottraversetheoddorevenelementsonly.
But, it is recommended to use the Java for-each loop
for traversing the elements of array and collection
because it makes the code readable.
5/11/2024 131Prof.Mithuna H.R,Dept of ISE,AcIT
Labeled Break Statement:
This is used for when we want to jump the program
control out of nested loops or multiple loops.
5/11/2024 138Prof.Mithuna H.R,Dept of ISE,AcIT
Find total number of iterations
A)10
B)12
C)14
D)16
5/11/2024 143Prof.Mithuna H.R,Dept of ISE,AcIT
Labeled Continue Statement:
This statement skips the current iteration of the loop
with the specified label.
5/11/2024 144Prof.Mithuna H.R,Dept of ISE,AcIT
Example
publicclassReturnDemo
{
publicstaticvoidmain(String[]args)
{
ReturnDemoreturnDemo=newReturnDemo();
System.out.println("No:"+returnDemo.returnCall());
}
intreturnCall()
{
return5;
}
}
5/11/2024 148Prof.Mithuna H.R,Dept of ISE,AcIT
Type Casting in Java
Assigningavalueofonetypetoavariableofanother
typeisknownasTypeCasting.
Javaobjecttypecastingoneobjectreferencecanbe
typecastintoanotherobjectreference.
Thecastcanbetoitsownclasstypeortooneofits
subclassorsuperclasstypesorinterfaces.
Therearecompile-timerulesandruntimerulesfor
castinginjava.
5/11/2024 149Prof.Mithuna H.R,Dept of ISE,AcIT
Example in Java
int x = 10;
byte y = (byte)x;
5/11/2024 150Prof.Mithuna H.R,Dept of ISE,AcIT
In Java, type casting is classified into two types,
1)Widening Casting(Implicit)
5/11/2024 151Prof.Mithuna H.R,Dept of ISE,AcIT
2) Narrowing Casting(Explicitly done)
5/11/2024 152Prof.Mithuna H.R,Dept of ISE,AcIT
Widening or Automatic type conversion
Automatic Type casting take place when,
the two types are compatible
the target type is larger than the source type
5/11/2024 153Prof.Mithuna H.R,Dept of ISE,AcIT
Example :
public class Test
{
public static void main(String[] args)
{
int i = 100;
long l = i;//no explicit type casting required
float f = l;//no explicit type casting required
System.out.println("Int value "+i);
System.out.println("Long value "+l);
System.out.println("Float value "+f);
}
}
5/11/2024 154Prof.Mithuna H.R,Dept of ISE,AcIT
Output :
Int value 100
Long value 100
Float value 100.0
5/11/2024 155Prof.Mithuna H.R,Dept of ISE,AcIT
Narrowing or Explicit type conversion
Whenyouareassigningalargertypevaluetoa
variableofsmallertype,thenyouneedtoperform
explicittypecasting.
5/11/2024 156Prof.Mithuna H.R,Dept of ISE,AcIT
Example :
public class Test
{
public static void main(String[] args)
{
double d = 100.04;
long l = (long)d; //explicit type casting required
int i = (int)l;//explicit type casting required
System.out.println("Double value "+d);
System.out.println("Long value "+l);
System.out.println("Int value "+i);
}
}
5/11/2024 157Prof.Mithuna H.R,Dept of ISE,AcIT
Output :
Double value 100.04
Long value 100
Int value 100
5/11/2024 158Prof.Mithuna H.R,Dept of ISE,AcIT
Default Access Modifier -No keyword:
Defaultaccessmodifiermeanswedonotexplicitly
declareanaccessmodifierforaclass,field,method,
etc.Avariableormethoddeclaredwithoutanyaccess
control
5/11/2024 162Prof.Mithuna H.R,Dept of ISE,AcIT
Advantages of JAVA:
•It is an open source, so users do not have to struggle with heavy license fees each
year.
•Platform independent.
•Java API's can easily be accessed by developers.
•Java perform supports garbage collection, so memory management is automatic.
•Java always allocates objects on the stack.
•Java embraced the concept of exception specification.
•Multi-platform support language and support for web-services.
•Using JAVA we can develop dynamic web applications.
•It allows you to create modular programs and reusable codes.
5/11/2024 163Prof.Mithuna H.R,Dept of ISE,AcIT