SlideShare a Scribd company logo
1 of 163
What is Java
 Java is a programming language and
a platform.
 Java was developed by Sun Microsystems in
1995
 James Gosling is known as the father of Java.
5/11/2024 2
Prof.Mithuna H.R,Dept of ISE,AcIT
 All java applications are compiled and interpreted.
 It generates byte codes rather than object code.
 Bytecode is 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 3
Prof.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 bytecode helps 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 5
Prof.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 7
Prof.Mithuna H.R,Dept of ISE,AcIT
5/11/2024 8
Prof.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 9
Prof.Mithuna H.R,Dept of ISE,AcIT
Java’s magic: Java Virtual Machine(JVM)
 The Java Virtual Machine (JVM) is an abstract
computer, on which the byte code can be executed.
 Java Virtual Machine (JVM) interprets the byte code
into the machine code depending upon the underlying
operating system and hardware combination.
 JVM does not know anything about Java program
rather it reads the bytecode, interprets the code and
executes the code.
5/11/2024 10
Prof.Mithuna H.R,Dept of ISE,AcIT
 Bytecode Platform Independent vs Java Virtual
Machine (JVM) Platform Dependent:
 JVM is platform dependent that means there are
different implementation of JVM on different OS.
 Java code / Bytecode is always the same on different
OS. That makes java program as platform
independent.
5/11/2024 Prof.Mithuna H.R,Dept of ISE,AcIT 11
5/11/2024 12
Prof.Mithuna H.R,Dept of ISE,AcIT
Java’s Magic – Just in Time (JIT):
 Just in time (JIT) is a part of Java Virtual Machine (JVM)
architecture.
 The job of JIT inside JVM is to compile bytecode into machine
executable code in real time, on a piece-by-piece, demand basis.
5/11/2024 13
Prof.Mithuna H.R,Dept of ISE,AcIT
 When Java programs are executed, JVM does not read
the entire Bytecode and converts it into machine
instructions.
 If JVM tries to do this approach then the program
execution time will be delayed for hours.
5/11/2024 14
Prof.Mithuna H.R,Dept of ISE,AcIT
 Java has overcome the latency of program execution
time by interpreting the required bytecode and keeps
the rest of the code aside.
 Just in time (JIT) helps to compile code that is only
needed and at the same time boost the program
performance.
 Whether the Java programs are interpreted traditional
way or on the fly the functionality and features like
portability and security remains the same.
5/11/2024 Prof.Mithuna H.R,Dept of ISE,AcIT 15
5/11/2024 16
Prof.Mithuna H.R,Dept of ISE,AcIT
Java’s Magic – Java Runtime Environment (JRE):
 Java programs cannot be executed on machine
without the JVM installed on machine.
 Java Runtime Environment (JRE) is software which
we can download and install on the any operating
system like Windows, Mac or Linux.
5/11/2024 17
Prof.Mithuna H.R,Dept of ISE,AcIT
5/11/2024 18
Prof.Mithuna H.R,Dept of ISE,AcIT
 JRE is combination of JVM and Java Application
Programming Interface (Java API).
 Java API is set of tools and libraries that are required by the
JVM to execute the java programs. Java Runtime Environment
provides an environment to execute java programs on the
computer.
 JRE = JVM + Java API’s (like util, math, lang, awt, swing etc)
+ Runtime libraries.
5/11/2024 19
Prof.Mithuna H.R,Dept of ISE,AcIT
•JRE does NOT contain any development tools such as
compiler, debugger, etc. and it is NOT for development
purpose.
5/11/2024 20
Prof.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 21
Prof.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 22
Prof.Mithuna H.R,Dept of ISE,AcIT
Types of Java Applications
 Standalone Application
 Web Application
 Enterprise Application
 Mobile Application
5/11/2024 23
Prof.Mithuna H.R,Dept of ISE,AcIT
5/11/2024 24
Prof.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 25
Prof.Mithuna H.R,Dept of ISE,AcIT
1.Object Oriented:
 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 26
Prof.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 27
Prof.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 28
Prof.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. Platform independent
 Platform independent language means once compiled you can execute the
program on any platform (OS).
 Java is platform independent. Because the Java compiler converts the
source code to bytecode, which is Intermidiate Language.
 Bytecode can be executed on any platform (OS) using JVM( Java Virtual
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 30
Prof.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 31
Prof.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 33
Prof.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:
 Java language and Java Virtual Machine helped in achieving
the goal of “write once; run anywhere, anytime, forever.”
 Changes and upgrades in operating systems, processors and
system resources will not force any changes in Java Programs.
 Bytecode helps Java to achieve portability.
5/11/2024 35
Prof.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
 Java is capable of linking in new class libraries, methods, and
objects.
 It can also link native methods (the functions written in other
languages such as C and C++).
 The Java Virtual Machine(JVM) maintains a lot of runtime
information about the program and the objects in the program.
5/11/2024 37
Prof.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
 Usually a computer language is either compiled or interpreted.
Java combines both this approach and makes it a two-stage
system.
 Compiled: Java enables creation of a cross platform programs
by compiling into an intermediate representation called Java
Bytecode.
 Interpreted: Bytecode is then interpreted, which generates
machine code that can be directly executed by the machine that
provides a Java Virtual machine.

5/11/2024 39
Prof.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’s Hot 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 41
Prof.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 42
Prof.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 44
Prof.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 46
Prof.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 47
Prof.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)
we can develop applications that run on small scale devices like mobile
phones.
5/11/2024 48
Prof.Mithuna H.R,Dept of ISE,AcIT
5/11/2024 49
Prof.Mithuna H.R,Dept of ISE,AcIT
Creating Hello World Example
class Simple{
public static void main(String args[]){
System.out.println("Hello Java");
}
}
5/11/2024 50
Prof.Mithuna H.R,Dept of ISE,AcIT
Compilation Flow
To compile: javac Simple.java
To execute: java Simple
Output: Hello Java
5/11/2024 51
Prof.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().
 class keyword is used to declare a class in java.
 public keyword is an access modifier which represents
visibility, it means it is visible to all.
 static is 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 52
Prof.Mithuna H.R,Dept of ISE,AcIT
 void is the return type of the method, it means it
doesn't return any value.
 main represents startup of the program.
 String[] args is used for command line argument.
 System.out.println() is used print statement.
 To write the simple program, open notepad by start
menu -> All Programs -> Accessories ->
notepad and 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 54
Prof.Mithuna H.R,Dept of ISE,AcIT
5/11/2024 55
Prof.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 56
Prof.Mithuna H.R,Dept of ISE,AcIT
Can you have multiple classes in a
java source file?
5/11/2024 57
Prof.Mithuna H.R,Dept of ISE,AcIT
OOPs (Object-Oriented
Programming System)
 Object
 Class
 Inheritance
 Polymorphism
 Abstraction
 Encapsulation
5/11/2024 58
Prof.Mithuna H.R,Dept of ISE,AcIT
Object
Any entity that has state and behavior is known as an object.
5/11/2024 59
Prof.Mithuna H.R,Dept of ISE,AcIT
Class
 Collection of objects is 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 60
Prof.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 61
Prof.Mithuna H.R,Dept of ISE,AcIT
Polymorphism
If one task is performed in different ways, it is known as
polymorphism
5/11/2024 62
Prof.Mithuna H.R,Dept of ISE,AcIT
Abstraction
 Hiding internal details and showing functionality is
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 63
Prof.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 64
Prof.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 65
Prof.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 Program to illustrate how to define a class and fields
//Defining a Student class.
class Student{
//defining fields
int id;//field or data member or instance variable
String name;
//creating main method inside the Student class
public static void main(String args[]){
//Creating an object or instance
Student s1=new Student();//creating an object of Student
//Printing values of the object
System.out.println(s1.id);//accessing member through reference variable
System.out.println(s1.name);
}
}
5/11/2024 Prof.Mithuna H.R,Dept of ISE,AcIT 68
Output:
0
null
Java Program structure:
Java program structure contains six stages. They are:
 Documentation Section: The documentation section contains a set of
