0% found this document useful (0 votes)
9 views

Java Basics Mod-1

Uploaded by

hari ram
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Java Basics Mod-1

Uploaded by

hari ram
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 185

BCSE103E

Computer Programming: JAVA



Dr. R.BHARANIDARAN

Professor

Department of Design and Automation

School of Mechanical Engineering
Course Objective
To introduce the core language features of Java and understand the fundamentals
of Object -Oriented programming in Java.

To develop the ability of using Java to solve real world problems.


Course Outcomes

Understand basic programming constructs; realize the


fundamentals of Object Orientated Programming in
Java; apply inheritance and interface concepts for
enhancing code reusability.

Realize the exception handling mechanism; process data


within files and use the data structures in the collection
framework for solving real world problems.
Course Content
Course Content
Course Content
Rubrics
Note: Preliminary plan for the Course
Sl. No Exams Marks Weightage Module
1 PAT1 10 10 Java Basics, Loops
2 PAT2 10 10 Module 12
3 PAT3 10 10 Module 1 - 3
4 Mid-Term 50 20 Module 1 - 5
5 Quiz 20 10 Module 1- 6
6 FAT 50 40 Module 1 - 7
Note
• Do not miss any class, practice problem, assessments
and challenging tasks.
• Be ethical and professional throughout the course
• Unethical practices are punishable
Important: No Re-exam
Exams will be conducted through

https://moovit.vit.ac.in/
JAVA - IDE
JAVA - Eclipse
Step 1) Installing Eclipse Open your browser and type https://www.eclipse.org/

Step 2) Click on “Download” button.


JAVA - Eclipse
Step 3) Click on “Download 64 bit” button

Step 4) Click on “Download” button


JAVA - Eclipse
Step 4) Install Eclipse.
1.Click on “downloads” in Windows file explorer.
2.Click on “eclipse-inst-win64.exe” file.

Step 5) Click on Run button


JAVA - Eclipse
Step 6) Click on “Eclipse IDE for Java Developers”
JAVA - Eclipse
Step 7) Click on “INSTALL” button
JAVA - Eclipse
Step 8) Click on “LAUNCH” button.
JAVA - Eclipse
Step 9) Click on “Launch” button.
JAVA - Eclipse
Step 10) Click on “Create a new Java project” link.
JAVA - Eclipse
Step 11) Create a new Java
Project:
1.Write project name.
2.Click on “Finish button”.
JAVA - Eclipse
Step 12) Create Java Package.
1.Goto “src”.
2.Click on “New”.
3.Click on “Package”.
JAVA - Eclipse
Step 13) Writing package name.
1.Write name of the package
2.Click on Finish button.
JAVA - Eclipse
Step 14) Creating Java Class
1.Click on package you have created.
2.Click on “New”.
3.Click on “Class”.
JAVA - Eclipse
Step 15) Defining Java Class.
1.Write class name
2.Click on “public static void main (String[]
args)” checkbox.
3.Click on “Finish” button.
JAVA - Eclipse
Helloword.java file will be created as shown below:
JAVA - Eclipse
Step 16) Click on “Run” button.

Reference: https://www.guru99.com/install-eclipse-
Output will be displayed as shown below.

java.html
Problem Solving Techniques
Problem Solving: Definition
• It is a process of identifying the problem, developing
an algorithm or approach, then converting algorithm
into computer code or program

• Programming is a problem-solving activity.

• Program - Instruction for the computer to solve


something for you.
Problem?
Problem to Solution
Input
List of Data provided

Processing
Actions needed to obtain the required output

Output
List of Output Required
Problem Analysis Chart (PAC)
• According to Sprankle and Hubbard, (2012), the initial step for
a programs need to do when get a problem is to analyze and
understand the requirements.
• To easily analyze the problem, a Problem Analysis Chart (PAC)
was introduced. This chart have four section:
• The given data
• The required result
• The processing involved
• A list of solution alternative
PAC - Table
Problem Analysis Chart (PAC)
1. A program is required to find average of five
numbers.
Given Data Required Result
Number_1 Average of 5 numbers
Number_2
Number_3
Number_4
Number_5

Process Required Solution Alternative


Total = Number 1+ Number 2+ 1. Define the numbers as constants.
Number 3+ Number 4+ 2. Define the numbers as input
Number 5 values
Average = Total / 5
Problem Analysis Chart (PAC)
• Calculate the area of a circle for any given radius

Given Data Required Result


Radius r Area of the Circle

Process Required Solution Alternative


Area = pi * r^2 1. R as constant
2. R can be a User input
Problem Analysis Chart (PAC)
2. A program is required to find the volume of a
cuboid. Please construct the PAC for this problem.
Input Output
Length (l) Volume (V)
breadth (b)
width(w)

Process Required Solution Alternative


V = l*b*w 1. l, b, w as constant
2. User input
Problem Analysis Chart (PAC)
3. Write a Problem Analysis Chart (PAC) to convert the distance
in miles to kilometers where 1.609 kilometers per mile.

Given Data Required Result


Distance (d) in miles Distance (D) Kilometer
Fac = 1.609

Process Required Solution Alternative


D = d*Fac 1. d can be a constant
2. d can be a user input
Problem Analysis Chart (PAC)
4. Write a Problem Analysis Chart (PAC) to find an area of a
rectangle where area = height * length.

Given Data Required Result

Process Required Solution Alternative


Algorithm
Definition: a complete, unambiguous, finite number of
logical steps for solving a specific problem
• A set of sequential steps usually written in Familiar
Language to solve a given problem is called
Algorithm.
• It may be possible to solve to problem in more than
one ways, resulting in more than one algorithm.
Algorithm
• The choice of various algorithms depends on the
factors like reliability, accuracy and easy to modify.
• The most important factor in the choice of algorithm
is the time requirement to execute it, after writing
code in High-level language with the help of a
computer.
• The algorithm which will need the least time when
executed is considered the best.
Steps involved in algorithm development
Identification of input
1

Identification of Output
2

Identification the processing operations


3

Processing Definiteness
4

Processing Finiteness
5

Possessing Effectiveness
6
Characteristics of a good algorithm
• Finiteness: An algorithm must terminate in a finite number of steps
• Precision: the steps are precisely stated or defined.
• Effectiveness: it should be primitive easily convert able into program
statement
• Generality: The algorithm must be complete in itself so that it can
be used to solve problems of a specific type for any input data.
• Input/output: Each algorithm must take zero, one or more quantities
as input data produce one or more output values.
• An algorithm can be written in English like sentences - Pseudo Code
• Visual Representation of Algorithms – Flow chart
Pseudocode
• It is a simpler version of a programming code in plain English
which uses short phrases to write code for a program before
it is implemented in a specific programming language. 
• It does not have a specific syntax like any of the programming
languages and thus cannot be executed on a computer.
• Many time algorithms are presented using pseudocode since
they can be read and understood by programmers who are
familiar with different programming languages
Pseudocode
• Pseudocode allows you to include several control structures
such as While, If-then-else, Repeat-until, for and case, which is
present in many high-level languages. 
Keywords : INPUT, COMPUTE,PRINT, INCREMENT, DECREMENT,
IF/ELSE, WHILE, TRUE/FALSE
Advantages of Pseudocode
 Reduced complexity
 Increased flexibility
 Ease of understanding
Pseudocode
• The programming process is a complicated one.
• You must first understand the program specifications.
• Then you need to organize your thoughts and create
the program.
• You must break the main tasks that must be
accomplished into smaller ones in order to be able
to eventually write fully developed code.
• Writing Pseudocode will save you time later during
the construction & testing phase of a program's
development.
Example
Write a pseudocode to display the sum of two numbers
entered by user.
input num1
input num2
COMPUTE Result = num1 + num2
PRINT Result
Example: Count and display the vowels in the strings.

Sample Test Case:

Input:
Enter strings = Hello Patrick Jane

Output:
Total 6
a2
e2
i1
o1

Dr.R. Bharanidaran, SMEC, VIT


PAC Chart
Given Data Required Result

Display Total
Input String
Display each vowels count

Process Required Solution Alternatives

Create a string with vowel


Run loop to count vowel in string Can use list data type
Count the vowel individually

Dr.R. Bharanidaran, SMEC, VIT


Pseudocode
Get input <- string
Convert string lower case
Vow = ‘aeiou’
Count = 0
Loop var in string
Check var in Vow
then count = count+1
Display Count
Loop var2 in Vow
Count multiples of var2 in string != o
Then display var2 and its count

Dr.R. Bharanidaran, SMEC, VIT


Flowchart
A graphical representation of the sequence of operations in an
information system or program.
 Information system flowcharts show how data flows from
source documents through the computer to final
distribution to users.
 Program flowcharts show the sequence of instructions in a
single program or subroutine. Different symbols are used
to draw each type of flowchart.
A Flowchart
 shows logic of an algorithm
 emphasizes individual steps and their interconnections
 e.g. control flow from one action to the next
Flowchart
A flow chart is an organized
combination of shapes, lines
and text that graphically
illustrate a process or
structure.
Flowchart
Flowchart symbol Function Description
Start/End Also called “Terminator” symbol. It indicates
where the flow starts and ends.
Process Also called “Action Symbol,” it represents a
process, action, or a single step.
Decision A decision or branching point, usually a yes/no or
true/ false question is asked, and based on the
answer, the path gets split into two branches

Input/ Also called data symbol, this parallelogram shape


Output is used to input or output data

Arrow Connector to show order of flow between shapes.

Connector Connection of flowchart on the same page.

Connector Connection of flowchart from page to page.


Example
Write an algorithm to display the sum of two numbers
entered by user, using both pseudocode and flow chart.
Examples
Write an algorithm and draw a flowchart to convert
the length in feet to centimeter. [1 feet = 30 cm.]
Examples
Pseudocode:
Input Length in feet (Lft)
Calculate Lcm = Lft * 30
Print Lcm
Examples
START

Input
Lft

Lcm  Lft x 30

Print
Lcm

STOP
Examples
Write an algorithm and draw a flowchart that will read
the two sides of a rectangle and calculate its area.
Examples
Pseudocode
• Input the width (W) and Length (L) of a rectangle
• Calculate the area (A) by multiplying L with W
• Print A
Examples

START

Input
W, L

ALxW

Print
A

STOP
Exercise
Write PAC, Pseudocode and draw a flowchart that will
calculate the roots of a quadratic equation
Three Basic Language Structures

