0% found this document useful (0 votes)
185 views50 pages

JAVA Examples

The document contains code snippets in Java for various array operations: 1) A method to find the second largest number in an integer array by sorting the array in descending order. 2) A method to find the longest palindrome number in an integer array by sorting in ascending order and checking from the last index. 3) A method to count the distinct elements in an array by checking for duplicates. 4) A method to find the repeating elements in an array by a nested loop comparison. 5) Methods to find the minimum and maximum scalar product of two integer arrays by sorting and multiplying corresponding elements.

Uploaded by

Hemant Kushwaha
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
185 views50 pages

JAVA Examples

The document contains code snippets in Java for various array operations: 1) A method to find the second largest number in an integer array by sorting the array in descending order. 2) A method to find the longest palindrome number in an integer array by sorting in ascending order and checking from the last index. 3) A method to count the distinct elements in an array by checking for duplicates. 4) A method to find the repeating elements in an array by a nested loop comparison. 5) Methods to find the minimum and maximum scalar product of two integer arrays by sorting and multiplying corresponding elements.

Uploaded by

Hemant Kushwaha
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 50

Second Greatest Number:

import java.util.Scanner;
class ArrayDemo {
public static int prep(int[] a, int total){
int temp;
for (int i = 0; i < total; i++)
{
for (int j = i + 1; j < total; j++)
{
if (a[i] > a[j])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
return a[1] ;//2nd element because index starts from 0
}
public static void main(String args[]){
int a[] = new int[200];
Scanner sc= new Scanner(System.in);
System.out.println("Enter a array Length");
int total = sc.nextInt();
System.out.println("Enter a array elements");
for(int i=0; i<total; i++)
{
a[i]= sc.nextInt();
}

System.out.println("Second smallest: "+prep(a,total));


}

}
Java program for longest palindrome in an array
import java.util.*;
public class Main
{
public static boolean isPalindrome(int n)
{
int remainder,number,reverse=0;
number=n;
//while loop for find the reverse of the number
while(n!=0)
{
remainder=n%10;
reverse=reverse*10+remainder;
n=n/10;
}
//check whether number is palindrome or not
if(number==reverse)
return true;
else
return false;
}

public static int longest(int []arr, int n)


{
int i,j,temp;
//sorting of number in ascending order
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
if(arr[i]<arr[j])
{
temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
}
//check from the last index of array that number is palindrome or not
//start from last because we want longest palindrome number that is the
reason of the sorting
for (i = n - 1; i >= 0; --i)
{
if (isPalindrome(arr[i]))
return arr[i];
}
return -1;
}
public static void main(String[] args)
{
int[] arr= new int[50];
Scanner sc=new Scanner(System.in);
System.out.println( "enter size");
int size=sc.nextInt();
System.out.println( "enter element");
for(int i=0;i<size;i++)
{
arr[i]=sc.nextInt();
}
int larger=longest(arr, size);
if(larger==-1)
System.out.println( "There is no palindrome number in the array");
else
System.out.println( "longest palindrome number in the
array"+longest(arr, size));
}
}

Java program to count distinct element in an


array
import java.util.Scanner;
class ArrayDemo {
public static int DCount(int a[],int n)
{
int res=0;

for(int i=0;i<n;i++)
{
int j;

for (j = 0; j < i; j++)

if (a[i] == a[j])
break;

if (i == j)
{
System.out.println(a[i]+ " ");
res++;
}
}

return res;
}
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
int[] a=new int[50];
System.out.println( "enter size of an array");
int size=sc.nextInt();
System.out.println( "enter elements of an array");

for(int i=0;i<size;i++)
{
a[i]=sc.nextInt();
}

System.out.println( "total distinct number of element


"+DCount(a,size));
}
}

finding repeating element in an array


import java.util.Scanner;
class ArrayDemo {
public static void Repeating(int a[],int n)
{
int count;
System.out.println("Repeating number in array" );
for(int i=0;i<n;i++)
{
count=0;
for (int j = i+1; j < n; j++)
{
if(a[i]==a[j] )
System.out.print(a[i]+" ");
}
}
}
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
int[] a=new int[50];
System.out.println("enter size of an array");
int size=sc.nextInt();
System.out.println("enter elements of an array");
for(int i=0;i<size;i++)
{
a[i]=sc.nextInt();
}
Repeating(a,size);
}
}
Java program to find non-repeating elements in
an array
import java.util.Scanner;
public class Main
{
public static void NonRepeating(int a[],int n)
{
int count;
System.out.println("Non Repeating element in array");

for(int i=0;i<n;i++)
{
count=0;
//initialise the for loop for checking the elenemnt which are not
repeated)
for (int j = 0; j < n; j++)
{
//check the condition if any number is same so
//incre
if(a[i]==a[j] && i!=j)
count++;
}
//if count became zero so print the current element
if(count==0)
System.out.print(a[i]+" ");
}
}

public static void main(String[] args)


{
Scanner sc=new Scanner(System.in);
int[] a=new int[50];
System.out.println("enter size of an array");
int size=sc.nextInt();
System.out.println("enter elements of an array");
for(int i=0;i<size;i++)
{
a[i]=sc.nextInt();
}
//call the NonRepeating function
NonRepeating(a,size);
}
}
Java program to find minimum scalar of two
vectors
import java.util.Scanner;
class ArrayDemo {
public static int MScalarProduct(int arr1[],int arr2[],int n)

{
int sum=0;

for(int i=0;i<n;i++)

{
sum=sum+arr1[i]*arr2[i];
}
return sum;
}

public static void sort(int arr1[],int arr2[],int n)

{
int temp=0;
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
if(arr1[i]<arr1[j])
{
temp=arr1[i];
arr1[i]=arr1[j];
arr1[j]=temp;
}
}
for(int j=0;j<n;j++)
{
if(arr2[i]>arr2[j])

{
temp=arr2[i];
arr2[i]=arr2[j];
arr2[j]=temp;
}
}
}
}

