0% found this document useful (0 votes)
4 views34 pages

Java - Unit 1 and Unit 2 - Except Arrays

The document discusses programming language paradigms, categorizing them into imperative and declarative paradigms, with further classifications into procedural and object-oriented for imperative, and functional and logical for declarative. It highlights the differences between Procedure Oriented Programming (POP) and Object Oriented Programming (OOP), explaining key OOP concepts such as abstraction, encapsulation, inheritance, and polymorphism. Additionally, it introduces Java as an object-oriented language, detailing its features, execution phases, and the roles of JVM, JDK, and JRE.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views34 pages

Java - Unit 1 and Unit 2 - Except Arrays

The document discusses programming language paradigms, categorizing them into imperative and declarative paradigms, with further classifications into procedural and object-oriented for imperative, and functional and logical for declarative. It highlights the differences between Procedure Oriented Programming (POP) and Object Oriented Programming (OOP), explaining key OOP concepts such as abstraction, encapsulation, inheritance, and polymorphism. Additionally, it introduces Java as an object-oriented language, detailing its features, execution phases, and the roles of JVM, JDK, and JRE.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Java – Unit 1 and Unit 2

PARADIGMS OF PROGRAMMING LANGUAGES


1. The term paradigm describes a set of techniques, methods, theories and standards that together
represent a way of thinking for problem solving.
2. Language paradigms were associated with classes of languages. First the paradigms are defined.
Thereafter, programming languages according to the different paradigms are classified.
3. The language paradigms are divided into two parts, imperative and declarative paradigms
4. Imperative languages can be further classified into procedural and object oriented approach.
Declarative languages can be classified into functional languages and logical languages.

5. Imperative paradigm: The meaning of imperative is “expressing a command or order”, so the


programming languages in this category specify the step-by-step explanation of command.
Imperative programming languages describe the details of how the results are to be obtained.
The programs specify step by step the entire set of transitions that the program goes through.
The program starts from an initial state, goes through the transitions and reaches a final state.
Within this paradigm we have the procedural approach and Object Oriented approach.
o Procedural paradigm: Procedural languages are statement oriented with the variables
holding values. We have two kinds of statements. Nonexecutable statements allocate
memory, bind symbolic names to absolute memory locations, and initialize memory.
Executable statements like computation, control flow, and input/output statements. The
popular programming languages in this category are Ada, Fortran, Basic, Algol, Pascal,
Cobol, Modula, C, etc.
o Object Oriented paradigm: The Object Oriented paradigm is centered on the concept of
the object. Everything is focused on objects. Computation in this paradigm is viewed as
the simulation of real world entities. The popular programming languages in this paradigm
are C++, Simula, Smalltalk and Java.

Developed by: Sreedhar A, CSE Dept., RGUKT Page 1


6. Declarative paradigm: In this paradigm programs declare or specify what is to be computed
without specifying how it is to be achieved. Declarative programming is also known as Value-
oriented programming. Declarative languages describe the relationships between variables in
terms of functions and inference rules. Declarative paradigm is further divided into two
categories, functional and logical paradigms.
o Functional paradigm: In this paradigm, a program consists of a collection of functions. A
function just computes and returns a value. A program consists of calling a function with
appropriate arguments, but any function can make use of other functions also. The main
programming languages in this category are Lisp, ML, Scheme, and Haskell.
o Logic paradigm: In this paradigm programs only explain what is to be computed not how
to compute it. Here program is represented by a set of relationships, between objects or
property of objects known as predicate which are held to be true, and a set of
logic/clauses (i.e. if A is true, then B is true). Basically logic paradigm integrates data and
control structures. The Prolog language is perhaps the most common example.

Differences between POP and OOP:-

Subject of Procedure Oriented Programming


Object Oriented Programming (OOP)
Difference (POP)
Problem Decompose the main problem in small Decompose the main problem in small
decomposition parts called functions. parts called objects.
Connects small parts of the program by Connects small parts of the program
Connections of
passing parameters & using operating by passing messages.
parts
system.
Emphasizing Emphasizes on functions. Emphasizes on data.
In large programs, most functions use Each object controls data under it.
Use of data
global data.
Data may get passed from one Data never get passed from one object
Passing of data
function to another. to another.
Appropriate & effective techniques are Data stay secured as no external
Security of data
unavailable to secure the data. function can use data of an object.
Modification of a completed program Modifications are easy as objects stay
Modification of
is very difficult and it may affect the independent to declare and define.
program
whole program.
Designing Employs top-down approach for Employs bottom-up approach for
approach designing programs. designing.
In large programs, it is very difficult to As data and functions stay close, it is
Data
find what data has been used by which easy to identify data.
identification
function.
Languages like C, FORTRAN, COBOL Languages like C++, JAVA etc. use OOP.
Used languages
etc. use POP.

Developed by: Sreedhar A, CSE Dept., RGUKT Page 2


Object
Object means a real word entity such as pen, chair, table etc. Object-Oriented Programming is a
methodology or paradigm to design a program using classes and objects. It simplifies the software
development and maintenance by providing some concepts:
 Object
 Class
 Inheritance
 Polymorphism
 Abstraction
 Encapsulation
Any entity that has state and behavior is known as an object. For example: chair, pen, table, keyboard,
bike etc. It can be physical and logical. Object is the physical as well as logical entity whereas class is the
logical entity only.
An entity that has state and behavior is known as an object e.g. chair, bike, marker, pen, table, car etc. It
can be physical or logical (tangible and intangible). The example of intangible object is banking system.
An object has three characteristics:
 state: represents data (value) of an object.
 behavior: represents the behavior (functionality) of an object such as deposit, withdraw etc.
 identity: Object identity is typically implemented via a unique ID. The value of the ID is not visible
