Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
3 views

java unit-1

The document provides an overview of Object-Oriented Programming (OOP) concepts in Java, including key principles such as objects, classes, inheritance, polymorphism, abstraction, and encapsulation. It also discusses the advantages of OOP, compares procedural programming with object-oriented programming, and outlines the history and evolution of Java as a programming language. Additionally, the document details Java's data types, variables, and their characteristics.

Uploaded by

rsgnr2006
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

java unit-1

The document provides an overview of Object-Oriented Programming (OOP) concepts in Java, including key principles such as objects, classes, inheritance, polymorphism, abstraction, and encapsulation. It also discusses the advantages of OOP, compares procedural programming with object-oriented programming, and outlines the history and evolution of Java as a programming language. Additionally, the document details Java's data types, variables, and their characteristics.

Uploaded by

rsgnr2006
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 38

OOPs (Object-Oriented Programming System)

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.

The concepts of Java (OOPs) object-oriented programming systems.

Java OOPs (Object-Oriented Programming) 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

In object-oriented programming, inheritance is a process by which we can reuse the


functionalities of existing classes to new classes. In the concept of inheritance, there are two
terms base (parent) class and derived (child) class. When a class is inherited from another
class (base class), it (derived class) obtains all the properties and behaviors of the base class.

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

In object-oriented programming, an abstraction is a technique of hiding internal details and


showing functionalities. The abstract classes and interfaces are used to achieve abstraction in
Java.

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

In an object-oriented approach, encapsulation is a process of binding the data members


(attributes) and methods together. The encapsulation restricts direct access to important data.
The best example of the encapsulation concept is making a class where the data members are
private and methods are public to access through an object. In this case, only methods can
access those private data.

Advantages of Java OOPs

The following are the advantages of using the OOPs in Java:

 The implementations of OOPs concepts are easier.


 The execution of the OOPs is faster than procedural-oriented programming.
 OOPs provide code reusability so that a programmer can reuse an existing code.
 OOPs help us to keep the important data hidden.
Procedural Programming vs Object-Oriented Programming

Below are some of the differences between procedural and object-oriented programming:

Procedural Oriented Programming Object-Oriented Programming

In object-oriented programming, the


In procedural programming, the program is
program is divided into small parts
divided into small parts called functions.
called objects.

Procedural programming follows a top-down Object-oriented programming follows


approach. a bottom-up approach.

There is no access specifier in procedural Object-oriented programming has access


programming. specifiers like private, public, protected, etc.

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.

In procedural programming, overloading is Overloading is possible in object-oriented


not possible. programming.

In object-oriented programming, the


In procedural programming, there is no
concept of data hiding and inheritance is
concept of data hiding and inheritance.
used.

In procedural programming, the function is In object-oriented programming, data is


more important than the data. more important than function.

Procedural programming is based on Object-oriented programming is based on


the unreal world. the real world.
Procedural Oriented Programming Object-Oriented Programming

Procedural programming is used for Object-oriented programming is used for


designing medium-sized programs. designing large and complex programs.

Procedural programming uses the concept of Object-oriented programming uses the


procedure abstraction. concept of data abstraction.

Code reusability absent in procedural Code reusability present in object-oriented


programming, programming.

Examples: C, FORTRAN, Pascal, Basic,


Examples: C++, Java, Python, C#, etc.
etc.

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.

5) Why Java was named as "Oak"?


6) In 1995, Oak was renamed as "Java" because it was already a trademark by Oak
Technologies.

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.

9) Why Java Programming named "Java"?

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.

13) 9) Notice that Java is just a name, not an acronym.

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:

1. JDK Alpha and Beta (1995)


2. JDK 1.0 (23rd Jan 1996)
3. JDK 1.1 (19th Feb 1997)
4. J2SE 1.2 (8th Dec 1998)
5. J2SE 1.3 (8th May 2000)
6. J2SE 1.4 (6th Feb 2002)
7. J2SE 5.0 (30th Sep 2004)
8. Java SE 6 (11th Dec 2006)
9. Java SE 7 (28th July 2011)
10. Java SE 8 (18th Mar 2014)
11. Java SE 9 (21st Sep 2017)
12. Java SE 10 (20th Mar 2018)
13. Java SE 11 (September 2018)
14. Java SE 12 (March 2019)
15. Java SE 13 (September 2019)
16. Java SE 14 (Mar 2020)
17. Java SE 15 (September 2020)
18. Java SE 16 (Mar 2021)
19. Java SE 17 (September 2021)
20. Java SE 18 (to be released by March 2022)

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.

Data Types in Java


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.

Java Primitive Data Types

In Java language, primitive data types are the building blocks of data manipulation. These are
the most basic data types available in Java language.

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
Data Type Default Value Default size