public static void main(String[] args)

Scanner sc=new Scanner(System.in);


int[] a1=new int[50];

int[] a2=new int[50];

System.out.println("enter size of an array");

int size=sc.nextInt();

System.out.println("enter elements of an array1");

for(int i=0;i<size;i++)

a1[i]=sc.nextInt();

System.out.println("enter elements of an array2");

for(int i=0;i<size;i++)

a2[i]=sc.nextInt();

sort(a1,a2,size);

System.out.println("the minimum scalar product of two vector is


"+MScalarProduct(a1,a2,size));

}
Java program to find maximum scalar product
of two vectors in an array
import java.util.Scanner;
class ArrayDemo {
public static int MScalarProduct(int arr1[],int arr2[],int n)

{
int sum=0;

for(int i=0;i<n;i++)

{
sum=sum+arr1[i]*arr2[i];
}
return sum;
}

static void sort_asc(int arr[], int d)


{
int i,j;
for (i = 0; i < d; ++i)
{
for (j = i + 1; j < d; ++j)
{
if (arr[i] < arr[j])
{
int a = arr[i];
arr[i] = arr[j];
arr[j] = a;

}
}
}

public static void main(String[] args)


{
int m;
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number of elements of the
array : ");
m = sc.nextInt();
int[] arr1 = new int[m];
int[] arr2 = new int[m];
System.out.print("Input the element of array 1 :");
int i;
for(i = 0; i < m ; i++)
{
arr1[i] = sc.nextInt();
}
System.out.print("Input the element of array 2 :");
for(i = 0; i < m ; i++)
{
arr2[i] = sc.nextInt();
}
sort_asc(arr1, m);
sort_asc(arr2,m);

System.out.println("Maximum product");
System.out.println( MScalarProduct(arr1,arr2,m));
}
}

Java program to find all symmetric elements in


an array(HashMap)
// A Java program to find all symmetric pairs in a given array of pairs
import java.util.HashMap;
   
class SymmetricPairs {
   
    // Print all pairs that have a symmetric counterpart
    static void findSymPairs(int arr[][])
    {
        // Creates an empty hashMap hM
        HashMap<Integer, Integer> hM = new HashMap<Integer, Integer>();
   
        // Traverse through the given array
        for (int i = 0; i < arr.length; i++)
        {
            // First and second elements of current pair
            int first = arr[i][0];
            int sec   = arr[i][1];
              
            // Look for second element of this pair in hash
            Integer val = hM.get(sec);
   
            // If found and value in hash matches with first
            // element of this pair, we found symmetry
            if (val != null && val == first)
               System.out.println("(" + sec + ", " + first + ")");
                 
            else  // Else put sec element of this pair in hash
               hM.put(first, sec);
        }
    }
   
