java unit-1
java unit-1
Object means a real-world entity such as a mobile, book, table, computer, watch, etc. Object-
Oriented Programming is a methodology or paradigm to design a program using classes and
objects. It simplifies software development and maintenance by providing some concepts.
Object
Class
Inheritance
Polymorphism
Abstraction
Encapsulation
1. Object
In object-oriented programming, an object is an entity that has two characteristics (states and
behavior). Some of the real-world objects are book, mobile, table, computer, etc. An object is
a variable of the type class, it is a basic component of an object-oriented programming
system. A class has the methods and data members (attributes), these methods and data
members are accessed through an object. Thus, an object is an instance of a class.
2. Class
In object-oriented programming, a class is a blueprint from which individual objects are
created (or, we can say a class is a data type of an object type). In Java, everything is related
to classes and objects. Each class has its methods and attributes that can be accessed and
manipulated through the objects.
3. Inheritance
4. Polymorphism
The term "polymorphism" means "many forms". In object-oriented programming,
polymorphism is useful when you want to create multiple forms with the same name of a
single entity. To implement polymorphism in Java, we use two concepts method
overloading and method overriding.
The method overloading is performed in the same class where we have multiple methods
with the same name but different parameters, whereas, the method overriding is performed by
using the inheritance where we can have multiple methods with the same name in parent and
child classes.
5. Abstraction
The real-world example of an abstraction is a Car, the internal details such as the engine,
process of starting a car, process of shifting gears, etc. are hidden from the user, and features
such as the start button, gears, display, break, etc are given to the user. When we perform any
action on these features, the internal process works.
6. Encapsulation
Below are some of the differences between procedural and object-oriented programming:
Adding new data and functions is not easy. Adding new data and function is easy.
Procedural programming does not have any Object-oriented programming provides data
proper way of hiding data so it is less secure. hiding so it is more secure.
History of Java
The history of Java is very interesting. Java was originally designed for interactive television,
but it was too advanced technology for the digital cable television industry at the time. The
history of Java starts with the Green Team. Java team members (also known as Green Team),
initiated this project to develop a language for digital devices such as set-top boxes,
televisions, etc. However, it was best suited for internet programming. Later, Java technology
was incorporated by Netscape.
Java was developed by James Gosling, who is known as the father of Java, in 1995. James
Gosling and his team members started the project in the early '90s. Currently, Java is used in
internet programming, mobile devices, games, e-business solutions, etc.
1) James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language
project in June 1991. The small team of sun engineers called Green Team.
2) 2) Initially it was designed for small, embedded systems in electronic appliances like
set-top boxes.
3) 3) Firstly, it was called "Greentalk" by James Gosling, and the file extension
was .gt.
4) 4) After that, it was called Oak and was developed as a part of the Green project.
7) 5) Why Oak? Oak is a symbol of strength and chosen as a national tree of many
countries like the U.S.A., France, Germany, Romania, etc.
8) 6) In 1995, Oak was renamed as "Java" because it was already a trademark by Oak
Technologies.
10) 7) Why had they chose the name Java for Java language? The team gathered to
choose a new name. The suggested words were "dynamic", "revolutionary", "Silk",
"jolt", "DNA", etc. They wanted something that reflected the essence of the
technology: revolutionary, dynamic, lively, cool, unique, and easy to spell, and fun to
say.
11) According to James Gosling, "Java was one of the top choices along with Silk". Since
Java was so unique, most of the team members preferred Java than other names.
12) 8) Java is an island in Indonesia where the first coffee was produced (called Java
coffee). It is a kind of espresso bean. Java name was chosen by James Gosling while
having a cup of coffee nearby his office.
14) 10) Initially developed by James Gosling at Sun Microsystems (which is now a
subsidiary of Oracle Corporation) and released in 1995.
15) 11) In 1995, Time magazine called Java one of the Ten Best Products of 1995.
16) 12) JDK 1.0 was released on January 23, 1996. After the first release of Java, there
have been many additional features added to the language. Now Java is being used in
Windows applications, Web applications, enterprise applications, mobile applications,
cards, etc. Each new version adds new features in Java.
Java versions:
Since Java SE 8 release, the Oracle corporation follows a pattern in which every even version
is release in March month and an odd version released in September month.
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.
Byte 0 1 byte
Short 0 2 byte
Int 0 4 byte
Long 0L 8 byte
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:
The byte data type is an example of primitive data type. It isan 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:
Java Variables
A variable is a container which holds the value while the Java program is executed. A
variable is assigned with a data type.
Variable is a name of memory location. There are three types of variables in java: local,
instance and static.
Variable
A variable is the name of a reserved area allocated in memory. In other words, it is a name of
the memory location
o local variable
o instance variable
o static variable
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.
2) Instance Variable
A variable declared inside the class but outside the body of the method, is called an instance
variable. It is not declared as static.
3) Static variable
A variable that is declared as static is called a static variable. It cannot be local. You can
create a single copy of the static variable and share it among all the instances of the class.
Memory allocation for static variables happens only once when the class is loaded in the
memory.
INSTANCE VARIABLE
A variable which is declared inside a class and outside all the methods and blocks is an
instance variable.
General scope of an instance variable is throughout the class except in static
methods. Lifetime of an instance variable is until the object stays in memory.
Class Variables
A variable which is declared inside a class, outside all the blocks and is marked static is
known as a class variable.
General scope of a class variable is throughout the class and the lifetime of a class
variable is until the end of the program or as long as the class is loaded in memory.
Local Variables
All other variables which are not instance and class variables are treated as local variables
including the parameters in a method.
Scope of a local variable is within the block in which it is declared and the lifetime of a
local variable is until the control leaves the block in which it is declared.
Scope of the variables:
public class Test
{
static int x = 11;
private int y = 33;
public void method1(int x)3265
{
Test t = new Test();
this.x = 22;
y = 44;
// Drive Class
class GFG {
// Main Function
public static void main (String[] args) {
}
}
2. Unary Operators
Unary operators need only one operand. They are used to increment, decrement, or negate a
value.
– : Unary minus, used for negating the values.
+ : Unary plus indicates the positive value (numbers are positive without this,
however). It performs an automatic conversion to int when the type of its operand is the
byte, char, or short. This is called unary numeric promotion.
++ : Increment operator, used for incrementing the value by 1. There are two varieties
of increment operators.
o Post-Increment: Value is first used for computing the result and then
incremented.
o Pre-Increment: Value is incremented first, and then the result is computed.
– – : Decrement operator, used for decrementing the value by 1. There are two
varieties of decrement operators.
Post-decrement: Value is first used for computing the result and then
o
decremented.
o Pre-Decrement: The value is decremented first, and then the result is
computed.
! : Logical not operator, used for inverting a boolean value.
Example:
Java
// Driver Class
class GFG {
// main function
public static void main(String[] args)
{
// Interger declared
int a = 10;
int b = 10;
Output
Postincrement : 10
Preincrement : 12
Postdecrement : 10
Predecrement : 8
3. Assignment Operator
‘=’ Assignment operator is used to assign a value to any variable. It has right-to-left
associativity, i.e. value given on the right-hand side of the operator is assigned to the
variable on the left, and therefore right-hand side value must be declared before using it or
should be a constant.
The general format of the assignment operator is:
variable = value;
In many cases, the assignment operator can be combined with other operators to build a
shorter version of the statement called a Compound Statement. For example, instead of
a = a+5, we can write a += 5.
+=, for adding the left operand with the right operand and then assigning it to the
variable on the left.
-=, for subtracting the right operand from the left operand and then assigning it to the
variable on the left.
*=, for multiplying the left operand with the right operand and then assigning it to the
variable on the left.
/=, for dividing the left operand by the right operand and then assigning it to the
variable on the left.
%=, for assigning the modulo of the left operand by the right operand and then
assigning it to the variable on the left.
Example:
Java
// Driver Class
class GFG {
// Main Function
public static void main(String[] args)
{
// Assignment operators
int f = 7;
System.out.println("f += 3: " + (f += 3));
System.out.println("f -= 2: " + (f -= 2));
System.out.println("f *= 4: " + (f *= 4));
System.out.println("f /= 3: " + (f /= 3));
System.out.println("f %= 2: " + (f %= 2));
System.out.println("f &= 0b1010: " + (f &= 0b1010));
System.out.println("f |= 0b1100: " + (f |= 0b1100));
System.out.println("f ^= 0b1010: " + (f ^= 0b1010));
System.out.println("f <<= 2: " + (f <<= 2));
System.out.println("f >>= 1: " + (f >>= 1));
System.out.println("f >>>= 1: " + (f >>>= 1));
}
}
Output
f += 3: 10
f -= 2: 8
f *= 4: 32
f /= 3: 10
f %= 2: 0
f &= 0b1010: 0
f |= 0b1100: 12
f ^= 0b1010: 6
f <<= 2: 24
f >>= 1: 12
f >>>= 1: 6
4. Relational Operators
These operators are used to check for relations like equality, greater than, and less than.
They return boolean results after the comparison and are extensively used in looping
statements as well as conditional if-else statements. The general format is,
variable relation_operator value
Some of the relational operators are-
==, Equal to returns true if the left-hand side is equal to the right-hand side.
!=, Not Equal to returns true if the left-hand side is not equal to the right-hand side.
<, less than: returns true if the left-hand side is less than the right-hand side.
<=, less than or equal to returns true if the left-hand side is less than or equal to the
right-hand side.
>, Greater than: returns true if the left-hand side is greater than the right-hand side.
>=, Greater than or equal to returns true if the left-hand side is greater than or equal
to the right-hand side.
Example:
Java
// Driver Class
class GFG {
// main function
public static void main(String[] args)
{
// Comparison operators
int a = 10;
int b = 3;
int c = 5;
Output
a > b: true
a < b: false
a >= b: true
a <= b: false
a == c: false
a != c: true
5. Logical Operators
These operators are used to perform “logical AND” and “logical OR” operations, i.e., a
function similar to AND gate and OR gate in digital electronics. One thing to keep in mind
is the second condition is not evaluated if the first one is false, i.e., it has a short-circuiting
effect. Used extensively to test for several conditions for making a decision. Java also has
“Logical NOT”, which returns true when the condition is false and vice-versa
Conditional operators are:
&&, Logical AND: returns true when both conditions are true.
||, Logical OR: returns true if at least one condition is true.
!, Logical NOT: returns true when a condition is false and vice-versa
Example:
Java
// Driver Class
class GFG {
// Main Function
public static void main (String[] args) {
// Logical operators
boolean x = true;
boolean y = false;
Output
x && y: false
x || y: true
!x: false
6. Ternary operator
The ternary operator is a shorthand version of the if-else statement. It has three operands
and hence the name Ternary.
The general format is:
condition ? if true : if false
The above statement means that if the condition evaluates to true, then execute the
statements after the ‘?’ else execute the statements after the ‘:’.
Example:
Java
Output
// Driver class
class GFG {
// main function
public static void main(String[] args)
{
// Bitwise operators
int d = 0b1010;
int e = 0b1100;
System.out.println("d & e: " + (d & e));
System.out.println("d | e: " + (d | e));
System.out.println("d ^ e: " + (d ^ e));
System.out.println("~d: " + (~d));
System.out.println("d << 2: " + (d << 2));
System.out.println("e >> 1: " + (e >> 1));
System.out.println("e >>> 1: " + (e >>> 1));
}
}
Output
d & e: 8
d | e: 14
d ^ e: 6
~d: -11
d << 2: 40
e >> 1: 6
e >>> 1: 6
8. Shift Operators
These operators are used to shift the bits of a number left or right, thereby multiplying or
dividing the number by two, respectively. They can be used when we have to multiply or
divide a number by two. General format-
number shift_op number_of_places_to_shift;
<<, Left shift operator: shifts the bits of the number to the left and fills 0 on voids left
as a result. Similar effect as multiplying the number with some power of two.
>>, Signed Right shift operator: shifts the bits of the number to the right and fills 0 on
voids left as a result. The leftmost bit depends on the sign of the initial number. Similar
effect to dividing the number with some power of two.
>>>, Unsigned Right shift operator: shifts the bits of the number to the right and fills
0 on voids left as a result. The leftmost bit is set to 0.
Java
// Driver Class
class GFG {
// main function
public static void main(String[] args)
{
int a = 10;
Output
a<<1 : 20
a>>1 : 5
9. instanceof operator
The instance of the operator is used for type checking. It can be used to test if an object is
an instance of a class, a subclass, or an interface. General format-
object instance of class/subclass/interface
TYPE CASTING?
When a data type is converted into another data type by a programmer or user while writing a
program code of any programming language, the mechanism is known as type casting
Syntax:
float b = 3.0;
int a = (int) b; // converting a float value into integer
AreaOfRectangle.c
1. #include<stdio.h>
2. #include<conio.h>
3. void main()
4. {
5. printf("\n Welcome to Javatpoint tutorials ");
6. float x = 3.5, y = 4.5;
7. int area;
8. area = (int) x * y; // after conversion the product converts into integer
9. printf("\n Area of a Rectangle is : %d", area);
10. printf("\n Here, we convert float data type into the Int data type");
11. getch();
12. }
1. #include<stdio.h>
2. #include<conio.h>
3. void main()
4. {
5. printf("\n Welcome to Javatpoint tutorials ");
6. int x = 3, y = 4; // the size of int variable is 2 byte.
7. float area; // the size of float variable is 4 bytes.
8. area = x * y; /* It is a type conversion that automatically converted by the compiler at the
compile time of a program. */
9. printf("\n Area of a Rectangle is : %f", area);
10. printf("\n Here, we convert int data type to the float data type");
11. getch();
12. }
The static keyword is used to construct methods that will exist regardless of whether or not
any instances of the class are generated. Any method that uses the static keyword is referred
to as a static method.
import java.io.*;
// instance variable
int b = 50;
void simpleDisplay()
{
System.out.println(a);
System.out.println(b);
}
// main method
public static void main(String[] args)
{
GFG obj = new GFG();
obj.simpleDisplay();
Output
40
50
40
In Java, Method Overloading allows different methods to have the same name, but different
signatures where the signature can differ by the number of input parameters or type of input
parameters, or a mixture of both.
Method overloading in Java is also known as Compile-time Polymorphism, Static
Polymorphism, or Early binding.
// Driver code
public static void main(String args[])
{
Sum s = new Sum();
System.out.println(s.sum(10, 20));
System.out.println(s.sum(10, 20, 30));
System.out.println(s.sum(10.5, 20.5));
}
}
Output
30
60
31.0
Student Id : 0
Student Name : null
Student Id : 10
Student Name : David
RECURSION IN JAVA:
Recursion in java is a process in which a method calls itself continuously. A method in java
that calls itself is called recursive method.
hello
hello
...
java.lang.StackOverflowError
hello 1
hello 2
hello 3
hello 4
hello 5
To do so, we were using free() function in C language and delete() in C++. But, in java it is
performed automatically. So, java provides better memory management.
Advantage of Garbage Collection
o It makes java memory efficient because garbage collector removes the unreferenced
objects from heap memory.
o It is automatically done by the garbage collector(a part of JVM) so we don't need to
make extra efforts.
1) By nulling a reference:
1. Employee e=new Employee();
2. e=null;
2) By assigning a reference to another:
1. Employee e1=new Employee();
2. Employee e2=new Employee();
3. e1=e2;//now the first object referred by e1 is available for garbage collection
3) By anonymous object:
1. new Employee();
BUILDING STRING:
Generally, String is a sequence of characters. But in Java, string is an object that represents a
sequence of characters. The java.lang.String class is used to create a string object.
1. By string literal
2. By new keyword
1) String Literal
Java String literal is created by using double quotes. For Example:
1. String s="welcome";
2) By new keyword
1. String s=new String("Welcome");/
Output:
java
strings
example
The java.lang.String class provides a lot of built-in methods that are used to
manipulate string in Java. By the help of these methods, we can perform operations on
String objects such as trimming, concatenating, converting, comparing, replacing strings etc.
The Java String toUpperCase() method converts this String into uppercase letter and String
toLowerCase() method into lowercase letter.
Stringoperation1.java
Output:
SACHIN
sachin
Sachin
Stringoperation2.java
Output:
Sachin
Sachin
The method startsWith() checks whether the String starts with the letters passed as arguments
and endsWith() method checks whether the String ends with the letters passed as arguments.
Stringoperation3.java
Output:
true
true
Stringoperation4.java
Output:
S
h
Stringoperation5.java
Output:
6
Java String valueOf() Method
The String class valueOf() method coverts given type such as int, long, float, double,
boolean, char and char array into String.
Stringoperation7.java
1010
Stringoperation8.java
7. System.out.println(replaceString);
8. }
9. }
Output:
In general, a method is a way to perform some task. Similarly, the method in Java is a
collection of instructions that performs a specific task. It provides the reusability of code. We
can also easily modify code using methods.
The most important method in Java is the main() method. If you want to read more about the
main() method, go through the link https://www.javatpoint.com/java-main-method.
Method Declaration
The method declaration provides information about method attributes, such as visibility,
return-type, name, and arguments. It has six components that are known as method header,
as we have shown in the following figure.
Method Signature: Every method has a method signature. It is a part of the method
declaration. It includes the method name and parameter list.
Access Specifier: Access specifier or modifier is the access type of the method. It specifies
the visibility of the method. Java provides four types of access specifier:
o Public: The method is accessible by all classes when we use public specifier in our
application.
o Private: When we use a private access specifier, the method is accessible only in the
classes in which it is defined.
o Protected: When we use protected access specifier, the method is accessible within
the same package or subclasses in a different package.
o Default: When we do not use any access specifier in the method declaration, Java
uses default access specifier by default. It is visible only from the same package only.
Return Type: Return type is a data type that the method returns. It may have a primitive data
type, object, collection, void, etc. If the method does not return anything, we use void
keyword.
Method Name: It is a unique name that is used to define the name of a method. It must be
corresponding to the functionality of the method. Suppose, if we are creating a method for
subtraction of two numbers, the method name must be subtraction(). A method is invoked
by its name.
Parameter List: It is the list of parameters separated by a comma and enclosed in the pair of
parentheses. It contains the data type and variable name. If the method has no parameter, left
the parentheses blank.
Method Body: It is a part of the method declaration. It contains all the actions to be
performed. It is enclosed within the pair of curly braces.
Naming a Method
While defining a method, remember that the method name must be a verb and start with
a lowercase letter. If the method name has more than two words, the first name must be a
verb followed by adjective or noun. In the multi-word method name, the first letter of each
word must be in uppercase except the first word. For example:
It is also possible that a method has the same name as another method name in the same
class, it is known as method overloading.
Types of Method
o Predefined Method
o User-defined Method
Predefined Method
In Java, predefined methods are the method that is already defined in the Java class libraries
is known as predefined methods. It is also known as the standard library method or built-
in method. We can directly use these methods just by calling them in the program at any
point. Some pre-defined methods are length(), equals(), compareTo(), sqrt(), etc. When we
call any of the predefined methods in our program, a series of codes related to the
corresponding method runs in the background that is already stored in the library.
Each and every predefined method is defined inside a class. Such as print() method is
defined in the java.io.PrintStream class. It prints the statement that we write inside the
method. For example, print("Java"), it prints Java on the console.
Demo.java
1. import java.util.Scanner;
2. public class EvenOdd
3. {
4. public static void main (String args[])
5. {
6. //creating Scanner class object
7. Scanner scan=new Scanner(System.in);
8. System.out.print("Enter the number: ");
9. //reading value from the user
10. int num=scan.nextInt();
11. //method calling
12. findEvenOdd(num);
13. }
In the above code snippet, as soon as the compiler reaches at line findEvenOdd(num), the
control transfer to the method and gives the output accordingly.
JAVA CONSTRUCTORS
A constructor in Java is a special method that is used to initialize objects. The constructor is
called when an object of a class is created. It can be used to set initial values for object
attributes:
Create a constructor:
public Main() {
Main myObj = new Main(); // Create an object of class Main (This will call the
constructor)
}
// Outputs 5
Note that the constructor name must match the class name, and it cannot have a return
type (like void).
Also note that the constructor is called when the object is created.
Constructor Parameters
The following example adds an int y parameter to the constructor. Inside the constructor we
set x to y (x=y). When we call the constructor, we pass a parameter to the constructor (5),
which will set the value of x to 5:
Example
int x;
public Main(int y) {
x = y;
System.out.println(myObj.x);
// Outputs 5
int modelYear;
String modelName;
modelYear = year;
modelName = name;