• Sequence structure
• Selection structure
• Repetition structure
Three Basic Language Structures
Flowcharts for three constructs
Pseudocode for three constructs
Examples
Create PAC, Pseudocode, Flowchart to check whether a number is
odd or even.
PAC
Given Data Required Result
n1 Display Odd or Even

Process Required Solution Alternative


If n1% 2 == 0 [% modulus]
even number
Else
odd Number
Pseudocode
PRINT "Enter the Number"
INPUT number
IF number MOD 2 == 0 THEN
PRINT "Number is Even"
ELSE
PRINT "Number is Odd"
Flow Chart
START

Input num1

Is
Yes num1 No
Mod
2==0?

Print “Even” Print “Odd”

STOP
Examples
Create PAC, Pseudocode, Flowchart to print the numbers 0 to “n”
value.
PAC
Given Data Required Result
n Sum of the n numbers

Process Required Solution Alternative


n value
I = 0 [Start]
While (i<=n)
Print I
i = i+1
End While
Pseudocode
PRINT "Enter the Number"
INPUT n
i= 0
WHILE (I <= n)
PRINT i
i= i+1
END WHILE
Flow Chart START

Input n

i=0

While False
(i<=n)

True

Print “i”

STOP
Programming Or Implementation Phase

Transcribing the logical flow of solution steps in flowchart


or algorithm to program code and run the program code
on a computer using a programming language.

1. Coding.
2. Compiling.
Programming phase takes 5 3. Debugging.
stages: 4. Run or Testing.
5. Documentation and
maintenance.
Programming Or Implementation Phase
• Once the program is coded using one of the
programming language, it will be compiled to ensure
there is no syntax error.

• Syntax free program will then be executed to produce


output and subsequently maintained and
documented for later reference.
CODING

COMPILE THE MAKE


PROGRAM CORRECTION

NO SYNTAX
ERROR

EXECUTE OR
RUN

DOCUMENTATION OR
MAINTENANCE
Coding
• Translation or conversion of each operation in the
flowchart or algorithm (Pseudocode) into a computer-
understandable language.
• Coding should follow the format of the chosen
programming language.
Compiling and Debugging
• Compiling - Translates a program written in a particular high–level
programming language into a form that the computer can understand
• Compiler checks the program code so that any part of source code that
does not follow the format or any other language requirements will be
flagged as syntax error.
• This syntax error in also called bug, when error is found the
programmer will debug or correct the error and then recompile the
source code again
• Debugging process is continued until there is no more error in program
Testing
• The program code that contains no more error is called
executable program. It is ready to be tested.
• When it is tested, the data is given and the result is verified
so that it should produced output as intended.
• Though the program is error free, sometimes it does not
produced the right result. In this case the program faces logic
error.
• Incorrect sequence of instruction is an example that causes
logic error.
Documentation and Maintenance
• When the program is thoroughly tested for a substantial period of time
and it is consistently producing the right output, it can be documented.
• Documentation is important for future reference. Other programmer may
take over the operation of the program and the best way to understand a
program is by studying the documentation.
• Trying to understand the logic of the program by looking at the source
code is not a good approach.
• Studying the documentation is necessary when the program is subjected
to enhancement or modification.
• Documentation is also necessary for management use as well as audit
purposes.
Basics
Procedure Oriented Programming
• Programming model which is derived from structured
programming, based upon the concept of calling procedure.

• Procedures, also known as routines, subroutines or functions,


simply consist of a series of computational steps to be carried out.

• During a program’s execution, any given procedure might be called


at any point, including by other procedures or itself.

• Languages used in Procedural Programming:

• FORTRAN, ALGOL, COBOL,

• BASIC, Pascal and C.


Procedure Oriented Programming

Main
Program

Function 1 Function 2

Function 3 Function 4 Function 5


Object Oriented Programming (OOPs) Paradigm

• Object-Oriented Programming System (OOPs) is a programming


concept that works on the principles of abstraction, encapsulation,
inheritance, and polymorphism.

• It allows users to create objects they want and create methods to


handle those objects.

• The basic concept of OOPs is to create objects, re-use them


throughout the program, and manipulate these objects to get results.

• OOP meaning “Object Oriented Programming” is a popularly known


and widely used concept in modern programming languages like Java.
OOPs
Object A
Data
Functions

Object B Object C

Data Data
Functions Functions
Object Oriented Programming (OOPs) Paradigm

• The main aim of OOP is to bind together the data and the
functions that operate on them so that no other part of the
code can access this data except that function.

• Let us do discuss pre-requisites by polishing concepts of


methods declaration and passing.

• Starting off with the method declaration, it consists of six


components:
Object Oriented Programming (OOPs) Paradigm
• Access Modifier: Defines access type of the method i.e. from where it
can be accessed in your application. In Java, there 4 type of the access
specifiers. 
• public: accessible in all class in your application.

• protected: accessible within the package in which it is defined and


in the situation subclass (es) (including subclasses declared
outside the package)
• private: accessible only within the class in which it is defined.

• default (declared/defined without using any modifier): accessible


within same class and package within which its class is defined.
Access Modifier
Access Modifier within class within package outside package outside package
by subclass only

Private Y N N N

Default Y Y N N

Protected Y Y Y N

