Java for beginners in java and want to write vtu exams

SagarBS12 22 views 163 slides May 11, 2024
Slide 1
Slide 1 of 163
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29
Slide 30
30
Slide 31
31
Slide 32
32
Slide 33
33
Slide 34
34
Slide 35
35
Slide 36
36
Slide 37
37
Slide 38
38
Slide 39
39
Slide 40
40
Slide 41
41
Slide 42
42
Slide 43
43
Slide 44
44
Slide 45
45
Slide 46
46
Slide 47
47
Slide 48
48
Slide 49
49
Slide 50
50
Slide 51
51
Slide 52
52
Slide 53
53
Slide 54
54
Slide 55
55
Slide 56
56
Slide 57
57
Slide 58
58
Slide 59
59
Slide 60
60
Slide 61
61
Slide 62
62
Slide 63
63
Slide 64
64
Slide 65
65
Slide 66
66
Slide 67
67
Slide 68
68
Slide 69
69
Slide 70
70
Slide 71
71
Slide 72
72
Slide 73
73
Slide 74
74
Slide 75
75
Slide 76
76
Slide 77
77
Slide 78
78
Slide 79
79
Slide 80
80
Slide 81
81
Slide 82
82
Slide 83
83
Slide 84
84
Slide 85
85
Slide 86
86
Slide 87
87
Slide 88
88
Slide 89
89
Slide 90
90
Slide 91
91
Slide 92
92
Slide 93
93
Slide 94
94
Slide 95
95
Slide 96
96
Slide 97
97
Slide 98
98
Slide 99
99
Slide 100
100
Slide 101
101
Slide 102
102
Slide 103
103
Slide 104
104
Slide 105
105
Slide 106
106
Slide 107
107
Slide 108
108
Slide 109
109
Slide 110
110
Slide 111
111
Slide 112
112
Slide 113
113
Slide 114
114
Slide 115
115
Slide 116
116
Slide 117
117
Slide 118
118
Slide 119
119
Slide 120
120
Slide 121
121
Slide 122
122
Slide 123
123
Slide 124
124
Slide 125
125
Slide 126
126
Slide 127
127
Slide 128
128
Slide 129
129
Slide 130
130
Slide 131
131
Slide 132
132
Slide 133
133
Slide 134
134
Slide 135
135
Slide 136
136
Slide 137
137
Slide 138
138
Slide 139
139
Slide 140
140
Slide 141
141
Slide 142
142
Slide 143
143
Slide 144
144
Slide 145
145
Slide 146
146
Slide 147
147
Slide 148
148
Slide 149
149
Slide 150
150
Slide 151
151
Slide 152
152
Slide 153
153
Slide 154
154
Slide 155
155
Slide 156
156
Slide 157
157
Slide 158
158
Slide 159
159
Slide 160
160
Slide 161
161
Slide 162
162
Slide 163
163

About This Presentation

Java ppt for notes


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: Java Virtual Machine(JVM)
TheJavaVirtualMachine(JVM)isanabstract
computer,onwhichthebytecodecanbeexecuted.
JavaVirtualMachine(JVM)interpretsthebytecode
intothemachinecodedependingupontheunderlying
operatingsystemandhardwarecombination.
JVMdoesnotknowanythingaboutJavaprogram
ratheritreadsthebytecode,interpretsthecodeand
executesthecode.
5/11/2024 10Prof.Mithuna H.R,Dept of ISE,AcIT

BytecodePlatformIndependentvsJavaVirtual
Machine(JVM)PlatformDependent:
JVMisplatformdependentthatmeansthereare
differentimplementationofJVMondifferentOS.
Javacode/Bytecodeisalwaysthesameondifferent
OS.Thatmakesjavaprogramasplatform
independent.
5/11/2024 Prof.Mithuna H.R,Dept of ISE,AcIT 11

5/11/2024 12Prof.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

Javahasovercomethelatencyofprogramexecution
timebyinterpretingtherequiredbytecodeandkeeps
therestofthecodeaside.
Justintime(JIT)helpstocompilecodethatisonly
neededandatthesametimeboosttheprogram
performance.
WhethertheJavaprogramsareinterpretedtraditional
wayorontheflythefunctionalityandfeatureslike
portabilityandsecurityremainsthesame.
5/11/2024 Prof.Mithuna H.R,Dept of ISE,AcIT 15

5/11/2024 16Prof.Mithuna H.R,Dept of ISE,AcIT