to the external user. But, it is used internally by the JVM to identify each object uniquely.
For Example: Pen is an object. Its name is Reynolds, color is white etc. known as its state. It is used to
write, so writing is its behavior.
Object is an instance of a class. Class is a template or blueprint from which objects are created. So
object is the instance(result) of a class.
Object Definitions:
 Object is a real world entity.
 Object is a run time entity.
 Object is an entity which has state and behavior.
 Object is an instance of a class.

Class
Collection of objects is called class. It is a logical entity.
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

Developed by: Sreedhar A, CSE Dept., RGUKT Page 3


Syntax to declare a class:
1. class <class_name>{
2. field;
3. method;
4. }

Introduction to OOPs using java:


JAVA was developed by Sun Microsystems Inc in 1991, later acquired by Oracle Corporation. It
was developed by James Gosling and Patrick Naughton. It is a simple programming language. Writing,
compiling and dxebugging a program is easy in java. It helps to create modular programs and reusable
code.
Java terminology:-
1. Java Virtual Machine (JVM)
This is generally referred as JVM. Before, we discuss about JVM lets see the phases of program
execution. Phases are as follows: we write the program, then we compile the program and at last
we run the program.
1) Writing of the program is of course done by java programmer like you and me.
2) Compilation of program is done by javac compiler, javac is the primary java compiler included
in java development kit (JDK). It takes java program as input and generates java bytecode as
output.
3) In third phase, JVM executes the bytecode generated by compiler. This is called program run
phase.
So, now that we understood that the primary function of JVM is to execute the bytecode
produced by compiler. Each operating system has different JVM, however the output they
produce after execution of bytecode is same across all operating systems. That is why we call
java as platform independent language.
2. bytecode
As discussed above, javac compiler of JDK compiles the java source code into bytecode so that it
can be executed by JVM. The bytecode is saved in a .class file by compiler.
3. Java Development Kit(JDK).
As the name suggests this is complete java development kit that includes JRE (Java Runtime
Environment), compilers and various tools like JavaDoc, Java debugger etc.
In order to create, compile and run Java program you would need JDK installed on your
computer.
4. Java Runtime Environment(JRE)
JRE is a part of JDK which means that JDK includes JRE. When you have JRE installed on your
system, you can run a java program however you won’t be able to compile it. JRE includes JVM,
browser plugins and applets support. When you only need to run a java program on your
computer, you would only need JRE.

Developed by: Sreedhar A, CSE Dept., RGUKT Page 4


Main Features of JAVA
Java is a platform independent language
Compiler (javac) converts source code (.java file) to the byte code(.class file). As mentioned
above, JVM executes the bytecode produced by compiler. This byte code can run on any platform such
as Windows, Linux, Mac OS etc. Which means a program that is compiled on windows can run on Linux
and vice-versa. Each operating system has different JVM, however the output they produce after
execution of bytecode is same across all operating systems. That is why we call java as platform
independent language.
Simple
Java is considered as one of simple language because it does not have complex features like
Operator overloading, Multiple inheritance, pointers and Explicit memory allocation.
Robust Language
Robust means reliable. Java programming language is developed in a way that puts a lot of
importance on early checking for possible errors, that’s why java compiler is able to detect errors that
are not easy to detect in other programming languages. The main features of java that makes it robust
are garbage collection, Exception Handling and memory allocation.
Secure
We don’t have pointers and we cannot access out of bound arrays (you get
ArrayIndexOutOfBoundsException if you try to do so) in java. That’s why several security flaws like stack
corruption or buffer overflow is impossible to exploit in Java.

Java is distributed
Using java programming language we can create distributed applications. RMI(Remote Method
Invocation) and EJB(Enterprise Java Beans) are used for creating distributed applications in java. In
simple words: The java programs can be distributed on more than one systems that are connected to
each other using internet connection. Objects on one JVM (java virtual machine) can execute procedures
on a remote JVM.
Multithreading
Java supports multithreading. Multithreading is a Java feature that allows concurrent execution
of two or more parts of a program for maximum utilisation of CPU.
Portable
As discussed above, java code that is written on one machine can run on another machine. The
platform independent byte code can be carried to any platform for execution that makes java code
portable.
OOPs Features:-
Java is an object oriented language because it provides the features to implement an object
oriented model. These features includes Abstraction, encapsulation, inheritance and polymorphism.
OOPS is about developing an application around its data, i.e. objects which provides the access to
their properties and the possible operations in their own way.
4 main concepts of Object Oriented programming are:
1. Abstraction
2. Encapsulation

Developed by: Sreedhar A, CSE Dept., RGUKT Page 5


3. Inheritance
4. Polymorphism

Abstraction
One of the most fundamental concept of OOPs is Abstraction. Abstraction is a process where you
show only “relevant” data and “hide” unnecessary details of an object from the user. For example, when
you login to your Amazon account online, you enter your user_id and password and press login, what
happens when you press login, how the input data sent to amazon server, how it gets verified is all
abstracted away from the you.
Another example of abstraction: A car in itself is a well-defined object, which is composed of
several other smaller objects like a gearing system, steering mechanism, engine, which are again have
their own subsystems. But for humans car is a one single object, which can be managed by the help of its
subsystems, even if their inner details are unknown.
Encapsulation
Encapsulation is:
 Binding the data with the code that manipulates it.
 It keeps the data and the code safe from external interference