comment lines describing about the program.// or /* */
 Package statement: The first statement allowed in a Java file is a package
statement. This statement declares a package name and informs the
compiler that the class defined here belong to the package.
Package student;
 Import statements: Import statements instruct the compiler to load the
specific class belongs to the mentioned package.
import student.test;
5/11/2024 Prof.Mithuna H.R,Dept of ISE,AcIT 69
 Interface statements: An interface is like a class but includes a group of
method deceleration. This is an optional statement.
 Class definition: A Java program may contain multiple class definition The
class are used to map the real world object.
 Main method class: The main method creates objects of various classes and
establish communication between them. On reaching to the end of main the
program terminates and the control goes back to operating system.
5/11/2024 Prof.Mithuna H.R,Dept of ISE,AcIT 70
Java command line arguments:
 Command line arguments are the parameters that are supplied to the
application program at the time when they are invoked.
 The main() method of Java program will take the command line arguments
as the parameter of the args[ ] variable which is a string array.
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
Java User Input (Scanner)
 The Scanner class is used to get user input, and it is found in
the java.util package.
 create an object of the class and use any of the available methods found
in the Scanner class documentation.
 Scanner is a class in java.util package used for obtaining the input of
the primitive types like int, double, etc. and strings.
 It is the easiest way to read input in a Java program, though not very
efficient if you want an input method for scenarios where time is a
constraint like in competitive programming.
5/11/2024 75
Prof.Mithuna H.R,Dept of ISE,AcIT
 To create an object of Scanner class, we usually pass the predefined
object System.in, which represents the standard input stream. We may
pass an object of class File if we want to read input from a file.
 To read numerical values of a certain data type XYZ, the function to use
is nextXYZ(). For example, to read a value of type short, we can use
nextShort()
 To read strings, we use nextLine().
 To read a single character, we use next().charAt(0). next() function
returns the next token/word in the input as a string and charAt(0)
function returns the first character in that string.
5/11/2024 Prof.Mithuna H.R,Dept of ISE,AcIT 76
User Input from Keyboard
 Accepting keyboard input in Java is done using a Scanner object.
 Consider the following statement
Scanner console = new Scanner(System.in);
 This statement declares a reference variable named console. The
Scanner object is associated with standard input device (System.in).
 To get input from keyboard, you can call methods of Scanner class. For
example in following statment nextInt() method of Scanner takes an
integer and returns to variable x :
 int x = console.nextInt();
5/11/2024 Prof.Mithuna H.R,Dept of ISE,AcIT 77
Input Types
5/11/2024 78
Prof.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:
 Reference variables are created using defined constructors of the
classes.
 They are used to access objects. These variables are declared to be of a
specific type that cannot be changed. For example, Employee, Students
etc.
 Class objects and various types of array variables come under reference
data type.
 Default value of any reference variable is null.
 A reference variable can be used to refer any object of the declared type
or any compatible type.
 Example: Animal animal = new Animal("giraffe");
5/11/2024 Prof.Mithuna H.R,Dept of ISE,AcIT 82
Variables
 Variable is a name of memory location.
 There are three types of variables in java: local, instance and static.
Variable is name of reserved area allocated in memory. In other words, it is
a name of memory location. It is a combination of "vary + able" that means
its value can be changed.
To declare one identifier as a variable there are certain rules. They are:
 They must not begin with a digit.
 Uppercase and lowercase are distinct.
 It should not be a keyword.
 White space is not allowed.
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
class A{
int data=50;//instance variable
static int m=100;//static variable
void method()
{
int n=90;//local variable
}
}//end of class
5/11/2024 Prof.Mithuna H.R,Dept of ISE,AcIT 86
Operators:
 Operator in 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:
 Array is a collection of similar type of elements that have contiguous