Java’s Magic –Java Runtime Environment (JRE):
Javaprogramscannotbeexecutedonmachine
withouttheJVMinstalledonmachine.
JavaRuntimeEnvironment(JRE)issoftwarewhich
wecandownloadandinstallontheanyoperating
systemlikeWindows,MacorLinux.
5/11/2024 17Prof.Mithuna H.R,Dept of ISE,AcIT

5/11/2024 18Prof.Mithuna H.R,Dept of ISE,AcIT

JREiscombinationofJVMandJavaApplication
ProgrammingInterface(JavaAPI).
JavaAPIissetoftoolsandlibrariesthatarerequiredbythe
JVMtoexecutethejavaprograms.JavaRuntimeEnvironment
providesanenvironmenttoexecutejavaprogramsonthe
computer.
JRE=JVM+JavaAPI’s(likeutil,math,lang,awt,swingetc)
+Runtimelibraries.
5/11/2024 19Prof.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

7. Architecture neutral:
JavalanguageandJavaVirtualMachinehelpedinachieving
thegoalof“writeonce;runanywhere,anytime,forever.”
Changesandupgradesinoperatingsystems,processorsand
systemresourceswillnotforceanychangesinJavaPrograms.
BytecodehelpsJavatoachieveportability.
5/11/2024 35Prof.Mithuna H.R,Dept of ISE,AcIT

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

8. Dynamic
Javaiscapableoflinkinginnewclasslibraries,methods,and
objects.
Itcanalsolinknativemethods(thefunctionswritteninother
languagessuchasCandC++).
TheJavaVirtualMachine(JVM)maintainsalotofruntime
informationabouttheprogramandtheobjectsintheprogram.
5/11/2024 37Prof.Mithuna H.R,Dept of ISE,AcIT

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

9. Interpreted
Usuallyacomputerlanguageiseithercompiledorinterpreted.
Javacombinesboththisapproachandmakesitatwo-stage
system.
Compiled:Javaenablescreationofacrossplatformprograms
bycompilingintoanintermediaterepresentationcalledJava
Bytecode.
Interpreted:Bytecodeistheninterpreted,whichgenerates
machinecodethatcanbedirectlyexecutedbythemachinethat
providesaJavaVirtualmachine.

5/11/2024 39Prof.Mithuna H.R,Dept of ISE,AcIT

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

OOPs (Object-Oriented
Programming System)
Object
Class
Inheritance
Polymorphism
Abstraction
Encapsulation
5/11/2024 58Prof.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

//JavaProgramtoillustratehowtodefineaclassandfields
//DefiningaStudentclass.
classStudent{
//definingfields
intid;//fieldordatamemberorinstancevariable
Stringname;
//creatingmainmethodinsidetheStudentclass
publicstaticvoidmain(Stringargs[]){
//Creatinganobjectorinstance
Students1=newStudent();//creatinganobjectofStudent
//Printingvaluesoftheobject
System.out.println(s1.id);//accessingmemberthroughreferencevariable
System.out.println(s1.name);
}
}
5/11/2024 Prof.Mithuna H.R,Dept of ISE,AcIT 68
Output:
0
null

Java Program structure:
Javaprogramstructurecontainssixstages.Theyare:
DocumentationSection:Thedocumentationsectioncontainsasetof
commentlinesdescribingabouttheprogram.//or/**/
Packagestatement:ThefirststatementallowedinaJavafileisapackage
statement.Thisstatementdeclaresapackagenameandinformsthe
compilerthattheclassdefinedherebelongtothepackage.
Packagestudent;
Importstatements:Importstatementsinstructthecompilertoloadthe
specificclassbelongstothementionedpackage.
importstudent.test;
5/11/2024 Prof.MithunaH.R,Deptof ISE,AcIT 69

Interfacestatements:Aninterfaceislikeaclassbutincludesagroupof
methoddeceleration.Thisisanoptionalstatement.
Classdefinition:AJavaprogrammaycontainmultipleclassdefinitionThe
classareusedtomaptherealworldobject.
Mainmethodclass:Themainmethodcreatesobjectsofvariousclassesand
establishcommunicationbetweenthem.Onreachingtotheendofmainthe
programterminatesandthecontrolgoesbacktooperatingsystem.
5/11/2024 Prof.Mithuna H.R,Dept of ISE,AcIT 70

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

