JAVA Examples
JAVA Examples
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();
}
}
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;
}
for(int i=0;i<n;i++)
{
int 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();
}
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]+" ");
}
}
{
int sum=0;
for(int i=0;i<n;i++)
{
sum=sum+arr1[i]*arr2[i];
}
return sum;
}
{
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;
}
}
}
}
int size=sc.nextInt();
for(int i=0;i<size;i++)
a1[i]=sc.nextInt();
for(int i=0;i<size;i++)
a2[i]=sc.nextInt();
sort(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;
}
}
}
}
System.out.println("Maximum product");
System.out.println( MScalarProduct(arr1,arr2,m));
}
}
Problem Statement
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.
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
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());
}
}
int empId;
String empName;
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();
}
}
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;
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");
}
}
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
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:
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
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();
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
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
Woof
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.
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
class EncapsulationDemo{
private int ssn;
private String empName;
private int empAge;
//Getter and Setter methods
public int getEmpSSN(){
return ssn;
}
package letmecalculate;
import letmecalculate.Calculator;
public class Demo{
public static void main(String args[]){
Calculator obj = new Calculator();
System.out.println(obj.add(100, 200));
}
}
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
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:
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:
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:
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:
ArrayList
import java.util.*;
// Displaying elements
System.out.println("Original ArrayList:");
for(String str:obj)
System.out.println(str);
// Displaying elements
System.out.println("ArrayList after add operation:");
for(String str:obj)
System.out.println(str);
// Displaying elements
System.out.println("ArrayList after remove operation:");
for(String str:obj)
System.out.println(str);
// 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[]){
//Iterating LinkedList
Iterator<String> iterator=list.iterator();
while(iterator.hasNext()){
System.out.print(iterator.next()+" ");
}
import java.util.HashMap;
import java.util.Map;
import java.util.Iterator;
import java.util.Set;
public class Details {
}
}
Output:
/*
* 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>();
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());
/*
* 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());
import java.util.ArrayList;
import java.util.Iterator;
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;
/*
* 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:
Direction: North
Multiplethreading
Method 1: Thread creation by extending Thread class
Example 1:
import java.awt.*;
public class ButtonListenerNewWay {
public static void main(String[] args) {
Frame frame=new Frame("ActionListener java8");
frame.setSize(200,200);
frame.setLayout(null);
frame.setVisible(true);
}
}
Instance Method
Result: 112
Example 2: Using predefined functional interface
import java.util.function.IntBinaryOperator;
}
}
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;
try
{
//FileInputStream to read the file
fis = new FileInputStream(file);
}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);
}
}
}
}
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
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:
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");
}catch(IOException ioe){
System.out.println("Exception occurred:");
ioe.printStackTrace();
}
}
}
Output: