Java Basics Mod-1
Java Basics Mod-1
https://moovit.vit.ac.in/
JAVA - IDE
JAVA - Eclipse
Step 1) Installing Eclipse Open your browser and type https://www.eclipse.org/
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
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
Identification of Output
2
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.
Input:
Enter strings = Hello Patrick Jane
Output:
Total 6
a2
e2
i1
o1
Display Total
Input String
Display each vowels count
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
ALxW
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
Input num1
Is
Yes num1 No
Mod
2==0?
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
Input n
i=0
While False
(i<=n)
True
Print “i”
STOP
Programming Or Implementation Phase
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.
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.
Main
Program
Function 1 Function 2
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.
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
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.
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.
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.
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
BYTE
• Byte stores from -128 and 127.
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.
long myNum = 15000000000L;
System.out.println(myNum);
Floating Point Types
FLOAT
• float can store fractional numbers from 3.4e−038 to 3.4e+038.
DOUBLE
• Double can store fractional numbers from 1.7e−308 to 1.7e+038.
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);
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
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).
Character
• The char data type is used to store a single character.
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.