    // Driver method
    public static void main(String arg[])
    {
        int arr[][] = new int[5][2];
        arr[0][0] = 11; arr[0][1] = 20;
        arr[1][0] = 30; arr[1][1] = 40;
        arr[2][0] = 5;  arr[2][1] = 10;
        arr[3][0] = 40;  arr[3][1] = 30;
        arr[4][0] = 10;  arr[4][1] = 5;
        findSymPairs(arr);
    }
}

Problem Statement

We want to estimate the cost of painting a property. Interior wall painting cost is


Rs.18 per sq.ft. and exterior wall painting cost is Rs.12 per sq.ft.

Take input as
1. Number of Interior walls
2. Number of Exterior walls
3. Surface Area of each Interior 4. Wall in units of square feet
Surface Area of each Exterior Wall in units of square feet

If a user enters zero  as the number of walls then skip Surface area values as
User may don’t  want to paint that wall.

Calculate and display the total cost of painting the property


Example 1:

6
3
12.3
15.2
12.3
15.2
12.3
15.2
10.10
10.10
10.00
Total estimated Cost : 1847.4 INR

Note: Follow in input and output format as given in above example

import java.util.Scanner;
class Main {
    public static void main(String[] args) {
       int ni, ne, i = 0;
       float intP = 18, extP = 12, cost = 0, temp;
       Scanner sc = new Scanner(System.in);
       ni = sc.nextInt();
       ne = sc.nextInt();
       if(ni < 0 || ne < 0) {
           System.out.print("INVALID INPUT");
       } else if(ni == 0 && ne == 0) {
           System.out.print("Total estimated Cost : 0.0");
       } else {
           for(i = 0; i < ni; i++) {
               temp = sc.nextFloat();
               cost += intP * temp;
           }
           for(i = 0; i < ne; i++) {
               temp = sc.nextFloat();
               cost += extP * temp;
           }
           System.out.printf("Total estimated Cost : %.1f", cost);
       }
    }
}
Constructor Examples

class Example2
{
private int var;
//default constructor
public Example2()
{
this.var = 10;
}
//parameterized constructor
public Example2(int num)
{
this.var = num;
}
public int getValue()
{
return var;
}
public static void main(String args[])
{
Example2 obj = new Example2();
Example2 obj2 = new Example2(100);
System.out.println("var is: "+obj.getValue());
System.out.println("var is: "+obj2.getValue());
}
}

public class Employee {

int empId;
String empName;

//parameterized constructor with two parameters


Employee(int id, String name){
this.empId = id;
this.empName = name;
}
void info(){
System.out.println("Id: "+empId+" Name: "+empName);
}

public static void main(String args[]){


Employee obj1 = new Employee(10245,"Chaitanya");
Employee obj2 = new Employee(92232,"Negan");
obj1.info();
obj2.info();
}
}

class MyParentClass {
MyParentClass(){
System.out.println("MyParentClass Constructor");
}
}
class MyChildClass extends MyParentClass{
MyChildClass() {
System.out.println("MyChildClass Constructor");
}
public static void main(String args[]) {
new MyChildClass();
}
}

Static Keyword Examples


class SimpleStaticExample
{
// This is a static method
static void myMethod()
{
System.out.println("myMethod");
}

public static void main(String[] args)


{
/* You can see that we are calling this
* method without creating any object.
*/
myMethod();
}
}

Example 1: Single static block


As you can see that both the static variables were intialized before we accessed
them in the main method.
class JavaExample{
static int num;
static String mystr;
static{
num = 97;
mystr = "Static keyword in Java";
}
public static void main(String args[])
{
System.out.println("Value of num: "+num);
System.out.println("Value of mystr: "+mystr);
}
}

Example 2: Static variables are shared among all the instances of class
In this example, String variable is non-static and integer variable is Static. As you
can see in the output that the non-static variable is different for both the objects
but the static variable is shared among them, thats the reason the changes made
to the static variable by object ob2 reflects in both the objects.

class JavaExample{
//Static integer variable
static int var1=77;
//non-static string variable
String var2;

public static void main(String args[])


{
JavaExample ob1 = new JavaExample();
JavaExample ob2 = new JavaExample();
/* static variables can be accessed directly without
* any instances. Just to demonstrate that static variables
* are shared, I am accessing them using objects so that
* we can check that the changes made to static variables
* by one object, reflects when we access them using other
* objects
*/
//Assigning the value to static variable using object ob1
ob1.var1=88;
ob1.var2="I'm Object1";
/* This will overwrite the value of var1 because var1 has a
single
* copy shared among both the objects.
*/
ob2.var1=99;
ob2.var2="I'm Object2";
System.out.println("ob1 integer:"+ob1.var1);
System.out.println("ob1 String:"+ob1.var2);
System.out.println("ob2 integer:"+ob2.var1);
System.out.println("ob2 STring:"+ob2.var2);
}
}
Output:

ob1 integer:99
ob1 String:I'm Object1
ob2 integer:99
ob2 STring:I'm Object2

Inheritance Example
class Teacher {
String designation = "Teacher";
String collegeName = "Beginnersbook";
void does(){
System.out.println("Teaching");
}
}

public class PhysicsTeacher extends Teacher{


String mainSubject = "Physics";
public static void main(String args[]){
PhysicsTeacher obj = new PhysicsTeacher();
System.out.println(obj.collegeName);
System.out.println(obj.designation);
System.out.println(obj.mainSubject);
obj.does();
}
}
Output:

Beginnersbook
Teacher
Physics
Teaching
Inheritance and Method Overriding
When we declare the same method in child class which is already present in the
parent class the this is called method overriding. In this case when we call the
method from child class object, the child class version of the method is called.
However we can call the parent class method using super keyword as I have
shown in the example below:

class ParentClass{
//Parent class constructor
ParentClass(){
System.out.println("Constructor of Parent");
}
void disp(){
System.out.println("Parent Method");
}
}
class JavaExample extends ParentClass{
JavaExample(){
System.out.println("Constructor of Child");
}
void disp(){
System.out.println("Child Method");
//Calling the disp() method of parent class
super.disp();
}
public static void main(String args[]){
//Creating the object of child class
JavaExample obj = new JavaExample();
obj.disp();
}
}
The output is :

Constructor of Parent
Constructor of Child
Child Method
Parent Method

Aggregation Example in Java

For example consider two classes Student class and Address class. Every


student has an address so the relationship between student and address is a
Has-A relationship. But if you consider its vice versa then it would not make any
sense as an Address doesn’t need to have a Student necessarily. Lets write this
example in a java program.
Student Has-A Address

class Address
{
int streetNum;
String city;
String state;
String country;
Address(int street, String c, String st, String coun)
{
this.streetNum=street;
this.city =c;
this.state = st;
this.country = coun;
}
}
class StudentClass
{
int rollNum;
String studentName;
//Creating HAS-A relationship with Address class
Address studentAddr;
StudentClass(int roll, String name, Address addr){
this.rollNum=roll;
this.studentName=name;
this.studentAddr = addr;
}
public static void main(String args[]){
Address ad = new Address(55, "Agra", "UP", "India");
StudentClass obj = new StudentClass(123, "Chaitanya", ad);
System.out.println(obj.rollNum);
System.out.println(obj.studentName);
System.out.println(obj.studentAddr.streetNum);
System.out.println(obj.studentAddr.city);
System.out.println(obj.studentAddr.state);
System.out.println(obj.studentAddr.country);
}
}
Output:

123
Chaitanya
55
Agra
UP
India
Why we need Aggregation?
To maintain code re-usability. To understand this lets take the same example
again. Suppose there are two other classes College and Staff along with above
two classes Student and Address. In order to maintain Student’s address,
College Address and Staff’s address we don’t need to use the same code again
and again. We just have to use the reference of Address class while defining
each of these classes like:

Student Has-A Address (Has-a relationship between student and


address)
College Has-A Address (Has-a relationship between college and
address)
Staff Has-A Address (Has-a relationship between staff and address)
Hence we can improve code re-usability by using Aggregation relationship.

So if I have to write this in a program, I would do it like this:

class Address
{
int streetNum;
String city;
String state;
String country;
Address(int street, String c, String st, String coun)
{
this.streetNum=street;
this.city =c;
this.state = st;
this.country = coun;
}
}
class StudentClass
{
int rollNum;
String studentName;
//Creating HAS-A relationship with Address class
Address studentAddr;
StudentClass(int roll, String name, Address addr){
this.rollNum=roll;
this.studentName=name;
this.studentAddr = addr;
}
...
}
class College
{
String collegeName;
//Creating HAS-A relationship with Address class
Address collegeAddr;
College(String name, Address addr){
this.collegeName = name;
this.collegeAddr = addr;
}
...
}
class Staff
{
String employeeName;
//Creating HAS-A relationship with Address class
Address employeeAddr;
Staff(String name, Address addr){
this.employeeName = name;
this.employeeAddr = addr;
}
...
}

Super Keyword
Accessing the num variable of parent class:
By calling a variable like this, we can access the variable of parent class if both
the classes (parent and child) have same variable.

super.variable_name
Let’s take the same example that we have seen above, this time in print
statement we are passing super.num instead of num.

class Superclass
{
int num = 100;
}
class Subclass extends Superclass
{
int num = 110;
void printNumber(){
/* Note that instead of writing num we are
* writing super.num in the print statement
* this refers to the num variable of Superclass
*/
System.out.println(super.num);
}
public static void main(String args[]){
Subclass obj= new Subclass();
obj.printNumber();
}
}
Output:
100

Example 1: Overloading – Different Number of parameters in argument list

This example shows how method overloading is done by having different number
of parameters

class DisplayOverloading
{
public void disp(char c)
{
System.out.println(c);
}
public void disp(char c, int num)
{
System.out.println(c + " "+num);
}
}
class Sample
{
public static void main(String args[])
{
DisplayOverloading obj = new DisplayOverloading();
obj.disp('a');
obj.disp('a',10);
}
}
Output:

a
Method Overriding and Dynamic Method
Dispatch
Method Overriding is an example of runtime polymorphism. When a parent class
reference points to the child class object then the call to the overridden method
is determined at runtime, because during method call which method(parent class
or child class) is to be executed is determined by the type of object. This process
in which call to the overridden method is resolved at runtime is known as
dynamic method dispatch. Lets see an example to understand this:

class ABC{
//Overridden method
public void disp()
{
System.out.println("disp() method of parent class");
}
}
class Demo extends ABC{
//Overriding method
public void disp(){
System.out.println("disp() method of Child class");
}
public void newMethod(){
System.out.println("new method of child class");
}
public static void main( String args[]) {
/* When Parent class reference refers to the parent class
object
* then in this case overridden method (the method of parent
class)
* is called.
*/
ABC obj = new ABC();
obj.disp();

/* When parent class reference refers to the child class


object
* then the overriding method (method of child class) is
called.
* This is called dynamic method dispatch and runtime
polymorphism
*/
ABC obj2 = new Demo();
obj2.disp();
}
}
Output:

disp() method of parent class


disp() method of Child class

Few more overriding examples:

ABC obj = new ABC();


obj.myMethod();
// This would call the myMethod() of parent class ABC

XYZ obj = new XYZ();


obj.myMethod();
// This would call the myMethod() of child class XYZ

ABC obj = new XYZ();


obj.myMethod();
// This would call the myMethod() of child class XYZ
.
Static binding example
Here we have two classes Human and Boy. Both the classes have same method
walk() but the method is static, which means it cannot be overriden so even
though I have used the object of Boy class while creating object obj, the parent
class method is called by it. Because the reference is of Human type (parent
class). So whenever a binding of static, private and final methods happen, type of
the class is determined by the compiler at compile time and the binding happens
then and there.

class Human{
public static void walk()
{
System.out.println("Human walks");
}
}
class Boy extends Human{
public static void walk(){
System.out.println("Boy walks");
}
public static void main( String args[]) {
/* Reference is of Human type and object is
* Boy type
*/
Human obj = new Boy();
/* Reference is of HUman type and object is
* of Human type.
*/
Human obj2 = new Human();
obj.walk();
obj2.walk();
}
}
Output:

Human walks
Human walks

Dynamic binding example


This is the same example that we have seen above. The only difference here is
that in this example, overriding is actually happening since these methods
are not static, private and final. In case of overriding the call to the overriden
method is determined at runtime by the type of object thus late binding happens.
Lets see an example to understand this:

class Human{
//Overridden Method
public void walk()
{
System.out.println("Human walks");
}
}
class Demo extends Human{
//Overriding Method
public void walk(){
System.out.println("Boy walks");
}
public static void main( String args[]) {
/* Reference is of Human type and object is
* Boy type
*/
Human obj = new Demo();
/* Reference is of HUman type and object is
* of Human type.
*/
Human obj2 = new Human();
obj.walk();
obj2.walk();
}
}
Output:

Boy walks
Human walks

Abstract class Example


//abstract parent class
abstract class Animal{
//abstract method
public abstract void sound();
}
//Dog class extends Animal class
public class Dog extends Animal{

public void sound(){


System.out.println("Woof");
}
public static void main(String args[]){
Animal obj = new Dog();
obj.sound();
}
}
Output:

Woof

Example of an Interface in Java

This is how a class implements an interface. It has to provide the body of all the
methods that are declared in interface or in other words you can say that class
has to implement all the methods of interface.

Do you know? class implements interface but an interface extends another


interface.

interface MyInterface
{
/* compiler will treat them as:
* public abstract void method1();
* public abstract void method2();
*/
public void method1();
public void method2();
}
class Demo implements MyInterface
{
/* This class must have to implement both the abstract methods
* else you will get compilation error
*/
public void method1()
{
System.out.println("implementation of method1");
}
public void method2()
{
System.out.println("implementation of method2");
}
public static void main(String arg[])
{
MyInterface obj = new Demo();
obj.method1();
}
}
Output:

implementation of method1

Example of Encapsulation in Java

How to implement encapsulation in java:


1) Make the instance variables private so that they cannot be accessed directly
from outside the class. You can only set and get values of these variables
through the methods of the class.
2) Have getter and setter methods in the class to set and get the values of the
fields.