Public Y Y Y Y
Object Oriented Programming (OOPs) Paradigm
• The return type: The data type of the value returned by the
method or void if does not return a value.
• Method Name: the rules for field names apply to method
names as well, but the convention is a little different.
• Parameter list: Comma separated list of the input parameters
are defined, preceded with their data type, within the
enclosed parenthesis. If there are no parameters, you must
use empty parentheses ().
• Exception list: The exceptions you expect by the method can
throw; you can specify these exception(s).
• Method body: it is enclosed between braces. The code you
need to be executed to perform your intended operations.
OOPs Concepts
Object
An object is a real-world element in an object–oriented
environment that may have a physical or a conceptual existence.
Each object has −
• Identity that distinguishes it from other objects in the system.
• State that determines the characteristic properties of an object
as well as the values of the properties that the object holds.
• Behavior that represents externally visible activities performed
by an object in terms of changes in its state.
Objects can be modelled according to the needs of the application.
An object may have a physical existence, like a customer, a car, etc.;
or an intangible conceptual existence, like a project, a process, etc.
Class
A class represents a collection of objects having same characteristic
properties that exhibit common behavior.
It gives the blueprint or description of the objects that can be created
from it.
Creation of an object as a member of a class is called instantiation.
Thus, object is an instance of a class.
The constituents of a class are −
• A set of attributes for the objects that are to be instantiated from
the class. Generally, different objects of a class have some
difference in the values of the attributes. Attributes are often
referred as class data.
• A set of operations that portray the behavior of the objects of the
class. Operations are also referred as functions or methods.
Class
Let us consider a simple class, Circle, that represents the
geometrical figure circle in a two–dimensional space.
The attributes of this class can be identified as follows −
• x–coord, to denote x–coordinate of the center
• y–coord, to denote y–coordinate of the center
• a, to denote the radius of the circle
Some of its operations can be defined as follows −
• findArea(), method to calculate area
• findCircumference(), method to calculate circumference
• scale(), method to increase or decrease the radius
Class
During instantiation, values are assigned for at least some
of the attributes.
If we create an object my_circle, we can assign values like
x-coord : 2, y-coord : 3, and a : 4 to depict its state.
Now, if the operation scale() is performed on my_circle
with a scaling factor of 2, the value of the variable a will
become 8.
This operation brings a change in the state of my_circle,
i.e., the object has exhibited certain behavior.
Class & Objects

Class

Objects
Class & Objects

Class Objects
Class & Objects

Class

