Java_Unit 1
Java_Unit 1
Unit 1
TYPE COVERSION
Type conversion is the process of conver ng a value of one data type into another data type. There
are many situa ons where data is available in one type and the program needs to treat it as another type.
Common instances are situa ons where a mathema cal opera on needs a float value and one of the
operands needed is an integer, or when processing user input that comes in as String data and it needs to be
interpreted as some sort of number.
int x = 15;
long y = 0L;
y = x; // y is now 15L
This process is also known as widening and follows the following pa ern:
byte -> short -> int -> long -> float -> double
Any data type can be “widened” to a data type to the right on this list.
Conver ng to a smaller data type, i.e. going to the le on this list, requires explicit conversion or type cas ng.
Each of these provides a .parseXXXX() method that takes a string and provides the equivalent data type.
// Convert a string into a number using .parseXXXX()
String s = "15"; // Convert a string into an integer.
int x = Integer.parseInt(s); // x is now 15
// Convert a string into a float.
float y = Float.parseFloat(s); // y is now 15f
Conver ng a lower data type into a higher one is called widening type cas ng. It is also
known as implicit conversion or cas ng down. It is done automa cally. It is safe because there is no chance
to lose data. It takes place when:
o Both data types must be compa ble with each other.
o The target type must be larger than the source type.
1. byte -> short -> char -> int -> long -> float -> double
NarrowingTypeCas ngExample.java
public class NarrowingTypeCas ngExample
{
public sta c void main(String args[])
{
double d = 166.66; //conver ng double data type into long data type
long l = (long)d; //conver ng long data type into int data type
int i = (int)l;
System.out.println("Before conversion: "+d); //frac onal part lost
System.out.println("A er conversion into long type: "+l); //frac onal part lost
System.out.println("A er conversion into int type: "+i);
}
}
Output
Before conversion: 166.66
A er conversion into long type: 166
A er conversion into int type: 166
Constructors in Java
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 me of calling constructor, memory for the object is allocated in the memory.
It is a special type of method which is used to ini alize the object.
Every me 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.
Types of Java Constructors:
There are two types of constructors in Java:
1. Default Constructor (no-arg constructor)
2. Parameterized Constructor
Java Default Constructor
A constructor is called "Default Constructor" when it does not have any parameter.
Syntax:
1. <class_name>(){}
Example of Default Constructor
In this example, we are crea ng the no-arg constructor in the Bike class. It will be invoked at the me of object
crea on.
//Java Program to create and call a default constructor
class Bike1{
//crea ng a default constructor
Bike1()
{
System.out.println("Bike is created");
}
//main method
public sta c void main(String args[]){
//calling a default constructor
Bike1 b=new Bike1();
}
}
Output:
Bike is created
In the following Java program, in which we have used different constructors in the class.
public class Student {
//instance variables of the class
int id;
String name;
Student(){
System.out.println("this a default constructor");
}
Student(int i, String n){
id = i;
name = n;
}
public sta c void main(String[] args) {
//object crea on
Student s = new Student();
System.out.println("\nDefault Constructor values: \n");
System.out.println("Student Id : "+s.id + "\nStudent Name : "+s.name);
System.out.println("\nParameterized Constructor values: \n");
Student student = new Student(10, "David");
System.out.println("Student Id : "+student.id + "\nStudent Name : "+student.name);
}
}
Output:
this a default constructor
Default Constructor values:
Student Id : 0
Student Name : null
Java Methods
Java Methods are blocks of code that perform a specific task. A method allows us to reuse code, improving
both efficiency and organiza on. All methods in Java must belong to a class. Methods are similar to func ons
and expose the behavior of objects.
Syntax of a Method
<access_modifier><return_type><method_name>(list_of_parameters)
{
//body
}
Example:
// Crea ng a method
// that prints a message
public class Method {
// Method to print message
public void printMessage() {
System.out.println("Hello, Geeks!");
}
public sta c void main(String[] args) {
Example:
Math.random() // returns random value
Math.PI() // return pi value
2. User-defined Method
The method wri en by the user or programmer is known as a user-defined method. These methods are
modified according to the requirement.
Example:
sayHello // user define method created above in the ar cle
Greet()
setName()
3.Instance Method
The method of the class is known as an instance method. It is a non-sta c method defined in the class. Before
calling or invoking the instance method, it is necessary to create an object of its class. Let's see an example of
an instance method.
InstanceMethodExample.java
public class InstanceMethodExample
{
public sta c void main(String [] args)
{
//Crea ng an object of the class
InstanceMethodExample obj = new InstanceMethodExample();
//invoking instance method
System.out.println("The sum is: "+obj.add(12, 13));
}
int s;
//user-defined method because we have not used sta c keyword
public int add(int a, int b)
{
s = a+b;
//returning the sum
return s;
}
}
Output:
The sum is: 25
Mutator Method: The method(s) read the instance variable(s) and also modify the values. We can easily
iden fy it because the method is prefixed with the word set. It is also known as se ers or modifiers. It does
not return anything. It accepts a parameter of the same data type that depends on the field. It is used to set
the value of the private field.
4.Sta c Method
A method that has sta c keyword is known as sta c method. In other words, a method that belongs to a class
rather than an instance of a class is known as a sta c method. We can also create a sta c method by using
the keyword sta c before the method name.
Example of sta c method
5.Abstract Method
The method that does not has method body is known as abstract method. In other words, without an
implementa on is known as abstract method. It always declares in the abstract class. It means the class itself
must be abstract if it has abstract method. To create an abstract method, we use the keyword abstract.
Syntax
1. abstract void method_name();
6.Factory method
It is a method that returns an object to the class to which it belongs. All sta c methods are factory methods.
For example, NumberFormat obj = NumberFormat.getNumberInstance();
Advantages of Methods
Reusability: Methods allow us to write code once and use it many mes.
Abstrac on: Methods allow us to abstract away complex logic and provide a simple interface for
others to use.
Encapsula on: Allow to encapsulate complex logic and data
Modularity: Methods allow us to break up your code into smaller, more manageable units, improving
the modularity of your code.
Customiza on: Easy to customize for specific tasks.
Improved performance: By organizing your code into well-structured methods, you can improve
performance by reducing the amount of code.
Java Method Overloading
In Java, two or more methods may have the same name if they differ in parameters (different number of
parameters, different types of parameters, or both). These methods are called overloaded methods and this
feature is called method overloading. For example:
void func() { ... }
void func(int a) { ... }
float func(double a) { ... }
float func(int a, float b) { ... }
Here, the func() method is overloaded. These methods have the same name but accept different
arguments.
Output:
Arguments: 1
Arguments: 1 and 4
Example
class Animal {
public void move() {
System.out.println("Animals can move");
}
}
class Dog extends Animal {
public void move() {
System.out.println("Dogs can walk and run");
}
}
public class TestDog {
public sta c void main(String args[]) {
Animal a = new Animal(); // Animal reference and object
Animal b = new Dog(); // Animal reference but Dog object
a.move(); // runs the method in Animal class
b.move(); // runs the method in Dog class
}
}
Output
Animals can move
Dogs can walk and run
A constructor is used to ini alize 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 constructor name must be same as the The method name may or may not be same as
class name. the class name.
// main method
public sta c void main(String[] args)
{
// instan a ng the class Sta cBlock
Sta cBlock sbObj = new Sta cBlock();
sbObj.print(); // invoking the print() method
}
}
Output:
Inside the sta c block.
Inside the constructor of the class.
Inside the print method.
Inside the constructor of the class.
StringBuffer class is used to create mutable (modifiable) strings. The StringBuffer class in Java is the same
as the String class except it is mutable i.e. it can be changed.
capacity() the total allocated capacity can be found by the capacity( ) method.
charAt() This method returns the char value in this sequence at the specified index.
class A {
public sta c void main(String args[])
{
StringBuffer sb = new StringBuffer("Hello ");
sb.append("Java"); // now original string is changed
System.out.println(sb);
}
}
Output
Hello Java
2. insert() method
The insert() method inserts the given string with this string at the given posi on.
Example:
import java.io.*;
class A {
public sta c void main(String args[])
{
StringBuffer sb = new StringBuffer("Hello ");
sb.insert(1, "Java");
// Now original string is changed
System.out.println(sb);
}
}
Output
HJavaello
3. replace() method
The replace() method replaces the given string from the specified beginIndex and endIndex-1.
Example:
import java.io.*;
class A {
public sta c void main(String args[]) {