class EncapsulationDemo{
private int ssn;
private String empName;
private int empAge;
//Getter and Setter methods
public int getEmpSSN(){
return ssn;
}

public String getEmpName(){


return empName;
}

public int getEmpAge(){


return empAge;
}

public void setEmpAge(int newValue){


empAge = newValue;
}

public void setEmpName(String newValue){


empName = newValue;
}

public void setEmpSSN(int newValue){


ssn = newValue;
}
}
public class EncapsTest{
public static void main(String args[]){
EncapsulationDemo obj = new EncapsulationDemo();
obj.setEmpName("Mario");
obj.setEmpAge(32);
obj.setEmpSSN(112233);
System.out.println("Employee Name: " + obj.getEmpName());
System.out.println("Employee SSN: " + obj.getEmpSSN());
System.out.println("Employee Age: " + obj.getEmpAge());
}
}
Output:

Employee Name: Mario


Employee SSN: 112233
Employee Age: 32

Example 1: Java packages


I have created a class Calculator inside a package name letmecalculate. To
create a class inside a package, declare the package name in the first statement
in your program. A class can have only one package declaration.
Calculator.java file created inside a package letmecalculate

package letmecalculate;

public class Calculator {


public int add(int a, int b){
return a+b;
}
public static void main(String args[]){
Calculator obj = new Calculator();
System.out.println(obj.add(10, 20));
}
}
Now lets see how to use this package in another program.

