Introduction to Java Programming(4CS4-06)
Unit-1: Introduction: OOP principles, Java essentials, Java Virtual
Machine, program structure in Java, Java class libraries, Data types,
Variables, and Arrays, Data types and casting, automatic type promotion
in expression , arrays, Operators and control statements, Arithmetic
operators, bit wise operators, relational operators, Boolean logical
operators, the ? operator, Java selection statements, iteration statements,
jump statement.
Introduction to Java:
Java is an object oriented programming language. Java is a high level,
robust, object-oriented and secure programming language.
Java was developed by Sun Microsystems in the year 1995. James
Gosling is known as the father of Java. Before Java, its name was Oak.
Since Oak was already a registered company, so James Gosling and his
team changed the name from Oak to Java.
Java is widely used for developing applications for desktop, web and
mobile devices.
Java is used in all kinds of applications, like mobile applications(Android
is Java based), desktop applications, web applications, client-server
applications and many more.
Java is an internet, age-built programming language. Java is fast, safe and
trustworthy.
Java is anywhere and everywhere.
Java syntax is similar to C/C++. But Java does not provide low-level
programming functionaries like pointers.
In Java all source code is first written in plain text files ending with
“.java” extension. The source files are then compiled into “.class” files
by javac compiler. A “.class” file does not contain code that is native to
processor, instead it contains – bytecode.
Progam.java Progam.class 1010110(executable
code)
(source code) (bytecode)
compiler(javac) JVM(java)
JVM is available on many different operating system, the “.class” file is
running on different operating system.
Where Java is used:
Desktop applications
Web applications
Embedded system
Mobile
Robotics
Games
JVM(Java Virtual Machine):
It is an abstract machine. It is a specification that provides runtime
environment in which Java bytecode can be executed. It is JVM which is
responsible for converting Byte code to machine-specific code. The JVM
performs the mentioned tasks: loads code, verifies code, executes code,
and provides runtime environment.
Java Bytecode:
Bytecode is an instruction set for JVM. It's an intermediate representation
of Java code, generated by the Java compiler after the source code is
compiled. As soon as Java program is compiled, Java bytecode is
generated.
Bytecode is not tied to a specific platform i.e. with the help of Java
bytecode we achieve platform independencein Java. It is saved as “.class”
file by the compiler., so it can run on any device that has a JVM. This is
known as the "write once, run anywhere" (WORA) principle.
JDK(Java Development Kit):
JDK is an abbreviation for Java Development Kit which includes all the
tools, including compiler, JRE(Java Runtime Environment), Java
Debuggers etc. JDK includes both JVM and JRE and is entirely
responsible for code execution. It is used to develop Java applications and
applets. JDK is platform dependent i.e for different platforms different
JDK required. JDK = Java Runtime Environment (JRE) + Development
tools.
JRE(Java Runtime Environment):
It is a set of software tools which are used for developing Java
applications. It is used to provide run time environment. It contains a set
of libraries and other files that uses JVM at run time.
JRE = Java Virtual Machine (JVM) + Libraries to run the application
Development tools
JVM Set of libraries
e.g. Javac, Java
Other files
(JRE)
JDK
Features of Java:
1. Object Oriented: Java is purely an Object Oriented Programming
language because without class and object it is impossible to write
any Java program.
2. Simple: Java is very easy to learn and understand. Its syntax is based
on C++ and it does not have complex features like pointers, operator
overloading, and multiple inheritance.
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. Java compiler coverts source code to bytecode
and JVM executes bytecode generated by the compiler. This
bytecode can run on any platform (Windows, Linux, Mac OS). The
bytecode is platform independent code it can run on multiple
platforms i.e. write once and run anywhere.
4. Secure: Java is known for its security. With java secure features it
enable us to develop virus free, temper free system. Java program
always runs in Java runtime environment with almost null
interaction with system OS, hence it is more secure.
5. Robust: Java is strictly typed language. It not only performs code
check at compile time but also at run time.
Java is robust because:
- It uses strong memory management.
- Java provides automatic garbage collection
which runs on JVM to get rid of objects which
are not being used by Java anymore.
- There is also exception handling mechanism
Also these make Java robust.
6. Distributed: In Java we can create distributed applications. Remote
Method Invocation Enterprise Java Beans are used for creating
distributed applications in Java. The Java programs can be easily
distributed on one or more systems that are connected to each other
through internet.
7. Multithreaded: A thread is like a separate program. Java
multithreading allows concurrent execution of two or more parts of
a program for maximum utilization of CPU.
8. Portable: Java Byte code can be carried to any platform. No
implementation dependent features. Everything related to storage is
predefined, e.g. : size of primitive data types.
9. Dynamic: Java is a dynamic language. It supports dynamic loading
of classes. It means classes are loaded on demand. We can add
classes, add methods to existing classes also new classes. It also
supports functions from its native languages i.e. C/C++.
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.
Structure of Java program:
1. Documentation section: It includes basic information about a Java
program. The information includes the author's name, program
name, etc. It improves the readability of the program. To write the
statements in the documentation section, we use comments. The
comments may be single-line, multi-
line, and documentation comments.
2. Package statement: It is optional. It is placed just after the
documentation section. In this section, we declare the package
name in which the class is placed. There is only one
package statement in a Java program.
e.g. package abc; (Package name)
package abc.abc1;
(package) (sub-package)
3. Import statement: The package contains the many predefined
classes and interfaces. If we want to use any class of a particular
package, we need to import that class. We use the import keyword
to import the class.
e.g. import abc.*; //import all classes of abc package
import abc.Test; //import only Test class
4. Interface section: It is an optional section. We can create
an interface in this section by using interface keyword.
An interface is a different from the class. It contains
only constants and method declarations. It cannot be instantiated.
We can use interface in classes by using the implements keyword.
e.g. interface Area
{
Void calc();
}
5. Class definition: In this section, we define a class. It is vital part of
a Java program. Without class, we cannot create any Java program.
A Java program may conation more than one class definition. We
use the class keyword to define the class. It is a blueprint of a Java
program. Every Java program has at least one class that contains the
main() method.
e.g. class Test
{
----
}
e.g. public class Abc
{
public static void main(String r[])
{
----
}
}
public class Abc : creates a public class Abc. The class name start with
capital letter. Public is a access specifier means it is accessible from other
classes.
In Java main() method is treated as an entry point of the program. The
main() method is declared as public, it means it can be accessible outside
of the declared class as well.
static: It means we want to access a method without making object of the
class , main() method is called without creating any object.
void: indicates that it does not return any value.
String r[]: it is an array and each element is a string. We can pass
command line parameters, the main() method takes it as an input.
Output in Java:
System.out.println() or System.out.print() statement is used in Java to
print any text as well as value of variables on the screen.
System: it is a class name
Out: is an object of PrintStream class which is a public and static member
of System class.
println or print: it is public method of PrintStream class which can be
accessed by the object out.
e.g. System.out.println(“a=”+a+”b=”+b);
Input in Java:
The Scanner class is used to get user input and it is found in java.util
package.
System.in : This is the standard input stream that is used to read characters
from keyboard or any other input device.
Scanner ob = new Scanner(System.in);
Scanner methods:
-nextInt(): returns the next integer value
-nextFloat() : returns the next float value
-nextDouble() : returns the next double value
-nextLine(): returns the next multiple word string value
e.g.
int a;
a=ob.nextInt();
OOP Principles:
1. Encapsulation: It is the process that binds together both code and
data into a single unit and keep safe from outside interference and
misuse. It is wrapping of data into a single unit. In this process the
data is hidden from other classes and can be accessed only through
the current class methods. It is also known as data hiding. So
encapsulation act as a protective wrapper that prevents the code and
data from being accessed by outsiders.
2. Polymorphism: It refers to many forms or it is a process that
performs a single action in different ways. We can perform
polymorphism in Java by method overloading and method
overriding. Method overloading is an example of compile time
polymorphism. Run time polymorphism also called a dynamic
method dispatch in which a call to an overridden method is resolvers
at run time mot at compile time.
3. Inheritance: It is a process by which one class can acquire the
properties of another class. Inheritance represents the parent-child
relationship. The idea behind inheritance is that we can create new
classes built on existing classes i.e. when we inherit from an existing
class, we can reuse methods and fields of the parent class.
4. Abstraction: It is a process which displays the information needed
and hides the unnecessary information. The purpose of abstraction
is data hiding. Abstraction means selecting data from a large number
of data to show the information needed, which helps in reducing
programming complexity and efforts.
Java Class Libraries (JCL):
The Java class library is a set of dynamically loadable libraries that JVM
can call at run time. Java platform is not dependent on specific operating
system, applications cannot rely on any of the platform native libraries.
Instead it provides a comprehensive set of standard class libraries.
Java Class Libraries
Java
util net awt math (packages)
lang
System Math Scanner URL (classes)
java.lang : It is always implicitly imported. It contains all fundamentals
classes.
e.g. String, Double, Math etc.
java.util : It is a built-in package that contains various utility classes and
interfaces. It provides basic functionality for commonly occurring use
cases. It contains Java's collections framework, date and time utilities,
etc.
java.math : provides mathematical expressions.
java.io: It contains classes for supporting input/output operations.
e.g BufferedInputStram, BufferedOutputStream,
BufferedReader, BufferedWriter
Data types in Java:
Data types specifies 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, and Arrays.
Data Type
Primitive Non-primitive
Boolean Numeric String
Character Integral Array
Class
integer floating
boolean char byte float
short double
Int
long
Data Type Size Range
boolean 1-bit true or false
byte 1-byte -128 to 127
short 2-bytes -32768 to 32767
Int 4-bytes -2,147,483,648 to
2,147,483,647
long 8-bytes 9,223,372,036,854,775,808 to
9,223,372,036,854,775,807
float 4-bytes Upto 7-decimal digits
double 8-bytes Upto 16-decimal digits
char 2-bytes 0 to 65535 (16-bit Unicode
characters)
Boolean data type: It stores only two possible values- true or false. It is
used for true/false conditions. It is used to store the result of logical
expressions or conditions.
e.g. boolean a=true;
boolean a=false;
byte data type: It is an 8-bit data. It has a range of values from -128 to
127. The byte data type is commonly used when working with raw
binary data or when memory conservation is concerned.
e.g. byte a=23;
short data type: It is 2-byte(16-bit) data. It has a range of values from -
32,768 to 32,767.
e.g. short a=523;
int data type: It is 4-byte data. It has a range of values from -
2,147,483,648 to 2,147,483,647.
The int data type is one of the most commonly used data types in Java.
e.g. int a=5023;
long data type: It is 8-byte data. It has a wider range of values than int,
ranging from -9,223,372,036,854,775,808 to
9,223,372,036,854,775,807.
e.g. long a=5547;
float data type: It is a primitive data type that represents 32-bit
floating-point numbers. It represents values upto 7-decimal points.
e.g. float a=5.7f;
double data type: It is a primitive data type that represents double-
precision 64-bit floating-point numbers. It provides a wider range of
values and greater precision compared to the float data type, making it
suitable for applications where accurate representation of decimal values
is required. It represents values upto 16 decimal points.
e.g. double a=5.7;
char data type: The char data type in Java is a primitive data type that
represents 16-bit Unicode character. It can store any character from the
Unicode character set, that allows Java to support internationalization and
representation of characters from various languages and writing systems.
The char data type is commonly used to represent characters, such as
letters, digits, and symbols, in Java programs. It can also be used to
perform arithmetic operations, as the Unicode values of characters can be
treated as integers. For example, you can perform addition or subtraction
operations on char variables to manipulate their Unicode values.
e.g. char a=’B’;
Unicode System:
Unicode is a universal international standard character encoding that is capable of
representing most of the world's written languages.
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.
This caused two problems:
A particular code value corresponds to different letters in the
various language standards.
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.
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
Java variables:
A variable is a container that stores data vales during program execution.
In Java all variables must be declared before can be used.
e.g. int a=20;
//Java program for the addition of two numbers
Class Sum
{
public static void main(String r[])
{
int a,b,c;
System.out.printlln(“Enter value for a & b:”);
Scanner s=new Scanner(System.in);
a= s.nextInt();
b= s.nextInt();
c=a+b;
System.out.printlln(“Sum=:”+c);
}
}
Arrays in Java:
An array is a collection of similar type of data or an array is an object
which contains elements of similar data type. The elements are stored in
contiguous memory location.
One dimensional array:
General form:
type name[]; // type is base type of array i.e. data type of each element
e.g.
int a[];
The declaration establishes a is array variable, no array actually exist.
The value of a is set to NULL, represents an array with no value.
For physical allocation use new and assign it to a.
new – It is a special operator that allocates memory
e.g. a=new int[5]; //a is array with 5 elements
All elements in the array will be initialized to zero
We can also declare array in a single step:
int [] a=new int[5];
or
int a[]=new int[5];
Array initialization:
int a[]={2,4,6,8,10};
Multidimensional aray: These are array of arrays.
e.g. int a[][]=new int[4][5];
or
int [][] a=new int[4][5];
Automatic type promotion in expression:
Automatic promotion in Java is a feature that automatically converts
smaller data types to larger data types when they are used in expressions
or method calls. It is used to ensure that the operands in an expression or
the arguments to a method have the same data type, so that the operation
can be performed successfully.
In Java while evaluating an expression intermediate value may exceed the
range of operands and hence the expression value will be promoted.
The ranking order, from lowest to highest, is as follows: byte, short, int,
long, float, and double. When two operands with different data types are
used in an expression, Java automatically promotes the lower-ranking
type to the higher-ranking type before performing the operation.
All byte, short and char values are promoted to int while
evaluating an expression
If one operand is long, float or double the whole expression is
promoted to long, float or double respectively
e.g. //program demonstrate type promotion in expresson
class Test
{
byte a=10;
short b=20;
int c;
c=a*b; //byte and short data promoted to int
System.out.println(“c=”+c);
}
Another example
class Test
{
byte a=10,b=20, c;
c=a*b; //error incompatible types (a and b promoted to int)
System.out.println(“c=”+c);
}
To overcome this problem use typecasting
class Test
{
byte a=10,b=20, c;
c=(byte)(a*b); //typecast int is converted to byte
System.out.println(“c=”+c);
}
When one type of data is assigned to another type of variable, an
automatic type of conversion will take place :
If the two types are compatible
If the destination type is larger than the source type
e.g.
int a;
float b=2.5;
a=b; // a is assigned 2 two types are compatible
Operators:
Operators are used to perform various type of operations.
There are many types of operators in Java which are given below:
Unary Operator,
Arithmetic Operator,
Shift Operator,
Relational Operator,
Bitwise Operator,
Logical Operator,
Ternary Operator and
Assignment Operator.
Unary Operator
The Java unary operators require only one operand. Unary operators are
used to perform various operations i.e.:
incrementing/decrementing a value by one
negating an expression
e.g.
public class Exam
{
public static void main(String a[])
{
int a=10;
System.out.println(x++);//10 (11)
System.out.println(++x);//12
System.out.println(x--);//12 (11)
System.out.println(--x);//10
}
}
Output:
10
12
12
10
Another e.g.
public class Exam
{
public static void main(String args[])
{
int a=10;
int b=10;
System.out.println(a++ + ++a);//10+12=22
System.out.println(b++ + b++);//10+11=21
}
}
Output:
22
21
Java Arithmetic Operators
Java arithmetic operators are used to perform addition, subtraction,
multiplication, and division. They act as basic mathematical operations.
e.g.
public class Exam
{
public static void main(String a[])
{
int a=10;
int b=5;
System.out.println(a+b);//15
System.out.println(a-b);//5
System.out.println(a*b);//50
System.out.println(a/b);//2
System.out.println(a%b);//0
}
}
Output:
15
5
50
2
0
The modulus operator(%)returns remainder, but in Java it can also be
applied to floating point types.
e.g. int a=23,b;
double c=36.5,d;
b=a%10; //b=3
d=c%10; //6.5
Java Relational Operators
Relational operators are used to check the relationship between two
operands
Operator Description Example
3 == 5 returns
== Is Equal To
false
!= Not Equal To 3 != 5 returns true
> Greater Than 3 > 5 returns false
< Less Than 3 < 5 returns true
Greater Than or 3 >= 5 returns
>=
Equal To false
Less Than or Equal
<= 3 <= 5 returns true
To
e.g.
class Exam
{
public static void main(String[] a)
{
int a = 7, b = 11; // create variables
System.out.println("a is " + a + " and b is " + b); // value of a and b
// == operator
System.out.println(a == b); // false
// != operator
System.out.println(a != b); // true
// > operator
System.out.println(a > b); // false
// < operator
System.out.println(a < b); // true
// >= operator
System.out.println(a >= b); // false
// <= operator
System.out.println(a <= b); // true
}
}
Java Logical Operators
Logical operators are used to check whether an expression
is true or false. They are used in decision making.
Operat
Example Meaning
or
&&
(Logic expression1 && true only if both expression1
al expression2 and expression2 are true
AND)
||
expression1 || true if either expression1 or
(Logic
expression2 expression2 is true
al OR)
!
(Logic true if expression is false
!expression
al and vice versa
NOT)
e.g.
class Exam
{
public static void main(String[] a)
{
// && operator
System.out.println((5 > 3) && (8 > 5)); // true
System.out.println((5 > 3) && (8 < 5)); // false
// || operator
System.out.println((5 < 3) || (8 > 5)); // true
System.out.println((5 > 3) || (8 < 5)); // true
System.out.println((5 < 3) || (8 < 5)); // false
// ! operator
System.out.println(!(5 == 3)); // true
System.out.println(!(5 > 3)); // false
}
}
Java Bitwise Operators:
Bitwise operators in Java are used to perform operations on individual
bits of their operand. They are applied for int, long, short, byte.
Bitwise operators present in Java are:
Operator Description
~ Bitwise Complement
<< Left Shift
>> Right Shift
Unsigned Right Shift (right
>>>
shift zero fill)
& Bitwise AND
^ Bitwise exclusive OR
Bitwise NOT(~): It is bitwise complement, inverts all the bits of its
operand.
e.g. a=01101110
~a=10010001
Bitwise AND(&): It returns bit by bit AND of input values.
e.g. a=5 0 1 0 1 (in binary)
b=7 0 1 1 1
a&b 0 1 0 1 =5(in decimal)
Bitwise OR(|): It returns bit by bit OR of input values.
e.g. a=5 0 1 0 1 (in binary)
b=7 0 1 1 1
a|b 0 1 1 1 =7(in decimal)
The Left shift (<<) operator: The operator shift all the bits of its
operand to the left a specified number of times.
Syntax: value<<num; //number of times
For each left shift the higher order bit is shifted out(and lost) and 0 is
brought in on the right.
e.g.
class Exam
{
public static void main(String[] a)
{
int n = 2;
// 2 bit left shift operation
int r = n << 2;
System.out.println(r); // prints 8
}
}
Java automatic type promotion produces some unexpected results when
we are shifting byte and short values (byte and short are promoted to int
when an expression is evaluated). The result of such an expression is also
int. It means the outcome of a left shift on a byte or short value will be an
int and bits shifted left will not be lost until they shift past bit position 31.
e.g.
byte a=64,b;
int c;
b=(byte)(a<<2); //b=0
c=a<<2; //c=256
Another e.g.
byte a=-64,b;
int c;
b=(byte)(a<<2); //b=0
c=a<<2; //c=-256
The right shift (>>) operator: The operator shifts all the bits of its
operand to the right a specified number of times.
Syntax: value>>num; //number of times
when we shift any number to the right, the least significant bits
(rightmost) are discarded and the most significant position (leftmost) is
filled with the sign bit(0 or 1).
e.g.
byte a=64,b;
int c;
b=(byte)(a>>2); //b=16
c=a>>2; //c=16
When bits are shifted right, the leftmost bits are filled in with the
previous contents of the leftmost bit. This is called sign conversion and
serves to preserve the sign of negative numbers when shift to the right.
e.g.
class Exam
{
public static void main(String[] args)
{
int n1 = 8;
int n2= -8;
// 2 bit signed right shift
System.out.println(n1 >> 2); // prints 2
System.out.println(n2 >> 2); // prints -2
}
}
If we shift -1 to the right, the result is always -1.
The unsigned right shift(>>>):
Java also provides an unsigned right shift. It is denoted by >>>. The
vacant leftmost position is filled with 0 instead of the sign bit. Sometimes
we are shifting that does not represent a numeric value, we do not want
sign extension take place. We want to shift a zero into high order bit no
matter what its initial value was. This is called unsigned shift.
e.g.
class Exam
{
public static void main(String[] a)
{
int n1 = 8;
int n2 = -8;
// 2 bit signed right shift
System.out.println(n1 >>> 2); // prints 2
System.out.println(n2 >>> 2); // prints 1073741822
}
}
Java Ternary Operator:
The ternary operator (conditional operator) is shorthand for the if-then-
else statement.
Syntax:
v = Exp ? expression1 : expression2
execution:
If the Exp is true, expression1 is assigned to the variable.
If the Exp is false, expression2 is assigned to the variable.
e.g.
class Test
{
public static void main(String[] a)
{
int febDays = 29;
String result;
// ternary operator
result = (febDays == 28) ? "Not a leap year" : "Leap year";
System.out.println(result);
}
}
Output:
Leap year