[go: up one dir, main page]

0% found this document useful (0 votes)
37 views51 pages

JAVA Unit-1

The document provides an overview of Java programming, covering its history, features, platforms, and basic structure. It explains key concepts such as the Java Development Kit, Java Runtime Environment, and Java Virtual Machine, along with differences between Java and C++. Additionally, it discusses tokens in Java programs, including keywords, identifiers, literals, operators, and separators.

Uploaded by

vishnumangina543
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)
37 views51 pages

JAVA Unit-1

The document provides an overview of Java programming, covering its history, features, platforms, and basic structure. It explains key concepts such as the Java Development Kit, Java Runtime Environment, and Java Virtual Machine, along with differences between Java and C++. Additionally, it discusses tokens in Java programs, including keywords, identifiers, literals, operators, and separators.

Uploaded by

vishnumangina543
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
You are on page 1/ 51

UNIT-I

Contents
1.1 Program Structure in Java:
1.1.1 Introduction,
1.1.2 Writing Simple Java Programs,
1.1.3 Tokens in Java Programs,
1.1.4 Command Line Arguments,
1.1.5 Comments.
1.2 Data Types, Variables, and Operators:
1.2.1 Introduction,
1.2.2 Data Types in Java,
1.2.3 Static Variables and Methods,(It will be covered
in unit-2)
1.2.4 Attribute Final, (It will be covered in unit-3)
1.2.5 Operators.
1.3 Control Statements:
1.3.1 If Expression,
1.3.2 Switch Statement,
1.3.3 Loops
1.1 Program Structure in Java
1.1.1 Introduction
History of Java:
James Gosling invented a platform independent programming language called as JAVA in the year
1994. At first Java was called as OAK. Java was originally designed for interactive TV, but the digital
cable industry wasn’t ready for the technology.
Java started out as a research project. Research began in 1991 as the Green Project at Sun
Microsystems, Inc. Research efforts birthed a new language, OAK. (A tree outside of the window of
James Gosling’s office at Sun). It was developed as an embedded programming language, which
would enable embedded system application. It was not really created as web programming language.
Java is available as jdk and it is an open-source s/w.
Language was created with 5 main goals:
 It should be object oriented.
 A single representation of a program could be executed on multiple operating systems. (i.e.
write once, run anywhere)
 It should fully support network programming.
 It should execute code from remote sources securely.
 It should be easy to use.
Oak was renamed Java in 1994. Now Sun Microsystems is a subsidiary of Oracle Corporation.

Java Platforms:
There are three main platforms for Java:
Java SE (Java Platform, Standard Edition) – runs on desktops and laptops.
Java ME (Java Platform, Micro Edition) – runs on mobile devices such as cell phones.
Java EE (Java Platform, Enterprise Edition) – runs on servers.

Features of Java (Java Buzz Words):


Simple: No pointers. Automatic garbage collection. Rich pre-defined class library.
Object Oriented: Focus on the data (objects) and methods manipulating the data. All methods are
associated with objects. Potentially better code organization and reuse
Compile, Interpreted and High Performance: Java compiler generate byte-codes, not native
machine code. The compiled byte-codes are platform-independent. Java byte codes are translated on
the fly to machine readable instructions in runtime (Java Virtual Machine). Easy to translate directly
into native machine code by using a just-in-time compiler.
Portable: Same application runs on all platforms. The sizes of the primitive data types are always the
same. The libraries define portable interfaces.
Reliable/Robust: Extensive compile-time and runtime error checking. No pointers but real arrays.
Memory corruptions or unauthorized memory accesses are impossible. Automatic garbage collection
tracks objects usage over time.
Secure: Java’s robustness features make java secure. Access restrictions are forced (private, public)
Java Features.
Multithreaded: It supports multithreaded programming. Need not wait for the application to finish
one task before beginning another one.
Dynamic: Libraries can freely add new methods and instance variables without any effect on their
clients. Interfaces promote flexibility and reusability in code by specifying a set of methods an object
can perform, but leaves open how these methods should be implemented.
Distributed: Java is designed for the distributed environment of the Internet, because it handles
TCP/IP protocols. Allows objects on two different computers to execute procedures remotely by using
package called Remote Method Invocation (RMI).
Architecture-Neutral: Goal of java designers is “write once; run anywhere, anytime, forever.”

Java Terminology:
Java Development Kit: It contains one (or more) JRE's along with the various development tools
like the Java source compilers, bundling and deployment tools, debuggers, development libraries, etc.
Java Runtime Environment: A runtime environment which implements Java Virtual Machine, and
provides all class libraries and other facilities necessary to execute Java programs. This is the software
on your computer that actually runs Java programs. JRE = JVM + Java Packages Classes (like util,
math, lang, awt, swing etc) +runtime libraries.

JVM (Java Virtual Machine) Architecture


JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime
environment in which java bytecode can be executed.

JVMs are available for many hardware and software platforms (i.e. JVM is platform dependent).

What is JVM
1. A specification where working of Java Virtual Machine is specified. But implementation provider is
independent to choose the algorithm. Its implementation has been provided by Oracle and other
companies.
2. An implementation Its implementation is known as JRE (Java Runtime Environment).
3. Runtime Instance Whenever you write java command on the command prompt to run the java class,
an instance of JVM is created.

What it does
The JVM performs following operation:

o Loads code
o Verifies code
o Executes code
o Provides runtime environment

JVM provides definitions for the:

o Memory area
o Class file format
o Register set
o Garbage-collected heap
o Fatal error reporting etc.

JVM Architecture
Let's understand the internal architecture of JVM. It contains classloader, memory area, execution
engine etc.
1) Class loader

Class loader is a subsystem of JVM which is used to load class files. Whenever we run the java
program, it is loaded first by the class loader. There are three built-in class loaders in Java.

2) Class(Method) Area

Class(Method) Area stores per-class structures such as the runtime constant pool, field and method
data, the code for methods.

3) Heap

It is the runtime data area in which objects are allocated.

4) Stack

Java Stack stores frames. It holds local variables and partial results, and plays a part in method
invocation and return. Each thread has a private JVM stack, created at the same time as thread. A new
frame is created each time a method is invoked. A frame is destroyed when its method invocation
completes.

5) Program Counter Register

PC (program counter) register contains the address of the Java virtual machine instruction currently
being executed.

6) Native Method Stack

It contains all the native methods used in the application.

7) Execution Engine

It contains:

1. A virtual processor
2. Interpreter: Read bytecode stream then execute the instructions.
3. Just-In-Time(JIT) compiler: It is used to improve the performance. JIT compiles parts of the byte
code that have similar functionality at the same time, and hence reduces the amount of time needed for
compilation. Here, the term "compiler" refers to a translator from the instruction set of a Java virtual
machine (JVM) to the instruction set of a specific CPU.
8) Java Native Interface

Java Native Interface (JNI) is a framework which provides an interface to communicate with another
application written in another language like C, C++, Assembly etc. Java uses JNI framework to send output to
the Console or interact with OS libraries.

Structure of Java Program


Java is an object-oriented programming, platform-independent, and secure programming language
that makes it popular. Using the Java programming language, we can develop a wide variety of
applications. So, before diving in depth, it is necessary to understand the basic structure of Java
program in detail. In this section, we have discussed the basic structure of a Java program. At the
end of this section, you will able to develop the Hello world Java program, easily.
Differences between C++ and Java

C++ Java
C++ is designed to work with compiler only Java can support both compiler and interpreter

Platform dependent Platform independent

C++ uses “cin” and “cout” Complex in/out methods (System.in and System.out)

Incorporates backward compatibility with C No backward compatibility support


C++ is a combination of OOPs and
Supports only Object-Oriented Programming style
Procedural type of programming

Memory management is manual, and the user is


JVM manages memory without user intervention
responsible for the memory consumed

C++ can provide multiple inheritances Java cannot support multiple inheritances
C++ supports both method overloading
Java supports only method overloading
and operator overloading
Source code is not portable between
Source code is portable to any operating system
different operating systems
Libraries offer low-level of functionality Libraries offer high-level functionality

The programmer is responsible for run-time JVM is responsible for run-time errors and
errors and exceptions exceptions

C++ supports pointers Java does not have pointers

C++ supports structures (custom data type) Java does not provide structures

C++ supports unions Java does not provide unions

C++ needs manual class and object Java is completely automatic regarding class and
management using new and delete keywords object management

C++ needs manual garbage memory clearance Java has an automatic garbage collector
Differences between procedural and object-oriented programming
Below are some of the differences between procedural and object-oriented
programming:

Procedural Oriented Programming Object-Oriented Programming

In object-oriented programming, the


In procedural programming, the program is
program is divided into small parts
divided into small parts called functions.
called objects.

Procedural programming follows a top- Object-oriented programming follows


down approach. a bottom-up approach.

Object-oriented programming has access


There is no access specifier in procedural
specifiers like private, public, protected,
programming.
etc.

Adding new data and functions is not easy. Adding new data and function is easy.

Procedural programming does not have any


Object-oriented programming provides
proper way of hiding data so it is less
data hiding so it is more secure.
secure.

In procedural programming, overloading is Overloading is possible in object-oriented


not possible. programming.

In object-oriented programming, the


In procedural programming, there is no
concept of data hiding and inheritance is
concept of data hiding and inheritance.
used.

In procedural programming, the function is In object-oriented programming, data is


more important than the data. more important than function.

Procedural programming is based on Object-oriented programming is based on


the unreal world. the real world.

Procedural programming is used for Object-oriented programming is used for


designing medium-sized programs. designing large and complex programs.
Procedural Oriented Programming Object-Oriented Programming

Procedural programming uses the concept Object-oriented programming uses the


of procedure abstraction. concept of data abstraction.

Code reusability absent in procedural Code reusability present in object-oriented


programming, programming.

Examples: C, FORTRAN, Pascal, Basic,


Examples: C++, Java, Python, C#, etc.
etc.

1.1.2 SIMPLE PROGRAM


Program:
class HelloWorld
{
public static void main (String args [])
{
System.out.println (“Welcome to Java Programming”);
}
}
public allows the program to control the visibility of class members. When a class member is preceded
by public, then that member may be accessed by code outside the class in which it is declared. In this
case, main ( ) must be declared as public, since it must be called by code outside of its class when the
program is started.
static allows main( ) to be called without having to instantiate a particular instance of the class. This
is necessary since main ( ) is called by the Java interpreter before any objects are made.
void states that the main method will not return any value.
main() is called when a Java application begins. In order to run a class, the class must have a main
method.
string args[] declares a parameter named args, which is an array of String. In this case, args receives
any command-line arguments present when the program is executed.
System is a class which is present in java.lang package.
out is a static field present in system class which returns a PrintStream object. As out is a static field
it can call directly with classname.
println() is a method which present in PrintStream class which can call through the PrintStream object
return by static field out present in System class to print a line to console.

Java achieving
platform independence:
What is Platform?
Computer is a combination of hardware and software this is called as "PLATFORM". Hardware mostly refers
to microprocessor. Software mostly refers to Operating System. The combination of microprocessor and OS is
called as platform.
platform dependency means the operating system of compilation and operating system of execution should be
same.

JAVA designed its own compiler called as Java Compiler which converts HLL into byte codes. This
byte code is given to Java Virtual Machine (JVM) which converts it to MLL.
Java Execution Procedure:
WORKING:
Let us assume you are writing code using java in your computer which has windows OS. User should
save the file with the extension ".java" so that it is consider to be a java file. For example, consider
Test.java is a file which consist of HLL code. Since Machine understands Machine Level code [MLL]
not your high-level code [HLL], conversion must happen.
Let us see how exactly conversion happens in java. Initially your HLL code is given as input to
compiler but java compiler will not give MLL code as output like C and C++ compiler rather it takes
HLL as input and gives a special type of code as output called as "BYTE CODE" which is platform
independent. Byte code is neither HLL code nor MLL code, hence it is also referred to as intermediate
code. If you can recollect machine understands only MLL code but java compiler gave you byte code.
To resolve this, James Gosling provided a software called as "Java virtual Machine"(JVM) which was
platform dependent that is different OS have different JVM. Since you are writing code on windows
OS, you will have to download windows compatible JVM. JVM will now convert byte code to
machine level code which machine can easily understand. In this way, java achieved platform in
dependency using a special type of code which is byte code