import letmecalculate.Calculator;
public class Demo{
public static void main(String args[]){
Calculator obj = new Calculator();
System.out.println(obj.add(100, 200));
}
}

Garbage Collection Example in Java

In this example we are demonstrating the garbage collection by calling


System.gc(). In this code we have overridden a finalize() method. This method is
invoked just before a object is destroyed by java garbage collection process. This
is the reason you would see in the output that this method has been invoked
twice.

public class JavaExample{


public static void main(String args[]){
/* Here we are intentionally assigning a null
* value to a reference so that the object becomes
* non reachable
*/
JavaExample obj=new JavaExample();
obj=null;

/* Here we are intentionally assigning reference a


* to the another reference b to make the object referenced
* by b unusable.
*/
JavaExample a = new JavaExample();
JavaExample b = new JavaExample();
b = a;
System.gc();
}
protected void finalize() throws Throwable
{
System.out.println("Garbage collection is performed by
JVM");
}
}
Output:

Garbage collection is performed by JVM


Garbage collection is performed by JVM

Whats the use of blank final variable?


Lets say we have a Student class which is having a field called Roll No. Since Roll
No should not be changed once the student is registered, we can declare it as a
final variable in a class but we cannot initialize roll no in advance for all the
students(otherwise all students would be having same roll no). In such case we
can declare roll no variable as blank final and we initialize this value during object
creation like this:

class StudentData{
//Blank final variable
final int ROLL_NO;

StudentData(int rnum){
//It must be initialized in constructor
ROLL_NO=rnum;
}
void myMethod(){
System.out.println("Roll no is:"+ROLL_NO);
}
public static void main(String args[]){
StudentData obj=new StudentData(1234);
obj.myMethod();
}
}
Output:

Roll no is:1234

Example: try catch block


If an exception occurs in try block then the control of execution is passed to the
corresponding catch block. A single try block can have multiple catch blocks
associated with it, you should place the catch blocks in such a way that the
generic exception handler catch block is at the last(see in the example below).
The generic exception handler can handle all the exceptions but you should place
is at the end, if you place it at the before all the catch blocks then it will display
the generic message. You always want to give the user a meaningful message
for each type of exception rather then a generic message.

class Example1 {
public static void main(String args[]) {
int num1, num2;
try {
  /* We suspect that this block of statement can throw
* exception so we handled it by placing these statements
* inside try and handled the exception in catch block
*/
num1 = 0;
num2 = 62 / num1;
System.out.println(num2);
System.out.println("Hey I'm at the end of try block");
}
  catch (ArithmeticException e) { 
/* This block will only execute if any Arithmetic
exception
* occurs in try block
*/
System.out.println("You should not divide a number by
zero");
}
catch (Exception e) {
/* This is a generic Exception handler which means it can
handle
* all the exceptions. This will execute if the exception
is not
* handled by previous catch blocks.
*/
System.out.println("Exception occurred");
}
System.out.println("I'm out of try-catch block in Java.");
}
}
Output:

You should not divide a number by zero


I'm out of try-catch block in Java.

Catching multiple exceptions


Lets take an example to understand how to handle multiple exceptions.

class Example{
public static void main(String args[]){
try{
int arr[]=new int[7];
arr[4]=30/0;
System.out.println("Last Statement of try block");
}
catch(ArithmeticException e){
System.out.println("You should not divide a number by
zero");
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("Accessing array elements outside of
the limit");
}
catch(Exception e){
System.out.println("Some Other Exception");
}
System.out.println("Out of the try-catch block");
}
}
Output:

You should not divide a number by zero


Out of the try-catch block
In the above example, the first catch block got executed because the code we
have written in try block throws ArithmeticException (because we divided the
number by zero).
Catching multiple exceptions
Lets take an example to understand how to handle multiple exceptions.

class Example{
public static void main(String args[]){
try{
int arr[]=new int[7];
arr[4]=30/0;
System.out.println("Last Statement of try block");
}
catch(ArithmeticException e){
System.out.println("You should not divide a number by
zero");
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("Accessing array elements outside of
the limit");
}
catch(Exception e){
System.out.println("Some Other Exception");
}
System.out.println("Out of the try-catch block");
}
}
Output:

You should not divide a number by zero


Out of the try-catch block
In the above example, the first catch block got executed because the code we
have written in try block throws ArithmeticException (because we divided the
number by zero).

A Simple Example of finally block


Here you can see that the exception occurred in try block which has been
handled in catch block, after that finally block got executed.

class Example
{
public static void main(String args[]) {
try{
int num=121/0;
System.out.println(num);
}
catch(ArithmeticException e){
System.out.println("Number should not be divided by
zero");
}
/* Finally block will always execute
* even if there is no exception in try block
*/
finally{
System.out.println("This is finally block");
}
System.out.println("Out of try-catch-finally");
}
}
Output:

Number should not be divided by zero


This is finally block
Out of try-catch-finally

Example of throw keyword


Lets say we have a requirement where we we need to only register the students
when their age is less than 12 and weight is less than 40, if any of the condition is
not met then the user should get an ArithmeticException with the warning
message “Student is not eligible for registration”. We have implemented the logic
by placing the code in the method that checks student eligibility if the entered
student age and weight doesn’t met the criteria then we throw the exception
using throw keyword.

/* In this program we are checking the Student age


* if the student age<12 and weight <40 then our program
* should return that the student is not eligible for registration.
*/
public class ThrowExample {
static void checkEligibilty(int stuage, int stuweight){
if(stuage<12 && stuweight<40) {
throw new ArithmeticException("Student is not eligible for
registration");
}
else {
System.out.println("Student Entry is Valid!!");
}
}

public static void main(String args[]){


System.out.println("Welcome to the Registration process!!");
checkEligibilty(10, 39);
System.out.println("Have a nice day..");
}
}
Output:

Welcome to the Registration process!!Exception in thread "main"


java.lang.ArithmeticException: Student is not eligible for
registration
at
beginnersbook.com.ThrowExample.checkEligibilty(ThrowExample.java:9)
at beginnersbook.com.ThrowExample.main(ThrowExample.java:18)

ArrayList
import java.util.*;

public class JavaExample {


public static void main(String args[]) {
/* Creating ArrayList of type "String" which means
* we can only add "String" elements
*/
ArrayList<String> obj = new ArrayList<String>();

/*This is how we add elements to an ArrayList*/


obj.add("Ajeet");
obj.add("Harry");
obj.add("Chaitanya");
obj.add("Steve");
obj.add("Anuj");

// Displaying elements
System.out.println("Original ArrayList:");
for(String str:obj)
System.out.println(str);

/* Add element at the given index


* obj.add(0, "Rahul") - Adding element "Rahul" at first
position
* obj.add(1, "Justin") - Adding element "Justin" at second
position
*/
obj.add(0, "Rahul");
obj.add(1, "Justin");

// Displaying elements
System.out.println("ArrayList after add operation:");
for(String str:obj)
System.out.println(str);

//Remove elements from ArrayList like this


obj.remove("Chaitanya"); //Removes "Chaitanya" from ArrayList
obj.remove("Harry"); //Removes "Harry" from ArrayList

// Displaying elements
System.out.println("ArrayList after remove operation:");
for(String str:obj)
System.out.println(str);

//Remove element from the specified index


obj.remove(1); //Removes Second element from the List

// Displaying elements
System.out.println("Final ArrayList:");
for(String str:obj)
System.out.println(str);
}
}

Output:
Original ArrayList:
Ajeet
Harry
Chaitanya
Steve
Anuj
ArrayList after add operation:
Rahul
Justin
Ajeet
Harry
Chaitanya
Steve
Anuj
ArrayList after remove operation:
Rahul
Justin
Ajeet
Steve
Anuj
Final ArrayList:
Rahul
Ajeet
Steve
Anuj
Java example of removing elements from
the LinkedList
In the following example we are checking out the few popular remove methods in
the LinkedList that are used to remove elements from certain positions in the
LinkedList. Detailed explanation of these methods along with examples are
covered in the separate tutorials, links are provided at the end of this article.

package com.beginnersbook;
import java.util.*;
public class JavaExample{
public static void main(String args[]){

LinkedList<String> list=new LinkedList<String>();

//Adding elements to the Linked list


list.add("Steve");
list.add("Carl");
list.add("Raj");
list.add("Negan");
list.add("Rick");

//Removing First element


//Same as list.remove(0);
list.removeFirst();

//Removing Last element


list.removeLast();

//Iterating LinkedList
Iterator<String> iterator=list.iterator();
while(iterator.hasNext()){
System.out.print(iterator.next()+" ");
}

//removing 2nd element, index starts with 0


list.remove(1);

System.out.print("\nAfter removing second element: ");


//Iterating LinkedList again
Iterator<String> iterator2=list.iterator();
while(iterator2.hasNext()){
System.out.print(iterator2.next()+" ");
}
}
}
Output:

HashMap Example in Java:


In this example we have demonstrated almost all the important methods of
HashMap class.

import java.util.HashMap;
import java.util.Map;
import java.util.Iterator;
import java.util.Set;
public class Details {

public static void main(String args[]) {

/* This is how to declare HashMap */


HashMap<Integer, String> hmap = new HashMap<Integer,
String>();

/*Adding elements to HashMap*/


hmap.put(12, "Chaitanya");
hmap.put(2, "Rahul");
hmap.put(7, "Singh");
hmap.put(49, "Ajeet");
hmap.put(3, "Anuj");

/* Display content using Iterator*/


Set set = hmap.entrySet();
Iterator iterator = set.iterator();
while(iterator.hasNext()) {
Map.Entry mentry = (Map.Entry)iterator.next();
System.out.print("key is: "+ mentry.getKey() + " & Value
is: ");
System.out.println(mentry.getValue());
}

/* Get values based on key*/


String var= hmap.get(2);
System.out.println("Value at index 2 is: "+var);

/* Remove values based on key*/


hmap.remove(3);
System.out.println("Map key and values after removal:");
Set set2 = hmap.entrySet();
Iterator iterator2 = set2.iterator();
while(iterator2.hasNext()) {
Map.Entry mentry2 = (Map.Entry)iterator2.next();
System.out.print("Key is: "+mentry2.getKey() + " & Value
is: ");
System.out.println(mentry2.getValue());
}

}
}
Output:

key is: 49 & Value is: Ajeet


key is: 2 & Value is: Rahul
key is: 3 & Value is: Anuj
key is: 7 & Value is: Singh
key is: 12 & Value is: Chaitanya
Value at index 2 is: Rahul
Map key and values after removal:
Key is: 49 & Value is: Ajeet
Key is: 2 & Value is: Rahul
Key is: 7 & Value is: Singh
Key is: 12 & Value is: Chaitanya

Java Queue Example


import java.util.*;
public class QueueExample1 {

public static void main(String[] args) {

/*
* We cannot create instance of a Queue as it is an
* interface, we can create instance of LinkedList or
* PriorityQueue and assign it to Queue
*/
Queue<String> q = new LinkedList<String>();

//Adding elements to the Queue


q.add("Rick");
q.add("Maggie");
q.add("Glenn");
q.add("Negan");
q.add("Daryl");

System.out.println("Elements in Queue:"+q);

/*
* We can remove element from Queue using remove() method,
* this would remove the first element from the Queue
*/
System.out.println("Removed element: "+q.remove());

/*
* element() method - this returns the head of the
* Queue. Head is the first element of Queue
*/
System.out.println("Head: "+q.element());

/*
* poll() method - this removes and returns the
* head of the Queue. Returns null if the Queue is empty
*/
System.out.println("poll(): "+q.poll());

/*
* peek() method - it works same as element() method,
* however it returns null if the Queue is empty
*/
System.out.println("peek(): "+q.peek());

//Again displaying the elements of Queue


System.out.println("Elements in Queue:"+q);
}
}
Output:

Elements in Queue:[Rick, Maggie, Glenn, Negan, Daryl]


Removed element: Rick
Head: Maggie
poll(): Maggie
peek(): Glenn
Elements in Queue:[Glenn, Negan, Daryl]

Java Deque Interface Example


import java.util.Deque;
import java.util.ArrayDeque;
public class ArrayDequeExample {

public static void main(String[] args) {

/*
* We cannot create instance of a Deque as it is an
* interface, we can create instance of ArrayDeque or
* LinkedList and assign it to Deque
*/
Deque<String> dq = new ArrayDeque<String>();

/*
* Adding elements to the Deque.
* addFirst() adds element at the beginning
* and addLast() method adds at the end.
*/
dq.add("Glenn");
dq.add("Negan");
dq.addLast("Maggie");
dq.addFirst("Rick");
dq.add("Daryl");

System.out.println("Elements in Deque:"+dq);

/*
* We can remove element from Deque using remove() method,
* we can use normal remove() method which removes first
* element or we can use removeFirst() and removeLast()
* methods to remove first and last element respectively.
*/
System.out.println("Removed element: "+dq.removeLast());

/*
* element() method - returns the head of the
* Deque. Head is the first element of Deque
*/
System.out.println("Head: "+dq.element());

/*
* pollLast() method - this method removes and returns the
* tail of the Deque(last element). Returns null if the Deque
is empty.
* We can also use poll() or pollFirst() to remove the first
element of
* Deque.
*/
System.out.println("poll(): "+dq.pollLast());

/*
* peek() method - it works same as element() method,
* however it returns null if the Deque is empty. We can also
use
* peekFirst() and peekLast() to retrieve first and last
element
*/
System.out.println("peek(): "+dq.peek());

//Again printing the elements of Deque


System.out.println("Elements in Deque:"+dq);
}
}
Output:

Elements in Deque:[Rick, Glenn, Negan, Maggie, Daryl]


Removed element: Daryl
Head: Rick
poll(): Maggie
peek(): Rick
Elements in Deque:[Rick, Glenn, Negan]

Iterator without Generics Example


Generics got introduced in Java 5. Before that there were no concept of
Generics.

import java.util.ArrayList;
import java.util.Iterator;

public class IteratorDemo1 {

public static void main(String args[]){


ArrayList names = new ArrayList();
names.add("Chaitanya");
names.add("Steve");
names.add("Jack");

Iterator it = names.iterator();

while(it.hasNext()) {
String obj = (String)it.next();
System.out.println(obj);
}
}

}
Output:

Chaitanya
Steve
Jack

ListIterator Example
In this example we are traversing an ArrayList in both the directions.

import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;

public class ListIteratorExample {


public static void main(String a[]){
ListIterator<String> litr = null;
List<String> names = new ArrayList<String>();
names.add("Shyam");
names.add("Rajat");
names.add("Paul");
names.add("Tom");
names.add("Kate");
//Obtaining list iterator
litr=names.listIterator();

System.out.println("Traversing the list in forward


direction:");
while(litr.hasNext()){
System.out.println(litr.next());
}
System.out.println("\nTraversing the list in backward
direction:");
while(litr.hasPrevious()){
System.out.println(litr.previous());
}
}
}
Output:

Traversing the list in forward direction:


Shyam
Rajat
Paul
Tom
Kate

Traversing the list in backward direction:


Kate
Tom
Paul
Rajat
Shyam

Example: Sorting arrays and Wrapper class


import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class Demo {


public static void main(String[] args) {
/*
* Integer class implements Comparable
* Interface so we can use the sort method
*/
int[] arr = {11,55,22,0,89};
Arrays.sort(arr);
System.out.print("Sorted Int Array: ");
System.out.println(Arrays.toString(arr));

/*
* String class implements Comparable
* Interface so we can use the sort method
*/
System.out.print("Sorted String Array: ");
String[] names = {"Steve", "Ajeet", "Kyle"};
Arrays.sort(names);
System.out.println(Arrays.toString(names));

/*
* String class implements Comparable
* Interface so we can use the sort method
*/
System.out.print("Sorted List: ");
List fruits = new ArrayList();
fruits.add("Orange");
fruits.add("Banana");
fruits.add("Apple");
fruits.add("Guava");
fruits.add("Grapes");
Collections.sort(fruits);
for(String s: fruits) System.out.print(s+", ");
}
}
Output:

Sorted Int Array: [0, 11, 22, 55, 89]


Sorted String Array: [Ajeet, Kyle, Steve]
Sorted List: Apple, Banana, Grapes, Guava, Orange,
Enum Example
This is just an example to demonstrate the use enums. If you understand the
core part and basics, you would be able to write your own logic based on the
requirement.

public enum Directions{


EAST,
WEST,
NORTH,
SOUTH
}
public class EnumDemo
{
public static void main(String args[]){
Directions dir = Directions.NORTH;
if(dir == Directions.EAST) {
System.out.println("Direction: East");
} else if(dir == Directions.WEST) {
System.out.println("Direction: West");
} else if(dir == Directions.NORTH) {
System.out.println("Direction: North");
} else {
System.out.println("Direction: South");
}
}
}
Output:

Direction: North

Multiplethreading
Method 1: Thread creation by extending Thread class
Example 1:

class MultithreadingDemo extends Thread{


public void run(){
System.out.println("My thread is in running state.");
}
public static void main(String args[]){
MultithreadingDemo obj=new MultithreadingDemo();
obj.start();
}
}
Output:

My thread is in running state.

Method 2: Thread creation by implementing Runnable Interface


A Simple Example

class MultithreadingDemo implements Runnable{


public void run(){
System.out.println("My thread is in running state.");
}
public static void main(String args[]){
MultithreadingDemo obj=new MultithreadingDemo();
Thread tobj =new Thread(obj);
tobj.start();
}
}
Output:

My thread is in running state.

Java Lambda expression Example


By using Lambda expression: Instead of creating anonymous inner class, we can
create a lambda expression like this:

import java.awt.*;
public class ButtonListenerNewWay {
public static void main(String[] args) {
Frame frame=new Frame("ActionListener java8");

Button b=new Button("Click Here");


b.setBounds(50,100,80,50);

b.addActionListener(e -> System.out.println("Hello World!"));


frame.add(b);

frame.setSize(200,200);
frame.setLayout(null);
frame.setVisible(true);
}
}

1. Method reference to an instance method of an object


@FunctionalInterface
interface MyInterface{
void display();
}
public class Example {
public void myMethod(){
System.out.println("Instance Method");
}
public static void main(String[] args) {
Example obj = new Example();
// Method reference using the object of the class
MyInterface ref = obj::myMethod;
// Calling the method of functional interface
ref.display();
}
}
Output:

Instance Method

Example 1: Creating your own functional interface


@FunctionalInterface
interface MyFunctionalInterface {

public int addMethod(int a, int b);


}
public class BeginnersBookClass {
public static void main(String args[]) {
// lambda expression
MyFunctionalInterface sum = (a, b) -> a + b;
System.out.println("Result: "+sum.addMethod(12, 100));
}
}
Output:

Result: 112
Example 2: Using predefined functional interface
import java.util.function.IntBinaryOperator;

public class BeginnersBookClass {

public static void main(String args[]) {


// lambda expression
IntBinaryOperator sum = (a, b) -> a + b;
System.out.println("Result: " + sum.applyAsInt(12, 100));

}
}
Output:

Result: 112

Create File
Complete code:
The below code would create a txt file named “newfile.txt” in C drive. You can
change the path in the below code in order to create the file in different directory
or in different drive.

package beginnersbook.com;
import java.io.File;
import java.io.IOException;

public class CreateFileDemo


{
public static void main( String[] args )
{
try {
File file = new File("C:\\newfile.txt");
/*If file gets created then the createNewFile()
* method would return true or if the file is
* already present it would return false
*/
boolean fvar = file.createNewFile();
if (fvar){
System.out.println("File has been created
successfully");
}
else{
System.out.println("File already present at the
specified location");
}
} catch (IOException e) {
System.out.println("Exception Occurred:");
e.printStackTrace();
}
}
}

How to read file in Java –


BufferedInputStream
package beginnersbook.com;
import java.io.*;
public class ReadFileDemo {
public static void main(String[] args) {
//Specify the path of the file here
File file = new File("C://myfile.txt");
BufferedInputStream bis = null;
FileInputStream fis= null;

try
{
//FileInputStream to read the file
fis = new FileInputStream(file);

/*Passed the FileInputStream to BufferedInputStream


*For Fast read using the buffer array.*/
bis = new BufferedInputStream(fis);

/*available() method of BufferedInputStream


* returns 0 when there are no more bytes
* present in the file to be read*/
while( bis.available() > 0 ){
System.out.print((char)bis.read());
}

}catch(FileNotFoundException fnfe)
{
System.out.println("The specified file not found" +
fnfe);
}
catch(IOException ioe)
{
System.out.println("I/O Exception: " + ioe);
}
finally
{
try{
if(bis != null && fis!=null)
{
fis.close();
bis.close();
}
}catch(IOException ioe)
{
System.out.println("Error in InputStream close():
" + ioe);
}
}
}
}

Complete Code: Writing to a File


In the below example we are writing a String to a file. To convert the String into
an array of bytes, we are using getBytes() method of String class.

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class WriteFileDemo {


public static void main(String[] args) {
FileOutputStream fos = null;
File file;
String mycontent = "This is my Data which needs" +
" to be written into the file";
try {
//Specify the file path here
file = new File("C:/myfile.txt");
fos = new FileOutputStream(file);

/* This logic will check whether the file


* exists or not. If the file is not found
* at the specified location it would create
* a new file*/
if (!file.exists()) {
file.createNewFile();
}

/*String content cannot be directly written into


* a file. It needs to be converted into bytes
*/
byte[] bytesArray = mycontent.getBytes();

fos.write(bytesArray);
fos.flush();
System.out.println("File Written Successfully");
}
catch (IOException ioe) {
ioe.printStackTrace();
}
finally {
try {
if (fos != null)
{
fos.close();
}
}
catch (IOException ioe) {
System.out.println("Error in closing the Stream");
}
}
}
}
Output:

File Written Successfully

1) Append content to File using FileWriter and


BufferedWriter
import java.io.File;
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.IOException;

class AppendFileDemo
{
public static void main( String[] args )
{
try{
String content = "This is my content which would be appended
" +
"at the end of the specified file";
//Specify the file name and path here
File file =new File("C://myfile.txt");

/* This logic is to create the file if the


* file is not already present
*/
if(!file.exists()){
file.createNewFile();
}

//Here true is to append the content to file


FileWriter fw = new FileWriter(file,true);
//BufferedWriter writer give better performance
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
//Closing BufferedWriter Stream
bw.close();

System.out.println("Data successfully appended at the end of


file");

}catch(IOException ioe){
System.out.println("Exception occurred:");
ioe.printStackTrace();
}
}
}
Output:

Data successfully appended at the end of file

You might also like