Looking at the example of a power steering mechanism of a car. Power steering of a car is a complex
system, which internally have lots of components tightly coupled together, they work synchronously to
turn the car in the desired direction. It even controls the power delivered by the engine to the steering
wheel. But to the external world there is only one interface is available and rest of the complexity is
hidden. Moreover, the steering unit in itself is complete and independent. It does not affect the
functioning of any other mechanism.
Similarly, same concept of encapsulation can be applied to code. Encapsulated code should have
following characteristics:
 Everyone knows how to access it.
 Can be easily used regardless of implementation details.
 There shouldn’t any side effects of the code, to the rest of the application.
Inheritance
 Inheritance is the mechanism by which an object acquires the some/all properties of another
object.
 It supports the concept of hierarchical classification.
For example: Car is a four wheeler vehicle so assume that we have a class FourWheeler and a sub
class of it named Car. Here Car acquires the properties of a class FourWheeler. Other classifications could
be a jeep, tempo, van etc. FourWheeler defines a class of vehicles that have four wheels, and specific
range of engine power, load carrying capacity etc. Car (termed as a sub-class) acquires these properties
from FourWheeler, and has some specific properties, which are different from other classifications of
FourWheeler, such as luxury, comfort, shape, size, usage etc.
A car can have further classification such as an open car, small car, big car etc, which will acquire the
properties from both Four Wheeler and Car, but will still have some specific properties. This way the
level of hierarchy can be extended to any level.
Java Swing and Awt classes represent best examples for inheritance.

Developed by: Sreedhar A, CSE Dept., RGUKT Page 6


Polymorphism
 Polymorphism means to process objects differently based on their data type.
 In other words it means, one method with multiple implementation, for a certain class of action.
And which implementation to be used is decided at runtime depending upon the situation (i.e.,
data type of the object)
 This can be implemented by designing a generic interface, which provides generic methods for a
certain class of action and there can be multiple classes, which provides the implementation of
these generic methods.
Lets us look at same example of a car. A car have a gear transmission system. It has four front gears
and one backward gear. When the engine is accelerated then depending upon which gear is engaged
different amount power and movement is delivered to the car. The action is same applying gear but
based on the type of gear the action behaves differently or you can say that it shows many forms
(polymorphism means many forms)
Polymorphism could be static and dynamic both. Method Overloading is static polymorphism while,
Method overriding is dynamic polymorphism.
 Overloading in simple words means more than one method having the same method name that
behaves differently based on the arguments passed while calling the method. This called static
because, which method to be invoked is decided at the time of compilation
 Overriding means a derived class is implementing a method of its super class. The call to
overriden method is resolved at runtime, thus called runtime polymorphism
Java Virtual Machine (JVM), Difference JDK, JRE & JVM – Core Java
Java is a high level programming language. A program written in high level language cannot be
run on any machine directly. First, it needs to be translated into that particular machine language. The
javac compiler does this thing, it takes java program (.java file containing source code) and translates it
into machine code (referred as byte code or .class file).
Java Virtual Machine (JVM) is a virtual machine that resides in the real machine (your computer)
and the machine language for JVM is byte code. This makes it easier for compiler as it has to generate
byte code for JVM rather than different machine code for each type of machine. JVM executes the byte
code generated by compiler and produce output. JVM is the one that makes java platform
independent.
So, now we understood that the primary function of JVM is to execute the byte code produced by
compiler. Each operating system has different JVM, however the output they produce after execution
of byte code is same across all operating systems. Which means that the byte code generated on
Windows can be run on Mac OS and vice versa. That is why we call java as platform independent
language. The same thing can be seen in the diagram below:

Developed by: Sreedhar A, CSE Dept., RGUKT Page 7


So to summarise everything: The Java Virtual machine (JVM) is the virtual machine that runs on
actual machine (your computer) and executes Java byte code. The JVM doesn’t understand Java source
code, that’s why we need to have javac compiler that compiles *.java files to obtain *.class files that
contain the byte codes understood by the JVM. JVM makes java portable (write once, run anywhere).
Each operating system has different JVM, however the output they produce after execution of byte code
is same across all operating systems.
JVM Architecture

How JVW works:


Class Loader: The class loader reads the .class file and save the byte code in the method area.
Method Area: There is only one method area in a JVM which is shared among all the classes. This holds
the class level information of each .class file.
Heap: Heap is a part of JVM memory where objects are allocated. JVM creates a Class object for each
.class file.
Stack: Stack is a also a part of JVM memory but unlike Heap, it is used for storing temporary variables.
PC Registers: This keeps the track of which instruction has been executed and which one is going to be
executed. Since instructions are executed by threads, each thread has a separate PC register.
Native Method stack: A native method can access the runtime data areas of the virtual machine.
Native Method interface: It enables java code to call or be called by native applications. Native
applications are programs that are specific to the hardware and OS of a system.
Garbage collection: A class instance is explicitly created by the java code and after use it is automatically
destroyed by garbage collection for memory management.
JVM Vs JRE Vs JDK
JRE: JRE is the environment within which the java virtual machine runs. JRE contains Java virtual
Machine(JVM), class libraries, and other files excluding development tools such as compiler and
debugger.
Which means you can run the code in JRE but you can’t develop and compile the code in JRE.
JVM: As we discussed above, JVM runs the program by using class, libraries and files provided by JRE.