Objects
Inheritance
Inheritance is an important pillar of OOP(Object Oriented Programming). It is
the mechanism in java by which one class is allow to inherit the
features(fields and methods) of another class.
• Let us discuss some of frequent used important terminologies:
• Super Class: The class whose features are inherited is known as
superclass(or a base class or a parent class).
• Sub Class: The class that inherits the other class is known as subclass(or a
derived class, extended class, or child class). The subclass can add its own
fields and methods in addition to the superclass fields and methods.
• Reusability: Inheritance supports the concept of “reusability”, i.e. when we
want to create a new class and there is already a class that includes some of
the code that we want, we can derive our new class from the existing class.
By doing this, we are reusing the fields and methods of the existing class.
Inheritance
Types of Inheritance
• Single Inheritance − A subclass derives from a single super-
class.
• Multiple Inheritance − A subclass derives from more than one
super-classes.
• Multilevel Inheritance − A subclass derives from a super-class
which in turn is derived from another class and so on.
• Hierarchical Inheritance − A class has a number of subclasses
each of which may have subsequent subclasses, continuing
for a number of levels, so as to form a tree structure.
• Hybrid Inheritance − A combination of multiple and multilevel
inheritance so as to form a lattice structure.
Inheritance
Inheritance
Polymorphism
• Polymorphism is originally a Greek word that means the ability to
take multiple forms.
• In object-oriented paradigm, polymorphism implies using
operations in different ways, depending upon the instance they
are operating upon.
• Polymorphism allows objects with different internal structures to
have a common external interface.
• Polymorphism is particularly effective while implementing
inheritance.
Note: Polymorphism in Java are mainly of 2 types:
• Overloading
• Overriding
Abstraction
• Data Abstraction is the property by virtue of which only the
essential details are displayed to the user.
• The trivial or the non-essentials units are not displayed to the user.
Ex: A car is viewed as a car rather than its individual components.
• Data Abstraction may also be defined as the process of identifying
only the required characteristics of an object ignoring the irrelevant
details.
• The properties and behaviors of an object differentiate it from
other objects of similar type and also help in classifying/grouping
the objects.
Abstraction
Abstraction
Encapsulation
It is defined as the wrapping up of data under a single unit. It is the
mechanism that binds together code and the data it manipulates. Another
way to think about encapsulation is, it is a protective shield that prevents
the data from being accessed by the code outside this shield.
• Technically in encapsulation, the variables or data of a class is hidden
from any other class and can be accessed only through any member
function of own class in which they are declared.
• As in encapsulation, the data in a class is hidden from other classes, so it
is also known as data-hiding.
• Encapsulation can be achieved by Declaring all the variables in the class as
private and writing public methods in the class to set and get the values
of variables.
Encapsulation
Encapsulation
History of Java
James Gosling and Patrick Naughton initiated the Java
language project in June 1991.
The idea was to develop a language which was
platform-independent and which could create
embedded software for consumer electronic devices,
It took 18 months to develop and had an initial name
as Oak, Renamed to Java in 1995, due to copyright
issues.
Java originally developed by James Gosling at Sun
Microsystems
The and
principles for released
creating in 1995
Java programming were "Simple, Robust, Portable,
Platform-independent, Secured, High Performance, Multithreaded,
Architecture Neutral, Object-Oriented, Interpreted, and Dynamic". Java
Versions of java
• 1995 version 1.0:
– The Java development kit was released for free by the sun
– 8-Packages 212-Classes
– Microsoft and other companies licensed Java
• 1997 version 1.1:
– 23 -Packages 504-Classes
– Improvement include better event handling inner classes ,
improved JVM.
– Microsoft developed its own 1.1 compatible Java Virtual
Machine for Internet Explorer
– Many browsers in use are still compatible only with 1.1
Versions of java…
1999 version 1.2:
-It is also called as the Java 2 platform
-59 Packages -1520 Classes
-Code & tools distributed as the SDK
-A Java foundation class based on swings for improved
graphics and user interfaces
-Collection API included list sets and hash map
Versions of java…
. 2000 VERSION 1.3:
- 76 Packages - 1842 Classes
- Java Sound (API for Digital & MIDI Sound)
•2002 VERSION 1.4:
- 135 Packages - 2991 Classes
- Improved XML support etc..,
•2004 VERSION 5.0 (1.5):
- 165 Packages - over 3000 Classes
- Faster startup metadata formatted Output
- Generic to operate on objects of various types
Versions of java…
2006 Java SE 6:
– Scripting language support
2011 Java SE 7:
– JVM Support for dynamic language
– String in switch
– Allowing underscores in numeric literals
2014 Java SE 8:
– for Each() method in Iterable interface.
- default and static methods in Interfaces.
- Functional Interfaces and Lambda Expressions.
Versions of java…
2017 Java SE 9:
-Stream API Improvements
-Multi-Resolution Image API
Java SE 10 (20th Mar 2018)
Java SE 11 (September 2018)
Java SE 12 (March 2019)
Java SE 13 (September 2019)
Java SE 14 (Mar 2020)
Java SE 15 (September 2020)
Java SE 16 (Mar 2021)
Java SE 17 (September 2021)
Java SE 18 (released March 2022)
Java SE 19 (Latest Available)
Features of Java
Features of Java
Simple
Java is very easy to learn, and its syntax is simple, clean and
easy to understand. According to Sun Microsystem, Java
language is a simple programming language because:
• Java syntax is based on C++ (so easier for programmers to
learn it after C++).
• Java has removed many complicated and rarely-used features,
for example, explicit pointers, operator overloading, etc.
• There is no need to remove unreferenced objects because
there is an Automatic Garbage Collection in Java.
Features of Java
Object-oriented
Java is an object-oriented programming language. Everything in
Java is an object. Object-oriented means we organize our
software as a combination of different types of objects that
incorporate both data and behavior.
Object-oriented programming (OOPs) is a methodology that
simplifies software development and maintenance by providing
some rules.
Basic concepts of OOPs are:
1.Object
2.Class
3.Inheritance
4.Polymorphism
5.Abstraction
6.Encapsulation
Features of Java
Platform Independent
Java is platform independent because it is different from other
languages like C, C++, etc. which are compiled into platform specific
machines while Java is a write once, run anywhere language. A
platform is the hardware or software environment in which a program
runs.
The Java platform differs from most other platforms in the sense that
it is a software-based platform that runs on top of other hardware-
based platforms. It has two components:
1.Runtime Environment
2.API(Application Programming Interface)
Features of Java
Platform Independent

Java code can be executed on multiple platforms, for example, Windows,


