Module 1 Java
Module 1 Java
Module 1 Java
AND TECHNOLOGY
CLASS NOTES
ON
Prepared
By
Surendra Nath Bhagat
Department Of
Information Technology
MODULE-I
CHAPTER-1
Programming is giving a set of instructions to a computer to execute.
Programming is the mental process of thinking up instructions to give to a machine (like a
computer).
Coding is the process of transforming those ideas into a written language that a computer can
understand.
There are basically two types of computer programming languages given below:
1. Low level language
2. High level language
Machine Language
The instructions in binary form, which can be directly understood by the computer (CPU) without
translating them, is called a machine language or machine code.
Machine language is also known as first generation of programming language. Machine language is the
fundamental language of the computer and the program instructions in this language is in the binary form
(that is 0's and 1's).
This language is different for different computers.
It is not easy to learn the machine language.
Procedural Language
Procedural languages are also known as third generation languages (3GLs). In a procedural language, a
program is designed using procedures.
A procedure is a sequence of instructions having a unique name. The instructions of the procedure are
executed with the reference of its name.
In procedural programming languages, the program instructions are written in a sequence or in a specific
order in which they must be executed to solve a specific problem. It means that the order of program
instructions is very important.
FORTRAN it stands for formula translation. It was developed in 1957 for IBM computers. It was
the first earliest high level programming language used to introduce the concept of modular
programming. It has been revised many times. Its commonly used version is FORTRAN 77
COBOL - it stands for common business oriented language. It was developed in 1959. this high-
level language was specially developed for business and commercial applications. It was suitable for
handling large amount of data such as:
o To prepare payroll
o To process credit and debit account
o To control inventory system and many other business applications
Pascal - this programming language is named in the honour of Blaise Pascal, a mathematician and
scientist who invented the first mechanical calculator. Structured programming language and is
popular in computer science development in 1971. It is suitable for scientific field.
ADA - it is developed in 1980 and is named in the honour of Lady Augusta ADA. She was the first
computer programmer. The high level structure language Pascal was used as a model for the
development of ADA language. This language is mainly used for defence purposes such as for
controlling military weapons like missiles etc.
C language - Dennis Ritchie and Brian Karnighan developed it in 1972 at Bell Laboratories. It is a
high level language but it can also support assembly language codes (low level codes). It is because,
C language is also referred to as middle level language. The program written in C can be compiled
and run on any type of computer. In other words programs written in C language are portable. C
language is a structured programming language. The main feature of C language is that, it uses a
large number of built-in functions to perform various tasks. The user can also creates its own
functions.
The object oriented programming concept was introduced in the late 1960s, but now it has become the most
popular approach to develop software.
In object oriented programming, the software is developed by using a set of interfacing object. An object is a
component of program that has a set of modules and data structure. The modules are also called methods
and are used to access the data from the object. The modern technique to design the program is object
oriented approach. It is a very easy approach, in which program designed by using objects. Once an object
for any program designed, it can be re-used in any other program.
Now-a-days, most popular and commonly used object oriented programming (OOPs) languages are C++
and Java.
To perform an instruction written in high-level language via computer, we need to convert it into machine
language. To do this, either a compiler or an interpreter, or both are used to convert a source code
programming language into machine code. Compiler and interpreter are software programs that convert a
high-level language into a machine language (0's and 1's binary form) that a computer can understand and
perform tasks as per the program's instructions. But there are variations in the working process and steps of a
compiler and interpreter. Before diving into the difference between a compiler and an interpreter, let's see a
brief introduction about both of them.
Compiler
A compileris a software program that follows the syntax rule of programming language to convert a source
code to machine code. It cannot fix any error if present in a program; it generates an error message, and you
have to correct it yourself in the program's syntax. If your written program is correct (contains no error),
then the compiler will convert your entire source code into machine code. A compiler converts complete
source code into machine code at once. And finally, your program get executes.
The entire compilation steps of source code are operated into two phases: Analysis Phase and Synthesis
Phase.
o Analysis Phase: This compiler phase is also known as the front end phase in which a source code is
divided into fundamental parts to check grammar, syntax, and semantic of code; after that,
the intermediate code is generated. The analysis phase of the compilation process includes a lexical
analyzer, semantic analyzer, and syntax analyzer.
o Synthesis Phase: The Synthesis phase is also known as the back end phase in which
the intermediate code (which was generated in Analysis Phase) is optimized and generated
into target machine code. The synthesis phase of the compilation process includes code optimizer
and code generator tasks.
Interpreter
An interpreteris also a software program that translates a source code into a machine language. However, an
interpreter converts high-level programming language into machine language line-by-line while interpreting
and running the program.
Difference between Compiler and Interpreter
Advantage As the source code is already converted into As the source code is interpreted line-by-
machine code, the code execution time line, error detection and correction become
becomes short. easy.
Disadvantage If you want to change your program for any Interpreted programs can run on only those
reason, either by error or logical changes, you computers which have the same interpreter.
can do it only by going back to your source
code.
Machine code It stores the converted machine code from It never stores the machine code at all on
your source code program on the disk. the disk.
Running time A compiler takes an enormous time to An interpreter takes less time to analyze
analyze source code. However, overall source code as compared to a compiler.
compiled programming code runs faster as However, overall interpreted programming
compression to an interpreter. code runs slower as compression to the
compiler.
Program The compiler generates an output of a The interpreter doesn't generate a separate
generation program (in the form of an exe file) that can machine code as an output program. So it
run separately from the source code program. checks the source code every time during
the execution.
Execution The process of program execution takes place The process of program execution is a part
separately from its compilation process. of interpretation steps, so it is done line-by-
Program execution only takes place after the line simultaneously.
complete program is compiled.
Memory A compiled program is generated into an An interpreted program does not generate
requirement intermediate object code, and it further an intermediate code. So there is no
required linking. So there is a requirement for requirement for extra memory.
more memory.
Best suited for The compiled program is bounded to the In web environments, compiling takes place
specific target machine. It requires the same relatively more time to run even small code,
compiler on the machine to execute; C and which may not run multiple times. As load
C++ are the most popular programming time is essential in the web environment,
language based on the compilation model. interpreters are better. JavaScript, Python,
Ruby are based on the interpreter model.
Error The compiler shows the complete errors and An interpreter reads the program line-by-
execution warning messages at program compilation line; it shows the error if present at that
time. So it is not possible to run the program specific line. You must have to correct the
without fixing program errors. Doing error first to interpret the next line of the
debugging of the program is comparatively program. Debugging is comparatively easy
complex while working with a compiler. while working with an Interpreter.
6. Inheritance: The capability of a class to derive properties and characteristics from another class is
called Inheritance. Inheritance is one of the most important features of Object-Oriented Programming.
Sub Class: The class that inherits properties from another class is called Sub class or Derived Class.
Super Class:The class whose properties are inherited by sub class is called Base Class or Super class.
Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to create a new class
and there is already a class that includes some of the code that we want, we can derive our new class
from the existing class. By doing this, we are reusing the fields and methods of the existing class.
7. Dynamic Binding: In dynamic binding, the code to be executed in response to function call is decided
at runtime.
8. Message Passing: Objects communicate with one another by sending and receiving information to each
other. A message for an object is a request for execution of a procedure and therefore will invoke a
function in the receiving object that generates the desired results. Message passing involves specifying the
name of the object, the name of the function and the information to be sent.
CHAPTER-II
Introduction to java:-JAVA was developed by James and Patrick Naughton. at Sun Microsystems Inc in
the year 1991, later acquired by Oracle Corporation. It is a simple programming language. Java makes
writing, compiling, and debugging programming easy. It helps to create reusable code and modular
programs.
What is java:- Java is a class-based, object-oriented programming language and is designed to have as
few implementation dependencies as possible. A general-purpose programming language made for
developers to write once run anywhere that is compiled Java code can run on all platforms that support
Java. Java applications are compiled to byte code that can run on any Java Virtual Machine. The syntax of
Java is similar to c/c++.
Why java:-
Java is easy to learn:-Java was designed to be easy to use and is therefore easy to write, compile,
debug, and learn than other programming languages.
Java is object-oriented:-This allows you to create modular programs and reusable code.
Java is platform-independent:-One of the most significant advantages of Java is its ability to move
easily from one computer system to another. The ability to run the same program on many different
systems is crucial to World Wide Web software, and Java succeeds at this by being platform-
independent at both the source and binary levels.
Features of Java
The primary objective of Java programminglanguage creation was to make it portable, simple and secure
programming language. Apart from this, there are also some excellent features which play an important role
in the popularity of this language. The features of Java are also known as Java buzzwords.
1. Simple:-Java is very easy to learn, and its syntax is simple, clean and easy to understand. According to
Sun Microsystem, Java language is a simple programming language because:
o Java syntax is based on C++ (so easier for programmers to learn it after C++).
o Java has removed many complicated and rarely-used features, for example, explicit pointers,
operator overloading, etc.
o There is no need to remove unreferenced objects because there is an Automatic Garbage Collection
in Java.
2. Object-oriented:- Java is an object-orientedprogramming language. Everything in Java is an object.
Object-oriented means we organize our software as a combination of different types of objects that
incorporate both data and behavior.
3. Platform Independent
Java is platform independent because it is different from other languages like C, C++, etc. which are
compiled into platform specific machines while Java is a write once, run anywhere language. A platform is
the hardware or software environment in which a program runs.
There are two types of platforms software-based and hardware-based. Java provides a software-based
platform.
The Java platform differs from most other platforms in the sense that it is a software-based platform that
runs on top of other hardware-based platforms. It has two components:
1. Runtime Environment
2. API(Application Programming Interface)
Java code can be executed on multiple platforms, for example, Windows, Linux, Sun Solaris, Mac/OS, etc.
Java code is compiled by the compiler and converted into bytecode. This bytecode is a platform-independent
code because it can be run on multiple platforms, i.e., Write Once and Run Anywhere (WORA).
4. Secured:-Java is best known for its security. With Java, we can develop virus-free systems. Java is
secured because:
o No explicit pointer
o Java Programs run inside a virtual machine sandbox
o Classloader: Classloader in Java is a part of the Java Runtime Environment (JRE) which is used to
load Java classes into the Java Virtual Machine dynamically. It adds security by separating the
package for the classes of the local file system from those that are imported from network sources.
o Bytecode Verifier: It checks the code fragments for illegal code that can violate access rights to
objects.
o Security Manager: It determines what resources a class can access such as reading and writing to
the local disk.
Java language provides these securities by default. Some security can also be provided by an application
developer explicitly through SSL, JAAS, Cryptography, etc.
7. High-performance
o Java is faster than other traditional interpreted programming languages because Java bytecode is
"close" to native code. It is still a little bit slower than a compiled language (e.g., C++). Java is an
interpreted language that is why it is slower than compiled languages, e.g., C, C++, etc.
8. Distributed
o Java is distributed because it facilitates users to create distributed applications in Java. RMI and EJB
are used for creating distributed applications. This feature of Java makes us able to access files by
calling the methods from any machine on the internet.
9. Multi-threaded
o A thread is like a separate program, executing concurrently. We can write Java programs that deal
with many tasks at once by defining multiple threads. The main advantage of multi-threading is that
it doesn't occupy memory for each thread. It shares a common memory area. Threads are important
for multi-media, Web applications, etc.
Dynamic
o Java is a dynamic language. It supports the dynamic loading of classes. It means classes are loaded
on demand. It also supports functions from its native languages, i.e., C and C++. Java supports
dynamic compilation and automatic memory management (garbage collection).
The languages are based on each other but still, they are different in design and philosophy. The following
table describes the major differences between C, C++, and Java. It will help you to select which language
you have to learn.
1 Origin The C language is based The C++ language is The Java programming
on BCPL. based on the C language. language is based on both
C and C++.
3 Approach It uses the top-down It uses the bottom-up It also uses the bottom-up
approach. approach. approach.
5 Code Execution The code is executed The code is executed The code is executed by
directly. directly. the JVM.
6 Platform It is platform dependent. It is platform dependent. It is platform-independent
Dependency because of byte code.
7 Translator It uses a compiler only to It also uses a compiler Java uses both compiler
translate the code into only to translate the and interpreter and it is
machine language. code into machine also known as an
language. interpreted language.
8 File Generation It generates the .exe, and It generates .exe file. It generates .class file.
.bak, files.
9 Number of There are 32 keywords in There are 60 keywords There are 52 keywords in
Keyword the C language. in the C++ language. the Java language.
10 Source File The source file has a .c The source file has a The source file has a .java
Extension extension. .cpp extension. extension.
11 Pointer Concept It supports pointer. It also supports pointer. Java does not support the
pointer concept because of
security.
12 Union and It supports union and It also supports union It does not support union
Structure structure data types. and structure data types. and structure data types.
Datatype
16 Memory It uses the calloc(), It uses new and delete It uses a garbage collector
Management malloc(), free(), and operator to manage the to manage the memory.
realloc() methods to memory.
manage the memory.
17 Overloading It does not support the Method and operator Only method overloading
overloading concept. overloading can be can be achieved.
achieved.
18 goto Statement It supports the goto It also supports the goto It does not support the
statement. statement. goto statements.
19 Used for It is widely used to It is widely used for It is used to develop web
develop drivers and system programming. applications, mobile
operating systems. applications, and windows
applications.
o class Simple{
o public static void main(String args[]){
o System.out.println("Hello Java");
o }
o }
Let's see what is the meaning of class, public, static, void, main, String[], System.out.println().
o class keyword is used to declare a class in Java.
o public keyword is an access modifier that represents visibility. It means it is visible to all.
o static is a keyword. If we declare any method as static, it is known as the static method. The core
advantage of the static method is that there is no need to create an object to invoke the static method.
The main() method is executed by the JVM, so it doesn't require creating an object to invoke the
main() method. So, it saves memory.
o void is the return type of the method. It means it doesn't return any value.
o main represents the starting point of the program.
o String[] args or String args[ ]This represents an array whose type is String and name is args. We
will discuss more about array in Java Array section.
o System.out.println() is used to print statement. Here, System is a class, out is an object of the
PrintStream class, println() is a method of the PrintStream class.
For executing any Java program, the following software or application must be properly installed.
o Install the JDK if you don't have installed it, and install it.
o Set path of the jdk/bin directory.
o Create the Java program
o Compile and run the Java program
Compiling and running a java program is very easy after JDK installation. Following are the steps −
Open a command prompt window and go to the directory where you saved the java program
(MyFirstJavaProgram.java). Assume it's C:\.
Type 'javac MyFirstJavaProgram.java' and press enter to compile your code. If there are no errors in
your code, the command prompt will take you to the next line (Assumption: The path variable is set).
Now, type ' java MyFirstJavaProgram ' to run your program.
You will be able to see the result printed on the window.
The class files generated by the compiler are independent of the machine or the OS, which allows
them to be run on any system. To run, the main class file (the class that contains the method main)
is passed to the JVM and then goes through three main stages before the final machine code is
executed. These stages are:
These states do include:
1. ClassLoader
2. Bytecode Verifier
3. Just-In-Time Compiler
Let us discuss all 3 stages.
Stage 1: Class Loader
The main class is loaded into the memory bypassing its ‘.class’ file to the JVM, through invoking the
latter. All the other classes referenced in the program are loaded through the class loader.
A class loader, itself an object, creates a flat namespace of class bodies that are referenced by a string
name. The method definition is provided below illustration as follows:
Illustration:
// loadClass function prototype
Class r = loadClass(String className, booleanresolveIt);
// className: name of the class to be loaded
// resolveIt: flag to decide whether any referenced class should be loaded or not.
There are two types of class loaders
primordial
non-primordial
The primordial class loader is embedded into all the JVMs and is the default class loader. A non-
primordial class loader is a user-defined class loader, which can be coded in order to customize the class-
loading process. Non-primordial class loader, if defined, is preferred over the default one, to load classes.
Stage 2: Bytecode Verifier
After the bytecode of a class is loaded by the class loader, it has to be inspected by the bytecode verifier,
whose job is to check that the instructions don’t perform damaging actions. The following are some of the
checks carried out:
Variables are initialized before they are used.
Method calls match the types of object references.
Rules for accessing private data and methods are not violated.
Local variable accesses fall within the runtime stack.
The run-time stack does not overflow.
If any of the above checks fail, the verifier doesn’t allow the class to be loaded.
Stage 3: Just-In-Time Compiler
This is the final stage encountered by the java program, and its job is to convert the loaded bytecode into
machine code. When using a JIT compiler, the hardware can execute the native code, as opposed to
having the JVM interpret the same sequence of bytecode repeatedly and incurring the penalty of a
relatively lengthy translation process. This can lead to performance gains in the execution speed unless
methods are executed less frequently.
The process can be well-illustrated by the following diagram as given above as follows from which we
landed up to the conclusion.
Conclusion: Due to the two-step execution process described above, a java program is independent of the
target operating system. However, because of the same, the execution time is way more than a similar
program written in a compiled platform-dependent program.
A Virtual Machine is a software implementation of a physical machine. Java was developed with the
concept of WORA (Write Once Run Anywhere), which runs on a VM. The compiler compiles the Java
file into a Java .class file, then that .class file is input into the JVM, which loads and executes the class
file. Below is a diagram of the Architecture of the JVM.
JVM Architecture Diagram
06. case 07. catch 08. char 09. continue 10. default
21. import 22. instanceof 23. int 24. interface 25. long
26. native 27. new 28. package 29. private 30. protected
31. public 32. return 33. short 34. static 35. super
36. switch 37. synchronized 38. this 39. thro 40. throws
41. transient 42. try 43. void 44. volatile 45. while
46. assert 47. const 48. enum 49. goto 50. strictfp
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.
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
"javatpoint" String
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
perator Symbols
Arithmetic +,-,/,*,%
Unary ++ , - - , !
Assignment = , += , -= , *= , /= , %= , ^=
Logical && , ||
Ternary (Condition) ? (Statement1) : (Statement2);
Bitwise &,|,^,~
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.
o
Comments: Comments allow us to specify information about the program inside our Java code. Java
compiler recognizes these comments as tokens but excludes it form further processing. The Java compiler
treats comments as whitespaces. Java provides the following two types of comments:
o Line Oriented: It begins with a pair of forwarding slashes (//).
o Block-Oriented: It begins with /* and continues until it founds */.
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0L 8 byte
Unicode System
Unicode is a universal international standard character encoding that is capable of representing most of the w
languages.
Why java uses Unicode System?
Before Unicode, there were many language standards:
ASCII (American Standard Code for Information Interchange) for the United States.
ISO 8859-1 for Western European Language.
KOI-8 for Russian.
GB18030 and BIG-5 for chinese, and so on.
Problem
This caused two problems:
1. A particular code value corresponds to different letters in the various language standards.
2. The encodings for languages with large character sets have variable length. Some common
characters are encoded as single bytes, other require two or more byte.
Solution
To solve these problems, a new language standard was developed i.e. Unicode System.
In unicode, character holds 2 byte, so java also uses 2 byte for characters.
lowest value:\u0000
highest value:\uFFFF
Operators in Java
Operators are the constructs which can manipulate the values of the operands. Consider the expression 2 + 3
= 5, here 2 and 3 are operands and + is called operator. In this article on Java operators, the goal is to get
you the expertise required to get started and work with operators in Java.
Java supports the following types of operators:
Arithmetic Operators
Assignment Operators
Logical Operators
Relational Operators
Unary Operators
Bitwise Operators
Ternary Operators
Shift Operators
Arithmetic Operators in Java:-Arithmetic Operators are used to perform mathematical operations like
addition, subtraction, etc. Assume that A = 10 and B = 20 for the below table.
Operator Description Example
Adds values on either side of the
+ Addition A+B=30
operator
Subtracts the right-hand operator
– Subtraction A-B=-10
with left-hand operator
Multiplies values on either side of
* Multiplication A*B=200
the operator
Divides left hand operand with
/ Division A/B=0
right hand operator
Divides left hand operand by right
% Modulus hand operand and returns A%B=0
remainder
Assignment Operators in Java:-An Assignment Operator is an operator used to assign a new value to a
variable. Assume A = 10 and B = 20 for the below table.
Operator Description Example
= Assigns values from right side operands to left side operand c=a+b
It adds right operand to the left operand and assigns the result to
+= c += a
left operand
It subtracts right operand from the left operand and assigns the
-= c -= a
result to left operand
It multiplies right operand with the left operand and assigns the
*= c *= a
result to left operand
It divides left operand with the right operand and assigns the
/= c /= a
result to left operand
It takes modulus using two operands and assigns the result to
%= c %= a
left operand
Performs exponential (power) calculation on operators and
^= c ^= a
assign value to the left operand
Relational Operators in Java:-These operators compare the values on either side of them and decide the
relation among them. Assume A = 10 and B = 20.
Logical Operators in Java:-The following are the Logical operators present in Java:
Operator Description Example
&& (and) True if both the operands is true a<10 && a<20
|| (or) True if either of the operands is true a<10 || a<20
! (not) True if an operand is false (complements the operand) !(x<10 && a<20)
Unary Operator in Java:- Unary operators are the one that needs a single operand and are used to
increment a value, decrement or negate a value.
Operator Description Example
increments the value by 1. There is post-increment and pre-increment
++ a++ and ++a
operators
decrements the value by 1. There is post decrement and pre decrement
— a– or –a
operators
! invert a boolean value !a
Bitwise Operator in Java:-Bitwise operations directly manipulate bits. In all computers, numbers are represented
with bits, a series of zeros and ones. In fact, pretty much everything in a computer is represented by bits. Assume that
A = 10 and B = 20 for the below table.
Operator Description Example
~
returns the one’s complement. (all bits reversed) ~a
(Complement)
Ternary Operators in Java:-The ternary operator is a conditional operator that decreases the length of
code while performing comparisons and conditionals. This method is an alternative for using if-else and
nested if-else statements. The order of execution for this operator is from left to right.
Shift Operators in Java:-Shift operators are used to shift the bits of a number left or right, thereby
multiplying or dividing the number. There are three different types of shift operators, namely left shift
operator()<<, signed right operator(>>) and unsigned right shift operator(>>>).
Typecasting in Java
Programming is playing around with data. In Java, there are many data types. Most of the times while
coding, it is necessary to change the type of data to understand the processing of a variable and this is called
Type Casting.
What is Type Casting?
Type casting is nothing but assigning a value of one primitive data type to another. When you assign the
value of one data type to another, you should be aware of the compatibility of the data type. If they are
compatible, then Java will perform the conversion automatically known as Automatic Type Conversion and
if not, then they need to be casted or converted explicitly.
There are two types of casting in Java as follows:
Widening Casting
Narrowing Casting
Widening Casting (automatically) – This involves the conversion of a smaller data type to the larger type
size.
byte -> short -> char -> int -> long -> float -> double
Narrowing Casting (manually) – This involves converting a larger data type to a smaller size type.
double -> float -> long -> int -> char -> short -> byte
Widening Casting
This type of casting takes place when two data types are automatically converted. It is also known as
Implicit Conversion. This happens when the two data types are compatible and also when we assign the
value of a smaller data type to a larger data type.
Example:-
public class Conversion{
public static void main(String[] args)
{
int i = 200;
//automatic type conversion
long l = i;
//automatic type conversion
float f = l;
System.out.println("Int value "+i);
System.out.println("Long value "+l);
System.out.println("Float value "+f);
}
}
Output:
Int value 200
Long value 200
Float value 200.0
Narrowing Casting
In this case, if you want to assign a value of larger data type to a smaller data type, you can perform Explicit
type casting or narrowing. This is useful for incompatible data types where automatic conversion cannot be
done.
Example:-
program to illustrate explicit type conversion
public class Narrowing
{
public static void main(String[] args)
{
double d = 200.06;
//explicit type casting
long l = (long)d;
//explicit type casting
int i = (int)l;
System.out.println("Double Data type value "+d);
//fractional part lost
System.out.println("Long Data type value "+l);
//fractional part lost
System.out.println("Int Data type value "+i);
}
}
Output:
Double Data type value 200.06
Long Data type value 200
Int Data type value 200
2) if-else statement:-
The if-else statementis 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.
Student.java
1. public class Student {
2. public static void main(String[] args) {
3. int x = 10;
4. int y = 12;
5. if(x+y < 10) {
6. System.out.println("x + y is less than 10");
7. } else {
8. System.out.println("x + y is greater than 20");
9. }
10. }
11. }
Output:
x + y is greater than 20
3) 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.
Student.java
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
4. 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.
Student.java
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
Switch Statement:
In Java, Switch statementsare 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.
switch (expression){
case value1:
statement1;
break;
.
.
.
case valueN:
statementN;
break;
default:
default statement;
}
Student.java
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:
2
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.
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
Java for loop
In Java, for loopis similar to Cand 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
}
Calculation.java
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
The traversal of elements in an array can be done by the for-each loop. The elements present in the array are
returned one by one. It must be noted that the user does not have to increment the value in the for-each loop.
Example:
public class foreachLoop{
public static void main(String args[]){
ints[] = {18,25,28,29,30};
for (inti : s) {
System.out.println(i);
}
}
}
Output:
18
25
28
29
30
while loop:-
The while loopis 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
}
Example:
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 loopchecks 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)
Calculation.java
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
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.,
1. Break and
2. Continue.
1. Java break statement
As the name suggests, the break statementis 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.
BreakExample.java
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
Advantages
Code Optimization: It makes the code optimized, we can retrieve or sort the data efficiently.
Random access: We can get any data located at an index position.
Disadvantages
Size Limit: We can store only the fixed size of elements in the array. It doesn't grow its size at runtime. To
solve this problem, collection framework is used in Java which grows automatically.
Types of Array in java
There are two types of array.
1. Single Dimensional Array
2. Multidimensional Array
Single Dimensional Array in Java
Syntax to Declare an Array in Java
datatype[] arr; (or)
datatype []arr; (or)
datatype arr[];
Instantiation of an Array in Java
arrayRefVar=new datatype[size];
Example of Java Array
Let's see the simple example of java array, where we are going to declare, instantiate, initialize and traverse
an array.
//Java Program to illustrate how to declare, instantiate, initialize
//and traverse the Java array.
class Testarray{
public static void main(String args[]){
int a[]=new int[5];//declaration and instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//traversing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}}
Output:
10
20
70
40
50
Declaration, Instantiation and Initialization of Java Array
We can declare, instantiate and initialize the java array together by:
int a[]={33,3,4,5};//declaration, instantiation and initialization
Example to print this array.
//Java Program to illustrate the use of declaration, instantiation
//and initialization of Java array in a single line
class Testarray1{
public static void main(String args[]){
int a[]={33,3,4,5};//declaration, instantiation and initialization
//printing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}}
Output:
33
3
4
5
For-each Loop for Java Array
We can also print the Java array using for-each loop
. The Java for-each loop prints the array elements one by one. It holds an array element in a variable, then
executes the body of the loop.
The syntax of the for-each loop is given below:
for(data_type variable:array){
//body of the loop
}
Example of print the elements of Java array using the for-each loop.
//Java Program to print the array elements using for-each loop
class Testarray1{
public static void main(String args[]){
int arr[]={33,3,4,5};
//printing array using for-each loop
for(int i:arr)
System.out.println(i);
}}
Output:
33
3
4
5
System.out.println(min);
}
Output:
Printing original array:
33
3
4
5
Printing clone of the array:
33
3
4
5
Are both equal?
False
class Main {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in);
System.out.println("Enter name, age and salary:");
String name = myObj.nextLine(); // String input
int age = myObj.nextInt(); // Numerical input
double salary = myObj.nextDouble();// Output input by user
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Salary: " + salary);
}
}
Note: If you enter wrong input (e.g. text in a numerical input), you will get an exception/error message (like
"InputMismatchException").
These are the following steps to take character input using BufferedReader:
1. In the first step, we have to create an instance of the BufferedReader class by using
the InputStreamReader The InputStreamReader is a class that act as a bridge in between the byte stream to
character stream. The reason of using InputStreamReaderis to decode bytes to characters.
2. We will use the read() method of the BufferedReader class to read character from the
given BufferedReader and typecast it to char.
3. We will store the return value of the read() method into the character type variable. The read() method
returns the character read by this method. The read() method gives us result -1 in case when the buffered
stream has ended and there is no character to be read.
4. At the end, we will print the character data on the screen which we read using the read() method.
Example:-Simply read the character data using the BufferedReader class and print it to the screen.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class BufferedReaderExample {
public static void main(String[] args) throws IOException{
BufferedReader obj = new BufferedReader(new InputStreamReader(System.in));
char data = (char)obj.read();
System.out.println(data);
}
}
Output:-
Example:- String from user using BufferedReader class and perform some operations on the user entered
string..
//Import classes and packages
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
//Creating BufferedReaderExample2 class
public class BufferedReaderExample2 {
public static void main(String[] args) throws IOException{ //main() method with IOException
//Creating instance of the BufferedReader class with InputStreamReader
BufferedReader obj = new BufferedReader(new InputStreamReader(System.in));
System.out.print ( "Enter the height of triangle:" ); //Getting height of triangle
String hightData = obj.readLine();
double height = Double.parseDouble ( hightData );
System.out.print ( "Enter the base of triangle:" ); //Getting base of triangle
String baseData = obj.readLine();
double base = Double.parseDouble ( baseData ); //Calculating area of triangle
double area = (height*base)/2; //Printing the area of the triangle
System.out.println("The area of triangle is:"+area );
}
}
Output
References:-
1. PROGRAMMING WITH JAVA BY E.BALAGURUSAMY
2. JAVA COMPLETE REFERENCE BY HERBALT SCHELIDT
3.CORE JAVA BY RASMI KANTA DAS
4. ONLINE DIFFERENT WEB SITES.