Developed by: Sreedhar A, CSE Dept., RGUKT Page 8


JDK: JDK is a superset of JRE, it contains everything that JRE has along with development tools such as compiler,
debugger etc.

Benefits of OOPs:
OOP offers several benefits to both the program developer and the user. The new technology
provides greater programmer productivity, better quality of software and lesser maintenance cost. The
major benefits are:
1. Ease in division of job: Since it is possible to map objects of the problem domain to those objects
in the program, the work can be easily partitioned based on objects.
2. Reduce complexity: Software complexity can be easily managed.
3. Provide extensibility: Object Oriented systems can be easily upgraded from small to large
system.
4. Eliminate redundancy: Through inheritance we can eliminate redundant code and extend the use
of existing classes.
5. Saves development time and increases productivity: Instead of writing code from scratch,
solutions can be built by using standard working modules.
6. Allows building secure programs: Data hiding principle helps programmer to build secure
programs that cannot be accessed by code in other parts of the program.
7. Allows designing simpler interfaces: Message passing techniques between objects allows making
simpler interface descriptions with external systems.
Applications of OOPs:
1. Object Oriented databases
2. Embedded systems
3. Simulation and modeling
4. Neural networks
5. Decision support systems
6. Office automation systems
7. AI and expert systems
8. CAD/CAM systems
9. Internet solutions.

Developed by: Sreedhar A, CSE Dept., RGUKT Page 9


API:
An application programming interface (API), in the context of Java, is a collection of prewritten
packages, classes, and interfaces with their respective methods, fields and constructors. Similar to a user
interface, which facilitates interaction between humans and computers, an API serves as a software
program interface facilitating interaction.
In Java, most basic programming tasks are performed by the API’s classes and packages, which
are helpful in minimizing the number of lines written within pieces of code.
Java Development Kit (JDK) is comprised of three basic components, as follows:
 Java compiler
 Java Virtual Machine (JVM)
 Java Application Programming Interface (API)
The Java API, included with the JDK, describes the function of each of its components. In Java
programming, many of these components are pre-created and commonly used. Thus, the programmer is
able to apply prewritten code via the Java API. After referring to the available API classes and packages,
the programmer easily invokes the necessary code classes and packages for implementation.

Introduction to JAVA
Types of java programming:
There are many types of Java programs which run differently:
 Java Applet - small program written in Java and that is downloaded from a website and executed
within a web browser on a client computer.
 Application - executes on a client computer. If online, it has to be downloaded before being run.
 JAR file (Java ARchive) - used to package Java files together into a single file (almost exactly like a
.zip file).
 Servlet - runs on a web server and helps to generate web pages.
 Swing application - used to build an application that has a GUI (windows, buttons, menus, etc.).
 EJB - runs on a web server and is used to develop large, complex websites.
How to Compile and Run your First Java Program
Simple Java Program:
public class FirstJavaProgram {
public static void main(String[] args){
[Link]("This is my first program in java");
}//End of main
}//End of FirstJavaProgram Class

Output: This is my first program in java

How to compile and run the above program


Prerequisite: You need to have java installed on your system.
Step 1: Open a text editor, like Notepad on windows and TextEdit on Mac. Copy the above program and
paste it in the text editor.

Developed by: Sreedhar A, CSE Dept., RGUKT Page 10


You can also use IDE like Eclipse to run the java program but we will cover that part later in the coming
tutorials.
Step 2: Save the file as [Link] You may be wondering why we have named the file as
FirstJavaProgram, the thing is that we should always name the file same as the public class name. In our
program, the public class name is FirstJavaProgram, that’s why our file name should be
[Link].
Step 3: In this step, we will compile the program. For this, open Terminal in Linux
To compile the program, type the following command and hit enter.
javac [Link]
Set path in Linux:
example: export PATH=$PATH:/home/jdk1.6.0/bin/
Step 4: After compilation the .java file gets translated into the .class file(byte code). Now we can run the
program. To run the program, type the following command and hit enter:
java FirstJavaProgram

Explanation to the First Java Program