Linux, Sun Solaris, Mac/OS, etc. Java code is compiled by the compiler and
converted into bytecode. This bytecode is a platform-independent code
because it can be run on multiple platforms, i.e., Write Once and Run
Anywhere (WORA).
Features of Java
Secured
Java is best known for its security. With Java, we can develop
virus-free systems. Java is secured because:
• No explicit pointer
• Java Programs run inside a virtual machine sandbox
Features of Java
• Classloader: Classloader in Java is a part of the Java Runtime Environment
(JRE) which is used to load Java classes into the Java Virtual Machine
dynamically. It adds security by separating the package for the classes of
the local file system from those that are imported from network sources.
• Bytecode Verifier: It checks the code fragments for illegal code that can
violate access rights to objects.
• Security Manager: It determines what resources a class can access such
as reading and writing to the local disk.
Java language provides these securities by default. Some security can also be
provided by an application developer explicitly through SSL, JAAS,
Cryptography, etc.
Features of Java
Robust
The English mining of Robust is strong. Java is robust because:
• It uses strong memory management.
• There is a lack of pointers that avoids security problems.
• Java provides automatic garbage collection which runs on
the Java Virtual Machine to get rid of objects which are not
being used by a Java application anymore.
• There are exception handling and the type checking
mechanism in Java. All these points make Java robust.
Features of Java
Architecture-neutral
Java is architecture neutral because there are no implementation
dependent features, for example, the size of primitive types is fixed.
In C programming, int data type occupies 2 bytes of memory for 32-bit
architecture and 4 bytes of memory for 64-bit architecture. However, it
occupies 4 bytes of memory for both 32 and 64-bit architectures in Java.
Portable
Java is portable because it facilitates you to carry the Java bytecode to any
platform. It doesn't require any implementation.
High-performance
Java is faster than other traditional interpreted programming languages
because Java bytecode is "close" to native code. It is still a little bit slower
than a compiled language (e.g., C++). Java is an interpreted language that
is why it is slower than compiled languages, e.g., C, C++, etc.
Features of Java
Distributed
Java is distributed because it facilitates users to create distributed
applications in Java. RMI and EJB are used for creating distributed
applications. This feature of Java makes us able to access files by calling the
methods from any machine on the internet.
Multi-threaded
A thread is like a separate program, executing concurrently. We can write
Java programs that deal with many tasks at once by defining multiple
threads. The main advantage of multi-threading is that it doesn't occupy
memory for each thread. It shares a common memory area. Threads are
important for multi-media, Web applications, etc.
Dynamic
Java is a dynamic language. It supports the dynamic loading of classes. It
means classes are loaded on demand. It also supports functions from its
native languages, i.e., C and C++.
JAVA Programming Model
Java Virtual Machine
• Java Virtual Machine is a Virtual Machine that allows a computer
system to run/execute Java Programs.
• JVM is an engine, which works as a runtime environment for Java code.
JVM converts the java code into machine language. When you run a
compiled .class file, it goes to JVM, and then JVM returns the output.
• Java Virtual Machine is a part of JRE, which stands for “Java Runtime
Environment”.
• Basic tasks for a Java Virtual Machine consist of Loading the code, then
verifying the code, and executing the code.
• Also, provide the runtime environment for code execution. JVM
consists of various components like Classloader, List of space assigned
by JVM like Stack, an Execution Engine, and a few native libraries.
The architecture of Java Virtual Machine
Class Loader

Execution Engine
As the name suggests, it is a component responsible for Loading Class
files. Loading, Linking, and initializing a class file are the major
functions of the Loader. The loader does it work in runtime.

Loading: Basically, the loader reads the .class file and then generates
the binary code and saves it in a method area. Bootstrap Classloader,
Extension Classloader, and Application Classloader are the various
ClassLoaders responsible for loading various classes.
Class Loader Linking: Three major functions like Verification, Preparation, and
Resolve. It starts with .class file verification. If verification fails, it
gives a run-time verification exception. Later, Memory is allocated to
the variables with default values. Then, finally, the symbolic memory
references are replaced with direct references from the memory
area.

Initializing: This is the final part of ClassLoader. Original values are


assigned to all the static variables, followed by the execution of Static
Block. This part executes from the top to the bottom of a class.
Heap
Details of an object and instance variables are all stored here. It is a shared memory area,
which means the data stored here is not thread-safe.

Exception in thread “main” java.lang.OutOfMemoryError: Java heap space

One of the most relatable errors is the “OutOfMemoryError” exception, which means the
JVM cannot allocate an object in the Heap area, or memory allocation cannot be done for
the same object.

Stack
This is where a separate runtime stack is created for every new thread. Also known as a
Run-Time Stack, every time a method is called upon, all the details are stored in the
corresponding runtime stand, and after the completion of the method, these details are
removed from the stack.
PC Registers
For every single thread, a separate PC (Program Counter) register is created, which stores the
address of the current execution instruction, which, later, will be updated with the next
instruction. This memory area is quite small and is of fixed size.

Native Method Stack

It is one of its own kind of memory area, which is invoked by a thread, and then the thread is at a
whole new level where structure and security restrictions implied by Java Virtual Machine are no
longer in exercise. Compared to other runtime memory areas, the memory occupied by the native
method stacks has no fixed size, with no limitations in increment or decrement.
Java Native Interface

JNI simply interacts with the below-mentioned Native Method Libraries, which
are of C, C++ implementation, and provide the same to the execution engine.
Direct Access to assembly code is allowed by JNI. For a JVM, Java and Native
are the two types of codes. The JNI smoothly establishes a well-defined link
between these two.

Native Method Libraries


Collection of Native Libraries, as required by the Execution Engine.
Execution Engine
Well, now we have a java program into bytecode, which is being assigned to the
above-explained data areas via a class loader, and now the bytecode will be executed
by the execution engine.
Execution Engine simply reads the bytecode in units, like a machine reading code
lines one by one.
The bytecode is a human-readable format, which is why the machine cannot read it as
it is and needs to be converted to a machine-readable format, where the below
components are utilized for the interpretation purpose.
The Execution Engine has three major components, which are Interpreter, JIT
Compiler, and a Garbage Collector.
The execution engine executes the .class file and reads the byte-code line by line. It
contains:
•A virtual processor.
•An interpreter that translates the bytecode line by line and executes.
•Just-In-Time (JIT) compiler: It compiles the bytecode and changes it into native
code.
Features of Java
1. Interpreter
• Simply executes the bytecode in a sequential method.
• A command-line query makes a call with a compiled file as an argument.
• The interpreter is quite quick in interpreting and executing commands one by one,
which happens faster than the JIT compiler to compile the code. java class name
• A main() class is must in a compiled .class file.

