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

java lab

Uploaded by

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

java lab

Uploaded by

pamidi.prameela
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 28

Widening Type Casting

In Widening Type Casting, Java automatically converts one


data type to another data type.
Example: Converting int to double
class Main {
public static void main(String[] args) {
// create int type variable
int num = 10;
System.out.println("The integer value: " + num);

// convert into double type


double data = num;
System.out.println("The double value: " + data);
}
}
Run Code

Output

The integer value: 10


The double value: 10.0

Java Method Overloading


In this article, you’ll learn about method overloading and how
you can achieve it in Java with the help of examples.

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.

Note: The return types of the above methods are not the
same. It is because method overloading is not associated with
return types. Overloaded methods may have the same or
different return types, but they must differ in parameters.
Why method overloading?
Suppose, you have to perform the addition of given numbers
but there can be any number of arguments (let’s say either 2
or 3 arguments for simplicity).

In order to accomplish the task, you can create two


methods sum2num(int, int) and sum3num(int, int, int) for
two and three parameters respectively. However, other
programmers, as well as you in the future may get confused
as the behavior of both methods are the same but they differ
by name.
The better way to accomplish this task is by overloading
methods. And, depending upon the argument passed, one of
the overloaded methods is called. This helps to increase the
readability of the program.
How to perform method overloading in
Java?
Here are different ways to perform method overloading:

1. Overloading by changing the number of


parameters
class MethodOverloading {
private static void display(int a){
System.out.println("Arguments: " + a);
}

private static void display(int a, int b){


System.out.println("Arguments: " + a + " and " +
b);
}

public static void main(String[] args) {


display(1);
display(1, 4);
}
}

Output:

Arguments: 1
Arguments: 1 and 4
2. Method Overloading by changing the data type of
parameters
class MethodOverloading {

// this method accepts int


private static void display(int a){
System.out.println("Got Integer data.");
}

// this method accepts String object


private static void display(String a){
System.out.println("Got String object.");
}

public static void main(String[] args) {


display(1);
display("Hello");
}
}

Output:

Got Integer data.


Got String object.

Here, both overloaded methods accept one argument.


However, one accepts the argument of type int whereas
other accepts String object.
Let’s look at a real-world example:

class HelperService {

private String formatNumber(int value) {


return String.format("%d", value);
}

private String formatNumber(double value) {


return String.format("%.3f", value);
}

private String formatNumber(String value) {


return String.format("%.2f",
Double.parseDouble(value));
}

public static void main(String[] args) {


HelperService hs = new HelperService();
System.out.println(hs.formatNumber(500));
System.out.println(hs.formatNumber(89.9934));
System.out.println(hs.formatNumber("550"));
}
}

When you run the program, the output will be:


500
89.993
550.00