Disadvantage of Java
● In java, extra step is involved in conversion from HLL to java code to MLL code java program are
relatively slower in execution when compared to C/C++ programs.
● Time consumption is more in java.
● Speed of execution is slower.
Flowchart 1 is execution steps in C and Flowchart 2 is execution steps in Java.

1.1.3 Tokens in Java Programs


In Java, the program contains classes and methods. Further, the methods contain the expressions and
statements required to perform a specific operation. These statements and expressions are made up
of tokens. In other words, we can say that the expression and statement is a set of tokens. The tokens
are the small building blocks of a Java program that are meaningful to the Java compiler. Further,
these two components contain variables, constants, and operators.

What is token in Java?

The Java compiler breaks the line of code into text (words) is called Java tokens. These are the
smallest element of the Java program. The Java compiler identified these words as tokens. These
tokens are separated by the delimiters. It is useful for compilers to detect errors. Remember that the
delimiters are not part of the Java tokens.

token <= identifier | keyword | separator | operator | literal | comment


public class Demo
{
public static void main(String args[])
{
System.out.println("javatpoint");
}
}

In the above code snippet, public, class, Demo, {, static, void, main, (, String, args, [ ], ), System,
., out, println, javatpoint, etc. are the Java tokens.

Types of Tokens

Java token includes the following:

1. Keywords
2. Identifiers
3. Literals
4. Operators
5. Separators
6. Comments

1)Java Keywords

Java keywords are also known as reserved words. Keywords are particular words that act as a key to
a code. These are predefined words by Java so they cannot be used as a variable or object name or
class name.

List of Java Keywords

A list of Java keywords or reserved words are given below:

1. abstract: Java abstract keyword is used to declare an abstract class. An abstract class can
provide the implementation of the interface. It can have abstract and non-abstract methods.
2. boolean: Java boolean keyword is used to declare a variable as a boolean type. It can hold
True and False values only.
3. break: Java break keyword is used to break the loop or switch statement. It breaks the current
flow of the program at specified conditions.
4. byte: Java byte keyword is used to declare a variable that can hold 8-bit data values.
5. case: Java case keyword is used with the switch statements to mark blocks of text.
6. catch: Java catch keyword is used to catch the exceptions generated by try statements. It must
be used after the try block only.
7. char: Java char keyword is used to declare a variable that can hold unsigned 16-bit Unicode
characters
8. class: Java class keyword is used to declare a class.
9. continue: Java continue keyword is used to continue the loop. It continues the current flow of
the program and skips the remaining code at the specified condition.
10. default: Java default keyword is used to specify the default block of code in a switch
statement.
11. do: Java do keyword is used in the control statement to declare a loop. It can iterate a part of
the program several times.
12. double: Java double keyword is used to declare a variable that can hold 64-bit floating-point
number.
13. else: Java else keyword is used to indicate the alternative branches in an if statement.
14. enum: Java enum keyword is used to define a fixed set of constants. Enum constructors are
always private or default.
15. extends: Java extends keyword is used to indicate that a class is derived from another class or
interface.
16. final: Java final keyword is used to indicate that a variable holds a constant value. It is used
with a variable. It is used to restrict the user from updating the value of the variable.
17. finally: Java finally keyword indicates a block of code in a try-catch structure. This block is
always executed whether an exception is handled or not.
18. float: Java float keyword is used to declare a variable that can hold a 32-bit floating-point
number.
19. for: Java for keyword is used to start a for loop. It is used to execute a set of
instructions/functions repeatedly when some condition becomes true. If the number of iteration
is fixed, it is recommended to use for loop.
20. if: Java if keyword tests the condition. It executes the if block if the condition is true.
21. implements: Java implements keyword is used to implement an interface.
22. import: Java import keyword makes classes and interfaces available and accessible to the
current source code.
23. instanceof: Java instanceof keyword is used to test whether the object is an instance of the
specified class or implements an interface.
24. int: Java int keyword is used to declare a variable that can hold a 32-bit signed integer.
25. interface: Java interface keyword is used to declare an interface. It can have only abstract
methods.
26. long: Java long keyword is used to declare a variable that can hold a 64-bit integer.
27. native: Java native keyword is used to specify that a method is implemented in native code
using JNI (Java Native Interface).
28. new: Java new keyword is used to create new objects.
29. null: Java null keyword is used to indicate that a reference does not refer to anything. It
removes the garbage value.
30. package: Java package keyword is used to declare a Java package that includes the classes.
31. private: Java private keyword is an access modifier. It is used to indicate that a method or
variable may be accessed only in the class in which it is declared.
32. protected: Java protected keyword is an access modifier. It can be accessible within the
package and outside the package but through inheritance only. It can't be applied with the
class.
33. public: Java public keyword is an access modifier. It is used to indicate that an item is
accessible anywhere. It has the widest scope among all other modifiers.
34. return: Java return keyword is used to return from a method when its execution is complete.
35. short: Java short keyword is used to declare a variable that can hold a 16-bit integer.
36. static: Java static keyword is used to indicate that a variable or method is a class method. The
static keyword in Java is mainly used for memory management.
37. strictfp: Java strictfp is used to restrict the floating-point calculations to ensure portability.
38. super: Java super keyword is a reference variable that is used to refer to parent class objects.
It can be used to invoke the immediate parent class method.
39. switch: The Java switch keyword contains a switch statement that executes code based on test
value. The switch statement tests the equality of a variable against multiple values.
40. synchronized: Java synchronized keyword is used to specify the critical sections or methods
in multithreaded code.
41. this: Java this keyword can be used to refer the current object in a method or constructor.
42. throw: The Java throw keyword is used to explicitly throw an exception. The throw keyword
is mainly used to throw custom exceptions. It is followed by an instance.
43. throws: The Java throws keyword is used to declare an exception. Checked exceptions can be
propagated with throws.
44. transient: Java transient keyword is used in serialization. If you define any data member as
transient, it will not be serialized.
45. try: Java try keyword is used to start a block of code that will be tested for exceptions. The try
block must be followed by either catch or finally block.
46. void: Java void keyword is used to specify that a method does not have a return value.
47. volatile: Java volatile keyword is used to indicate that a variable may change asynchronously.
48. while: Java while keyword is used to start a while loop. This loop iterates a part of the program
several times. If the number of iteration is not fixed, it is recommended to use the while loop.