boolean false 1 bit

Char '\u0000' 2 byte

Byte 0 1 byte

Short 0 2 byte

Int 0 4 byte

Long 0L 8 byte

Float 0.0f 4 byte

double 0.0d 8 byte

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:

1. Boolean one = false

Byte Data Type

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:

1. 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 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:

1. 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 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:

1. 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
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:

1. 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. 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

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. 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

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:

1. char letterA = 'A'


Why char uses 2 byte in java and what is \u0000 ?
It is because java uses Unicode system not ASCII code system. The \u0000 is the lowest
range of Unicode system.

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

1. int data=50;//Here data is variable


Types of Variables
There are three types of variables in Java:

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.

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 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.

Example to understand the types of variables in java


1. public class A
2. {
3. static int m=100;//static variable
4. void method()
5. {
6. int n=90;//local variable
7. }
8. public static void main(String args[])
9. {
10. int data=50;//instance variable
11. }
12. }//end of class

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;

System.out.println("Test.x: " + Test.x);


System.out.println("t.x: " + t.x);
System.out.println("t.y: " + t.y);
System.out.println("y: " + y);
}

public static void main(String args[])


{
Test t = new Test();
t.method1(5);
}
}

What are the Java Operators?


Operators in Java are the symbols used for performing specific operations in Java.
Operators make tasks like addition, multiplication, etc which look easy although the
implementation of these tasks is quite complex.
Operators are the building blocks of Java expressions, allowing you to perform
calculations, comparisons, and more.
Types of Operators in Java
There are multiple types of operators in Java all are mentioned below:
1. Arithmetic Operators
2. Unary Operators
3. Assignment Operator
4. Relational Operators
5. Logical Operators
6. Ternary Operator
7. Bitwise Operators
8. Shift Operators
9. instance of operator
1. Arithmetic Operators
They are used to perform simple arithmetic operations on primitive and non-primitive data
types.
 * : Multiplication
 / : Division
 % : Modulo
 + : Addition
 – : Subtraction
Example:
Java

// Java Program to implement


// Arithmetic Operators
import java.io.*;

// Drive Class
class GFG {
// Main Function
public static void main (String[] args) {

// Arithmetic operators on integers


int a = 10;
int b = 3;

// Arithmetic operators on Strings


String num1 = "15";
String num2 = "25";

// Convert Strings to integers


int a1 = Integer.parseInt(num1);
int b1 = Integer.parseInt(num2);

System.out.println("a + b = " + (a + b));


System.out.println("a - b = " + (a - b));
System.out.println("a * b = " + (a * b));
System.out.println("a / b = " + (a / b));
System.out.println("a % b = " + (a % b));
System.out.println("a1 + b1 = " + (a1 + b1));

}
}
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

// Java Program to implement


// Unary Operators
import java.io.*;

// Driver Class
class GFG {
// main function
public static void main(String[] args)
{
// Interger declared
int a = 10;
int b = 10;

// Using unary operators


System.out.println("Postincrement : " + (a++));
System.out.println("Preincrement : " + (++a));

System.out.println("Postdecrement : " + (b--));


System.out.println("Predecrement : " + (--b));
}
}

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

// Java Program to implement


// Assignment Operators
import java.io.*;

// 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

// Java Program to implement


// Relational Operators
import java.io.*;

// Driver Class
class GFG {
// main function
public static void main(String[] args)
{
// Comparison operators
int a = 10;
int b = 3;
int c = 5;

System.out.println("a > b: " + (a > b));


System.out.println("a < b: " + (a < b));
System.out.println("a >= b: " + (a >= b));
System.out.println("a <= b: " + (a <= b));
System.out.println("a == c: " + (a == c));
System.out.println("a != c: " + (a != c));
}
}

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

// Java Program to implemenet


// Logical operators
import java.io.*;

// Driver Class
class GFG {
// Main Function
public static void main (String[] args) {
// Logical operators
boolean x = true;
boolean y = false;

System.out.println("x && y: " + (x && y));


System.out.println("x || y: " + (x || y));
System.out.println("!x: " + (!x));
}
}

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

// Java program to illustrate


// max of three numbers using
// ternary operator.
public class operators {
public static void main(String[] args)
{
int a = 20, b = 10, c = 30, result;

// result holds max of three


// numbers
result
= ((a > b) ? (a > c) ? a : c : (b > c) ? b : c);
System.out.println("Max of three numbers = "
+ result);
}
}

Output

Max of three numbers = 30


7. Bitwise Operators
These operators are used to perform the manipulation of individual bits of a number. They
can be used with any of the integer types. They are used when performing update and query
operations of the Binary indexed trees.
 &, Bitwise AND operator: returns bit by bit AND of input values.
 |, Bitwise OR operator: returns bit by bit OR of input values.
 ^, Bitwise XOR operator: returns bit-by-bit XOR of input values.
 ~, Bitwise Complement Operator: This is a unary operator which returns the one’s