Constructors Overloading
in Java
Similar to Java method overloading,
we can also create two or more
constructors with different parameters.
This is called constructors overloading.
Example 6: Java Constructor
Overloading
class Main {

String language;

// constructor with no parameter


Main() {
this.language = "Java";
}

// constructor with a single


parameter
Main(String language) {
this.language = language;
}

public void getName() {


System.out.println("Programming
Langauage: " + this.language);
}

public static void main(String[]


args) {

// call constructor with no


parameter
Main obj1 = new Main();

// call constructor with a single


parameter
Main obj2 = new Main("Python");

obj1.getName();
obj2.getName();
}
}
Run Code

Output:
Programming Language: Java
Programming Language: Python

In the above example, we have two


constructors: Main() and Main(String

language) . Here, both the constructor


initialize the value of the variable
language with different values.
Based on the parameter passed during
object creation, different constructors
are called and different values are
assigned.

It is also possible to call one


constructor from another constructor.
Java this Keyword
In this article, we will learn about this keyword in Java, how and
where to use them with the help of examples.

this Keyword
In Java, this keyword is used to refer to the current object
inside a method or a constructor. For example,

class Main {
int instVar;

Main(int instVar){
this.instVar = instVar;
System.out.println("this reference = " + this);
}

public static void main(String[] args) {


Main obj = new Main(8);
System.out.println("object reference = " + obj);
}
}
Run Code

Output:

this reference = Main@23fc625e


object reference = Main@23fc625e
In the above example, we created an object named obj of the
class Main . We then print the reference to the
object obj and this keyword of the class.
Here, we can see that the reference of both obj and this is
the same. It means this is nothing but the reference to the
current object.

Use of this Keyword


There are various situations where this keyword is commonly
used.
Using this for Ambiguity Variable Names
In Java, it is not allowed to declare two or more variables
having the same name inside a scope (class scope or method
scope). However, instance variables and parameters may
have the same name. For example,

class MyClass {
// instance variable
int age;

// parameter
MyClass(int age){
age = age;
}
}

In the above program, the instance variable and the


parameter have the same name: age. Here, the Java compiler
is confused due to name ambiguity.

In such a situation, we use this keyword. For example,

First, let's see an example without using this keyword:


class Main {

int age;
Main(int age){
age = age;
}

public static void main(String[] args) {


Main obj = new Main(8);
System.out.println("obj.age = " + obj.age);
}
}
Run Code

Output:
obj.age = 0

In the above example, we have passed 8 as a value to the


constructor. However, we are getting 0 as an output. This is
because the Java compiler gets confused because of the
ambiguity in names between instance the variable and the
parameter.
Now, let's rewrite the above code using this keyword.
class Main {

int age;
Main(int age){
this.age = age;
}

public static void main(String[] args) {


Main obj = new Main(8);
System.out.println("obj.age = " + obj.age);
}
}
Run Code

Output:

obj.age = 8

Using this in Constructor Overloading


While working with constructor overloading, we might have to
invoke one constructor from another constructor. In such a
case, we cannot call the constructor explicitly. Instead, we
have to use this keyword.
Here, we use a different form of this keyword. That is, this() .

Let's take an example,


class Complex {

private int a, b;

// constructor with 2 parameters


private Complex( int i, int j ){
this.a = i;
this.b = j;
}

// constructor with single parameter


private Complex(int i){
// invokes the constructor with 2 parameters
this(i, i);
}

// constructor with no parameter


private Complex(){
// invokes the constructor with single parameter
this(0);
}

@Override
public String toString(){
return this.a + " + " + this.b + "i";
}

public static void main( String[] args ) {

// creating object of Complex class


// calls the constructor with 2 parameters
Complex c1 = new Complex(2, 3);

// calls the constructor with a single parameter


Complex c2 = new Complex(3);

// calls the constructor with no parameters


Complex c3 = new Complex();

// print objects
System.out.println(c1);
System.out.println(c2);
System.out.println(c3);
}
}
Run Code

Output:

2 + 3i
3 + 3i
0 + 0i

In the above example, we have used this keyword,