public class FirstJavaProgram {
This is the first line of our java program. Every java application must have at least one class definition
that consists of class keyword followed by class name. When I say keyword, it means that it should not
be changed, we should use it as it is. However the class name can be anything.
You need to know now that a java file can have any number of classes but it can have only one public
class and the file name should be same as public class name.
public static void main(String[] args) {
This is our next line in the program, lets break it down to understand it:
public: This makes the main method public that means that we can call the method from outside the
class.
static: We do not need to create object for static methods to run. They can run itself.
void: It does not return anything.
main: It is the method name. This is the entry point method from which the JVM can run your program.
(String[] args): Used for command line arguments that are passed as strings.
[Link]("This is my first program in java");
This method prints the contents inside the double quotes into the console and inserts a newline after.

Variable
A Java variable is a piece of memory that can contain a data value. A variable thus has a data type.
Variables are typically used to store information which your Java program needs to do its job. This can be
any kind of information ranging from texts, codes to numbers, temporary results of multi step
calculations etc.
In the code example below, the main() method contains the declaration of a single integer variable
named number. The value of the integer variable is first set to 10, and then 20 is added to the variable
afterwards.

Developed by: Sreedhar A, CSE Dept., RGUKT Page 11


public class MyClass {
public static void main(String[] args) {
int number = 10;
number = number + 20;
}
}
Java Variable Types
In Java there are four types of variables:
1. Non-static fields
2. Static fields
3. Local variables
4. Parameters
1. A non-static field is a variable that belongs to an object. Objects keep their internal state in non-
static fields. Non-static fields are also called instance variables, because they belong to instances
(objects) of a class. Non-static fields are covered in more detail in the text on Java fields.
2. A static field is a variable that belongs to a class. A static field has the same value for all objects
that access it. Static fields are also called class variables. Static fields are also covered in more
detail in the text on Java fields.
3. A local variable is a variable declared inside a method. A local variable is only accessible inside the
method that declared it. Local variables are covered in more detail in the text on Java methods.
4. A parameter is a variable that is passed to a method when the method is called. Parameters are
also only accessible inside the method that declares them, although a value is assigned to them
when the method is called. Parameters are also covered in more detail in the text on Java
methods.

Java Variable Declaration


Exactly how a variable is declared depends on what type of variable it is (non-static, static, local,
parameter). However, there are certain similarities that
In Java you declare a variable like this:
type name ;
Instead of the word type, you write the data type of the variable. Similarly, instead of the word name
you write the name you want the variable to have.
Here is an example declaring a variable named myVariable of type int.
int myVariable;
Java Variable Assignment
Assigning a value to a variable in Java follows this pattern:
variableName = value ;
Here are three concrete examples which assign values to three different variables with different data
types
myInt = 127;
myFloat = 199.99;
myString = "This is a text";

Developed by: Sreedhar A, CSE Dept., RGUKT Page 12


Java Variable Naming Conventions
There are a few rules and conventions related to the naming of variables.
The rules are:
1. Java variable names are case sensitive. The variable name money is not the same as Money or
MONEY.
2. Java variable names must start with a letter, or the $ or _ character.
3. After the first character in a Java variable name, the name can also contain numbers (in addition
to letters, the $, and the _ character).
4. Variable names cannot be equal to reserved key words in Java. For instance, the words int or for
are reserved words in Java. Therefore you cannot name your variables int or for.
Here are a few valid Java variable name examples:
myvar
myVar
MYVAR
_myVar
$myVar
myVar1
myVar_1

Data Types

Data type defines the values that a variable can take, for example if a variable has int data type, it can
only take integer values.
In java we have two categories of data type:
1) Primitive data types 2) Non-primitive data types – Arrays and Strings are non-primitive data types.
1) Primitive data types
In Java, we have eight primitive data types: boolean, char, byte, short, int, long, float and double. Java
developers included these data types to maintain the portability of java as the size of these primitive
data types do not change from one operating system to another.
 byte, short, int and long data types are used for storing whole numbers.
 float and double are used for fractional numbers.
 char is used for storing characters(letters).
 boolean data type is used for variables that holds either true or false.

byte:
This can hold whole number between -128 and 127. Mostly used to save memory and when you are
certain that the numbers would be in the limit specified by byte data type.
Default size of this data type: 1 byte.
Default value: 0

Developed by: Sreedhar A, CSE Dept., RGUKT Page 13


Example:
class JavaExample {
public static void main(String[] args) {
byte num;
num = 113;
[Link](num);
}
}
Output:
113
Try the same program by assigning value assigning 150 value to variable num, you would get type
mismatch error because the value 150 is out of the range of byte data type. The range of byte as I
mentioned above is -128 to 127.

short:
This is greater than byte in terms of size and less than integer. Its range is -32,768 to 32767.
Default size of this data type: 2 byte
short num = 45678;

int:
Used when short is not large enough to hold the number, it has a wider range: -2,147,483,648 to
2,147,483,647
Default size: 4 byte
Default value: 0
Example:
class JavaExample {
public static void main(String[] args) {
short num;
num = 150;
[Link](num);
}
}
Output:
150

long:
Used when int is not large enough to hold the value, it has wider range than int data type, ranging from -
9,223,372,036,854,775,808 to 9,223,372,036,854,775,807.
size: 8 bytes
Default value: 0

Developed by: Sreedhar A, CSE Dept., RGUKT Page 14


Example:
class JavaExample {
public static void main(String[] args) {
long num = -12332252626L;
[Link](num);
}
}
Output:
-12332252626

double:
Sufficient for holding 15 decimal digits
size: 8 bytes
Example:
class JavaExample {
public static void main(String[] args) {

double num = -42937737.9d;


[Link](num);
}
}
Output:
-4.29377379E7

float:
Sufficient for holding 6 to 7 decimal digits
size: 4 bytes
class JavaExample {
public static void main(String[] args) {
float num = 19.98f;
[Link](num);
}
}
Output:
19.98

boolean:
Holds either true of false.
class JavaExample {
public static void main(String[] args) {
boolean b = false;
[Link](b);

Developed by: Sreedhar A, CSE Dept., RGUKT Page 15


}
}
Output:
false

char:
Holds characters.
Size: 2 bytes
class JavaExample {
public static void main(String[] args) {

char ch = 'Z';
[Link](ch);
}
}
Output:
Z

Literals in Java
A literal is a fixed value that we assign to a variable in a Program.
int num=10;
Here value 10 is a Integer literal.
char ch = 'A';
Here A is a char literal
Integer Literal
Integer literals are assigned to the variables of data type byte, short, int and long.
byte b = 100;
short s = 200;
int num = 13313131;
long l = 928389283L;
Float Literals
Used for data type float and double.
double num1 = 22.4;
float num2 = 22.4f;
Note: Always suffix float value with the “f” else compiler will consider it as double.
Char and String Literal
Used for char and String type.
char ch = 'Z';
String str = "BeginnersBook";