complement representation of the input value, i.e., with all bits inverted.
Java

// Java Program to implement


// bitwise operators
import java.io.*;

// 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

// Java Program to implement


// shift operators
import java.io.*;

// Driver Class
class GFG {
// main function
public static void main(String[] args)
{
int a = 10;

// using left shift


System.out.println("a<<1 : " + (a << 1));

// using right shift


System.out.println("a>>1 : " + (a >> 1));
}
}

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:

1. Destination_datatype = (target_datatype) variable;


2. (data_type) it is known as casting operator

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. }

What is type conversion?


If a data type is automatically converted into another data type at compile time is known as
type conversion. The conversion is performed by the compiler if both data types are
compatible with each other. Remember that the destination data type should not be smaller
than the source type.

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. }

STATIC FIELDE AND METHODS:

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.*;

public class GFG {


// static variable
static int a = 40;

// instance variable
int b = 50;

void simpleDisplay()
{
System.out.println(a);
System.out.println(b);
}

// Declaration of a static method.


static void staticDisplay()
{
System.out.println(a);
}

// main method
public static void main(String[] args)
{
GFG obj = new GFG();
obj.simpleDisplay();

// Calling static method.


staticDisplay();
}
}

Output
40
50
40

Method Overloading in Java

Last Updated : 04 Oct, 2024



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.