memory location.
 Java array is an object the contains elements of similar data type.
 It is a data structure where we store similar elements.
 We can store only fixed set of elements in a java array.
 Array in java is index based, first element of the array is stored at 0
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
To use an array in a program, you must declare a variable to
reference the array, and you must specify the type of array the
variable can reference.
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)
 dataType arrayRefVar[];
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
class Testarray
{
public static void main(String args[])
{
int a[]=new int[5];//declaration an
d instantiation
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
//printing array
for(int i=0;i<a.length;i++)//length is
the property of array
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:
int a[]={33,3,4,5};//declaration, instantiation and initialization
 Let's see the simple example to print this array.
class Testarray1
{
public static void main(String args[])
{
int a[]={33,3,4,5};//declaration, instantiation and initialization
//printing array
for(int i=0;i<a.length;i++)//length is the property of array
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.
class Testarray2
{
static void min(int arr[])
{
int min=arr[0]; //33
for(int i=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
public static void main(String args[])
{
int a[]={33,3,4,5};
min(a);//passing array to method
}
}
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)
 dataType arrayRefVar[][]; (or)
 dataType []arrayRefVar[];
5/11/2024 Prof.Mithuna H.R,Dept of ISE,AcIT 102
 Example to instantiate Multidimensional Array in
java
int[][] arr=new int[3][3];//3 row and 3 column
 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.
class Testarray3
{
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++)
{
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
class Testarray5{
public static void main(String args[])
{
//creating two matrices
int a[][]={{1,3,4},{3,4,5}};
int b[][]={{1,3,4},{3,4,5}};
//creating another matrix to store the sum of two matrices
int c[][]=new int[2][3];
//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];
System.out.print (c[i][j]+" ");
} System.out.println ();//new line
} }}
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 contained statement (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 contained statement 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
import java.util.Scanner;
public class IfDemo
{
public static void main(String[] args) {
int age;
Scanner inputDevice = new Scanner(System.in);
System.out.print("Please enter Age: ");
age = inputDevice.nextInt();
if(age > 18)
System.out.println("above 18 ");
}
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
import java.util.Scanner;
public class IfElseDemo
{
public static void main( String[] args )
{
int age;
Scanner inputDevice = new Scanner( System.in );
System.out.print( "Please enter Age: " );
age = inputDevice.nextInt();
if ( age >= 18 )
System.out.println( "above 18 " );
else
System.out.println( "below 18" );
}
}

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
import java.util.Scanner;
public class IfElseIfDemo
{
public static void main( String[] args )
{
int age;
Scanner inputDevice = new Scanner( System.in );
System.out.print( "Please enter Age: " );
age = inputDevice.nextInt();
if ( age >= 18 && age <=35 )
System.out.println( "between 18-35 " );
else if(age >35 && age <=60)
System.out.println("between 36-60");
else
System.out.println( "not matched" );
}
}
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
import java.util.Scanner;
public class SwitchDemo
{
public static void main( String[] args )
{
int age;
Scanner inputDevice = new Scanner( System.in );
System.out.print( "Please enter Age: " );
age = inputDevice.nextInt();
switch ( age )
{
case 18:
System.out.println( "age 18" );
break;
case 19:
System.out.println( "age 19" );
break;
default:
System.out.println( "not matched" );
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
 Repeating the same code fragment several times until
a specified condition is satisfied is called iteration.
 Iteration statements execute the same set of
instructions until a termination condition is met.
 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
 It continually executes a statement (that is usually be a
block) while a condition is true. The condition must
return a Boolean value.
5/11/2024 118
Prof.Mithuna H.R,Dept of ISE,AcIT
Example:
public class WhileDemo
{
public static void main( String[] args )
{
int i = 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
 The only difference between a while and a do-while
loop is that do-while evaluates its expression at the
bottom of the loop instead of the top. The do-while
loop executes at least one time then it will check the
expression prior to the next iteration.
5/11/2024 Prof.Mithuna H.R,Dept of ISE,AcIT 120
Example:
public class DoWhileDemo
{
public static void main( String[] args )
{
int i = 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
 A for loop executes a statement (that is usually a block)
as long as the Boolean condition evaluates to true. A
for loop is a combination of the three elements
initialization statement, Boolean expression and
increment or decrement statement.
 Syntax:
for(<initialization>;<condition>;<increment or decrement
statement>)
{
<block of code>
}
5/11/2024 Prof.Mithuna H.R,Dept of ISE,AcIT 122
 The initialization block executes first before the loop
starts. It is used to initialize the loop variable.
 The condition statement evaluates every time prior to
when the statement (that is usually be a block)
executes, if the condition is true then only the
statement (that is usually a block) will execute.
 The increment or decrement statement executes every
time after the statement (that is usually a block).
5/11/2024 Prof.Mithuna H.R,Dept of ISE,AcIT 123
Example
public class WhileDemo
{
public static void main( String[] args )
{
for (int i = 0; i < 5;i++ )
{
System.out.println( "Value :: " + i );
}
} }
5/11/2024
OUTPUT:
Value::0
Value::1
Value::2
Value::3
Value::4
124
Prof.Mithuna H.R,Dept of ISE,AcIT
The For each loop
 The Java for-each loop or enhanced for loop is
introduced since J2SE 5.0. It provides an alternative
approach to traverse the array or collection in Java. It is
mainly used to traverse the array or collection
elements.
 For-each is another array traversing technique like for
loop, while loop, do-while loop introduced in Java5.
5/11/2024 125
Prof.Mithuna H.R,Dept of ISE,AcIT
 It starts with the keyword for like a normal for-loop.
 Instead of declaring and initializing a loop counter
variable, you declare a variable that is the same type as
the base type of the array, followed by a colon, which is
then followed by the array name.
 In the loop body, you can use the loop variable you
created rather than using an indexed array element.
 It’s commonly used to iterate over an array or a
Collections class (eg, ArrayList)
5/11/2024 126
Prof.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 127
Prof.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 128
Prof.Mithuna H.R,Dept of ISE,AcIT
 Compile by: javac ForEachExample1.java
 Run by: java ForEachExample1
ouput:
12
13
14
44
5/11/2024 129
Prof.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 130
Prof.Mithuna H.R,Dept of ISE,AcIT
 Drawback of the enhanced for loop
 It cannot traverse the elements in reverse order.
 we do not have the option to skip any element because
it does not work on an index basis. Moreover, we
cannot traverse the odd or even elements only.
 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 131
Prof.Mithuna H.R,Dept of ISE,AcIT
Example:
class ForEachExample1
{
public static void main(String args[])
{
int arr[]={12,13,14,44};
int total=0;
for(int i:arr)
{
total=total+i;
}
System.out.println("Total: "+total); }}
5/11/2024 132
Prof.Mithuna H.R,Dept of ISE,AcIT
Jump Statements
 Jump statements are used to unconditionally transfer
the program control to another part of the program.
 Java provides the following jump statements:
 break statement
 continue statement
 return statement
5/11/2024 133
Prof.Mithuna H.R,Dept of ISE,AcIT
Break Statement
 The break statement immediately quits the current
iteration and goes to the first statement following the
loop. Another form of break is used in the switch
statement.
 The break statement has the following two forms:
 Labeled Break Statement
 Unlabeled Break Statement
5/11/2024 134
Prof.Mithuna H.R,Dept of ISE,AcIT
Unlabeled Break Statement:
 This is used to jump program control out of the
specific loop on the specific condition.
5/11/2024 135
Prof.Mithuna H.R,Dept of ISE,AcIT
Example
public class UnLabeledBreakDemo
{
public static void main( String[] args )
{
for ( int var = 0; var < 5; var++ )
{
System.out.println( "Var is : " + var );
if ( var == 3 )
break;
}
} }
5/11/2024 136
Prof.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 137
Prof.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 138
Prof.Mithuna H.R,Dept of ISE,AcIT
Example
public class LabeledBreakDemo
{
public static void main( String[] args )
{
Outer: for ( int var1 = 0; var1 < 5; var1++ )
{
for ( int var2 = 1; var2 < 5; var2++ )
{
System.out.println( "var1:" + var1 + ", var2:" + var2 );
if ( var1 == 3 )
break Outer;
}
}
}
}
5/11/2024 139
Prof.Mithuna H.R,Dept of ISE,AcIT
Find total number of iterations
 A)10
 B)12
 C)13
 D)16
5/11/2024 140
Prof.Mithuna H.R,Dept of ISE,AcIT
continue statement
 The continue statement is used when you want to
continue running the loop with the next iteration and
want to skip the rest of the statements of the body for
the current iteration.
The continue statement has the following two forms:
 Labeled Continue Statement
 Unlabeled Continue Statement
 Unlabeled Continue Statement: This statement skips
the current iteration of the innermost for, while and
do-while loop.
5/11/2024 141
Prof.Mithuna H.R,Dept of ISE,AcIT
 Example
public class UnlabeledContinueDemo
{
public static void main( String[] args )
{
for ( int var1 = 0; var1 < 4; var1++ )
{
for ( int var2 = 0; var2 < 4; var2++ )
{
if ( var2 == 2 )
continue;
System.out.println( "var1:" + var1 + ", var2:" + var2 );
}
}
}
}
5/11/2024 142
Prof.Mithuna H.R,Dept of ISE,AcIT
Find total number of iterations
 A)10
 B)12
 C)14
 D)16
5/11/2024 143
Prof.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 144
Prof.Mithuna H.R,Dept of ISE,AcIT
Example
public class LabeledContinueDemo
{
public static void main( String[] args )
{
Outer: for ( int var1 = 0; var1 < 5; var1++ )
{
for ( int var2 = 0; var2 < 5; var2++ )
{
if ( var2 == 2 )
continue Outer;
System.out.println( "var1:" + var1 + ", var2:" + var2 );
}
}
}
}
5/11/2024 145
Prof.Mithuna H.R,Dept of ISE,AcIT
Find total number of iterations
 A)10
 B)12
 C)13
 D)15
5/11/2024 146
Prof.Mithuna H.R,Dept of ISE,AcIT
Return Statement
 The return statement is used to immediately quit the
current method and return to the calling method. It is
mandatory to use a return statement for non-void
methods to return a value.
5/11/2024 147
Prof.Mithuna H.R,Dept of ISE,AcIT
Example
public class ReturnDemo
{
public static void main( String[] args )
{
ReturnDemo returnDemo = new ReturnDemo();
System.out.println( "No : " + returnDemo.returnCall() );
}
int returnCall()
{
return 5;
}
}
5/11/2024 148
Prof.Mithuna H.R,Dept of ISE,AcIT
Type Casting in Java
 Assigning a value of one type to a variable of another
type is known as Type Casting.
 Java object typecasting one object reference can be
type cast into another object reference.
 The cast can be to its own class type or to one of its
subclass or superclass types or interfaces.
 There are compile-time rules and runtime rules for
casting in java.
5/11/2024 149
Prof.Mithuna H.R,Dept of ISE,AcIT
 Example in Java
int x = 10;
byte y = (byte)x;
5/11/2024 150
Prof.Mithuna H.R,Dept of ISE,AcIT
 In Java, type casting is classified into two types,
1)Widening Casting(Implicit)
5/11/2024 151
Prof.Mithuna H.R,Dept of ISE,AcIT
2) Narrowing Casting(Explicitly done)
5/11/2024 152
Prof.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 153
Prof.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 154
Prof.Mithuna H.R,Dept of ISE,AcIT
 Output :