2. JIT Compiler
• One of the most important components of the Java Runtime Environment which
enhances the Java Application performance at run time.
• No other component has more impact on performance than the JIT Compiler.
• This is a default compiler and is activated when any Java method is called.
Features of Java
3. Garbage Collector
• As the name suggests, it does have something to do with garbage; Garbage
Collector simply searches for every possible object available in the JVM heap
space, checks if it is in use, and then delete the unused ones.
• So, it simply marks the pieces of memory which are in use or not. Then it goes on
sweeping, where it simply removes the object marked.
• The best use case is that no manual memory allocation system is needed as the
Garbage Collector does the job of automatically removing unused memory space.
• As this is an automatic task, no programmer has control over scheduling any time
slot for specific cleaning tasks and requires more CPU power as it searches for
object references.
Byte Code
• In java when you compile a program, the java compiler(javac)
converts/rewrite your program in another form/language which we call
as bytecode.
• The .class file that is generated after compilation is nothing but just the
bytecode instructions of your program.
• The word bytecode and .class are used interchangeably, so if someone
says bytecode, it simply means the .class file of program.
JDK, JRE, JVM
Java Programming Structure
My First Program
Write a code to print the words Hello World.
Data Types in JAVA
Primitive Data Types

Data – Type Size Description

Byte (8 bit) 1 byte Stores whole numbers from -128 to 127

int 4 bytes Stores whole numbers from -2,147,483,648 to 2,147,483,647

short 2 bytes Stores whole numbers from -32,768 to 32,767

long 8 bytes Stores whole numbers from -9,223.372,036.854,775.808 to


9,223.372,036,854,775,808

char 2 bytes Stores a single character/letter

boolean 1 byte Stores true or false values

float 4 bytes Stores fractional numbers from 3.4e−038 to 3.4e+038. Sufficient


for storing 6 to 7 decimal digits

double 8 bytes Stores fractional numbers from 1.7e−308 to 1.7e+038. Sufficient


for storing 15 decimal digits
Integer

BYTE
• Byte stores from -128 and 127.

• Can be used instead of int or other integer types to save memory.

byte myNum = 100;
System.out.println(myNum);

SHORT
short myNum = 5000;
System.out.println(myNum);
INT
• int stores from -2147483648 to 2147483647. 
 
• preferred data type when we create variables with a numeric value.

int myNum = 100000;
System.out.println(myNum);

LONG
• long stores from -9223372036854775808 to
9223372036854775808.

• Used when int is not large enough to store the value.

• you should end the value with an "L":

long myNum = 15000000000L;
System.out.println(myNum);
Floating Point Types
FLOAT
• float can store fractional numbers from 3.4e−038 to 3.4e+038.

• should end the value with an "f":


float myNum = 5.75f;
System.out.println(myNum);

DOUBLE
• Double can store fractional numbers from 1.7e−308 to 1.7e+038.

• you should end the value with a "d":

double myNum = 19.99d;
System.out.println(myNum);
Scientific Numbers
A floating point number can also be a scientific number with an "e"
to indicate the power of 10:

float f1 = 35e3f;
double d1 = 12E4d;
System.out.println(f1);
System.out.println(d1);

Use float or double?

The precision of a floating point value indicates how many digits the
value can have after the decimal point. The precision of float is only six or
seven decimal digits, while double variables have a precision of about 15
digits. Therefore it is safer to use double for most calculations.
Boolean

• declared with the boolean keyword

• can only take the values true or false:

boolean isJavaFun = true;
boolean isFishTasty = false;
System.out.println(isJavaFun); 
System.out.println(isFishTasty);  
String
• The String data type is used to store a sequence of characters (text).

• String values must be surrounded by double quotes:

String greeting = "Hello World";


System.out.println(greeting);

Character
• The char data type is used to store a single character.

• A char value must be surrounded by single quotes, like 'A' or 'c':

char myGrade = 'B';
System.out.println(myGrade);
Non-Primitive Data Types
Non-primitive data types are called reference types because they refer to
objects.
The main difference between primitive and non-primitive data types are:
• Primitive types are predefined (already defined) in Java. Non-primitive
types are created by the programmer and is not defined by Java (except
for String).
• Non-primitive types can be used to call methods to perform certain
operations, while primitive types cannot.
• A primitive type has always a value, while non-primitive types can be null.
• A primitive type starts with a lowercase letter, while non-primitive types
starts with an uppercase letter.
• The size of a primitive type depends on the data type, while non-
primitive types have all the same size.
Examples of non-primitive types are Strings, Arrays, Classes, Interface, etc.
VARIABLES
What is a variable ?
• A variable which holds value, during the life of a Java program. 
• Every variable is assigned a data type which designates the type and
quantity of value it can hold.
• Variable is a memory location name of the data.
• In order to use a variable in a program you to need to perform 2 steps
• Variable Declaration
• Variable Initialization
• Variable is a name of memory location. There are three types of
variables in java: local, instance and static.
VARIABLES
• A variable is a name given to a memory location. It is the basic
unit of storage in a program.
• The value stored in a variable can be changed during
program execution.
• A variable is only a name given to a memory location, all
the operations done on the variable effects that memory
location.
• In Java, all the variables must be declared before use.
Variable Declaration
To declare a variable, you must specify the data type & give the variable a
unique name.

Variable-
Data-type
name

int count;
Variable Initialization
To initialize a variable, you must assign it a valid value.

You can combine variable declaration and initialization.