Developed by: Sreedhar A, CSE Dept., RGUKT Page 16


Java Keywords
Keywords are predefined, reserved words used in Java programming that have special meanings to the
compiler.
For example: int score;
Here, int is a keyword. It indicates that the variable score is of integer type.
You cannot use keywords like int, for, class etc as variable name (or identifiers) as they are part of the
Java programming language syntax. Here's the complete list of all keywords in Java programming.
Java Keywords List
abstract assert boolean break byte
case catch char class const
continue default do double else
enum extends final finally float
for goto if implements import
instanceof int interface long native
new package private protected public
return short static strictfp super
switch synchronized this throw throws
transient try void volatile while

Java identifiers
Identifiers are the name given to variables, classes, methods etc.
Example: int score;
Here, score is a variable (an identifier). You cannot use keywords as variable name. It's because keywords
have predefined meaning.
Rules for Naming an Identifier
 Identifier cannot be a keyword.
 Identifiers are case-sensitive.
 It can have a sequence of letters and digits. However, it must begin with a letter, $ or _. The first
letter of an identifier cannot be a digit.
 It's convention to start an identifier with a letter rather and $ or _.
 Whitespaces are not allowed.
 Similarly, you cannot use symbols such as @, #, and so on.
Java Command Line Arguments
The java command-line argument is an argument i.e. passed at the time of running the java
program. The arguments passed from the console can be received in the java program and it can be used
as an input. So, it provides a convenient way to check the behavior of the program for the different
values.
Example:
In this example, we are receiving only one argument and printing it. To run this java program, you must
pass at least one argument from the command prompt.

Developed by: Sreedhar A, CSE Dept., RGUKT Page 17


class CommandLineExample{
public static void main(String args[]){
[Link]("Your first argument is: "+args[0]);
}
}

compile by > javac [Link]


run by > java CommandLineExample sonoo

Basic Examples:
Java Program to read integer value from the Standard Input
In this program we will see how to read an integer number entered by user. Scanner class is in [Link]
package. It is used for capturing the input of the primitive types like int, double etc. and strings.

Methods for Scanner Objects:


Method Description
nextByte() reads an integer of the byte type.
nextShort() reads an integer of the short type.
nextInt() reads an integer of the int type.
nextLong() reads an integer of the long type.
nextFloat() reads a number of the float type.
nextDouble() reads a number of the double type.
next() reads a string that ends before a whitespace character.
nextLine() reads a line of text (i.e., a string ending with the Enter key pressed).

Program to read the number entered by user


We have imported the package [Link] to use the Scanner. In order to read the input provided
by user, we first create the object of Scanner by passing [Link] as parameter. Then we are using
nextInt() method of Scanner class to read the integer.

import [Link];
public class Demo {
public static void main(String[] args) {
Scanner scan = new Scanner([Link]);
[Link]("Enter any number: ");
// This method reads the number provided using keyboard
int num = [Link]();
// Closing Scanner after the use
[Link]();
// Displaying the number
[Link]("The number entered by user: "+num);
}

Developed by: Sreedhar A, CSE Dept., RGUKT Page 18


}
Output:
Enter any number: 101
The number entered by user: 101

Program to check whether the given number is positive or negative


In this program we have specified the value of number during declaration and the program checks
whether the specified number is positive or negative.
public class Demo
{
public static void main(String[] args)
{
int number=109;
if(number > 0)
{
[Link](number+" is a positive number");
}
else if(number < 0)
{
[Link](number+" is a negative number");
}
else
{
[Link](number+" is neither positive nor negative");
}
}
}
Output:
109 is a positive number
Example 2: Check whether the input number(entered by user) is positive or negative
Here we are using Scanner to read the number entered by user and then the program checks and
displays the result.
import [Link];
public class Demo
{
public static void main(String[] args)
{
int number;
Scanner scan = new Scanner([Link]);
[Link]("Enter the number you want to check:");
number = [Link]();
[Link]();

Developed by: Sreedhar A, CSE Dept., RGUKT Page 19


if(number > 0)
{
[Link](number+" is positive number");
}
else if(number < 0)
{
[Link](number+" is negative number");
}
else
{
[Link](number+" is neither positive nor negative");
}
}
}
Output:
Enter the number you want to check:-12
-12 is negative number
Sum of two numbers
public class AddTwoNumbers {
public static void main(String[] args) {
int num1 = 5, num2 = 15, sum;
sum = num1 + num2;
[Link]("Sum of these numbers: "+sum);
}
}
Output:
Sum of these numbers: 20
Sum of two numbers using Scanner
The scanner allows us to capture the user input so that we can get the values of both the numbers from
user. The program then calculates the sum and displays it.
import [Link];
public class AddTwoNumbers2 {
public static void main(String[] args) {
int num1, num2, sum;
Scanner sc = new Scanner([Link]);
[Link]("Enter First Number: ");
num1 = [Link]();
[Link]("Enter Second Number: ");
num2 = [Link]();
[Link]();
sum = num1 + num2;
[Link]("Sum of these numbers: "+sum);

Developed by: Sreedhar A, CSE Dept., RGUKT Page 20


}
}
Output:
Enter First Number:
121
Enter Second Number:
19
Sum of these numbers: 140

Control Flow Statements:


The program is a set of statements, which are stored into a file. The interpreter executes these
statements in a sequential manner, i.e., in the order in which they appear in the file. But there are
situations where programmers want to alter this normal sequential flow of control. For example, if one
wants to repeatedly execute a block of statements or one wants to conditionally execute statements.
Therefore’ one more category of statements called control flow statements is provided.

Statement Type Keyword


Selection If-else, nested if , if-else-if, switch-case
Iteration While, do-while, for
Jump Break, continue, label;, return
Exception handling Try-catch-finally, throw

Java if (if-then) Statement


The Java if statement tests the condition. It executes the if block, if condition is true.
The syntax:
if (expression) {
// statements
}
Flow chart:

Developed by: Sreedhar A, CSE Dept., RGUKT Page 21


Example:
class IfStatement {
public static void main(String[] args) {
int number = 10;
if (number > 0) {
[Link]("Number is positive.");
}
[Link]("This statement is always executed.");
}
}
Output:
Number is positive.

Java if...else Statement


The if statement executes a certain section of code if the test expression is evaluated to true. The
if statement can have optional else statement. Codes inside the body of else statement are executed if
the test expression is false.
Syntax:
if (expression) {
// codes
}
else {
// some other code
}
Flowchart:

Developed by: Sreedhar A, CSE Dept., RGUKT Page 22


Example:
class IfElse {
public static void main(String[] args) {
int number = 10;
if (number > 0) {
[Link]("Number is positive.");
}
else {
[Link]("Number is not positive.");
}
[Link]("This statement is always executed.");
}
}
Output:
Number is positive.

Java IF-else-if ladder Statement


The if-else-if ladder statement executes one condition from multiple statements.
Syntax:
if (expression1)
{
// codes
}
else if(expression2)
{
// codes
}
else if (expression3)
{
// codes
}
.
.
else
{
// codes
}
The if statements are executed from the top towards the bottom. As soon as the test expression is true,
codes inside the body of that if statement is executed. Then, the control of program jumps outside if-
else-if ladder. If all test expressions are false, codes inside the body of else is executed.
Flowchart:

Developed by: Sreedhar A, CSE Dept., RGUKT Page 23


Example:
class Ladder {
public static void main(String[] args) {

int number = 0;

if (number > 0) {
[Link]("Number is positive.");
}
else if (number < 0) {
[Link]("Number is negative.");
}
else {
[Link]("Number is 0.");
}
}
}
Output:
Number is 0.

Nested if…else:
A nested if is an if statement that is the target of another if statement. Nested if statements
means an if statement inside another if statement

Developed by: Sreedhar A, CSE Dept., RGUKT Page 24


Example:
class Number{
public static void main(String[] args) {

Double n1 = -1.0, n2 = 4.5, n3 = -5.3, largestNumber;

if (n1 >= n2) {


if (n1 >= n3) {
largestNumber = n1;
}
else {
largestNumber = n3;
}
}
else {
if (n2 >= n3) {
largestNumber = n2;
}
else {
largestNumber = n3;
}
}

[Link]("Largest number is " + largestNumber);


}
}
Output:
Largest number is 4.5
Flow chart:

Developed by: Sreedhar A, CSE Dept., RGUKT Page 25


Switch Statement:
The Java switch statement executes one statement from multiple conditions. It is like if-else-if ladder
statement.
Syntax:
switch (variable/expression) {
case value1:
// statements
break;
case value2:
// statements
break;
.. .. ...
.. .. ...
default:
// statements
}
It's also important to note that switch statement in Java only works with:
 Primitive data types: byte, short, char and int
 Enumerated types (Java enums)
 String class
 a few classes that wrap primitive types: Character, Byte, Short, and Integer.

Developed by: Sreedhar A, CSE Dept., RGUKT Page 26


Flowchart:

Example 1:
class Day {
public static void main(String[] args) {

int week = 4;
String day;

switch (week) {
case 1:
day = "Sunday";
break;
case 2:
day = "Monday";
break;
case 3:
day = "Tuesday";
break;
case 4:
day = "Wednesday";
break;
case 5:

Developed by: Sreedhar A, CSE Dept., RGUKT Page 27


day = "Thursday";
break;
case 6:
day = "Friday";
break;
case 7:
day = "Saturday";
break;
default:
day = "Invalid day";
break;
}
[Link](day);
}
}
Output:
Wednesday
Example 2:
The program below takes three inputs from the user: operator and 2 numbers. It performs calculation
based on numbers and operator entered. Then the result is displayed on the screen.
We have used Scanner object to take input from the user.
import [Link];
class Calculator {
public static void main(String[] args) {
char operator;
int number1, number2, result;
float div;
Scanner scanner = new Scanner([Link]);
[Link]("Enter operator (either +, -, * or /): ");
operator = [Link]().charAt(0);
[Link]("Enter number1 and number2 respectively: ");
number1 = [Link]();
number2 = [Link]();

switch (operator) {
case '+':
result = number1 + number2;
[Link](number1 + "+" + number2 + " = " + result);
break;

case '-':
result = number1 - number2;

Developed by: Sreedhar A, CSE Dept., RGUKT Page 28


[Link](number1 + "-" + number2 + " = " + result);
break;

case '*':
result = number1 * number2;
[Link](number1 + "*" + number2 + " = " + result);
break;

case '/':
div =(float) number1 / number2;
[Link](number1 + "/" + number2 + " = " + result);
break;

default:
[Link]("Invalid operator!");
break;
}
}
}
Output:
Enter operator (either +, -, * or /): *
Enter number1 and number2 respectively: 1
-5
1*-5 = -5
break statement
When a break statement is encountered inside a loop, the loop is terminated and program
control resumes at the next statement following the loop. Here is a simple example:
Example:
public class BreakDemo
{
public static void main(String[] args)
{
for (int i = 1; i <= 10; i++)
{
if (i == 5)
{
break; // terminate loop if i is 5
}
[Link](i + " ");
}
[Link]("Loop is over.");
}

Developed by: Sreedhar A, CSE Dept., RGUKT Page 29


}
Output :
1 2 3 4 Loop is over.
continue statement :
When a continue statement is encountered inside the body of a loop, remaining statements are
skipped and loop proceeds with the next iteration. Here is a simple example.
Example:
public class ContinueDemo
{
public static void main(String[] args)
{
for (int i = 1; i <= 10; i++)
{
if (i % 2 == 0)
{
continue; // skip next statement if i is even
}
[Link](i + " ");
}
}
}
Output : 13579