JavaUser Input (Scanner)
TheScannerclassisusedtogetuserinput,anditisfoundin
thejava.utilpackage.
createanobjectoftheclassanduseanyoftheavailablemethodsfound
intheScannerclassdocumentation.
Scannerisaclassinjava.utilpackageusedforobtainingtheinputof
theprimitivetypeslikeint,double,etc.andstrings.
ItistheeasiestwaytoreadinputinaJavaprogram,thoughnotvery
efficientifyouwantaninputmethodforscenarioswheretimeisa
constraintlikeincompetitiveprogramming.
5/11/2024 75Prof.Mithuna H.R,Dept of ISE,AcIT

TocreateanobjectofScannerclass,weusuallypassthepredefined
objectSystem.in,whichrepresentsthestandardinputstream.Wemay
passanobjectofclassFileifwewanttoreadinputfromafile.
ToreadnumericalvaluesofacertaindatatypeXYZ,thefunctiontouse
isnextXYZ().Forexample,toreadavalueoftypeshort,wecanuse
nextShort()
Toreadstrings,weusenextLine().
Toreadasinglecharacter,weusenext().charAt(0).next()function
returnsthenexttoken/wordintheinputasastringandcharAt(0)
functionreturnsthefirstcharacterinthatstring.
5/11/2024 Prof.Mithuna H.R,Dept of ISE,AcIT 76

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

Variables
Variableisanameofmemorylocation.
Therearethreetypesofvariablesinjava:local,instanceandstatic.
Variableisnameofreservedareaallocatedinmemory.Inotherwords,itis
anameofmemorylocation.Itisacombinationof"vary+able"thatmeans
itsvaluecanbechanged.
Todeclareoneidentifierasavariabletherearecertainrules.Theyare:
Theymustnotbeginwithadigit.
Uppercaseandlowercasearedistinct.
Itshouldnotbeakeyword.
Whitespaceisnotallowed.
5/11/2024 Prof.Mithuna H.R,Dept of ISE,AcIT 83

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

Arrays:
Arrayisacollectionofsimilartypeofelementsthathavecontiguous
memorylocation.
Javaarrayisanobjectthecontainselementsofsimilardatatype.
Itisadatastructurewherewestoresimilarelements.
Wecanstoreonlyfixedsetofelementsinajavaarray.
Arrayinjavaisindexbased,firstelementofthearrayisstoredat0
index.
5/11/2024 Prof.Mithuna H.R,Dept of ISE,AcIT 90

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

Addition of 2 matrices in java
classTestarray5{
publicstaticvoidmain(Stringargs[])
{
//creatingtwomatrices
inta[][]={{1,3,4},{3,4,5}};
intb[][]={{1,3,4},{3,4,5}};
//creatinganothermatrixtostorethesumoftwomatrices
intc[][]=newint[2][3];
//addingandprintingadditionof2matrices
for(inti=0;i<2;i++)
{
for(intj=0;j<3;j++)
{
c[i][j]=a[i][j]+b[i][j];
System.out.print (c[i][j]+"");
}System.out.println ();//newline
}}}
5/11/2024 Prof.Mithuna H.R,Dept of ISE,AcIT 105
Output:2 6 8
6 8 10

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