2)Identifier: Identifiers are used to name a variable, constant, function, class, and array. It usually
defined by the user. It uses letters, underscores, or a dollar sign as the first character. The label is also
known as a special kind of identifier that is used in the goto statement. Remember that the identifier
name must be different from the reserved keywords.

There are some rules to declare identifiers are:

o The first letter of an identifier must be a letter, underscore or a dollar sign. It cannot start with
digits but may contain digits.
o The whitespace cannot be included in the identifier.
o Identifiers are case sensitive.

Examples:

PhoneNumber
PRICE
radius
a
a1
_phonenumber
$circumference
jagged_array
12radius //invalid

3)Literals: In programming literal is a notation that represents a fixed value (constant) in the source
code. It can be categorized as an integer literal, string literal, Boolean literal, etc. It is defined by the
programmer. Once it has been defined cannot be changed.

Java provides five types of literals are as follows:


o Integer
o Floating Point
o Character
o String
o Boolean
Literal Type

23 int

9.86 double

false, true boolean

'K', '7', '-' char

"javatpoint" String

null any reference type

4)Operators: In programming, operators are the special symbol that tells the compiler to perform a
special operation. Java provides different types of operators that can be classified according to the
functionality they provide.

There are eight types of operators in Java, are as follows:


o Arithmetic Operators
o Assignment Operators
o Relational Operators
o Unary Operators
o Logical Operators
o Ternary Operators
o Bitwise Operators
o Shift Operators
5)Separators: The separators in Java is also known as punctuators.

There are nine separators in Java, are as follows:

separator <= ; | , | . | ( | ) | { | } | [ | ]
o Square Brackets []: It is used to define array elements. A pair of square brackets represents
the single-dimensional array, two pairs of square brackets represent the two-dimensional array.
o Parentheses (): It is used to call the functions and parsing the parameters.
o Curly Braces {}: The curly braces denote the starting and ending of a code block.
o Comma (,): It is used to separate two values, statements, and parameters.
o Assignment Operator (=): It is used to assign a variable and constant.
o Semicolon (;): It is the symbol that can be found at end of the statements. It separates the two
statements.
o Period (.): It separates the package name form the sub-packages and class. It also separates a
variable or method from a reference variable.

6)Java Comments: The Java comments are the statements in a program that are not executed by the
compiler and interpreter.

Why do we use comments in a code?

o Comments are used to make the program more readable by adding the details of the code.
o It makes easy to maintain the code and to find the errors easily.
o The comments can be used to provide information or explanation about the variable,
method, class, or any statement.
o It can also be used to prevent the execution of program code while testing the alternative code.

1.1.4 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 behaviour of the program for the different values.
You can pass N (1,2,3 and so on) numbers of arguments from the command prompt.
What is this Identifier?
It is nothing but String [] args It is the command line argument which stores data and it is nothing but
an array.

What is args?
Arguments means data passed on the command line. Args is technically called as "Dynamic Array"
using which the command line arguments are collected. In java, along with the control of execution
we can also give inputs/ data to the main method. To collect the input / data there is args. Initially args
is an empty basket.
Different way to declare Syntax / Signatures in main method
● public static void main (String [] args)
● static public void main (String [] args)
● public static void main (String args [])
● public static void main (String...args)

1.1.5 Java Comments


The Java comments are the statements in a program that are not executed by the compiler and
interpreter.
Types of Java Comments

There are three types of comments in Java.

1. Single Line Comment


2. Multi Line Comment
3. Documenation Comment

1) Java Single Line Comment

The single-line comment is used to comment only one line of the code. It is the widely used and easiest
way of commenting the statements. Single line comments starts with two forward slashes (//). Any
text in front of // is not executed by Java.

Syntax:
//This is single line comment
2) Java Multi Line Comment

The multi-line comment is used to comment multiple lines of code. It can be used to explain a complex
code snippet or to comment multiple lines of code at a time (as it will be difficult to use single-line
comments there). Multi-line comments are placed between /* and */. Any text between /* and */ is
not executed by Java.

Syntax:
/*
This
is
multi line
comment
*/
3) Java Documentation Comment

Documentation comments are usually used to write large programs for a project or software
application as it helps to create documentation API. These APIs are needed for reference, i.e., which
classes, methods, arguments, etc., are used in the code.

To create documentation API, we need to use the javadoc tool. The documentation comments are
placed between /** and */.

Syntax:
/**
*
*We can use various tags to depict the parameter
*or heading or author name
*We can also use HTML tags
*
*/

1.2 Data Types, Variables, and Operators


1.2.1 Introduction
The data type of a value (or variable in some contexts) is an attribute that tells what kind of data that
value can have. Most often the term is used in connection with static typing of variables in
programming languages like C/C++, Java and C# etc, where the type of a variable is known at compile
time. Data types include the storage classifications like integers, floating point values, strings,
characters etc.
Data types are especially important in Java because it is a strongly typed language. This means that
all operations are type-checked by the compiler for type compatibility. Illegal operations will not be
compiled. Thus, strong type checking helps prevent errors and enhances reliability. To enable strong
type checking, all variables, expressions, and values have a type. There is no concept of a “type-less”
variable, for example. Furthermore, the type of a value determines what operations are allowed on it.
An operation allowed on one type might not be allowed on another.

1.2.2 Data Types in Java