Loops in Java:
Looping in programming languages is a feature which facilitates the execution of a set of
instructions/functions repeatedly while some condition evaluates to true.
Java provides three ways for executing the loops. While all the ways provide similar basic functionality,
they differ in their syntax and condition checking time.
They are:
1. while loop
2. for loop
3. do-while loop

while loop: A while loop is a control flow statement that allows code to be executed repeatedly based on
a given Boolean condition. The while loop can be thought of as a repeating if statement.
Syntax :
while (boolean condition)
{
loop statements...
}

Developed by: Sreedhar A, CSE Dept., RGUKT Page 30


Flowchart:

 While loop starts with the checking of condition. If it evaluated to true, then the loop body
statements are executed otherwise first statement following the loop is executed. For this reason
it is also called Entry control loop.
 Once the condition is evaluated to true, the statements in the loop body are executed. Normally
the statements contain an update value for the variable being processed for the next iteration.
 When the condition becomes false, the loop terminates which marks the end of its life cycle.
Example Program:
// Java program to illustrate while loop
class whileLoopDemo
{
public static void main(String args[])
{
int x = 1;

// Exit when x becomes greater than 4


while (x <= 4)
{
[Link]("Value of x:" + x);

//increment the value of x for next iteration


x++;
}
}
}
Output:
Value of x:1
Value of x:2
Value of x:3
Value of x:4

Developed by: Sreedhar A, CSE Dept., RGUKT Page 31


for loop:
for loop provides a concise way of writing the loop structure. Unlike a while loop, a for statement
consumes the initialization, condition and increment/decrement in one line thereby providing a shorter,
easy to debug structure of looping.
Syntax:
for (initialization condition; testing condition; increment/decrement)
{
statement(s)
}
 Initialization condition: Here, we initialize the variable in use. It marks the start of a for loop. An
already declared variable can be used or a variable can be declared, local to loop only.
 Testing Condition: It is used for testing the exit condition for a loop. It must return a Boolean
value. It is also an Entry Control Loop as the condition is checked prior to the execution of the
loop statements.
 Statement execution: Once the condition is evaluated to true, the statements in the loop body
are executed.
 Increment/ Decrement: It is used for updating the variable for next iteration.
 Loop termination: When the condition becomes false, the loop terminates marking the end of its
life cycle.
Flowchart:

Example:
// Java program to illustrate for loop.
class forLoopDemo
{
public static void main(String args[])
{
// for loop begins when x=2
// and runs till x <=4
for (int x = 2; x <= 4; x++)
[Link]("Value of x:" + x);

Developed by: Sreedhar A, CSE Dept., RGUKT Page 32


}
}
Output:
Value of x:2
Value of x:3
Value of x:4

Enhanced For loop


Enhanced for loop provides a simpler way to iterate through the elements of a collection or array.
It is inflexible and should be used only when there is a need to iterate through the elements in sequential
manner without knowing the index of currently processed element.
Syntax:
for (T element:Collection obj/array)
{
statement(s)
}
Suppose there is an array of names and we want to print all the names in that array. Let’s see the
difference with these two examples
Enhanced for loop simplifies the work as follows-
Example: Java program to illustrate enhanced for loop
public class enhancedforloop
{
public static void main(String args[])
{
String array[] = {"IIIT", "RGUKT", "Basar"};
//enhanced for loop
for (String x:array)
{
[Link](x);
}
/* for loop for same function
for (int i = 0; i < [Link]; i++)
{
[Link](array[i]);
}
*/
}
}
Output:
IIIT
RGUKT
Basar

Developed by: Sreedhar A, CSE Dept., RGUKT Page 33


do while: do while loop is similar to while loop with only difference that it checks for condition after
executing the statements, and therefore is an example of Exit Control Loop.
Syntax:
do
{
statements..
}
while (condition);
Flowchart:

 do while loop starts with the execution of the statement(s). There is no checking of any condition
for the first time.
 After the execution of the statements, and update of the variable value, the condition is checked
for true or false value. If it is evaluated to true, next iteration of loop starts.
 When the condition becomes false, the loop terminates which marks the end of its life cycle.
 It is important to note that the do-while loop will execute its statements atleast once before any
condition is checked, and therefore is an example of exit control loop.
Example: Java program to illustrate do-while loop
class dowhileloopDemo
{
public static void main(String args[])
{
int x = 21;
do
{
[Link]("Value of x:" + x);
x++;
}
while (x < 20);
}
}
Output:
Value of x: 21
Developed by: Sreedhar A, CSE Dept., RGUKT Page 34

You might also like