Java - Unit1 2023-24 (CS Major)
Java - Unit1 2023-24 (CS Major)
Example: A Student is an object because it has states i.e. name, rollnumber,section etc. as well as behaviours
i.e. add, delete, edit student data and learn etc.
In java Object is created with following statement:
Classname Objectname =new Classname();
Students obj = new Students ();
Real Life Examples for Objects : Table, fan, pen etc.
UNIT-1
Class:
Collection of similar objects (same methods and properties) is called class. It is a logical entity.In
another way, a class can be defined as a template/blueprint that describes the behavior/state that the object of
its type supports.
Consider many student objects and logically group all student objects as class Students i.e.) shown below.
Objects: Student1 Student2 Student3 Student4
Class : Students
Class Symbolic notation in OOP is shown below.
Polymorphism
Ability to shown one thing in many forms. In another way, when one task is performed by different ways i.e.
known as polymorphism. In java, we use method overloading, method overriding to achieve
polymorphism.
Example1: cat speaks meow, dog barks woof etc
Example 2 (Operator Overloading): “+” symbol is used in different purposes in our programs shown
below.
2 + 2=4 (Integer addition)
“Ram” + “Krishna “ =”Ram Krishna “ (String Concatenation )
Adding new data and functions is not easy. Adding new data and function is easy.
It does not provide any inheritance. It achieves inheritance
There is no access specifier in procedural Object-oriented programming has access
programming. specifiers like private, public, protected, etc.
In procedural programming, overloading is not Overloading is possible in object-oriented
possible. programming.
Examples: C, FORTRAN, Pascal, Basic, etc. Examples: C++, Java, Python, C#, etc.
Java Programming
Introduction to java
Java is a programming language developed by James Gosling with other team members named Mike
Sheridan and Patrick Naughton also called as Green Team in 1995 for Sun Microsystems for digital
devices such as set-top boxes, televisions etc.
Java is a general-purpose, concurrent, object-oriented, class-based, and the runtime environment (JRE)
which consists of JVM which is the cornerstone of the Java platform.
Where Java used?
Java has been used in different domains. Some of them are listed below.
1. Desktop Applications such as acrobat reader, media player, antivirus etc.
2. Web Applications like irctc.co.in, http://www.nannayauniversity.info/ etc.
3. Enterprise Applications such as banking applications.
4. Mobile Applications.
5. Embedded Systems.
6. Smart Cards.
7. Robotics.
8. Games etc.
Features of JAVA
The main objective of Java programming language creation was to make it portable, simple and secure
programming language. Apart from this, there are also some awesome features which play important role in
the popularity of this language. The features of Java are also known as java buzzwords.
Lists of most important features of Java language are given below.
1. Simple
2. Object-Oriented
3. Portable
4. Platform independent
5. Secured
6. Robust
7. Architecture neutral
8. Interpreted
9. High Performance
10. Multithreaded
11. Distributed
12. Dynamic
UNIT-1
Simple:
Java is very easy to learn and its syntax is simple, clean and easy to understand. According to Sun, 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 confusing and rarely-used features e.g. explicit pointers, operator overloading
etc.
o There is no need to remove unreferenced objects because there is Automatic Garbage Collection in
java.
Object-oriented
Java is object-oriented programming language. Everything in Java is an object. Object-oriented means we
organize our software as a combination of different types of objects that incorporates both data and behaviour.
Object-oriented programming (OOPs) is a methodology that simplifies software development and
maintenance by providing some rules.
Basic concepts of OOPs are:
1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation
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.
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 virtual machine sandbox
Robust
Robust simply means strong. Java is robust because:
o It uses strong memory management.
o There are lack of pointers that avoids security problems.
o There is automatic garbage collection in java which runs on the Java Virtual Machine to get rid of
objects which are not being used by a Java application anymore.
o There is exception handling and type checking mechanism in java. All these points make java robust.
UNIT-1
Architecture-neutral
Java is architecture neutral because there is no implementation dependent features e.g. size of
primitive types is fixed.
Portable
Java is portable because it facilitates you to carry the java bytecode to any platform. It doesn't require
any type of implementation.
High-performance
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.
Distributed
Java is distributed because it facilitates users to create distributed applications in java. This feature of
Java makes us able to access files by calling the methods from any machine on the internet.
Multi-threaded
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.
Dynamic
Java is a dynamic language. It supports dynamic loading of classes & dynamic linking. It means
classes are loaded on demand. Java supports automatic memory management (garbage collection).
.
UNIT-1
Java Program Structure
Java Program has the following specified sections:
Documentation Section:
The documentation section comprises a set of comment lines describing the programme for easy maintenance
and understand ability .Comments in java program are shown below.
1. // Single line comment
2. /*
Multiple line comments
*/
Package Statement:
The first statement allowed in a Java file is a package statement. This statement declares a package name and
informs the compiler that the classes defined here belong to this package.
Example: package packagename;
Import Statements:
The next thing after a package statement (but before any class definitions) may be a number of import
statements. This is similar to the #include statement in C. The below statement instructs the interpreter to load
io –classes contained in the sub package io.
Example : import java. io.*;
Interface Statements:
An interface is like a class but includes a group of method declarations. This is also an optional section and is
used only when we wish to implement the multiple inheritance features in the program.
Class Definitions:
A Java program may contain multiple class definitions. Classes are the primary and essential elements of a
Java program. But every java program must contain one class with main method. This main method defines
the execution flow of program.
Example java program:
//Example program
package Example;
import java.io.*;
class SarnpleOne
{
public static void rnain(String args[ ])
{
Systerm.out.println("Java is better than C++.");
}
}
UNIT-1
Data Type Default Value Default size(in bytes) Default size(in bits)
boolean FALSE 1 bit 1 bit
char '\u0000' 2 byte 16 bits
Byte 0 1 byte 1 bit
short 0 2 byte 16 bits
Int 0 4 byte 32 bits
Long 0L 8 byte 64 bits
float 0.0f 4 byte 32 bits
double 0.0d 8 byte 64 bits
Boolean Data Type
The Boolean data type is used to store only two possible values: true and false. This data type is used
for simple flags that track true/false conditions.
The Boolean data type specifies one bit of information, but its "size" can't be defined precisely.
Example: Boolean one = false
UNIT-1
Byte Data Type
The byte data type is an example of primitive data type. It is an 8-bit signed two's complement integer.
Its value range lies between -128 to 127 (inclusive). Its minimum value is -128 and maximum value is 127. Its
default value is 0.
The byte data type is used to save memory in large arrays where the memory savings is most required.
It saves space because a byte is 4 times smaller than an integer. It can also be used in place of "int" data type.
Example: byte a = 10, byte b = -20
Short Data Type
The short data type is a 16-bit signed two's complement integer. Its value-range lies between -32,768
to 32,767 (inclusive). Its default value is 0.
The short data type can also be used to save memory just like byte data type. A short data type is 2 times
smaller than an integer.
Example: short s = 10000, short r = -5000
Int Data Type
The int data type is a 32-bit signed two's complement integer. Its value-range lies between -
2,147,483,648 (-2^31) to 2,147,483,647 (2^31 -1) (inclusive). Its default value is 0.
The int data type is generally used as a default data type for integral values unless if there is no problem about
memory.
Example: int a = 100000, int b = -200000
Long Data Type
The long data type is a 64-bit two's complement integer. Its value-range lies between -
9,223,372,036,854,775,808(-2^63) to 9,223,372,036,854,775,807(2^63 -1)(inclusive). Its default value is 0.
The long data type is used when you need a range of values more than those provided by int.
Example: long a = 100000L, long b = -200000L
Float Data Type
The float data type is a single-precision 32-bit IEEE 754 floating point. Its value range is unlimited. It
is recommended to use a float (instead of double) if you need to save memory in large arrays of floating point
numbers. It is generally used as the default data type for decimal values. Its default value is 0.0d.
Example: float f1 = 234.5f
Double Data Type
The double data type is a double-precision 64-bit IEEE 754 floating point. Its value range is unlimited. The
double data type is generally used for decimal values just like float. Its default value is 0.0d.
Example: double d1 = 12.3
Char Data Type
The char data type is a single 16-bit Unicode character. Its value-range lies between '\u0000' (or 0) to '\uffff'
(or 65,535 inclusive).The char data type is used to store characters.
Example: char letterA = 'A'
UNIT-1
Java Variables
A variable is a container which holds the value while the program is executed. A variable
is assigned with a data type. Variable is a name of memory location. There are three types of
variables in java.
1. local
2. instance
3. static
1) Local Variable
A variable declared inside the body of the method is called local variable. You can use
this variable only within that method and the other methods in the class aren't even aware
that the variable exists.
A local variable cannot be defined with "static" keyword.
2) Instance Variable
A variable declared inside the class but outside the body of the method, is called instance
variable. It is not declared as static.
It is called instance variable because its value is instance specific and is not shared
among instances.
3) Static variable
A variable which is declared as static is called static variable. It cannot be local. You can
create a single copy of static variable and share among all the instances of the class. Memory
allocation for static variable happens only once when the class is loaded in the memory.
Example to understand the types of variables in java
1. class A
2. {
3. int data=50; //instance variable
4. static int m=100; //static variable
5. void method()
6. {
7. int n=90; //local variable
8. }
9. }//end of class
UNIT-1
Type Casting
Assigning a value of one type to a variable of another type is known as Type Casting.
Example:
int x = 10;
byte y = (byte)x;
In Java, type casting is classified into two types.
Widening Casting(Implicit)
Operators in Java
Java provides a rich set of operators environment. Java operators can be divided into following categories:
Arithmetic operators
Relation operators
Logical operators
Bitwise operators
Assignment operators
Conditional operators
Misc operators
Arithmetic operators
Arithmetic operators are used in mathematical expression in the same way that are used in algebra.
Operator Description
+ adds two operands
- subtract second operands from first
* multiply two operand
/ divide numerator by denumerator
% remainder of division
++ Increment operator increases integer value by one
-- Decrement operator decreases integer value by one
UNIT-1
Example Program:
public class Test {
public static void main(String args[]) {
int a = 10;
int b = 20;
int c = 25;
int d = 25;
System.out.println("a + b = " + (a + b) );
System.out.println("a - b = " + (a - b) );
System.out.println("a * b = " + (a * b) );
System.out.println("b / a = " + (b / a) );
System.out.println("b % a = " + (b % a) );
System.out.println("c % a = " + (c % a) );
System.out.println("a++ = " + (a++) );
System.out.println("b-- = " + (a--) );
// Check the difference in d++ and ++d
System.out.println("d++ = " + (d++) );
System.out.println("++d = " + (++d) );
}
}
Output :
a + b = 30
a - b = -10
a * b = 200
b/a=2
b%a=0
c%a=5
a++ = 10
b-- = 11
d++ = 25
++d = 27
Relation operators:
The following table shows all relation operators supported by Java.
Operator Description
== Check if two operand are equal
!= Check if two operand are not equal.
> Check if operand on the left is greater than operand on the right
< Check operand on the left is smaller than right operand
>= check left operand is greater than or equal to right operand
<= Check if operand on left is smaller than or equal to right operand
Example Program:
public class Test {
public static void main(String args[]) {
UNIT-1
Assignment Operators
Assignment operator supported by Java are as follows:
Operator Description Example
= assigns values from right side operands to left side operand a=b
+= adds right operand to the left operand and assign the result to a+=b is same
left as a=a+b
-= subtracts right operand from the left operand and assign the a-=b is same as
result to left operand a=a-b
*= mutiply left operand with the right operand and a*=b is same
assign the result to left operand as a=a*b
/= divides left operand with the right operand and a/=b is same
assign the result to left operand as a=a/b
%= calculate modulus using two operands and a%=b is same
assign the result to left operand as a=a%b
Misc operator
There are few other operator supported by java language.
Conditional operator
It is also known as ternary operator and used to evaluate Boolean expression,
epr1 ? expr2 : expr3
If epr1 Condition is true? Then value expr2: Otherwise value expr3
Example:
instanceOf operator
This operator is used for object reference variables. The operator checks whether the object is of particular
type (class type or interface type)
// Reading a string
System.out.print("Enter your name: ");
String name = scanner.nextLine();
// Reading an integer
System.out.print("Enter your age: ");
int age = scanner.nextInt();
// Reading a double
System.out.print("Enter your height (in meters): ");
double height = scanner.nextDouble();
format: A format string that specifies how the output should be structured.
arguments: The values to be formatted and inserted into the format string.
Common Format Specifiers
%s: String
%d: Integer
%f: Floating-point number
%x: Hexadecimal
%t: Date and time
Examples
1. Basic Formatting
int age = 25;
String name = "Alice";
String formatted = String.format("%s is %d years old.", name, age);
UNIT-1
System.out.println(formatted); // Output: Alice is 25 years old.
2. Floating-Point Precision
double pi = 3.14159;
String formatted = String.format("Value of Pi: %.2f", pi);
System.out.println(formatted); // Output: Value of Pi: 3.14
Control Statements
A Control statement is a statement that controls the flow of execution of the program. Java‟s program control
statements are divided into 3 categories
● Selection Statements
● Iteration Statements
● Jump Statements
1)Selection Statements:
Selection statement controls the flow of the program depending on the result of the conditional expression
or the state of a variable. There are two selection statements: if and switch
a. if statement:
„if‟ is a selection statement that is used to choose two choices in a program.
Syntax: Example
if(condition) if(condition)
statement1; System.out.println(“if block”);
else else
statement2; System.out.println(“else block”);
„condition‟ is any expression that returns a Boolean value (i.e., true/false). Statement is a single
or multiple statements.
If the condition is true then the control goes to the statement1 and it is executed. Otherwise, the
statement2 is executed.
b. Nested if statement:
It means an if statement under another if statement.
Syntax:
if(condition)
{
if(condition)
statement;
}
c. If - else- if ladder:
if-else-if statement is a sequence of if-else statements. In if-else-if ladder if a condition is not met then the
control flows from top to bottom until the last if statement.
Syntax:
if(condition)
statement1;
else if(condition)
statement2;
else if(condition)
UNIT-1
statement3;
. …..
else statementn;
d. switch statement: It provides more than one choice to choose. It‟s a better alternative to if-else-if
ladder.
Syntax:
switch(expression) public class Test {
{ public static void main(String args[]) {
case value1: statement1; // char grade = args[0].charAt(0);
break; char grade = 'C';
case value2: statement2; switch(grade) {
break; case 'A' :
case value3: statement3; System.out.println("Excellent!");
break; break;
. case 'B' :
. case 'C' :
case valueN: statementN; System.out.println("Well done");
break; break;
default : statement; case 'F' :
} System.out.println("Better try again");
break;
default :
System.out.println("Invalid grade");
}
System.out.println("Your grade is " + grade);
}
}
Here, the expression may be of type byte, short, int or char only. the case values must be of type expression
and each value should be unique. When control comes to the switch statement then the value of the expression
is compared with the case values, if a match is found then the statement(s) corresponding to that case is
executed. If none of the case is matched then the default statement is executed.
2) Iteration Statements: These statements allow the part of the program to repeat one or more times until
some condition becomes true. There are 3 iteration statements: while, do-while and for.
a. while statement: „while‟ is an iteration statement, that repeats a statement or block of statements until
some condition is true.
Syntax:
Syntax Example
while(condition) public class Test {
{ public static void main(String args[]) {
// body of the loop int x = 10;
} while( x < 20 ) {
System.out.print("value of x : " + x );
x++;
System.out.print("\n");
}
}
}
UNIT-1
where the condition may be any boolean expression. The body of the loop will be executed as long as the
condition is true. Once the condition becomes false, the control passes to the statement immediately after
the while loop.
b. do-while statement:
„do-while‟ statement is very much similar to while statement with little difference. In while
statement, if the condition is initially false then the body of loop will not be executed at all. Where as
in do-while statement, body of the loop will be executed at least once since the condition of do-while
is at the bottom of the loop.
Syntax Example
Do public class Test {
{ public static void main(String args[]) {
// body of the loop int x = 10;
} while(condition); do {
System.out.print("value of x : " + x );
x++;
System.out.print("\n");
}while( x < 20 );
}
}
Each iteration of do-while executes the body of loop first and evaluates the condition later. If condition
is true, the loop repeats. Otherwise, the loop terminates.
c. for statement:
„for‟ statement also repeats the execution of statements while its condition is true.
Syntax:
Syntax Example
for(initialization; public class Test {
condition; iteration) public static void main(String args[]) {
{ for(int x = 10; x < 20; x = x + 1) {
// body of the loop System.out.print("value of x : " + x );
System.out.print("\n");
}
}
}
}
Where initialization portion of the loop sets the value of the variable that acts as a counter. This
portion is executed first when the loop starts. And it is executed only once. When the control goes to
condition, condition is evaluated. If condition is true, the body of loop is executes. Otherwise the loop
terminates. Next iteration portion is executed. This helps to increment or decrement the control
variable.
The loop then iterates evaluating condition, then executing the body and then executing the
iteration portion each time it iterates.
2) Jump Statements:
Jump statements allow the control to jump to a particular position. There are 3 types of jump
statements.
a. break statement:
In java, there are 3 uses of break statement.
i. It helps to terminate a statement sequence in switch statement.
UNIT-1
ii. It can be used to exit or terminate the loop
iii. It can be used as another form of goto
Example:
class A
{
public static void main(String arg[])
{
for(int i=0; i<100; i++)
{
if(i==10)
break; // terminates loop if i is 10
System.out.println(“i :”+i);
}
}
}
b. continue statement: The continue statement starts the next iteration of the immediately enclosing
iteration statements (while, do-while or for). When the control goes to continue statement, then it skips
the remaining statements and starts the next iteration of enclosing structure. Example shown below.
class A
{
public static void main(String arg[])
{
for(int i=0; i<100; i++)
{
System.out.println(“i :”+i);
if(i%2==0)
continue;
System.out.println(“ “);
}
}
}
c. return statement: This is used to return from a method. When the control reaches to return
statement, it causes the program control to transfer back to the caller of the method. Example shown
below.
class A
{
public static void main(String arg[])
{
boolean t=true;
if(t)
return;
System.out.println(“Hi”); // This won‟t execute
}
}