Data types specify the different sizes and values that can be stored in the variable. There are two types
of data types in Java:

1. Primitive data types: The primitive data types include boolean, char, byte, short, int, long, float and
double.
2. Non-primitive data types: The non-primitive data types include Classes, Interfaces, Strings
and Arrays.

Java Primitive Data Types:

In Java language, primitive data types are the building blocks of data manipulation. These are the most
basic data types available in Java language.

Integer Data Types:


Java does not support unsigned, positive-only integers. All are signed, positive and negative values.
Integer types of data represent integer number without any fractional parts or decimal points.
For example: age of a person, number of students in a class, distance between planets, distance
between galaxy, etc.,
In Java, to store Integer type data we have four data types.
1)Byte Data Type: The smallest integer type is byte. Variables of type byte are especially useful while
working with a stream of data from a network or file. Byte variables are declared by use of the byte
keyword.

Syntax:
byte byteVar;
Ex: byte b, c=100;
2) short is a signed 16-bit byte. Assume, if we create a short type variable as short a; It means in the
memory two bytes is allocated and it is referred as a
Syntax:
short shortVar;
Ex: short b, c=234;
3) int is a signed 32-bit byte. It is the most commonly used integer type. In addition to other uses,
variables of type int are commonly employed to control loops and to index arrays. Assume, if we
create an int type variable as int a; It means in the memory four bytes is allocated and it is referred as
a.
Syntax:
int intVar;
Ex: int b, c=234443;
4) long is a signed 64-bit byte and is useful for those occasions where an int type is not large enough
to hold the desired value. The range of long is quite large. This is useful, when big whole numbers are
needed. Assume, if we create an long type variable as long a; It means in the memory eight bytes is
allocated and it is referred as a.

Syntax:
long longVar;
Ex: long b, c=233444L;

Floating Point Types:


There are two kinds of floating-point types. All math functions, such as sin( ), cos( ), and sqrt( ), return
double values.
1)float: The float data type is a single-precision 32-bit IEEE 754 floating-point. Float data type in
Java stores a decimal value with 6-7 total digits of precision. So for example 12.12345 can be saved
as a float, but 12.123456789 cannot be saved as the float. When representing a float data type in Java
we should append the letter f to the end of the data type, otherwise, it will save as double. Assume, if
we create an float type variable as float a; It means in the memory four bytes is allocated and it is
referred as a.

Syntax:
float floatVar;
Ex: float b, c=2.4f;
2)double: The double data type is a double-precision 64-bit IEEE 754 floating-point. The double data
type is normally the default choice for decimal values. The data type should never be used for precise
values, such as currency. Double data type stores decimal values with 15-16 digits of precision. The
default value is 0.0d, this means that if you do not append f or d to the end of the decimal, the value
will be stored as a double in Java. Assume, if we create an double type variable as double a; It means
in the memory eight bytes is allocated and it is referred as a.
Syntax:
double doubleVar;
Ex: double b, c=2.4;

Boolean Data Type:


To store yes/no type data or true/false type data, java provides boolean data type. Size of this data type
is decided by JVM and we have already learned JVM is platform dependent, hence the size of this
data type will differ depending on the type of operating system.
The remaining types of data that is audio, video and still pictures are handled using built in libraries.

Syntax:
boolean booleanVar;
Ex: boolean b, c=true;

Character Data Type:


Char in Java is not the same as char in C or C++. Java uses Unicode to represent characters. Unicode
defines a fully international character set that can represent all of the characters found in all human
languages. It is a unification of dozens of character sets, such as Latin, Greek, Arabic, Cyrillic,
Hebrew, Katakana, Hangul, and many more. Hence it requires 16 bits. The range of a char in java is
0 to 65,536. There are no negative chars.
Syntax:
char charVar;
Ex: char b, c=’s’;

Why is the Size of char 2 bytes in Java?


So, other languages like C/C++ use only ASCII characters, and to represent all ASCII characters
8 bits is enough. But Java uses the Unicode system not the ASCII code System and to represent
the Unicode system 8 bits is not enough to represent all characters so Java uses 2 bytes for
characters. Unicode defines a fully international character set that can represent most of the
world’s written languages. It is a unification of dozens of character sets, such as Latin, Greek,
Cyrillic, Katakana, Arabic, and many more.

Name Width in bits Range


long 64 –9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
int 32 –2,147,483,648 to 2,147,483,647
short 16 –32,768 to 32,767
byte 8 –128 to 127
double 64 4.9e–324 to 1.8e+308
float 32 1.4e−045 to 3.4e+038
char 16 0 to 65,536
Program:
public class DataTypes
{
static byte a;
static short b;
static int c;
static long d;
static char e;
static float f;
static double g;
static boolean h;
public static void main(String[] args)
{
System.out.println("Default value of byte Type = " +a);
System.out.println("Default value of short Type = " +b);
System.out.println("Default value of int Type = " +c);
System.out.println("Default value of long Type = " +d);
System.out.println("Default value of char Type = " +e);
System.out.println("Default value of float type = " +f);
System.out.println("Default value of double Type = " +g);
System.out.println("Default value of boolean Type = " +h);
}
}
1.2.3 Variables
The variable is the basic unit of storage in a Java program. A variable is a container which holds the
value while the Java program is executed. A variable is assigned with a data type. Variable is a name
of memory location. A variable is defined by the combination of an identifier, a type, and an optional
initializer.
Declaring a Variable
In Java, all variables must be declared before they can be used.
type identifier [ = value][, identifier [= value] ...] ;
Types:
1)Instance Variable
2)Class Variable / static variables
3)Local Variable
4)Parameters

1)Local variables:
• Local variables are declared in methods, constructors, or blocks.
• Local variables are created when the method, constructor or block is entered and the variable will be
destroyed once it exits the method, constructor or block.
• Access modifiers cannot be used for local variables.
• Local variables are visible only within the declared method, constructor or block.
• There is no default value for local variables so local variables should be declared and an initial value
should be assigned before the first use.
The control of execution will start from the main method and the memory for variables a,b,c,d is
allocated in the stack segment and values will be assigned. Default values for local variables will not
be assigned by jvm.