 to call the constructor Complex(int i, int j) from the
constructor Complex(int i)
 to call the constructor Complex(int i) from the
constructor Complex()

Notice the line,

System.out.println(c1);

Here, when we print the object c1 , the object is converted into


a string. In this process, the toString() is called. Since we
override the toString() method inside our class, we get the
output according to that method.
One of the huge advantages of this() is to reduce the
amount of duplicate code. However, we should be always
careful while using this() .

This is because calling constructor from another constructor


adds overhead and it is a slow process. Another huge
advantage of using this() is to reduce the amount of
duplicate code.
Narrowing Type Casting
In Narrowing Type Casting, we manually convert one data
type into another using the parenthesis.
Example: Converting double into an int
class Main {
public static void main(String[] args) {
// create double type variable
double num = 10.99;
System.out.println("The double value: " + num);

// convert into int type


int data = (int)num;
System.out.println("The integer value: " + data);
}
}
Run Code

Output

The double value: 10.99


The integer value: 10

Notice the line,

int data = (int)num;

Here, the int keyword inside the parenthesis indicates that


that the num variable is converted into the int type.
Example 1: Type conversion from int to
String
class Main {
public static void main(String[] args) {
// create int type variable
int num = 10;
System.out.println("The integer value is: " + num);

// converts int to string type


String data = String.valueOf(num);
System.out.println("The string value is: " + data);
}
}
Run Code

Output

The integer value is: 10


The string value is: 10

In the above program, notice the line

String data = String.valueOf(num);

Here, we have used the valueOf() method of the Java String


class to convert the int type variable into a string.
One-dimensional array input in Java
One-dimensional array or single dimensional array contains
only a row. We can declare single-dimensional array in the
following way:

1. datatype arrayName[] = new datatype[size];

The above statement occupies the space of the specified size


in the memory.

Where,

datatype: is the type of the elements that we want to enter


in the array, like int, float, double, etc.

arrayName: is an identifier.

new: is a keyword that creates an instance in the memory.

size: is the length of the array.

Let's create a program that takes a single-dimensional array


as input.

ArrayInputExample1.java

1. import java.util.Scanner;
2. public class ArrayInputExample1
3. {
4. public static void main(String[] args)
5. {
6. int n;
7. Scanner sc=new Scanner(System.in);
8. System.out.print("Enter the number of elements you want to
store: ");
9. //reading the number of elements from the that we want to e
nter
10. n=sc.nextInt();
11. //creates an array in the memory of length 10
12. int[] array = new int[10];
13. System.out.println("Enter the elements of the array: ");
14. for(int i=0; i<n; i++)
15. {
16. //reading array elements from the user
17. array[i]=sc.nextInt();
18. }
19. System.out.println("Array elements are: ");
20. // accessing array elements using the for loop
21. for (int i=0; i<n; i++)
22. {
23. System.out.println(array[i]);
24. }
25. }
26. }

Output:
Two-dimensional array input in Java
A two-dimensional array is an array that contains elements in
the form of rows and columns. It means we need both row
and column to populate a two-dimensional array. Matrix is
the best example of a 2D array. We can declare a two-
dimensional array by using the following statement.

1. datatype arrayName[][] = new datatype[m][n];

Where,

datatype: is the type of the elements that we want to enter


in the array, like int, float, double, etc.

arrayName: is an identifier.

new: is a keyword that creates an instance in the memory.

m: is the number of rows.

n: is the number of columns.

Let's create a Java program that takes a two-dimensional


array as input.

ArrayInputExample2.java
1. import java.util.Scanner;
2. public class ArrayInputExample2
3. {
4. public static void main(String args[])
5. {
6. int m, n, i, j;
7. Scanner sc=new Scanner(System.in);
8. System.out.print("Enter the number of rows: ");
9. //taking row as input
10. m = sc.nextInt();
11. System.out.print("Enter the number of columns: ");
12. //taking column as input
13. n = sc.nextInt();
14. // Declaring the two-dimensional matrix
15. int array[][] = new int[m][n];
16. // Read the matrix values
17. System.out.println("Enter the elements of the array: ");
18. //loop for row
19. for (i = 0; i < m; i++)
20. //inner for loop for column
21. for (j = 0; j < n; j++)
22. array[i][j] = sc.nextInt();
23. //accessing array elements
24. System.out.println("Elements of the array are: ");
25. for (i = 0; i < m; i++)
26. {
27. for (j = 0; j < n; j++)
28. //prints the array elements
29. System.out.print(array[i][j] + " ");
30. //throws the cursor to the next line
31. System.out.println();
32. }
33. }
34. }

Output:

Fibonacci Series in Java without using


recursion
Let's see the fibonacci series program in java without using
recursion.

1. class FibonacciExample1{
2. public static void main(String args[])
3. {
4. int n1=0,n2=1,n3,i,count=10;
5. System.out.print(n1+" "+n2);//printing 0 and 1
6.
7. for(i=2;i<count;++i)//loop starts from 2 because 0 and 1 are
already printed
8. {
9. n3=n1+n2;
10. System.out.print(" "+n3);
11. n1=n2;
12. n2=n3;
13. }
14.
15. }}
Test it Now

Output:
0 1 1 2 3 5 8 13 21 34
Prime Number Program in Java
Prime number in Java: Prime number is a number that is
greater than 1 and divided by 1 or itself only. In other words,
prime numbers can't be divided by other numbers than itself
or 1. For example 2, 3, 5, 7, 11, 13, 17.... are the prime
numbers.

Note: 0 and 1 are not prime numbers. The 2 is the only even prime number
because all the other even numbers can be divided by 2.

Let's see the prime number program in java. In this java


program, we will take a number variable and check whether
the number is prime or not.

1. public class PrimeExample{


2. public static void main(String args[]){
3. int i,m=0,flag=0;
4. int n=3;//it is the number to be checked
5. m=n/2;
6. if(n==0||n==1){
7. System.out.println(n+" is not prime number");
8. }else{
9. for(i=2;i<=m;i++){
10. if(n%i==0){
11. System.out.println(n+" is not prime number");
12. flag=1;
13. break;
14. }
15. }
16. if(flag==0) { System.out.println(n+" is prime number
"); }
17. }//end of else
18. }
19. }

Reverse a number using while loop


ReverseNumberExample1.java

1. public class ReverseNumberExample1


2. {
3. public static void main(String[] args)
4. {
5. int number = 987654, reverse = 0;
6. while(number != 0)
7. {
8. int remainder = number % 10;
9. reverse = reverse * 10 + remainder;
10. number = number/10;
11. }
12. System.out.println("The reverse of the given number is:
" + reverse);
13. }
14. }
Output
The reverse of the given number is: 456789

You might also like