Int value 100
Long value 100
Float value 100.0
5/11/2024 155
Prof.Mithuna H.R,Dept of ISE,AcIT
Narrowing or Explicit type conversion
 When you are assigning a larger type value to a
variable of smaller type, then you need to perform
explicit type casting.
5/11/2024 156
Prof.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 157
Prof.Mithuna H.R,Dept of ISE,AcIT
 Output :
Double value 100.04
Long value 100
Int value 100
5/11/2024 158
Prof.Mithuna H.R,Dept of ISE,AcIT
Java Access Specifiers/Modifiers
 Private Access Modifier - private:
 Methods, Variables and Constructors that are declared
private can only be accessed within the declared class itself.
 Private access modifier is the most restrictive access level.
Class and interfaces cannot be private.
 Using the private modifier is the main way that an object
encapsulates itself and hides data from the outside world.
5/11/2024 159
Prof.Mithuna H.R,Dept of ISE,AcIT
 Public Access Modifier - public:
 A class, method, constructor, interface etc declared public
can be accessed from any other class. Therefore fields,
methods, blocks declared inside a public class can be
accessed from any class belonging to the Java Universe.
 However if the public class we are trying to access is in a
different package, then the public class still need to be
imported.
 Because of class inheritance, all public methods and
variables of a class are inherited by its subclasses.
5/11/2024 160
Prof.Mithuna H.R,Dept of ISE,AcIT
 Protected Access Modifier - protected:
 Variables, methods and constructors which are
declared protected in a superclass can be accessed only
by the subclasses in other package or any class within
the package of the protected members' class.
 The protected access modifier cannot be applied to
class and interfaces. Methods, fields can be declared
protected, however methods and fields in a interface
cannot be declared protected.
5/11/2024 161
Prof.Mithuna H.R,Dept of ISE,AcIT
Default Access Modifier - No keyword:
 Default access modifier means we do not explicitly
declare an access modifier for a class, field, method,
etc.A variable or method declared without any access
control
5/11/2024 162
Prof.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 163
Prof.Mithuna H.R,Dept of ISE,AcIT

More Related Content

Similar to Java for beginners in java and want to write vtu exams

TechSearchWeb.pdf
TechSearchWeb.pdfTechSearchWeb.pdf
TechSearchWeb.pdf
TechSearchWeb
 
Technology Tutorial.pdf
Technology Tutorial.pdfTechnology Tutorial.pdf
Technology Tutorial.pdf
TechSearchWeb
 
Java Basic.pdf
Java Basic.pdfJava Basic.pdf
Java Basic.pdf
TechSearchWeb
 

Similar to Java for beginners in java and want to write vtu exams (20)

Core Java-1 (1).pdf
Core Java-1 (1).pdfCore Java-1 (1).pdf
Core Java-1 (1).pdf
 
TechSearchWeb.pdf
TechSearchWeb.pdfTechSearchWeb.pdf
TechSearchWeb.pdf
 
Technology Tutorial.pdf
Technology Tutorial.pdfTechnology Tutorial.pdf
Technology Tutorial.pdf
 
TechSearchWeb Tutorials.pdf
TechSearchWeb Tutorials.pdfTechSearchWeb Tutorials.pdf
TechSearchWeb Tutorials.pdf
 
Java Lecture 1
Java Lecture 1Java Lecture 1
Java Lecture 1
 
Java Programming : introduction
Java Programming : introductionJava Programming : introduction
Java Programming : introduction
 
Inside JVM
Inside JVMInside JVM
Inside JVM
 
java course in chandigarh...
java    course     in      chandigarh...java    course     in      chandigarh...
java course in chandigarh...
 
JAVA PROGRAMMING-Unit I - Final PPT.pptx
JAVA PROGRAMMING-Unit I - Final PPT.pptxJAVA PROGRAMMING-Unit I - Final PPT.pptx
JAVA PROGRAMMING-Unit I - Final PPT.pptx
 
Java Basic.pdf
Java Basic.pdfJava Basic.pdf
Java Basic.pdf
 
BIT211.pdf
BIT211.pdfBIT211.pdf
BIT211.pdf
 
0f0cef_1dac552af56c4338ab0672859199e693.pdf
0f0cef_1dac552af56c4338ab0672859199e693.pdf0f0cef_1dac552af56c4338ab0672859199e693.pdf
0f0cef_1dac552af56c4338ab0672859199e693.pdf
 
Java session2
Java session2Java session2
Java session2
 
JAVA CORE
JAVA COREJAVA CORE
JAVA CORE
 
CORE JAVA
CORE JAVACORE JAVA
CORE JAVA
 
Java and its features
Java and its featuresJava and its features
Java and its features
 
Java training in chennai, Java course in chennai
Java training in chennai, Java course in chennaiJava training in chennai, Java course in chennai
Java training in chennai, Java course in chennai
 
tranning synopsis(java programming).pdf
tranning synopsis(java programming).pdftranning synopsis(java programming).pdf
tranning synopsis(java programming).pdf
 
50120140507001
5012014050700150120140507001
50120140507001
 
50120140507001 2
50120140507001 250120140507001 2
50120140507001 2
 

Recently uploaded

Structuring Teams and Portfolios for Success
Structuring Teams and Portfolios for SuccessStructuring Teams and Portfolios for Success
Structuring Teams and Portfolios for Success
UXDXConf
 

Recently uploaded (20)

ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...
ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...
ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...
 
Extensible Python: Robustness through Addition - PyCon 2024
Extensible Python: Robustness through Addition - PyCon 2024Extensible Python: Robustness through Addition - PyCon 2024
Extensible Python: Robustness through Addition - PyCon 2024
 
FDO for Camera, Sensor and Networking Device – Commercial Solutions from VinC...
FDO for Camera, Sensor and Networking Device – Commercial Solutions from VinC...FDO for Camera, Sensor and Networking Device – Commercial Solutions from VinC...
FDO for Camera, Sensor and Networking Device – Commercial Solutions from VinC...
 
Syngulon - Selection technology May 2024.pdf
Syngulon - Selection technology May 2024.pdfSyngulon - Selection technology May 2024.pdf
Syngulon - Selection technology May 2024.pdf
 
Custom Approval Process: A New Perspective, Pavel Hrbacek & Anindya Halder
Custom Approval Process: A New Perspective, Pavel Hrbacek & Anindya HalderCustom Approval Process: A New Perspective, Pavel Hrbacek & Anindya Halder
Custom Approval Process: A New Perspective, Pavel Hrbacek & Anindya Halder
 
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptxUnpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
Unpacking Value Delivery - Agile Oxford Meetup - May 2024.pptx
 
Simplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdf
Simplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdfSimplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdf
Simplified FDO Manufacturing Flow with TPMs _ Liam at Infineon.pdf
 
ECS 2024 Teams Premium - Pretty Secure
ECS 2024   Teams Premium - Pretty SecureECS 2024   Teams Premium - Pretty Secure
ECS 2024 Teams Premium - Pretty Secure
 
Where to Learn More About FDO _ Richard at FIDO Alliance.pdf
Where to Learn More About FDO _ Richard at FIDO Alliance.pdfWhere to Learn More About FDO _ Richard at FIDO Alliance.pdf
Where to Learn More About FDO _ Richard at FIDO Alliance.pdf
 
10 Differences between Sales Cloud and CPQ, Blanka Doktorová
10 Differences between Sales Cloud and CPQ, Blanka Doktorová10 Differences between Sales Cloud and CPQ, Blanka Doktorová
10 Differences between Sales Cloud and CPQ, Blanka Doktorová
 
A Business-Centric Approach to Design System Strategy
A Business-Centric Approach to Design System StrategyA Business-Centric Approach to Design System Strategy
A Business-Centric Approach to Design System Strategy
 