Example
importjava.util.Scanner;
publicclassIfDemo
{
publicstaticvoidmain(String[]args){
intage;
ScannerinputDevice=newScanner(System.in);
System.out.print("PleaseenterAge:");
age=inputDevice.nextInt();
if(age>18)
System.out.println("above18");
}
5/11/2024 Prof.Mithuna H.R,Dept of ISE,AcIT 109

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

Example
importjava.util.Scanner;
publicclassIfElseDemo
{
publicstaticvoidmain(String[]args)
{
intage;
ScannerinputDevice=newScanner(System.in);
System.out.print("PleaseenterAge:");
age=inputDevice.nextInt();
if(age>=18)
System.out.println("above18");
else
System.out.println("below18");
}
}
5/11/2024 Prof.Mithuna H.R,Dept of ISE,AcIT 111

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

Example
importjava.util.Scanner;
publicclassIfElseIfDemo
{
publicstaticvoidmain(String[]args)
{
intage;
ScannerinputDevice=newScanner(System.in);
System.out.print("PleaseenterAge:");
age=inputDevice.nextInt();
if(age>=18&&age<=35)
System.out.println("between18-35");
elseif(age>35&&age<=60)
System.out.println("between36-60");
else
System.out.println("notmatched");
}
}
5/11/2024 Prof.Mithuna H.R,Dept of ISE,AcIT 113

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

importjava.util.Scanner;
publicclassSwitchDemo
{
publicstaticvoidmain(String[]args)
{
intage;
ScannerinputDevice=newScanner(System.in);
System.out.print("PleaseenterAge:");
age=inputDevice.nextInt();
switch(age)
{
case18:
System.out.println("age18");
break;
case19:
System.out.println("age19");
break;
default:
System.out.println("notmatched");
break;
}}}
5/11/2024 Prof.Mithuna H.R,Dept of ISE,AcIT 115

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

Example:
publicclassWhileDemo
{
publicstaticvoidmain(String[]args)
{
inti=0;
while(i<5)
{
System.out.println("Value::"+i);
i++;
}
}
}
5/11/2024 Prof.Mithuna H.R,Dept of ISE,AcIT 119
OUTPUT:
Value::0
Value::1
Value::2
Value::3
Value::4

The do-while loop
Theonlydifferencebetweenawhileandado-while
loopisthatdo-whileevaluatesitsexpressionatthe
bottomoftheloopinsteadofthetop.Thedo-while
loopexecutesatleastonetimethenitwillcheckthe
expressionpriortothenextiteration.
5/11/2024 Prof.Mithuna H.R,Dept of ISE,AcIT 120

Example:
publicclassDoWhileDemo
{
publicstaticvoidmain(String[]args)
{
inti=0;
do
{
System.out.println("value::"+i);
i++;
}
while(i<5);
}
}
5/11/2024 Prof.Mithuna H.R,Dept of ISE,AcIT 121
OUTPUT:
Value::0
Value::1
Value::2
Value::3
Value::4

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

Theinitializationblockexecutesfirstbeforetheloop
starts.Itisusedtoinitializetheloopvariable.
Theconditionstatementevaluateseverytimepriorto
whenthestatement(thatisusuallybeablock)
executes,iftheconditionistruethenonlythe
statement(thatisusuallyablock)willexecute.
Theincrementordecrementstatementexecutesevery
timeafterthestatement(thatisusuallyablock).
5/11/2024 Prof.Mithuna H.R,Dept of ISE,AcIT 123

Example
publicclassWhileDemo
{
publicstaticvoidmain(String[]args)
{
for(inti=0;i<5;i++)
{
System.out.println("Value::"+i);
}
}}
5/11/2024
OUTPUT:
Value::0
Value::1
Value::2
Value::3
Value::4
124Prof.Mithuna H.R,Dept of ISE,AcIT

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

Itstartswiththekeywordforlikeanormalfor-loop.
Insteadofdeclaringandinitializingaloopcounter
variable,youdeclareavariablethatisthesametypeas
thebasetypeofthearray,followedbyacolon,whichis
thenfollowedbythearrayname.
Intheloopbody,youcanusetheloopvariableyou
createdratherthanusinganindexedarrayelement.
It’scommonlyusedtoiterateoveranarrayora
Collectionsclass(eg,ArrayList)
5/11/2024 126Prof.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

Compile by: javac ForEachExample1.java
Run by: java ForEachExample1
ouput:
12
13
14
44
5/11/2024 129Prof.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

Example:
classForEachExample1
{
publicstaticvoidmain(Stringargs[])
{
intarr[]={12,13,14,44};
inttotal=0;
for(inti:arr)
{
total=total+i;
}
System.out.println("Total:"+total);}}
5/11/2024 132Prof.Mithuna H.R,Dept of ISE,AcIT

Jump Statements
Jumpstatementsareusedtounconditionallytransfer
theprogramcontroltoanotherpartoftheprogram.
Javaprovidesthefollowingjumpstatements:
breakstatement
continuestatement
returnstatement
5/11/2024 133Prof.Mithuna H.R,Dept of ISE,AcIT

Break Statement
Thebreakstatementimmediatelyquitsthecurrent
iterationandgoestothefirststatementfollowingthe
loop.Anotherformofbreakisusedintheswitch
statement.
Thebreakstatementhasthefollowingtwoforms:
LabeledBreakStatement
UnlabeledBreakStatement
5/11/2024 134Prof.Mithuna H.R,Dept of ISE,AcIT

Unlabeled Break Statement:
Thisisusedtojumpprogramcontroloutofthe
specificlooponthespecificcondition.
5/11/2024 135Prof.Mithuna H.R,Dept of ISE,AcIT

Example
publicclassUnLabeledBreakDemo
{
publicstaticvoidmain(String[]args)
{
for(intvar=0;var<5;var++)
{
System.out.println("Varis:"+var);
if(var==3)
break;
}
}}
5/11/2024 136Prof.Mithuna H.R,Dept of ISE,AcIT

CHOOSE CORRECT OUTPUT
A)0,1,2,3
B)0,1,2,3,4
C)0,1,2,3,4,5
D)0,1,2
5/11/2024 137Prof.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