public class Sum {


// Overloaded sum(). This sum takes two int parameters
public int sum(int x, int y) { return (x + y); }

// Overloaded sum(). This sum takes three int parameters


public int sum(int x, int y, int z)
{
return (x + y + z);
}

// Overloaded sum(). This sum takes two double


// parameters
public double sum(double x, double y)
{
return (x + y);
}

// 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

Constructor Overloading in Java


Java supports Constructor Overloading in addition to overloading methods. In Java,


overloaded constructor is called based on the parameters specified when a new is executed.

1. public class Student {


2. //instance variables of the class
3. int id;
4. String name;
5.
6. Student(){
7. System.out.println("this a default constructor");
8. }
9.
10. Student(int i, String n){
11. id = i;
12. name = n;
13. }
14.
15. public static void main(String[] args) {
16. //object creation
17. Student s = new Student();
18. System.out.println("\nDefault Constructor values: \n");
19. System.out.println("Student Id : "+s.id + "\nStudent Name : "+s.name);
20.
21. System.out.println("\nParameterized Constructor values: \n");
22. Student student = new Student(10, "David");
23. System.out.println("Student Id : "+student.id + "\nStudent Name : "+student.name);
24. }
25. }
Output:

this a default constructor

Default Constructor values:

Student Id : 0
Student Name : null

Parameterized Constructor values:

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.

It makes the code compact but complex to understand.

Recursion with infinite times:

1. public class RecursionExample1 {


2. static void p(){
3. System.out.println("hello");
4. p();
5. }
6.
7. public static void main(String[] args) {
8. p();
9. }
10. }

hello
hello
...
java.lang.StackOverflowError

Java Recursion Example 2: Finite times

1. public class RecursionExample2 {


2. static int count=0;
3. static void p(){
4. count++;
5. if(count<=5){
6. System.out.println("hello "+count);
7. p();
8. }
9. }
10. public static void main(String[] args) {
11. p();
12. }
13. }
Output:

hello 1
hello 2
hello 3
hello 4
hello 5

JAVA GARBAGE COLLECTION:

In java, garbage means unreferenced objects.

Garbage Collection is process of reclaiming the runtime unused memory automatically. In


other words, it is a way to destroy the unused objects.

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.

How to create a string object?


There are two ways to create 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");/

1. public class StringExample{


2. public static void main(String args[]){
3. String s1="java";//creating string by Java string literal
4. char ch[]={'s','t','r','i','n','g','s'};
5. String s2=new String(ch);//converting char array to string
6. String s3=new String("example");//creating Java string by new keyword
7. System.out.println(s1);
8. System.out.println(s2);
9. System.out.println(s3);
10. }}

Output:

java
strings
example

JAVA STRING CLASS METHODS:

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.

Let's use some important methods of String class.

Java String toUpperCase() and toLowerCase() method:

The Java String toUpperCase() method converts this String into uppercase letter and String
toLowerCase() method into lowercase letter.

Stringoperation1.java

1. public class Stringoperation1


2. {
3. public static void main(String ar[])
4. {
5. String s="Sachin";
6. System.out.println(s.toUpperCase());//SACHIN
7. System.out.println(s.toLowerCase());//sachin
8. System.out.println(s);//Sachin(no change in original)
9. }
10. }

Output:
SACHIN
sachin
Sachin

Java String trim() method


The String class trim() method eliminates white spaces before and after the String.

Stringoperation2.java

1. public class Stringoperation2


2. {
3. public static void main(String ar[])
4. {
5. String s=" Sachin ";
6. System.out.println(s);// Sachin
7. System.out.println(s.trim());//Sachin
8. }
9. }
Test it Now

Output:

Sachin
Sachin

Java String startsWith() and endsWith() method:

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

1. public class Stringoperation3


2. {
3. public static void main(String ar[])
4. {
5. String s="Sachin";
6. System.out.println(s.startsWith("Sa"));//true
7. System.out.println(s.endsWith("n"));//true
8. }
9. }
Test it Now

Output:
true
true

Java String charAt() Method


The String class charAt() method returns a character at specified index.

Stringoperation4.java

1. public class Stringoperation4


2. {
3. public static void main(String ar[])
4. {
5. String s="Sachin";
6. System.out.println(s.charAt(0));//S
7. System.out.println(s.charAt(3));//h
8. }
9. }
Test it Now

Output:

S
h

Java String length() Method


The String class length() method returns length of the specified String.

Stringoperation5.java

1. public class Stringoperation5


2. {
3. public static void main(String ar[])
4. {
5. String s="Sachin";
6. System.out.println(s.length());//6
7. }
8. }
Test it Now

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

1. public class Stringoperation7


2. {
3. public static void main(String ar[])
4. {
5. int a=10;
6. String s=String.valueOf(a);
7. System.out.println(s+10);
8. }
9. }
Output:

1010

Java String replace() Method


The String class replace() method replaces all occurrence of first sequence of character with
second sequence of character.

Stringoperation8.java

1. public class Stringoperation8


2. {
3. public static void main(String ar[])
4. {
5. String s1="Java is a programming language. Java is a platform. Java is an Island.";
6. String replaceString=s1.replace("Java","Kava");//replaces all occurrences of "Java" to "Kava"

7. System.out.println(replaceString);
8. }
9. }
Output:

Kava is a programming language. Kava is a platform. Kava is an Island.


METHODS IN JAVA:

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.

What is a method in Java?

A method is a block of code or collection of statements or a set of code grouped together to


perform a certain task or operation. It is used to achieve the reusability of code. We write a
method once and use it many times. We do not require to write code again and again. It also
provides the easy modification and readability of code, just by adding or removing a chunk
of code. The method is executed only when we call or invoke it.

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:

Single-word method name: sum(), area()

Multi-word method name: areaOfCircle(), stringComparision()

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

There are two types of methods in Java:

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.

Let's see an example of the predefined method.

Demo.java

1. public class Demo


2. {
3. public static void main(String[] args)
4. {
5. // using the max() method of Math class
6. System.out.print("The maximum number is: " + Math.max(9,7));
7. }
8. }
User-defined Method
The method written by the user or programmer is known as a user-defined method. These
methods are modified according to the requirement.

How to Create a User-defined Method


Let's create a user defined method that checks the number is even or odd. First, we will define
the method.

1. //user defined method


2. public static void findEvenOdd(int num)
3. {
4. //method body
5. if(num%2==0)
6. System.out.println(num+" is even");
7. else
8. System.out.println(num+" is odd");
9. }
We have defined the above method named findevenodd(). It has a parameter num of type int.
The method does not return any value that's why we have used void. The method body
contains the steps to check the number is even or odd. If the number is even, it prints the
number is even, else prints the number is odd.

How to Call or Invoke a User-defined Method


Once we have defined a method, it should be called. The calling of a method in a program is
simple. When we call or invoke a user-defined method, the program control transfer to the
called method.

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:

ExampleGet your own Java Server

Create a constructor:

// Create a Main class

public class Main {

int x; // Create a class attribute

// Create a class constructor for the Main class

public Main() {

x = 5; // Set the initial value for the class attribute x

public static void main(String[] args) {

Main myObj = new Main(); // Create an object of class Main (This will call the
constructor)

System.out.println(myObj.x); // Print the value of x

}
// 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

Constructors can also take parameters, which is used to initialize attributes.

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

public class Main {

int x;

public Main(int y) {

x = y;

public static void main(String[] args) {

Main myObj = new Main(5);

System.out.println(myObj.x);

// Outputs 5

You can have as many parameters as you want:


Example

public class Main {

int modelYear;

String modelName;

public Main(int year, String name) {

modelYear = year;

modelName = name;

public static void main(String[] args) {

Main myCar = new Main(1969, "Mustang");

System.out.println(myCar.modelYear + " " + myCar.modelName);

// Outputs 1969 Mustang

You might also like