JAVA - UNIT - 1 Customised
JAVA - UNIT - 1 Customised
1. Introduction to JAVA
JAVA History
James Gosling, Patrick Naughton, Chris Warth, Ed Frank, and Mike Sheridan conceived Java at Sun
Microsystems, Inc. in 1991. It took 18 months to develop the first working version. This language
was initially called “Oak” but was renamed “Java” in 1995. The original motivation for java was not
the Internet! Instead, the primary motivation was the need for a platform-independent
(Architectural Neutral).
S.N Year Name of the Place &Developers Drawbacks
o programming
language
1. 1960 ALGOL 60 International Too general and too abstract
Committee
2. 1963 CPL Cambridge University Hard to learn and implement
3. 1967 BCPL Martin Richards at Could only deal with specific
Cambridge University problems.
4. 1970 B Ken Thompson at Dealt with only specific problems
AT&T BELL Laboratory
5. 1972 C Dennis Ritchie at AT&T Added features of B and BCPL and
BELL Laboratory lost generality and abstractions
6. 1979 C++ Bjarne Stroustrup Derived from C and added features
of object-oriented programming
7. 1991 JAVA James Goslling, Patrick Completely object based and
Naughtson, Chris Architectural Neutral.
Warth, Ed Frank and
Mike Sheridan at Sun
Micro Systems
JAVA
JAVA is high-level programming language that follows OOP principle. The main motto of JAVA
programming language is “write once and run everywhere”. The syntax and semantics of JAVA
are very much similar to C & C++ programming languages.
JAVA is considered a programming language and a platform independent. As a programming
language, it is a general-purpose, object-oriented, high-level programming language that has its
own syntax and style. As a platform, it provides an environment in which java applications run.
Applications of JAVA
Mobile Applications
Desktop GUI Applications
Web-based Applications
Enterprise Applications
Scientific Applications
Gaming Applications
Big Data technologies
Business Applications
Distributed Applications
Cloud-based Applications
Features of JAVA
There are eleven features of JAVA programming Language. They are:
i.) Simple:
It is easy to understand and learn.
Java is a simple programming language and its syntax is based on C++, easy for
C++ learners.
It removed some difficult and rarely used like pointers, operator overloading etc.
No need to remove unwanted data because there is an automatic garbage
collector.
ii.) Object-oriented:
It is independent because other languages like C and C++ can’t move from one
system to other, which is possible in JAVA. The compiler converts the written
program in byte code, which is done internally in the system.
iv.) Secured:
v.) Portable:
vi.) Robust:
It is a faster programming language. JAVA bytecode is close to naïve code but its
slower than C++.
JAVA is an interpreted language, that is why it is slower.
ix.) Distributed:
The distributed feature of JAVA makes us to access the files by calling methods.
x.) Multi-threaded:
It means “more than one”. We can perform 2 (or) more tasks at a time.
xi.) Dynamic:
This means class libraries are linked with some other libraries.
JDK:
The Java Development Kit (JDK) is one of three core technology
packages used in Java programming, along with the JVM (Java Virtual
Machine) and the JRE (Java Runtime Environment). It's important to
differentiate between these three technologies and understand how
they're connected:
The JRE is the on-disk part of Java that creates the JVM and loads
programs into them.
The JDK provides the tools necessary to write Java programs that can
be executed and run by the JVM and JRE.
Developers new to Java often confuse the Java Development Kit and
the Java Runtime Environment. The distinction is that the JDK is a
package of tools for developing Java-based software, whereas the
JRE is a package of tools for running Java code.
Basic Operators
The operator is applied between two Boolean expressions. It is denoted by the two AND
operators (&&). It returns true if and only if both expressions are true, else returns false.
X Y X && Y
2) Conditional OR:
The operator is applied between two Boolean expressions. It is denoted by the two OR
operator (||). It returns true if any of the expression is true, else returns false.
X Y X || Y
3)Ternary Operators:
The meaning of ternary is composed of three parts. The ternary operator (? :) consists of
three operands. It is used to evaluate Boolean expressions. The operator decides which
value will be assigned to the variable. It is the only conditional operator that accepts
three operands. It can be used instead of the if-else statement. It makes the code much
more easy, readable, and shorter.
CONDITIONAL STATEMENTS:
IF STATEMENT:
If basically analysis and chooses in which direction a program flows based on certain
parameters and conditions.
SYNTAX:
If(condition)
//Block of statements
PROGRAM:
Int age=18;
If(age>=18);
IF ELSE STATEMENT:
In if else program if the condition is true then the statement present in if statement will be
executed if the condition is false the else statement will be executed.
SYNTAX:
If(condition)
//block of statement
}
else
//block of statements
PROGRAM:
int age=18;
If(age>=18)
else
SWITCH STATEMENT:
The switch statement is a multi-way branching statement. In simple words, the java switch
statement executes one statement from multiple conditions.
SYNTAX:
Switch(condition)
Case 1:
//block of statements
Break;
Case 2:
//block of statement
Break;
Default:
//block of statement
PROGRAM:
int i=5;
Case 1:
System.out.println(“I is 1”);
Break;
Case 2:
System.out.println(“I is 2”);
Break;
Case 3:
System.out.println(“I is 3”);
Break;
Case 4:
System.out.println(“I is 4”);
Break;
Case 5:
System.out.println(“I is 5”);
Break;
Default:
System.out.println(“INVALID VALUE”);
Data types specify the different sizes and values that can be stored in the variable. There
are two types of data types in Java:
1. Primitive data types: The primitive data types include boolean, char, byte, short,
int, long, float and double.
2. Non-primitive data types: The non-primitive data types
include Classes, Interfaces, and Arrays.
In Java language, primitive data types are the building blocks of data manipulation.
These are the most basic data types available in Java language.
There are 8 types of primitive data types:Backward Skip 10sPlay VideoForward Skip 10s
o boolean data type
o byte data type
o char data type
o short data type
o int data type
o long data type
o float data type
o double 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.
Example:
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:
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 minimum value is -32,768 and maximum value
is 32,767. 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:
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 minimum
value is - 2,147,483,648and maximum value is 2,147,483,647. 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:
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
minimum value is - 9,223,372,036,854,775,808and maximum value is
9,223,372,036,854,775,807. 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:
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. The float data type should never be
used for precise values, such as currency. Its default value is 0.0F.
Example:
1. float f1 = 234.5f
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. The
double data type also should never be used for precise values, such as currency. Its
default value is 0.0d.
Example:
1. double d1 = 12.3
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:
Loops in java:
Loops in java : Loop is used in programming to repeat a specific block of code when some
conditions become true. There are three types of loops in java.
(1) for loop
(2) while loop
(3) do-while loop >
The for Loop : The for loop is used to iterate a part of the program several times. If the number
of iteration is fixed, it is recommended to use for loop. There are three types of for loops in java.
✓ Simple For Loop
✓For-each or Enhanced For Loop
✓Labeled For Loop
Simple For Loop : We can initialize variable, check condition The simple for loop is same as
C/C++. and increment/decrement value.
Syntax :
for(initialization; condition; incr/decr)
{ //code to be executed }
Program to show usage to of for loop:
Public class Forexample
{
public static void main(String[]args)
{
for(int i=1;i<=5;i++)
{
System.out.println(i);
}
}
}
Output:
1
2
3
4
5
for-each Loop : The for-each loop is used to traverse array or collection in java. It is easier to use
than simple for loop because we don't need to increment value and use subscript notation. It
works on elements basis not index. It returns element one by one in the defined variable
. Syntax :
for(Type var : array)
{
//code to be executed
}
program to show usage of for each loop:
public class ForEachExample:
{
public static void main(String[] args)
{
int arr[]= (10,12,25,30,56);
for(int i : arr)
{
System.out.println(i);
}
}
}
Output :
10
12
25
30
56
LOOPS
While Loop : The Java while loop is used to iterate a part of the program several times. If number
of iteration is not fixed, it is recommended to use while loop.
Syntax :
while(condition)
{
//code to be executed
}
Program to show usage of while loop
public class Whilexample
{
public static void main(String[] args)
{
int i=1;
while(i<=5)
System.out.println(i);
i++;
}
}
}
Output :
1
2
3
4
5
do-while Loop :
The java dowhile loop is used to iterate a part of program several times . If the number of
iteration is not fixed and you must have to execute the loop at least once, it is recommended to
use do while loop. The java do-while loop is executed at least once because condition is checked
after loop body .
Syntax :
do
{
//code to be executed
}
while(condition);
Program to show usage of do-while loop:
2. DEFINING CLASSES
Class:
Class is the collection of instance variables and methods which are nothing but variables and
functions in C language and Data variables and member functions in C++ language.
Syntax of Class:
Class < classname>
{
-----------
------------
------------
------------
}
No need to put “;” at the end of the class in Java as in C++.
System.out.println(“Name=”+name);
System.out.println(“Rollno=”+rollno);
}
}
We use + symbol(Concat) to add. If we want to add any argument to first argument, we use +.
Method:
Method Syntax:
returntype methodname(argument, argument)
{
-----------
--------- //body
----------
}
voidset( ) is the method from above class example.
Object:
The instance of class is called object.
Syntax:
Classname objectname = new Classname( );
Student s = new Student( );
Here, new keyword allocates memory dynamically.
class Add
{
int a, b, t; //instance variables create separate copies for a,b,c and t when objcre
void sum()
{
a=13
b=7
t=a+b;
system.out.println(“Sum of the two numbers =” +t)
}
}
class Madd
{
public static void main(string args[]);
{
Add obj = new add();
obj.sum();
}
}
Execution starts from main class which is ‘public static void main(string args[]); in the
above program.
We have to save program with main class name only (i.e.) Madd.java
Instance Methods are the group of codes that performs a particular task. Sometimes
the program grows in size, and we want to separate the logic of the main method from
other methods.
Instance methods can access instance variables and instance methods directly and
undeviatingly.
Instance methods can access static variables and static methods directly.
Syntax:
modifier return_type method_name( )
{
method body;
}
Exmaple:
public void disp( )
{
int a= 10;
System.out.println(a);
}
Calling Instance Method:
You cannot call an instance method in the static method directly, so the instance
method can be invoked using an object of the class. As we know java program
starts from the main method is static. So first we have to call class object then we
can call the instance method in the main method.
Example:
// Java program to see how can we call
// an instance method with parameter
importjava.io.*;
class Luck {
// static method
Public static void main (String[] args) {
// creating object
LUCK obj = new Luck();
// calling instance method by passing value
obj.add(2,3);
System.out.println("LUCK!");
}
// Instance method with parameter
Void add(int a, int b)
{
// local variables
Int x= a;
Int y= b;
Int z= x + y;
System.out.println("Sum : "+ z);
}
}
output:
Sum : 5
LUCK !
The accessor method is used to make the code more secure and increase its protection
level, accessor is also known as a getter. Getter returns the value that returns the value
of data type int, string, double, float, etc. For the convenience of the program, getter
starts with the word “get” followed by the variable name.
The mutator method is also known as the setter. It sets the value for any variable which is
used in the programs of a class and starts with the word “set” followed by the variable
name.
Getter and Setter make the programmer convenient in setting and getting the value for a
particular data type. In both getter and setter, the first letter of the variable should be
capital.
Accessor and mutator are mainly used to access or set the value for the private member
of the class in the main method.
Constructors:
In Java, a constructor is a block of codes similar to the method. It is called when an instance
of the class is created. At the time of calling constructor, memory for the object is allocated
in the memory.
Every time an object is created using the new () keyword, at least one constructor is called.
It calls a default constructor if there is no constructor available in the class. In such case,
Java compiler provides a default constructor by default.
There are two types of constructors in Java: Default constructor, and parameterized
constructor.
Bike is created
The default constructor is used to provide the default values to the object like 0, null, etc.,
depending on the type.
Java Parameterized Constructor
The parameterized constructor is used to provide different values to distinct objects. However,
you can provide the same values also.
//Java Program to demonstrate the use of the parameterized constructor.
class Student
{
int id;
String name;
//creating a parameterized constructor
Student(int i,String n)
{
id = i;
name = n;
}
//method to display the values
void display()
{
System.out.println(id+" "+name);
}
public static void main(String args[])
{
//creating objects and passing values
Student s1 = new Student4(111,"Karan");
Student s2 = new Student4(222,"Aryan");
//calling method to display the values of object
s1.display();
s2.display();
}
}
Output:
111 Karan
222 Aryan
Constructor overloading in Java is a technique of having more than one constructor with
different parameter lists. They are arranged in a way that each constructor performs a different
task. They are differentiated by the compiler by the number of parameters in the list and their
types.
PROGRAM :
Class Add
{
Int x,y,total;
x=10;
y=20;
}
Add (int x)
x=a;
y=a;
Add(int a, int b )
x=a;
y=b;
Void sum()
Total=x+y;
System.out.println(“sum=”+total);
}
}
class Madd
args);
01.sum();
02.sum();
03.sum();
METHOD OVERLOADING:
If a class has multiple methods having same name but different in parameters, it is
known as Method Overloading.
Example program:
class mo
{
System.out.println(“sum=”+(a+b))’;
System.out.println(“sum”+(a+b+c));
}
void add (float x, float y)
{
system.out.println(“sum”+(x+y));
}//class closed
Class Mmo
{
Public static void main(string []args);
obj .add(10,20);
obj.add(10.20,10.40);
obj.add (10,20,30);
}
}
There are many differences between constructors and methods. They are given below.
A constructor is used to initialize the state of an A method is used to expose the behavior of an
object. object.
A constructor must not have a return type. A method must have a return type.
The Java compiler provides a default constructor The method is not provided by the compiler in any
if you don't have any constructor in a class. case.
The constructor name must be same as the class The method name may or may not be same as the
name. class name.
There is no copy constructor in Java. However, we can copy the values from one object to
another like copy constructor in C++.
There are many ways to copy the values of one object into another in Java. They are:
o By constructor
o By assigning the values of one object into another
o By clone() method of Object class
Copying values without constructor
We can copy the values of one object into another by assigning the objects values to another
object. In this case, there is no need to create the constructor.
class Student7{
int id;
String name;
Student7(int i,String n){
id = i;
name = n;
}
Student7(){
}
void display()
{
System.out.println(id+" "+name);
}
public static void main(String args[]){
Student7 s1 = new Student7(111,"Karan");
Student7 s2 = new Student7();
s2.id=s1.id;
s2.name=s1.name;
s1.display();
s2.display();
}
}
Output:
111 Karan
111 Karan
Access specifiers
The access specifiers in Java specifies the accessibility / scope of a field, method, constructor or
class.
We can change the access levels of the fields, constructors and class by applying access
specifiers / modifiers on it.
Variables:
A variable is the name of a reserved area allocated in the memory.
It is the combo of Varry and Able (Varry + Able) which means the value can be changed.
It is of 3 types. They are
1) Local Variable: A variable which is declares inside the body of the method / method
parameter is called as local variable.
Example:
Void add ()
{
Int x; // local variable
}
(OR)
Void add(int x) // int x is the local variable
2) Instance Variable: A variable which is declared inside the class but outside the method.
Example:
Class Book
{
Int a, b; // Instance Variable
Public static void main(string args[])
}
{
------------
----------
}
3) Static Variable: A variable which is declared with the help of static keyword is called as
static variable.
Example:
Static int a;
// We can use this anywhere in the program
Static Keyword:
Final Keyword:
A method can take an objects as a parameter. For example, in the following program, the
method setData( ) takes three parameters. The first parameter is a Data object. If you pass an
object as an argument to a method, the mechanism that applies is called pass-by-reference,
because a copy of the reference contained in the variable is transferred to the method, not a
copy of the object itself.
class Data {
int data1;
int data2;
}
class setData{
void setData(Data da,int d1,int d2)
{
da.data1 = d1;
da.data2 = d2;
}
void getData(Data da)
{
System.out.println(“data1 : “+da.data1);
System.out.println(“data2 : “+da.data2);
}
}
public class Javaapp{
public static void main(String[] args){
Data da = new Data();
SetData sd = new setData();
sd.setData(da,50,100);
sd.getData(da);
}
}
Output:
data1 : 50
data2 : 100
They are defined in class but outside the They are defined as a type of variable declared
body of methods. within programming blocks.
These variables are created when an These variables are created when a block, method
object is instantiated and are accessible or constructor is started and the variable will be
to all constructors, methods, or blocks in destroyed once it exits the block, method, or
class. constructor.
These variables are destroyed when the These variables are destroyed when the
object is destroyed. constructor or method is exited.
It can be accessed throughout the class. Its access is limited to the method in which it is
declared.
They are used to reserving memory for They are used to decreasing dependencies
data that the class needs and that too for between components I.e., the complexity of code
the lifetime of the object. is decreased.
These variables are given a default value These variables do not always have some value,
if it is not assigned by code. so there must be a value assigned by code.
It includes access modifiers such as It does not include any access modifiers such as
private, public, protected, etc. private, public, protected, etc.
Object class is present in java.lang package. Object Class in Java is the topmost class
among all the classes in Java. We can also say that the Object class in Java is the parent class for
all the classes. It means that all the classes in Java are derived classes and their base class is the
Object class.All the classes directly or indirectly inherit from the Object class in Java.
Class Vehicle{
//body of class Vehicle
}
Here we can see that the class Vehicle is not inheriting any class, but it inherits the Object class.
It is an example of the direct inheritance of object class.
Class Vehicle{
//body of class Vehicle
}
Class Car extends Vehicle{
//body of class Car
}
Here we can see that the Car class directly inherits the Vehicle class. The extends keyword is
used to establish inheritance between two classes. But we have seen in the above example that if
we define a class without inheriting it from some other class, it directly inherits the Object class.
Since Car inherits the Vehicle and the Vehicle inherits the Object class, the Car indirectly
inherits the Object class.
User Input from Keyboard
Accepting keyboard input in Java is done using a Scanner object.
int x = console.nextInt();