2)Instance variables:
• Instance variables are declared in a class, but outside a method, constructor or any block.
• Instance variables are created when an object is created with the use of the key word 'new' and
destroyed when the object is destroyed.
• Access modifiers can be given for instance variables.
• The instance variables are visible for all methods, constructors and block in the class.
• Instance variables have default values.
• Instance variables can be accessed directly by calling the variable name inside the class.
• However, within static methods and different class (when instance variables are given accessibility)
that should be called using the fully qualified name ObjectReference.VariableName

Here control of execution will start from the main method. In the main method when a new keyword
is called an object is created in the heap segment and memory for instance variables name, breed and
cost is allocated the default values for the variables is allocated then the values that is assigned will
get allocated i.e name=” scooby”, breed = “pug”, cost = 12000.

3) Class/Static variables:
• Class variables also known as static variables are declared with the static keyword in a class, but
outside a method, constructor or a block.
• There would only be one copy of each class variable per class, regardless of how many objects are
created from it.
• Static variables are stored in static memory.
• Static variables are created when the program starts and destroyed when the program stops.
• Visibility is similar to instance variables.
• Default values are same as instance variables.
• Static variables can be accessed by calling with the class name
Syntax:
ClassName.VariableName
Program:
public class DefaultVariables
{

static int a=20;


static int b=30;
public static void main(String[] args)
{
System.out.println(a);
System.out.println(b);
}
}

The Scope and Lifetime of Variables:


Scope: The scope of a declared element is the portion of the program where the element is visible.
Lifetime: The lifetime of a declared element is the period of time during which it is alive. The lifetime
of the variable can be determined by looking at the context in which they're defined.
Java allows variables to be declared within any block. A block begins with an opening curly brace and
ends by a closing curly brace.
Variables declared inside a scope are not accessible to code outside. Scopes can be nested. The outer
scope encloses the inner scope. Variables declared in the outer scope are visible to the inner scope.
Variables declared in the inner scope are not visible to the outside scope.
Program:
public class Scope
{
public static void main(String args[])
{
int x; //know to all code within main
x=10;
if(x==10)
{ // starts new scope
int y=20; //Known only to this block //x and y both known here
System.out.println("x and y: "+x+" "+y);
x=y+2;
}
y=100; // error ! y not known here //x is still known here
System.out.println("x is "+x);
}
}

Type casting and type conversion in java:


Type casting is a process of converting one type of data to another type of data type.
In Java, there are two types of casting:
1)Implicit casting (automatically) - converting a smaller type to a larger type size
byte -> short -> char -> int -> long -> float -> double.
2)Explicit casting (manually) - converting a larger type to a smaller size type.
Implicit type casting(type conversion or widening conversion): When a smaller data type is
converted to a larger data type, the conversion is automatically performed by the java complier and is
referred to as implicit type casting.
Advantage: No loss of precision. Consider the Implicit type casting chart given below to understand
this:
Let us consider a code snippet to understand this:
Ex: byte a = 45;
double b;
b = a;
let us understand implicit type casting using the above code snippet. a is a variable of type byte whose
size is 1 byte. b is a variable of type double whose size is 8 bytes.
b = a;
we are now trying to store the data present in a into b. a is of type byte and can store 1 byte. b is of
type double and can store 8 bytes. we are trying to store data of smaller size into larger size.

This conversion is implicitly done without user interaction and hence it is referred to as implicit type
casting.
Explicit type casting(type casting or narrowing conversion):
When a larger data type is converted to a smaller data type, the conversion not automatically
performed by the java complier and must be done by programmer explicitly and hence it is referred
to as explicit type casting.
Let us consider a simple code snippet to understand this, the way we understood explicit type casting.
double a = 45.5;
byte b;
b = a; → error
a is a variable of type double whose size is 8 bytes. b is a variable of type byte whose size is 1 byte.
b = a;
will give you error as you are trying to store a larger type of data into smaller type.

The above conversion will result in error as loss of precision occurs. To get the error free output, we
have to explicitly convert the data as shown below
double a = 45.5;
byte b;
b = byte(a);
b is of type byte and it will only store 45 and 0.5 is lost during the conversion which is the disadvantage
of explicit type casting.

1.2.4 Final Keyword


The final keyword in java is used to restrict the user. The java final keyword can be used in many
context. Final can be:

1. variable
2. method
3. class

The final keyword can be applied with the variables, a final variable that have no value it is called
blank final variable or uninitialized final variable. It can be initialized in the constructor only. The
blank final variable can be static also which will be initialized in the static block only. We will
have detailed learning of these. Let's first learn the basics of final keyword.

Java final variable

If you make any variable as final, you cannot change the value of final variable(It will be
constant).
Example of final variable

There is a final variable speedlimit, we are going to change the value of this variable, but It can't
be changed because final variable once assigned a value can never be changed.

Program:

class FinalKeyword
{
public static void main(String args[]){
final int speedlimit=90;
speedlimit=40; /* error: cannot assign a value to final //variable speedlimit=40; */
System.out.print(speedlimit);
}
}

1.2.5 Operators
In programming, operators are the special symbol that tells the compiler to perform a special
operation. Java provides different types of operators that can be classified according to the
functionality they provide. There are eight types of operators in Java, are as follows:

o Arithmetic Operators
o Assignment Operators
o Relational Operators
o Unary Operators
o Logical Operators
o Ternary Operators
o Bitwise Operators
o Shift Operators

Arithmetic Operators:
Operator Result
+ Addition
– Subtraction
* Multiplication
/ Division
% Modulus
++ Increment

Assignment Operators:
Operator Result
+= Addition assignment
–= Subtraction assignment
*= Multiplication assignment
/= Division assignment
%= Modulus assignment

Relational Operators:
The relational operators determine the relationship that one operand has to the other. They determine
equality and ordering.
Operator Result
== Equal to
!= Not equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to

Unary Operator:
++. --,!