Example
publicclassLabeledBreakDemo
{
publicstaticvoidmain(String[]args)
{
Outer:for(intvar1=0;var1<5;var1++)
{
for(intvar2=1;var2<5;var2++)
{
System.out.println("var1:"+var1+",var2:"+var2);
if(var1==3)
breakOuter;
}
}
}
}
5/11/2024 139Prof.Mithuna H.R,Dept of ISE,AcIT

Find total number of iterations
A)10
B)12
C)13
D)16
5/11/2024 140Prof.Mithuna H.R,Dept of ISE,AcIT

continue statement
Thecontinuestatementisusedwhenyouwantto
continuerunningtheloopwiththenextiterationand
wanttoskiptherestofthestatementsofthebodyfor
thecurrentiteration.
Thecontinuestatementhasthefollowingtwoforms:
LabeledContinueStatement
UnlabeledContinueStatement
UnlabeledContinueStatement:Thisstatementskips
thecurrentiterationoftheinnermostfor,whileand
do-whileloop.
5/11/2024 141Prof.Mithuna H.R,Dept of ISE,AcIT

Example
publicclassUnlabeledContinueDemo
{
publicstaticvoidmain(String[]args)
{
for(intvar1=0;var1<4;var1++)
{
for(intvar2=0;var2<4;var2++)
{
if(var2==2)
continue;
System.out.println("var1:"+var1+",var2:"+var2);
}
}
}
}
5/11/2024 142Prof.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
publicclassLabeledContinueDemo
{
publicstaticvoidmain(String[]args)
{
Outer:for(intvar1=0;var1<5;var1++)
{
for(intvar2=0;var2<5;var2++)
{
if(var2==2)
continueOuter;
System.out.println("var1:"+var1+",var2:"+var2);
}
}
}
}
5/11/2024 145Prof.Mithuna H.R,Dept of ISE,AcIT

Find total number of iterations
A)10
B)12
C)13
D)15
5/11/2024 146Prof.Mithuna H.R,Dept of ISE,AcIT

Return Statement
Thereturnstatementisusedtoimmediatelyquitthe
currentmethodandreturntothecallingmethod.Itis
mandatorytouseareturnstatementfornon-void
methodstoreturnavalue.
5/11/2024 147Prof.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

Java Access Specifiers/Modifiers
PrivateAccessModifier-private:
Methods,VariablesandConstructorsthataredeclared
privatecanonlybeaccessedwithinthedeclaredclassitself.
Privateaccessmodifieristhemostrestrictiveaccesslevel.
Classandinterfacescannotbeprivate.
Usingtheprivatemodifieristhemainwaythatanobject
encapsulatesitselfandhidesdatafromtheoutsideworld.
5/11/2024 159Prof.Mithuna H.R,Dept of ISE,AcIT

Public Access Modifier -public:
Aclass,method,constructor,interfaceetcdeclaredpublic
canbeaccessedfromanyotherclass.Thereforefields,
methods,blocksdeclaredinsideapublicclasscanbe
accessedfromanyclassbelongingtotheJavaUniverse.
Howeverifthepublicclasswearetryingtoaccessisina
differentpackage,thenthepublicclassstillneedtobe
imported.
Becauseofclassinheritance,allpublicmethodsand
variablesofaclassareinheritedbyitssubclasses.
5/11/2024 160Prof.Mithuna H.R,Dept of ISE,AcIT

Protected Access Modifier -protected:
Variables,methodsandconstructorswhichare
declaredprotectedinasuperclasscanbeaccessedonly
bythesubclassesinotherpackageoranyclasswithin
thepackageoftheprotectedmembers'class.
Theprotectedaccessmodifiercannotbeappliedto
classandinterfaces.Methods,fieldscanbedeclared
protected,howevermethodsandfieldsinainterface
cannotbedeclaredprotected.
5/11/2024 161Prof.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