int count=100;
TYPES OF VARIABLES
Types of Variables
1) Local Variable
• Local Variables are a variable that are declared inside the body of a method.
• Valid only within that method
• A local variable cannot be defined with "static" keyword.
2) Instance Variable
• A variable declared inside the class but outside the body of the method, is
called an instance variable. It is not declared as static.
• It is called an instance variable because its value is instance-specific and is not
shared among instances.
3) Static variable
• A variable that is declared as static is called a static variable. It cannot be local.
• You can create a single copy of the static variable and share it among all the
instances of the class.
• Memory allocation for static variables happens only once when the class is
loaded in the memory.
Consider this code snippet
NAMING CONVENTION OF VARIABLES
The general rules for naming variables are:
• Names can contain letters, digits, underscores, and dollar signs
• Names must begin with a letter
• Names should start with a lowercase letter and it cannot contain
whitespace
• Names can also begin with $ and _
• Names are case sensitive ("myVar" and "myvar" are different
variables)
• Reserved words (like Java keywords, such as int or boolean) cannot
be used as names
Non-static variable V/S Static variable
Non-static variable Static variable

1. Memory is allocated multiple time 1. Memory is allocated for these


whenever a new object is created. variable only once in the program.
2. Non-static variable also known as 2. Memory is allocated at the time of
instance variable while because loading of class so that these are
memory is allocated whenever also known as class variable.
instance is created. 3. Static variable are common for
3. Non-static variable are specific to every object that means there
an object memory location can be sharable
4. Non-static variable can access by every object reference or same
with object reference. class.
4. Static variable can access with
class reference.
Java Variable Example: Add Two Numbers
Java Variable Example: Widening
RULES FOR WIDENING PRIMITVE CONVERSION

• The result of adding Java chars, shorts or bytes is an int.


• If either operand is of type double, the other is converted to
double.
• Otherwise, if either operand is of type float, the other is
converted to float.
• Otherwise, if either operand is of type long, the other is
converted to long.
• Otherwise, both operands are converted to type int
Consider this code snippet

public class Test Can you predict the output?


{
    public static void main(String[] args) YOLO
    {
        System.out.print("Y" + "O");
        System.out.print('L' + 'O'); YO155
    }
}
Now, try to predict the output

public class Test 


{
    public static void main(String[] args)  YO7679
    {
        System.out.print("Y" + "O");
YOLO
        System.out.print('L');
        System.out.print('O');
    }
}
NARROWING OR EXPLICIT TYPE-CASTING

If we want to assign a value of larger data type to a smaller data


type we perform explicit type casting or narrowing.

• This is useful for incompatible data types where automatic


conversion cannot be done.

• Here, target-type specifies the desired type to convert the specified


value to.
Guess the output
public class Test
{
  public static void main(String[] argv)
  {
    char ch = 'c'; Error
    int num = 88;
    ch = num;
  }
}
Now, try to predict the output
class Simple
{  
public static void main(String[] args)
{  
10.5
float f=10.5f;   10
//int a=f;//Compile time error  
int a=(int)f;  
System.out.println(f);  
System.out.println(a);  
}

Java Variable Example: Narrowing (Typecasting)
Java Variable Example: Overflow
Java Variable Example: Adding Lower Type
Java Naming Convention
Identifiers Type Naming Rules Examples

Class It should start with the uppercase letter. public


It should be a noun such as Color, Button, class Employee
System, Thread, etc. {
Use appropriate words, instead of acronyms. //code snippet
}

Interface It should start with the uppercase letter. interface Printable


It should be an adjective such as Runnable, {
Remote, ActionListener. //code snippet
Use appropriate words, instead of acronyms. }
Identifiers Type Naming Rules Examples
Method It should start with lowercase letter. class Employee
It should be a verb such as main(), print(), {
println(). // method
If the name contains multiple words, start it with void draw()
a lowercase letter followed by an uppercase letter {
such as actionPerformed(). //code snippet
}
}
Variable It should start with a lowercase letter such as id, class Employee
name. It should not start with the special {
characters like & (ampersand), $ (dollar), _ // variable
(underscore). If the name contains multiple int id;
words, start it with the lowercase letter followed //code snippet
by an uppercase letter such as firstName, }
lastName. Avoid using one-character variables
such as x, y, z.
Identifiers Type Naming Rules Examples

Package It should be a lowercase letter such as java, //package


lang. If the name contains multiple words, package com.javatpoint;
it should be separated by dots (.) such as class Employee
java.util, java.lang. {
//code snippet
}

Constant It should be in uppercase letters such as class Employee


RED, YELLOW. {
If the name contains multiple words, it //constant
should be separated by an underscore(_) static final
such as MAX_PRIORITY. int MIN_AGE = 18;
It may contain digits but not as the first //code snippet
letter. }
Operators in Java
Java AND Operator Example: Logical && and Bitwise &
Java OR Operator Example: Logical || and Bitwise |
Java Ternary Operator Example
Java Ternary Operator Example
Java Assignment Operator Example
Java Assignment Operator Example: Adding short
Example
References:
• https://www.javatpoint.com/
• https://www.geeksforgeeks.org/
• https://www.w3schools.com/
• https://www.educba.com/
• Y. Daniel Liang, Intro to Java Programming, Pearson
Education India
Thank You All

You might also like