The Metaverse: Are We There Yet?
The  Metaverse:    Are   We  There  Yet?The  Metaverse:    Are   We  There  Yet?
The Metaverse: Are We There Yet?
 
How Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdf
How Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdfHow Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdf
How Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdf
 
What's New in Teams Calling, Meetings and Devices April 2024
What's New in Teams Calling, Meetings and Devices April 2024What's New in Teams Calling, Meetings and Devices April 2024
What's New in Teams Calling, Meetings and Devices April 2024
 
Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdf
Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdfIntroduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdf
Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdf
 
IESVE for Early Stage Design and Planning
IESVE for Early Stage Design and PlanningIESVE for Early Stage Design and Planning
IESVE for Early Stage Design and Planning
 
Strategic AI Integration in Engineering Teams
Strategic AI Integration in Engineering TeamsStrategic AI Integration in Engineering Teams
Strategic AI Integration in Engineering Teams
 
Structuring Teams and Portfolios for Success
Structuring Teams and Portfolios for SuccessStructuring Teams and Portfolios for Success
Structuring Teams and Portfolios for Success
 
Demystifying gRPC in .Net by John Staveley
Demystifying gRPC in .Net by John StaveleyDemystifying gRPC in .Net by John Staveley
Demystifying gRPC in .Net by John Staveley
 
THE BEST IPTV in GERMANY for 2024: IPTVreel
THE BEST IPTV in  GERMANY for 2024: IPTVreelTHE BEST IPTV in  GERMANY for 2024: IPTVreel
THE BEST IPTV in GERMANY for 2024: IPTVreel
 