Logical Operator:
Operator Result
& Logical AND
| Logical OR
^ Logical XOR (exclusive OR)
! Logical unary NOT
|| Short-circuit OR
&& Short-circuit AND

Ternary Operator:
Operator Result
?: Ternary if-then-else

Bitwise Operators:
bitwise operators can be applied to the integer types, long, int, short, byte and char.  These operators
act upon the individual bits of their operands.
Operator Result
~ Bitwise unary NOT
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR

Shift Operator:
Operator Result
>> Shift right
>>> Shift right zero fill
<< Shift left
>>= Shift right assignment
>>>= Shift right zero fill assignment
<<= Shift left assignment
Increement and Decreement Operators:
Increment and Decrement in Java programming let you easily add 1 or subtract 1 from variable. To achieve
this, we have two different types of operators.
INCREMENT In Java, the increment unary operator increases the value of the variable by one.
" ++ " is the operator used to increment.
There are two types of Increment
● Pre-Increment.
● Post-Increment.
Pre-Increment-
● "++” is written before Variable name.
● Value will be Incremented First and then incremented value is used in expression.

Post-Increment
● "++” is written after Variable name.
● Value is used in expression first and then gets incremented.
Decrement
In Java, the decrement unary operator decreases the value of the variable by one. " -- " is the operator used to
decrement.
There are two types of Increment
● Post-Decrement.
● Pre-Decrement.
Pre-Decrement-
● “--” is written before Variable name.
● Value is decremented First and then decremented value is used in expression

Post-Decrement-
● “--” is written after Variable name.
● Value is used in expression first and then gets decremented.
Expressions:
An expression is a combination of constants (like 10), operators ( like +), variables(section of memory)
and parentheses ( like “(” and “)” ) used to calculate a value.
Ex1: x = 1;
Ex2: y = 100 + x;
Ex3: x = (32 - y) / (x + 5)
1.3 Control Statements
Java Control Statements or Control Flow in Java
Java compiler executes the code from top to bottom. The statements in the code are executed according
to the order in which they appear. However, Java provides statements that can be used to control the
flow of Java code. Such statements are called control flow statements. It is one of the fundamental
features of Java, which provides a smooth flow of program.

Java provides three types of control flow statements.

1. Decision Making statements


o if statements
o switch statement
2. Loop statements
o do while loop
o while loop
o for loop
o for-each loop
3. Jump statements
o break statement
o continue statement

1. Decision-Making statements:

As the name suggests, decision-making statements decide which statement to execute and when.
Decision-making statements evaluate the Boolean expression and control the program flow depending
upon the result of the condition provided. There are two types of decision-making statements in Java,
i.e., If statement and switch statement.

If Statement:

In Java, the "if" statement is used to evaluate a condition. The control of the program is diverted
depending upon the specific condition. The condition of the If statement gives a Boolean value, either
true or false. In Java, there are four types of if-statements given below.

1. Simple if statement
2. if-else statement
3. if-else-if ladder
4. Nested if-statement

Let's understand the if-statements one by one.

Simple if statement:

It is the most basic statement among all control flow statements in Java. It evaluates a Boolean
expression and enables the program to enter a block of code if the expression evaluates to true.

Syntax of if statement is given below.

if(condition) {
statement 1; //executes when condition is true
}

Consider the following example in which we have used the if statement in the java code.

Example for if:

Program:

public class Student {


public static void main(String[] args) {
int x = 10;
int y = 12;
if(x+y > 20) {
System.out.println("x + y is greater than 20");
}
}
}

Output:

x + y is greater than 20

if-else statement:

The if-else statement is an extension to the if-statement, which uses another block of code, i.e., else
block. The else block is executed if the condition of the if-block is evaluated as false.

Syntax:
if(condition) {
statement 1; //executes when condition is true
}
else{
statement 2; //executes when condition is false
}

Consider the following example.

Example for if-else:

Program:

public class Student {


public static void main(String[] args) {
int x = 10;
int y = 12;
if(x+y < 10) {
System.out.println("x + y is less than 10");
} else {
System.out.println("x + y is greater than 20");
}
}
}

Output:

x + y is greater than 20

if-else-if ladder:

The if-else-if statement contains the if-statement followed by multiple else-if statements. In other
words, we can say that it is the chain of if-else statements that create a decision tree where the program
may enter in the block of code where the condition is true. We can also define an else statement at the
end of the chain.

Syntax of if-else-if statement is given below.

if(condition 1) {
statement 1; //executes when condition 1 is true
}
else if(condition 2) {
statement 2; //executes when condition 2 is true
}
else {
statement 2; //executes when all the conditions are false
}

Consider the following example.

Example for if-else-if:

Program:

public class Student {


public static void main(String[] args) {
String city = "Delhi";
if(city == "Meerut") {
System.out.println("city is meerut");
}else if (city == "Noida") {
System.out.println("city is noida");
}else if(city == "Agra") {
System.out.println("city is agra");
}else {
System.out.println(city);
}
}
}

Output:

Delhi

Nested if-statement:

In nested if-statements, the if statement can contain a if or if-else statement inside another if or else-
if statement.

Syntax of Nested if-statement is given below.


if(condition 1) {
statement 1; //executes when condition 1 is true
if(condition 2) {
statement 2; //executes when condition 2 is true
}
else{
statement 2; //executes when condition 2 is false
}
}

Consider the following example.

Example for Nested if:

Program:

public class Student {


public static void main(String[] args) {
String address = "Delhi, India";
if(address.endsWith("India")) {
if(address.contains("Meerut")) {
System.out.println("Your city is Meerut");
}else if(address.contains("Noida")) {
System.out.println("Your city is Noida");
}else {
System.out.println(address.split(",")[0]);
}
}else {
System.out.println("You are not living in India");
}
}
}

Output:

Delhi
1.3.2 Switch Statement:
In Java, Switch statements are similar to if-else-if statements. The switch statement contains multiple
blocks of code called cases and a single case is executed based on the variable which is being switched.
The switch statement is easier to use instead of if-else-if statements. It also enhances the readability
of the program.

Points to be noted about switch statement:

o The case variables can be int, short, byte, char, or enumeration. String type is also supported
since version 7 of Java
o Cases cannot be duplicate
o Default statement is executed when any of the case doesn't match the value of expression. It
is optional.
o Break statement terminates the switch block when the condition is satisfied.
It is optional, if not used, next case is executed.
o While using switch statements, we must notice that the case expression will be of the same
type as the variable. However, it will also be a constant value.

The syntax to use the switch statement is given below.

switch (expression){
case value1:
statement1;
break;
.
.
.
case valueN:
statementN;
break;
default:
default statement;
}

Consider the following example to understand the flow of the switch statement.

Example for Switch:


Program:

public class Student implements Cloneable {


public static void main(String[] args) {
int num = 2;
switch (num){
case 0: System.out.println("number is 0");
break;
case 1: System.out.println("number is 1");
break;
default: System.out.println(num);
}
}
}

Output:

While using switch statements, we must notice that the case expression will be of the same type as the
variable. However, it will also be a constant value. The switch permits only int, string, and Enum type
variables to be used.

1.3.3 Loop Statements


In programming, sometimes we need to execute the block of code repeatedly while some condition
evaluates to true. However, loop statements are used to execute the set of instructions in a repeated
order. The execution of the set of instructions depends upon a particular condition.

In Java, we have three types of loops that execute similarly. However, there are differences in their
syntax and condition checking time.

1. for loop
2. while loop
3. do-while loop

Let's understand the loop statements one by one.


for loop:

In Java, for loop is similar to C and C++. It enables us to initialize the loop variable, check the
condition, and increment/decrement in a single line of code. We use the for loop only when we exactly
know the number of times, we want to execute the block of code.

for(initialization, condition, increment/decrement) {


//block of statements
}

The flow chart for the for-loop is given below.

Consider the following example to understand the proper functioning of the for loop in java.

Example for for:

Program:

public class Calculattion {


public static void main(String[] args) {
// TODO Auto-generated method stub
int sum = 0;
for(int j = 1; j<=10; j++) {
sum = sum + j;
}
System.out.println("The sum of first 10 natural numbers is " + sum);
}
}

Output:

The sum of first 10 natural numbers is 55


for-each loop:

Java provides an enhanced for loop to traverse the data structures like array or collection. In the for-
each loop, we don't need to update the loop variable. The syntax to use the for-each loop in java is
given below.

for(data_type var : array_name/collection_name){


//statements
}

Consider the following example to understand the functioning of the for-each loop in Java.

Example for for-each:

Program:

public class Calculation {


public static void main(String[] args) {
// TODO Auto-generated method stub
String[] names = {"Java","C","C++","Python","JavaScript"};
System.out.println("Printing the content of the array names:\n");
for(String name:names) {
System.out.println(name);
}
}
}

Output:

Printing the content of the array names:

Java
C
C++
Python
JavaScript

while loop:

The while loop is also used to iterate over the number of statements multiple times. However, if we
don't know the number of iterations in advance, it is recommended to use a while loop. Unlike for
loop, the initialization and increment/decrement doesn't take place inside the loop statement in while
loop.
It is also known as the entry-controlled loop since the condition is checked at the start of the loop. If
the condition is true, then the loop body will be executed; otherwise, the statements after the loop will
be executed.

The syntax of the while loop is given below.

while(condition){
//looping statements
}

The flow chart for the while loop is given in the following image.

Consider the following example.

Example for while:

Program:

public class Calculation {


public static void main(String[] args) {
// TODO Auto-generated method stub
int i = 0;
System.out.println("Printing the list of first 10 even numbers \n");
while(i<=10) {
System.out.println(i);
i = i + 2;
}
}
}

Output:

Printing the list of first 10 even numbers

0
2
4
6
8
10

do-while loop:

The do-while loop checks the condition at the end of the loop after executing the loop statements.
When the number of iteration is not known and we have to execute the loop at least once, we can use
do-while loop.

It is also known as the exit-controlled loop since the condition is not checked in advance. The syntax
of the do-while loop is given below.

do
{
//statements
} while (condition);

The flow chart of the do-while loop is given in the following image.

Consider the following example to understand the functioning of the do-while loop in Java.
Example for do-while:

Program:

public class Calculation {


public static void main(String[] args) {
// TODO Auto-generated method stub
int i = 0;
System.out.println("Printing the list of first 10 even numbers \n");
do {
System.out.println(i);
i = i + 2;
}while(i<=10);
}
}

Output:

Printing the list of first 10 even numbers


0
2
4
6
8
10

3. Jump Statements

Jump statements are used to transfer the control of the program to the specific statements. In other
words, jump statements transfer the execution control to the other part of the program. There are two
types of jump statements in Java, i.e., break and continue.

Java break statement

As the name suggests, the break statement is used to break the current flow of the program and transfer
the control to the next statement outside a loop or switch statement. However, it breaks only the inner
loop in the case of the nested loop.

The break statement cannot be used independently in the Java program, i.e., it can only be written
inside the loop or switch statement.

The break statement example with for loop


Consider the following example in which we have used the break statement with the for loop.

Example for Break:

Program:

public class BreakExample {


public static void main(String[] args) {
// TODO Auto-generated method stub
for(int i = 0; i<= 10; i++) {
System.out.println(i);
if(i==6) {
break;
}
}
}
}

Output:

0
1
2
3
4
5
6

Java continue statement:

Unlike break statement, the continue statement doesn't break the loop, whereas, it skips the specific
part of the loop and jumps to the next iteration of the loop immediately.

Consider the following example to understand the functioning of the continue statement in Java.

Example for Continue:

Program:

public class ContinueExample {


public static void main(String[] args) {
// TODO Auto-generated method stub
for(int i = 0; i<= 2; i++) {
for (int j = i; j<=5; j++) {
if(j == 4) {
continue;
}
System.out.println(j);
}
}
}
}

Output:

0
1
2
3
5
1
2
3
5
2
3
5

Prepared by Y. Suma Chamundeswari


Asst. Professor CSE(DS)

You might also like