0% found this document useful (0 votes)
5 views

Java_Unit 1

The document provides an overview of type conversion in Java, detailing widening and narrowing type casting, as well as converting strings to numeric types. It also explains constructors, including default and parameterized constructors, and introduces Java methods, their syntax, types, and advantages. Additionally, it covers method overloading and the importance of methods in improving code reusability and organization.

Uploaded by

Magesh Bala
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Java_Unit 1

The document provides an overview of type conversion in Java, detailing widening and narrowing type casting, as well as converting strings to numeric types. It also explains constructors, including default and parameterized constructors, and introduces Java methods, their syntax, types, and advantages. Additionally, it covers method overloading and the importance of methods in improving code reusability and organization.

Uploaded by

Magesh Bala
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

Java Programming

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.

Conver ng Between Numeric Types


In certain situa ons, where the data types are compa ble, Java can do type conversion automa cally. This
happens when a smaller data type, like int, is assigned to a variable of a longer data type, like long.

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.

// Explicit type cas ng


long x = 15L;
int y = 0;
y = (int)x; // y is now 15

Conver ng Strings to Numeric Types


String values are not directly compa ble with numeric values. However, Java provides Number subclasses for
the primi ve numeric types; Byte, Integer, Double, Float, Long and Short.

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

Type Cas ng in Java


Type cas ng in Java is a fundamental concept that allows developers to convert data from one data
type to another. It is essen al for handling data in various situa ons, especially when dealing with different
types of variables, expressions, and methods. In Java, type cas ng is a method or process that converts a data
type into another data type in both ways manually and automa cally. The automa c conversion is done by
the compiler and manual conversion performed by the programmer.
Types of Type Cas ng

There are two types of type cas ng:

 Widening Type Cas ng


 Narrowing Type Cas ng
Widening Type Cas ng

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

Types of Widening Type Cas ng:


The common procedure of the Widening type cas ng is about conversion from primi ve to primi ve data
types in Java.
o From byte to short, int, long, float, or double.
o From data to type int, long, float, or double.
o Char to int, long, float, or double can be converted.
o Various other types like int, long, float, or double can also be used.

Key Points to Note


o Widening typecas ng is performed automa cally by the Java compiler when conver ng from a
smaller data type to a larger data type.
o No explicit nota on, such as cas ng, is required for widening typecas ng.
o Widening conversions are always safe and do not result in any loss of data.
o Widening typecas ng is commonly used in assignments, expressions, and method invoca ons where
data of different types interact.
For example, the conversion between numeric data type to char or Boolean is not done automa cally. Also,
the char and Boolean data types are not compa ble with each other. Let's see an example.

public class WideningTypeCas ngExample


{
public sta c void main(String[] args)
{
int x = 7; //automa cally converts the integer type into long type
long y = x; //automa cally converts the long type into float type
float z = y;
System.out.println("Before conversion, int value "+x);
System.out.println("A er conversion, long value "+y);
System.out.println("A er conversion, float value "+z);
}
}
Output
Before conversion, the value is: 7
A er conversion, the long value is: 7
A er conversion, the float value is: 7.0

Narrowing Type Cas ng


Conver ng a higher data type into a lower one is called narrowing type cas ng. It is also
known as explicit conversion or cas ng up. It is done manually by the programmer. If we do not perform
cas ng, then the compiler reports a compile- me error.
1. double -> float -> long -> int -> char -> short -> byte
In the following example, we have performed the narrowing type cas ng two mes. First, we have converted
the double type into long data type a er that long data type is converted into int type.

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

Basic Java Program Examples With Outputs


Here are some basic Java program examples with outputs:
1) Hello World Program:
public class HelloWorld {
public sta c void main(String[] args) {
System.out.println(“Hello, World!”);
}
}
Output:
Hello, World!

2) Addi on of Two Numbers:


public class AddNumbers {
public sta c void main(String[] args) {
int num1 = 5, num2 = 10, sum;
sum = num1 + num2;
System.out.println(“Sum of ” + num1 + ” and ” + num2 + ” is: ” + sum);
}
}
Output:
Sum of 5 and 10 is: 15

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

Java Parameterized Constructor


A constructor which has a specific number of parameters is called a parameterized constructor.
//Java Program to demonstrate the use of the parameterized constructor.
class Student4{
int id;
String name;
//crea ng a parameterized constructor
Student4(int i,String n){
id = i;
name = n;
}
//method to display the values
void display(){System.out.println(id+" "+name);}

public sta c void main(String args[]){


//crea ng objects and passing values
Student4 s1 = new Student4(111,"Karan");
Student4 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


In Java, we can overload constructors like methods. The constructor overloading can be defined as the
concept of having more than one constructor with different parameters so that every constructor can perform
a different task.

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

Parameterized Constructor values:


Student Id : 10
Student Name : David

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) {

// Create an instance of the Method class


Method m = new Method();
m.printMessage(); // Calling the method
}
}
Output
Hello, Geeks!

Key Components of a Method Declara on

 Modifier: It specifies the


method’s access level (e.g.,
public, private, protected, or
default).
 Return Type: The type of value
returned, or void if no value is
returned.
 Method Name: It
follows Java naming
conven ons; it should start with a lowercase verb and use camel case for mul ple words.
 Parameters: A list of input values (op onal). Empty parentheses are used if no parameters are
needed.
 Excep on List: The excep ons the method might throw (op onal).
 Method Body: It contains the logic to be executed (op onal in the case of abstract methods).

Types of Methods in Java


1. Predefined Method
Predefined methods are the method that is already defined in the Java class libraries. It is also known as the
standard library method or built-in method.

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

There are two types of instance method:


o Accessor Method
o Mutator Method
Accessor Method: The method(s) that reads the instance variable(s) is known as the accessor method. We
can easily iden fy it because the method is prefixed with the word get. It is also known as ge ers. It returns
the value of the private field. It is used to get the value of the private field.

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

public class Display


{
public sta c void main(String[] args)
{
show();
}
sta c void show()
{
System.out.println("It is an example of sta c method.");
}
}
Output:
It is an example of a 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();

Example of abstract method


abstract class Demo //abstract class
{
//abstract method declara on
abstract void display();
}
public class MyClass extends Demo
{
//method impelmenta on
void display()
{
System.out.println("Abstract method?");
}
public sta c void main(String args[])
{
//crea ng object of abstract class
Demo obj = new MyClass();
//invoking abstract method
obj.display();
}
}
Output:
Abstract method...

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.

Overloading by changing the number of parameters


class MethodOverloading {
private sta c void display(int a){
System.out.println("Arguments: " + a);
}
private sta c void display(int a, int b){
System.out.println("Arguments: " + a + " and " + b);
}
public sta c void main(String[] args) {
display(1);
display(1, 4);
}
}

Output:
Arguments: 1
Arguments: 1 and 4

Method Overriding in Java


If subclass (child class) has the same method as declared in the parent class, it is known as method overriding
in Java.

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

Difference Between Constructor and Method in Java


There are many differences between constructors and methods. They are given below.

Java Constructor Java Method

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 is invoked implicitly. The method is invoked explicitly.

The Java compiler provides a default


The method is not provided by the compiler in
constructor if we do not have any constructor
any case.
in a class.

The constructor name must be same as the The method name may or may not be same as
class name. the class name.

Sta c Block in Java


When a block is decorated or associated with the word sta c, it is called a sta c block. Sta c Block is known
as the sta c clause. A sta c block can be used for the sta c ini aliza on of a class. The code that is wri en
inside the sta c block run once, when the class is ge ng loaded into the memory.

Invoking a Sta c Block


To invoke the sta c block, there is no specific way since the sta c block gets executed automa cally, whenever
in the memory the class is loaded. Observe the following illustra on.
public class Sta cBlock
{
// Constructor of the class Sta cBlock
Sta cBlock()
{
System.out.println("Inside the constructor of the class.");
}

// print method of the Sta cBlock class


public sta c void print()
{
System.out.println("Inside the print method.");
}
sta c
{
System.out.println("Inside the sta c block.");
}

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

// invoking the constructor inside the main() method


new Sta cBlock();

}
}
Output:
Inside the sta c block.
Inside the constructor of the class.
Inside the print method.
Inside the constructor of the class.

StringBuffer class in Java


StringBuffer is a class in Java that represents a mutable sequence of characters. It provides an alterna ve to
the immutable String class, allowing you to modify the contents of a string without crea ng a new object
every me.
Features of StringBuffer Class
Here are some important features and methods of the StringBuffer class:
 StringBuffer objects are mutable, meaning that you can change the contents of the buffer without
crea ng a new object.
 The ini al capacity of a StringBuffer can be specified when it is created, or it can be set later with the
ensureCapacity() method.
 The append() method is used to add characters, strings, or other objects to the end of the buffer.
 The insert() method is used to insert characters, strings, or other objects at a specified posi on in the
buffer.
 The delete() method is used to remove characters from the buffer.
 The reverse() method is used to reverse the order of the characters in the buffer.
Example:
public class StringBufferExample {
public sta c void main(String[] args){
// Crea ng StringBuffer
StringBuffer s = new StringBuffer();

// Adding elements in StringBuffer


s.append("Hello");
s.append(" ");
s.append("world");

// String with the StringBuffer value


String str = s.toString();
System.out.println(str);
}
}
Output
Hello world

Advantages of using StringBuffer in Java


There are several advantages of using StringBuffer over regular String objects in Java:
 Mutable: StringBuffer objects are mutable, which means that you can modify the contents of the
object a er it has been created. In contrast, String objects are immutable, which means that you
cannot change the contents of a String once it has been created.
 Efficient: Because StringBuffer objects are mutable, they are more efficient than crea ng new String
objects each me you need to modify a string. This is especially true if you need to modify a string
mul ple mes, as each modifica on to a String object creates a new object and discards the old one.

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.

Constructors of StringBuffer Class


Constructor Description Syntax

It reserves room for 16


StringBuffer() StringBuffer s = new StringBuffer();
characters without reallocation

It accepts an integer argument


StringBuffer s
StringBuffer(int size) that explicitly sets the size of
= new StringBuffer(20);
the buffer.

It accepts a string argument


that sets the initial contents of
StringBuffer(String the StringBuffer object and StringBuffer s
str) reserves room for 16 more = new StringBuffer(“Hello”);
characters without
reallocation.
Methods of Java StringBuffer Class
Methods Action Performed

append() Used to add text at the end of the existing text.

length() The length of a StringBuffer can be found by the length( ) method.

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.

delete() Deletes a sequence of characters from the invoking object.

deleteCharAt() Deletes the character at the index specified by the loc.

ensureCapacity() Ensures capacity is at least equal to the given minimum.

insert() Inserts text at the specified index position.

length() Returns the length of the string.

reverse() Reverse the characters within a StringBuffer object.

Replace one set of characters with another set inside a StringBuffer


replace()
object.

Examples of Java StringBuffer Method


1. append() method
The append() method concatenates the given argument with this string.
Example:
1
import java.io.*;

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[]) {

StringBuffer sb = new StringBuffer("Hello");


sb.replace(1, 3, "Java");
System.out.println(sb);
}
}
Output
HJavalo

Comparison between String and StringBuffer

You might also like