Java for beginners in java and want to write vtu exams

  • 1.
  • 2. What is Java  Java is a programming language and a platform.  Java was developed by Sun Microsystems in 1995  James Gosling is known as the father of Java. 5/11/2024 2 Prof.Mithuna H.R,Dept of ISE,AcIT
  • 3.  All java applications are compiled and interpreted.  It generates byte codes rather than object code.  Bytecode is 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 3 Prof.Mithuna H.R,Dept of ISE,AcIT
  • 4.  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 bytecode helps 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
  • 5.  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 5 Prof.Mithuna H.R,Dept of ISE,AcIT
  • 6.  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
  • 9.  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 9 Prof.Mithuna H.R,Dept of ISE,AcIT
  • 10. Java’s magic: Java Virtual Machine(JVM)  The Java Virtual Machine (JVM) is an abstract computer, on which the byte code can be executed.  Java Virtual Machine (JVM) interprets the byte code into the machine code depending upon the underlying operating system and hardware combination.  JVM does not know anything about Java program rather it reads the bytecode, interprets the code and executes the code. 5/11/2024 10 Prof.Mithuna H.R,Dept of ISE,AcIT
  • 11.  Bytecode Platform Independent vs Java Virtual Machine (JVM) Platform Dependent:  JVM is platform dependent that means there are different implementation of JVM on different OS.  Java code / Bytecode is always the same on different OS. That makes java program as platform independent. 5/11/2024 Prof.Mithuna H.R,Dept of ISE,AcIT 11
  • 13. Java’s Magic – Just in Time (JIT):  Just in time (JIT) is a part of Java Virtual Machine (JVM) architecture.  The job of JIT inside JVM is to compile bytecode into machine executable code in real time, on a piece-by-piece, demand basis. 5/11/2024 13 Prof.Mithuna H.R,Dept of ISE,AcIT
  • 14.  When Java programs are executed, JVM does not read the entire Bytecode and converts it into machine instructions.  If JVM tries to do this approach then the program execution time will be delayed for hours. 5/11/2024 14 Prof.Mithuna H.R,Dept of ISE,AcIT
  • 15.  Java has overcome the latency of program execution time by interpreting the required bytecode and keeps the rest of the code aside.  Just in time (JIT) helps to compile code that is only needed and at the same time boost the program performance.  Whether the Java programs are interpreted traditional way or on the fly the functionality and features like portability and security remains the same. 5/11/2024 Prof.Mithuna H.R,Dept of ISE,AcIT 15
  • 17. Java’s Magic – Java Runtime Environment (JRE):  Java programs cannot be executed on machine without the JVM installed on machine.  Java Runtime Environment (JRE) is software which we can download and install on the any operating system like Windows, Mac or Linux. 5/11/2024 17 Prof.Mithuna H.R,Dept of ISE,AcIT
  • 19.  JRE is combination of JVM and Java Application Programming Interface (Java API).  Java API is set of tools and libraries that are required by the JVM to execute the java programs. Java Runtime Environment provides an environment to execute java programs on the computer.  JRE = JVM + Java API’s (like util, math, lang, awt, swing etc) + Runtime libraries. 5/11/2024 19 Prof.Mithuna H.R,Dept of ISE,AcIT
  • 20. •JRE does NOT contain any development tools such as compiler, debugger, etc. and it is NOT for development purpose. 5/11/2024 20 Prof.Mithuna H.R,Dept of ISE,AcIT
  • 21. 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 21 Prof.Mithuna H.R,Dept of ISE,AcIT
  • 22. 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 22 Prof.Mithuna H.R,Dept of ISE,AcIT
  • 23. Types of Java Applications  Standalone Application  Web Application  Enterprise Application  Mobile Application 5/11/2024 23 Prof.Mithuna H.R,Dept of ISE,AcIT
  • 25. 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 25 Prof.Mithuna H.R,Dept of ISE,AcIT
  • 26. 1.Object Oriented:  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 26 Prof.Mithuna H.R,Dept of ISE,AcIT
  • 27. 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 27 Prof.Mithuna H.R,Dept of ISE,AcIT
  • 28. 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 28 Prof.Mithuna H.R,Dept of ISE,AcIT
  • 29.  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
  • 30. 4. Platform independent  Platform independent language means once compiled you can execute the program on any platform (OS).  Java is platform independent. Because the Java compiler converts the source code to bytecode, which is Intermidiate Language.  Bytecode can be executed on any platform (OS) using JVM( Java Virtual 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 30 Prof.Mithuna H.R,Dept of ISE,AcIT
  • 31. 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 31 Prof.Mithuna H.R,Dept of ISE,AcIT
  • 32.  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
  • 33. 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 33 Prof.Mithuna H.R,Dept of ISE,AcIT
  • 34.  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
  • 35. 7. Architecture neutral:  Java language and Java Virtual Machine helped in achieving the goal of “write once; run anywhere, anytime, forever.”  Changes and upgrades in operating systems, processors and system resources will not force any changes in Java Programs.  Bytecode helps Java to achieve portability. 5/11/2024 35 Prof.Mithuna H.R,Dept of ISE,AcIT
  • 36.  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
  • 37. 8. Dynamic  Java is capable of linking in new class libraries, methods, and objects.  It can also link native methods (the functions written in other languages such as C and C++).  The Java Virtual Machine(JVM) maintains a lot of runtime information about the program and the objects in the program. 5/11/2024 37 Prof.Mithuna H.R,Dept of ISE,AcIT
  • 38.  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
  • 39. 9. Interpreted  Usually a computer language is either compiled or interpreted. Java combines both this approach and makes it a two-stage system.  Compiled: Java enables creation of a cross platform programs by compiling into an intermediate representation called Java Bytecode.  Interpreted: Bytecode is then interpreted, which generates machine code that can be directly executed by the machine that provides a Java Virtual machine.  5/11/2024 39 Prof.Mithuna H.R,Dept of ISE,AcIT
  • 40.  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’s Hot 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
  • 41. 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 41 Prof.Mithuna H.R,Dept of ISE,AcIT
  • 42. 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 42 Prof.Mithuna H.R,Dept of ISE,AcIT
  • 43.  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
  • 44. 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 44 Prof.Mithuna H.R,Dept of ISE,AcIT
  • 45.  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
  • 46. 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 46 Prof.Mithuna H.R,Dept of ISE,AcIT
  • 47. 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 47 Prof.Mithuna H.R,Dept of ISE,AcIT
  • 48. 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) we can develop applications that run on small scale devices like mobile phones. 5/11/2024 48 Prof.Mithuna H.R,Dept of ISE,AcIT
  • 50. Creating Hello World Example class Simple{ public static void main(String args[]){ System.out.println("Hello Java"); } } 5/11/2024 50 Prof.Mithuna H.R,Dept of ISE,AcIT
  • 51. Compilation Flow To compile: javac Simple.java To execute: java Simple Output: Hello Java 5/11/2024 51 Prof.Mithuna H.R,Dept of ISE,AcIT
  • 52. Understanding first java program  Let's see what is the meaning of class, public, static, void, main, String[], System.out.println().  class keyword is used to declare a class in java.  public keyword is an access modifier which represents visibility, it means it is visible to all.  static is 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 52 Prof.Mithuna H.R,Dept of ISE,AcIT
  • 53.  void is the return type of the method, it means it doesn't return any value.  main represents startup of the program.  String[] args is used for command line argument.  System.out.println() is used print statement.  To write the simple program, open notepad by start menu -> All Programs -> Accessories -> notepad and write simple program as displayed below: 5/11/2024 Prof.Mithuna H.R,Dept of ISE,AcIT 53
  • 54. 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 54 Prof.Mithuna H.R,Dept of ISE,AcIT
  • 56. 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 56 Prof.Mithuna H.R,Dept of ISE,AcIT
  • 57. Can you have multiple classes in a java source file? 5/11/2024 57 Prof.Mithuna H.R,Dept of ISE,AcIT
  • 58. OOPs (Object-Oriented Programming System)  Object  Class  Inheritance  Polymorphism  Abstraction  Encapsulation 5/11/2024 58 Prof.Mithuna H.R,Dept of ISE,AcIT
  • 59. Object Any entity that has state and behavior is known as an object. 5/11/2024 59 Prof.Mithuna H.R,Dept of ISE,AcIT
  • 60. Class  Collection of objects is 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 60 Prof.Mithuna H.R,Dept of ISE,AcIT
  • 61. 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 61 Prof.Mithuna H.R,Dept of ISE,AcIT
  • 62. Polymorphism If one task is performed in different ways, it is known as polymorphism 5/11/2024 62 Prof.Mithuna H.R,Dept of ISE,AcIT
  • 63. Abstraction  Hiding internal details and showing functionality is 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 63 Prof.Mithuna H.R,Dept of ISE,AcIT
  • 64. 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 64 Prof.Mithuna H.R,Dept of ISE,AcIT
  • 65. 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 65 Prof.Mithuna H.R,Dept of ISE,AcIT
  • 66. 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
  • 67. 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
  • 68. //Java Program to illustrate how to define a class and fields //Defining a Student class. class Student{ //defining fields int id;//field or data member or instance variable String name; //creating main method inside the Student class public static void main(String args[]){ //Creating an object or instance Student s1=new Student();//creating an object of Student //Printing values of the object System.out.println(s1.id);//accessing member through reference variable System.out.println(s1.name); } } 5/11/2024 Prof.Mithuna H.R,Dept of ISE,AcIT 68 Output: 0 null
  • 69. Java Program structure: Java program structure contains six stages. They are:  Documentation Section: The documentation section contains a set of comment lines describing about the program.// or /* */  Package statement: The first statement allowed in a Java file is a package statement. This statement declares a package name and informs the compiler that the class defined here belong to the package. Package student;  Import statements: Import statements instruct the compiler to load the specific class belongs to the mentioned package. import student.test; 5/11/2024 Prof.Mithuna H.R,Dept of ISE,AcIT 69
  • 70.  Interface statements: An interface is like a class but includes a group of method deceleration. This is an optional statement.  Class definition: A Java program may contain multiple class definition The class are used to map the real world object.  Main method class: The main method creates objects of various classes and establish communication between them. On reaching to the end of main the program terminates and the control goes back to operating system. 5/11/2024 Prof.Mithuna H.R,Dept of ISE,AcIT 70
  • 71. Java command line arguments:  Command line arguments are the parameters that are supplied to the application program at the time when they are invoked.  The main() method of Java program will take the command line arguments as the parameter of the args[ ] variable which is a string array. 5/11/2024 Prof.Mithuna H.R,Dept of ISE,AcIT 71
  • 72.  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
  • 73. 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
  • 74. 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
  • 75. Java User Input (Scanner)  The Scanner class is used to get user input, and it is found in the java.util package.  create an object of the class and use any of the available methods found in the Scanner class documentation.  Scanner is a class in java.util package used for obtaining the input of the primitive types like int, double, etc. and strings.  It is the easiest way to read input in a Java program, though not very efficient if you want an input method for scenarios where time is a constraint like in competitive programming. 5/11/2024 75 Prof.Mithuna H.R,Dept of ISE,AcIT
  • 76.  To create an object of Scanner class, we usually pass the predefined object System.in, which represents the standard input stream. We may pass an object of class File if we want to read input from a file.  To read numerical values of a certain data type XYZ, the function to use is nextXYZ(). For example, to read a value of type short, we can use nextShort()  To read strings, we use nextLine().  To read a single character, we use next().charAt(0). next() function returns the next token/word in the input as a string and charAt(0) function returns the first character in that string. 5/11/2024 Prof.Mithuna H.R,Dept of ISE,AcIT 76
  • 77. User Input from Keyboard  Accepting keyboard input in Java is done using a Scanner object.  Consider the following statement Scanner console = new Scanner(System.in);  This statement declares a reference variable named console. The Scanner object is associated with standard input device (System.in).  To get input from keyboard, you can call methods of Scanner class. For example in following statment nextInt() method of Scanner takes an integer and returns to variable x :  int x = console.nextInt(); 5/11/2024 Prof.Mithuna H.R,Dept of ISE,AcIT 77
  • 79. 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
  • 80. Types of data types 5/11/2024 Prof.Mithuna H.R,Dept of ISE,AcIT 80
  • 82. Reference Data types:  Reference variables are created using defined constructors of the classes.  They are used to access objects. These variables are declared to be of a specific type that cannot be changed. For example, Employee, Students etc.  Class objects and various types of array variables come under reference data type.  Default value of any reference variable is null.  A reference variable can be used to refer any object of the declared type or any compatible type.  Example: Animal animal = new Animal("giraffe"); 5/11/2024 Prof.Mithuna H.R,Dept of ISE,AcIT 82
  • 83. Variables  Variable is a name of memory location.  There are three types of variables in java: local, instance and static. Variable is name of reserved area allocated in memory. In other words, it is a name of memory location. It is a combination of "vary + able" that means its value can be changed. To declare one identifier as a variable there are certain rules. They are:  They must not begin with a digit.  Uppercase and lowercase are distinct.  It should not be a keyword.  White space is not allowed. 5/11/2024 Prof.Mithuna H.R,Dept of ISE,AcIT 83
  • 84. 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
  • 85.  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
  • 86.  Example to understand the types of variables in java class A{ int data=50;//instance variable static int m=100;//static variable void method() { int n=90;//local variable } }//end of class 5/11/2024 Prof.Mithuna H.R,Dept of ISE,AcIT 86
  • 87. Operators:  Operator in 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
  • 88. 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
  • 89. 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
  • 90. Arrays:  Array is a collection of similar type of elements that have contiguous memory location.  Java array is an object the contains elements of similar data type.  It is a data structure where we store similar elements.  We can store only fixed set of elements in a java array.  Array in java is index based, first element of the array is stored at 0 index. 5/11/2024 Prof.Mithuna H.R,Dept of ISE,AcIT 90
  • 91. 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.
  • 92. 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 To use an array in a program, you must declare a variable to reference the array, and you must specify the type of array the variable can reference. 5/11/2024 Prof.Mithuna H.R,Dept of ISE,AcIT 92
  • 93. 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)  dataType arrayRefVar[]; 5/11/2024 Prof.Mithuna H.R,Dept of ISE,AcIT 93
  • 94.  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
  • 95. 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
  • 96.  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
  • 97.  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
  • 99. Example of single dimensional java array class Testarray { public static void main(String args[]) { int a[]=new int[5];//declaration an d instantiation 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 //printing array for(int i=0;i<a.length;i++)//length is the property of array System.out.println(a[i]); } } Output: 10 20 70 40 50
  • 100.  Declaration, Instantiation and Initialization of Java Array  We can declare, instantiate and initialize the java array together by: int a[]={33,3,4,5};//declaration, instantiation and initialization  Let's see the simple example to print this array. class Testarray1 { public static void main(String args[]) { int a[]={33,3,4,5};//declaration, instantiation and initialization //printing array for(int i=0;i<a.length;i++)//length is the property of array System.out.println(a[i]); } } 5/11/2024 Prof.Mithuna H.R,Dept of ISE,AcIT 100
  • 101. 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. class Testarray2 { static void min(int arr[]) { int min=arr[0]; //33 for(int i=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 public static void main(String args[]) { int a[]={33,3,4,5}; min(a);//passing array to method } } Output:3
  • 102. 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)  dataType arrayRefVar[][]; (or)  dataType []arrayRefVar[]; 5/11/2024 Prof.Mithuna H.R,Dept of ISE,AcIT 102
  • 103.  Example to instantiate Multidimensional Array in java int[][] arr=new int[3][3];//3 row and 3 column  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
  • 104.  Example of Multidimensional java array Let's see the simple example to declare, instantiate, initialize and print the 2Dimensional array. class Testarray3 { 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++) { 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
  • 105.  Addition of 2 matrices in java class Testarray5{ public static void main(String args[]) { //creating two matrices int a[][]={{1,3,4},{3,4,5}}; int b[][]={{1,3,4},{3,4,5}}; //creating another matrix to store the sum of two matrices int c[][]=new int[2][3]; //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]; System.out.print (c[i][j]+" "); } System.out.println ();//new line } }} 5/11/2024 Prof.Mithuna H.R,Dept of ISE,AcIT 105 Output:2 6 8 6 8 10
  • 106. 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
  • 107.  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
  • 108. If Statements  The first contained statement (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 contained statement 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
  • 109.  Example import java.util.Scanner; public class IfDemo { public static void main(String[] args) { int age; Scanner inputDevice = new Scanner(System.in); System.out.print("Please enter Age: "); age = inputDevice.nextInt(); if(age > 18) System.out.println("above 18 "); } 5/11/2024 Prof.Mithuna H.R,Dept of ISE,AcIT 109
  • 110. 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
  • 111. Example import java.util.Scanner; public class IfElseDemo { public static void main( String[] args ) { int age; Scanner inputDevice = new Scanner( System.in ); System.out.print( "Please enter Age: " ); age = inputDevice.nextInt(); if ( age >= 18 ) System.out.println( "above 18 " ); else System.out.println( "below 18" ); } }  5/11/2024 Prof.Mithuna H.R,Dept of ISE,AcIT 111
  • 112. 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
  • 113. Example import java.util.Scanner; public class IfElseIfDemo { public static void main( String[] args ) { int age; Scanner inputDevice = new Scanner( System.in ); System.out.print( "Please enter Age: " ); age = inputDevice.nextInt(); if ( age >= 18 && age <=35 ) System.out.println( "between 18-35 " ); else if(age >35 && age <=60) System.out.println("between 36-60"); else System.out.println( "not matched" ); } } 5/11/2024 Prof.Mithuna H.R,Dept of ISE,AcIT 113
  • 114. 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
  • 115. import java.util.Scanner; public class SwitchDemo { public static void main( String[] args ) { int age; Scanner inputDevice = new Scanner( System.in ); System.out.print( "Please enter Age: " ); age = inputDevice.nextInt(); switch ( age ) { case 18: System.out.println( "age 18" ); break; case 19: System.out.println( "age 19" ); break; default: System.out.println( "not matched" ); break; } } } 5/11/2024 Prof.Mithuna H.R,Dept of ISE,AcIT 115
  • 116.  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
  • 117. Iteration Statements  Repeating the same code fragment several times until a specified condition is satisfied is called iteration.  Iteration statements execute the same set of instructions until a termination condition is met.  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
  • 118. The while loop  It continually executes a statement (that is usually be a block) while a condition is true. The condition must return a Boolean value. 5/11/2024 118 Prof.Mithuna H.R,Dept of ISE,AcIT
  • 119. Example: public class WhileDemo { public static void main( String[] args ) { int i = 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
  • 120. The do-while loop  The only difference between a while and a do-while loop is that do-while evaluates its expression at the bottom of the loop instead of the top. The do-while loop executes at least one time then it will check the expression prior to the next iteration. 5/11/2024 Prof.Mithuna H.R,Dept of ISE,AcIT 120
  • 121. Example: public class DoWhileDemo { public static void main( String[] args ) { int i = 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
  • 122. The for loop  A for loop executes a statement (that is usually a block) as long as the Boolean condition evaluates to true. A for loop is a combination of the three elements initialization statement, Boolean expression and increment or decrement statement.  Syntax: for(<initialization>;<condition>;<increment or decrement statement>) { <block of code> } 5/11/2024 Prof.Mithuna H.R,Dept of ISE,AcIT 122
  • 123.  The initialization block executes first before the loop starts. It is used to initialize the loop variable.  The condition statement evaluates every time prior to when the statement (that is usually be a block) executes, if the condition is true then only the statement (that is usually a block) will execute.  The increment or decrement statement executes every time after the statement (that is usually a block). 5/11/2024 Prof.Mithuna H.R,Dept of ISE,AcIT 123
  • 124. Example public class WhileDemo { public static void main( String[] args ) { for (int i = 0; i < 5;i++ ) { System.out.println( "Value :: " + i ); } } } 5/11/2024 OUTPUT: Value::0 Value::1 Value::2 Value::3 Value::4 124 Prof.Mithuna H.R,Dept of ISE,AcIT
  • 125. The For each loop  The Java for-each loop or enhanced for loop is introduced since J2SE 5.0. It provides an alternative approach to traverse the array or collection in Java. It is mainly used to traverse the array or collection elements.  For-each is another array traversing technique like for loop, while loop, do-while loop introduced in Java5. 5/11/2024 125 Prof.Mithuna H.R,Dept of ISE,AcIT
  • 126.  It starts with the keyword for like a normal for-loop.  Instead of declaring and initializing a loop counter variable, you declare a variable that is the same type as the base type of the array, followed by a colon, which is then followed by the array name.  In the loop body, you can use the loop variable you created rather than using an indexed array element.  It’s commonly used to iterate over an array or a Collections class (eg, ArrayList) 5/11/2024 126 Prof.Mithuna H.R,Dept of ISE,AcIT
  • 127. 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 127 Prof.Mithuna H.R,Dept of ISE,AcIT
  • 128. 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 128 Prof.Mithuna H.R,Dept of ISE,AcIT
  • 129.  Compile by: javac ForEachExample1.java  Run by: java ForEachExample1 ouput: 12 13 14 44 5/11/2024 129 Prof.Mithuna H.R,Dept of ISE,AcIT
  • 130. 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 130 Prof.Mithuna H.R,Dept of ISE,AcIT
  • 131.  Drawback of the enhanced for loop  It cannot traverse the elements in reverse order.  we do not have the option to skip any element because it does not work on an index basis. Moreover, we cannot traverse the odd or even elements only.  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 131 Prof.Mithuna H.R,Dept of ISE,AcIT
  • 132. Example: class ForEachExample1 { public static void main(String args[]) { int arr[]={12,13,14,44}; int total=0; for(int i:arr) { total=total+i; } System.out.println("Total: "+total); }} 5/11/2024 132 Prof.Mithuna H.R,Dept of ISE,AcIT
  • 133. Jump Statements  Jump statements are used to unconditionally transfer the program control to another part of the program.  Java provides the following jump statements:  break statement  continue statement  return statement 5/11/2024 133 Prof.Mithuna H.R,Dept of ISE,AcIT
  • 134. Break Statement  The break statement immediately quits the current iteration and goes to the first statement following the loop. Another form of break is used in the switch statement.  The break statement has the following two forms:  Labeled Break Statement  Unlabeled Break Statement 5/11/2024 134 Prof.Mithuna H.R,Dept of ISE,AcIT
  • 135. Unlabeled Break Statement:  This is used to jump program control out of the specific loop on the specific condition. 5/11/2024 135 Prof.Mithuna H.R,Dept of ISE,AcIT
  • 136. Example public class UnLabeledBreakDemo { public static void main( String[] args ) { for ( int var = 0; var < 5; var++ ) { System.out.println( "Var is : " + var ); if ( var == 3 ) break; } } } 5/11/2024 136 Prof.Mithuna H.R,Dept of ISE,AcIT
  • 137. 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 137 Prof.Mithuna H.R,Dept of ISE,AcIT
  • 138. 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 138 Prof.Mithuna H.R,Dept of ISE,AcIT
  • 139. Example public class LabeledBreakDemo { public static void main( String[] args ) { Outer: for ( int var1 = 0; var1 < 5; var1++ ) { for ( int var2 = 1; var2 < 5; var2++ ) { System.out.println( "var1:" + var1 + ", var2:" + var2 ); if ( var1 == 3 ) break Outer; } } } } 5/11/2024 139 Prof.Mithuna H.R,Dept of ISE,AcIT
  • 140. Find total number of iterations  A)10  B)12  C)13  D)16 5/11/2024 140 Prof.Mithuna H.R,Dept of ISE,AcIT
  • 141. continue statement  The continue statement is used when you want to continue running the loop with the next iteration and want to skip the rest of the statements of the body for the current iteration. The continue statement has the following two forms:  Labeled Continue Statement  Unlabeled Continue Statement  Unlabeled Continue Statement: This statement skips the current iteration of the innermost for, while and do-while loop. 5/11/2024 141 Prof.Mithuna H.R,Dept of ISE,AcIT
  • 142.  Example public class UnlabeledContinueDemo { public static void main( String[] args ) { for ( int var1 = 0; var1 < 4; var1++ ) { for ( int var2 = 0; var2 < 4; var2++ ) { if ( var2 == 2 ) continue; System.out.println( "var1:" + var1 + ", var2:" + var2 ); } } } } 5/11/2024 142 Prof.Mithuna H.R,Dept of ISE,AcIT
  • 143. Find total number of iterations  A)10  B)12  C)14  D)16 5/11/2024 143 Prof.Mithuna H.R,Dept of ISE,AcIT
  • 144. Labeled Continue Statement:  This statement skips the current iteration of the loop with the specified label. 5/11/2024 144 Prof.Mithuna H.R,Dept of ISE,AcIT
  • 145. Example public class LabeledContinueDemo { public static void main( String[] args ) { Outer: for ( int var1 = 0; var1 < 5; var1++ ) { for ( int var2 = 0; var2 < 5; var2++ ) { if ( var2 == 2 ) continue Outer; System.out.println( "var1:" + var1 + ", var2:" + var2 ); } } } } 5/11/2024 145 Prof.Mithuna H.R,Dept of ISE,AcIT
  • 146. Find total number of iterations  A)10  B)12  C)13  D)15 5/11/2024 146 Prof.Mithuna H.R,Dept of ISE,AcIT
  • 147. Return Statement  The return statement is used to immediately quit the current method and return to the calling method. It is mandatory to use a return statement for non-void methods to return a value. 5/11/2024 147 Prof.Mithuna H.R,Dept of ISE,AcIT
  • 148. Example public class ReturnDemo { public static void main( String[] args ) { ReturnDemo returnDemo = new ReturnDemo(); System.out.println( "No : " + returnDemo.returnCall() ); } int returnCall() { return 5; } } 5/11/2024 148 Prof.Mithuna H.R,Dept of ISE,AcIT
  • 149. Type Casting in Java  Assigning a value of one type to a variable of another type is known as Type Casting.  Java object typecasting one object reference can be type cast into another object reference.  The cast can be to its own class type or to one of its subclass or superclass types or interfaces.  There are compile-time rules and runtime rules for casting in java. 5/11/2024 149 Prof.Mithuna H.R,Dept of ISE,AcIT
  • 150.  Example in Java int x = 10; byte y = (byte)x; 5/11/2024 150 Prof.Mithuna H.R,Dept of ISE,AcIT
  • 151.  In Java, type casting is classified into two types, 1)Widening Casting(Implicit) 5/11/2024 151 Prof.Mithuna H.R,Dept of ISE,AcIT
  • 152. 2) Narrowing Casting(Explicitly done) 5/11/2024 152 Prof.Mithuna H.R,Dept of ISE,AcIT
  • 153. 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 153 Prof.Mithuna H.R,Dept of ISE,AcIT
  • 154. 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 154 Prof.Mithuna H.R,Dept of ISE,AcIT
  • 155.  Output : Int value 100 Long value 100 Float value 100.0 5/11/2024 155 Prof.Mithuna H.R,Dept of ISE,AcIT
  • 156. Narrowing or Explicit type conversion  When you are assigning a larger type value to a variable of smaller type, then you need to perform explicit type casting. 5/11/2024 156 Prof.Mithuna H.R,Dept of ISE,AcIT
  • 157. 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 157 Prof.Mithuna H.R,Dept of ISE,AcIT
  • 158.  Output : Double value 100.04 Long value 100 Int value 100 5/11/2024 158 Prof.Mithuna H.R,Dept of ISE,AcIT
  • 159. Java Access Specifiers/Modifiers  Private Access Modifier - private:  Methods, Variables and Constructors that are declared private can only be accessed within the declared class itself.  Private access modifier is the most restrictive access level. Class and interfaces cannot be private.  Using the private modifier is the main way that an object encapsulates itself and hides data from the outside world. 5/11/2024 159 Prof.Mithuna H.R,Dept of ISE,AcIT
  • 160.  Public Access Modifier - public:  A class, method, constructor, interface etc declared public can be accessed from any other class. Therefore fields, methods, blocks declared inside a public class can be accessed from any class belonging to the Java Universe.  However if the public class we are trying to access is in a different package, then the public class still need to be imported.  Because of class inheritance, all public methods and variables of a class are inherited by its subclasses. 5/11/2024 160 Prof.Mithuna H.R,Dept of ISE,AcIT
  • 161.  Protected Access Modifier - protected:  Variables, methods and constructors which are declared protected in a superclass can be accessed only by the subclasses in other package or any class within the package of the protected members' class.  The protected access modifier cannot be applied to class and interfaces. Methods, fields can be declared protected, however methods and fields in a interface cannot be declared protected. 5/11/2024 161 Prof.Mithuna H.R,Dept of ISE,AcIT
  • 162. Default Access Modifier - No keyword:  Default access modifier means we do not explicitly declare an access modifier for a class, field, method, etc.A variable or method declared without any access control 5/11/2024 162 Prof.Mithuna H.R,Dept of ISE,AcIT
  • 163. 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 163 Prof.Mithuna H.R,Dept of ISE,AcIT

Editor's Notes

  1. output:83